path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
wrappers/html.js
dominictracey/dominictracey.com
import React from 'react' module.exports = React.createClass({ propTypes () { return { router: React.PropTypes.object, } }, render () { const post = this.props.route.page.data return ( <div className="markdown"> <h1 dangerouslySetInnerHTML={{ __html: post.title }} /> <div dangerouslySetInnerHTML={{ __html: post.body }} /> </div> ) }, })
src/js/pages/RegisterPage.js
nekuno/client
import { SOCIAL_NETWORKS_NAMES, FACEBOOK_SCOPE } from '../constants/Constants'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import FacebookButton from '../components/ui/FacebookButton'; import translate from '../i18n/Translate'; import connectToStores from '../utils/connectToStores'; import ConnectActionCreators from '../actions/ConnectActionCreators'; import * as GroupActionCreators from '../actions/GroupActionCreators'; import RouterActionCreators from '../actions/RouterActionCreators'; import LoginActionCreators from '../actions/LoginActionCreators'; import InvitationStore from '../stores/InvitationStore'; import RegisterStore from '../stores/RegisterStore'; import LocaleStore from '../stores/LocaleStore'; import SocialNetworkService from '../services/SocialNetworkService'; import Framework7Service from '../services/Framework7Service'; function getState(props) { const error = InvitationStore.error; const token = InvitationStore.token; const profile = RegisterStore.profile; const registerData = RegisterStore.getData(); const invitation = InvitationStore.invitation; const interfaceLanguage = LocaleStore.locale; return { error, token, profile, registerData, invitation, interfaceLanguage }; } @translate('RegisterPage') @connectToStores([InvitationStore, LocaleStore], getState) export default class RegisterPage extends Component { static propTypes = { // Injected by @translate: strings : PropTypes.object, // Injected by @connectToStores: error : PropTypes.object, token : PropTypes.string, profile : PropTypes.object, registerData : PropTypes.object, invitation : PropTypes.object, interfaceLanguage: PropTypes.string }; static contextTypes = { router: PropTypes.object.isRequired }; constructor(props) { super(props); this.handleSocialNetwork = this.handleSocialNetwork.bind(this); this._registerUser = this._registerUser.bind(this); this.state = { loginUser: false, registeringUser: false, initialToken: null } } componentDidMount() { const {location, token, profile, registerData} = this.props; let initialToken = location.query && location.query.token ? location.query.token : null; if (registerData && registerData.oauth) { this.handleSocialNetwork(SOCIAL_NETWORKS_NAMES.FACEBOOK, FACEBOOK_SCOPE); } else if (initialToken) { this.setState({initialToken}); ConnectActionCreators.validateInvitation(initialToken); } else if (!token && !profile) { this.context.router.push('/'); } } handleSocialNetwork(resource, scope) { const {token, invitation, interfaceLanguage, strings} = this.props; this.setState({loginUser: true}); SocialNetworkService.login(resource, scope, true).then(() => { const oauthData = SocialNetworkService.buildOauthData(resource); LoginActionCreators.loginUserByResourceOwner( resource, SocialNetworkService.getAccessToken(resource), SocialNetworkService.getRefreshToken(resource) ).then( () => { console.log('User already logged in. Using invitation', invitation); if (invitation && invitation.hasOwnProperty('group')) { console.log('Joining group', invitation.group); return GroupActionCreators.joinGroup(invitation.group.id); } return null; // User is logged in }, () => { let user = SocialNetworkService.getUser(resource); let profile = SocialNetworkService.getProfile(resource); if (!user || !profile) { Framework7Service.nekunoApp().alert(strings.blockingError); this.setState({registeringUser: false}); } else { profile.interfaceLanguage = interfaceLanguage; profile.orientationRequired = false; this._registerUser(user, profile, token, oauthData); } }); }, (status) => { Framework7Service.nekunoApp().alert(resource + ' login failed: ' + status.error.message) }); } _registerUser(user, profile, token, oauthData) { LoginActionCreators.preRegister(user, profile, token, oauthData); setTimeout(() => RouterActionCreators.replaceRoute('answer-username'), 0); this.setState({ registeringUser: true }); } render() { const {error, token, invitation, strings} = this.props; const {initialToken, registeringUser, loginUser} = this.state; return ( <div className="views"> <div className="view view-main register-view"> <div className="page register-page"> <div className="register-image" style={invitation && invitation.image_url && (!initialToken || token || error) ? {background: 'url("' + invitation.image_url + '") no-repeat center top', minHeight: '100%'} : null}> <div className="gradient-transparency"></div> </div> <div className="register-nekuno-logo-wrapper"> <div className="register-nekuno-logo"></div> </div> <div id="page-content" className="register-content"> <div className="register-title bold"> <div className="title">{token && invitation ? (invitation.slogan ? invitation.slogan : strings.titleCorrect) : strings.title}</div> </div> <div className="register-sub-title bold"> {strings.openSource} </div> </div> <div> <FacebookButton onClickHandler={this.handleSocialNetwork} text={initialToken ? strings.compatibility : strings.signUp} disabled={registeringUser || loginUser}/> <br /> <div className="privacy-terms-text"> <p dangerouslySetInnerHTML={{__html: strings.legalTerms}}/> </div> <br /> <br /> </div> </div> </div> </div> ); } } RegisterPage.defaultProps = { strings: { register : 'Create account', cancel : 'Cancel', title : 'Nekuno analyzes your interests to offer you recommendations', openSource : 'Open & free software', titleCorrect : 'Awesome! You got an invitation!', subtitle : 'Please copy the URL that you\'ve received your invitation and paste it into the field below to create your account at Nekuno.', paste : 'Paste the invitation url here', correct : 'Just one last step! Connect Facebook:', loadingMessage : 'Loading', registeringMessage: 'Registering user', publishMessage : 'We\'ll never publish anything on your wall', legalTerms : 'We will never post anything on your networks.</br>By registering, you agree to the <a href="https://nekuno.com/terms-and-conditions" target="_blank">End-user license agreement</a>.', signUp : 'Analyze', compatibility : 'Analize compatibility', blockingError : 'Your browser has blocked a Facebook request and we are not able to register you. Please, disable the blocking configuration or use an other browser.' } };
packages/mineral-ui-icons/src/IconInvertColorsOff.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconInvertColorsOff(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M20.65 20.87l-2.35-2.35-6.3-6.29-3.56-3.57-1.42-1.41L4.27 4.5 3 5.77l2.78 2.78a8.005 8.005 0 0 0 .56 10.69A7.98 7.98 0 0 0 12 21.58c1.79 0 3.57-.59 5.03-1.78l2.7 2.7L21 21.23l-.35-.36zM12 19.59c-1.6 0-3.11-.62-4.24-1.76A5.945 5.945 0 0 1 6 13.59c0-1.32.43-2.57 1.21-3.6L12 14.77v4.82zM12 5.1v4.58l7.25 7.26c1.37-2.96.84-6.57-1.6-9.01L12 2.27l-3.7 3.7 1.41 1.41L12 5.1z"/> </g> </Icon> ); } IconInvertColorsOff.displayName = 'IconInvertColorsOff'; IconInvertColorsOff.category = 'communication';
client/ui/atoms/card.story.js
LestaD/InstaClone
/* eslint-disable react/prop-types */ import React from 'react' import { storiesOf } from '@storybook/react' import { Card } from './card' storiesOf('ui/atoms', module) .addWithJSX('Card', () => ( <Card>Simple content of card</Card> ))
app/routes.js
oeb25/colio
import React from 'react'; import { Route } from 'react-router'; import LandingContainer from './containers/LandingContainer'; import RoomContainer from './containers/RoomContainer'; import CreateRoom from './components/CreateRoom'; const routes = ( <Route> <Route path="/" component={LandingContainer}/> <Route path="/room" component={CreateRoom} /> <Route path="/room/:id" component={RoomContainer} /> </Route> ); export default routes;
components/summary.js
dvzrd/gatsby-utool.io
import React from 'react'; import { prune } from 'underscore.string'; import { fixLinks } from 'utils'; const style = { summary: { display: 'block', position: 'relative', margin: '0 auto', color: '#555' } }; class Summary extends React.Component { summary(body) { const split = body.split('<hr>'); return split.length !== 0 && split[0].length < 200 ? split[0] : prune(body.replace(/<[^>]*>/g, ''), 200); } componentDidMount() { fixLinks(this.refs.markdown, this.context.router); } render() { return ( <p className="article summary" ref="markdown" style={style.summary} dangerouslySetInnerHTML={{__html: this.summary(this.props.body)}}/> ); } } Summary.propTypes = { body: React.PropTypes.string.isRequired }; Summary.contextTypes = { router: React.PropTypes.object.isRequired }; export default Summary;
src/svg-icons/av/add-to-queue.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvAddToQueue = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-7v2h-3v3h-2v-3H8v-2h3V7h2v3h3z"/> </SvgIcon> ); AvAddToQueue = pure(AvAddToQueue); AvAddToQueue.displayName = 'AvAddToQueue'; AvAddToQueue.muiName = 'SvgIcon'; export default AvAddToQueue;
pages/api/toolbar.js
cherniavskii/material-ui
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './toolbar.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
lib/Components/Current/Current.js
francylang/weathrly
import React from 'react'; import './Current.css'; const Current = (props) => { return ( <div className={`mobileCard ${props.colors}`}> <div className="topCard"> <h1 className="city">{props.weather.location}</h1> <h2 className="currentTemp"> {props.weather.currentTemp} <span className="deg">&deg;</span> </h2> <h2 className="high-low"> HIGH {props.weather.dayHigh} <span className="deg">&deg;</span> / LOW {props.weather.dayLow} <span className="deg">&deg;</span> </h2> </div> <div className="middleCard"> <i className={`wi wi-wu-${props.weather.currentIcon} currentIcon`}></i> <h2 className="currentTime">{props.weather.day}</h2> </div> <div className="bottomCard"> <p className="weatherSummary">{props.weather.dailyDescrip}</p> </div> </div> ); }; export default Current;
src/frontend/screens/Video/index.js
resummed/resummed
import React from 'react'; /** * Video by pexels.com: * https://videos.pexels.com/videos/birds-flying-over-industrial-area-569 */ const Video = () => ( <div> <video src={require('url-loader?limit=100000000!./video.mp4')} autoPlay loop /> </div> ); export default Video;
js/react/workspace.js
CANTUS-Project/vitrail
// -*- coding: utf-8 -*- // ------------------------------------------------------------------------------------------------ // Program Name: vitrail // Program Description: HTML/CSS/JavaScript user agent for the Cantus API. // // Filename: js/react/workspaces.js // Purpose: The "Workspace" components for Vitrail. // // Copyright (C) 2016 Christopher Antila // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // ----------------------------------------------------------------------------------------------- import {Immutable} from 'nuclear-js'; import React from 'react'; import {Link, withRouter} from 'react-router'; import Button from 'react-bootstrap/lib/Button'; import ButtonGroup from 'react-bootstrap/lib/ButtonGroup'; import Col from 'react-bootstrap/lib/Col'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; import Form from 'react-bootstrap/lib/Form'; import FormControl from 'react-bootstrap/lib/FormControl'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import Glyphicon from 'react-bootstrap/lib/Glyphicon'; import Grid from 'react-bootstrap/lib/Grid'; import Modal from 'react-bootstrap/lib/Modal'; import MenuItem from 'react-bootstrap/lib/MenuItem'; import Nav from 'react-bootstrap/lib/Nav'; import NavDropdown from 'react-bootstrap/lib/NavDropdown'; import PageHeader from 'react-bootstrap/lib/PageHeader'; import Panel from 'react-bootstrap/lib/Panel'; import Row from 'react-bootstrap/lib/Row'; import getters from '../nuclear/getters'; import reactor from '../nuclear/reactor'; import ResultList from './result_list'; import signals from '../nuclear/signals'; // for the "add to collection" and "remove from collection" buttons const addToCollTooltip = 'Save Chant in a Collection'; const removeFromCollTooltip = 'Remove Chant from this Collection'; /** Displays existing collections, asking the user which collection a resource should be added to. * * NuclearJS State * --------------- * @param (ImmutableJS.Map) collections - The collections that exist. */ const AddToCollection = React.createClass({ propTypes: { close: React.PropTypes.func.isRequired, rid: React.PropTypes.string, }, mixins: [reactor.ReactMixin], getDataBindings() { return {collections: getters.collections}; }, handleClick(event) { const startOfSlice = 4; // after the "col-" part signals.addToCollection(event.target.id.slice(startOfSlice), this.props.rid); this.handleHide(); }, handleHide() { this.props.close(); }, render() { return ( <Modal show onHide={this.handleHide}> <Modal.Header> {`Add resource to which collection?`} </Modal.Header> <Modal.Body> {this.state.collections.map((value, key) => <Button onClick={this.handleClick} id={`col-${key}`} key={key} block> {value.get('name')} </Button> ).toList()} </Modal.Body> <Modal.Footer> <Button bsStyle="danger" onClick={this.handleHide}>{`Cancel`}</Button> </Modal.Footer> </Modal> ); }, }); /** Produces a <ButtonGroup> with buttons for adding/removing a resource to a collection, as applicable. * * Props * ----- * @param (string) rid - The resource ID to add or remove. * * State * ----- * @param {bool} showAddToCollection - Whether to render the AddToCollection subcomponent. * @param (bool) showingCollection - From the "showingCollection" getter. * * Note that a "remove" button will only be produced if "state.showingCollection" is not false. * Otherwise, we don't know from which collection to remove the resource. * * The "add" button is always shown because you might want a resource to be in many collections. */ const AddRemoveCollection = React.createClass({ propTypes: { rid: React.PropTypes.string.isRequired, }, mixins: [reactor.ReactMixin], getDataBindings() { return {showingCollection: getters.showingCollection}; }, getInitialState() { return {showAddToCollection: false}; }, handleRemove() { signals.removeFromCollection(this.state.showingCollection, this.props.rid); }, openAddToCollection() { this.setState({showAddToCollection: true}); }, closeAddToCollection() { this.setState({showAddToCollection: false}); }, render() { let removeButton; if (this.state.showingCollection) { removeButton = ( <Button onClick={this.handleRemove} bsSize="small" title={removeFromCollTooltip}> <Glyphicon glyph="minus"/> <span className="sr-only">{removeFromCollTooltip}</span> </Button> ); } let addToCollection; if (this.state.showAddToCollection) { addToCollection = <AddToCollection rid={this.props.rid} close={this.closeAddToCollection}/>; } return ( <ButtonGroup> {addToCollection} <Button onClick={this.openAddToCollection} bsSize="small" title={addToCollTooltip}> <Glyphicon glyph="save"/> <span className="sr-only">{addToCollTooltip}</span> </Button> {removeButton} </ButtonGroup> ); }, }); /** Sub-component of Collection that allows renaming. * * Props: * ------ * @param (ImmutableJS.Map) collection - Optional. The collection corresponding to this Collection. * If this is omitted, we assume this is for a new collection. * @param (function) handleHide - This function is called to hide the component. * @param (function) chooseName - This function is called with the newly-chosen name. * * State: * ------ * @param (string) name - The new name for the collection, as it's typed. */ const CollectionRename = React.createClass({ propTypes: { chooseName: React.PropTypes.func.isRequired, collection: React.PropTypes.instanceOf(Immutable.Map), handleHide: React.PropTypes.func.isRequired, }, getInitialState() { if (this.props.collection) { return {name: this.props.collection.get('name')}; } return {name: ''}; }, handleNameChange(event) { this.setState({name: event.target.value}); }, handleRename() { this.props.chooseName(this.state.name); this.props.handleHide(); }, render() { let header; if (this.props.collection) { header = `Rename "${this.props.collection.get('name')}"`; } else { header = 'New collection'; } return ( <Modal show onHide={this.props.handleHide}> <Modal.Header> {header} </Modal.Header> <Modal.Body> <Form onSubmit={this.handleRename}> <FormGroup controlId="formControlsTextarea"> <ControlLabel>{`New name for the collection`}</ControlLabel> <FormControl type="text" value={this.state.name} onChange={this.handleNameChange}/> </FormGroup> </Form> </Modal.Body> <Modal.Footer> <Button bsStyle="danger" onClick={this.props.handleHide}>{`Cancel`}</Button> <Button bsStyle="primary" onClick={this.handleRename}>{`Choose Name`}</Button> </Modal.Footer> </Modal> ); }, }); /** A collection of database resources, as represented in the Shelf component. * * Props: * ------ * @param (ImmutableJS.Map) collection - The collection corresponding to this Collection. * * State: * ------ * @param (bool) showRenamer - Whether to show the <CollectionRename> component. */ const Collection = withRouter(React.createClass({ propTypes: { collection: React.PropTypes.instanceOf(Immutable.Map).isRequired, router: React.PropTypes.object.isRequired, }, getInitialState() { return {showRenamer: false}; }, handleDelete() { signals.deleteCollection(this.props.collection.get('colid')); }, handleShowRenamer() { this.setState({showRenamer: !this.state.showRenamer}); }, submitRename(newName) { signals.renameCollection(this.props.collection.get('colid'), newName); }, render() { const colid = this.props.collection.get('colid'); const linkToCollection = this.props.router.createHref(`/workspace/collection/${colid}`); let renamer; if (this.state.showRenamer) { renamer = ( <CollectionRename collection={this.props.collection} handleHide={this.handleShowRenamer} chooseName={this.submitRename} /> ); } return ( <NavDropdown title={this.props.collection.get('name')} id={`coll-${colid}`}> <MenuItem href={linkToCollection}>{`Open`}</MenuItem> <MenuItem onClick={this.handleShowRenamer}>{`Rename`}</MenuItem> <MenuItem onClick={this.handleDelete}>{`Delete`}</MenuItem> {renamer} </NavDropdown> ); }, })); /** The main workspace, where users can view a collection. * * State: * ------ * @param (ImmutableJS.Map) collections - From NuclearJS, all of this user's Collections. * @param (bool) showingCollection - From the "showingCollection" getter. */ const Desk = React.createClass({ mixins: [reactor.ReactMixin], getDataBindings() { return { collections: getters.collections, showingCollection: getters.showingCollection, }; }, render() { let header; if (this.state.collections.has(this.state.showingCollection)) { header = `Desk (viewing collection "${this.state.collections.get(this.state.showingCollection).get('name')}")`; } return ( <Col lg={10}> <Panel header={header}> <ResultList/> </Panel> </Col> ); }, }); /** Confirm with the user that they want to reset the NuclearJS reactor. * * @param (function) handleHide - This function is called to hide the component. */ const ReactorResetter = React.createClass({ propTypes: { handleHide: React.PropTypes.func.isRequired, }, handleClear() { signals.clearShelf(); this.props.handleHide(); }, render() { return ( <Modal show onHide={this.props.handleHide}> <Modal.Header>{`Really clear your shelf?`}</Modal.Header> <Modal.Body> {`When you clear your shelf:`} <ul> <li>{`all your collections are deleted,`}</li> <li>{`all your saved collections are deleted, and`}</li> <li>{`all your saved chants are deleted too.`}</li> </ul> {`This does not affect data on the server. Only your local data are affected.`} <div className="alert alert-danger"> <strong>{`NOTE`}</strong> {`: it does not fully work, so you have to refresh the page after you clear`} </div> </Modal.Body> <Modal.Footer> <Button bsStyle="danger" onClick={this.handleClear}>{`Clear`}</Button> <Button bsStyle="success" onClick={this.props.handleHide}>{`Keep Shelf`}</Button> </Modal.Footer> </Modal> ); }, }); /** TODO * * State: * ------ * @param (ImmutableJS.Map) collections - From NuclearJS. The collections that exist. * @param (bool) addingNewCollection - Whether we are currently adding a new collection, and the * "CollectionRename" component should therefore be shown. * @param (bool) showResetter - Whether we are currently asking the user whether they want to reset * the NuclearJS Reactor, and should therefore show the "ReactorResetter" component. */ const Shelf = React.createClass({ mixins: [reactor.ReactMixin], getDataBindings() { return {collections: getters.collections}; }, getInitialState() { return {addingNewCollection: false, showResetter: false}; }, toggleAddingCollection() { this.setState({addingNewCollection: !this.state.addingNewCollection}); }, toggleShowResetter() { this.setState({showResetter: !this.state.showResetter}); }, addCollection(newName) { signals.newCollection(newName); }, render() { const collections = this.state.collections.size > 0 ? this.state.collections.map((value) => <Collection key={value.get('colid')} collection={value}/> ).toArray() : <li>{'Choose '}<Glyphicon glyph="plus"/>{' below to make a collection.'}</li> ; let renamer; if (this.state.addingNewCollection) { renamer = ( <CollectionRename handleHide={this.toggleAddingCollection} chooseName={this.addCollection} /> ); } let resetter; if (this.state.showResetter) { resetter = <ReactorResetter handleHide={this.toggleShowResetter}/>; } return ( <Col lg={2}> {renamer} {resetter} <Panel header="Shelf"> <Nav stacked> {collections} </Nav> <hr/> <ButtonGroup block vertical> <Button bsStyle="primary" onClick={this.toggleAddingCollection}> <Glyphicon glyph="plus"/>{` New Collection`} </Button> <Button bsStyle="primary" onClick={this.toggleShowResetter}> <Glyphicon glyph="trash"/>{` Clear Shelf`} </Button> </ButtonGroup> </Panel> </Col> ); }, }); /** * * NOTE: this component is responsible for setting the current collection ID * * Props: * ------ * @param (str) params.colid - From react-router, the collection ID to display. */ const DeskAndShelf = React.createClass({ propTypes: { children: React.PropTypes.element, params: React.PropTypes.shape({ colid: React.PropTypes.string.isRequired, }).isRequired, }, componentWillMount() { this.loadCollection(this.props.params.colid); }, componentWillUpdate(nextProps) { if (this.props.params.colid !== nextProps.params.colid) { this.loadCollection(nextProps.params.colid); } }, componentWillUnmount() { signals.setShowingCollection(false); }, /** Load the data for the collection given by "colid." * * @param {str} colid - The collection ID to load. */ loadCollection(colid) { if (colid) { signals.setShowingCollection(colid); signals.setPage(1); signals.loadCollection(colid); } }, render() { return ( <div> <Desk/> <Shelf/> {this.props.children} </div> ); }, }); const JustShelf = React.createClass({ render() { return ( <div> <Col lg={10}> <Panel header="Desk"> <p> {`Choose a Collection from the Shelf to see its contents on the Desk.`} </p> </Panel> </Col> <Shelf/> </div> ); }, }); const WorkspaceHelp = React.createClass({ propTypes: { handleHide: React.PropTypes.func, }, render() { return ( <Modal show onHide={this.props.handleHide} > <Modal.Header> <Modal.Title>{`About the Workspace`}</Modal.Title> </Modal.Header> <Modal.Body> <p> {`Use the Workspace to save "Collections" of chants to view offline. Your collections are held on the "Shelf." Click or tap a collection on the Shelf to open its chants on the "Desk."`} </p> <p> {`You can name your collections and use them to keep track of search results or any other group of chants you may want to view later. However, your collections are only stored in your browser, so nobody else can see them.`} </p> <p> {`When you add chants to a collection, they're automatically saved in your browser. This means you can view the chants in your collections even if you're not connected to the internet. Refer to our `} <Link to="/offline">{`offline page `}</Link>{`for more information.`} </p> </Modal.Body> <Modal.Footer> <Button bsStyle="primary" onClick={this.props.handleHide}>{`Close`}</Button> </Modal.Footer> </Modal> ); }, }); const Workspace = React.createClass({ propTypes: { children: React.PropTypes.element, }, getInitialState() { return {showHelp: false}; }, handleHelp() { this.setState({showHelp: !this.state.showHelp}); }, render() { const help = this.state.showHelp ? <WorkspaceHelp handleHide={this.handleHelp}/> : undefined; return ( <Grid id="vitrail-workspace" fluid> {help} <PageHeader> {`Workspace\u2003`} <small> <i>{`Manage your personal collections.\u2003`}</i> <Button bsStyle="info" className="help-icon" onClick={this.handleHelp}> <Glyphicon glyph="question-sign"/> </Button> </small> </PageHeader> <Row> {this.props.children} </Row> </Grid> ); }, }); const moduleForTesting = { Workspace: Workspace, }; export {AddToCollection, AddRemoveCollection, DeskAndShelf, JustShelf, Workspace, moduleForTesting};
app/routes.js
FermORG/FermionJS
import React from 'react'; import { Switch, Route } from 'react-router'; import App from './containers/App'; import HomePage from './containers/HomePage'; import CorePage from './containers/CorePage'; export default () => ( <App> <Switch> <Route path="/core" component={CorePage} /> <Route path="/" component={HomePage} /> </Switch> </App> );
src/render-react.js
abramz/gulp-react-render
/*! Gulp Render React | MIT License */ import gutil from 'gulp-util'; import through from 'through2'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; /** * Requires a file containing a React component and create an instance of it * @param {String} filePath file path to the React component to render * @param {Object} props properties to apply to the element * @return {Element} the created React element */ function createElement(filePath, props) { if (!filePath || typeof filePath !== 'string' || filePath.length === 0) { throw new Error('Expected filePath to be a string'); } // clear the require cache if we have already imported the file (if we are watching it) if (require.cache[filePath]) { delete require.cache[filePath]; } const component = require(filePath); // eslint-disable-line global-require, import/no-dynamic-require const element = React.createElement(component.default || component, props || {}); return element; } /** * Uses ReactDOMServer.renderToString on a component at filePath. Will apply optional pro * https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring * * @param {String} filePath react component to render * @param {Object} props properties to apply to the React component * @return {Buffer} buffer of the component rendered to a string */ function renderToString(filePath, props) { const element = createElement(filePath, props); const elementString = ReactDOMServer.renderToString(element); return new Buffer(elementString); } /** * Uses ReactDOMServer.renderToStatic on a component at filePath. Will apply optional props * https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostaticmarkup * * @param {String} filePath react component to render * @param {Object} props properties to apply to the React component * @return {Buffer} buffer of the component rendered to a string */ function renderToStaticMarkup(filePath, props) { const element = createElement(filePath, props); const elementMarkup = ReactDOMServer.renderToStaticMarkup(element); return new Buffer(elementMarkup); } module.exports = (options) => { const opts = options || {}; if (!opts.type || (opts.type !== 'string' && opts.type !== 'markup')) { throw new gutil.PluginError('gulp-render-react', '`type` required (`string` or `markup`)'); } return through.obj(function process(file, enc, callback) { try { const newFile = file; // temporary before we allow src extension in options if (opts.type === 'string') { newFile.contents = renderToString(file.path, opts.props ? opts.props : {}); } else if (opts.type === 'markup') { newFile.contents = renderToStaticMarkup(file.path, opts.props ? opts.props : {}); } // temporary before we allow dest extension in options newFile.path = gutil.replaceExtension(file.path, '.html'); this.push(newFile); } catch (err) { this.emit('error', new gutil.PluginError('gulp-render-react', err, { fileName: file.path })); } callback(); }); };
src/clincoded/static/libs/bootstrap/popover.js
ClinGen/clincoded
"use strict"; import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; // Display a popover that shows descriptive text content until the user dismisses it. // The typical format looks like: // // <PopOverComponent {...this.props}> // // Render JSX... // </PopOverComponent> // // This component has been written in similar way to the rewritten modal component. // // <PopOverComponent> usage details: // See 'PopOverComponent.propTypes' for details export default class PopOverComponent extends React.Component { constructor(props) { super(props); this.state = { isPopOverOpen: false }; this.handlePopOver = this.handlePopOver.bind(this); this.closePopOver = this.closePopOver.bind(this); } componentDidMount() { this.props.popOverRef(this); } componentWillUnmount() { this.props.popOverRef(null); } // Called by the actuator (link/button to toggle the popover) handlePopOver() { this.setState({ isPopOverOpen: !this.state.isPopOverOpen }); } // Called by the popover's own Close button defined in the "PopOver" component closePopOver() { this.setState({ isPopOverOpen: false }); } render() { return ( <div className={'popover-component ' + this.props.popOverWrapperClass}> {this.props.actuatorTitle ? <a className="popover-actuator" onClick={() => this.handlePopOver()}>{this.props.actuatorTitle}</a> : null} <PopOver isPopOverOpen={this.state.isPopOverOpen} closePopOver={this.closePopOver} popOverStyleClass={this.props.popOverStyleClass}> {this.props.children} </PopOver> </div> ); } } PopOverComponent.propTypes = { popOverWrapperClass: PropTypes.string, // CSS class for popover DOM wrapper popOverStyleClass: PropTypes.string, // CSS class for popover style (e.g. alert-info, alert-warning) actuatorTitle: PropTypes.oneOfType([ // Text for link to invoke popover PropTypes.object, PropTypes.string ]), children: PropTypes.node // JSX such as input field(s), dropdown(s), buttons, or text string }; class PopOver extends React.Component { render() { if (this.props.isPopOverOpen === false) { return null; } return ( <div className={'popover-wrapper ' + this.props.popOverStyleClass} style={{display: 'block'}}> <a className="closePopOver" aria-label="Close" onClick={this.props.closePopOver}> <span aria-hidden="true"><i className="icon icon-times"></i></span> </a> <div className="popover-content"> {this.props.children} </div> </div> ); } } PopOver.propTypes = { closePopOver: PropTypes.func, isPopOverOpen: PropTypes.bool, popOverStyleClass: PropTypes.string };
8-css-inline/src/App.js
mariusz-malinowski/tutorial-react
import React, { Component } from 'react'; import initialState from './data'; import TodoList from './TodoList'; import TodoDetails from './TodoDetails'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import reducer from './reducer'; import createHistory from 'history/createBrowserHistory'; import { Router, Route } from 'react-router-dom'; const history = createHistory(); const store = createStore(reducer, initialState); class App extends Component { render() { return ( <Provider store={store}> <Router history={history}> <div> <Route exact path="/" component={TodoList} /> <Route path="/todoDetails" component={TodoDetails} /> </div> </Router> </Provider> ); } } export default App;
app/setup.js
JohnKim/react-native-boilerplate
/** * * @flow */ import React, { Component } from 'react'; import { APP_ID, SERVER_URL } from 's5-env'; import { FacebookSDK } from 's5-util'; import Parse from 'parse/react-native'; import Relay from 'react-relay'; import { Provider } from 'react-redux'; import configureStore from './store/configureStore'; /* Application */ import App from './components/app'; /* Application (for UI test) */ //import App from './AppPlayground'; function setup(): Component { console.disableYellowBox = true; Parse.initialize(APP_ID); Parse.serverURL = `${SERVER_URL}/parse`; FacebookSDK.init(); Parse.FacebookUtils.init(); Relay.injectNetworkLayer( new Relay.DefaultNetworkLayer(`${SERVER_URL}/graphql`, { fetchTimeout: 30000, retryDelays: [5000, 10000], }) ); class Root extends Component { state = { isLoading: true, store: configureStore(() => this.setState({isLoading: false})), }; render() { if (this.state.isLoading) { return null; } /** 컴포넌트에 Store를 제공하는 Provider (최상위 컨포넌트) **/ return ( <Provider store={this.state.store}> <App /> </Provider> ); } } return Root; } global.LOG = (...args) => { console.log('/------------------------------\\'); console.log(...args); console.log('\\------------------------------/'); return args[args.length - 1]; }; module.exports = setup;
js/BaseComponents/InfoBlock.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. */ // @flow 'use strict'; import React from 'react'; import Text from './Text'; import View from './View'; import BlockIcon from './BlockIcon'; import Theme from '../App/Theme'; const InfoBlock = (props: Object): Object => { const { text, appLayout, infoIconStyle, infoContainer, textStyle, } = props; const { infoContainerDef, infoIconStyleDef, textStyleDef, blockIconContainerStyle, } = getStyles(appLayout); return ( <View level={2} style={[infoContainerDef, infoContainer]}> <BlockIcon icon={'info'} iconLevel={36} style={[infoIconStyleDef, infoIconStyle]} containerStyle={blockIconContainerStyle}/> <View style={{ flex: 1, flexDirection: 'row', flexWrap: 'wrap', }}> <Text level={26} style={[textStyleDef, textStyle]}> {text} </Text> </View> </View> ); }; const getStyles = (appLayout: Object): Object => { const { height, width } = appLayout; const isPortrait = height > width; const deviceWidth = isPortrait ? width : height; const { shadow, paddingFactor, fontSizeFactorTwelve, } = Theme.Core; const padding = deviceWidth * paddingFactor; const fontSizeBody = deviceWidth * fontSizeFactorTwelve; return { infoContainerDef: { flex: 1, flexDirection: 'row', marginBottom: padding / 2, padding: padding, ...shadow, alignItems: 'center', justifyContent: 'space-between', borderRadius: 2, }, blockIconContainerStyle: { backgroundColor: 'transparent', }, infoIconStyleDef: { fontSize: deviceWidth * 0.14, }, textStyleDef: { flex: 1, fontSize: fontSizeBody, flexWrap: 'wrap', marginLeft: padding, }, }; }; export default (React.memo<Object>(InfoBlock): Object);
src/app/client.js
lmcjt37/kulor-reactify
import 'react-toolbox/lib/commons.scss'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.js'; ReactDOM.render(<App />, document.getElementById('app'));
src/Flags/Nigeria.js
runjak/css-flags
// @flow import React from 'react'; import LinearFlag from './LinearFlag'; import gradient from '../utils/gradient'; const green = '#008850'; const white = '#FFFFFF'; export default function Nigeria() { return ( <LinearFlag gradient={`to right, ${gradient([green, white, green])}`} /> ); }
src/components/Assets/Arrow.js
LifeSourceUA/lifesource.ua
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import svg from 'lib/svg'; @svg({ width: 8, height: 14 }) export default class Arrow extends Component { static propTypes = { color: PropTypes.string.isRequired }; render() { const { color } = this.props; return ( <path fill={ color } d="M0.2,13.8L0.2,13.8c-0.3-0.3-0.3-0.8,0-1.1L6.2,7L0.2,1.3c-0.3-0.3-0.3-0.8, 0-1.1l0,0c0.3-0.3,0.8-0.3,1.1,0l6.5,6.3c0.3,0.3,0.3,0.8,0,1.1l-6.5,6.3C1,14.1,0.5,14.1,0.2,13.8z" /> ); } }
popup/src/scripts/components/friends/LiveFriendVideoReplaysList.js
CaliAlec/ChromeIGStory
import React, { Component } from 'react'; import Toolbar from '@material-ui/core/Toolbar'; import Tooltip from '@material-ui/core/Tooltip'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import Avatar from '@material-ui/core/Avatar'; import MenuItem from '@material-ui/core/MenuItem'; import IconButton from '@material-ui/core/IconButton'; import ListSubheader from '@material-ui/core/ListSubheader'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import DownloadIcon from '@material-ui/icons/GetApp'; import ShareIcon from '@material-ui/icons/Share'; import VideoLibraryIcon from '@material-ui/icons/VideoLibrary'; import MusicLibraryIcon from '@material-ui/icons/LibraryMusic'; import LiveVideo from '../../../../../utils/LiveVideo'; import {getTimeElapsed} from '../../../../../utils/Utils'; import {setCurrentStoryObject} from '../../utils/PopupUtils'; import AnalyticsUtil from '../../../../../utils/AnalyticsUtil'; import LiveVideoReplayDownloadDialog from '../../../../../utils/LiveVideoReplayDownloadDialog'; class LiveFriendVideoReplaysList extends Component { constructor(props){ super(props); this.state = { selectedIndex: -1, downloadingIndex: -1, isDownloadLiveVideoDialogOpen: false } } handleRequestChange (event, index) { var selectedStory = this.props.friendStories.post_live.post_live_items[index]; setCurrentStoryObject('LIVE_REPLAY', {post_live_item: selectedStory}); this.setState({ selectedIndex: index, }); AnalyticsUtil.track("Story List Item Clicked", AnalyticsUtil.getStoryObject(selectedStory)); } onDownloadStory(index) { this.setState({ isDownloadLiveVideoDialogOpen: true, downloadingIndex: index }); } onShareStory(index) { var selectedStory = this.props.friendStories.post_live.post_live_items[index].broadcasts[0]; AnalyticsUtil.track("Share Story", AnalyticsUtil.getStoryObject(selectedStory)); window.open('https://watchmatcha.com/user/' + selectedStory.broadcast_owner.username); } renderListItem(index, liveVideoReplay) { const styles = { listItem: { flex: 1, background: 'transparent', paddingLeft: '0px', paddingRight: '0px', minHeight: '48px' }, listItemContent: { display: 'flex', flex: 1 }, listItemActions: { textAlign: 'right' } } const { selectedIndex } = this.state; const isPrivate = liveVideoReplay.user.is_private; const latestBroadcast = liveVideoReplay.broadcasts[liveVideoReplay.broadcasts.length - 1]; return ( <ListItem key={index} button selected={selectedIndex === index} onClick={event => this.handleRequestChange(event, index)} > <Toolbar style={styles.listItem}> <div style={styles.listItemContent}> <ListItemAvatar> <Avatar src={liveVideoReplay.user.profile_pic_url} /> </ListItemAvatar> <ListItemText primary={liveVideoReplay.user.username} secondary={getTimeElapsed(latestBroadcast.published_time)} /> </div> <div style={styles.listItemActions}> {/* <Tooltip title={(isPrivate) ? "Can't Share Private Story" : "Share"} placement="bottom" > <IconButton disabled={isPrivate} onClick={() => this.onShareStory(index)}> <ShareIcon /> </IconButton> </Tooltip> */} <Tooltip title="Download" placement="bottom" > <IconButton onClick={() => this.onDownloadStory(index)}> <DownloadIcon /> </IconButton> </Tooltip> </div> </Toolbar> </ListItem> ) } render() { if(this.props.friendStories.post_live.post_live_items.length === 0) { return (<div></div>); } const liveFriendVideoReplaysListData = this.props.friendStories.post_live.post_live_items.map((liveVideoReplay, key) => { return this.renderListItem(key, liveVideoReplay); }); return ( <div> <List onChange={this.handleRequestChange.bind(this)}> <ListSubheader disableSticky>Live Video Replays</ListSubheader> {liveFriendVideoReplaysListData} </List> {this.state.isDownloadLiveVideoDialogOpen && <LiveVideoReplayDownloadDialog isOpen={this.state.isDownloadLiveVideoDialogOpen} liveVideoReplays={this.props.friendStories.post_live.post_live_items[this.state.downloadingIndex].broadcasts} onRequestClose={() => this.setState({isDownloadLiveVideoDialogOpen: false})} /> } </div> ) } } export default LiveFriendVideoReplaysList;
app/components/widget-list.js
svtizg/svtizg.github.io
import React from 'react'; const WidgetList = React.createClass({ render: function() { return ( <ul className="widget-list"> <li>Сообщение от пользователя 1</li> <li>Сообщение от пользователя 2</li> <li>Сообщение от пользователя 3</li> </ul> ); } }); export default WidgetList;
app/javascript/mastodon/features/compose/components/emoji_picker_dropdown.js
Ryanaka/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { EmojiPicker as EmojiPickerAsync } from '../../ui/util/async-components'; import Overlay from 'react-overlays/lib/Overlay'; import classNames from 'classnames'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { supportsPassiveEvents } from 'detect-passive-events'; import { buildCustomEmojis, categoriesFromEmojis } from '../../emoji/emoji'; import { assetHost } from 'mastodon/utils/config'; const messages = defineMessages({ emoji: { id: 'emoji_button.label', defaultMessage: 'Insert emoji' }, emoji_search: { id: 'emoji_button.search', defaultMessage: 'Search...' }, custom: { id: 'emoji_button.custom', defaultMessage: 'Custom' }, recent: { id: 'emoji_button.recent', defaultMessage: 'Frequently used' }, search_results: { id: 'emoji_button.search_results', defaultMessage: 'Search results' }, people: { id: 'emoji_button.people', defaultMessage: 'People' }, nature: { id: 'emoji_button.nature', defaultMessage: 'Nature' }, food: { id: 'emoji_button.food', defaultMessage: 'Food & Drink' }, activity: { id: 'emoji_button.activity', defaultMessage: 'Activity' }, travel: { id: 'emoji_button.travel', defaultMessage: 'Travel & Places' }, objects: { id: 'emoji_button.objects', defaultMessage: 'Objects' }, symbols: { id: 'emoji_button.symbols', defaultMessage: 'Symbols' }, flags: { id: 'emoji_button.flags', defaultMessage: 'Flags' }, }); let EmojiPicker, Emoji; // load asynchronously const listenerOptions = supportsPassiveEvents ? { passive: true } : false; const backgroundImageFn = () => `${assetHost}/emoji/sheet_13.png`; const notFoundFn = () => ( <div className='emoji-mart-no-results'> <Emoji emoji='sleuth_or_spy' set='twitter' size={32} sheetSize={32} backgroundImageFn={backgroundImageFn} /> <div className='emoji-mart-no-results-label'> <FormattedMessage id='emoji_button.not_found' defaultMessage='No matching emojis found' /> </div> </div> ); class ModifierPickerMenu extends React.PureComponent { static propTypes = { active: PropTypes.bool, onSelect: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, }; handleClick = e => { this.props.onSelect(e.currentTarget.getAttribute('data-index') * 1); } componentWillReceiveProps (nextProps) { if (nextProps.active) { this.attachListeners(); } else { this.removeListeners(); } } componentWillUnmount () { this.removeListeners(); } handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } attachListeners () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); } removeListeners () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } render () { const { active } = this.props; return ( <div className='emoji-picker-dropdown__modifiers__menu' style={{ display: active ? 'block' : 'none' }} ref={this.setRef}> <button onClick={this.handleClick} data-index={1}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={1} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={2}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={2} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={3}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={3} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={4}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={4} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={5}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={5} backgroundImageFn={backgroundImageFn} /></button> <button onClick={this.handleClick} data-index={6}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={6} backgroundImageFn={backgroundImageFn} /></button> </div> ); } } class ModifierPicker extends React.PureComponent { static propTypes = { active: PropTypes.bool, modifier: PropTypes.number, onChange: PropTypes.func, onClose: PropTypes.func, onOpen: PropTypes.func, }; handleClick = () => { if (this.props.active) { this.props.onClose(); } else { this.props.onOpen(); } } handleSelect = modifier => { this.props.onChange(modifier); this.props.onClose(); } render () { const { active, modifier } = this.props; return ( <div className='emoji-picker-dropdown__modifiers'> <Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={modifier} onClick={this.handleClick} backgroundImageFn={backgroundImageFn} /> <ModifierPickerMenu active={active} onSelect={this.handleSelect} onClose={this.props.onClose} /> </div> ); } } @injectIntl class EmojiPickerMenu extends React.PureComponent { static propTypes = { custom_emojis: ImmutablePropTypes.list, frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string), loading: PropTypes.bool, onClose: PropTypes.func.isRequired, onPick: PropTypes.func.isRequired, style: PropTypes.object, placement: PropTypes.string, arrowOffsetLeft: PropTypes.string, arrowOffsetTop: PropTypes.string, intl: PropTypes.object.isRequired, skinTone: PropTypes.number.isRequired, onSkinTone: PropTypes.func.isRequired, }; static defaultProps = { style: {}, loading: true, frequentlyUsedEmojis: [], }; state = { modifierOpen: false, readyToFocus: false, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); // Because of https://github.com/react-bootstrap/react-bootstrap/issues/2614 we need // to wait for a frame before focusing requestAnimationFrame(() => { this.setState({ readyToFocus: true }); if (this.node) { const element = this.node.querySelector('input[type="search"]'); if (element) element.focus(); } }); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } getI18n = () => { const { intl } = this.props; return { search: intl.formatMessage(messages.emoji_search), categories: { search: intl.formatMessage(messages.search_results), recent: intl.formatMessage(messages.recent), people: intl.formatMessage(messages.people), nature: intl.formatMessage(messages.nature), foods: intl.formatMessage(messages.food), activity: intl.formatMessage(messages.activity), places: intl.formatMessage(messages.travel), objects: intl.formatMessage(messages.objects), symbols: intl.formatMessage(messages.symbols), flags: intl.formatMessage(messages.flags), custom: intl.formatMessage(messages.custom), }, }; } handleClick = (emoji, event) => { if (!emoji.native) { emoji.native = emoji.colons; } if (!(event.ctrlKey || event.metaKey)) { this.props.onClose(); } this.props.onPick(emoji); } handleModifierOpen = () => { this.setState({ modifierOpen: true }); } handleModifierClose = () => { this.setState({ modifierOpen: false }); } handleModifierChange = modifier => { this.props.onSkinTone(modifier); } render () { const { loading, style, intl, custom_emojis, skinTone, frequentlyUsedEmojis } = this.props; if (loading) { return <div style={{ width: 299 }} />; } const title = intl.formatMessage(messages.emoji); const { modifierOpen } = this.state; const categoriesSort = [ 'recent', 'people', 'nature', 'foods', 'activity', 'places', 'objects', 'symbols', 'flags', ]; categoriesSort.splice(1, 0, ...Array.from(categoriesFromEmojis(custom_emojis)).sort()); return ( <div className={classNames('emoji-picker-dropdown__menu', { selecting: modifierOpen })} style={style} ref={this.setRef}> <EmojiPicker perLine={8} emojiSize={22} sheetSize={32} custom={buildCustomEmojis(custom_emojis)} color='' emoji='' set='twitter' title={title} i18n={this.getI18n()} onClick={this.handleClick} include={categoriesSort} recent={frequentlyUsedEmojis} skin={skinTone} showPreview={false} showSkinTones={false} backgroundImageFn={backgroundImageFn} notFound={notFoundFn} autoFocus={this.state.readyToFocus} emojiTooltip /> <ModifierPicker active={modifierOpen} modifier={skinTone} onOpen={this.handleModifierOpen} onClose={this.handleModifierClose} onChange={this.handleModifierChange} /> </div> ); } } export default @injectIntl class EmojiPickerDropdown extends React.PureComponent { static propTypes = { custom_emojis: ImmutablePropTypes.list, frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string), intl: PropTypes.object.isRequired, onPickEmoji: PropTypes.func.isRequired, onSkinTone: PropTypes.func.isRequired, skinTone: PropTypes.number.isRequired, button: PropTypes.node, }; state = { active: false, loading: false, placement: null, }; setRef = (c) => { this.dropdown = c; } onShowDropdown = ({ target }) => { this.setState({ active: true }); if (!EmojiPicker) { this.setState({ loading: true }); EmojiPickerAsync().then(EmojiMart => { EmojiPicker = EmojiMart.Picker; Emoji = EmojiMart.Emoji; this.setState({ loading: false }); }).catch(() => { this.setState({ loading: false, active: false }); }); } const { top } = target.getBoundingClientRect(); this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' }); } onHideDropdown = () => { this.setState({ active: false }); } onToggle = (e) => { if (!this.state.loading && (!e.key || e.key === 'Enter')) { if (this.state.active) { this.onHideDropdown(); } else { this.onShowDropdown(e); } } } handleKeyDown = e => { if (e.key === 'Escape') { this.onHideDropdown(); } } setTargetRef = c => { this.target = c; } findTarget = () => { return this.target; } render () { const { intl, onPickEmoji, onSkinTone, skinTone, frequentlyUsedEmojis, button } = this.props; const title = intl.formatMessage(messages.emoji); const { active, loading, placement } = this.state; return ( <div className='emoji-picker-dropdown' onKeyDown={this.handleKeyDown}> <div ref={this.setTargetRef} className='emoji-button' title={title} aria-label={title} aria-expanded={active} role='button' onClick={this.onToggle} onKeyDown={this.onToggle} tabIndex={0}> {button || <img className={classNames('emojione', { 'pulse-loading': active && loading })} alt='🙂' src={`${assetHost}/emoji/1f602.svg`} />} </div> <Overlay show={active} placement={placement} target={this.findTarget}> <EmojiPickerMenu custom_emojis={this.props.custom_emojis} loading={loading} onClose={this.onHideDropdown} onPick={onPickEmoji} onSkinTone={onSkinTone} skinTone={skinTone} frequentlyUsedEmojis={frequentlyUsedEmojis} /> </Overlay> </div> ); } }
client/src/components/side_menu_button/SideMenuButton.js
thewizardplusplus/vk-group-stats
import React from 'react' import IconicButton from '../iconic_button/IconicButton' export default class SideMenuButton extends React.Component { // this name required by the AppBar component for a correct styles processing static muiName = 'IconButton' static propTypes = { iconStyle: React.PropTypes.object, onClick: React.PropTypes.func, } render() { return <IconicButton icon="menu" iconStyle={this.props.iconStyle} onTouchTap={this.props.onClick} /> } }
packages/enzyme-adapter-react-helper/src/ifReact.js
airbnb/enzyme
import React from 'react'; import { intersects } from 'semver'; export default function ifReact(range, yes, no) { if (typeof yes !== 'function') { throw new TypeError('"yes" must be a function'); } if (typeof no !== 'function') { throw new TypeError('"no" must be a function'); } return intersects(range, React.version) ? yes : no; }
index.android.js
wellnine/maelstorm
import "./bin/index"; // /** // * Sample React Native App // * https://github.com/facebook/react-native // * @flow // */ // // import React, { Component } from 'react'; // import { // AppRegistry, // StyleSheet, // Text, // View // } from 'react-native'; // // export default class maelstorm extends Component { // render() { // return ( // <View style={styles.container}> // <Text style={styles.welcome}> // Welcome to React Native 1! // </Text> // <Text style={styles.instructions}> // To get started, edit index.android.js // </Text> // <Text style={styles.instructions}> // Double tap R on your keyboard to reload,{'\n'} // Shake or press menu button for dev menu // </Text> // </View> // ); // } // } // // const styles = StyleSheet.create({ // container: { // flex: 1, // justifyContent: 'center', // alignItems: 'center', // backgroundColor: '#F5FCFF', // }, // welcome: { // fontSize: 20, // textAlign: 'center', // margin: 10, // }, // instructions: { // textAlign: 'center', // color: '#333333', // marginBottom: 5, // }, // }); // // AppRegistry.registerComponent('maelstorm', () => maelstorm);
src/svg-icons/action/settings-input-component.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsInputComponent = (props) => ( <SvgIcon {...props}> <path d="M5 2c0-.55-.45-1-1-1s-1 .45-1 1v4H1v6h6V6H5V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2H9v2zm-8 0c0 1.3.84 2.4 2 2.82V23h2v-4.18C6.16 18.4 7 17.3 7 16v-2H1v2zM21 6V2c0-.55-.45-1-1-1s-1 .45-1 1v4h-2v6h6V6h-2zm-8-4c0-.55-.45-1-1-1s-1 .45-1 1v4H9v6h6V6h-2V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2h-6v2z"/> </SvgIcon> ); ActionSettingsInputComponent = pure(ActionSettingsInputComponent); ActionSettingsInputComponent.displayName = 'ActionSettingsInputComponent'; ActionSettingsInputComponent.muiName = 'SvgIcon'; export default ActionSettingsInputComponent;
src/components/common/NavBarLeftButton.js
jinqiupeter/mtsr
import React from 'react'; import {StyleSheet, Platform, View, Text, TouchableOpacity} from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import {COLOR} from '../../config'; export default ({icon, text, children, onPress, containerStyle, iconStyle, textStyle}) => { if (children) { return ( <TouchableOpacity onPress={onPress} style={[styles.container, containerStyle]}> {children} </TouchableOpacity> ); } else { return ( <TouchableOpacity onPress={onPress} style={styles.container}> {icon ? <Icon name={icon} style={[styles.icon, iconStyle]} /> : null} {text ? <Text style={[styles.text, textStyle]}>{text}</Text> : null} </TouchableOpacity> ); } } const styles = StyleSheet.create({ container: { position: 'absolute', minWidth: 30, ...Platform.select({ ios: { top: -6, left: 3, height: 50, }, android: { top: 12, left: 3, height: 34, }, }), flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, icon: { fontSize: 14, color: COLOR.textLightPrompt, }, text: { fontSize: 14, color: COLOR.textLightPrompt, }, });
src/chapters/04-porazdelitve-verjetnosti/01-funkcija-gostote/index.js
medja/ovs-prirocnik
import React from 'react'; import { createChapter } from 'components/chapter'; import Equation from 'components/equation'; const title = 'Funkcija gostote'; function Title(props) { return ( <span> { props.title }{' '} <Equation math="f(x)" /> </span> ); } function Chapter() { return ( <div> <p> Funkcija gostote nam omogoča računanje verjetnosti slučajev spremenljivke, <strong>če poznamo njeno porazdelitev</strong>. Njeno vrednost lahko razberemo tudi s pomočjo verjetnostne tabele, saj je njena vrednost za neki <Equation math="x" />{' '} natanko vrednost v tabeli pod tem <Equation math="x" />-om, torej <Equation math="p_x" />. </p> <p> Ta funkcija nam zato pride prav, ko ne poznamo vnaprej verjetnosti izidov oziroma kadar potrebujemo enačbo za izračun le teh. Ker ta funkcija vrača relativno gostoto oziroma verjetnost nekega izida pa seveda more biti omejena. Ker nič ne more biti več kot <Equation math="100\%" /> mora biti vsota vseh vrednosti te funkcije vedno enaka <Equation math="1" />. </p> </div> ); } export default createChapter(title, Chapter, [], { Title });
demo/components/popup/PopupOptions.js
f0zze/rosemary-ui
import React from 'react'; import {Popup} from '../../../src'; import OptionsTable from '../../helper/OptionsTable'; export default () => { let propDescription = { attachment: { values: `Mandatory, One Of: top left, top center, top right, middle left, middle right, bottom left, bottom center, bottom right`, description: 'Popup attachment position' }, on: { values: 'One Of: hover, click', description: 'Whether popup should be opened on click or on hover' }, popupClassName: { values: 'Variations: tooltip, popup, popup-blue-border', description: 'Popup class name' }, targetClassName: { values: 'string', description: 'Component to which popup is attached class name' }, changeAttachmentDynamically: { values: 'boolean', description: 'Whether popup will change location on window resize' }, modal: { values: 'boolean', description: 'Whether popup is modal' }, animationBaseName: { values: 'string', description: 'Animation class name' }, onOpen: { values: 'function', description: 'Callback when popup is opened' } }; return ( <div> <OptionsTable component={Popup} propDescription={propDescription}/> </div> ); };
src/Parser/Druid/Restoration/Modules/NetherlightCrucibleTraits/NLCTraits.js
hasseboulen/WoWAnalyzer
import React from 'react'; import StatisticsListBox from 'Main/StatisticsListBox'; import CoreNLCTraits from "Parser/Core/Modules//NetherlightCrucibleTraits/NLCTraits"; import LightSpeed from "./LightSpeed"; import MasterOfShadows from "./MasterOfShadows"; class NLCTraits extends CoreNLCTraits { static dependencies = { ...CoreNLCTraits.dependencies, lightSpeed: LightSpeed, masterOfShadows: MasterOfShadows, }; statistic() { return ( <StatisticsListBox title="Netherlight Crucible" tooltip="This provides an overview of the increased provide by the Netherlight Crucible traits." > {this.murderousIntent.active && this.murderousIntent.subStatistic()} {this.shocklight.active && this.shocklight.subStatistic()} {this.refractiveShell.active && this.refractiveShell.subStatistic()} {this.secureInTheLight.active && this.secureInTheLight.subStatistic()} {this.infusionOfLight.active && this.infusionOfLight.subStatistic()} {this.lightsEmbrace.active && this.lightsEmbrace.subStatistic()} {this.shadowbind.active && this.shadowbind.subStatistic()} {this.chaoticDarkness.active && this.chaoticDarkness.subStatistic()} {this.tormentTheWeak.active && this.tormentTheWeak.subStatistic()} {this.darkSorrows.active && this.darkSorrows.subStatistic()} {this.lightSpeed.active && this.lightSpeed.subStatistic()} {this.masterOfShadows.active && this.masterOfShadows.subStatistic()} </StatisticsListBox> ); } } export default NLCTraits;
web/src/routes/ExampleIndexPage.js
ZhuPeng/trackupdates
import React from 'react'; import { connect } from 'dva'; import styles from './ExampleIndexPage.css'; function ExampleIndexPage() { return ( <div className={styles.normal}> <h1 className={styles.title}>Yay! Welcome to dva!</h1> <div className={styles.welcome} /> <ul className={styles.list}> <li>To get started, edit <code>src/index.js</code> and save to reload.</li> <li><a href="https://github.com/dvajs/dva-docs/blob/master/v1/en-us/getting-started.md">Getting Started</a></li> </ul> </div> ); } ExampleIndexPage.propTypes = { }; export default connect()(ExampleIndexPage);
src/Range/Range.js
nirhart/wix-style-react
import React from 'react'; import {children, optional, once} from '../Composite'; import Label from '../Label'; import Input from '../Input'; import RangeInputWithLabelComposite from '../Composite/RangeInputWithLabelComposite/RangeInputWithLabelComposite'; const Range = ({...props, children}) => ( <RangeInputWithLabelComposite {...props}> {children} </RangeInputWithLabelComposite> ); Range.propTypes = { children: children(optional(Label), once(Input), once(Input)) }; Range.displayName = 'Range'; export default Range;
src/svg-icons/maps/local-library.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalLibrary = (props) => ( <SvgIcon {...props}> <path d="M12 11.55C9.64 9.35 6.48 8 3 8v11c3.48 0 6.64 1.35 9 3.55 2.36-2.19 5.52-3.55 9-3.55V8c-3.48 0-6.64 1.35-9 3.55zM12 8c1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3 1.34 3 3 3z"/> </SvgIcon> ); MapsLocalLibrary = pure(MapsLocalLibrary); MapsLocalLibrary.displayName = 'MapsLocalLibrary'; MapsLocalLibrary.muiName = 'SvgIcon'; export default MapsLocalLibrary;
index.ios.js
dddzg/app
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class app extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('app', () => app);
imports/api/administrativeAreas/administrativeAreas.js
howlround/worldtheatremap
// Meteor import { Mongo } from 'meteor/mongo'; import React from 'react'; import ReactSelect from 'react-select'; import { FormattedMessage } from 'react-intl'; import t from 'tcomb-form'; class AdministrativeAreasCollection extends Mongo.Collection { // insert(profile, callback) { // } // remove(selector, callback) { // } } export const AdministrativeAreas = new AdministrativeAreasCollection('AdministrativeAreas'); // Deny all client-side updates since we will be using methods to manage this collection AdministrativeAreas.deny({ insert() { return true; }, update() { return true; }, remove() { return true; }, }); AdministrativeAreas.publicFields = { value: 1, label: 1, }; export const factory = () => { // Administrative Area options const ExistingAdministrativeAreas = AdministrativeAreas.find({}, { sort: { label: 1 } }).fetch(); // Administrative Area template const existingAdministrativeAreasTags = t.form.Form.templates.select.clone({ renderSelect: (locals) => { function onChange(options) { const values = (options || []).map(({ value }) => value); locals.onChange(values); } const placeholder = ( <FormattedMessage id="forms.selectPlaceholder" description="Select widget placeholder" defaultMessage="Select..." /> ); return ( <ReactSelect multi autoBlur options={ExistingAdministrativeAreas} value={locals.value} onChange={onChange} className="administrative-area-select-edit" placeholder={placeholder} /> ); }, }); // Administrative Area factory function class ReactSelectExistingAdministrativeAreasFactory extends t.form.Component { getTemplate() { return existingAdministrativeAreasTags; } } // Administrative Area transformer ReactSelectExistingAdministrativeAreasFactory.transformer = t.form.List.transformer; return ReactSelectExistingAdministrativeAreasFactory; };
examples/src/components/examples/RightToLeft.js
rackt/react-tabs
import React from 'react'; import ExampleItem from '../ExampleItem'; const code = `const Component = ( <div dir="rtl"> <Tabs direction={'rtl'}> <TabList> <Tab>כותרת</Tab> <Tab disabled>כותרת כבויה</Tab> <Tab>כותרת שנייה</Tab> <Tab>כותרת שלישית</Tab> </TabList> <TabPanel> <p> לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי. </p> <p> Source:{' '} <a href="https://en.wikipedia.org/wiki/" target="_blank"> Wikipedia </a> </p> </TabPanel> <TabPanel> <p> לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי. </p> <p> Source:{' '} <a href="https://en.wikipedia.org/wiki/" target="_blank"> Wikipedia </a> </p> </TabPanel> <TabPanel> <p> לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי. לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי. לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי. </p> <p> Source:{' '} <a href="https://en.wikipedia.org/wiki/" target="_blank"> Wikipedia </a> </p> </TabPanel> <TabPanel> <h4>תת כותרת</h4> <p> לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי. לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי. </p> <p> Source:{' '} <a href="https://en.wikipedia.org/wiki/" target="_blank"> Wikipedia </a> </p> </TabPanel> </Tabs> </div> ); render(Component);`; const hint = 'This is an example of a right to left option. Just pass the `direction` prop to the <Tabs /> element'; export default () => ( <ExampleItem code={code} direction="rtl" hint={hint} label="Right To Left Example" /> );
src/AppNavigator.js
mstmustisnt/wishlist
/* * * @providesModule AppNavigator * * */ import React from 'react'; import { observable, action } from 'mobx'; import { observer, Provider } from 'mobx-react'; import { StackNavigator } from 'react-navigation'; import { Root, Content } from 'native-base'; import appStyles from 'appStyles'; import ManageWishItemScreen from 'ManageWishItemScreen'; import ManageListScreen from 'ManageListScreen'; import ListsScreen from 'ListsScreen'; import WishItemsScreen from 'WishItemsScreen'; import Layout from './components/Layout'; import stores from './stores'; const navItems = [ { title: 'Lists', component: ListsScreen, path: 'lists', }, { title: 'New List', component: ManageListScreen, path: 'lists/create' }, { title: 'Edit List', component: ManageListScreen, path: 'lists/:id/edit' }, { title: 'New Wish', component: ManageWishItemScreen, path: 'wishes/create' }, { title: 'Edit Wish', component: ManageWishItemScreen, path: 'lists/:listId/wishes/:id/edit' }, { title: 'Wishes', component: WishItemsScreen, path: 'lists/:id/wishes' }, ]; const navOptions = {}; navItems.forEach((item) => { const { component: Component, navigationOptions = {}, title } = item; return navOptions[item.title] = { screen(props) { return ( <Layout {...props}> <Component {...props}/> </Layout> ); }, path: item.path, navigationOptions: Object.assign({ title }, navigationOptions) }; }); const Navigator = StackNavigator(navOptions); @observer class AppNavigator extends React.Component { render() { return ( <Root> <Provider {...stores}> <Navigator style={appStyles.content}/> </Provider> </Root> ); } } export default AppNavigator;
src/backward/Widgets/Title.js
sampsasaarela/NativeBase
import React from 'react'; import { Platform, View } from 'react-native'; import { connectStyle } from 'native-base-shoutem-theme'; import mapPropsToStyleNames from '../../Utils/mapPropsToStyleNames'; import NativeBaseComponent from '../Base/NativeBaseComponent'; import { Text } from './Text'; import computeProps from '../../Utils/computeProps'; class Title extends NativeBaseComponent { prepareRootProps() { const type = { fontFamily: this.getTheme().btnFontFamily, fontWeight: (Platform.OS === 'ios') ? '500' : undefined, alignSelf: (Platform.OS === 'ios') ? 'center' : 'flex-start', }; const defaultProps = { style: type, }; return computeProps(this.props, defaultProps); } render() { return ( <View style={{ justifyContent: 'center' }}><Text ref={c => this._root = c} {...this.prepareRootProps()} numberOfLines={1}>{this.props.children}</Text></View> ); } } Title.propTypes = { ...Text.propTypes, style: React.PropTypes.object, }; const StyledTitle = connectStyle('NativeBase.Title', {}, mapPropsToStyleNames)(Title); export { StyledTitle as Title, };
src/utils/createContextWrapper.js
tonylinyy/react-bootstrap
import React from 'react'; /** * Creates new trigger class that injects context into overlay. */ export default function createContextWrapper(Trigger, propName) { return function (contextTypes) { class ContextWrapper extends React.Component { getChildContext() { return this.props.context; } render() { // Strip injected props from below. const {wrapped, context, ...props} = this.props; return React.cloneElement(wrapped, props); } } ContextWrapper.childContextTypes = contextTypes; class TriggerWithContext { render() { const props = {...this.props}; props[propName] = this.getWrappedOverlay(); return ( <Trigger {...props}> {this.props.children} </Trigger> ); } getWrappedOverlay() { return ( <ContextWrapper context={this.context} wrapped={this.props[propName]} /> ); } } TriggerWithContext.contextTypes = contextTypes; return TriggerWithContext; }; }
src/components/Navbar/Navbar/index.js
easingthemes/easingthemes.github.io
/** * * Navbar * */ import React from 'react'; import styles from './styles.global.scss'; import Logo from 'components/navbar/Logo'; import Navigation from 'components/navbar/Navigation'; class Navbar extends React.Component { //------------------------------------------------------------------------------------------------------------------ // React methods //------------------------------------------------------------------------------------------------------------------ /** * * Set the initial state * * @private */ constructor(props) { super(props); this.state = { pluginsInit: false }; } componentDidUpdate (nextProps, nextState) { //console.log('nextState', nextState); //console.log('Navbar did update: ', this.props.path); this.initPlugins(); } componentDidMount() { //console.log('Navbar did mount: ', this.props.path); } initPlugins () { /* -------------------------------------------- CLOSE COLLAPSE MENU ON MOBILE VIEW EXCEPT DROPDOWN -------------------------------------------- */ $('.navbar-collapse ul li a:not(.dropdown-toggle)').on('click',function (event) { $('.navbar-toggle:visible').click(); }); /* -------------------------------------------- STICKY SETTING -------------------------------------------- */ if( $('.navbar-sticky').length > 0){ //$('.navbar-sticky').sticky({ topSpacing: 0 }); $('.navbar-sticky').css('z-index','100'); $('.navbar-sticky').addClass('bg-light'); $('.navbar-sticky').addClass('top-nav-collapse'); } /* -------------------------------------------------------- NAVBAR FIXED TOP ON SCROLL ----------------------------------------------------------- */ const toggleNav = function() { if ($('.navbar').offset().top > 10) { $('.navbar-pasific-toggle').addClass('top-nav-collapse'); } else { $('.navbar-pasific-toggle').removeClass('top-nav-collapse'); } }; if (this.props.path !== '/' && this.props.path !== '/portfolio' && this.props.path !== '/contact') { $('.navbar-pasific-toggle').addClass('top-nav-collapse'); $(window).off('scroll', toggleNav); } else { toggleNav(); //console.log('on'); $(window).on('scroll', toggleNav); } /* -------------------------------------------------------- NAVBAR-INVERSE FIXED TOP ON SCROLL ----------------------------------------------------------- */ if( $('.navbar-pasific-inverse').length > 0 ){ $(window).scroll(function() { if ($('.navbar').offset().top > 10) { $('.navbar-pasific').addClass('top-nav-collapse-inverse'); } else { $('.navbar-pasific').removeClass('top-nav-collapse-inverse'); } }); } } render() { let navBg = ''; if (this.props.path !== '/' && this.props.path !== '/portfolio' && this.props.path !== '/contact') { navBg = 'navbar-standart top-nav-collapse'; } else { navBg = 'navbar-pasific-toggle'; } //const path = this.props.path === '/' ? '' : 'navbar-standart'; //bg-white const style = navBg + ' '; //console.log('style', this.props.path); return ( <nav className={style + ' navbar navbar-pasific navbar-fixed-top navbar-mp megamenu'}> <div className="container-fluid"> <Logo /> <Navigation /> </div> </nav> ); } } export default Navbar;
src/server.js
montemishkin/mishkin_com
// third party imports import express from 'express' import compression from 'compression' import logger from 'morgan' import favicon from 'serve-favicon' import serveStatic from 'serve-static' import React from 'react' import {renderToString} from 'react-dom/server' import Helmet from 'react-helmet' // local imports import { buildDir, publicDir, favicon as faviconPath, } from 'config/projectPaths' import Root from 'views/Root' import renderTemplate from 'templates/index' const server = express() /* Server-wide Middleware */ // compress responses server.use(compression()) // log requests server.use(logger(process.env.NODE_ENV === 'production' ? 'combined' : 'dev')) // serve favicon server.use(favicon(faviconPath)) /* Routing */ // route static files to build and public dirs server.use('/static', serveStatic(buildDir), serveStatic(publicDir)) // any url that hits this server server.all('*', (req, res) => { const renderedComponent = renderToString(<Root />) // see: https://github.com/nfl/react-helmet#server-usage const helmet = Helmet.rewind() const html = renderTemplate({ renderedComponent, title: helmet.title, }) res.send(html) }) export default server
src/App.js
tal87/operationcode_frontend
import React, { Component } from 'react'; import { Route, Router } from 'react-router'; import ReactGA from 'react-ga'; import createHistory from 'history/createBrowserHistory'; import ScrollToTop from 'shared/components/scrollToTop/scrollToTop'; import Home from './scenes/home/home'; const history = createHistory(); ReactGA.initialize('UA-75642413-1'); class App extends Component { componentDidMount() { if (process.env.NODE_ENV === 'production') { // History listening doesn't catch first page load ReactGA.set({ page: history.location.pathname }); ReactGA.pageview(history.location.pathname); history.listen((location) => { ReactGA.set({ page: location.pathname }); ReactGA.pageview(location.pathname); }); } } render() { return ( <Router history={history}> <ScrollToTop> <Route path="/" component={Home} /> </ScrollToTop> </Router> ); } } export default App;
src/view/private/index.js
coma/spotify
import React from 'react'; import style from './index.css'; import Top from './top'; import Nav from './nav'; class PrivateView extends React.Component { render () { return ( <div className={ style.main }> <Top/> <div className={ style.body }> <Nav/> <main className={ style.content }>{ this.props.children }</main> </div> </div> ); } } export default PrivateView;
src/components/Footer/Footer.js
DaveSpringer/bmg-rap-sheets
import React from 'react' import './style/Footer.scss' class Footer extends React.Component { render () { return ( <div className='utility-belt-footer footer hidden-print'> <p>&copy; TM &copy; DC Comics. WB SHIELD: TM; Warner Bros. Entertainment. Inc. (s17). Copyright © 2017 DC Comics. All characters, their distinctive likenesses and related elements featured in this publication are trademarks of DC Comics. Their stories, characters and incidents featured in this publication are entirely fictional.</p> <p>Batman Miniature Game &copy;2008-2017 KNIGHT MODELS - All Rights Reserved.</p> <p>Bruce's Utility Belt &copy;2017 David Springer</p> </div> ) } } export default Footer
src/components/pages/preferences/Images.js
DragonLegend/game
import React from 'react'; import ImagesForm from '../../preferences/ImagesForm'; export default () => ( <div> <h2>Images</h2> <ImagesForm /> </div> );
writeExampleWebpack2Middleware/src/js/App.js
fengnovo/webpack-react
import React from 'react' import Header from './containers/Header' import Body from './containers/Body' import Footer from './containers/Footer' class App extends React.Component { constructor (props) { super(props) } render () { return <div> <Header /> <Body /> <Footer /> </div> } } export default App
src/components/article/LeadingImage.js
garfieldduck/twreporter-react
/* eslint no-unused-vars:0 */ 'use strict' import React from 'react' // eslint-disable-line import ReactDOM from 'react-dom' import classNames from 'classnames' import styles from './LeadingImage.scss' import { getImageSrcSet, replaceStorageUrlPrefix } from '../../utils/' // lodash import get from 'lodash/get' const _ = { get } class LeadingImage extends React.Component { constructor(props) { super(props) this.state = { isMount: false } } componentDidMount() { this.setState({ isMount: true }) } render() { const { size, image, id, description } = this.props let leadingImgClass if (!image) { return null } switch (size) { case 'normal': leadingImgClass = 'leading-img' break case 'extend': leadingImgClass = 'extended-leading-img' break case 'small': leadingImgClass = 'small-leading-img' break default: leadingImgClass = 'leading-img' break } const defaultImgUrl = replaceStorageUrlPrefix(_.get(image, 'tiny.url')) const imgJsx = this.state.isMount ? ( <img src={defaultImgUrl} alt={description} srcSet={getImageSrcSet(image)} /> ) : ( <img src={defaultImgUrl} alt={description} className={styles['img-placeholder']} /> ) return ( <div className={styles[leadingImgClass]}> {imgJsx} </div> ) } } LeadingImage.propTypes = { size: React.PropTypes.string, image: React.PropTypes.object, description: React.PropTypes.string, id: React.PropTypes.string } LeadingImage.defaultProps = { size: 'normal', image: null, description: '', id: '' } export { LeadingImage }
src/schema/test.dataSchema.js
RodgerLai/nodejs-nedb-excel
import React from 'react'; import {Icon} from 'antd'; // 定义某个表的dataSchema, 结构跟querySchema很相似, 见下面的例子 // 注意: 所有的key不能重复 // 这个配置不只决定了table的schema, 也包括用于新增/删除的表单的schema module.exports = [ { key: 'id', // 传递给后端的key title: 'ID', // 前端显示的名字 // 其实dataType对前端的意义不大, 更重要的是生成后端接口时要用到, 所以要和DB中的类型一致 // 对java而言, int/float/varchar/datetime会映射为Long/Double/String/Date dataType: 'int', // 数据类型, 目前可用的: int/float/varchar/datetime // 这一列是否是主键? // 如果不指定主键, 不能update/delete, 但可以insert // 如果指定了主键, insert/update时不能填写主键的值; // 只有int/varchar可以作为主键, 但是实际上主键一般都是自增id primary: true, // 可用的showType: normal/radio/select/checkbox/multiSelect/textarea/image/imageArray/file // FIXME: image/imageArray/file类型暂未实现 showType: 'normal', // 默认是normal, 就是最普通的输入框 showInTable: true, // 这一列是否要在table中展示, 默认true disabled: false, // 表单中这一列是否禁止编辑, 默认false // 扩展接口, 决定了这一列渲染成什么样子 render: (text, record) => text, }, { key: 'name', title: '用户名', dataType: 'varchar', // 对于普通的input框, 可以设置addonBefore/addonAfter placeholder: '请输入用户名', addonBefore: (<Icon type="user"/>), addonAfter: '切克闹', defaultValue: 'foolbear', // 默认值, 只在insert时生效, update时不生效 }, { key: 'weight', title: '体重(千克)', dataType: 'int', min: 10, defaultValue: 70, // 默认值 disabled: true, showInForm: false, // 这一列是否要在表单中展示, 默认true. 这种列一般都是不需要用户输入的, DB就会给一个默认值那种 }, { key: 'gender', title: '性别', dataType: 'int', showType: 'radio', options: [{key: '1', value: '男'}, {key: '2', value: '女'}], defaultValue: '1', disabled: true, }, { key: 'marriage', title: '婚否', dataType: 'varchar', showType: 'select', options: [{key: 'yes', value: '已婚'}, {key: 'no', value: '未婚'}], // 对于dataSchema可以设置校验规则, querySchema不能设置 // 设置校验规则, 参考https://github.com/yiminghe/async-validator#rules validator: [{type: 'string', required: true, message: '必须选择婚否!'}], }, { key: 'interest', title: '兴趣爱好', dataType: 'int', showType: 'checkbox', options: [{key: '1', value: '吃饭'}, {key: '2', value: '睡觉'}, {key: '3', value: '打豆豆'}], defaultValue: ['1', '2'], validator: [{type: 'array', required: true, message: '请至少选择一项兴趣'}], }, { key: 'good', title: '优点', dataType: 'varchar', showType: 'multiSelect', options: [{key: 'lan', value: '懒'}, {key: 'zhai', value: '宅'}], validator: [{type: 'array', required: true, message: '请选择优点'}], }, { key: 'pic1', title: '头像', dataType: 'varchar', showType: 'image', // 后端必须提供图片上传接口 showInTable: false, }, { key: 'pic2', title: '自拍', dataType: 'varchar', showType: 'imageArray', // 上传多张图片 limit: 5, // 最多传几张图片 showInTable: false, }, { key: 'jianli', title: '简历', dataType: 'varchar', showType: 'file', // 文件上传 url: 'xxx', // 要上传的地址 disabled: true, showInTable: false, }, { key: 'desc', title: '个人简介', dataType: 'varchar', showType: 'textarea', // 用于编辑大段的文本 showInTable: false, defaultValue: '个人简介个人简介个人简介', validator: [{type: 'string', max: 20, message: '最长20个字符'}], }, { key: 'score', title: '分数', dataType: 'int', max: 99, min: 9, }, { key: 'gpa', title: 'GPA', dataType: 'float', max: 9.9, placeholder: '哈哈', }, { key: 'birthday', title: '生日', // 对于日期类型要注意下, 在js端日期被表示为yyyy-MM-dd HH:mm:ss的字符串, 在java端日期被表示为java.util.Date对象 // fastjson反序列化时可以自动识别 // 序列化倒是不用特别配置, 看自己需求, fastjson会序列化为一个字符串, 前端原样展示 dataType: 'datetime', // 对于datetime而言, 配置showType是无意义的 placeholder: 'happy!', }, { key: 'xxday', title: 'xx日期', dataType: 'datetime', defaultValue: '2017-01-01 11:22:33', showInTable: false, showInForm: false, // 这个只是测试下...如果一列在table和form中都不出现, 那就不如直接去掉. // 另外showInForm=false时, 很多针对form的字段都没意义了, 比如defaultValue/placeholder/validator等等 }, ];
examples/counter/containers/Root.js
yz89/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import CounterApp from './CounterApp'; import configureStore from '../store/configureStore'; const store = configureStore(); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <CounterApp />} </Provider> ); } }
lib/withData.js
wzalazar/spotify
import React from 'react' import PropsTypes from 'prop-types' import { Provider } from 'react-redux' import initStore from './initStore' import { get } from 'lodash' import ip from 'ip' export default (Component) => ( class extends React.Component { static propTypes = { initialState: PropsTypes.object, } static defaultProps = { initialState: {}, } static async getInitialProps(ctx) { const headers = get(ctx, 'req.headers', {}) ctx.isServer = get(ctx, 'req', false) const currentHost = get(ctx, 'req.headers.host', 'localhost') const host = process.env.NODE_ENV === 'production' ? currentHost : ip.address() const isProduction = process.env.NODE_ENV === 'production' ? true : false const config = { host, isProduction } if (ctx.isServer) { ctx.config = { config } } const { store } = initStore() ctx.store = store const props = { url: { ...ctx.query, pathname: ctx.pathname }, ...await (Component.getInitialProps ? Component.getInitialProps(ctx) : {}), } const state = ctx.store.getState() return { initialState: { ...state, config, }, headers, ...props, } } constructor(props) { super(props) const { store } = initStore(props.initialState) this.store = store } render() { return ( <Provider store={this.store}> <Component {...this.props} /> </Provider> ) } } )
packages/material-ui-icons/legacy/SignalCellularConnectedNoInternet3BarSharp.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M22 8V2L2 22h16V8h4z" /><path d="M18 22V6L2 22h16zm2-12v8h2v-8h-2zm0 12h2v-2h-2v2z" /></React.Fragment> , 'SignalCellularConnectedNoInternet3BarSharp');
examples/huge-apps/app.js
shunitoh/react-router
import React from 'react' import { render } from 'react-dom' import { Router, browserHistory } from 'react-router' import withExampleBasename from '../withExampleBasename' import './stubs/COURSES' const rootRoute = { childRoutes: [ { path: '/', component: require('./components/App'), childRoutes: [ require('./routes/Calendar'), require('./routes/Course'), require('./routes/Grades'), require('./routes/Messages'), require('./routes/Profile') ] } ] } render(( <Router history={withExampleBasename(browserHistory, __dirname)} routes={rootRoute} /> ), document.getElementById('example')) // I've unrolled the recursive directory loop that is happening above to get a // better idea of just what this huge-apps Router looks like, or just look at the // file system :) // // import { Route } from 'react-router' // import App from './components/App' // import Course from './routes/Course/components/Course' // import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar' // import Announcements from './routes/Course/routes/Announcements/components/Announcements' // import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement' // import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar' // import Assignments from './routes/Course/routes/Assignments/components/Assignments' // import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment' // import CourseGrades from './routes/Course/routes/Grades/components/Grades' // import Calendar from './routes/Calendar/components/Calendar' // import Grades from './routes/Grades/components/Grades' // import Messages from './routes/Messages/components/Messages' // render( // <Router> // <Route path="/" component={App}> // <Route path="calendar" component={Calendar} /> // <Route path="course/:courseId" component={Course}> // <Route path="announcements" components={{ // sidebar: AnnouncementsSidebar, // main: Announcements // }}> // <Route path=":announcementId" component={Announcement} /> // </Route> // <Route path="assignments" components={{ // sidebar: AssignmentsSidebar, // main: Assignments // }}> // <Route path=":assignmentId" component={Assignment} /> // </Route> // <Route path="grades" component={CourseGrades} /> // </Route> // <Route path="grades" component={Grades} /> // <Route path="messages" component={Messages} /> // <Route path="profile" component={Calendar} /> // </Route> // </Router>, // document.getElementById('example') // )
app/App.js
mastermel/wwg_battle_tool
import React, { Component } from 'react'; import { createStore } from 'redux'; import { Provider, connect } from 'react-redux'; import { Router, Scene, ActionConst } from 'react-native-router-flux'; import { appReducer } from './Reducers/index'; import { navColor, font } from './Shared/Styles'; import Home from './Scenes/Home/index'; import Units from './Scenes/Units/index'; const store = createStore(appReducer); const ConnectedRouter = connect()(Router); export default class App extends Component { render() { return ( <Provider store={store}> <ConnectedRouter> <Scene key='root' navigationBarStyle={styles.navigationBarStyle} navBarButtonColor={font.color} titleStyle={styles.titleStyle} > <Scene key='home' initial title='Home' component={Home} type={ActionConst.REPLACE} /> <Scene key='units' title='Units' component={Units} /> </Scene> </ConnectedRouter> </Provider> ); } } const styles = { navigationBarStyle: { backgroundColor: navColor, }, titleStyle: { color: font.color, }, };
docs/app/Examples/elements/Reveal/Content/index.js
Rohanhacker/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const RevealContentExamples = () => ( <ExampleSection title='Content'> <ComponentExample title='Visible Content' description='A reveal may contain content that is visible before interaction.' examplePath='elements/Reveal/Content/RevealExampleVisible' /> <ComponentExample title='Hidden Content' description='A reveal may contain content that is hidden before user interaction.' examplePath='elements/Reveal/Content/RevealExampleHidden' /> </ExampleSection> ) export default RevealContentExamples
components/auth/Forget.js
digithun/jamplay-nap
import React from 'react' import PropTypes from 'prop-types' import { gql, graphql } from 'react-apollo' import userProfile from '../userProfile.gql' const Forget = ({ forget }) => { const handleSubmit = e => { e.preventDefault() let email = e.target.elements.email.value if (email === '') { window.alert('Email fields are required.') return false } forget(email) } return ( <form onSubmit={handleSubmit}> <h1>Forget Password (GraphQL)</h1> <input placeholder='email' name='email' defaultValue='[email protected]' /> <button type='submit'>Forget</button> <style jsx>{` form { border-bottom: 1px solid #ececec; padding-bottom: 20px; margin-bottom: 20px; } h1 { font-size: 20px; } input { display: block; margin-bottom: 10px; } `}</style> </form> ) } const forget = gql` mutation forget($email: String!) { forget(email: $email) { status } } ` Forget.propTypes = () => ({ forget: PropTypes.func.isRequired }) export default graphql(forget, { props: ({ mutate }) => ({ forget: email => mutate({ variables: { email }, update: (proxy, { data }) => { // Read the data from our cache for this query. let cached = proxy.readQuery({ query: userProfile }) // User cached.user = cached.user || { _id: null, name: null, status: null, isLinkedWithFacebook: null, __typename: 'User' } cached.user.status = data.forget.status // Write our data back to the cache. proxy.writeQuery({ query: userProfile, data: cached }) } }).catch(err => { window.alert(err.message) }) }) })(Forget)
src/gifPreview/index.js
SodhanaLibrary/react-examples
import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import App from './app'; render( <AppContainer><App/></AppContainer>, document.querySelector("#app")); if (module.hot) { module.hot.accept('./app.js', () => { const App = require('./app.js').default; render( <AppContainer> <App/> </AppContainer>, document.querySelector("#app") ); }); }
src/main.js
ryanturner7/portfolio
import React from 'react' import ReactDom from 'react-dom' import {BrowserRouter, Route} from 'react-router-dom' class App extends React.Component { // constructor constructor(props){ super(props) this.state = { content: '', } this.getApp = this.getApp.bind(this) } //hooks componentDidUpdate(){ console.log('__STATE__', this.state) } //methods getApp(){ return { state: this.state, setState: this.setState.bind(this) } } //render render(){ return ( <main className='app'> <BrowserRouter> <div> </div> </BrowserRouter> </main> ) } } ReactDom.render(<App title='' />, document.getElementById('root'))
app/utils.js
MichelHalmes/sankey
import React from 'react'; import request from 'superagent'; var MIN_LINK_VALUE = 50; function loadData(path) { request .get(path) .end((err, res) => { if (err) { console.log(err); } var links = res.body.links; var nodes = res.body.nodes.map((node, i) => { if (!node.node_id) { node.node_id = i; } return node }); this.setState({nodes, links}); }); } function parseLevelData(level_nodes, level_links, split_level_1){ var node_map = parseLevelNodes(level_nodes, split_level_1); var links = parseLevelLinks(level_links, node_map, split_level_1); var nodes = Array.from(node_map.values()) .filter((node) => node.source_value>MIN_LINK_VALUE || node.target_value>MIN_LINK_VALUE) // .filter((node, index, self) => index === self.findIndex((t) => ( // t.node_id === node.node_id && t.name === node.name // )) // ); return {nodes, links} } function parseLevelNodes(level_nodes, split_level_1) { var node_map = new Map(); var node_count = -1; var prev_level_1 = null; level_nodes.sort((a,b) => a.level_1.localeCompare(b.level_1)); level_nodes.forEach(function(node) { if(node.level_1 == split_level_1) { node_count++; node_map.set(node.level_0, {node_id: node_count, name: node.level_0, source_value: 0, target_value: 0, is_split: true}); } else { if (node.level_1 != prev_level_1) { node_count++; prev_level_1 = node.level_1; } node_map.set(node.level_0, {node_id: node_count, name: node.level_1, source_value: 0, target_value: 0}); } }); return node_map; } function parseLevelLinks(level_links, node_map, split_level_1) { level_links = level_links.map(function(link) { var source = node_map.get(link.source_0); if (!source){ console.log(`The link '${link}'' has the source '${link.source_0}' unspecified in the nodes`); return {delete: true}; // Will be filtered } var target = node_map.get(link.target_0); if (!target){ console.log(`The link '${link}'' has the target '${link.target_0}' unspecified in the nodes`); return {delete: true}; // Will be filtered } if (!split_level_1 || source.is_split || target.is_split) { source.source_value+= link.value; target.target_value+= link.value; return {source: source, target: target, value : link.value} } else { return {delete: true}; // Will be filtered } }); level_links = level_links.filter((link) => ( !link.delete && link.source.node_id != link.target.node_id && link.value > MIN_LINK_VALUE && (link.value > 0.2*link.source.source_value || link.value > 0.2*link.target.target_value) )) .map((link) => ({source: link.source.node_id, target: link.target.node_id, value: link.value}) ) .sort((a, b) => a.source - b.source || a.target - b.target); var links = level_links.reduce(function (acc, curr, idx) { var prev = level_links[idx-1] || {source: -1, target: -1}; if (curr.source == prev.source && curr.target == prev.target) { acc[acc.length - 1].value += curr.value; } else { acc.push(curr); } return acc; }, []); return links; } export { loadData, parseLevelData }
src/fields/InputField.ios.js
MichaelCereda/react-native-form-generator
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import ReactNative from 'react-native'; import {InputComponent} from '../lib/InputComponent'; const {StyleSheet} = ReactNative; export class InputField extends React.Component{ handleValidation(isValid, validationErrors){ this.valid = isValid; this.validationErrors = validationErrors; } setValue(value){ this.refs.fieldComponent.setValue(value) } focus(){ this.refs.fieldComponent.focus() } render(){ return(<InputComponent {...this.props} ref='fieldComponent' onValidation={this.handleValidation.bind(this)} labelStyle={[formStyles.fieldText, this.props.labelStyle]} inputStyle={[formStyles.input, (this.props.multiline)?formStyles.multiline:{}, (this.props.label)?formStyles.textRight:{}, this.props.style ]} containerStyle={[formStyles.fieldContainer, formStyles.horizontalContainer, this.props.containerStyle, ]} /> ) } } InputField.propTypes = { multiline: PropTypes.bool, placeholder:PropTypes.string, } let fieldStyles =StyleSheet.create({ input:{ paddingLeft: 10, paddingRight: 10, }, }); let formStyles = StyleSheet.create({ form:{ }, alignRight:{ marginTop: 7, position:'absolute', right: 10 }, textRight:{ textAlign: 'right' }, multiline:{ lineHeight: 32, fontSize: 34/2, paddingBottom:10 }, separatorContainer:{ // borderTopColor: '#C8C7CC', // borderTopWidth: 1, paddingTop: 35, borderBottomColor: '#C8C7CC', borderBottomWidth: 1, }, fieldsWrapper:{ // borderTopColor: '#afafaf', // borderTopWidth: 1, }, horizontalContainer:{ flexDirection: 'row', justifyContent: 'flex-start' }, fieldContainer:{ borderBottomWidth: 1, borderBottomColor: '#C8C7CC', backgroundColor: 'white', justifyContent: 'center', }, fieldText:{ fontSize: 34/2, paddingLeft: 10, paddingRight: 10, justifyContent: 'center', lineHeight: 32, }, input:{ paddingLeft: 10, paddingRight: 10, }, helpTextContainer:{ marginTop:9, marginBottom: 25, paddingLeft: 20, paddingRight: 20, }, helpText:{ color: '#7a7a7a' } }); {/*<View onLayout={this.handleLayoutChange.bind(this)}> {(this.props.iconLeft) ? this.props.iconLeft : null } {(this.props.label) ? <Text style={formStyles.fieldText} onLayout={this.handleLabelLayoutChange.bind(this)} onPress={this.handleFieldPress.bind(this)} >{this.props.label}</Text> : null } <TextInput {...this.props} ref='inputBox' keyboardType = {this.props.keyboardType} style={[formStyles.input, (this.props.multiline)?formStyles.multiline:{}, (this.props.label)?formStyles.textRight:{}, this.props.style, {height: this.state.inputHeight} ]} onChange={this.handleChange.bind(this)} onFocus={this._scrollToInput.bind(this)} placeholder={this.props.placeholder} value={this.state.value} width={this.state.width-this.state.labelWidth -((this.props.iconRight)?this.props.iconRight.props.size:0) -((this.props.iconLeft)?this.props.iconLeft.props.size:0) } /> {(this.props.iconRight) ? this.props.iconRight : null } </View>*/}
node_modules/react-bootstrap/es/Pagination.js
premcool/getmydeal
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import PaginationButton from './PaginationButton'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { activePage: React.PropTypes.number, items: React.PropTypes.number, maxButtons: React.PropTypes.number, /** * When `true`, will display the first and the last button page when * displaying ellipsis. */ boundaryLinks: React.PropTypes.bool, /** * When `true`, will display the default node value ('&hellip;'). * Otherwise, will display provided node (when specified). */ ellipsis: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]), /** * When `true`, will display the default node value ('&laquo;'). * Otherwise, will display provided node (when specified). */ first: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]), /** * When `true`, will display the default node value ('&raquo;'). * Otherwise, will display provided node (when specified). */ last: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]), /** * When `true`, will display the default node value ('&lsaquo;'). * Otherwise, will display provided node (when specified). */ prev: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]), /** * When `true`, will display the default node value ('&rsaquo;'). * Otherwise, will display provided node (when specified). */ next: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]), onSelect: React.PropTypes.func, /** * You can use a custom element for the buttons */ buttonComponentClass: elementType }; var defaultProps = { activePage: 1, items: 1, maxButtons: 0, first: false, last: false, prev: false, next: false, ellipsis: true, boundaryLinks: false }; var Pagination = function (_React$Component) { _inherits(Pagination, _React$Component); function Pagination() { _classCallCheck(this, Pagination); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Pagination.prototype.renderPageButtons = function renderPageButtons(activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps) { var pageButtons = []; var startPage = void 0; var endPage = void 0; if (maxButtons && maxButtons < items) { startPage = Math.max(Math.min(activePage - Math.floor(maxButtons / 2, 10), items - maxButtons + 1), 1); endPage = startPage + maxButtons - 1; } else { startPage = 1; endPage = items; } for (var page = startPage; page <= endPage; ++page) { pageButtons.push(React.createElement( PaginationButton, _extends({}, buttonProps, { key: page, eventKey: page, active: page === activePage }), page )); } if (ellipsis && boundaryLinks && startPage > 1) { if (startPage > 2) { pageButtons.unshift(React.createElement( PaginationButton, { key: 'ellipsisFirst', disabled: true, componentClass: buttonProps.componentClass }, React.createElement( 'span', { 'aria-label': 'More' }, ellipsis === true ? '\u2026' : ellipsis ) )); } pageButtons.unshift(React.createElement( PaginationButton, _extends({}, buttonProps, { key: 1, eventKey: 1, active: false }), '1' )); } if (ellipsis && endPage < items) { if (!boundaryLinks || endPage < items - 1) { pageButtons.push(React.createElement( PaginationButton, { key: 'ellipsis', disabled: true, componentClass: buttonProps.componentClass }, React.createElement( 'span', { 'aria-label': 'More' }, ellipsis === true ? '\u2026' : ellipsis ) )); } if (boundaryLinks) { pageButtons.push(React.createElement( PaginationButton, _extends({}, buttonProps, { key: items, eventKey: items, active: false }), items )); } } return pageButtons; }; Pagination.prototype.render = function render() { var _props = this.props, activePage = _props.activePage, items = _props.items, maxButtons = _props.maxButtons, boundaryLinks = _props.boundaryLinks, ellipsis = _props.ellipsis, first = _props.first, last = _props.last, prev = _props.prev, next = _props.next, onSelect = _props.onSelect, buttonComponentClass = _props.buttonComponentClass, className = _props.className, props = _objectWithoutProperties(_props, ['activePage', 'items', 'maxButtons', 'boundaryLinks', 'ellipsis', 'first', 'last', 'prev', 'next', 'onSelect', 'buttonComponentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); var buttonProps = { onSelect: onSelect, componentClass: buttonComponentClass }; return React.createElement( 'ul', _extends({}, elementProps, { className: classNames(className, classes) }), first && React.createElement( PaginationButton, _extends({}, buttonProps, { eventKey: 1, disabled: activePage === 1 }), React.createElement( 'span', { 'aria-label': 'First' }, first === true ? '\xAB' : first ) ), prev && React.createElement( PaginationButton, _extends({}, buttonProps, { eventKey: activePage - 1, disabled: activePage === 1 }), React.createElement( 'span', { 'aria-label': 'Previous' }, prev === true ? '\u2039' : prev ) ), this.renderPageButtons(activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps), next && React.createElement( PaginationButton, _extends({}, buttonProps, { eventKey: activePage + 1, disabled: activePage >= items }), React.createElement( 'span', { 'aria-label': 'Next' }, next === true ? '\u203A' : next ) ), last && React.createElement( PaginationButton, _extends({}, buttonProps, { eventKey: items, disabled: activePage >= items }), React.createElement( 'span', { 'aria-label': 'Last' }, last === true ? '\xBB' : last ) ) ); }; return Pagination; }(React.Component); Pagination.propTypes = propTypes; Pagination.defaultProps = defaultProps; export default bsClass('pagination', Pagination);
app/src/components/Synth/PianoKeyNote.js
civa86/web-synth
import React from 'react'; const PianoKeyNote = (props) => { const { note, semiNote, playNoteHandler, stopNoteHandler, playingVoices, octave } = props; function getClassName (color, key) { const voiceLabel = key + '-' + octave; let result = 'key-' + color + ' no-select'; if (playingVoices && playingVoices.indexOf(voiceLabel) !== -1) { result += ' playing'; } return result; } function semiNoteKey () { if (semiNote) { return ( <div className={getClassName('black', semiNote.key)} onMouseDown={(e) => playNoteHandler(e, semiNote.key)} onTouchStart={(e) => playNoteHandler(e, semiNote.key)} onMouseOut={() => stopNoteHandler(null, semiNote.key)} onMouseUp={(e) => stopNoteHandler(e, semiNote.key)} onTouchEnd={(e) => stopNoteHandler(e, semiNote.key)}><span>{semiNote.label}</span> </div> ); } else { return ''; } } return ( <div className={getClassName('white', note.key)} onMouseDown={(e) => playNoteHandler(e, note.key)} onTouchStart={(e) => playNoteHandler(e, note.key)} onMouseOut={() => stopNoteHandler(null, note.key)} onMouseUp={(e) => stopNoteHandler(e, note.key)} onTouchEnd={(e) => stopNoteHandler(e, note.key)}><span>{note.label}</span> {semiNoteKey()} </div> ); }; export default PianoKeyNote;
client/About/Social.js
PicDrop/PicDrop
import React from 'react'; import Github from './Github'; import LinkedIn from './LinkedIn'; class Social extends React.Component { render() { return ( <div> <LinkedIn linkedIn={this.props.linkedIn}/> <Github github={this.props.github}/> </div> ); } } export default Social;
node_modules/expo/src/Modal/ModalHost.js
RahulDesai92/PHR
/* @flow */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, StyleSheet } from 'react-native'; import PureContainer from './PureContainer'; type Layout = { width: number, height: number, }; type LayoutEvent = { nativeEvent: { layout: Layout, }, }; type Renderer = (layout: Layout, key: number) => any; type Props = { children?: any, }; type State = { modals: Array<{ key: number, renderer: Renderer }>, layout: { measured: boolean, } & Layout, }; export const channel = '__$expo_modal_host'; export default class ModalHost extends Component<Props, State> { static childContextTypes = { [channel]: PropTypes.object, }; state = { modals: [], layout: { height: 0, width: 0, measured: false, }, }; getChildContext() { return { [channel]: { register: this._register, }, }; } _currentKey = 0; _register = (renderer: Renderer) => { const key = this._currentKey; this._currentKey++; this.setState(state => ({ modals: [...state.modals, { key, renderer }], })); const update = (r: Renderer) => this.setState(state => ({ modals: state.modals.map( m => (m.key === key ? { key, renderer: r } : m) ), })); const remove = () => this.setState(state => ({ modals: state.modals.filter(m => m.key !== key), })); return { update, remove, }; }; _handleLayout = (e: LayoutEvent) => { const { layout } = e.nativeEvent; if ( layout.height !== this.state.layout.height || layout.width !== this.state.layout.width ) { this.setState({ layout: { ...e.nativeEvent.layout, measured: true } }); } }; render() { return ( <View style={styles.host} onLayout={this._handleLayout}> <PureContainer {...this.props}> {this.props.children} </PureContainer> {this.state.layout.measured ? this.state.modals.map(({ key, renderer }) => { return renderer(this.state.layout, key); }) : null} </View> ); } } const styles = StyleSheet.create({ host: { flex: 1, }, });
src/index.js
bkkeye/redux_carouse
/** * Created by u on 2017/5/20. */ import React from 'react'; import ReactDOM from 'react-dom'; import {createStore,applyMiddleware} from 'redux'; import {Provider} from "react-redux"; import thunk from 'redux-thunk'; import Carousel from "./components/Carousel.jsx"; import reducer from "./reducers"; const store = createStore(reducer,applyMiddleware(thunk)); ReactDOM.render( <Provider store={store}> <Carousel/> </Provider>, document.getElementById('root') )
src/components/SplitIt/SplitDashboard.js
tfrankie88/splitzi_react
import React, { Component } from 'react'; import NavigationSplitIt from '../Navigation/NavigationSplitIt'; import RestaurantSearch from './RestaurantSearch'; import MenuList from './MenuList'; class SplitDashboard extends Component { constructor() { super(); this.state = { menu: [], cart: 0 }; } componentWillMount() { if (localStorage.getItem('token')) { window.localStorage.removeItem('token'); } if(localStorage.getItem('restuarant')) { window.localStorage.removeItem('restaurant'); } } searchRestaurant(term) { fetch(`https://splitzi-api.herokuapp.com/restaurant/name/${term}`) .then(r => r.json()) .then((data) => { console.log('this is data from first fetch', data); this.setState({ menuItems: data.search }) console.log('this is data.id', data.id) fetch(`https://splitzi-api.herokuapp.com/menu/${data.id}/menu`) .then(r => r.json()) .then((menuData) => { console.log(menuData); this.setState({ menu: menuData }); console.log('this is state menu state', this.state.menuItems[0]); }) }) .catch(err => console.log('ERROR', err)); } addToCart(){ this.setState({cart: this.state.cart + 1}, () => { // console.log("this is the cart", this.state.cart); }); } render() { return( <div> <NavigationSplitIt /> <div className="content-container"> <h1 className="search-items-title">where did you <span>eat?</span></h1> <div> <RestaurantSearch searchRestaurant={this.searchRestaurant.bind(this)} /> </div> <div className="item-cards-container"> <MenuList menu={this.state.menu} addToCart={this.addToCart.bind(this)} /> </div> </div> </div> ); } } export default SplitDashboard;
js/example-work.js
sithadmin/my-portfolio
import React from 'react'; import ExampleWorkModal from './example-work-modal'; class ExampleWork extends React.Component { constructor(props) { super(props); this.state = { 'modalOpen': false, 'selectedExample': this.props.work[0] }; this.openModal = this.openModal.bind(this); this.closeModal = this.closeModal.bind(this); } openModal(evt, example) { this.setState({ 'modalOpen': true, 'selectedExample': example }); } closeModal(evt) { this.setState({ 'modalOpen': false }); } render() { return ( <span> <section className="section section--alignCentered section--description"> { this.props.work.map( (example, idx) => { return ( <ExampleWorkBubble example={example} key={idx} openModal={this.openModal} /> ) }) } </section> <ExampleWorkModal example={this.state.selectedExample} open={this.state.modalOpen} closeModal={this.closeModal} /> </span> ) } } class ExampleWorkBubble extends React.Component { render() { let example = this.props.example; return ( <div className="section__exampleWrapper" onClick={(evt) => this.props.openModal(evt, example) }> <div className="section__example"> <img alt="{example.image.desc}" className="section__exampleImage" src={example.image.src}/> <dl className="color--cloud"> <dt className="section__exampleTitle section__text--centered"> {example.title} </dt> <dd></dd> </dl> </div> </div> ) } } export default ExampleWork; export { ExampleWorkBubble };
src/withControl.js
andrewkshim/react-animatronics
// @flow /** * @module withControl */ import React from 'react' import hoistNonReactStatics from 'hoist-non-react-statics' import type { ComponentType } from 'react' import ContextTypes from './internal/context-types' import Control from './Control' import { IS_PRODUCTION } from './internal/constants' import { getDisplayName, isStatelessComponent, isReactComponent, makeError, } from './internal/utils' type Props = { innerRef: Function, }; const withControl = (name: string) => (BaseComponent: ComponentType<{}>) => { if (!IS_PRODUCTION) { if (!isReactComponent(BaseComponent)) { throw makeError( `The withControl() higher-order component must be used to wrap a`, `valid React component.` ); } } class ControlledComponent extends React.Component<Props> { static contextTypes: Object = ContextTypes render() { const { innerRef, ...props } = this.props; return ( <Control name={ name }>{ ({ animatronicStyles, ref }) => <BaseComponent { ...this.props } animatronicStyles={ animatronicStyles } ref={ isStatelessComponent(BaseComponent) ? null : element => { innerRef && innerRef(element); ref(element); } } /> }</Control> ); } } ControlledComponent.displayName = `withControl(${ getDisplayName(BaseComponent) })`; return hoistNonReactStatics(ControlledComponent, BaseComponent); } export default withControl;
examples/universal/client/index.js
keyanzhang/redux
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import configureStore from '../common/store/configureStore' import App from '../common/containers/App' const initialState = window.__INITIAL_STATE__ const store = configureStore(initialState) const rootElement = document.getElementById('app') render( <Provider store={store}> <App/> </Provider>, rootElement )
app/javascript/mastodon/components/modal_root.js
anon5r/mastonon
import React from 'react'; import PropTypes from 'prop-types'; export default class ModalRoot extends React.PureComponent { static propTypes = { children: PropTypes.node, onClose: PropTypes.func.isRequired, }; state = { revealed: !!this.props.children, }; activeElement = this.state.revealed ? document.activeElement : null; handleKeyUp = (e) => { if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27) && !!this.props.children) { this.props.onClose(); } } componentDidMount () { window.addEventListener('keyup', this.handleKeyUp, false); } componentWillReceiveProps (nextProps) { if (!!nextProps.children && !this.props.children) { this.activeElement = document.activeElement; this.getSiblings().forEach(sibling => sibling.setAttribute('inert', true)); } else if (!nextProps.children) { this.setState({ revealed: false }); } } componentDidUpdate (prevProps) { if (!this.props.children && !!prevProps.children) { this.getSiblings().forEach(sibling => sibling.removeAttribute('inert')); this.activeElement.focus(); this.activeElement = null; } if (this.props.children) { requestAnimationFrame(() => { this.setState({ revealed: true }); }); } } componentWillUnmount () { window.removeEventListener('keyup', this.handleKeyUp); } getSiblings = () => { return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node); } setRef = ref => { this.node = ref; } render () { const { children, onClose } = this.props; const { revealed } = this.state; const visible = !!children; if (!visible) { return ( <div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} /> ); } return ( <div className='modal-root' ref={this.setRef} style={{ opacity: revealed ? 1 : 0 }}> <div style={{ pointerEvents: visible ? 'auto' : 'none' }}> <div role='presentation' className='modal-root__overlay' onClick={onClose} /> <div role='dialog' className='modal-root__container'>{children}</div> </div> </div> ); } }
app/javascript/mastodon/features/ui/components/embed_modal.js
tootsuite/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { defineMessages, FormattedMessage, injectIntl } from 'react-intl'; import api from 'mastodon/api'; import IconButton from 'mastodon/components/icon_button'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, }); export default @injectIntl class EmbedModal extends ImmutablePureComponent { static propTypes = { url: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, onError: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, } state = { loading: false, oembed: null, }; componentDidMount () { const { url } = this.props; this.setState({ loading: true }); api().post('/api/web/embed', { url }).then(res => { this.setState({ loading: false, oembed: res.data }); const iframeDocument = this.iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(res.data.html); iframeDocument.close(); iframeDocument.body.style.margin = 0; this.iframe.width = iframeDocument.body.scrollWidth; this.iframe.height = iframeDocument.body.scrollHeight; }).catch(error => { this.props.onError(error); }); } setIframeRef = c => { this.iframe = c; } handleTextareaClick = (e) => { e.target.select(); } render () { const { intl, onClose } = this.props; const { oembed } = this.state; return ( <div className='modal-root__modal report-modal embed-modal'> <div className='report-modal__target'> <IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={16} /> <FormattedMessage id='status.embed' defaultMessage='Embed' /> </div> <div className='report-modal__container embed-modal__container' style={{ display: 'block' }}> <p className='hint'> <FormattedMessage id='embed.instructions' defaultMessage='Embed this status on your website by copying the code below.' /> </p> <input type='text' className='embed-modal__html' readOnly value={oembed && oembed.html || ''} onClick={this.handleTextareaClick} /> <p className='hint'> <FormattedMessage id='embed.preview' defaultMessage='Here is what it will look like:' /> </p> <iframe className='embed-modal__iframe' frameBorder='0' ref={this.setIframeRef} sandbox='allow-same-origin' title='preview' /> </div> </div> ); } }
docs/app/Examples/collections/Breadcrumb/Variations/BreadcrumbExampleMassiveSize.js
clemensw/stardust
import React from 'react' import { Breadcrumb } from 'semantic-ui-react' const BreadcrumbExampleMassiveSize = () => ( <Breadcrumb size='massive'> <Breadcrumb.Section link>Home</Breadcrumb.Section> <Breadcrumb.Divider icon='right chevron' /> <Breadcrumb.Section link>Registration</Breadcrumb.Section> <Breadcrumb.Divider icon='right chevron' /> <Breadcrumb.Section active>Personal Information</Breadcrumb.Section> </Breadcrumb> ) export default BreadcrumbExampleMassiveSize
src/shared/components/idme/idme.js
tal87/operationcode_frontend
import React, { Component } from 'react'; import config from 'config/environment'; import troopImage from 'images/Troop.png'; import styles from './idme.css'; class Idme extends Component { idMe = () => { window.open(`${config.idmeOAuthUrl}?client_id=${config.idmeClientId}&redirect_uri=${config.host}/profile/verify&response_type=token&scope=military&display=popup', '', 'scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,width=750,height=780,top=200,left=200`); }; render() { return ( <div className={styles.wrapper}> <span className={styles.authbtn} role="link" onClick={this.idMe} tabIndex={0}> <img className={styles.authImage} src={troopImage} alt="Verify your status with Id.Me" /> </span> </div> ); } } export default Idme;
jenkins-design-language/src/js/components/material-ui/svg-icons/maps/pin-drop.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsPinDrop = (props) => ( <SvgIcon {...props}> <path d="M18 8c0-3.31-2.69-6-6-6S6 4.69 6 8c0 4.5 6 11 6 11s6-6.5 6-11zm-8 0c0-1.1.9-2 2-2s2 .9 2 2-.89 2-2 2c-1.1 0-2-.9-2-2zM5 20v2h14v-2H5z"/> </SvgIcon> ); MapsPinDrop.displayName = 'MapsPinDrop'; MapsPinDrop.muiName = 'SvgIcon'; export default MapsPinDrop;
actor-apps/app-web/src/app/components/activity/UserProfileContactInfo.react.js
Jaeandroid/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class UserProfileContactInfo extends React.Component { static propTypes = { phones: React.PropTypes.array }; constructor(props) { super(props); } render() { let phones = this.props.phones; let contactPhones = _.map(phones, (phone, i) => { return ( <li className="profile__list__item row" key={i}> <i className="material-icons">call</i> <div className="col-xs"> <span className="contact">+{phone.number}</span> <span className="title">{phone.title}</span> </div> </li> ); }); return ( <ul className="profile__list profile__list--contacts"> {contactPhones} </ul> ); } } export default UserProfileContactInfo;
src/Interpolate.js
Firfi/meteor-react-bootstrap
// https://www.npmjs.org/package/react-interpolate-component // TODO: Drop this in favor of es6 string interpolation import React from 'react'; import ValidComponentChildren from './utils/ValidComponentChildren'; const REGEXP = /\%\((.+?)\)s/; const Interpolate = React.createClass({ displayName: 'Interpolate', propTypes: { format: React.PropTypes.string }, getDefaultProps() { return { component: 'span' }; }, render() { let format = (ValidComponentChildren.hasValidComponent(this.props.children) || (typeof this.props.children === 'string')) ? this.props.children : this.props.format; let parent = this.props.component; let unsafe = this.props.unsafe === true; let props = {...this.props}; delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { let content = format.split(REGEXP).reduce(function(memo, match, index) { let html; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (React.isValidElement(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return React.createElement(parent, props); } else { let kids = format.split(REGEXP).reduce(function(memo, match, index) { let child; if (index % 2 === 0) { if (match.length === 0) { return memo; } child = match; } else { child = props[match]; delete props[match]; } memo.push(child); return memo; }, []); return React.createElement(parent, props, kids); } } }); export default Interpolate;
js/jqwidgets/demos/react/app/datatable/serverpaging/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxDataTable from '../../../jqwidgets-react/react_jqxdatatable.js'; class App extends React.Component { render() { let source = { dataType: 'json', dataFields: [ { name: 'ShipCountry', type: 'string' }, { name: 'ShipCity', type: 'string' }, { name: 'ShipAddress', type: 'string' }, { name: 'ShipName', type: 'string' }, { name: 'Freight', type: 'number' }, { name: 'ShippedDate', type: 'date' } ], root: 'value', url: 'http://services.odata.org/V3/Northwind/Northwind.svc/Orders?$format=json&$callback=?' }; let dataAdapter = new $.jqx.dataAdapter(source, { formatData: (data) => { // update the $skip and $top params of the OData service. // data.pagenum - page number starting from 0. // data.pagesize - page size data.$skip = data.pagenum * data.pagesize; data.$top = data.pagesize; data.$inlinecount = 'allpages'; return data; }, downloadComplete: (data, status, xhr) => { if (!source.totalRecords) { source.totalRecords = parseInt(data['odata.count']); } }, loadError: (xhr, status, error) => { throw new Error('http://services.odata.org: ' + error.toString()); } } ); let columns = [ { text: 'Ship Name', dataField: 'ShipName', width: 300 }, { text: 'Ship Country', hidden: true, dataField: 'ShipCountry', width: 250 }, { text: 'Ship City', dataField: 'ShipCity', width: 150 }, { text: 'Ship Address', dataField: 'ShipAddress' } ]; return ( <div> <h3 style={{ fontSize: 16, fontFamily: 'Verdana' }}>Data Source: 'http://services.odata.org'</h3> <JqxDataTable width={850} source={dataAdapter} altRows={true} pageable={true} columnsResize={true} serverProcessing={true} columns={columns} pagerButtonsCount={10} /> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/containers/Asians/TabControls/PreliminaryRounds/EnterRoundResults/Ballots/Instance/InstanceTabs.js
westoncolemanl/tabbr-web
import React from 'react' import { connect } from 'react-redux' import Tabs, { Tab } from 'material-ui/Tabs' import AppBar from 'material-ui/AppBar' import withStyles from 'material-ui/styles/withStyles' const styles = theme => ({ indicator: { backgroundColor: '#ffffff' } }) export default connect(mapStateToProps)(withStyles(styles)(({ room, value, adjudicatorsById, onChange, classes }) => <AppBar position={'static'} elevation={0} > <Tabs className={'w-100'} value={value} onChange={(e, v) => onChange(v)} scrollable scrollButtons={'auto'} classes={{ indicator: classes.indicator }} > <Tab label={'Room'} value={'room'} /> <Tab label={`${adjudicatorsById[room.chair].firstName} ${adjudicatorsById[room.chair].lastName}`} value={'chair'} /> {room.panels.map(panel => <Tab key={panel} label={`${adjudicatorsById[panel].firstName} ${adjudicatorsById[panel].lastName}`} value={panel} /> )} </Tabs> </AppBar> )) function mapStateToProps (state, ownProps) { return { adjudicatorsById: state.adjudicators.data } }
frontend/src/layouts/CoreLayout/CoreLayout.js
qurben/mopidy-jukebox
import React from 'react' import Header from '../../components/Header' import classes from './CoreLayout.scss' import '../../styles/core.scss' export const CoreLayout = ({ children }) => ( <div className='container text-center'> <Header/> <div className={classes.mainContainer}> {children} </div> </div> ) CoreLayout.propTypes = { children: React.PropTypes.element.isRequired } export default CoreLayout
src/pages/about/index.js
joefraley/ratticusscript
'use strict' import Helmet from 'react-helmet' import React from 'react' const ratPictures = require.context('./assets', true, /rat/) export const Thumbnail = ({ alt, link, source }) => <a href={ link } target="_"> <img src={ require(`./${source}`) } alt={ alt }></img> </a> export const AboutPage = props => <section> <Helmet title="About | RatticusScript" meta={[{ content: 'Some stuff you can pretend to like if you need to make conversation with me.', name: 'description' }]} /> <h1>About Me</h1> <p>I studied analytic philosophy at the University of Colorado, Boulder, and also at Western Washington University. I see everything through a Socratic lens, and it makes me lame at parties. Please reach out to chat about anything you like - I'm always excited to meet new people. Otherwise I wouldn't have a personal website 😘</p> <p>If you'd like to talk, but aren't sure about what, here are some things that have influenced me:</p> <ul> <h2>Philosophy</h2> <div> <Thumbnail link="https://www.overdrive.com/media/1223521/countdown" source="assets/cover-countdown.jpg" alt="Countdown book cover."/> <Thumbnail link="https://www.overdrive.com/media/515281/the-world-without-us" source="assets/cover-world-without-us.jpg" alt="The World Without Us book cover."/> <Thumbnail link="https://www.overdrive.com/media/265875/eating-animals" source="assets/cover-eating-animals.jpg" alt="Eating animals book cover."/> <Thumbnail link="https://www.overdrive.com/media/511535/dominion" source="assets/cover-dominion.jpg" alt="Dominion book cover."/> <Thumbnail link="https://www.overdrive.com/media/1263597/slaughterhouse" source="assets/cover-slaughterhouse.jpg" alt="Slaughterhouse book cover."/> <Thumbnail link="https://www.overdrive.com/media/585585/the-best-of-all-possible-worlds" source="assets/cover-best-of-all-worlds.jpg" alt="Best of All Possible Worlds book cover."/> <Thumbnail link="http://www.physics.princeton.edu/ph115/LQ.pdf" source="assets/cover-the-last-question.jpg" alt="The Last Question book cover."/> <Thumbnail link="http://www.tandon-books.com/Humanities/PL2064%20-%20Ethics%20and%20Technology/(PL2143)%20Elements%20of%20Moral%20Philosophy.pdf" source="assets/cover-elements-of-moral-philosophy.jpg" alt="Elements of Moral Philosophy book cover." /> </div> <li>John Stuart Mill, Jeremy Bentham, Peter Singer, and several other important consquentialists have inspired me. Early on I thought that consquentialism was clearly the craziest possible world view. You can read up on it around here: <ul> <li><a href="http://www.utilitarianism.com/mill1.htm" target="_"><em>Utilitarianism</em> - John Stuart Mill</a></li> <li><a href="http://utilitarianism.com/jeremy-bentham/index.html" target="_"><em>An Introduction to the Principles of Morals and Legislation</em> - Jeremy Bentham</a></li> <li><a href="https://nwveg.org/files/Singer_The_Animal_Liberation_Movement.pdf" target="_"><em>Animal Liberation</em> - Peter Singer</a></li> </ul> </li> <li>There is a deep and yet mysterious connection between the words we use, the concepts they represent, and the material states-of-affairs they pick out. Very little has been written directly on this subject, but good starting points are important figures in the philosophy of language like Bertrand Russel and Saul Kripke. <em>On Denoting</em> is a great place to start. <ul> <li><a href="http://philo.ruc.edu.cn/logic/reading/On%20sense%20and%20reference.pdf" target="_"><em>On Sense and Reference</em> - Gottlob Frege</a></li> <li><a href="http://www.theotodman.com/Kripke_Naming.pdf" target="_"><em>Naming and Necessity</em> - Saul Kripke</a></li> <li><a href="http://www.uvm.edu/~lderosse/courses/lang/Russell(1905).pdf" target="_"><em>On Denoting</em> - Bertrand Russel</a></li> </ul> </li> <li>Many people have written about the problem of evil for traditional Christianity. The best thing you can read about it is probably: <ul> <li><a href="https://www.overdrive.com/media/585585/the-best-of-all-possible-worlds" target="_"><em>The Best of All Possible Worlds: A Story of Philosophers, God, and Evil in the Age of Reason</em> - Steven Nadler</a></li> </ul> </li> <li>The problem of induction is irresolvable. There is no plausible way to salvage it. Accepting that commits you to a leaky world view that empirical evidence alone can't seal. David Hume defined the problem once and for all in his <em>Enquiry Concerning Human Understanding</em>. <ul> <li><a href="http://www.earlymoderntexts.com/assets/pdfs/hume1748.pdf" target="_"><em>Enquiry Concerning Human Understanding</em> - David Hume</a></li> </ul> </li> <li>Perhaps no book has had a larger impact on me than <em>Countdown: Our Last, Best Hope for a Future on Earth?</em> This book changed the entire direction of my life - it is the reason I learned to program in pursuit of a longer lever of influence, and it has shaped more of my personal decisions than anything else I can think of since. I recommend you read it next to its companion <em>The World Witout Us</em> <ul> <li><a href="https://www.overdrive.com/media/515281/the-world-without-us" target="_"><em>The World Without Us</em> - Alan Weisman</a></li> <li><a href="https://www.overdrive.com/media/1223521/countdown" target="_"><em>Countdown: Our Last, Best Hope for a Future on Earth?</em> - Alan Weisman</a></li> </ul> </li> <li>There are many, many people that helped to open my eyes to the intrinsic worth of non-human animals, and the tyranical cruelty with which we treat them. Here's a short list: <ul> <li><a href="https://www.overdrive.com/media/265875/eating-animals" target="_"><em>Eating Animals</em> - Jonath Safran Foer</a></li> <li><a href="https://www.overdrive.com/media/114394/charlottes-web" target="_"><em>Charlotte's Web</em> - E.B. White</a></li> <li><a href="http://www.authorama.com/a-dogs-tale-1.html" target="_"><em>A Dog's Tale</em> - Mark Twain</a></li> <li><a href="http://www.playr.org/play/pokemon_red/420" target="_">Pokémon Red</a></li> <li><a href="https://en.wikipedia.org/wiki/Avatar:_The_Last_Airbender" target="_">Avatar: the Last Airbender</a></li> </ul> </li> <h2>Fiction</h2> <div> <Thumbnail link="https://en.wikipedia.org/wiki/Eternal_Sunshine_of_the_Spotless_Mind" source="assets/movie-eternal-sunshine.jpg" alt="Eternal Sunshine on the Spotless Mind movie poster."/> <Thumbnail link="https://en.wikipedia.org/wiki/Once_(film)" source="assets/movie-once.jpg" alt="Once movie poster" /> <Thumbnail link="https://www.overdrive.com/media/1866841/shining" source="assets/cover-the-shining.jpg" alt="The Shining bespoke cartoon book cover"/> <Thumbnail link="http://www.adultswim.com/videos/rick-and-morty/" source="assets/movie-rick-and-morty.jpg" alt="Rick using a terrified Morty as a human shield"/> <Thumbnail link="https://www.overdrive.com/media/2678033/the-sandman-volume-1" source="assets/comics-sandman.jpg" alt="Sandman Vol.2 book cover"/> <Thumbnail link="https://www.overdrive.com/media/2504933/the-gunslinger" source="assets/cover-dark-tower.jpg" alt="Wizard and Glass, Dark Tower Vol. 4 book cover"/> <Thumbnail link="https://www.overdrive.com/media/2677748/all-star-superman" source="assets/comics-superman.jpg" alt="A benevelont superman holds the word in his hands. Image by Frank Quietly."/> <Thumbnail link="http://www.avclub.com/tv/batman-the-animated-series/" source="assets/comics-batman.jpg" alt="Batman in the shadows, circa Batman: the animated series."/> </div> <li>Some stories that have strongly influenced my views about love and <strong>The Point of Life™</strong> include <em>Eternal Sunshine on the Spotless Mind</em>, <em>Once</em>, <em>The Wonder Years</em>, <em>500 Days of Summer</em>, <em>The Shining</em>, and <em>Adventure Time</em>. They are all beautiful works of fiction.</li> <li>Many works of science-fiction have inspired me, especially time-travel stories generally. Reading The Dark Tower series fundamentally changed the way I think about stories and endings. Sandman, too.</li> <li>Superhero mythology has profoundly influenced me. Superman, Batman, Judge Dredd, and Hellboy especially resonate at my frequency - as well as many others. Brilliant people have said much in their voices. See especially: <ul> <li><a href="http://www.avclub.com/tv/batman-the-animated-series/"><em>Batman: the Animated Series</em></a></li> <li><a href="https://www.overdrive.com/media/2677748/all-star-superman">Grant Morrison's <em>All-Star Superman</em></a></li> </ul> </li> <li><a href="http://comicsalliance.com/author/chris-sims/">Comicsalliance writer and batmanologist Chris Sims</a> has shaped much of the way I approach fiction. <a href="http://moviebob.blogspot.com/">Bob Chipman</a>, formerly of <a href="http://www.escapistmagazine.com/videos/view/escape-to-the-movies">Escape to the Movies on the Escapist</a> has had a similar impact on my approach to film.</li> <h2>Music</h2> <div> <Thumbnail link="https://www.youtube.com/watch?v=IluRBvnYMoY&list=PLDGvrCyjfEatTU8RGi1lNZ5KB75bq6KRV" source="assets/music-daft-punk.jpg" alt="Random Access Memories album cover" /> <Thumbnail link="https://www.youtube.com/watch?v=9NLZCLKppZs&list=PLxfOxxV02Em24f9rdvz8t1OfGAf1TI1I6" source="assets/music-john-mayer-2.jpg" alt="Where the Light Is album cover" /> <Thumbnail link="https://www.youtube.com/watch?v=GeCClzNCfcA&list=PL4y_nGkVeFwslrc5Gw6UKEkxjVdozI0-e" source="assets/music-john-mayer-3.jpg" alt="Battle Studies album cover" /> <Thumbnail link="https://www.youtube.com/watch?v=ktQxEpr_emU&list=PLBAHmVTbbf92bwrFZMlWbSD8Dpm_vYq8a" source="assets/music-justin-timberlake.jpg" alt="Future Sex Love Sounds album cover"/> </div> <li>No musician has influenced me more than John Mayer. He taught me to seek sinceriety in all things, and to value heart above all else in art and expression. One day Daft Punk will go on a US tour again...</li> <h2>Programming and Technology</h2> <div> <Thumbnail link="https://github.com/funjs/book-source" source="assets/cover-functional-javascript.jpg" alt="Functional JavaScript book cover"/> <Thumbnail link="https://github.com/getify/You-Dont-Know-JS" source="assets/cover-you-dont-know-js.jpg" alt="You Don't Know JS: Async and Performance book cover"/> <Thumbnail link="http://eloquentjavascript.net" source="assets/cover-eloquent-javascript.jpg" alt="Eloquent JavaScript: 2nd Edition book cover" /> <Thumbnail link="http://craphound.com/news/2014/12/10/information-doesnt-want-to-be-free-audiobook" source="assets/cover-information-doesnt-want-to-be-free.jpg" alt="Inofrmation Doesn't Want to Be Free book cover"/> </div> <li>I have lots of opinions about the fabric of technology in our lives, especially the internet. It's hard to name particular works that have strongly influenced me, since there are so many little things happening all the time that nudge me this way or that. A great book on the subject is <a href="http://craphound.com/news/2014/12/10/information-doesnt-want-to-be-free-audiobook/">Information Doesn't Want to Be Free</a>.</li> <li>On the subject of programming, <a href="https://github.com/funjs/book-source">Michael Fogus's Functional Javascript</a> forever altered my perspective on the language, as has Kyle Simpson's work, especially <a href="https://github.com/getify/You-Dont-Know-JS">You Don't Know JS</a>.</li> <li>I strongly identify with declarative programming styles, and frameworks like <a href="https://facebook.github.io/react/">React</a> and <a href="http://elm-lang.org/">the Elm architecture</a> have shaped that perspective. Both enjoy positive, intelligent communities full of clever, diverse people.</li> <h2>Rats</h2> <div> { ratPictures.keys().map((file, index) => { const picture = ratPictures(file) return <img key={ index } src={ picture } alt="My rats: Clementine, Jalino, and Pandora"></img> }) } </div> <li>If you've never met rats, you should. They are the model of innocence in this world.</li> </ul> <p>You can also check out <a href="/reading">my reading journal here on this site</a>. I've written about <a href="/posts/2016-09-23">the general architecture for this website here</a>.</p> </section>
src/app/components/DevTools/index.js
omrilitov/react-universal
import React from 'react'; import {createDevTools} from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' > <LogMonitor /> </DockMonitor> );
assets/javascripts/kitten/components/structure/cards/horizontal-project-card/index.js
KissKissBankBank/kitten
import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import styled from 'styled-components' import { pxToRem } from '../../../../helpers/utils/typography' import COLORS from '../../../../constants/colors-config' import { ScreenConfig } from '../../../../constants/screen-config' import { Progress } from '../../../feedback/progress' import { Text } from '../../../typography/text' const StyledCard = styled.a` border: var(--border-width) solid transparent; background-color: ${COLORS.background1}; box-sizing: border-box; height: ${pxToRem(70)}; width: 100%; padding: ${pxToRem(4)}; display: grid; gap: ${pxToRem(5)} ${pxToRem(10)}; grid-template-columns: ${pxToRem(100)} ${pxToRem(110)} 1fr; grid-template-rows: auto repeat(2, 1fr); text-decoration: none; color: ${COLORS.font1}; /* Border Radius should Image border radius (4) plus padding plus border. */ border-radius: calc(${pxToRem(4 + 4)} + var(--border-width)); transition: background-color 0.2s ease, border-color 0.2s ease; &[href]:hover { border-color: var(--color-grey-400); background-color: ${COLORS.background2}; } &[href]:active { border-color: var(--color-grey-500); background-color: ${COLORS.background3}; } &[href]:focus-visible { outline: auto; } .k-HorizontalProjectCard__imageWrapper { grid-column: 1 / span 1; grid-row: 1 / span 3; img { width: ${pxToRem(100)}; height: ${pxToRem(60)}; object-fit: cover; object-position: center; border-radius: var(--border-radius-xs); } } .k-HorizontalProjectCard__title { grid-column: 2 / span 2; grid-row: 1 / 2; margin: 0; line-height: 1.2; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .k-HorizontalProjectCard__description { grid-column: 2 / span 2; grid-row: 2 / 3; margin: 0; line-height: 1; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .k-HorizontalProjectCard__info { grid-column: 2 / span 1; grid-row: 3 / 4; } .k-HorizontalProjectCard__progress { grid-column: 3 / span 1; grid-row: 3 / 4; place-self: center stretch; display: flex; gap: ${pxToRem(5)}; align-items: center; .k-HorizontalProjectCard__progress__ramp { flex: 1 0 calc(100% - ${pxToRem(5 + 46)}); } .k-HorizontalProjectCard__progress__value { flex: 0 0 ${pxToRem(46)}; width: ${pxToRem(46)}; } @media (max-width: ${pxToRem(ScreenConfig.XXS.max)}) { display: none; } } @media (max-width: ${pxToRem(ScreenConfig.XS.max)}) { &.k-HorizontalProjectCard--noProgressOnMobile { .k-HorizontalProjectCard__progress { display: none; } .k-HorizontalProjectCard__info { grid-column: 2 / span 2; } } } ` export const HorizontalProjectCard = ({ href = '#', imageProps = { src: '', alt: '', }, title = '', titleTag = 'h3', description = '', info = null, progress = 0, progressColor = COLORS.primary1, className, noProgressOnMobile = false, noProgress = false, progressLabel = 'progression', ...props }) => { return ( <StyledCard href={href} className={classNames('k-HorizontalProjectCard', className, { 'k-HorizontalProjectCard--noProgressOnMobile': noProgressOnMobile, })} {...props} > <div className="k-HorizontalProjectCard__imageWrapper"> <img {...imageProps} alt={imageProps.alt || ''} /> </div> <Text weight="regular" size="small" as={titleTag} className="k-HorizontalProjectCard__title" > {title} </Text> <Text as="p" weight="light" size="micro" className="k-HorizontalProjectCard__description" > {description} </Text> <div className="k-HorizontalProjectCard__info">{info}</div> {!noProgress && ( <div className="k-HorizontalProjectCard__progress"> <Progress aria-label={progressLabel} value={progress} color={progressColor} rampProps={{ style: { height: 4 } }} className="k-HorizontalProjectCard__progress__ramp" /> <Text weight="light" size="micro" className="k-HorizontalProjectCard__progress__value" > {progress}&nbsp;% </Text> </div> )} </StyledCard> ) } HorizontalProjectCard.propTypes = { href: PropTypes.string, imageProps: PropTypes.object, title: PropTypes.string, titleTag: PropTypes.string, description: PropTypes.string, info: PropTypes.node, progress: PropTypes.number, progressColor: PropTypes.string, progressLabel: PropTypes.string, noProgress: PropTypes.bool, noProgressOnMobile: PropTypes.bool, }
node_modules/react-bootstrap/es/ModalBody.js
geng890518/editor-ui
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var ModalBody = function (_React$Component) { _inherits(ModalBody, _React$Component); function ModalBody() { _classCallCheck(this, ModalBody); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ModalBody.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return ModalBody; }(React.Component); ModalBody.propTypes = propTypes; ModalBody.defaultProps = defaultProps; export default bsClass('modal-body', ModalBody);
app/routes.js
yaolei/Node-Clound
import React from 'react'; import ReactDOM from 'react-dom'; import { HashRouter, Route, Link } from 'react-router-dom'; import Navbar from './components/Navbar'; import App from './components/App'; import Home from './components/Home'; import FooterBar from './components/Footer'; import ChatBar from './components/Chat'; import TableBar from './components/Table'; import JsonBar from './components/reJson'; //<FooterBar /> if(typeof window !== 'undefined') { ReactDOM.render(( <HashRouter> <div> <Navbar /> <Route exact path="/" component={Home} /> <Route exact path="/app" component={App} /> <Route exact path="/chat" component={ChatBar} /> <Route exact path="/table" component={TableBar} /> <Route exact path="/json" component={JsonBar} /> </div> </HashRouter > ), document.getElementById('root')) }
src/.stories/index.js
clauderic/react-infinite-calendar
/* eslint-disable sort-keys */ import React from 'react'; import {addDecorator, storiesOf} from '@kadira/storybook'; import InfiniteCalendar, { Calendar, defaultMultipleDateInterpolation, withDateSelection, withKeyboardSupport, withMultipleDates, withRange, } from '../'; import styles from './stories.scss'; // Date manipulation utils import addDays from 'date-fns/add_days'; import addMonths from 'date-fns/add_months'; import endOfMonth from 'date-fns/end_of_month'; import format from 'date-fns/format'; import isBefore from 'date-fns/is_before'; import subMonths from 'date-fns/sub_months'; const CenterDecorator = story => <div className={styles.center}>{story()}</div>; addDecorator(CenterDecorator); const today = new Date(); storiesOf('Basic settings', module) .add('Default Configuration', () => <InfiniteCalendar />) .add('Initially Selected Date', () => <InfiniteCalendar selected={addDays(today, 5)} />) .add('Blank Initial State', () => <InfiniteCalendar selected={null} />) .add('Min Date', () => ( <InfiniteCalendar min={subMonths(today, 1)} // Minimum month to render minDate={addDays(today, 1)} // Minimum selectable date selected={addDays(today, 5)} /> )) .add('Max Date', () => ( <InfiniteCalendar max={endOfMonth(addMonths(today, 1))} // Maximum rendered month maxDate={today} // Maximum selectable date /> )) .add('Disable Specific Dates', () => ( <InfiniteCalendar disabledDates={[-10, -5, -6, 5, 6, 7, 2].map(amount => addDays(today, amount) )} /> )) .add('Disable Specific Weekdays', () => ( <InfiniteCalendar disabledDays={[0, 6]} /> )); storiesOf('Higher Order Components', module) .add('Range selection', () => ( <InfiniteCalendar selected={{ start: addDays(new Date(), 2), end: addDays(new Date(), 17), }} locale={{ headerFormat: 'MMM Do', }} Component={withRange(withKeyboardSupport(Calendar))} /> )) .add('Multiple date selection', () => { return ( <InfiniteCalendar selected={[addDays(today, -600), addDays(today, -200), today, addDays(today, 50), addDays(today, 400)]} interpolateSelection={defaultMultipleDateInterpolation} Component={withMultipleDates(withKeyboardSupport(Calendar))} /> ); }) .add('Keyboard Support', () => { return <InfiniteCalendar Component={withDateSelection(withKeyboardSupport(Calendar))} />; }); storiesOf('Internationalization', module) .add('Locale', () => ( <InfiniteCalendar locale={{ blank: 'Aucune date sélectionnée', headerFormat: 'dddd, D MMM', locale: require('date-fns/locale/fr'), todayLabel: { long: "Aujourd'hui", short: 'Auj.', }, weekdays: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'], }} /> )) .add('First Day of the Week', () => ( <InfiniteCalendar locale={{ weekStartsOn: 1, }} /> )); storiesOf('Customization', module) .add('Theming', () => ( <InfiniteCalendar theme={{ floatingNav: { background: 'rgba(105, 74, 228, 0.91)', chevron: '#FFA726', color: '#FFF', }, headerColor: 'rgb(127, 95, 251)', selectionColor: 'rgb(146, 118, 255)', textColor: { active: '#FFF', default: '#333', }, weekdayColor: 'rgb(146, 118, 255)', }} /> )) .add('Flexible Size', () => ( <InfiniteCalendar width={'94%'} height={window.innerHeight - 147} rowHeight={70} /> )) .add('Select Year First', () => ( <InfiniteCalendar display={'years'} selected={null} /> )) .add('Dynamic Selection Color', () => ( <InfiniteCalendar selected={addDays(today, -1)} theme={{ selectionColor: date => { return isBefore(date, today) ? '#EC6150' : '#559FFF'; }, }} /> )); storiesOf('Display Options', module) .add('Landscape Layout', () => ( <InfiniteCalendar displayOptions={{ layout: 'landscape', }} width={600} height={350} /> )) .add('Disable Header', () => ( <InfiniteCalendar displayOptions={{ showHeader: false, }} /> )) .add('Disable Header Animation', () => ( <InfiniteCalendar displayOptions={{ shouldHeaderAnimate: false, }} /> )) .add('Disable Month Overlay', () => ( <InfiniteCalendar displayOptions={{ showOverlay: false, }} /> )) .add('Disable Floating Today Helper', () => ( <InfiniteCalendar displayOptions={{ showTodayHelper: false, }} /> )) .add('Hide Months in Year Selection', () => ( <InfiniteCalendar display={'years'} displayOptions={{ showMonthsForYears: false, }} /> )) .add('Hide Weekdays Helper', () => ( <InfiniteCalendar displayOptions={{ showWeekdays: false, }} /> )); storiesOf('Events', module) .add('On Select', () => ( <InfiniteCalendar onSelect={date => alert(`You selected: ${format(date, 'ddd, MMM Do YYYY')}`)} /> )) .add('On Scroll', () => [ <label key="label">Check your console logs.</label>, <InfiniteCalendar key="calendar" onScroll={scrollTop => console.info('onScroll() – Scroll top:', scrollTop)} />, ]);
src/components/App.js
TorinoMeteo/tm-realtime-map
import React from 'react' import { browserHistory, Router } from 'react-router' import { Provider } from 'react-redux' import PropTypes from 'prop-types' class App extends React.Component { static propTypes = { store: PropTypes.object.isRequired, routes: PropTypes.array.isRequired } shouldComponentUpdate () { return false } render () { return ( <Provider store={this.props.store}> <div style={{ height: '100%' }}> <Router history={browserHistory} children={this.props.routes} /> </div> </Provider> ) } } export default App
packages/react-dom/src/server/ReactPartialRenderer.js
syranide/react
/** * Copyright (c) 2013-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. * * @flow */ import type {ReactElement} from 'shared/ReactElementType'; import type { ReactProvider, ReactConsumer, ReactContext, } from 'shared/ReactTypes'; import React from 'react'; import emptyFunction from 'fbjs/lib/emptyFunction'; import emptyObject from 'fbjs/lib/emptyObject'; import hyphenateStyleName from 'fbjs/lib/hyphenateStyleName'; import invariant from 'fbjs/lib/invariant'; import lowPriorityWarning from 'shared/lowPriorityWarning'; import memoizeStringOnly from 'fbjs/lib/memoizeStringOnly'; import warning from 'fbjs/lib/warning'; import checkPropTypes from 'prop-types/checkPropTypes'; import describeComponentFrame from 'shared/describeComponentFrame'; import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState'; import {warnAboutDeprecatedLifecycles} from 'shared/ReactFeatureFlags'; import { REACT_FRAGMENT_TYPE, REACT_STRICT_MODE_TYPE, REACT_ASYNC_MODE_TYPE, REACT_CALL_TYPE, REACT_RETURN_TYPE, REACT_PORTAL_TYPE, REACT_PROVIDER_TYPE, REACT_CONTEXT_TYPE, } from 'shared/ReactSymbols'; import { createMarkupForCustomAttribute, createMarkupForProperty, createMarkupForRoot, } from './DOMMarkupOperations'; import escapeTextForBrowser from './escapeTextForBrowser'; import { Namespaces, getIntrinsicNamespace, getChildNamespace, } from '../shared/DOMNamespaces'; import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes'; import assertValidProps from '../shared/assertValidProps'; import dangerousStyleValue from '../shared/dangerousStyleValue'; import isCustomComponent from '../shared/isCustomComponent'; import omittedCloseTags from '../shared/omittedCloseTags'; import warnValidStyle from '../shared/warnValidStyle'; import {validateProperties as validateARIAProperties} from '../shared/ReactDOMInvalidARIAHook'; import {validateProperties as validateInputProperties} from '../shared/ReactDOMNullInputValuePropHook'; import {validateProperties as validateUnknownProperties} from '../shared/ReactDOMUnknownPropertyHook'; // Based on reading the React.Children implementation. TODO: type this somewhere? type ReactNode = string | number | ReactElement; type FlatReactChildren = Array<null | ReactNode>; type toArrayType = (children: mixed) => FlatReactChildren; const toArray = ((React.Children.toArray: any): toArrayType); let currentDebugStack; let currentDebugElementStack; let getStackAddendum = emptyFunction.thatReturns(''); let describeStackFrame = emptyFunction.thatReturns(''); let validatePropertiesInDevelopment = (type, props) => {}; let setCurrentDebugStack = (stack: Array<Frame>) => {}; let pushElementToDebugStack = (element: ReactElement) => {}; let resetCurrentDebugStack = () => {}; if (__DEV__) { validatePropertiesInDevelopment = function(type, props) { validateARIAProperties(type, props); validateInputProperties(type, props); validateUnknownProperties(type, props, /* canUseEventSystem */ false); }; describeStackFrame = function(element): string { const source = element._source; const type = element.type; const name = getComponentName(type); const ownerName = null; return describeComponentFrame(name, source, ownerName); }; currentDebugStack = null; currentDebugElementStack = null; setCurrentDebugStack = function(stack: Array<Frame>) { const frame: Frame = stack[stack.length - 1]; currentDebugElementStack = ((frame: any): FrameDev).debugElementStack; // We are about to enter a new composite stack, reset the array. currentDebugElementStack.length = 0; currentDebugStack = stack; ReactDebugCurrentFrame.getCurrentStack = getStackAddendum; }; pushElementToDebugStack = function(element: ReactElement) { if (currentDebugElementStack !== null) { currentDebugElementStack.push(element); } }; resetCurrentDebugStack = function() { currentDebugElementStack = null; currentDebugStack = null; ReactDebugCurrentFrame.getCurrentStack = null; }; getStackAddendum = function(): null | string { if (currentDebugStack === null) { return ''; } let stack = ''; let debugStack = currentDebugStack; for (let i = debugStack.length - 1; i >= 0; i--) { const frame: Frame = debugStack[i]; let debugElementStack = ((frame: any): FrameDev).debugElementStack; for (let ii = debugElementStack.length - 1; ii >= 0; ii--) { stack += describeStackFrame(debugElementStack[ii]); } } return stack; }; } let didWarnDefaultInputValue = false; let didWarnDefaultChecked = false; let didWarnDefaultSelectValue = false; let didWarnDefaultTextareaValue = false; let didWarnInvalidOptionChildren = false; const didWarnAboutNoopUpdateForComponent = {}; const didWarnAboutBadClass = {}; const didWarnAboutDeprecatedWillMount = {}; const didWarnAboutUndefinedDerivedState = {}; const didWarnAboutUninitializedState = {}; const valuePropNames = ['value', 'defaultValue']; const newlineEatingTags = { listing: true, pre: true, textarea: true, }; function getComponentName(type) { return typeof type === 'string' ? type : typeof type === 'function' ? type.displayName || type.name : null; } // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name const VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset const validatedTagCache = {}; function validateDangerousTag(tag) { if (!validatedTagCache.hasOwnProperty(tag)) { invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag); validatedTagCache[tag] = true; } } const processStyleName = memoizeStringOnly(function(styleName) { return hyphenateStyleName(styleName); }); function createMarkupForStyles(styles): string | null { let serialized = ''; let delimiter = ''; for (const styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } const isCustomProperty = styleName.indexOf('--') === 0; const styleValue = styles[styleName]; if (__DEV__) { if (!isCustomProperty) { warnValidStyle(styleName, styleValue, getStackAddendum); } } if (styleValue != null) { serialized += delimiter + processStyleName(styleName) + ':'; serialized += dangerousStyleValue( styleName, styleValue, isCustomProperty, ); delimiter = ';'; } } return serialized || null; } function warnNoop( publicInstance: React$Component<any, any>, callerName: string, ) { if (__DEV__) { const constructor = publicInstance.constructor; const componentName = (constructor && getComponentName(constructor)) || 'ReactClass'; const warningKey = componentName + '.' + callerName; if (didWarnAboutNoopUpdateForComponent[warningKey]) { return; } warning( false, '%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName, ); didWarnAboutNoopUpdateForComponent[warningKey] = true; } } function shouldConstruct(Component) { return Component.prototype && Component.prototype.isReactComponent; } function getNonChildrenInnerMarkup(props) { const innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { return innerHTML.__html; } } else { const content = props.children; if (typeof content === 'string' || typeof content === 'number') { return escapeTextForBrowser(content); } } return null; } function flattenTopLevelChildren(children: mixed): FlatReactChildren { if (!React.isValidElement(children)) { return toArray(children); } const element = ((children: any): ReactElement); if (element.type !== REACT_FRAGMENT_TYPE) { return [element]; } const fragmentChildren = element.props.children; if (!React.isValidElement(fragmentChildren)) { return toArray(fragmentChildren); } const fragmentChildElement = ((fragmentChildren: any): ReactElement); return [fragmentChildElement]; } function flattenOptionChildren(children: mixed): string { let content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. React.Children.forEach(children, function(child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else { if (__DEV__) { if (!didWarnInvalidOptionChildren) { didWarnInvalidOptionChildren = true; warning( false, 'Only strings and numbers are supported as <option> children.', ); } } } }); return content; } function maskContext(type, context) { const contextTypes = type.contextTypes; if (!contextTypes) { return emptyObject; } const maskedContext = {}; for (const contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; } function checkContextTypes(typeSpecs, values, location: string) { if (__DEV__) { checkPropTypes(typeSpecs, values, location, 'Component', getStackAddendum); } } function processContext(type, context) { const maskedContext = maskContext(type, context); if (__DEV__) { if (type.contextTypes) { checkContextTypes(type.contextTypes, maskedContext, 'context'); } } return maskedContext; } const STYLE = 'style'; const RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null, suppressHydrationWarning: null, }; function createOpenTagMarkup( tagVerbatim: string, tagLowercase: string, props: Object, namespace: string, makeStaticMarkup: boolean, isRootElement: boolean, ): string { let ret = '<' + tagVerbatim; for (const propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } let propValue = props[propKey]; if (propValue == null) { continue; } if (propKey === STYLE) { propValue = createMarkupForStyles(propValue); } let markup = null; if (isCustomComponent(tagLowercase, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = createMarkupForCustomAttribute(propKey, propValue); } } else { markup = createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (makeStaticMarkup) { return ret; } if (isRootElement) { ret += ' ' + createMarkupForRoot(); } return ret; } function validateRenderResult(child, type) { if (child === undefined) { invariant( false, '%s(...): Nothing was returned from render. This usually means a ' + 'return statement is missing. Or, to render nothing, ' + 'return null.', getComponentName(type) || 'Component', ); } } function resolve( child: mixed, context: Object, ): {| child: mixed, context: Object, |} { let element: ReactElement; let Component; let publicContext; let inst, queue, replace; let updater; let initialState; let oldQueue, oldReplace; let nextState, dontMutate; let partial, partialState; let childContext; let childContextTypes, contextKey; while (React.isValidElement(child)) { // Safe because we just checked it's an element. element = ((child: any): ReactElement); if (__DEV__) { pushElementToDebugStack(element); } Component = element.type; if (typeof Component !== 'function') { break; } publicContext = processContext(Component, context); queue = []; replace = false; updater = { isMounted: function(publicInstance) { return false; }, enqueueForceUpdate: function(publicInstance) { if (queue === null) { warnNoop(publicInstance, 'forceUpdate'); return null; } }, enqueueReplaceState: function(publicInstance, completeState) { replace = true; queue = [completeState]; }, enqueueSetState: function(publicInstance, currentPartialState) { if (queue === null) { warnNoop(publicInstance, 'setState'); return null; } queue.push(currentPartialState); }, }; if (shouldConstruct(Component)) { inst = new Component(element.props, publicContext, updater); if (typeof Component.getDerivedStateFromProps === 'function') { if (__DEV__) { if (inst.state === null || inst.state === undefined) { const componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutUninitializedState[componentName]) { warning( false, '%s: Did not properly initialize state during construction. ' + 'Expected state to be an object, but it was %s.', componentName, inst.state === null ? 'null' : 'undefined', ); didWarnAboutUninitializedState[componentName] = true; } } } partialState = Component.getDerivedStateFromProps.call( null, element.props, inst.state, ); if (__DEV__) { if (partialState === undefined) { const componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutUndefinedDerivedState[componentName]) { warning( false, '%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName, ); didWarnAboutUndefinedDerivedState[componentName] = true; } } } if (partialState != null) { inst.state = Object.assign({}, inst.state, partialState); } } } else { if (__DEV__) { if ( Component.prototype && typeof Component.prototype.render === 'function' ) { const componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutBadClass[componentName]) { warning( false, "The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName, ); didWarnAboutBadClass[componentName] = true; } } } inst = Component(element.props, publicContext, updater); if (inst == null || inst.render == null) { child = inst; validateRenderResult(child, Component); continue; } } inst.props = element.props; inst.context = publicContext; inst.updater = updater; initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } if ( typeof inst.UNSAFE_componentWillMount === 'function' || typeof inst.componentWillMount === 'function' ) { if (typeof inst.componentWillMount === 'function') { if (__DEV__) { if ( warnAboutDeprecatedLifecycles && inst.componentWillMount.__suppressDeprecationWarning !== true ) { const componentName = getComponentName(Component) || 'Unknown'; if (!didWarnAboutDeprecatedWillMount[componentName]) { lowPriorityWarning( false, '%s: componentWillMount() is deprecated and will be ' + 'removed in the next major version. Read about the motivations ' + 'behind this change: ' + 'https://fb.me/react-async-component-lifecycle-hooks' + '\n\n' + 'As a temporary workaround, you can rename to ' + 'UNSAFE_componentWillMount instead.', componentName, ); didWarnAboutDeprecatedWillMount[componentName] = true; } } } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for any component with the new gDSFP. if (typeof Component.getDerivedStateFromProps !== 'function') { inst.componentWillMount(); } } if ( typeof inst.UNSAFE_componentWillMount === 'function' && typeof Component.getDerivedStateFromProps !== 'function' ) { // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for any component with the new gDSFP. inst.UNSAFE_componentWillMount(); } if (queue.length) { oldQueue = queue; oldReplace = replace; queue = null; replace = false; if (oldReplace && oldQueue.length === 1) { inst.state = oldQueue[0]; } else { nextState = oldReplace ? oldQueue[0] : inst.state; dontMutate = true; for (let i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { partial = oldQueue[i]; partialState = typeof partial === 'function' ? partial.call(inst, nextState, element.props, publicContext) : partial; if (partialState != null) { if (dontMutate) { dontMutate = false; nextState = Object.assign({}, nextState, partialState); } else { Object.assign(nextState, partialState); } } } inst.state = nextState; } } else { queue = null; } } child = inst.render(); if (__DEV__) { if (child === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. child = null; } } validateRenderResult(child, Component); if (typeof inst.getChildContext === 'function') { childContextTypes = Component.childContextTypes; if (typeof childContextTypes === 'object') { childContext = inst.getChildContext(); for (contextKey in childContext) { invariant( contextKey in childContextTypes, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', getComponentName(Component) || 'Unknown', contextKey, ); } } else { warning( false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', getComponentName(Component) || 'Unknown', ); } } if (childContext) { context = Object.assign({}, context, childContext); } } return {child, context}; } type Frame = { type: mixed, domNamespace: string, children: FlatReactChildren, childIndex: number, context: Object, footer: string, }; type FrameDev = Frame & { debugElementStack: Array<ReactElement>, }; class ReactDOMServerRenderer { stack: Array<Frame>; exhausted: boolean; // TODO: type this more strictly: currentSelectValue: any; previousWasTextNode: boolean; makeStaticMarkup: boolean; providerStack: Array<?ReactProvider<any>>; providerIndex: number; constructor(children: mixed, makeStaticMarkup: boolean) { const flatChildren = flattenTopLevelChildren(children); const topFrame: Frame = { type: null, // Assume all trees start in the HTML namespace (not totally true, but // this is what we did historically) domNamespace: Namespaces.html, children: flatChildren, childIndex: 0, context: emptyObject, footer: '', }; if (__DEV__) { ((topFrame: any): FrameDev).debugElementStack = []; } this.stack = [topFrame]; this.exhausted = false; this.currentSelectValue = null; this.previousWasTextNode = false; this.makeStaticMarkup = makeStaticMarkup; // Context (new API) this.providerStack = []; // Stack of provider objects this.providerIndex = -1; } pushProvider<T>(provider: ReactProvider<T>): void { this.providerIndex += 1; this.providerStack[this.providerIndex] = provider; const context: ReactContext<any> = provider.type.context; context.currentValue = provider.props.value; } popProvider<T>(provider: ReactProvider<T>): void { if (__DEV__) { warning( this.providerIndex > -1 && provider === this.providerStack[this.providerIndex], 'Unexpected pop.', ); } this.providerStack[this.providerIndex] = null; this.providerIndex -= 1; const context: ReactContext<any> = provider.type.context; if (this.providerIndex < 0) { context.currentValue = context.defaultValue; } else { // We assume this type is correct because of the index check above. const previousProvider: ReactProvider<any> = (this.providerStack[ this.providerIndex ]: any); context.currentValue = previousProvider.props.value; } } read(bytes: number): string | null { if (this.exhausted) { return null; } let out = ''; while (out.length < bytes) { if (this.stack.length === 0) { this.exhausted = true; break; } const frame: Frame = this.stack[this.stack.length - 1]; if (frame.childIndex >= frame.children.length) { const footer = frame.footer; out += footer; if (footer !== '') { this.previousWasTextNode = false; } this.stack.pop(); if (frame.type === 'select') { this.currentSelectValue = null; } else if ( frame.type != null && frame.type.type != null && frame.type.type.$$typeof === REACT_PROVIDER_TYPE ) { const provider: ReactProvider<any> = (frame.type: any); this.popProvider(provider); } continue; } const child = frame.children[frame.childIndex++]; if (__DEV__) { setCurrentDebugStack(this.stack); } out += this.render(child, frame.context, frame.domNamespace); if (__DEV__) { // TODO: Handle reentrant server render calls. This doesn't. resetCurrentDebugStack(); } } return out; } render( child: ReactNode | null, context: Object, parentNamespace: string, ): string { if (typeof child === 'string' || typeof child === 'number') { const text = '' + child; if (text === '') { return ''; } if (this.makeStaticMarkup) { return escapeTextForBrowser(text); } if (this.previousWasTextNode) { return '<!-- -->' + escapeTextForBrowser(text); } this.previousWasTextNode = true; return escapeTextForBrowser(text); } else { let nextChild; ({child: nextChild, context} = resolve(child, context)); if (nextChild === null || nextChild === false) { return ''; } else if (!React.isValidElement(nextChild)) { if (nextChild != null && nextChild.$$typeof != null) { // Catch unexpected special types early. const $$typeof = nextChild.$$typeof; invariant( $$typeof !== REACT_PORTAL_TYPE, 'Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.', ); // Catch-all to prevent an infinite loop if React.Children.toArray() supports some new type. invariant( false, 'Unknown element-like object type: %s. This is likely a bug in React. ' + 'Please file an issue.', ($$typeof: any).toString(), ); } const nextChildren = toArray(nextChild); const frame: Frame = { type: null, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '', }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.stack.push(frame); return ''; } // Safe because we just checked it's an element. const nextElement = ((nextChild: any): ReactElement); const elementType = nextElement.type; if (typeof elementType === 'string') { return this.renderDOM(nextElement, context, parentNamespace); } switch (elementType) { case REACT_STRICT_MODE_TYPE: case REACT_ASYNC_MODE_TYPE: case REACT_FRAGMENT_TYPE: { const nextChildren = toArray( ((nextChild: any): ReactElement).props.children, ); const frame: Frame = { type: null, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '', }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.stack.push(frame); return ''; } case REACT_CALL_TYPE: case REACT_RETURN_TYPE: invariant( false, 'The experimental Call and Return types are not currently ' + 'supported by the server renderer.', ); // eslint-disable-next-line-no-fallthrough default: break; } if (typeof elementType === 'object' && elementType !== null) { switch (elementType.$$typeof) { case REACT_PROVIDER_TYPE: { const provider: ReactProvider<any> = (nextChild: any); const nextProps = provider.props; const nextChildren = toArray(nextProps.children); const frame: Frame = { type: provider, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '', }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.pushProvider(provider); this.stack.push(frame); return ''; } case REACT_CONTEXT_TYPE: { const consumer: ReactConsumer<any> = (nextChild: any); const nextProps: any = consumer.props; const nextValue = consumer.type.currentValue; const nextChildren = toArray(nextProps.children(nextValue)); const frame: Frame = { type: nextChild, domNamespace: parentNamespace, children: nextChildren, childIndex: 0, context: context, footer: '', }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.stack.push(frame); return ''; } default: break; } } let info = ''; if (__DEV__) { const owner = nextElement._owner; if ( elementType === undefined || (typeof elementType === 'object' && elementType !== null && Object.keys(elementType).length === 0) ) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; } const ownerName = owner ? getComponentName(owner) : null; if (ownerName) { info += '\n\nCheck the render method of `' + ownerName + '`.'; } } invariant( false, 'Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + 'but got: %s.%s', elementType == null ? elementType : typeof elementType, info, ); } } renderDOM( element: ReactElement, context: Object, parentNamespace: string, ): string { const tag = element.type.toLowerCase(); let namespace = parentNamespace; if (parentNamespace === Namespaces.html) { namespace = getIntrinsicNamespace(tag); } if (__DEV__) { if (namespace === Namespaces.html) { // Should this check be gated by parent namespace? Not sure we want to // allow <SVG> or <mATH>. warning( tag === element.type, '<%s /> is using uppercase HTML. Always use lowercase HTML tags ' + 'in React.', element.type, ); } } validateDangerousTag(tag); let props = element.props; if (tag === 'input') { if (__DEV__) { ReactControlledValuePropTypes.checkPropTypes( 'input', props, getStackAddendum, ); if ( props.checked !== undefined && props.defaultChecked !== undefined && !didWarnDefaultChecked ) { warning( false, '%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', 'A component', props.type, ); didWarnDefaultChecked = true; } if ( props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultInputValue ) { warning( false, '%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', 'A component', props.type, ); didWarnDefaultInputValue = true; } } props = Object.assign( { type: undefined, }, props, { defaultChecked: undefined, defaultValue: undefined, value: props.value != null ? props.value : props.defaultValue, checked: props.checked != null ? props.checked : props.defaultChecked, }, ); } else if (tag === 'textarea') { if (__DEV__) { ReactControlledValuePropTypes.checkPropTypes( 'textarea', props, getStackAddendum, ); if ( props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultTextareaValue ) { warning( false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', ); didWarnDefaultTextareaValue = true; } } let initialValue = props.value; if (initialValue == null) { let defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. let textareaChildren = props.children; if (textareaChildren != null) { if (__DEV__) { warning( false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.', ); } invariant( defaultValue == null, 'If you supply `defaultValue` on a <textarea>, do not pass children.', ); if (Array.isArray(textareaChildren)) { invariant( textareaChildren.length <= 1, '<textarea> can only have at most one child.', ); textareaChildren = textareaChildren[0]; } defaultValue = '' + textareaChildren; } if (defaultValue == null) { defaultValue = ''; } initialValue = defaultValue; } props = Object.assign({}, props, { value: undefined, children: '' + initialValue, }); } else if (tag === 'select') { if (__DEV__) { ReactControlledValuePropTypes.checkPropTypes( 'select', props, getStackAddendum, ); for (let i = 0; i < valuePropNames.length; i++) { const propName = valuePropNames[i]; if (props[propName] == null) { continue; } const isArray = Array.isArray(props[propName]); if (props.multiple && !isArray) { warning( false, 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, '', // getDeclarationErrorAddendum(), ); } else if (!props.multiple && isArray) { warning( false, 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, '', // getDeclarationErrorAddendum(), ); } } if ( props.value !== undefined && props.defaultValue !== undefined && !didWarnDefaultSelectValue ) { warning( false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', ); didWarnDefaultSelectValue = true; } } this.currentSelectValue = props.value != null ? props.value : props.defaultValue; props = Object.assign({}, props, { value: undefined, }); } else if (tag === 'option') { let selected = null; const selectValue = this.currentSelectValue; const optionChildren = flattenOptionChildren(props.children); if (selectValue != null) { let value; if (props.value != null) { value = props.value + ''; } else { value = optionChildren; } selected = false; if (Array.isArray(selectValue)) { // multiple for (let j = 0; j < selectValue.length; j++) { if ('' + selectValue[j] === value) { selected = true; break; } } } else { selected = '' + selectValue === value; } props = Object.assign( { selected: undefined, children: undefined, }, props, { selected: selected, children: optionChildren, }, ); } } if (__DEV__) { validatePropertiesInDevelopment(tag, props); } assertValidProps(tag, props, getStackAddendum); let out = createOpenTagMarkup( element.type, tag, props, namespace, this.makeStaticMarkup, this.stack.length === 1, ); let footer = ''; if (omittedCloseTags.hasOwnProperty(tag)) { out += '/>'; } else { out += '>'; footer = '</' + element.type + '>'; } let children; const innerMarkup = getNonChildrenInnerMarkup(props); if (innerMarkup != null) { children = []; if (newlineEatingTags[tag] && innerMarkup.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> out += '\n'; } out += innerMarkup; } else { children = toArray(props.children); } const frame = { domNamespace: getChildNamespace(parentNamespace, element.type), type: tag, children, childIndex: 0, context: context, footer: footer, }; if (__DEV__) { ((frame: any): FrameDev).debugElementStack = []; } this.stack.push(frame); this.previousWasTextNode = false; return out; } } export default ReactDOMServerRenderer;
packages/bonde-admin/src/pages/app.js
ourcities/rebu-client
import React from 'react' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' import DevTools from '@/components/dev-tools' import '@/styles/main.scss' import { TechnicalIssues } from '@/components/error/index' import { ZendeskWidget } from '@/components/external-services' import { GoogleFontsLoader } from '@/components/fonts' import NotificationSystem from '@/components/notification-system' import AccountRegisterPage from './public/account-register' import SubscriptionEditPage from './public/subscription-edit' import LoggedRoute from './admin' const AuthExample = () => ( <div> <Router> <Switch> <Route exact path='/register' component={AccountRegisterPage} /> <Route exact path='/subscriptions/:id/edit' component={SubscriptionEditPage} /> <Route path='/' component={LoggedRoute} /> <Route component={TechnicalIssues} /> </Switch> </Router> {process.env.NODE_ENV !== 'production' ? <DevTools /> : <div></div>} <ZendeskWidget /> <NotificationSystem /> <GoogleFontsLoader fonts='Source Sans Pro' /> </div> ) export default AuthExample
src/WorkWeek.js
intljusticemission/react-big-calendar
import PropTypes from 'prop-types' import React from 'react' import Week from './Week' import TimeGrid from './TimeGrid' function workWeekRange(date, options) { return Week.range(date, options).filter( d => [6, 0].indexOf(d.getDay()) === -1 ) } class WorkWeek extends React.Component { render() { let { date, ...props } = this.props let range = workWeekRange(date, this.props) return <TimeGrid {...props} range={range} eventOffset={15} /> } } WorkWeek.propTypes = { date: PropTypes.instanceOf(Date).isRequired, } WorkWeek.defaultProps = TimeGrid.defaultProps WorkWeek.range = workWeekRange WorkWeek.navigate = Week.navigate WorkWeek.title = (date, { localizer }) => { let [start, ...rest] = workWeekRange(date, { localizer }) return localizer.format({ start, end: rest.pop() }, 'dayRangeHeaderFormat') } export default WorkWeek
project-setup/libs/react-router/src/index.js
kasiriveni/practice
import React from 'react'; import {render} from 'react-dom'; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; import Hello from './components/welcome'; import {Home,About,Topics} from './components/menu'; const root =document.getElementById("root"); render( <Router> <div> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> <li> <Link to="/topics">Topics</Link> </li> </ul> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/topics" component={Topics} /> <Hello/> </div> </Router>, root )
docs/src/app/components/pages/discover-more/Community.js
frnk94/material-ui
import React from 'react'; import Title from 'react-title-component'; import MarkdownElement from '../../MarkdownElement'; import communityText from './community.md'; const Community = () => ( <div> <Title render={(previousTitle) => `Community - ${previousTitle}`} /> <MarkdownElement text={communityText} /> </div> ); export default Community;
src/routes/bbs/Category/index.js
pmg1989/dva-admin
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'dva' import { checkPower } from 'utils' import { ADD, UPDATE, DELETE } from 'constants/options' import CategoryList from './List' import CategorySearch from './Search' import CategoryModal from './ModalForm' function Category ({ location, curPowers, dispatch, bbsCategory, modal, loading }) { const addPower = checkPower(ADD, curPowers) const updatePower = checkPower(UPDATE, curPowers) const deletePower = checkPower(DELETE, curPowers) const { field, keyword } = location.query const searchProps = { field, keyword, addPower, onSearch (fieldsValue) { dispatch({ type: 'bbsCategory/query', payload: { current: 1, // pageSize: 10, ...fieldsValue, }, }) }, onAdd () { dispatch({ type: 'modal/showModal', payload: { type: 'create', }, }) }, } const listProps = { bbsCategory, loading, updatePower, deletePower, onPageChange (fieldsValue) { dispatch({ type: 'bbsCategory/query', payload: { ...fieldsValue }, }) }, onDeleteItem (id) { dispatch({ type: 'bbsCategory/delete', payload: { id } }) }, onEditItem (item) { dispatch({ type: 'modal/showModal', payload: { type: 'update', curItem: item, }, }) }, } const modalProps = { modal, loading, onOk (data) { dispatch({ type: data.cid ? 'bbsCategory/update' : 'bbsCategory/create', payload: { curItem: data, }, }) }, onCancel () { dispatch({ type: 'modal/hideModal' }) }, } return ( <div className="content-inner"> <CategorySearch {...searchProps} /> <CategoryList {...listProps} /> <CategoryModal {...modalProps} /> </div> ) } Category.propTypes = { bbsCategory: PropTypes.object.isRequired, location: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, curPowers: PropTypes.array.isRequired, modal: PropTypes.object.isRequired, loading: PropTypes.bool.isRequired, } function mapStateToProps ({ bbsCategory, modal, loading }) { return { bbsCategory, modal, loading: loading.models.bbsCategory } } export default connect(mapStateToProps)(Category)
src/views/hr-view/components/ul.js
vynogradskyi/resume
import React from 'react'; import styles from 'css-modules/hr-view/ul.scss'; import {li_types as types} from "appConstants"; import classnames from 'classnames'; //components import Li from './li'; export default ({points, type, className}) => { return ( <ul className={classnames(styles.ul, className || '')}> {points.map((point, i) => { let customLi = getCusomLi(type); return ( <Li text={point} key={i} customLi={customLi && customLi(point)}/> ) }) } </ul> ) } const getCusomLi = type => { switch (type) { case types.coding: return codingLi; case types.social: return socialLi; default: return null; } }; const socialLi = point => { let aParam = {}; if(!point.nohref){ aParam.href = point.url; } if(!point.noTarget){ aParam.target = '_blank'; } return ( <a {...aParam}> <span className={classnames(styles.site, 'text-grey')}>{`${point.site} / `}</span> {point.value} </a> ) }; const codingLi = point => { return ( <span> {point.title} <span className={classnames(styles.level, 'text-grey')}>{` (${point.level})`}</span> </span> ) }
src/js/sections/Title1.js
BavoG/onesupportdocu
import React from 'react'; import classnames from 'classnames'; import Headline from 'grommet/components/Headline'; import Box from 'grommet/components/Box'; import InfographicSection from '../components/InfographicSection'; import PlatformAndroid from 'grommet/components/icons/base/PlatformAndroid'; import Anchor from 'grommet/components/Anchor'; const CLASS_ROOT = "title-section"; export default function Title1 () { const classes = classnames([ CLASS_ROOT, `${CLASS_ROOT}--left-align`, `${CLASS_ROOT}--column-reverse` ]); return ( <InfographicSection className={classes} direction="row" colorIndex="accent-1"> <Box className={`${CLASS_ROOT}__col-2`} direction="column" alignContent="start"> <Headline className={`${CLASS_ROOT}__title`} size="medium"> Visit the <Anchor href="https://play.google.com/store/apps/details?id=com.hpeit.mobile.support&hl=en" target="_blank">play store</Anchor> and install. That is all folks! </Headline> <Headline className={`${CLASS_ROOT}__desc`} size="small"> p.s. you can click the little android to take you there </Headline> </Box> <Box pad={{vertical: "medium", between: "medium"}} direction="column" className={`${CLASS_ROOT}__col-1`}justify="center"> <Anchor href="https://play.google.com/store/apps/details?id=com.hpeit.mobile.support&hl=en" target="_blank"> <PlatformAndroid size="huge" colorIndex="grey-1" /> </Anchor> </Box> </InfographicSection> ); };
client/src/react/journal/Journal.js
charlesj/Apollo
import React from 'react' import { connect, } from 'react-redux' import MarkdownRenderer from 'react-markdown-renderer' import PropTypes from 'prop-types' import { journalActions, } from '../../redux/actions' import { journalSelectors, } from '../../redux/selectors' import { NotifySuccess, } from '../../services/notifier' import { Page, LoadMoreButton, Tag, AddButton, } from '../_controls' import JournalEntryForm from './JournalEntryForm' import './logs.css' function EntryDisplay(props) { const { entry, } = props return ( <div className="note"> <div className="createdTime">{entry.createdAtDisplay}</div> <div className="content"> <MarkdownRenderer markdown={entry.note} /> </div> <div className="tags"> {entry.tags && entry.tags.map((t, i) => { return <Tag key={i} name={t} /> })} </div> </div> ) } EntryDisplay.propTypes = { entry: PropTypes.object.isRequired, } function EntryListDisplay(props) { return ( <div> {props.entries.map((entry) => { return <EntryDisplay entry={entry} key={entry.id} /> })} </div> ) } EntryListDisplay.propTypes = { entries: PropTypes.array.isRequired, } class Journal extends React.Component { constructor(props) { super(props) this.state = { addNote: true, } } componentDidMount() { const { loadEntries, entries, } = this.props loadEntries(entries.length) } handleNewEntry(formResult) { const { saveEntry, } = this.props saveEntry({ note: formResult.note, tags: formResult.unifiedTags.split(','), }) NotifySuccess('Added note') this.setState({ addNote: false, }) } render() { const { entries, loadEntries, total, } = this.props const { addNote, } = this.state return ( <Page> {!addNote && ( <AddButton onClick={() => this.setState({ addNote: !addNote, })} noun="Entry" /> )} {addNote && ( <JournalEntryForm onCancel={() => this.setState({ addNote: !addNote, })} onSubmit={formResult => this.handleNewEntry(formResult)} /> )} <EntryListDisplay entries={entries} /> <div> {total} Total Entries {entries.length} Loaded </div> <LoadMoreButton onClick={() => loadEntries(entries.length)} /> </Page> ) } } Journal.propTypes = { entries: PropTypes.array.isRequired, total: PropTypes.number.isRequired, loadEntries: PropTypes.func.isRequired, saveEntry: PropTypes.func.isRequired, } function mapStateToProps(state) { const entries = journalSelectors.all(state) return { entries, total: state.journal.total, } } function mapDispatchToProps(dispatch) { return { loadEntries: start => dispatch(journalActions.load({ start, })), saveEntry: entry => dispatch(journalActions.save(entry)), } } export default connect(mapStateToProps, mapDispatchToProps)(Journal)
src/containers/DevToolsWindow.js
fforres/coworks_client_side
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; export default createDevTools( <LogMonitor /> );
src/svg-icons/maps/local-cafe.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalCafe = (props) => ( <SvgIcon {...props}> <path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM2 21h18v-2H2v2z"/> </SvgIcon> ); MapsLocalCafe = pure(MapsLocalCafe); MapsLocalCafe.displayName = 'MapsLocalCafe'; export default MapsLocalCafe;
setup/src/universal/features/user/auth/components/ResetPasswordForm/index.js
ch-apptitude/goomi
/** * * ResetPasswordForm * */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Form } from 'react-form'; import { Row, Col } from 'react-flexbox-grid'; import Theme from 'assets/theme'; import Box from 'features/common_ui/components/Box'; import { GreenButton } from 'features/common_ui/components/Button'; import Field from 'features/common_ui/form/Field'; import validate from './validate'; import messages from './messages'; class ResetPasswordForm extends Component { renderForm = ({ submitForm }) => { return ( <form onSubmit={submitForm} name="ResetPasswordForm"> <Box> <Field type="password" field="password" label={messages.password} autoFocus /> <Field type="password" field="repassword" label={messages.repassword} /> </Box> <Box smallHeight borderTop> <Row middle="xs"> <Col xs={12}> <GreenButton type="submit" message={messages.save} fitWidth /> </Col> </Row> </Box> </form> ); }; render() { const { onSubmit, onChange } = this.props; return ( <Form onSubmit={onSubmit} validate={validate} onChange={onChange}> {this.renderForm} </Form> ); } } ResetPasswordForm.defaultProps = { onChange: () => {}, onSubmit: () => {}, }; ResetPasswordForm.propTypes = { onSubmit: PropTypes.func, onChange: PropTypes.func, }; export default ResetPasswordForm;
examples/todomvc/index.js
wong2/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; import 'todomvc-app-css/index.css'; const store = configureStore(); React.render( <Provider store={store}> {() => <App />} </Provider>, document.getElementById('root') );
src/renderer/components/TitleBarShim.js
digidem/ecuador-map-editor
import React from 'react' import { remote } from 'electron' import styled from 'styled-components' const TitleBarArea = styled.div` position: relative; height: 22px; ` // Create a space for MacOS title bar buttons on a frameless Window const TitleBarShim = () => { const win = remote.getCurrentWindow() const titleBarSize = win.getSize()[1] - win.getContentSize()[1] if (titleBarSize > 0) return null return <TitleBarArea /> } export default TitleBarShim