path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
fields/types/cloudinaryimage/CloudinaryImageFilter.js
jacargentina/keystone
import React from 'react'; import { SegmentedControl } from 'elemental'; var PasswordFilter = React.createClass({ getInitialState () { return { checked: this.props.value || true, }; }, toggleChecked (checked) { this.setState({ checked: checked, }); }, render () { const options = [ { label: 'Is Set', value: true }, { label: 'Is NOT Set', value: false }, ]; return <SegmentedControl equalWidthSegments options={options} value={this.state.checked} onChange={this.toggleChecked} />; }, }); module.exports = PasswordFilter;
src/components/pages/PropousalPage/PropousalPage.js
ESTEBANMURUZABAL/bananaStore
import React from 'react'; import {FormattedMessage} from 'react-intl'; import intlData from './PropousalPage.intl'; import IntlStore from '../../../stores/Application/IntlStore'; import {Link} from 'react-router'; export default class PropousalPage extends React.Component { static contextTypes = { executeAction: React.PropTypes.func.isRequired, getStore: React.PropTypes.func.isRequired }; componentDidMount() { require('./PropousalPage.scss'); } render() { let intlStore = this.context.getStore(IntlStore); let routeParams = {locale: intlStore.getCurrentLocale()}; const packName = this.props.params.packNum; const templateId = this.props.params.templateId; let content = null; if (this.props.params.packNum === 'webPack1' || this.props.params.packNum === 'mobilePack1') { content = <div> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text place"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature1')} /></span></i></li> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text phone"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature2')} /></span></i></li> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text place"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature3')} /></span></i></li> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text phone"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature4')} /></span></i></li> </div>; } else if (this.props.params.packNum === 'webPack4' || this.props.params.packNum === 'mobilePack4') { content = <div> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text place"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature1')} /></span></i></li> </div>; } else { content = <div> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text place"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature1')} /></span></i></li> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text phone"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature2')} /></span></i></li> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text gmail"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature3')} /></span></i></li> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text gmail"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature4')} /></span></i></li> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text gmail"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature5')} /></span></i></li> <li className="list-item"><i className="fa fa-check-square fa-2x"><span className="contact-text gmail"><FormattedMessage message={intlStore.getMessage(intlData, this.props.params.packNum+'Feature6')} /></span></i></li> </div>; } return ( <section id="propousalPage"> <div className="propusal-title"><FormattedMessage message={intlStore.getMessage(intlData, 'string1')} /> {this.props.params.packNum}<FormattedMessage message={intlStore.getMessage(intlData, 'string2')} /></div> <div className="propousal-wrapper"> <div className="direct-propousal-container"> <div> {this.props.params.packNum === 'webPack4' || this.props.params.packNum === 'mobilePack4' ? null : <div className="subtitle-text"><FormattedMessage message={intlStore.getMessage(intlData, 'subtitle')} /></div> } <ul className="contact-list"> {content} </ul> </div> </div> <form className="propousal-form-horizontal" role="form" method="post" action="https://formspree.io/[email protected]"> <div className="propousal-form-group"> <div className="col-sm-12"> <input type="text" className="propousal-form-control" id="name" placeholder={intlStore.getMessage(intlData, 'name')} name="name" required/> </div> </div> <div className="propousal-form-group"> <div className="col-sm-12"> <input type="numbers" className="propousal-form-control" id="phone" placeholder={intlStore.getMessage(intlData, 'phone')} name="phone" required/> </div> </div> <div className="propousal-form-group"> <div className="col-sm-12"> <input type="email" className="propousal-form-control" id="email" placeholder={intlStore.getMessage(intlData, 'email')} name="email" required/> </div> </div> <div className="propousal-form-group"> <div className="col-sm-12"> <input type="text" className="propousal-form-control" id="pack" placeholder={packName + ' ' + templateId} name="pack" disabled/> </div> </div> <textarea className="propousal-form-control" rows="10" placeholder={intlStore.getMessage(intlData, 'propousalMessage')} name="propousalMessage" required></textarea> <button className="btn btn-primary propousal-send-button" id="submit" type="submit" value="SEND"> <div className="propousal-button"> <i className="fa fa-paper-plane"></i><span className="propousal-send-text"><FormattedMessage message={intlStore.getMessage(intlData, 'send')} /></span> </div> </button> <input type="hidden" name="_next" value="http://bananacat.co/es/contact" /> </form> </div> </section> ); } }
src/app/components/public/Loading.js
cherishstand/OA-react
import React from 'react'; import CircularProgress from 'material-ui/CircularProgress'; const load = { position: 'fixed', top: '40%', left: '40%', zIndex: 9999, } const Loading = () => { return( <CircularProgress style={load} color='rgb(94, 149, 201)'/> ) } export default Loading
test/helpers/shallowRenderHelper.js
leonzhang2008/gallery-by-react
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
src/app/views/calculator.js
webcoding/reactui-starter
import React from 'react'; import Reflux from 'reflux'; import DocMeta from 'react-doc-meta'; import { Navigation } from 'react-router'; import calculatorStore from 'stores/calculator'; import recipeActions from 'actions/recipe'; import FormSaveRecipe from 'components/formSaveRecipe'; import Imageable from 'components/imageable'; import SapCalculator from 'components/sapCalculator'; export default React.createClass( { mixins: [ Navigation, Reflux.connect( calculatorStore, 'recipe' ) ], getInitialState() { return { saving: false }; }, componentDidMount() { document.title = 'Soapee - Lye Calculator'; }, render() { return ( <div id="calculator"> <DocMeta tags={ this.tags() } /> <SapCalculator recipe={ this.state.recipe } /> { this.state.recipe.countWeights() > 0 && <div> <legend>Recipe Images</legend> <Imageable imageableType='recipes' startImageUpload={ this.startImageUploadHookFn } OnUploadedCompleted={ this.showRecipe } /> </div> } { this.state.recipe.countWeights() > 0 && <div className="row"> <FormSaveRecipe recipe={ this.state.recipe } buttonPrint={ true } buttonReset={ true } buttonCaptionSave={ this.saveCaption() } buttonDisabledSave={ this.state.saving } onSave={ this.saveRecipe } onPrint={ this.printRecipe } onPrintPreview={ this.printPreviewRecipe } onReset={ this.resetRecipe } /> </div> } </div> ); }, startImageUploadHookFn( fnToStartUploads ) { this.startUploads = fnToStartUploads; }, saveCaption() { return this.state.saving ? 'Saving Recipe' : 'Save Recipe'; }, saveRecipe() { function uploadImages() { this.startUploads( this.newRecipe.id ); } this.setState( { saving: true } ); recipeActions.createRecipe( this.state.recipe ) .then( recipe => this.newRecipe = recipe ) .then( uploadImages.bind( this ) ); }, showRecipe() { this.resetRecipe(); this.transitionTo( 'recipe', { id: this.newRecipe.id } ); }, printRecipe() { this.replaceWith( 'print' ); }, printPreviewRecipe() { this.transitionTo( 'print', null, { preview: true } ); }, resetRecipe() { recipeActions.resetRecipe(); }, tags() { let description = 'Soapee Lye Calculator'; return [ {name: 'description', content: description}, {name: 'twitter:card', content: description}, {name: 'twitter:title', content: description}, {property: 'og:title', content: description} ]; } } );
ui/src/components/OfflineSimulation/SimulationType.js
vlad-doru/experimento
import React from 'react' import Divider from 'material-ui/Divider'; import * as Colors from 'material-ui/styles/colors'; import TextField from 'material-ui/TextField'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import __ from 'lodash'; const style={ backgroundColor: 'white', } const innerDiv={ backgroundColor: 'white', border: '1px solid white', } export class SimulationType extends React.Component { constructor(props) { super(); } _change = (field, value) => { this.props.onChange && this.props.onChange({ ...this.props.simulation, [field]: value, }) } _experimentSpecific = (group, field) => { return this.props.id + "_" + group + "_" + field; } _changeSpecific = (group, field, value) => { this.props.onChange && this.props.onChange({ ...this.props.simulation, [this._experimentSpecific(group, field)]: value, }) } render () { return ( <div> <SelectField style={{ width: '49%', }} value={this.props.simulation.assigner} floatingLabelText="Assigner Type" onChange={(evt, index, value) => this._change("assigner", value)} > <MenuItem style={style} innerDivStyle={innerDiv} value="ab" primaryText="AB Testing" /> <MenuItem style={style} innerDivStyle={innerDiv} value="multiarm" primaryText="Multi-armed Bandit" /> <MenuItem style={style} innerDivStyle={innerDiv} value="experimento" primaryText="Experimento Assigner" /> </SelectField> <SelectField value={this.props.simulation.distribution} style={{ marginLeft: 10, width: '49%', }} floatingLabelText="Metric distribution" onChange={(evt, index, value) => this._change("distribution", value)} > <MenuItem style={style} innerDivStyle={innerDiv} value="bernoulli" primaryText="Bernoulli" /> <MenuItem style={style} innerDivStyle={innerDiv} value="normal" primaryText="Normal" /> </SelectField> <br/> {__.map(this.props.groups, (info, name) => <div key={name} style={{display: 'inline-block', marginRight: 10, minWidth: '48.5%'}}> <div style={{fontSize: 16, fontWeight: 'bold', display: 'inline-block', marginTop: 10}}> Group {name} </div> {(this.props.simulation.distribution == 'bernoulli') ? <div> <TextField hintText="Success probability" fullWidth={true} value={this.props.simulation[this._experimentSpecific(name, 'bernoulli')]} floatingLabelText="Bernoulli Probability" onChange={(evt, value) => this._changeSpecific(name, "bernoulli", value)} /> </div> : this.props.simulation.distribution == 'normal' ? <div> <TextField hintText="Normal Mean" fullWidth={true} value={this.props.simulation[this._experimentSpecific(name, 'normalMean')]} floatingLabelText="Normal Mean" onChange={(evt, value) => this._changeSpecific(name, "normalMean", value)} /> <br/> <TextField hintText="Normal SD" fullWidth={true} value={this.props.simulation[this._experimentSpecific(name, 'normalSD')]} floatingLabelText="Normal SD" onChange={(evt, value) => this._changeSpecific(name, "normalSD", value)} /> </div> : <div></div> }</div> )} </div> ) } } SimulationType.defaultProps = { simulation: {} }; export default SimulationType
sam-front/src/pages/NewApplication.js
atgse/sam
import React from 'react'; import { connect } from 'react-redux'; import NewApplication from '../components/NewApplication'; import * as applicationActions from '../actions/applicationActions'; import { fromGroup } from '../reducers'; const NewApplicationContainer = ({ groupIds = [], handleCreate }) => ( <div> <h2>New application</h2> <NewApplication groupIds={groupIds} onCreate={handleCreate} /> </div> ); const mapStateToProps = (state) => ({ groupIds: fromGroup.getIds(state), }); const Actions = { handleCreate: applicationActions.createApplication, }; export default connect(mapStateToProps, Actions)(NewApplicationContainer);
ozwillo-datacore-web/src/main/webapp/dc-ui/src/components/reading/userManual.js
ozwillo/ozwillo-datacore
import React from 'react'; import LinkPlayground from '../linkPlayground.js'; export default class UserManual extends React.Component{ render() { return ( <div> <h2>Playground User Manual</h2> <table className="ui basic table"> <tbody> <tr><td><strong>Click on a URI's id</strong> to go to the corresponding Resource</td></tr> <tr><td><strong>Click on type in a URI or on an item of the @type list</strong> to go to the corresponding model definition.</td></tr> <tr><td><strong>Click on :</strong> between a property's key and value to query all other resources with the same value for this property in the same model type. Note that the Playground shows said key and value UNencoded in order to make it easier to enter text in the language of the user, but that developers should URI-encode them nonetheless, as Playground actually does. (see <a href="http://www.w3schools.com/tags/ref_urlencode.asp">http://www.w3schools.com/tags/ref_urlencode.asp </a>) </td></tr> <tr><td><strong>Click on /</strong> between a URI's model type and id to look for resources that refer (link) to it : if it's a metamodel it queries its resources, otherwise it lists all models that define a resource field that links to it through its model type at top level or in a top level list field, and provides links allowing to do the same at further depth below top level and for other mixins besides its model type. </td></tr> <tr><td><strong>Project portal</strong> : select another project in the dropdown above the Playground (see details on <a>how to explore its available (meta)models</a>). </td></tr> <tr><td><strong>Query line </strong>: write there the relative URI of a single Resource or of a LDP-like Datacore query (see documentation below in Swagger UI of operation findDataInType for typed queries (criteria, sort, ranged query- or iterator-based pagination). </td></tr> <tr><td><strong>Buttons </strong>: roll your mouse over them to see what they do. </td></tr> </tbody> </table> </div> ); } }
src/app/components/comment.js
webcoding/soapee-ui
import _ from 'lodash'; import moment from 'moment'; import React from 'react'; import { Link } from 'react-router'; import MarkedDisplay from 'components/markedDisplay'; import UserAvatar from 'components/userAvatar'; export default React.createClass( { render() { let comment = this.props.comment; return ( <div className="comment media"> <div className="media-left"> <UserAvatar user={ comment.user } /> </div> <div className="media-body"> <div className="about"> <span className="user"> <Link to="userProfile" params={ { id: comment.user_id } }>{ comment.user.name }</Link> </span> <span className="time" title={ moment( comment.created_at ).format( 'LLLL' ) } > { moment( comment.created_at ).fromNow() } </span> { this.renderExtraLinks() } </div> <MarkedDisplay content={ comment.comment } /> </div> </div> ); }, renderExtraLinks() { function renderLink( link ) { return ( <span className="link">{ link }</span> ); } return _.map( this.props.links, renderLink, this ); } } );
src/components/setup/Footer.js
alexzherdev/pandemic
import React from 'react'; import { Link } from 'react-router'; import { OutboundLink } from 'react-ga'; const Footer = () => <footer> <div> <small>Made by Alex Zherdev in 2016.</small> </div> <div> <OutboundLink eventLabel="outboundGithub" to="https://github.com/alexzherdev/pandemic" className="github" target="_blank"> <img src={require('../../assets/images/github.png')} /> </OutboundLink> <OutboundLink eventLabel="outboundTwitter" to="https://twitter.com/endymion_r" className="twitter" target="_blank"> <img src={require('../../assets/images/twitter.png')} /> </OutboundLink> <OutboundLink eventLabel="outboundLinkedin" to="https://www.linkedin.com/in/alex-zherdev" target="_blank"> <img src={require('../../assets/images/linkedin.png')} /> </OutboundLink> </div> <div> <Link to="credits" className="credits"> <small>Credits</small> </Link> </div> </footer>; export default Footer;
src/svg-icons/notification/voice-chat.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationVoiceChat = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12l-4-3.2V14H6V6h8v3.2L18 6v8z"/> </SvgIcon> ); NotificationVoiceChat = pure(NotificationVoiceChat); NotificationVoiceChat.displayName = 'NotificationVoiceChat'; NotificationVoiceChat.muiName = 'SvgIcon'; export default NotificationVoiceChat;
src/ReactBoilerplate/Scripts/containers/Manage/Email/Email.js
pauldotknopf/react-aspnet-boilerplate
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { loadEmail, destroyEmail, verifyEmail } from 'redux/modules/manage'; import { ChangeEmailForm, Spinner } from 'components'; import { Alert, Button } from 'react-bootstrap'; class Email extends Component { constructor(props) { super(props); this.verifyClick = this.verifyClick.bind(this); this.state = { sendingEmailVerification: false }; } componentDidMount() { this.props.loadEmail(); } componentWillUnmount() { this.props.destroyEmail(); } verifyClick(event) { event.preventDefault(); this.setState({ sendingEmailVerification: true }); this.props.verifyEmail() .then(() => { this.setState({ sendingEmailVerification: false }); }, () => { this.setState({ sendingEmailVerification: false }); }); } render() { const { email, emailConfirmed } = this.props.email; const { sendingEmailVerification } = this.state; console.log(email); if (typeof email === 'undefined') { return (<Spinner />); } return ( <div> <h2>Email</h2> <div className="form-horizontal"> <div className="form-group"> <label className="col-md-2 control-label" htmlFor="currentEmail">Current email</label> <div className="col-md-10"> <p id="currentEmail" className="form-control-static">{email}</p> </div> </div> </div> {!emailConfirmed && <Alert bsStyle="danger"> Your email is not verified. <br /> <Button onClick={this.verifyClick} disabled={sendingEmailVerification}> Verify </Button> </Alert> } <h3>Change your email</h3> <ChangeEmailForm /> </div> ); } } export default connect( (state) => ({ email: state.manage.email }), { loadEmail, destroyEmail, verifyEmail } )(Email);
client/src/services/services.page.js
Thiht/docktor
// React import React from 'react'; import { connect } from 'react-redux'; import { Scrollbars } from 'react-custom-scrollbars'; import DebounceInput from 'react-debounce-input'; // API Fetching import ServicesThunks from './services.thunks.js'; import ServicesActions from './services.actions.js'; // Components import ServiceCard from './service.card.component.js'; // Selectors import { getFilteredServices } from './services.selectors.js'; // Style import './services.page.scss'; // Services Component class Services extends React.Component { componentWillMount() { this.props.fetchServices(); } render() { const services = this.props.services; const filterValue = this.props.filterValue; const fetching = this.props.isFetching; const changeFilter = this.props.changeFilter; return ( <div className='flex layout vertical start-justified'> <div className='layout horizontal justified services-bar'> <div className='ui left corner labeled icon input flex' > <div className='ui left corner label'><i className='search icon'></i></div> <i className='remove link icon' onClick={() => changeFilter('')}></i> <DebounceInput minLength={1} debounceTimeout={300} placeholder='Search...' onChange={(event) => changeFilter(event.target.value)} value={filterValue}/> </div> <div className='flex-2'></div> </div> <Scrollbars className='flex ui dimmable'> <div className='flex layout horizontal center-center services-list wrap'> {(fetching => { if (fetching) { return ( <div className='ui active inverted dimmer'> <div className='ui text loader'>Fetching</div> </div> ); } })(fetching)} {services.map(service => { return ( <ServiceCard service={service} key={service.id} /> ); })} </div> </Scrollbars> </div> ); } } Services.propTypes = { services: React.PropTypes.array, filterValue: React.PropTypes.string, isFetching: React.PropTypes.bool, fetchServices: React.PropTypes.func.isRequired, changeFilter: React.PropTypes.func.isRequired }; // Function to map state to container props const mapStateToServicesProps = (state) => { const filterValue = state.services.filterValue; const services = getFilteredServices(state.services.items, filterValue); const isFetching = state.services.isFetching; return { filterValue, services, isFetching }; }; // Function to map dispatch to container props const mapDispatchToServicesProps = (dispatch) => { return { fetchServices : () => { dispatch(ServicesThunks.fetchIfNeeded()); }, changeFilter: (filterValue) => dispatch(ServicesActions.changeFilter(filterValue)) }; }; // Redux container to Sites component const ServicesPage = connect( mapStateToServicesProps, mapDispatchToServicesProps )(Services); export default ServicesPage;
packages/react-scripts/fixtures/kitchensink/src/features/webpack/NoExtInclusion.js
amido/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 from 'react'; import aFileWithoutExt from './assets/aFileWithoutExt'; const text = aFileWithoutExt.includes('base64') ? atob(aFileWithoutExt.split('base64,')[1]).trim() : aFileWithoutExt; export default () => ( <a id="feature-no-ext-inclusion" href={text}> aFileWithoutExt </a> );
src/svg-icons/editor/format-list-bulleted.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatListBulleted = (props) => ( <SvgIcon {...props}> <path d="M4 10.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm0-6c-.83 0-1.5.67-1.5 1.5S3.17 7.5 4 7.5 5.5 6.83 5.5 6 4.83 4.5 4 4.5zm0 12c-.83 0-1.5.68-1.5 1.5s.68 1.5 1.5 1.5 1.5-.68 1.5-1.5-.67-1.5-1.5-1.5zM7 19h14v-2H7v2zm0-6h14v-2H7v2zm0-8v2h14V5H7z"/> </SvgIcon> ); EditorFormatListBulleted = pure(EditorFormatListBulleted); EditorFormatListBulleted.displayName = 'EditorFormatListBulleted'; EditorFormatListBulleted.muiName = 'SvgIcon'; export default EditorFormatListBulleted;
react/CriticalIcon/CriticalIcon.iconSketch.js
seekinternational/seek-asia-style-guide
import React from 'react'; import CriticalIcon from './CriticalIcon'; export const symbols = { 'CriticalIcon': <CriticalIcon /> };
packages/react-scripts/fixtures/kitchensink/src/features/webpack/JsonInclusion.js
christiantinauer/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import { abstract } from './assets/abstract.json'; export default () => <summary id="feature-json-inclusion">{abstract}</summary>;
html.js
nickroberts404/meadowlab
import React from 'react' import Helmet from 'react-helmet' import { prefixLink } from 'gatsby-helpers' const BUILD_TIME = new Date().getTime() module.exports = React.createClass({ propTypes () { return { body: React.PropTypes.string, } }, render () { const head = Helmet.rewind() let css if (process.env.NODE_ENV === 'production') { css = <style dangerouslySetInnerHTML={{ __html: require('!raw!./public/styles.css') }} /> } return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta property="og:type" content="website" /> <meta property="og:image" content="https://meadowlab.io/img/og-image.jpg" /> {head.title.toComponent()} {head.meta.toComponent()} {css} <link href="https://fonts.googleapis.com/css?family=Muli:300,400,900" rel="stylesheet"/> </head> <body> <div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} /> <script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} /> </body> </html> ) }, })
react/Service/ServiceItem.js
morattoo/jekyll-react-firebase
import React, { Component } from 'react'; class ServiceItem extends Component { constructor(props) { super(props) } render() { let classNameIcon = ""; let displayName = ""; switch (this.props.name) { case "chauffe": classNameIcon="fa fa-thermometer-three-quarters"; displayName = this.props.active ? "Chauffé" : "Non chauffé"; break; case "eau-chaude": classNameIcon="fa fa-bath"; displayName = this.props.active ? "Eau chaude" : "Non eau chaude"; break; case "eclaire": classNameIcon="fa fa-lightbulb-o"; displayName = this.props.active ? "Éclairé" : "Non éclairé"; break; case "semi-meuble": classNameIcon="fa fa-bed"; displayName = this.props.active ? "Semi-meublé" : "Non semi-meublé"; break; case "wifi": classNameIcon="fa fa-wifi"; displayName = this.props.active ? "Wi-Fi" : "Non wi-fi"; break; default: } const classNameItem = this.props.active ? "listAptos__serviceItem" : "listAptos__serviceItem inactive"; return(<li className={classNameItem} data-tooltip={displayName}> <i className={classNameIcon} aria-hidden="true"></i> </li>); } } export default ServiceItem;
js/components/home/index.js
bsisic/Mobilux
import React, { Component } from 'react'; import { TouchableOpacity } from 'react-native'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Content, Text, Button, Icon, Card, CardItem, View } from 'native-base'; import { Grid, Row } from 'react-native-easy-grid'; import { openDrawer } from '../../actions/drawer'; import { setIndex } from '../../actions/list'; import myTheme from '../../themes/base-theme'; import styles from './styles'; import Hr from 'react-native-hr'; const { reset, pushRoute, } = actions; class Home extends Component { static propTypes = { name: React.PropTypes.string, list: React.PropTypes.arrayOf(React.PropTypes.string), setIndex: React.PropTypes.func, openDrawer: React.PropTypes.func, pushRoute: React.PropTypes.func, reset: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } pushRoute(route, index) { this.props.setIndex(index); this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key); } render() { return ( <Container theme={myTheme} style={styles.container}> <Header> <Button transparent onPress={this.props.openDrawer}> <Icon name="ios-menu" /> </Button> <Title style={{color:'#fff'}}>{(this.props.name) ? this.props.name : 'Dashboard'}</Title> </Header> <Content> <Card> <CardItem header> <Text>Alertes Infos</Text> </CardItem> <CardItem> <View style={styles.det}> <Text style={styles.imptxt}><Icon style={styles.iconmt} name="ios-car" /> Trafic : accident sur l'A4</Text> </View> <View style={styles.det}> <Text style={styles.dettxt}>Dernière mise à jour : il y a 36 min</Text> </View> </CardItem> <CardItem> <View style={styles.det}> <Text style={styles.imptxt}><Icon style={styles.iconmt} name="ios-train" /> Train : retard de +/- 35min sur la ligne 5</Text> </View> <View style={styles.det}> <Text style={styles.dettxt}>Dernière mise à jour : il y a 6 min</Text> </View> </CardItem> <CardItem header> <Text>Météo</Text> </CardItem> <CardItem> <View style={styles.det}> <Text style={styles.imptxt}><Icon style={styles.iconmt} name="ios-thunderstorm-outline" /> Alerte : orage prévu vers 17h</Text> </View> <View style={styles.det}> <Text style={styles.dettxt}>Dernière mise à jour : il y a 11 min</Text> </View> </CardItem> </Card> <Button style={styles.alertbtn} onPress={() => this.pushRoute('blankPage')}> + </Button> </Content> </Container> ); } } function bindAction(dispatch) { return { setIndex: index => dispatch(setIndex(index)), openDrawer: () => dispatch(openDrawer()), pushRoute: (route, key) => dispatch(pushRoute(route, key)), reset: key => dispatch(reset([{ key: 'login' }], key, 0)), }; } const mapStateToProps = state => ({ name: state.user.name, list: state.list.list, navigation: state.cardNavigation, }); export default connect(mapStateToProps, bindAction)(Home);
example/example.js
JamieDixon/styled-components
import React from 'react' import styled, { injectGlobal, keyframes } from '../dist/styled-components' export default () => { injectGlobal` body { font-family: sans-serif; } ` // Create a <Title> react component that renders an <h1> which is // centered, palevioletred and sized at 1.5em const Title = styled.h1` font-size: 1.5em; text-align: center; color: palevioletred; animation: ${keyframes`from { opacity: 0; }`} 1s both; `; // Create a <Wrapper> react component that renders a <section> with // some padding and a papayawhip background const Wrapper = styled.section` padding: 4em; background: papayawhip; `; return class Example extends React.Component { render() { return ( <Wrapper> <Title>Hello World, this is my first styled component!</Title> </Wrapper> ) } } }
app/containers/NotFoundPage/index.js
abasalilov/react-boilerplate
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import H1 from 'components/H1'; import messages from './messages'; export default function NotFound() { return ( <article> <H1> <FormattedMessage {...messages.header} /> </H1> </article> ); }
src/svg-icons/maps/streetview.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsStreetview = (props) => ( <SvgIcon {...props}> <path d="M12.56 14.33c-.34.27-.56.7-.56 1.17V21h7c1.1 0 2-.9 2-2v-5.98c-.94-.33-1.95-.52-3-.52-2.03 0-3.93.7-5.44 1.83z"/><circle cx="18" cy="6" r="5"/><path d="M11.5 6c0-1.08.27-2.1.74-3H5c-1.1 0-2 .9-2 2v14c0 .55.23 1.05.59 1.41l9.82-9.82C12.23 9.42 11.5 7.8 11.5 6z"/> </SvgIcon> ); MapsStreetview = pure(MapsStreetview); MapsStreetview.displayName = 'MapsStreetview'; MapsStreetview.muiName = 'SvgIcon'; export default MapsStreetview;
src/ui/ButtonGroup.js
ZeroCho/react-rte
/* @flow */ import React from 'react'; import cx from 'classnames'; import styles from './ButtonGroup.css'; type Props = { className?: string; }; export default function ButtonGroup(props: Props) { let className = cx(props.className, styles.root); return ( <div {...props} className={className} /> ); }
src/components/Reel.js
tehfailsafe/portfolio
import React from 'react'; import {Link} from 'react-router' const Reel = React.createClass({ render(){ return( <div className="video reel-wrapper"> <div className="reel"> <Link to="/" ref="back" className="back"> <img src="assets/images/back.png" className="back"/> </Link> <iframe src="//player.vimeo.com/video/45412246?title=0&portrait=0&badge=0&byline=0&width=500px&autoplay=1" frameBorder="0" autoPlay webkitAllowFullscreen mozallowFullScreen allowFullScreen></iframe> </div> </div> ) } }) export default Reel;
demo/index.js
hexsprite/focuster-react-typeahead
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; const app = document.getElementsByClassName('demonstration')[0]; ReactDOM.render(<App />, app);
src/components/common/InnerHtml.js
VGraupera/1on1tracker
import React from 'react'; function createMarkup(html) { return { __html: html }; } /** * @function InnerHtml * @param props * @returns {XML} */ function InnerHtml(props) { return <div dangerouslySetInnerHTML={createMarkup(props.html)} />; } export default InnerHtml;
addons/options/.storybook/stories.js
shilman/storybook
import React from 'react'; import { storiesOf } from '@storybook/react'; storiesOf('Hello', module) .add('Hello World', () => ( <pre>Hello World</pre> )) .add('Hello Earth', () => ( <pre>Hello Earth</pre> ));
docs/app/Examples/elements/Label/Types/LabelExampleFloating.js
shengnian/shengnian-ui-react
import React from 'react' import { Icon, Label, Menu } from 'shengnian-ui-react' const LabelExampleFloating = () => ( <Menu compact> <Menu.Item as='a'> <Icon name='mail' /> Messages <Label color='red' floating>22</Label> </Menu.Item> <Menu.Item as='a'> <Icon name='users' /> Friends <Label color='teal' floating>22</Label> </Menu.Item> </Menu> ) export default LabelExampleFloating
react/src/components/Blog.js
rumbleyam/morty-api
import React from 'react'; import {connect} from 'react-redux'; import Typography from 'material-ui/Typography'; import moment from 'moment'; import PostList from './PostList'; const Blog = ({blog}) => <div style={{paddingLeft : 16, paddingRight : 16}}> <PostList posts={blog}/> </div>; const mapState = state => { return state.blog || {}; }; export default connect(mapState)(Blog);
src/components/Item/Item.js
nbschool/ecommerce_web
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { translate } from 'react-i18next'; import placehold from './placehold.png'; import './Item.css'; class Item extends Component { constructor(props) { super(props); this.state = { numItems: 0, }; this.setNumberItemToCart = this.setNumberItemToCart.bind(this); } setNumberItemToCart(amount) { let count = this.state.numItems; count += amount; this.setState({ numItems: count }); this.props.setItemInCart(this.props.uuid, this.props.price, count); } render() { const item = this.props; const {t} = this.props; const tagStock = item.availability > 0; let emojiStock, textStock; if (tagStock) { emojiStock = '✅'; textStock = t('item:in_stock'); } else { emojiStock = '❌'; textStock = t('item:out_stock'); } let itemsAdded = []; let btnAdd = []; if (this.state.numItems > 0 && item.availability > this.state.numItems) { itemsAdded = <label>{this.state.numItems}</label>; btnAdd = <div className="overlay-buttons"> <button className="addToCart" onClick={() => this.setNumberItemToCart(1)}> {t('item:addToCart')} </button> <button className="removeFromCart" onClick={() => this.setNumberItemToCart(-1)}> {t('item:removeFromCart')} </button> </div>; } else if (this.state.numItems === 0 && item.availability === 0) { btnAdd = <div className="overlay-buttons"> <button className="buttonDisabled" disabled>{t('item:addToCart')}</button> <button className="buttonDisabled" disabled>{t('item:removeFromCart')}</button> </div>; } else if (this.state.numItems === 0 && item.availability > this.state.numItems) { btnAdd = <div className="overlay-buttons"> <button className="addToCart" onClick={() => this.setNumberItemToCart(1)}> {t('item:addToCart')} </button> <button className="buttonDisabled" disabled>{t('item:removeFromCart')}</button> </div>; } else if (this.state.numItems > 0) { itemsAdded = <label>{this.state.numItems}</label>; btnAdd = <div className="overlay-buttons"> <button className="buttonDisabled" disabled>{t('item:addToCart')}</button> <button className="removeFromCart" onClick={() => this.setNumberItemToCart(-1)}> {t('item:removeFromCart')} </button> </div>; } let itemAvailable; if (item.availability > 0) { itemAvailable = <div className="overlay" > {btnAdd} {itemsAdded} </div>; } return ( <article key={item.uuid} className="Item"> <div className="image"> <img src={item.pictureUrl ? item.pictureUrl : placehold} alt={item.name} /> </div> <div className="info"> <div className="name">{item.name}</div> <div className="price">€{item.price}</div> <div className="description block-with-text">{item.description}</div> {itemAvailable} </div> <div className="in_Stock"> {emojiStock}<p>{textStock}</p> </div> </article> ); } } Item.propTypes = { uuid: PropTypes.string.isRequired, name: PropTypes.string.isRequired, price: PropTypes.number.isRequired, description: PropTypes.string.isRequired, pictureUrl: PropTypes.string, category: PropTypes.string.isRequired, availability: PropTypes.number.isRequired, setItemInCart: PropTypes.func.isRequired, t: PropTypes.func.isRequired }; export default translate('item')(Item);
public/js/components/search/SearchItem.react.js
TRomesh/Coupley
import React from 'react'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Paper from 'material-ui/lib/paper'; import GridList from 'material-ui/lib/grid-list/grid-list'; import GridTile from 'material-ui/lib/grid-list/grid-tile'; import IconButton from 'material-ui/lib/icon-button'; const styles = { root: { marginRight: "40" }, gridList: { width: 500, height: 225, }, }; const linkStyle = { color: 'white' }; const SearchItem = React.createClass({ _redirect: function() { document.location = "/#/" + this.props.username + "/about"; }, render: function() { return ( <div> <div className="col-lg-3" style={styles.root}> <GridList cellHeight={200} style={styles.gridList} > <GridTile key={this.props.firstname} title={<a href="" onClick={this._redirect} id="username-a" style={linkStyle}>{this.props.firstname + " " +this.props.lastname}</a>} subtitle={this.props.gender} actionIcon={<IconButton></IconButton>} > <img src={'/img/profilepics/' + this.props.image} /> </GridTile> </GridList> </div> </div> ); } }); export default SearchItem;
tests/components/axes-tests.js
Apercu/react-vis
import test from 'tape'; import React from 'react'; import {mount} from 'enzyme'; import CustomAxes from '../../showcase/axes/custom-axes'; import CustomAxis from '../../showcase/axes/custom-axis'; import PaddedAxis from '../../showcase/axes/padded-axis'; import CustomAxesOrientation from '../../showcase/axes/custom-axes-orientation'; import AxisWithTurnedLabels from '../../showcase/plot/axis-with-turned-labels'; test('Axis: Showcase Example - CustomAxesOrientation', t => { const $ = mount(<CustomAxesOrientation />); t.equal($.text(), '1.01.52.02.53.03.54.0X Axis246810Y Axis', 'should find appropriate text'); t.equal($.find('.rv-xy-plot__series--line').length, 2, 'should find the right number of lines'); t.equal($.find('line').length, 26, 'should find the right number of grid lines'); t.end(); }); test('Axis: Showcase Example - Custom axis', t => { const $ = mount(<CustomAxis />); t.equal($.text(), '1.01.52.03.0X', 'should find appropriate text'); t.equal($.find('.rv-xy-plot__series--line').length, 1, 'should find the right number of lines'); t.equal($.find('line').length, 15, 'should find the right number of grid lines'); t.end(); }); test('Axis: Showcase Example - Even more Custom axes', t => { const $ = mount(<CustomAxes />); t.equal($.text(), '01345XValue is 0Value is 1Value is 2Value is 3Value is 4Value is 501491625cooldogskateboardwowsuchMultilinedogs', 'should find appropriate text'); t.equal($.find('line').length, 26, 'should find the right number of grid lines'); t.end(); }); test('Axis: Showcase Example - AxisWithTurnedLabels', t => { const $ = mount(<AxisWithTurnedLabels />); t.equal($.text(), 'ApplesBananasCranberries02468101214', 'should find appropriate text'); t.equal($.find('rect').length, 6, 'should find the right number of lines'); t.equal($.find('line').length, 24, 'should find the right number of grid lines'); t.end(); }); test('Axis: Showcase Example - Padded', t => { const $ = mount(<PaddedAxis />); t.equal($.find('.rv-xy-plot__series--line').length, 4, 'should find the right number of lines'); t.ok($.find('line').length > 30, 'should find the right number of grid lines'); t.end(); });
src/widgets/JSONForm/fields/String.js
sussol/mobile
/* eslint-disable no-console */ import React from 'react'; import { Text, View } from 'react-native'; export const String = props => { console.log('-------------------------------------------'); console.log('String - props', props); console.log('-------------------------------------------'); return ( <View style={{ borderWidth: 1, marginLeft: 10 }}> <Text>StringField</Text> </View> ); };
frontend/src/app/events/index.js
the-invoice/nab
import React, { Component } from 'react'; import { Link, IndexLink } from 'react-router'; import { Route, IndexRoute } from 'react-router'; import urls from 'app/urls'; import { View } from 'ui/layout'; import styles from 'app/index.css'; export class Events extends Component { render() { return ( <View {...this.props} layout='vertical'> <View height={35}> <div className={styles.navigation}> <IndexLink activeClassName={styles.active} to={urls.events.index()}>Dashboard</IndexLink> <Link activeClassName={styles.active} to={urls.events.problems()}>Problem Hosts</Link> </div> </View> <View> { this.props.children } </View> </View> ); } } const Index = (props) => <View {...props}><div>Dashboard under construction.</div></View>; import { route as problemsRoute } from './problems'; export const route = (path) => { return ( <Route path={path} component={Events}> <IndexRoute component={Index} /> { problemsRoute('problems') } </Route> ); };
app/containers/WochitPage/index.js
Statfine/reactDemo
/** * Created by easub on 2017/3/14. */ import React from 'react'; import styled from 'styled-components'; import CanvasVideo from './CanvasVideo'; import Timeline from './Timeline'; const ImageRe = styled.div` width: ${(props) => `${props.width}px`} height: ${(props) => `${props.height}px`} background-image: ${(props) => `url(${props.src})`} background-repeat: repeat; `; const TimeLineContainer = styled.div` height: 130px; background: #2a3139; width: 100%; `; export default class WochitPage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function /* * length 视频长度 * playSt 开始时间(相对视频) * playEt 结束时间(相对视频) * st 开始时间(相对时间总轴) * et 结束时间(相对时间总轴) */ state = { time: 0, list: [ { src: 'http://video.clip.easub.com/vod-out/hd/63a8b948-149f-4619-93dc-a9386c868a7a.mp4', cover: 'http://image.clip.easub.com/snapshot/63a8b948-149f-4619-93dc-a9386c868a7a-1000.jpg?x-oss-process=image/format,jpg/resize,h_100,interlace,1', length: 10, playSt: 0, playEt: 10, st: 0, et: 10, }, { src: 'http://video.clip.easub.com/vod-out/hd/d56f9ee7-23ab-463d-a950-b0794f5288c7.mp4', cover: 'http://image.clip.easub.com/snapshot/d56f9ee7-23ab-463d-a950-b0794f5288c7-1000.jpg?x-oss-process=image/format,jpg/resize,h_100,interlace,1', length: 13, playSt: 0, playEt: 13, st: 10, et: 23, }, { src: 'http://video.clip.easub.com/vod-out/hd/3236ccd2-9723-46b9-a431-8576a478fb9f.mp4', cover: 'http://image.clip.easub.com/snapshot/3236ccd2-9723-46b9-a431-8576a478fb9f-1000.jpg?x-oss-process=image/format,jpg/resize,h_100,interlace,1', length: 15, playSt: 0, playEt: 15, st: 23, et: 38, }, { src: 'http://video.clip.easub.com/vod-out/hd/754895b8-40c0-4750-8b93-fc11c48035db.mp4', cover: 'http://image.clip.easub.com/snapshot/754895b8-40c0-4750-8b93-fc11c48035db-1000.jpg?x-oss-process=image/format,jpg/resize,h_100,interlace,1', length: 15, playSt: 0, playEt: 15, st: 38, et: 53, }, ], } // 单个点击 onActiveChange = (index, st, et) => { console.log(`onActiveChange:${index} ${st} ${et}`); } handleTimeChange = (time) => { this.setState({ time, }); } // 时间轴拖动 handleVideoTimeChange = (time) => { console.log(time); this.setState({ time, }); } // 单个时间修改 changeSentenceTime = (index, st, et) => { console.log(`changeSentenceTime:${index} ${st} ${et}`); const list = this.state.list.concat([]); list[index].st = st; list[index].et = et; this.setState({ list }); } render() { const { time, list } = this.state; return ( <div> <CanvasVideo list={list} handleTimeChange={this.handleTimeChange} /> <ImageRe src="http://image.clip.easub.com/snapshot/754895b8-40c0-4750-8b93-fc11c48035db-1000.jpg?x-oss-process=image/format,jpg/resize,h_100,interlace,1" width={300} height={100} /> <TimeLineContainer> <Timeline editFlag videoLength={53} onActiveChange={this.onActiveChange} onVideoTimeChange={this.handleVideoTimeChange} time={time} subtitles={this.state.list} onTimeChange={this.changeSentenceTime} > </Timeline> </TimeLineContainer> </div> ); } }
docs/app/Examples/collections/Menu/States/MenuExampleDisabled.js
koenvg/Semantic-UI-React
import React from 'react' import { Menu } from 'semantic-ui-react' const MenuExampleDisabled = () => { return ( <Menu compact> <Menu.Item disabled> Link </Menu.Item> </Menu> ) } export default MenuExampleDisabled
jenkins-design-language/src/js/components/material-ui/svg-icons/action/accessible.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionAccessible = (props) => ( <SvgIcon {...props}> <circle cx="12" cy="4" r="2"/><path d="M19 13v-2c-1.54.02-3.09-.75-4.07-1.83l-1.29-1.43c-.17-.19-.38-.34-.61-.45-.01 0-.01-.01-.02-.01H13c-.35-.2-.75-.3-1.19-.26C10.76 7.11 10 8.04 10 9.09V15c0 1.1.9 2 2 2h5v5h2v-5.5c0-1.1-.9-2-2-2h-3v-3.45c1.29 1.07 3.25 1.94 5 1.95zm-6.17 5c-.41 1.16-1.52 2-2.83 2-1.66 0-3-1.34-3-3 0-1.31.84-2.41 2-2.83V12.1c-2.28.46-4 2.48-4 4.9 0 2.76 2.24 5 5 5 2.42 0 4.44-1.72 4.9-4h-2.07z"/> </SvgIcon> ); ActionAccessible.displayName = 'ActionAccessible'; ActionAccessible.muiName = 'SvgIcon'; export default ActionAccessible;
app/javascript/mastodon/features/follow_requests/index.js
vahnj/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import { ScrollContainer } from 'react-router-scroll-4'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import AccountAuthorizeContainer from './containers/account_authorize_container'; import { fetchFollowRequests, expandFollowRequests } from '../../actions/accounts'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ heading: { id: 'column.follow_requests', defaultMessage: 'Follow requests' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'follow_requests', 'items']), }); @connect(mapStateToProps) @injectIntl export default class FollowRequests extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(fetchFollowRequests()); } handleScroll = (e) => { const { scrollTop, scrollHeight, clientHeight } = e.target; if (scrollTop === scrollHeight - clientHeight) { this.props.dispatch(expandFollowRequests()); } } render () { const { intl, accountIds } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column icon='users' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollContainer scrollKey='follow_requests'> <div className='scrollable' onScroll={this.handleScroll}> {accountIds.map(id => <AccountAuthorizeContainer key={id} id={id} /> )} </div> </ScrollContainer> </Column> ); } }
src/index.js
NJU-itxia/front-end
import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/css/bootstrap-theme.min.css'; import 'bootstrap/dist/js/bootstrap.min.js'; import React from 'react'; import ReactDOM from 'react-dom'; import { browserHistory, Router, Route, IndexRedirect, Redirect, Link, IndexLink } from 'react-router'; import App from './App'; import LoginPage from './component/login/LoginPage'; import StudentLogin from './component/login/StudentLogin'; import KnightLogin from './component/login/KnightLogin'; import StudentPage from './component/student/StudentPage'; import NewOrder from './component/student/NewOrder'; import History from './component/student/History'; import KnightPage from './component/knight/KnightPage'; import Orders from './component/knight/order/Orders'; import Message from './component/knight/Message'; import Setting from './component/knight/Setting'; import studentModel from './model/student'; import knightModel from './model/knight'; function redirectIfLoggedIn(nextState, replace) { if (studentModel.token) { replace('/student/order'); } else if (knightModel.token) { // TODO } } function requireStudentLogin(nextState, replace) { if (!studentModel.token) { replace('/'); } } function requireKnightLogin() { if (!knightModel.token) { replace('/'); } } const routes = ( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRedirect to="/login/student" /> <Route path="login" component={LoginPage} onEnter={redirectIfLoggedIn} > <Route path="student" component={StudentLogin} /> <Route path="knight" component={KnightLogin} /> </Route> <Route path="student" component={StudentPage} onEnter={requireStudentLogin} > <Route path="order" component={NewOrder} /> <Route path="history" component={History} /> </Route> <Route path="knight" component={KnightPage} onEnter={requireKnightLogin} > <Route path="orders" component={ Orders } /> <Route path="message" component={Message} /> <Route path="setting" component={Setting} /> </Route> </Route> </Router> ); function renderAll() { console.log('render'); ReactDOM.render(routes, document.getElementById('app')); } studentModel.subscribe(renderAll); renderAll();
src/svg-icons/communication/stay-current-landscape.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationStayCurrentLandscape = (props) => ( <SvgIcon {...props}> <path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/> </SvgIcon> ); CommunicationStayCurrentLandscape = pure(CommunicationStayCurrentLandscape); CommunicationStayCurrentLandscape.displayName = 'CommunicationStayCurrentLandscape'; CommunicationStayCurrentLandscape.muiName = 'SvgIcon'; export default CommunicationStayCurrentLandscape;
actor-apps/app-web/src/app/components/modals/create-group/ContactItem.react.js
zomeelee/actor-platform
import React from 'react'; import AvatarItem from 'components/common/AvatarItem.react'; class ContactItem extends React.Component { static propTypes = { contact: React.PropTypes.object, onToggle: React.PropTypes.func } constructor(props) { super(props); this.onToggle = this.onToggle.bind(this); this.state = { isSelected: false }; } onToggle() { const isSelected = !this.state.isSelected; this.setState({ isSelected: isSelected }); this.props.onToggle(this.props.contact, isSelected); } render() { let contact = this.props.contact; let icon; if (this.state.isSelected) { icon = 'check_box'; } else { icon = 'check_box_outline_blank'; } return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this.onToggle}>{icon}</a> </div> </li> ); } } export default ContactItem;
src/containers/pages/decks/deck/left-container/sidebar-body/deck-details.js
vFujin/HearthLounge
import React from 'react'; import { connect } from "react-redux"; import DecklistSidebar from "../../../../../../components/decklist-sidebar/decklist"; import ManaCurve from "../../../../../../components/mana-curve/mana-curve"; import CopyDeck from "./copy-deck"; const DeckDetails = ({activeDeck, activeDeckCopy}) => { const {cards, max, manaCurve} = activeDeckCopy; const {deckstring, playerClass} = activeDeck; return ( <div className="container__mana-curve"> <h3>Mana Curve</h3> <ManaCurve deck={cards} max={max} barHeight="70%" padding="1vh 0" manaCurveObj={manaCurve} barColor={playerClass}/> <h3>Cards <CopyDeck deckstring={deckstring} playerClass={playerClass}/></h3> <DecklistSidebar showCardAdditionBox inDeckCreation={false} deck={activeDeckCopy.cards} deckLength={activeDeckCopy.length} /> </div> ) }; const mapStateToProps = state => { const { activeDeck, activeDeckCopy } = state.deckView; return { activeDeck, activeDeckCopy}; }; export default connect(mapStateToProps)(DeckDetails);
frontend/src/Movie/Editor/Delete/DeleteMovieModalContent.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import FormGroup from 'Components/Form/FormGroup'; import FormInputGroup from 'Components/Form/FormInputGroup'; import FormLabel from 'Components/Form/FormLabel'; import Button from 'Components/Link/Button'; import ModalBody from 'Components/Modal/ModalBody'; import ModalContent from 'Components/Modal/ModalContent'; import ModalFooter from 'Components/Modal/ModalFooter'; import ModalHeader from 'Components/Modal/ModalHeader'; import { inputTypes, kinds } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; import styles from './DeleteMovieModalContent.css'; class DeleteMovieModalContent extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { deleteFiles: false, addImportExclusion: false }; } // // Listeners onDeleteFilesChange = ({ value }) => { this.setState({ deleteFiles: value }); } onAddImportExclusionChange = ({ value }) => { this.setState({ addImportExclusion: value }); } onDeleteMovieConfirmed = () => { const deleteFiles = this.state.deleteFiles; const addImportExclusion = this.state.addImportExclusion; this.setState({ deleteFiles: false, addImportExclusion: false }); this.props.onDeleteSelectedPress(deleteFiles, addImportExclusion); } // // Render render() { const { movies, onModalClose } = this.props; const deleteFiles = this.state.deleteFiles; const addImportExclusion = this.state.addImportExclusion; return ( <ModalContent onModalClose={onModalClose}> <ModalHeader> {translate('DeleteSelectedMovie')} </ModalHeader> <ModalBody> <div> <FormGroup> <FormLabel>{`Delete Movie Folder${movies.length > 1 ? 's' : ''}`}</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="deleteFiles" value={deleteFiles} helpText={`Delete Movie Folder${movies.length > 1 ? 's' : ''} and all contents`} kind={kinds.DANGER} onChange={this.onDeleteFilesChange} /> </FormGroup> <FormGroup> <FormLabel>{translate('AddListExclusion')}</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="addImportExclusion" value={addImportExclusion} helpText={translate('AddImportExclusionHelpText')} kind={kinds.DANGER} onChange={this.onAddImportExclusionChange} /> </FormGroup> </div> <div className={styles.message}> {`Are you sure you want to delete ${movies.length} selected movie(s)${deleteFiles ? ' and all contents' : ''}?`} </div> <ul> { movies.map((s) => { return ( <li key={s.title}> <span>{s.title}</span> { deleteFiles && <span className={styles.pathContainer}> - <span className={styles.path}> {s.path} </span> </span> } </li> ); }) } </ul> </ModalBody> <ModalFooter> <Button onPress={onModalClose}> {translate('Cancel')} </Button> <Button kind={kinds.DANGER} onPress={this.onDeleteMovieConfirmed} > {translate('Delete')} </Button> </ModalFooter> </ModalContent> ); } } DeleteMovieModalContent.propTypes = { movies: PropTypes.arrayOf(PropTypes.object).isRequired, onModalClose: PropTypes.func.isRequired, onDeleteSelectedPress: PropTypes.func.isRequired }; export default DeleteMovieModalContent;
universal_project_template/shared/js/components/NotFound.js
Mikeysax/mikey
import React from 'react'; export default class NotFound extends React.Component { render() { return ( <div> <h1 className="text-center"> Not Found </h1> </div> ); } }
src/SegmentedControl/macOs/index.js
gabrielbull/react-desktop
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Dimension, { dimensionPropTypes } from '../../style/dimension'; import Margin, { marginPropTypes } from '../../style/margin'; import Hidden, { hiddenPropTypes } from '../../style/hidden'; import Item from './Item'; import Tabs from './Tabs'; import styles from './style/10.11'; import Box from '../../Box/macOs'; let warnOnce = false; function applyItem() { return function(ComposedComponent) { const nextItem = Item; ComposedComponent.prototype.Item = ComposedComponent.Item = function( ...args ) { if (!warnOnce) { warnOnce = true; console.warn( 'React Desktop: Using SegmentedControl.Item is deprecated, import SegmentedControlItem instead.' ); } return new nextItem(...args); }; return ComposedComponent; }; } @applyItem() @Dimension() @Margin() @Hidden() class SegmentedControl extends Component { static propTypes = { ...dimensionPropTypes, ...marginPropTypes, ...hiddenPropTypes, box: PropTypes.bool }; select(item) { this.refs.tabs.select(item); } unselect(item) { this.refs.tabs.unselect(item); } render() { let { children, box, ...props } = this.props; let content; if (box) { content = ( <Box style={{ marginTop: '-11px', zIndex: 0 }}>{this.renderItem()}</Box> ); } else { content = <div>{this.renderItem()}</div>; } return ( <div style={styles.sergmentedControl} {...props}> <Tabs style={{ position: 'relative', zIndex: 1 }}>{children}</Tabs> {content} </div> ); } renderItem() { let child = null; let children; // todo: use Children.map if (!this.props.children) { return null; } else if ( Object.prototype.toString.call(this.props.children) !== '[object Array]' ) { children = [this.props.children]; } else { children = [...this.props.children]; } for (let i = 0, len = children.length; i < len; ++i) { if (children[i].props.selected) child = children[i]; } return child; } } export default SegmentedControl;
src/js/components/global/NotFound.js
jorgemxm/r-movies
'use strict'; import React from 'react'; // 404 Route //-------------- const NotFound = props => ( <div className="page--not-found"> <div className="container has-text-centered"> <p className="title"> <strong>:[</strong> </p> <p className="subtitle">Not Found</p> </div> </div> ); export default NotFound;
stories/index.js
sedooe/cevirgec
import React from 'react'; import { storiesOf, action, linkTo } from '@kadira/storybook'; import DictionaryList from './DictionaryList'; import Button from './Button'; import tr from '../app/utils/Translation'; import { Form, Checkbox } from 'semantic-ui-react'; import DictionaryModal from './DictionaryModal'; import {dictionariesForDropdown} from './MockData'; import ActiveDictionarySelector from './ActiveDictionarySelector'; import Register from './Register'; import NewDefinitionWindow from './NewDefinitionWindow'; import Study from './Study'; import '../app/index.scss'; storiesOf('Button', module) .add('with text', () => ( <Button onClick={action('clicked')}>Hello Button</Button> )); storiesOf('DictionaryList', module) .add('deneme', () => ( <DictionaryList/> )); storiesOf('DictionaryModal', module) .add('deneme', () => ( <DictionaryModal/> )); storiesOf('Register', module) .add('Register', () => ( <Register /> )); storiesOf('New Definition Window', module) .add('The Container', () => ( <NewDefinitionWindow /> )) .add('ActiveDictionarySelector', () => ( <ActiveDictionarySelector dictionaries={dictionariesForDropdown} /> )) storiesOf('Study', module) .add('Study', () => ( <Study definitions = {Array(5).fill().map(() => ({id: Math.ceil(Math.random()*1000)}))} /> ));
node_modules/react-router/es/Prompt.js
yaolei/Node-Clound
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; /** * The public API for prompting the user before navigating away * from a screen with a component. */ var Prompt = function (_React$Component) { _inherits(Prompt, _React$Component); function Prompt() { _classCallCheck(this, Prompt); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Prompt.prototype.enable = function enable(message) { if (this.unblock) this.unblock(); this.unblock = this.context.router.history.block(message); }; Prompt.prototype.disable = function disable() { if (this.unblock) { this.unblock(); this.unblock = null; } }; Prompt.prototype.componentWillMount = function componentWillMount() { if (this.props.when) this.enable(this.props.message); }; Prompt.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (nextProps.when) { if (!this.props.when || this.props.message !== nextProps.message) this.enable(nextProps.message); } else { this.disable(); } }; Prompt.prototype.componentWillUnmount = function componentWillUnmount() { this.disable(); }; Prompt.prototype.render = function render() { return null; }; return Prompt; }(React.Component); Prompt.propTypes = { when: PropTypes.bool, message: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired }; Prompt.defaultProps = { when: true }; Prompt.contextTypes = { router: PropTypes.shape({ history: PropTypes.shape({ block: PropTypes.func.isRequired }).isRequired }).isRequired }; export default Prompt;
src/server/html.js
fk1blow/repeak
import React from 'react'; export default class Html extends React.Component { render() { // Only for production. For dev, it's handled by webpack with livereload. const linkStyles = this.props.isProduction && <link href={`/build/app.css?v=${this.props.version}`} rel="stylesheet" />; // TODO: Add favicon. const linkFavicon = false && <link href={`/build/img/favicon.icon?v=${this.props.version}`} rel="shortcut icon" />; return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" /> <title>{this.props.title}</title> {linkStyles} {linkFavicon} </head> <body dangerouslySetInnerHTML={{__html: this.props.bodyHtml}} /> </html> ); } } Html.propTypes = { bodyHtml: React.PropTypes.string.isRequired, isProduction: React.PropTypes.bool.isRequired, title: React.PropTypes.string.isRequired, version: React.PropTypes.string.isRequired };
frontend/app/components/pages/admin/link-remove-password-modal.js
LINKIWI/linkr
import Link from 'react-router/lib/Link'; import LoadingHOC from 'react-loading-hoc'; import React from 'react'; import request from 'browser-request'; import Alert, {ALERT_TYPE_SUCCESS, ALERT_TYPE_ERROR} from '../../alert'; import Button from '../../ui/button'; import LoadingBar from '../../ui/loading-bar'; import Modal from '../../ui/modal'; import context from '../../../util/context'; /** * Modal used for removing a link's password. */ class LinkRemovePasswordModal extends React.Component { static propTypes = { linkID: React.PropTypes.number, alias: React.PropTypes.string, fullAlias: React.PropTypes.string, outgoingURL: React.PropTypes.string, // Function to reload the link details in the parent component. // This should be called after a successful server-side link update, so that the UI reflects // the information that was just submitted by the user. reloadLinkDetails: React.PropTypes.func }; constructor(props) { super(props); this.state = { passwordStatus: { success: null } }; } /** * Default behavior for the modal's cancel button is to close the modal. * * @param {Object} evt DOM event object */ handleCancelClick(evt) { evt.preventDefault(); this.modal.hideModal(); } /** * On submission, call the API for removing the link password. This will also trigger a link * details reload in the parent component on success. * * @param {Object} evt DOM event object */ handleSubmitClick(evt) { evt.preventDefault(); const {linkID, reloadLinkDetails, loading} = this.props; loading((done) => request.post({ url: context.uris.LinkUpdatePasswordURI, json: { /* eslint-disable camelcase */ link_id: linkID, password: null /* eslint-enable camelcase */ } }, (err, resp, passwordStatus) => { // eslint-disable-line handle-callback-err this.setState({passwordStatus}); if (passwordStatus.success) { reloadLinkDetails(); } return done(); })); } render() { const {alias, fullAlias, isLoading} = this.props; const {passwordStatus} = this.state; return ( <Modal ref={(elem) => { this.modal = elem; }} cancelable={!isLoading} > {isLoading && <LoadingBar />} <div className={`modal-content transition ${isLoading && 'fade'}`}> { passwordStatus.success !== null && ( <Alert className={'iota'} type={passwordStatus.success ? ALERT_TYPE_SUCCESS : ALERT_TYPE_ERROR} title={ passwordStatus.success ? 'This link\'s password was removed successfully!' : 'There was an error removing this link\'s password.' } message={ passwordStatus.success ? 'All future requests to this link will no longer require a password.' : passwordStatus.message } failure={passwordStatus.failure} failureMessages={{ /* eslint-disable camelcase */ failure_incomplete_params: 'This link does not seem to exist.' /* eslint-enable camelcase */ }} /> ) } <div className="margin-large--bottom"> <p className="sans-serif bold text-gray-70 delta margin-small--bottom"> Remove Link Password </p> <p className="sans-serif text-gray-60 iota"> This will remove the existing password from the link with the alias&nbsp; <span className="sans-serif bold text-primary">{alias}</span>. All future requests to <Link to={fullAlias}>{fullAlias}</Link> will redirect without prompting for a password. </p> </div> <div className="text-right"> <a className="sans-serif bold iota margin--right" href="#" onClick={this.handleCancelClick.bind(this)} > CANCEL </a> <Button className="sans-serif bold iota text-white" text="Submit" onClick={this.handleSubmitClick.bind(this)} /> </div> </div> </Modal> ); } } export default LoadingHOC(LinkRemovePasswordModal);
src/components/Users.js
TheDuckFIN/react-chat
import React from 'react'; import User from './User'; export default class Users extends React.Component { render() { return ( <div className="users"> <strong>Online users (server)</strong> <ul className="userlist"> { Object.keys(this.props.users).map((userid) => <User key={userid} nick={this.props.users[userid].nick} /> ) } </ul> </div> ); } }
docs/src/Root.js
HorizonXP/react-bootstrap
import React from 'react'; import Router from 'react-router'; const Root = React.createClass({ statics: { /** * Get the list of pages that are renderable * * @returns {Array} */ getPages() { return [ 'index.html', 'introduction.html', 'getting-started.html', 'components.html', 'support.html' ]; } }, getDefaultProps() { return { assetBaseUrl: '' }; }, childContextTypes: { metadata: React.PropTypes.object }, getChildContext() { return { metadata: this.props.propData }; }, render() { // Dump out our current props to a global object via a script tag so // when initialising the browser environment we can bootstrap from the // same props as what each page was rendered with. let browserInitScriptObj = { __html: `window.INITIAL_PROPS = ${JSON.stringify(this.props)}; // console noop shim for IE8/9 (function (w) { var noop = function () {}; if (!w.console) { w.console = {}; ['log', 'info', 'warn', 'error'].forEach(function (method) { w.console[method] = noop; }); } }(window));` }; let head = { __html: `<title>React-Bootstrap</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="${this.props.assetBaseUrl}/assets/bundle.css" rel="stylesheet"> <link href="${this.props.assetBaseUrl}/assets/favicon.ico?v=2" type="image/x-icon" rel="shortcut icon"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script> <![endif]-->` }; return ( <html> <head dangerouslySetInnerHTML={head} /> <body> <Router.RouteHandler propData={this.props.propData} /> <script dangerouslySetInnerHTML={browserInitScriptObj} /> <script src={`${this.props.assetBaseUrl}/assets/bundle.js`} /> </body> </html> ); } }); export default Root;
src/containers/IndustryPage/IndustryPage.js
VumeroInstitute/Vumero-Talent-Matrix
/** * Created by wangdi on 4/10/17. */ import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Tag from '../../components/Tag/Tag'; import '../SkillPage/skill.css'; import RaisedButton from 'material-ui/RaisedButton'; export default class IndustryPage extends React.Component { static propTypes = { tags: PropTypes.array, addCallback: PropTypes.func, deleteCallback: PropTypes.func, nextCallback: PropTypes.func }; componentDidMount(){ this.refs.indInput.focus(); } render() { return ( <div className="function-container"> <input ref="indInput" type="text" placeholder="List the industries you have has most experience in (up to 6)" onKeyDown={this._inputOnKeyDown.bind(this)}/> <div className="tags-container"> {this.props.tags.map((tag, i) => { return <Tag key={i} title={tag} deleteCallback={this._deleteOnClick.bind(this, i)}/> })} </div> <RaisedButton label="Next" backgroundColor="#fd6c21" labelColor="#fff" style={{marginTop: '20px'}} onClick={() => { this.props.nextCallback() }} /> </div> ); } _deleteOnClick(index) { this.props.deleteCallback(index); } _inputOnKeyDown(evt) { if (evt.keyCode === 13) { const funName = ReactDOM.findDOMNode(this.refs.indInput).value.trim(); if (funName.length > 0) { ReactDOM.findDOMNode(this.refs.indInput).value = ''; this.props.addCallback(funName); } } } }
www/spa/src/Survey/router.js
gram7gram/Survey
"use strict"; import React from 'react'; import { Router, Route, IndexRoute, hashHistory } from 'react-router'; import trans from './translator'; import Layout from './components/Layout'; import ClientIndex from './components/Pages/Client/Index'; import CompleteSurvey from './components/Pages/CompleteSurvey/Index'; import CompletedSurvey from './components/Pages/CompletedSurvey/Index'; import NoAccess from './components/NoAccess'; const toTop = () => { window.scrollTo(0, 0) } const onCompleteEnter = (getState, nextState, replace) => { document.title = trans.ru.surveyTitle toTop() const store = getState(); if (store.ActiveSurvey.isDenied) { hashHistory.push('/no-access') } else if (!store.Promocode.isVerified) { hashHistory.push('/') } } const onCompletedEnter = (getState, nextState, replace) => { document.title = trans.ru.surveyTitle toTop() const store = getState(); if (store.ActiveSurvey.isDenied) { hashHistory.push('/no-access') } else if (!store.Promocode.isVerified) { hashHistory.push('/') } } const onNoAccessEnter = (store, nextState, replace) => { document.title = trans.ru.accessDenied toTop() } const onSurveyEnter = (store, nextState, replace) => { document.title = trans.ru.homepageTitle toTop() } const createRouter = (store) => { return ( <Router history={hashHistory}> <Route path="/" component={Layout}> <IndexRoute component={ClientIndex} onEnter={onSurveyEnter.bind(this, store)}/> <Route path="/complete/:id" component={CompleteSurvey} onEnter={onCompleteEnter.bind(this, store)}/> <Route path="/completed/:id" component={CompletedSurvey} onEnter={onCompletedEnter.bind(this, store)}/> <Route path="/no-access" component={NoAccess} onEnter={onNoAccessEnter.bind(this, store)}/> </Route> </Router> ) } export default createRouter;
react/features/toolbox/components/native/ScreenSharingIosButton.js
gpolitis/jitsi-meet
// @flow import React from 'react'; import { findNodeHandle, NativeModules, Platform } from 'react-native'; import { ScreenCapturePickerView } from 'react-native-webrtc'; import { getFeatureFlag, IOS_SCREENSHARING_ENABLED } from '../../../base/flags'; import { translate } from '../../../base/i18n'; import { IconShareDesktop } from '../../../base/icons'; import { connect } from '../../../base/redux'; import { AbstractButton, type AbstractButtonProps } from '../../../base/toolbox/components'; import { isLocalVideoTrackDesktop } from '../../../base/tracks'; /** * The type of the React {@code Component} props of {@link ScreenSharingIosButton}. */ type Props = AbstractButtonProps & { /** * True if the button needs to be disabled. */ _disabled: boolean, /** * Whether video is currently muted or not. */ _screensharing: boolean, /** * The redux {@code dispatch} function. */ dispatch: Function }; const styles = { screenCapturePickerView: { display: 'none' } }; /** * An implementation of a button for toggling screen sharing on iOS. */ class ScreenSharingIosButton extends AbstractButton<Props, *> { _nativeComponent: ?Object; _setNativeComponent: Function; accessibilityLabel = 'toolbar.accessibilityLabel.shareYourScreen'; icon = IconShareDesktop; label = 'toolbar.startScreenSharing'; toggledLabel = 'toolbar.stopScreenSharing'; /** * Initializes a new {@code ScreenSharingIosButton} instance. * * @param {Object} props - The React {@code Component} props to initialize * the new {@code ScreenSharingIosButton} instance with. */ constructor(props) { super(props); this._nativeComponent = null; // Bind event handlers so they are only bound once per instance. this._setNativeComponent = this._setNativeComponent.bind(this); } /** * Sets the internal reference to the React Component wrapping the * {@code RPSystemBroadcastPickerView} component. * * @param {ReactComponent} component - React Component. * @returns {void} */ _setNativeComponent(component) { this._nativeComponent = component; } /** * Handles clicking / pressing the button. * * @override * @protected * @returns {void} */ _handleClick() { const handle = findNodeHandle(this._nativeComponent); NativeModules.ScreenCapturePickerViewManager.show(handle); } /** * Returns a boolean value indicating if this button is disabled or not. * * @protected * @returns {boolean} */ _isDisabled() { return this.props._disabled; } /** * Indicates whether this button is in toggled state or not. * * @override * @protected * @returns {boolean} */ _isToggled() { return this.props._screensharing; } /** * Helper function to be implemented by subclasses, which may return a * new React Element to be appended at the end of the button. * * @protected * @returns {ReactElement|null} */ _getElementAfter() { return ( <ScreenCapturePickerView ref = { this._setNativeComponent } style = { styles.screenCapturePickerView } /> ); } } /** * Maps (parts of) the redux state to the associated props for the * {@code ScreenSharingIosButton} component. * * @param {Object} state - The Redux state. * @private * @returns {{ * _disabled: boolean, * }} */ function _mapStateToProps(state): Object { const enabled = getFeatureFlag(state, IOS_SCREENSHARING_ENABLED, false); return { _screensharing: isLocalVideoTrackDesktop(state), // TODO: this should work on iOS 12 too, but our trick to show the picker doesn't work. visible: enabled && Platform.OS === 'ios' && Number.parseInt(Platform.Version.split('.')[0], 10) >= 14 }; } export default translate(connect(_mapStateToProps)(ScreenSharingIosButton));
example/examples/StaticMap.js
amitv87/react-native-maps
import React from 'react'; import { StyleSheet, View, Text, Dimensions, ScrollView, } from 'react-native'; import MapView from 'react-native-maps'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; class StaticMap extends React.Component { constructor(props) { super(props); this.state = { region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, }; } render() { return ( <View style={styles.container}> <ScrollView style={StyleSheet.absoluteFill} contentContainerStyle={styles.scrollview} > <Text>Clicking</Text> <Text>and</Text> <Text>dragging</Text> <Text>the</Text> <Text>map</Text> <Text>will</Text> <Text>cause</Text> <Text>the</Text> <MapView provider={this.props.provider} style={styles.map} scrollEnabled={false} zoomEnabled={false} pitchEnabled={false} rotateEnabled={false} initialRegion={this.state.region} > <MapView.Marker title="This is a title" description="This is a description" coordinate={this.state.region} /> </MapView> <Text>parent</Text> <Text>ScrollView</Text> <Text>to</Text> <Text>scroll.</Text> <Text>When</Text> <Text>using</Text> <Text>a Google</Text> <Text>Map</Text> <Text>this only</Text> <Text>works</Text> <Text>if you</Text> <Text>disable:</Text> <Text>scroll,</Text> <Text>zoom,</Text> <Text>pitch,</Text> <Text>rotate.</Text> <Text>...</Text> <Text>It</Text> <Text>would</Text> <Text>be</Text> <Text>nice</Text> <Text>to</Text> <Text>have</Text> <Text>an</Text> <Text>option</Text> <Text>that</Text> <Text>still</Text> <Text>allows</Text> <Text>zooming.</Text> </ScrollView> </View> ); } } StaticMap.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, justifyContent: 'flex-end', alignItems: 'center', }, scrollview: { alignItems: 'center', paddingVertical: 40, }, map: { width: 250, height: 250, }, }); module.exports = StaticMap;
dawn/renderer/components/Dashboard.js
pioneers/PieCentral
import React from 'react'; import PropTypes from 'prop-types'; import { Grid, Row, Col } from 'react-bootstrap'; import PeripheralList from './PeripheralList'; import GamepadList from './GamepadList'; import EditorContainer from './EditorContainer'; const Dashboard = props => ( <Grid fluid> <Row> <Col smPush={8} sm={4}> <PeripheralList connectionStatus={props.connectionStatus} runtimeStatus={props.runtimeStatus} /> <GamepadList /> </Col> <Col smPull={4} sm={8}> <EditorContainer runtimeStatus={props.runtimeStatus} isRunningCode={props.isRunningCode} /> </Col> </Row> </Grid> ); Dashboard.propTypes = { connectionStatus: PropTypes.bool.isRequired, runtimeStatus: PropTypes.bool.isRequired, isRunningCode: PropTypes.bool.isRequired, }; export default Dashboard;
priv/chat_client/src/index.js
lilrooness/erlang_react_chat
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
client/src/components/beers/beer-detail.js
commoncode/ontap
/** * Beer Detail component. * * Show a single beer with editing and deleting. */ import React from 'react'; import { Container } from 'flux/utils'; import { fetchBeer, deleteBeer, toggleEditBeer } from '../../actions/beers'; import beerDetailStore from '../../stores/beer-detail'; import profileStore from '../../stores/profile'; import * as propTypes from '../../proptypes'; import Loader from '../loader/'; import BeerEdit from './beer-edit'; import BeerSummary from './beer-summary'; import BeerKegs from './beer-kegs'; class BeerDetail extends React.Component { static propTypes() { return { beer: propTypes.beerModel, profile: propTypes.profile, }; } constructor() { super(); this.deleteBeer = this.deleteBeer.bind(this); } deleteBeer() { deleteBeer(this.props.beer.model.id) .then(document.location.hash = '/beers'); } render() { const { fetching, editing, model } = this.props.beer; const { profile } = this.props; const isAdmin = profile.data && profile.data.admin; if (fetching) return <Loader />; return ( <div> <div className="beer-detail-view view"> <BeerSummary {...model} /> <BeerKegs beer={model} profile={profile.data} /> { isAdmin && ( <div className="beer-actions"> <button className="btn" onClick={toggleEditBeer}>Edit Beer</button> <button className="btn" onClick={this.deleteBeer}>Delete Beer</button> </div> ) } { editing && <BeerEdit model={model} profile={profile} /> } </div> </div> ); } } class BeerDetailContainer extends React.Component { static getStores() { return [beerDetailStore, profileStore]; } static calculateState() { return { beer: beerDetailStore.getState(), profile: profileStore.getState(), }; } componentWillMount() { fetchBeer(this.props.beerId); } render() { return <BeerDetail beer={this.state.beer} profile={this.state.profile} />; } } export default Container.create(BeerDetailContainer, { withProps: true });
src/svg-icons/action/polymer.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPolymer = (props) => ( <SvgIcon {...props}> <path d="M19 4h-4L7.11 16.63 4.5 12 9 4H5L.5 12 5 20h4l7.89-12.63L19.5 12 15 20h4l4.5-8z"/> </SvgIcon> ); ActionPolymer = pure(ActionPolymer); ActionPolymer.displayName = 'ActionPolymer'; ActionPolymer.muiName = 'SvgIcon'; export default ActionPolymer;
src/pages/speakers.js
ThoughtAtWork/Website
import React from 'react' import Link from 'gatsby-link' import CardGridSpeaker from '../components/CardGridSpeaker' const SpeakerPage = () => ( <div> <h1>Speakers Page</h1> <p>Currently under construction</p> <Link to="/">Go back to the homepage</Link> <CardGridSpeaker /> </div> ) export default SpeakerPage
src/components/Mention.js
devsy-io/devsy-editor
import React from 'react' export default function Mention ({children}) { return <span className='devsy-Mention'>{children}</span> }
src/svg-icons/action/stars.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionStars = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm4.24 16L12 15.45 7.77 18l1.12-4.81-3.73-3.23 4.92-.42L12 5l1.92 4.53 4.92.42-3.73 3.23L16.23 18z"/> </SvgIcon> ); ActionStars = pure(ActionStars); ActionStars.displayName = 'ActionStars'; ActionStars.muiName = 'SvgIcon'; export default ActionStars;
src/svg-icons/image/filter-none.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterNone = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"/> </SvgIcon> ); ImageFilterNone = pure(ImageFilterNone); ImageFilterNone.displayName = 'ImageFilterNone'; export default ImageFilterNone;
docs/src/app.js
sick-sad-world/react-validable
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import SimpleForm from './forms/simple.jsx'; // import DynamicForm from 'forms/dynamic'; // import FormWithCustomItem from 'forms/custom'; render( ( <div className='index'> <hgroup> <h1>Validation for react</h1> <h2>Testing playground</h2> <blockquote>Do what ever you want here</blockquote> </hgroup> <SimpleForm exposeRaw={true}/> </div> ), document.getElementById('appRoot') );
examples/js/custom/show-only-select-button/fully-custom-show-select-button.js
powerhome/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-unused-vars: 0 */ /* eslint no-alert: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class FullyCustomShowSelectButtonTable extends React.Component { createCustomShowSelectButton = (onClick, showSelected) => { return ( <button style={ { color: 'red' } } onClick={ onClick }> { showSelected ? 'Select Only' : 'All' } </button> ); } render() { const selectRow = { mode: 'radio', showOnlySelected: true }; const options = { showSelectedOnlyBtn: this.createCustomShowSelectButton }; return ( <BootstrapTable data={ products } options={ options } selectRow={ selectRow }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
client/src/MyJobs.js
roxroy/codeploy
import React, { Component } from 'react'; const EachJob = require('./EachJob'); const JobModal = require('./JobModal'); const AddJobButton = require('./AddJobButton'); class MyJobs extends Component { constructor(props) { super(props); this.state = { viewingJob: false, viewingJobResources: false, currentJob: null, currentSort: ["jobPosition", true] }; this.handleViewJob = this.handleViewJob.bind(this); this.handleViewResources = this.handleViewResources.bind(this); this.handleCloseModal = this.handleCloseModal.bind(this); this.handleClick = this.handleClick.bind(this); } handleViewJob(cJob) { let currentJobResources = this.setState({ viewingJob: true, viewingResource: false, currentJob: cJob }); } handleViewResources() { this.setState({ viewingJob: false, viewingResource: true }); } handleCloseModal() { this.setState({ viewingJob: false, viewingJobResources: false }); } handleClick(event) { // order: true==ascending, false==descending const cTH = event.target.id; let order; // if current column is being sorted if (cTH === this.state.currentSort[0]) { order = !this.state.currentSort[1]; } else { order = true; }; this.setState({ currentSort: [cTH, order] }); } componentDidMount() { console.log('myjob componentDidMount'); (!this.props.jobs) && this.props.getJobs(); } render() { const jobSort = { jobPosition(jobs) { return jobs.sort((a, b) => { // return true if a.jobPosition comes after b.jobPosition return a.jobPosition.localeCompare(b.jobPosition); }); }, companyName(jobs) { return jobs.sort((a, b) => { // return true if a.name comes after b.name return a.companyName.localeCompare(b.companyName); }); }, dateApplied(jobs) { return jobs.sort((a, b) => { return new Date(b.dateApplied) - new Date(a.dateApplied); }); } } let jobs = jobSort[this.state.currentSort[0]](this.props.jobs); if (!this.state.currentSort[1]) jobs.reverse(); return ( <div> <AddJobButton jobs={this.props.jobs} saveJob={this.props.saveJob} /> <div className="job-list-container"> <table> <tbody> <tr> <th onClick={this.handleClick} id="jobPosition"> {"Job Position "} {(this.state.currentSort[0] === "jobPosition") && ( this.state.currentSort[1] ? <i id="jobPosition" className="fa fa-arrow-up" aria-hidden="true"></i> : <i id="jobPosition" className="fa fa-arrow-down" aria-hidden="true"></i> )} </th> <th onClick={this.handleClick} id="companyName"> {"Company Name "} {(this.state.currentSort[0] === "companyName") && ( this.state.currentSort[1] ? <i id="companyName" className="fa fa-arrow-up" aria-hidden="true"></i> : <i id="companyName" className="fa fa-arrow-down" aria-hidden="true"></i> )} </th> <th onClick={this.handleClick} id="dateApplied"> {"Date Applied "} {(this.state.currentSort[0] === "dateApplied") && ( this.state.currentSort[1] ? <i id="dateApplied" className="fa fa-arrow-up" aria-hidden="true"></i> : <i id="dateApplied" className="fa fa-arrow-down" aria-hidden="true"></i> )} </th> <th>Relevant Resources</th> <th className="last-jobs-th">Comments</th> </tr> {jobs.map((row, i) => <EachJob row={row} key={i} handleViewJob={this.handleViewJob} deleteJob={this.props.deleteJob} /> )} </tbody> </table> {/*Modal that renders a list of resources for the respective job*/} {this.state.viewingJob && <JobModal handleCloseModal={this.handleCloseModal} viewingJob={this.state.viewingJob} job={this.state.currentJob} />} </div> </div> ); } } module.exports = MyJobs;
src/FadeMixin.js
chilts/react-bootstrap
import React from 'react'; import domUtils from './utils/domUtils'; import deprecationWarning from './utils/deprecationWarning'; // TODO: listen for onTransitionEnd to remove el function getElementsAndSelf (root, classes){ let els = root.querySelectorAll('.' + classes.join('.')); els = [].map.call(els, function(e){ return e; }); for(let i = 0; i < classes.length; i++){ if( !root.className.match(new RegExp('\\b' + classes[i] + '\\b'))){ return els; } } els.unshift(root); return els; } export default { componentWillMount(){ deprecationWarning('FadeMixin', 'Fade Component'); }, _fadeIn() { let els; if (this.isMounted()) { els = getElementsAndSelf(React.findDOMNode(this), ['fade']); if (els.length) { els.forEach(function (el) { el.className += ' in'; }); } } }, _fadeOut() { let els = getElementsAndSelf(this._fadeOutEl, ['fade', 'in']); if (els.length) { els.forEach(function (el) { el.className = el.className.replace(/\bin\b/, ''); }); } setTimeout(this._handleFadeOutEnd, 300); }, _handleFadeOutEnd() { if (this._fadeOutEl && this._fadeOutEl.parentNode) { this._fadeOutEl.parentNode.removeChild(this._fadeOutEl); } }, componentDidMount() { if (document.querySelectorAll) { // Firefox needs delay for transition to be triggered setTimeout(this._fadeIn, 20); } }, componentWillUnmount() { let els = getElementsAndSelf(React.findDOMNode(this), ['fade']); let container = (this.props.container && React.findDOMNode(this.props.container)) || domUtils.ownerDocument(this).body; if (els.length) { this._fadeOutEl = document.createElement('div'); container.appendChild(this._fadeOutEl); this._fadeOutEl.appendChild(React.findDOMNode(this).cloneNode(true)); // Firefox needs delay for transition to be triggered setTimeout(this._fadeOut, 20); } } };
gritsurvey/node_modules/react-router/es/MemoryRouter.js
Alex-Gardner/grit-survey
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; import createHistory from 'history/createMemoryHistory'; import Router from './Router'; /** * The public API for a <Router> that stores location in memory. */ var MemoryRouter = function (_React$Component) { _inherits(MemoryRouter, _React$Component); function MemoryRouter() { var _temp, _this, _ret; _classCallCheck(this, MemoryRouter); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret); } MemoryRouter.prototype.render = function render() { return React.createElement(Router, { history: this.history, children: this.props.children }); }; return MemoryRouter; }(React.Component); MemoryRouter.propTypes = { initialEntries: PropTypes.array, initialIndex: PropTypes.number, getUserConfirmation: PropTypes.func, keyLength: PropTypes.number, children: PropTypes.node }; export default MemoryRouter;
admin/client/components/Forms/EditFormHeader.js
andreufirefly/keystone
import React from 'react'; import ReactDOM from 'react-dom'; import Toolbar from '../Toolbar'; import { Button, FormIconField, FormInput, ResponsiveText } from 'elemental'; var Header = React.createClass({ displayName: 'EditFormHeader', propTypes: { data: React.PropTypes.object, list: React.PropTypes.object, toggleCreate: React.PropTypes.func, }, getInitialState () { return { searchString: '', }; }, toggleCreate (visible) { this.props.toggleCreate(visible); }, searchStringChanged (event) { this.setState({ searchString: event.target.value, }); }, handleEscapeKey (event) { const escapeKeyCode = 27; if (event.which === escapeKeyCode) { ReactDOM.findDOMNode(this.refs.searchField).blur(); } }, renderDrilldown () { return ( <Toolbar.Section left> {this.renderDrilldownItems()} {this.renderSearch()} </Toolbar.Section> ); }, renderDrilldownItems () { var list = this.props.list; var items = this.props.data.drilldown ? this.props.data.drilldown.items : []; var els = items.map((dd, i) => { var links = []; dd.items.forEach((el, i) => { links.push(<a key={'dd' + i} href={el.href} title={dd.list.singular}>{el.label}</a>); if (i < dd.items.length - 1) { links.push(<span key={'ds' + i} className="separator">,</span>); // eslint-disable-line comma-spacing } }); var more = dd.more ? <span>...</span> : ''; return ( <li key={`dd-${i}`}> {links} {more} </li> ); }); if (!els.length) { return ( <Button type="link" href={`${Keystone.adminPath}/${list.path}`}> <span className="octicon octicon-chevron-left" /> {list.plural} </Button> ); } else { // add the current list els.push( <li key="back"> <a type="link" href={`${Keystone.adminPath}/${list.path}`}>{list.plural}</a> </li> ); return <ul className="item-breadcrumbs" key="drilldown">{els}</ul>; } }, renderSearch () { var list = this.props.list; return ( <form action={`${Keystone.adminPath}/${list.path}`} className="EditForm__header__search"> <FormIconField iconPosition="left" iconColor="primary" iconKey="search" className="EditForm__header__search-field"> <FormInput ref="searchField" type="search" name="search" value={this.state.searchString} onChange={this.searchStringChanged} onKeyUp={this.handleEscapeKey} placeholder="Search" className="EditForm__header__search-input" /> </FormIconField> </form> ); }, renderInfo () { return ( <Toolbar.Section right> {this.renderCreateButton()} </Toolbar.Section> ); }, renderCreateButton () { if (this.props.list.nocreate) return null; var props = {}; if (this.props.list.autocreate) { props.href = '?new' + Keystone.csrf.query; } else { props.onClick = () => { this.toggleCreate(true); }; } return ( <Button type="success" {...props}> <span className="octicon octicon-plus" /> <ResponsiveText hiddenXS={`New ${this.props.list.singular}`} visibleXS="Create" /> </Button> ); }, render () { return ( <Toolbar> {this.renderDrilldown()} {this.renderInfo()} </Toolbar> ); }, }); module.exports = Header;
src/utils/CustomPropTypes.js
laran/react-bootstrap
import React from 'react'; import warning from 'react/lib/warning'; import childrenToArray from './childrenToArray'; const ANONYMOUS = '<<anonymous>>'; /** * Create chain-able isRequired validator * * Largely copied directly from: * https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94 */ function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName) { componentName = componentName || ANONYMOUS; if (props[propName] == null) { if (isRequired) { return new Error( `Required prop '${propName}' was not specified in '${componentName}'.` ); } } else { return validate(props, propName, componentName); } } let chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function errMsg(props, propName, componentName, msgContinuation) { return `Invalid prop '${propName}' of value '${props[propName]}'` + ` supplied to '${componentName}'${msgContinuation}`; } function createMountableChecker() { function validate(props, propName, componentName) { if (typeof props[propName] !== 'object' || typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) { return new Error( errMsg(props, propName, componentName, ', expected a DOM element or an object that has a `render` method') ); } } return createChainableTypeChecker(validate); } function createKeyOfChecker(obj) { function validate(props, propName, componentName) { let propValue = props[propName]; if (!obj.hasOwnProperty(propValue)) { let valuesString = JSON.stringify(Object.keys(obj)); return new Error( errMsg(props, propName, componentName, `, expected one of ${valuesString}.`) ); } } return createChainableTypeChecker(validate); } function createSinglePropFromChecker(arrOfProps) { function validate(props, propName) { const usedPropCount = arrOfProps .map(listedProp => props[listedProp]) .reduce((acc, curr) => acc + (curr !== undefined ? 1 : 0), 0); if (usedPropCount > 1) { const [first, ...others] = arrOfProps; const message = `${others.join(', ')} and ${first}`; return new Error( `Invalid prop '${propName}', only one of the following ` + `may be provided: ${message}` ); } } return validate; } function all(propTypes) { if (propTypes === undefined) { throw new Error('No validations provided'); } if (!(propTypes instanceof Array)) { throw new Error('Invalid argument must be an array'); } if (propTypes.length === 0) { throw new Error('No validations provided'); } return function validate(props, propName, componentName) { for (let i = 0; i < propTypes.length; i++) { let result = propTypes[i](props, propName, componentName); if (result !== undefined && result !== null) { return result; } } }; } function createElementTypeChecker() { function validate(props, propName, componentName) { let errBeginning = errMsg(props, propName, componentName, '. Expected an Element `type`'); if (typeof props[propName] !== 'function') { if (React.isValidElement(props[propName])) { return new Error(errBeginning + ', not an actual Element'); } if (typeof props[propName] !== 'string') { return new Error(errBeginning + ' such as a tag name or return value of React.createClass(...)'); } } } return createChainableTypeChecker(validate); } export default { deprecated(propType, explanation) { return function validate(props, propName, componentName) { if (props[propName] != null) { warning(false, `"${propName}" property of "${componentName}" has been deprecated.\n${explanation}`); } return propType(props, propName, componentName); }; }, isRequiredForA11y(propType) { return function validate(props, propName, componentName) { if (props[propName] == null) { return new Error( 'The prop `' + propName + '` is required to make ' + componentName + ' accessible ' + 'for users using assistive technologies such as screen readers `' ); } return propType(props, propName, componentName); }; }, requiredRoles(...roles) { return createChainableTypeChecker( function requiredRolesValidator(props, propName, component) { let missing; let children = childrenToArray(props.children); let inRole = (role, child) => role === child.props.bsRole; roles.every(role => { if (!children.some(child => inRole(role, child))) { missing = role; return false; } return true; }); if (missing) { return new Error(`(children) ${component} - Missing a required child with bsRole: ${missing}. ` + `${component} must have at least one child of each of the following bsRoles: ${roles.join(', ')}`); } }); }, exclusiveRoles(...roles) { return createChainableTypeChecker( function exclusiveRolesValidator(props, propName, component) { let children = childrenToArray(props.children); let duplicate; roles.every(role => { let childrenWithRole = children.filter(child => child.props.bsRole === role); if (childrenWithRole.length > 1) { duplicate = role; return false; } return true; }); if (duplicate) { return new Error( `(children) ${component} - Duplicate children detected of bsRole: ${duplicate}. ` + `Only one child each allowed with the following bsRoles: ${roles.join(', ')}`); } }); }, /** * Checks whether a prop provides a DOM element * * The element can be provided in two forms: * - Directly passed * - Or passed an object that has a `render` method * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ mountable: createMountableChecker(), /** * Checks whether a prop provides a type of element. * * The type of element can be provided in two forms: * - tag name (string) * - a return value of React.createClass(...) * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ elementType: createElementTypeChecker(), /** * Checks whether a prop matches a key of an associated object * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ keyOf: createKeyOfChecker, /** * Checks if only one of the listed properties is in use. An error is given * if multiple have a value * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ singlePropFrom: createSinglePropFromChecker, all };
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js
ryardley/react-router
import React from 'react'; import { Link } from 'react-router'; class Sidebar extends React.Component { render () { var assignments = COURSES[this.props.params.courseId].assignments return ( <div> <h3>Sidebar Assignments</h3> <ul> {assignments.map(assignment => ( <li key={assignment.id}> <Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}> {assignment.title} </Link> </li> ))} </ul> </div> ); } } export default Sidebar;
public/js/components/activityfeed/CountBox.react.js
TRomesh/Coupley
import React from 'react'; import Card from 'material-ui/lib/card/card'; import FlatButton from 'material-ui/lib/flat-button'; import Paper from 'material-ui/lib/paper'; import Dialog from 'material-ui/lib/dialog'; import ListItem from 'material-ui/lib/lists/list-item'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; import Colors from 'material-ui/lib/styles/colors'; import RaisedButton from 'material-ui/lib/raised-button'; import ActivityfeedAction from '../../actions/ActivityFeed/ActivityfeedAction'; import LikeStatusStore from '../../stores/LikeStatusStore'; import StatusStore from '../../stores/StatusStore'; const style2 = { width: 800, }; var firstname; var sfirstname; var username; var susername; const CountBox = React.createClass({ getInitialState: function () { return { likedUsers: LikeStatusStore.getLikedUsers(), sharedUsers: StatusStore.getSharedUsers(), open: false, firstname: '', sfirstname: '', username: '', susername: '', }; }, componentDidMount: function () { LikeStatusStore.addChangeListener(this._onChange); let likeData = { postId: this.props.post_id, }; ActivityfeedAction.getLikedUsers(likeData); let shareData = { postId: this.props.post_id, }; ActivityfeedAction.getSharedUsers(shareData); }, _onChange: function () { this.setState({likedUsers: LikeStatusStore.getLikedUsers()}); this.setState({sharedUsers: StatusStore.getSharedUsers()}); }, handleClose: function () { this.setState({open: false}); this.setState({open2: false}); }, _getLikedUsers: function () { this.setState({open: true}); let self = this; return (this.state.likedUsers.map(function(likes) { return (likes.map(function(result) { if(self.props.post_id == result.post_id) { firstname=result.firstname; username=result.username; self.setState({ firstname: firstname, username: username }); } })); })); }, _getSharedUsers: function () { this.setState({open2: true}); this.setState({sharedUsers: StatusStore.getSharedUsers()}); let self = this; return (this.state.sharedUsers.map(function(shares) { return (shares.map(function(result) { if(self.props.post_id == result.post_id) { firstname=result.firstname; username=result.username; self.setState({ sfirstname: firstname, susername: username }); } })); })); }, _loadMoreComments: function () { let commentData = { postId: this.props.ckey, }; ActivityfeedAction.loadMoreComment(commentData); }, render: function () { const likeActions = [ <FlatButton label="Close" secondary={true} onTouchTap={this.handleClose}/>, ]; const sharedActions = [ <FlatButton label="Close" secondary={true} onTouchTap={this.handleClose}/>, ]; return ( <div> <div> { (this.props.likedCount) ? <div> <Card style={style2}> <FlatButton label={this.props.likedCount + " Likes"} onClick={this._getLikedUsers}/> </Card> </div> : '' } </div> <div> { (this.props.shareCount) ? <div> <Card style={style2}> <FlatButton label={this.props.shareCount + " Shares"} onClick={this._getSharedUsers}/> </Card> </div> : '' } </div> <div> { (this.props.cCount > 2) ? <div> <Card style={style2}> <FlatButton label="load more comments" onClick={this._loadMoreComments} /> </Card> </div> : '' } </div> <Dialog autoDetectWindowHeight={false} title="Liked Users" actions={likeActions} modal={true} open={this.state.open}> <ListItem leftAvatar={<Avatar src={'img/profilepics/'+ this.state.username}/>} primaryText={this.state.firstname} /> <Divider inset={true} /> </Dialog> <Dialog autoDetectWindowHeight={false} title="Shared Users" actions={sharedActions} modal={true} open={this.state.open2}> <ListItem leftAvatar={<Avatar src={'img/profilepics/'+ this.state.susername} />} primaryText={this.state.sfirstname} /> <Divider inset={true} /> </Dialog> </div> ); } }); export default CountBox;
src/Parser/Paladin/Retribution/Modules/PaladinCore/Crusade.js
hasseboulen/WoWAnalyzer
import React from 'react'; import Wrapper from 'common/Wrapper'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatNumber } from 'common/format'; import Combatants from 'Parser/Core/Modules/Combatants'; import Analyzer from 'Parser/Core/Analyzer'; import AbilityTracker from 'Parser/Core/Modules/AbilityTracker'; const CAST_BUFFER = 500; class Crusade extends Analyzer { static dependencies = { combatants: Combatants, abilityTracker: AbilityTracker, }; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.CRUSADE_TALENT.id); } crusadeCastTimestamp = 0; badFirstGlobal = 0; on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.CRUSADE_TALENT.id) { return; } this.crusadeCastTimestamp = event.timestamp; } on_byPlayer_applybuffstack(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.CRUSADE_TALENT.id) { return; } if(this.crusadeCastTimestamp && event.timestamp > this.crusadeCastTimestamp + CAST_BUFFER) { this.badFirstGlobal++; } this.crusadeCastTimestamp = null; } get badGlobalPercent() { return this.badFirstGlobal / this.abilityTracker.getAbility(SPELLS.CRUSADE_TALENT.id).casts; } get suggestionThresholds() { return { actual: 1 - this.badGlobalPercent, isLessThan: { minor: 1, average: 0.75, major: 0.5, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual) => { return suggest(<Wrapper>You want to build stacks of <SpellLink id={SPELLS.CRUSADE_TALENT.id} icon/> as quickly as possible. Make sure you are using <SpellLink id={SPELLS.TEMPLARS_VERDICT.id} icon/> or <SpellLink id={SPELLS.DIVINE_STORM.id} icon/> almost instantly after casting <SpellLink id={SPELLS.CRUSADE_TALENT.id} icon/>.</Wrapper>) .icon(SPELLS.CRUSADE_TALENT.icon) .actual(`${formatNumber(this.badFirstGlobal)} bad first global(s)`) .recommended(`0 is recommended`); }); } } export default Crusade;
jenkins-design-language/src/js/components/material-ui/svg-icons/editor/vertical-align-center.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const EditorVerticalAlignCenter = (props) => ( <SvgIcon {...props}> <path d="M8 19h3v4h2v-4h3l-4-4-4 4zm8-14h-3V1h-2v4H8l4 4 4-4zM4 11v2h16v-2H4z"/> </SvgIcon> ); EditorVerticalAlignCenter.displayName = 'EditorVerticalAlignCenter'; EditorVerticalAlignCenter.muiName = 'SvgIcon'; export default EditorVerticalAlignCenter;
actor-apps/app-web/src/app/components/sidebar/HeaderSection.react.js
liqk2014/actor-platform
import _ from 'lodash'; import React from 'react'; import mixpanel from 'utils/Mixpanel'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import MyProfileActions from 'actions/MyProfileActions'; import LoginActionCreators from 'actions/LoginActionCreators'; import HelpActionCreators from 'actions/HelpActionCreators'; import AddContactActionCreators from 'actions/AddContactActionCreators'; import AvatarItem from 'components/common/AvatarItem.react'; import MyProfileModal from 'components/modals/MyProfile.react'; import ActorClient from 'utils/ActorClient'; import AddContactModal from 'components/modals/AddContact.react'; import PreferencesModal from '../modals/Preferences.react'; import PreferencesActionCreators from 'actions/PreferencesActionCreators'; var getStateFromStores = () => { return { dialogInfo: null }; }; @ReactMixin.decorate(IntlMixin) class HeaderSection extends React.Component { constructor(props) { super(props); this.state = _.assign({ isOpened: false }, getStateFromStores()); } componentDidMount() { ActorClient.bindUser(ActorClient.getUid(), this.setUser); } componentWillUnmount() { ActorClient.unbindUser(ActorClient.getUid(), this.setUser); } setUser = (user) => { this.setState({user: user}); }; setLogout = () => { LoginActionCreators.setLoggedOut(); }; openMyProfile = () => { MyProfileActions.modalOpen(); mixpanel.track('My profile open'); }; openHelpDialog = () => { HelpActionCreators.open(); mixpanel.track('Click on HELP'); }; openAddContactModal = () => { AddContactActionCreators.openModal(); }; onSettingsOpen = () => { PreferencesActionCreators.show(); }; toggleHeaderMenu = () => { const isOpened = this.state.isOpened; if (!isOpened) { this.setState({isOpened: true}); mixpanel.track('Open sidebar menu'); document.addEventListener('click', this.closeHeaderMenu, false); } else { this.closeHeaderMenu(); } }; closeHeaderMenu = () => { this.setState({isOpened: false}); document.removeEventListener('click', this.closeHeaderMenu, false); }; render() { const user = this.state.user; if (user) { let headerClass = classNames('sidebar__header', 'sidebar__header--clickable', { 'sidebar__header--opened': this.state.isOpened }); let menuClass = classNames('dropdown', { 'dropdown--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="tiny" title={user.name} /> <span className="sidebar__header__user__name col-xs">{user.name}</span> <div className={menuClass}> <span className="dropdown__button"> <i className="material-icons">arrow_drop_down</i> </span> <ul className="dropdown__menu dropdown__menu--right"> <li className="dropdown__menu__item hide"> <i className="material-icons">photo_camera</i> <FormattedMessage message={this.getIntlMessage('setProfilePhoto')}/> </li> <li className="dropdown__menu__item" onClick={this.openMyProfile}> <i className="material-icons">edit</i> <FormattedMessage message={this.getIntlMessage('editProfile')}/> </li> <li className="dropdown__menu__item" onClick={this.openAddContactModal}> <i className="material-icons">person_add</i> Add contact </li> <li className="dropdown__menu__separator"></li> <li className="dropdown__menu__item hide"> <svg className="icon icon--dropdown" dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#integration"/>'}}/> <FormattedMessage message={this.getIntlMessage('configureIntegrations')}/> </li> <li className="dropdown__menu__item" onClick={this.openHelpDialog}> <i className="material-icons">help</i> <FormattedMessage message={this.getIntlMessage('helpAndFeedback')}/> </li> <li className="dropdown__menu__item hide" onClick={this.onSettingsOpen}> <i className="material-icons">settings</i> <FormattedMessage message={this.getIntlMessage('preferences')}/> </li> <li className="dropdown__menu__item dropdown__menu__item--light" onClick={this.setLogout}> <FormattedMessage message={this.getIntlMessage('signOut')}/> </li> </ul> </div> </div> <MyProfileModal/> <AddContactModal/> <PreferencesModal/> </header> ); } else { return null; } } } export default HeaderSection;
src/mui/input/NullableBooleanInput.js
azureReact/AzureReact
import React from 'react'; import PropTypes from 'prop-types'; import SelectInput from './SelectInput'; import translate from '../../i18n/translate'; export const NullableBooleanInput = ({ input, meta, label, source, elStyle, resource, translate, }) => ( <SelectInput input={input} label={label} source={source} resource={resource} choices={[ { id: null, name: '' }, { id: false, name: translate('aor.boolean.false') }, { id: true, name: translate('aor.boolean.true') }, ]} meta={meta} style={elStyle} /> ); NullableBooleanInput.propTypes = { addField: PropTypes.bool.isRequired, elStyle: PropTypes.object, input: PropTypes.object, label: PropTypes.string, meta: PropTypes.object, resource: PropTypes.string, source: PropTypes.string, }; NullableBooleanInput.defaultProps = { addField: true, }; export default translate(NullableBooleanInput);
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js
ProjectSunday/rooibus
import React from 'react'; const First = React.createNotClass({ displayName: 'First' }); class Second extends React.NotComponent {}
src/index.js
juazugas/MonoThor
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
docs/src/app/components/pages/components/SelectField/ExampleCustomLabel.js
rhaedes/material-ui
import React from 'react'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; export default class SelectFieldExampleCustomLabel extends React.Component { constructor(props) { super(props); this.state = {value: 1}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <SelectField value={this.state.value} onChange={this.handleChange}> <MenuItem value={1} label="5 am - 12 pm" primaryText="Morning" /> <MenuItem value={2} label="12 pm - 5 pm" primaryText="Afternoon" /> <MenuItem value={3} label="5 pm - 9 pm" primaryText="Evening" /> <MenuItem value={4} label="9 pm - 5 am" primaryText="Night" /> </SelectField> ); } }
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SvgInCss.js
mangomint/create-react-app
import React from 'react'; import './assets/svg.css'; export default () => <div id="feature-svg-in-css" />;
src/main/resources/public/js/components/update-title.js
SICTIAM/ozwillo-portal
import React from 'react'; import PropTypes from 'prop-types'; class UpdateTitle extends React.Component { static propTypes = { title: PropTypes.string }; componentDidMount() { // First render document.title = this.props.title; } componentWillReceiveProps(nextProps) { // Other renders document.title = nextProps.title; } render() { return null; } } export default UpdateTitle;
client/src/components/Hero.js
fmoliveira/rexql-boilerplate
import React from 'react' import { FormatMessage } from 'react-easy-intl' export default ({title, children, size}) => { const customSize = size ? `is-${size}` : null return ( <section className={`hero is-primary ${customSize} is-bold`}> <div className='hero-body'> <div className='container'> <h1 className='title'> <FormatMessage>{title}</FormatMessage> </h1> {children && <h2 className='subtitle'> <FormatMessage>{children}</FormatMessage> </h2>} </div> </div> </section> ) }
packages/web/src/components/range/DynamicRangeSlider.js
appbaseio/reactivesearch
/** @jsx jsx */ import { jsx } from '@emotion/core'; import React, { Component } from 'react'; import { addComponent, removeComponent, watchComponent, updateQuery, setQueryOptions, setQueryListener, setComponentProps, setCustomQuery, updateComponentProps, mockDataForTesting, } from '@appbaseio/reactivecore/lib/actions'; import hoistNonReactStatics from 'hoist-non-react-statics'; import { isEqual, checkValueChange, checkPropChange, checkSomePropChange, getClassName, pushToAndClause, updateCustomQuery, getOptionsFromQuery, isValidDateRangeQueryFormat, queryFormatMillisecondsMap, getCalendarIntervalErrorMessage, } from '@appbaseio/reactivecore/lib/utils/helper'; import types from '@appbaseio/reactivecore/lib/utils/types'; import Rheostat from 'rheostat/lib/Slider'; import { componentTypes } from '@appbaseio/reactivecore/lib/utils/constants'; import dateFormats from '@appbaseio/reactivecore/lib/utils/dateFormats'; import { oneOf } from 'prop-types'; import HistogramContainer from './addons/HistogramContainer'; import RangeLabel from './addons/RangeLabel'; import SliderHandle from './addons/SliderHandle'; import Slider from '../../styles/Slider'; import Title from '../../styles/Title'; import { rangeLabelsContainer } from '../../styles/Label'; import { connect, formatDateString, getNumericRangeArray, getRangeQueryWithNullValues, getValidPropsKeys, } from '../../utils'; // the formatRange() function formats the range value received from props // when dealing with dates we are always storing // milliseconds value in the local state const formatRange = (range = {}, props = {}) => { const rangeArray = getNumericRangeArray(range, props.queryFormat); return { start: rangeArray[0], end: rangeArray[1], }; }; class DynamicRangeSlider extends Component { constructor(props) { super(props); const { queryFormat } = props; if (queryFormat) { if (!isValidDateRangeQueryFormat(queryFormat)) { throw new Error('queryFormat is not supported. Try with a valid queryFormat.'); } } this.state = { currentValue: null, range: null, stats: [], }; // Caution: Don't change the ids unnecessarily. // If it's required then you need to update it in reactivecore(transform.js) too. this.internalHistogramComponent = `${this.props.componentId}__histogram__internal`; this.internalRangeComponent = `${this.props.componentId}__range__internal`; this.internalMatchAllComponent = `${this.props.componentId}__match_all__internal`; props.addComponent(props.componentId); props.addComponent(this.internalHistogramComponent); props.addComponent(this.internalRangeComponent); props.setQueryListener(props.componentId, props.onQueryChange, null); // Update props in store props.setComponentProps(props.componentId, props, componentTypes.dynamicRangeSlider); props.setComponentProps( this.internalHistogramComponent, props, componentTypes.dynamicRangeSlider, ); props.setComponentProps( this.internalRangeComponent, props, componentTypes.dynamicRangeSlider, ); // Set custom query in store updateCustomQuery(props.componentId, props, this.state.currentValue); if (props.mockData) { props.setTestData( this.internalRangeComponent, props.mockData[this.internalRangeComponent], ); props.setTestData(props.componentId, props.mockData[props.componentId]); } else { // get range before executing other queries this.updateRangeQueryOptions(props); } } static getDerivedStateFromProps(props, state) { // Update the current value based on range to avoid the unnecessary API calls if (!state.currentValue && props.range) { const range = formatRange(props.range, props); if (props.selectedValue) { // selected value must be in limit // we are using getNumericRangeArray() util method to get a numeric range array // since the value from redux store can be a string // as we have started using dateFormats const selectedValueNumericArray = getNumericRangeArray({ start: props.selectedValue[0], end: props.selectedValue[1], }); if ( selectedValueNumericArray[0] >= range.start && selectedValueNumericArray[1] <= range.end ) { return { currentValue: null, }; } return { currentValue: [range.start, range.end], }; } else if (!isEqual(state.currentValue, [range.start, range.end])) { // Just set the value for visibility don't apply as query or filter return { currentValue: [range.start, range.end], }; } } return null; } componentDidUpdate(prevProps) { checkSomePropChange(this.props, prevProps, getValidPropsKeys(this.props), () => { this.props.updateComponentProps( this.props.componentId, { ...this.props, ...(this.props.range && !this.props.calendarInterval && this.props.queryFormat ? { calendarInterval: getCalendarIntervalErrorMessage( formatRange(this.props.range, this.props).end - formatRange(this.props.range, this.props).start, ).calculatedCalendarInterval, } : {}), }, componentTypes.dynamicRangeSlider, ); this.props.updateComponentProps( this.internalHistogramComponent, this.props, componentTypes.dynamicRangeSlider, ); this.props.updateComponentProps( this.internalRangeComponent, this.props, componentTypes.dynamicRangeSlider, ); }); if (!isEqual(this.props.range, prevProps.range) && this.props.range) { // when range prop is changed // it will happen due to initial mount (or) due to subscription this.updateQueryOptions(this.props, this.props.range); // floor and ceil to take edge cases into account this.updateRange(formatRange(this.props.range, this.props)); // only listen to selectedValue initially, after the // component has mounted and range is received if (this.props.selectedValue) { this.handleChange(this.props.selectedValue); } else { this.handleChange(); } } else if ( this.props.range && !isEqual( this.props.value && this.props.value(this.props.range.start, this.props.range.end), prevProps.value && prevProps.value(this.props.range.start, this.props.range.end), ) ) { // when value prop is changed const { start, end } = this.props.value(this.props.range.start, this.props.range.end); this.handleChange([start, end]); } else if ( this.props.range && this.props.selectedValue === null && prevProps.selectedValue ) { // when the filter is reset this.handleChange(); } checkPropChange(this.props.react, prevProps.react, () => { this.updateRangeQueryOptions(this.props); this.setReact(this.props); }); checkSomePropChange(this.props, prevProps, ['dataField', 'nestedField'], () => { this.updateRangeQueryOptions(this.props); }); checkSomePropChange( this.props, prevProps, ['showHistogram', 'interval', 'calendarInterval'], () => this.updateQueryOptions(this.props, this.props.range || this.state.range), ); checkPropChange(this.props.options, prevProps.options, () => { const { options } = this.props; options.sort((a, b) => { if (a.key < b.key) return -1; if (a.key > b.key) return 1; return 0; }); this.setState({ stats: options, }); }); } componentDidMount() { const { enableAppbase, index, mode } = this.props; if (!enableAppbase && index) { console.warn( 'Warning(ReactiveSearch): In order to use the `index` prop, the `enableAppbase` prop must be set to true in `ReactiveBase`.', ); } if (mode !== 'test') { this.setReact(this.props); } } shouldComponentUpdate(nextProps, nextState) { if (nextState.range) { const upperLimit = Math.floor((nextState.range.end - nextState.range.start) / 2); if (nextProps.stepValue < 1 || nextProps.stepValue > upperLimit) { console.warn( `stepValue for DynamicRangeSlider ${nextProps.componentId} should be greater than 0 and less than or equal to ${upperLimit}`, ); return false; } // when testing with playround, the queryformat knob changed the queryFormat prop // which changed the value incase of date types but the local state didn't update // this block of code takes care of updating the local value with optimized rerendering checkSomePropChange(nextProps, this.props, ['queryFormat'], () => { this.setState({ currentValue: [ formatRange(nextProps.range, nextProps).start, formatRange(nextProps.range, nextProps).end, ], range: formatRange(nextProps.range, nextProps), }); this.updateRangeQueryOptions(nextProps); // stopping the rerender since setState call above would rerender anyway. return false; }); return true; } return true; } componentWillUnmount() { this.props.removeComponent(this.props.componentId); this.props.removeComponent(this.internalHistogramComponent); this.props.removeComponent(this.internalRangeComponent); this.props.removeComponent(this.internalMatchAllComponent); } setReact = (props) => { const { react } = props; if (react) { props.watchComponent(this.internalRangeComponent, props.react); const newReact = pushToAndClause(react, this.internalHistogramComponent); props.watchComponent(props.componentId, newReact); } else { // internalRangeComponent watches internalMatchAll component allowing execution of query // in case of no react prop this.props.addComponent(this.internalMatchAllComponent); props.setQueryOptions( this.internalMatchAllComponent, { aggs: { match_all: {} } }, false, ); props.watchComponent(this.internalRangeComponent, { and: this.internalMatchAllComponent, }); props.watchComponent(props.componentId, { and: this.internalHistogramComponent, }); } }; // value parser for SSR static parseValue = (value, props) => { if (Array.isArray(value)) return value; return value ? getNumericRangeArray({ start: value().start, end: value().end }, props.queryFormat) : null; }; static defaultQuery = (value, props) => { let query = null; if (Array.isArray(value) && value.length) { query = getRangeQueryWithNullValues(value, props); } if (query && props.nestedField) { return { nested: { path: props.nestedField, query, }, }; } return query; }; getSnapPoints = () => { let snapPoints = []; let { stepValue } = this.props; const { range } = this.state; // limit the number of steps to prevent generating a large number of snapPoints if ((range.end - range.start) / stepValue > 100) { stepValue = (range.end - range.start) / 100; } for (let i = range.start; i <= range.end; i += stepValue) { snapPoints = snapPoints.concat(i); } if (snapPoints[snapPoints.length - 1] !== range.end) { snapPoints = snapPoints.concat(range.end); } return snapPoints; }; getValidInterval = (props, range) => { if (isValidDateRangeQueryFormat(props.queryFormat)) { const calendarInterval = props.calendarInterval || getCalendarIntervalErrorMessage(range.end - range.start).calculatedCalendarInterval; const numberOfIntervals = Math.ceil( (range.end - range.start) / queryFormatMillisecondsMap[calendarInterval], ); if (numberOfIntervals > 100) { console.error( `${props.componentId}: ${ getCalendarIntervalErrorMessage(range.end - range.start, calendarInterval) .errorMessage }`, ); } return queryFormatMillisecondsMap[calendarInterval]; } const min = Math.ceil((range.end - range.start) / 100) || 1; if (!props.interval) { return min; } else if (props.interval < min) { console.error( `${props.componentId}: interval prop's value should be greater than or equal to ${min}`, ); return min; } return props.interval; }; histogramQuery = (props, range) => { const query = { [props.dataField]: { histogram: { field: props.dataField, interval: this.getValidInterval(props, range), offset: range.start, }, }, }; if (props.nestedField) { return { inner: { aggs: query, nested: { path: props.nestedField, }, }, }; } return query; }; rangeQuery = props => ({ min: { min: { field: props.dataField } }, max: { max: { field: props.dataField } }, }); handleChange = (currentValue, props = this.props) => { let normalizedValue = null; if (currentValue) { const [start, end] = currentValue; // converting the received value params to numeric equivalent // incase of date type, we convert them to milliseconds value always const [processedStart, processedEnd] = getNumericRangeArray( { start, end }, props.queryFormat, ); // always keep the values within range // props.range.start / (props.queryFormat !== dateFormats.epoch_second ? 1 : 1000) is required // since we need to convert the milliseconds value into seconds in case of epoch_second normalizedValue = [ processedStart < props.range.start ? props.range.start : processedStart, processedEnd > props.range.end ? props.range.end : processedEnd, ]; if (props.range.start === null) { normalizedValue = [processedStart, processedEnd]; } } // isValidDateRangeQueryFormat(props.queryFormat) // checks if date type is used // props.queryFormat !== dateFormats.epoch_second // to avoid further division by 1000 // getRangeValueString(normalizedValue[0], props) // we store this string in redux store for representational purpose // normalizedValue[0], // default behaviour for numerics and dateFormats.epoch_second const normalizedValues = normalizedValue ? [ isValidDateRangeQueryFormat(props.queryFormat) ? formatDateString(normalizedValue[0]) : normalizedValue[0], isValidDateRangeQueryFormat(props.queryFormat) ? formatDateString(normalizedValue[1]) : normalizedValue[1], ] : null; const performUpdate = () => { this.setState( { currentValue: normalizedValue, }, () => { // Only update the queries for dependent components when range is changed by input this.updateQuery(normalizedValues, props); if (props.onValueChange) props.onValueChange(normalizedValues); }, ); }; checkValueChange( props.componentId, normalizedValues, props.beforeValueChange, performUpdate, ); }; handleSlider = ({ values }) => { if (!isEqual(values, this.state.currentValue)) { const { value, onChange } = this.props; if (value === undefined) { this.handleChange(values); } else if (onChange) { onChange(values); } else { this.handleChange(values); } } }; handleDrag = (values) => { if (this.props.onDrag) { const { min, max, values: currentValue } = values; this.props.onDrag(currentValue, [min, max]); } }; updateQuery = (value, props) => { const { customQuery } = props; let query = DynamicRangeSlider.defaultQuery(value, props); let customQueryOptions; if (customQuery) { ({ query } = customQuery(value, props) || {}); customQueryOptions = getOptionsFromQuery(customQuery(value, props)); updateCustomQuery(props.componentId, props, value); } const { showFilter } = props; props.setQueryOptions(props.componentId, customQueryOptions); props.updateQuery({ componentId: props.componentId, query, value, label: props.filterLabel, showFilter, URLParams: props.URLParams, componentType: componentTypes.dynamicRangeSlider, }); }; updateQueryOptions = (props, range) => { if (props.showHistogram) { const queryOptions = { aggs: this.histogramQuery(props, range), }; const { customQuery } = props; const query = props.customQuery || DynamicRangeSlider.defaultQuery; const value = [range.start, range.end]; const customQueryOptions = customQuery ? getOptionsFromQuery(customQuery(value, props)) : null; props.setQueryOptions( this.internalHistogramComponent, { ...queryOptions, ...customQueryOptions }, false, ); props.updateQuery({ componentId: this.internalHistogramComponent, query: query(value, props), value, }); } }; updateRange = (range) => { this.setState({ range, }); }; updateRangeQueryOptions = (props) => { let queryOptions = {}; const { nestedField } = props; if (nestedField) { queryOptions = { aggs: { [nestedField]: { nested: { path: nestedField, }, aggs: this.rangeQuery(props), }, }, }; } else { queryOptions = { aggs: this.rangeQuery(props), }; } props.setQueryOptions(this.internalRangeComponent, queryOptions); }; getRangeLabels = () => { let { start: startLabel, end: endLabel } = this.state.range; if (this.props.rangeLabels) { const rangeLabels = this.props.rangeLabels( this.props.range.start, this.props.range.end, ); startLabel = rangeLabels.start; endLabel = rangeLabels.end; return { startLabel, endLabel, }; } return { // formatDateString gives value as string in the format 'yyyy-MM-dd' startLabel: isValidDateRangeQueryFormat(this.props.queryFormat) ? formatDateString(startLabel) : startLabel, endLabel: isValidDateRangeQueryFormat(this.props.queryFormat) ? formatDateString(endLabel) : endLabel, }; }; renderHistogram() { if (this.props.isLoading && this.props.loader) { return this.props.loader; } if (this.state.stats.length && this.props.showHistogram) { const rangeValue = this.state.range; return ( <HistogramContainer stats={this.state.stats} range={rangeValue} interval={this.getValidInterval(this.props, rangeValue)} /> ); } return null; } render() { if (!this.state.currentValue || !this.state.range || this.props.range.start === null) { return null; } const { startLabel, endLabel } = this.getRangeLabels(); return ( <Slider primary style={this.props.style} className={this.props.className}> {this.props.title && ( <Title className={getClassName(this.props.innerClass, 'title') || null}> {this.props.title} </Title> )} {this.renderHistogram()} <Rheostat min={this.state.range.start} max={this.state.range.end} values={this.state.currentValue} onChange={this.handleSlider} onValuesUpdated={this.handleDrag} snap={this.props.snap} snapPoints={this.props.snap ? this.getSnapPoints() : null} className={getClassName(this.props.innerClass, 'slider')} handle={({ className, style, ...passProps }) => ( <SliderHandle style={style} className={className} {...passProps} renderTooltipData={this.props.renderTooltipData} tooltipTrigger={this.props.tooltipTrigger} /> )} /> <div css={rangeLabelsContainer}> <RangeLabel align="left" className={getClassName(this.props.innerClass, 'label') || null} > {startLabel} </RangeLabel> <RangeLabel align="right" className={getClassName(this.props.innerClass, 'label') || null} > {endLabel} </RangeLabel> </div> </Slider> ); } } DynamicRangeSlider.propTypes = { addComponent: types.funcRequired, removeComponent: types.funcRequired, setQueryListener: types.funcRequired, setQueryOptions: types.funcRequired, updateQuery: types.funcRequired, watchComponent: types.funcRequired, options: types.options, range: types.range, selectedValue: types.selectedValue, setComponentProps: types.funcRequired, updateComponentProps: types.funcRequired, isLoading: types.bool, setCustomQuery: types.funcRequired, enableAppbase: types.bool, setTestData: types.funcRequired, // component props beforeValueChange: types.func, className: types.string, componentId: types.stringRequired, customQuery: types.func, dataField: types.stringRequired, defaultValue: types.func, value: types.func, filterLabel: types.string, innerClass: types.style, interval: types.number, loader: types.title, nestedField: types.string, onDrag: types.func, onQueryChange: types.func, onValueChange: types.func, onChange: types.func, rangeLabels: types.func, react: types.react, showHistogram: types.bool, showFilter: types.bool, tooltipTrigger: types.tooltipTrigger, renderTooltipData: types.func, snap: types.bool, stepValue: types.number, style: types.style, title: types.title, URLParams: types.bool, includeNullValues: types.bool, index: types.string, queryFormat: oneOf([...Object.keys(dateFormats)]), calendarInterval: types.calendarInterval, mockData: types.any, // eslint-disable-line mode: types.string, }; DynamicRangeSlider.defaultProps = { className: null, showHistogram: true, tooltipTrigger: 'none', snap: true, stepValue: 1, style: {}, URLParams: false, showFilter: true, includeNullValues: false, }; // Add componentType for SSR DynamicRangeSlider.componentType = componentTypes.dynamicRangeSlider; const mapStateToProps = (state, props) => { let aggregation = state.aggregations[props.componentId]; if (props.nestedField) { aggregation = state.aggregations[props.componentId] && state.aggregations[props.componentId].inner; } let options = aggregation && aggregation[props.dataField]; let range = state.aggregations[`${props.componentId}__range__internal`]; if (props.nestedField) { options = options && aggregation[props.dataField] && aggregation[props.dataField].buckets ? aggregation[props.dataField].buckets : []; range = range && state.aggregations[`${props.componentId}__range__internal`][props.nestedField].min ? { start: state.aggregations[`${props.componentId}__range__internal`][props.nestedField].min.value, end: state.aggregations[`${props.componentId}__range__internal`][props.nestedField].max.value, } // prettier-ignore : null; } else { options = options && aggregation[props.dataField].buckets ? aggregation[props.dataField].buckets : []; range = range && state.aggregations[`${props.componentId}__range__internal`].min ? { start: state.aggregations[`${props.componentId}__range__internal`].min.value, end: state.aggregations[`${props.componentId}__range__internal`].max.value, } // prettier-ignore : null; } if (range) { range = formatRange(range); } return { options, isLoading: state.isLoading[props.componentId], range, selectedValue: state.selectedValues[props.componentId] ? state.selectedValues[props.componentId].value : null, enableAppbase: state.config.enableAppbase, }; }; const mapDispatchtoProps = dispatch => ({ setTestData: (component, data) => dispatch(mockDataForTesting(component, data)), setComponentProps: (component, options, componentType) => dispatch(setComponentProps(component, options, componentType)), setCustomQuery: (component, query) => dispatch(setCustomQuery(component, query)), updateComponentProps: (component, options, componentType) => dispatch(updateComponentProps(component, options, componentType)), addComponent: component => dispatch(addComponent(component)), removeComponent: component => dispatch(removeComponent(component)), setQueryOptions: (component, props, execute) => dispatch(setQueryOptions(component, props, execute)), setQueryListener: (component, onQueryChange, beforeQueryChange) => dispatch(setQueryListener(component, onQueryChange, beforeQueryChange)), updateQuery: (updateQueryObject, execute) => dispatch(updateQuery(updateQueryObject, execute)), watchComponent: (component, react) => dispatch(watchComponent(component, react)), }); const ConnectedComponent = connect( mapStateToProps, mapDispatchtoProps, )(props => <DynamicRangeSlider ref={props.myForwardedRef} {...props} />); // eslint-disable-next-line const ForwardRefComponent = React.forwardRef((props, ref) => ( <ConnectedComponent {...props} myForwardedRef={ref} /> )); hoistNonReactStatics(ForwardRefComponent, DynamicRangeSlider); ForwardRefComponent.displayName = 'DynamicRangeSlider'; export default ForwardRefComponent;
src/svg-icons/action/extension.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionExtension = (props) => ( <SvgIcon {...props}> <path d="M20.5 11H19V7c0-1.1-.9-2-2-2h-4V3.5C13 2.12 11.88 1 10.5 1S8 2.12 8 3.5V5H4c-1.1 0-1.99.9-1.99 2v3.8H3.5c1.49 0 2.7 1.21 2.7 2.7s-1.21 2.7-2.7 2.7H2V20c0 1.1.9 2 2 2h3.8v-1.5c0-1.49 1.21-2.7 2.7-2.7 1.49 0 2.7 1.21 2.7 2.7V22H17c1.1 0 2-.9 2-2v-4h1.5c1.38 0 2.5-1.12 2.5-2.5S21.88 11 20.5 11z"/> </SvgIcon> ); ActionExtension = pure(ActionExtension); ActionExtension.displayName = 'ActionExtension'; ActionExtension.muiName = 'SvgIcon'; export default ActionExtension;
components/animals/krkavecVelky.child.js
marxsk/zobro
import React, { Component } from 'react'; import { Text } from 'react-native'; import styles from '../../styles/styles'; import InPageImage from '../inPageImage'; import AnimalText from '../animalText'; import AnimalTemplate from '../animalTemplate'; const IMAGES = [ require('../../images/animals/krkavecVelky/01.jpg'), ]; const THUMBNAILS = [ require('../../images/animals/krkavecVelky/01-thumb.jpg'), ]; var AnimalDetail = React.createClass({ render() { return ( <AnimalTemplate firstIndex={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}> <AnimalText> Nazdar krasavci! </AnimalText> <AnimalText> Jistě jste zdatní přírodovědci, přesto vás musíme upozornit, že ne každý zná naše opravdové jméno. Takže aby bylo jasno – nejsme havrani, protože ti jsou oproti nám menší a v&nbsp;zimě je někdy potkáte ve městech. Nejsme ani vrány. Jsme krkavci. Brázdíme lesy i&nbsp;otevřená prostředí skoro celé severní polokoule, a tak se občas objevíme i&nbsp;v&nbsp;těch českých. </AnimalText> <AnimalText> Jeden takový hluboký hvozd obýval náš prapradědeček Krako. Už od malička se chtěl stát rytířem. Neohroženě se pral o&nbsp;každou kořist, zobákem naporcoval kdejakou mršinu a k&nbsp;tomu všemu byl vysoce inteligentní. Říká se, že dokonce uměl napočítat do osmi! </AnimalText> <AnimalText> Žádná z&nbsp;těchto schopností mu bohužel nezajistila to, po čem toužil nejvíc – správný rytíř musel patřit k&nbsp;nějakému řádu. Přijímací zkoušky se však vyhlašovaly jen do Řádu pěvců, kde na jeho krákání nebyl nikdo zvědav. Krako se rozhodl, že se do přijímaček prostě zpívat naučí. </AnimalText> <AnimalText> Sehnat v&nbsp;lese učitele nebylo jednoduché. Zvířata se krkavců bála, protože je často viděla na popravištích. Krako nechtěl nikoho vyděsit, a tak nakonec přestal hledat ptačího učitele a začal tajně poslouchat turisty. Člověčí hlas ho fascinoval. </AnimalText> <AnimalText> Zanedlouho přišel den přijímacích zkoušek. Krako stanul na větvi před odbornou porotou z&nbsp;Řádu pěvců a spustil: „Hele, hříbek! Pojďme doprava. Tady je krásně!“ Sice to bylo spíš mluvení než zpěv, ale porota byla ohromená. Ocenila Krakovu snahu a do Řádu pěvců ho přijala. </AnimalText> <AnimalText> Krako byl od té doby respektovaný rytíř. Odháněl turisty od zvířecích obydlí – vždycky se někam schoval, pronesl naučenou větu a lidé šli tam, kam je navedl. Za odměnu si mohl vystlat hnízdo jemným mechem a prvotřídním blátem, které zajistily pohodlí pro šest krkavčích ptáčat. </AnimalText> <AnimalText> Vědci od té doby říkají, že krkavci jsou dokonce největší ptáci patřící do řádu pěvců. Někteří se naučí napodobovat řeč nebo zpěv lidí víc, jiní se jen schovávají v&nbsp;přírodě, sedí na rameni čarodějnicím nebo radostně krákají v&nbsp;zoo. My krkavci z&nbsp;brněnské zoo jsme na svoje krákání pyšní. Když tu u&nbsp;nás chvilku počkáte, určitě vám svůj hlas předvedeme. </AnimalText> </AnimalTemplate> ); } }); module.exports = AnimalDetail;
docs/app/Examples/views/Card/Variations/CardExampleFluid.js
koenvg/Semantic-UI-React
import React from 'react' import { Card } from 'semantic-ui-react' const CardExampleFluid = () => ( <Card.Group> <Card fluid color='red' header='Option 1' /> <Card fluid color='orange' header='Option 2' /> <Card fluid color='yellow' header='Option 3' /> </Card.Group> ) export default CardExampleFluid
app/components/agent/Index/AgentTokenItem.js
fotinakis/buildkite-frontend
import React from 'react'; import PropTypes from 'prop-types'; import { createFragmentContainer, graphql } from 'react-relay/compat'; import Badge from '../../shared/Badge'; import Panel from '../../shared/Panel'; import RevealButton from '../../shared/RevealButton'; class AgentTokenItem extends React.PureComponent { static propTypes = { agentToken: PropTypes.shape({ id: PropTypes.string.isRequired, description: PropTypes.string.isRequired, public: PropTypes.bool.isRequired, token: PropTypes.string.isRequired }).isRequired, showDescription: PropTypes.bool }; render() { return ( <Panel.Row key={this.props.agentToken.id}> {this.renderDescription()} <RevealButton caption="Reveal Agent Token"> <code className="red monospace" style={{ wordWrap: "break-word" }}> {this.props.agentToken.token} </code> </RevealButton> </Panel.Row> ); } renderDescription() { if (this.props.showDescription) { return ( <small className="dark-gray mb1 block"> {this.props.agentToken.description} {this.renderPublicBadge()} </small> ); } } renderPublicBadge() { if (this.props.agentToken.public) { return ( <Badge outline={true} className="regular" title="Agents registered with this token will be visible to everyone, including people outside this organization">Public</Badge> ); } } } export default createFragmentContainer(AgentTokenItem, { agentToken: graphql` fragment AgentTokenItem_agentToken on AgentToken { id description public token } ` });
src/__tests__/fixtures/flow-export-type.js
reactjs/react-docgen
/** * @flow */ import React, { Component } from 'react'; export type Props = { foo: string } /** * This is a Flow class component */ export default class FlowComponent extends Component<Props> { render() { return <h1>Hello world</h1>; } foo(a: string): string { return a; } bar(a: string): string { return a; } }
src/scenes/dashboard/newsfeed/index.js
PowerlineApp/powerline-rn
//Newsfeed tab GH13 //The backend call for this scene will be driven primarily by https://api-dev.powerli.ne/api-doc#get--api-v2-activities //The default view is "All" feed, but a specific group may be called for group Feed (GH45), Friends Feed (GH51), a specific user's feed (GH44) //Group feed will look very different depending on if in Feed view or Conversation view. import React, { Component } from 'react'; import KeyboardSpacer from 'react-native-keyboard-spacer'; import { connect } from 'react-redux'; import { Actions } from 'react-native-router-flux'; import { ActionSheet, Container, Header, Title, Content, Text, Button, Icon, Left, Right, Body, Item, Input, Grid, Row, Col, ListItem, Thumbnail, List, Card, CardItem, Label, Footer } from 'native-base'; import { ListView, View, RefreshControl, TouchableOpacity, Image, WebView, Platform, Share } from 'react-native'; import Carousel from 'react-native-snap-carousel'; import { loadActivities, resetActivities, votePost, editFollowers, loadActivityByEntityId, createPostToGroup, deletePost, deletePetition } from 'PLActions'; import styles, { sliderWidth, itemWidth } from './styles'; import TimeAgo from 'react-native-timeago'; import ImageLoad from 'react-native-image-placeholder'; import YouTube from 'react-native-youtube'; import Menu, { MenuContext, MenuTrigger, MenuOptions, MenuOption, renderers } from 'react-native-popup-menu'; import ConversationActivity from '../../../components/Conversation/ConversationActivity'; import FeedActivity from '../../../components/Feed/FeedActivity'; import ContentPlaceholder from '../../../components/ContentPlaceholder'; import PLOverlayLoader from 'PLOverlayLoader'; import PLLoader from 'PLLoader'; const PLColors = require('PLColors'); const { WINDOW_WIDTH, WINDOW_HEIGHT } = require('PLConstants'); const { youTubeAPIKey } = require('PLEnv'); import { Dimensions } from 'react-native'; const { width, height } = Dimensions.get('window'); class Newsfeed extends Component { static propTypes = { token: React.PropTypes.string, } constructor(props) { super(props); var ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2, }); this.state = { isRefreshing: false, isLoadingTail: false, isLoading: false, dataArray: [], dataSource: ds, text: "", showAvatar: true, lastOffset: 0 }; } componentWillMount() { this.props.dispatch(resetActivities()); this.loadInitialActivities(); } componentWillReceiveProps(nextProps) { this.setState({ dataArray: nextProps.payload, dataSource: this.state.dataSource.cloneWithRows(nextProps.payload), }); } //JC I'm unclear on what this actually is subscribe(item) { Share.share({ message: item.description, title: "" }); } async loadInitialActivities() { this.setState({ isRefreshing: true }); const { props: { token, dispatch, page, group } } = this; try { await Promise.race([ dispatch(loadActivities(token, 0, 20, group )), timeout(15000), ]); } catch (e) { const message = e.message || e; if (message !== 'Timed out') { alert(message); } else { alert('Timed out. Please check internet connection'); } return; } finally { this.setState({ isRefreshing: false }); } this.setState({ dataSource: this.state.dataSource.cloneWithRows(this.state.dataArray), }); } async loadNextActivities() { this.setState({ isLoadingTail: true }); const { props: { token, page, dispatch, group } } = this; try { await Promise.race([ dispatch(loadActivities(token, page, 20, group)), timeout(15000), ]); } catch (e) { const message = e.message || e; if (message !== 'Timed out') { alert(message); } else { alert('Timed out. Please check internet connection'); } return; } finally { this.setState({ isLoadingTail: false }); } this.setState({ dataSource: this.state.dataSource.cloneWithRows(this.state.dataArray), }); } _onRefresh() { this.props.dispatch(resetActivities()); this.loadInitialActivities(); } _onEndReached() { const { props: { page, count } } = this; if (this.state.isLoadingTail === false && count > 0) { this.loadNextActivities(); } } _onBeginReached() { this.props.dispatch(resetActivities()); this.loadInitialActivities(); } //Related: GH160 _renderTailLoading() { if (this.state.isLoadingTail === true) { return <PLLoader position="bottom" /> } else { return null; } } onChangeText(text){ this.setState({ text: text }); } onCreatePost(){ if (this.state.postingOnGroup){ return; } var { token, savedGroup, dispatch } = this.props; this.setState({postingOnGroup: true}) console.log(token, savedGroup, this.state.text) if(this.state.text != "" || this.state.text.trim() != ""){ createPostToGroup(token, savedGroup.group, this.state.text) .then(data => { this.setState({ text: "" }); dispatch({type: 'DELETE_ACTIVITIES'}); this.loadInitialActivities(); this.setState({postingOnGroup: false}) }) .catch(err => { this.setState({postingOnGroup: false}) }) } } render() { // test if we should show conversationFeed or ActivityFeed let conversationView = this.props.group != 'all' && this.props.payload.length <= this.props.groupLimit; let dataSouce = this.state.dataSource; if (dataSouce[0] && conversationView) { dataSouce = dataSouce.reverse(); } // this is hardcode for testing purposes -- I will remove once ConversationFeed is 100% working /Felipe conversationView = false; // console.log({token, savedGroup} = this.props) return ( // The default view of the newsfeed is the All feed. <Container style={styles.container}> { this.props.savedGroup && this.props.savedGroup.group != 'all' && <TouchableOpacity onPress={() => Actions.groupprofile({id: this.props.savedGroup.group})}> <View style={styles.groupHeaderContainer}> {this.state.showAvatar && this.props.savedGroup.groupAvatar != '' && this.props.savedGroup.groupAvatar != null ? <Thumbnail square source={{ uri: this.props.savedGroup.groupAvatar + '&w=200&h=200&auto=compress,format,q=95' }} style={styles.groupAvatar} /> : null} <Text style={styles.groupName}>{this.props.savedGroup.groupName}</Text> </View> </TouchableOpacity> } {this.state.isRefreshing && <PLLoader position="bottom" />} <ContentPlaceholder empty={!this.state.isRefreshing && !this.state.isLoading && this.state.dataArray.length === 0} title="The world belongs to those who speak up! Be the first to create a post!" refreshControl={ Platform.OS === 'android' && !conversationView && <RefreshControl refreshing={false} onRefresh={this._onRefresh.bind(this)} /> } onScroll={(e) => { var height = e.nativeEvent.contentSize.height; var offset = e.nativeEvent.contentOffset.y; if (offset > 30 && this.state.showAvatar){ this.setState({showAvatar : false}) } else if (offset < 20 && !this.state.showAvatar) { this.setState({showAvatar: true}) } console.log(offset, height) if (offset < -3) { if (conversationView){ console.log('_onEndReached') this._onEndReached(); } else { console.log('refresh') this._onRefresh(); } } if (offset > height + 3){ if (conversationView){ console.log('refresh') this._onRefresh(); } else { console.log('_onEndReached') this._onEndReached(); } } }} > <ListView dataSource={dataSouce} renderRow={item => { return (conversationView ? <ConversationActivity item={item} token={this.props.token} profile={this.props.profile} /> : <FeedActivity item={item} token={this.props.token} profile={this.props.profile} /> ) }} /> <PLOverlayLoader visible={this.state.isLoading} logo /> {this._renderTailLoading()} </ContentPlaceholder> { /** * if we are in conversation view, we have a textinput */ conversationView ? <Footer style={styles.CFooter}> <Item style={styles.CFooterItem}> <Thumbnail small source={{uri: this.props.profile.avatar_file_name+'&w=200&h=200&auto=compress,format,q=95'}}/> <Input style={styles.CFooterItemInput} value={this.state.text} onChangeText={(text) => !this.state.postingOnGroup ? this.onChangeText(text) : {}}/> <Button transparent style={styles.sendBtn} onPress={() => this.onCreatePost()}> <Text color={'#ccc'} >SEND</Text> <Icon name="md-send" color={'#ccc'}/> </Button> </Item> <KeyboardSpacer /> </Footer> : null } </Container> ); } } const optionsStyles = { optionsContainer: { backgroundColor: '#fafafa', paddingLeft: 5, width: WINDOW_WIDTH, }, }; async function timeout(ms: number): Promise { return new Promise((resolve, reject) => { setTimeout(() => reject(new Error('Timed out')), ms); }); } const mapStateToProps = state => ({ token: state.user.token, page: state.activities.page, totalItems: state.activities.totalItems, payload: state.activities.payload, count: state.activities.count, profile: state.user.profile, userId: state.user.id, group: state.activities.group, groupName: state.activities.groupName, groupAvatar: state.activities.groupAvatar, groupLimit: state.activities.groupLimit, savedGroup: state.activities.savedGroup, }); export default connect(mapStateToProps)(Newsfeed);
src/svg-icons/action/https.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHttps = (props) => ( <SvgIcon {...props}> <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/> </SvgIcon> ); ActionHttps = pure(ActionHttps); ActionHttps.displayName = 'ActionHttps'; ActionHttps.muiName = 'SvgIcon'; export default ActionHttps;
demo/index.js
Shikib/react-chat-reply-annotation
import React from 'react' import { render } from 'react-dom' import { Chat } from '../lib' console.log(Chat); render( React.createElement(Chat), document.getElementById('chat-ui') )
src/shared/Gist.js
kashisau/enroute
/** * Gist.js * * (C) 2017 mobile.de GmbH * * @author <a href="mailto:[email protected]">Patrick Hund</a> * @since 09 Feb 2017 */ import React from 'react'; export default ({ gist }) => ( <div> <h1>{gist.description || '[no description]'}</h1> <p><a href={gist.html_url}>view on GitHub</a></p> <p>Files:</p> <ul> { Object.keys(gist.files).map(key => ( <li key={key}> <a href={gist.files[key].raw_url}> {key} </a> </li> )) } </ul> </div> );
src/manager/UI/Toolbar.js
sm-react/react-theming
import React from 'react'; import * as styled from './Toolbar.styled'; const Toolbar = ({ children, footer }) => { return <styled.Container footer={footer}>{children}</styled.Container>; }; export default Toolbar;
docs/lib/NotFound/index.js
video-react/video-react
import React from 'react'; import { Button, Container, Row, Col } from 'reactstrap'; import { Link } from 'react-router'; import Helmet from 'react-helmet'; export default () => { return ( <div> <Helmet title="404 Page Not Found" /> <section className="jumbotron text-xs-center m-b-3"> <Container fluid> <Row> <Col> <p className="lead"> <img src="/assets/logo.png" alt="" width="150px" /> </p> <h1 className="jumbotron-heading display-4">404 - Not Found</h1> <p className="lead"> Can't find what you're looking for?{' '} <a href="https://github.com/video-react/video-react/issues/new"> Open </a>{' '} up an issue. </p> <p> <Button outline color="danger" className="m-r-1" tag={Link} to="/" > Get Started </Button> <Button color="danger" tag={Link} to="/components"> View Components </Button> </p> </Col> </Row> </Container> </section> </div> ); };
src/components/renderButton.js
Johj/cqdb
import React from 'react'; import { Button, Col, } from 'react-bootstrap'; import { countFilters, } from '../util/countFilters'; export function renderButton(handleButton, label, checkboxFilters = {}) { const numCheckboxFilters = countFilters(checkboxFilters); return ( <Col lg={4} md={6} sm={12} xs={12}> <Button block onClick={handleButton} style={{marginBottom: 5,}}> {label + (!numCheckboxFilters ? '' : ` (${numCheckboxFilters})`)} </Button> </Col> ); }
src/create-glamorous.js
paypal/glamorous
/* * This is a relatively small abstraction that's ripe for open sourcing. * Documentation is in the README.md */ import React from 'react' import {PropTypes} from './react-compat' import withTheme from './with-theme' import getGlamorClassName from './get-glamor-classname' export default createGlamorous function createGlamorous(splitProps) { return glamorous /** * This is the main export and the function that people * interact with most directly. * * It accepts a component which can be a string or * a React Component and returns * a "glamorousComponentFactory" * @param {String|ReactComponent} comp the component to render * @param {Object} options helpful info for the GlamorousComponents * @return {Function} the glamorousComponentFactory */ function glamorous(comp, config = {}) { const { rootEl, displayName, shouldClassNameUpdate, filterProps = [], forwardProps = [], propsAreCssOverrides = comp.propsAreCssOverrides, withProps: basePropsToApply, } = config Object.assign(glamorousComponentFactory, {withConfig}) return glamorousComponentFactory function withConfig(newConfig) { return glamorous(comp, {...config, ...newConfig}) } /** * This returns a React Component that renders the comp (closure) * with a className based on the given glamor styles object(s) * @param {...Object|Function} styles the styles to create with glamor. * If any of these are functions, they are invoked with the component * props and the return value is used. * @return {ReactComponent} the ReactComponent function */ function glamorousComponentFactory(...styles) { /** * This is a component which will render the comp (closure) * with the glamorous styles (closure). Forwards any valid * props to the underlying component. */ const GlamorousComponent = withTheme( function GlamorousInnerComponent(props, context) { props = getPropsToApply( GlamorousComponent.propsToApply, {}, props, context, ) const updateClassName = shouldUpdate(props, context, this.previous) if (shouldClassNameUpdate) { this.previous = {props, context} } const {toForward, cssOverrides, cssProp} = splitProps( props, GlamorousComponent, ) // create className to apply this.className = updateClassName ? getGlamorClassName({ styles: GlamorousComponent.styles, props, cssOverrides, cssProp, context, displayName: GlamorousComponent.displayName, }) : this.className return React.createElement(GlamorousComponent.comp, { // if innerRef is forwarded we don't want to apply it here ref: 'innerRef' in toForward ? undefined : props.innerRef, ...toForward, className: this.className, }) }, {noWarn: true, createElement: false}, ) GlamorousComponent.propTypes = { // className accepts an object due to glamor's css function // returning an object with a toString method that gives the className className: PropTypes.oneOfType([PropTypes.string, PropTypes.object]), cssOverrides: PropTypes.object, innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), glam: PropTypes.object, } function withComponent(newComp, options = {}) { const { forwardProps: fwp, filterProps: flp, ...componentProperties } = GlamorousComponent return glamorous( { ...componentProperties, comp: newComp, rootEl: getRootEl(newComp), }, { // allows the forwardProps and filterProps to be overridden forwardProps: fwp, filterProps: flp, ...options, }, )() } function withProps(...propsToApply) { return glamorous(GlamorousComponent, {withProps: propsToApply})() } function shouldUpdate(props, context, previous) { // exiting early so components which do not use this // optimization are not penalized by hanging onto // references to previous props and context if (!shouldClassNameUpdate) { return true } let update = true if (previous) { if ( !shouldClassNameUpdate( previous.props, props, previous.context, context, ) ) { update = false } } return update } Object.assign( GlamorousComponent, getGlamorousComponentMetadata({ comp, styles, rootEl, filterProps, forwardProps, displayName, propsToApply: basePropsToApply, }), { isGlamorousComponent: true, propsAreCssOverrides, withComponent, withProps, withConfig, }, ) return GlamorousComponent } } function getGlamorousComponentMetadata({ comp, styles, rootEl, filterProps, forwardProps, displayName, propsToApply: basePropsToApply, }) { const componentsComp = comp.comp ? comp.comp : comp const propsToApply = comp.propsToApply ? [...comp.propsToApply, ...arrayify(basePropsToApply)] : arrayify(basePropsToApply) return { // join styles together (for anyone doing: glamorous(glamorous.a({}), {})) styles: when(comp.styles, styles), // keep track of the ultimate rootEl to render (we never // actually render anything but // the base component, even when people wrap a glamorous // component in glamorous comp: componentsComp, rootEl: rootEl || getRootEl(comp), // join forwardProps and filterProps // (for anyone doing: glamorous(glamorous.a({}), {})) forwardProps: when(comp.forwardProps, forwardProps), filterProps: when(comp.filterProps, filterProps), // set the displayName to something that's slightly more // helpful than `GlamorousComponent` :) displayName: displayName || `glamorous(${getDisplayName(comp)})`, // these are props that should be applied to the component at render time propsToApply, } } } /** * reduces the propsToApply given to a single props object * @param {Array} propsToApply an array of propsToApply objects: * - object * - array of propsToApply items * - function that accepts the accumulated props and the context * @param {Object} accumulator an object to apply props onto * @param {Object} props the props that should ultimately take precedence * @param {*} context the context object * @return {Object} the reduced props */ function getPropsToApply(propsToApply, accumulator, props, context) { // using forEach rather than reduce here because the reduce solution // effectively did the same thing because we manipulate the `accumulator` propsToApply.forEach(propsToApplyItem => { if (typeof propsToApplyItem === 'function') { return Object.assign( accumulator, propsToApplyItem(Object.assign({}, accumulator, props), context), ) } else if (Array.isArray(propsToApplyItem)) { return Object.assign( accumulator, getPropsToApply(propsToApplyItem, accumulator, props, context), ) } return Object.assign(accumulator, propsToApplyItem) }) // props wins return Object.assign(accumulator, props) } function arrayify(x = []) { return Array.isArray(x) ? x : [x] } function when(comp, prop) { return comp ? comp.concat(prop) : prop } function getRootEl(comp) { return comp.rootEl ? comp.rootEl : comp.comp || comp } function getDisplayName(comp) { return typeof comp === 'string' ? comp : comp.displayName || comp.name || 'unknown' }
packages/ringcentral-widgets-docs/src/app/pages/Components/DialPad/index.js
u9520107/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/DialPad'; const DialPadPage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="DialPad" description={info.description} /> <CodeExample code={demoCode} title="DialPad Example" > <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default DialPadPage;
src/higherOrder/loadable/index.js
ProteinsWebTeam/interpro7-client
import React from 'react'; import LoadingComponent from 'components/SimpleCommonComponents/Loading'; const loadable = ({ loader, loading }) /*: Object */ => { if (!loader) return; const Loaded = React.lazy(loader); const Loading = loading || LoadingComponent; const Loadable = props => { return ( <React.Suspense fallback={<Loading />}> <Loaded {...props} /> </React.Suspense> ); }; return React.memo(Loadable); }; export default loadable;