path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/NotFoundPage.js
oded-soffrin/gkm_viewer
import React from 'react'; import { Link } from 'react-router'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
frontend/components/AppRoutes.js
heekzz/PowerHour
'use strict'; import React from 'react'; import { Router, browserHistory } from 'react-router'; import routes from '../routes'; export default class AppRoutes extends React.Component { render() { return ( <Router history={browserHistory} routes={routes} onUpdate={() => window.scrollTo(0, 0)}/> ); } }
fixtures/ssr/src/index.js
silvestrijonathan/react
import React from 'react'; import {hydrate} from 'react-dom'; import App from './components/App'; hydrate(<App assets={window.assetManifest} />, document);
client/my-sites/media-library/list-plan-promo.js
allendav/wp-calypso
/** * External dependencies */ import React from 'react'; import page from 'page'; import analytics from 'analytics'; import { preventWidows } from 'lib/formatting'; /** * Internal dependencies */ const EmptyContent = require( 'components/empty-content' ), Button = require( 'components/button' ); module.exports = React.createClass( { displayName: 'MediaLibraryListPlanPromo', propTypes: { site: React.PropTypes.object, filter: React.PropTypes.string }, getTitle: function() { switch ( this.props.filter ) { case 'videos': return this.translate( 'Upload Videos', { textOnly: true, context: 'Media upload plan needed' } ); break; case 'audio': return this.translate( 'Upload Audio', { textOnly: true, context: 'Media upload plan needed' } ); break; default: return this.translate( 'Upload Media', { textOnly: true, context: 'Media upload plan needed' } ); } }, getSummary: function() { switch ( this.props.filter ) { case 'videos': return preventWidows( this.translate( 'To upload video files to your site, upgrade your plan.', { textOnly: true, context: 'Media upgrade promo' } ), 2 ); break; case 'audio': return preventWidows( this.translate( 'To upload audio files to your site, upgrade your plan.', { textOnly: true, context: 'Media upgrade promo' } ), 2 ); break; default: return preventWidows( this.translate( 'To upload audio and video files to your site, upgrade your plan.', { textOnly: true, context: 'Media upgrade promo' } ), 2 ); } }, viewPlansPage: function() { const { slug = '' } = this.props.site; analytics.tracks.recordEvent( 'calypso_media_plans_button_click' ); page( `/plans/${ slug }` ); }, render: function() { const action = ( <Button className="button is-primary" onClick={ this.viewPlansPage }>{ this.translate( 'See Plans' ) }</Button> ); return ( <EmptyContent title={ this.getTitle() } line={ this.getSummary() } action={ action } illustration={ '' } /> ); } } );
app/addons/fauxton/notifications/components/NotificationCenterPanel.js
michellephung/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import PropTypes from 'prop-types'; import React from 'react'; import {TransitionMotion, spring, presets} from 'react-motion'; import NotificationPanelRow from './NotificationPanelRow'; export default class NotificationCenterPanel extends React.Component { static propTypes = { isVisible: PropTypes.bool.isRequired, filter: PropTypes.string.isRequired, notifications: PropTypes.array.isRequired, hideNotificationCenter: PropTypes.func.isRequired, selectNotificationFilter: PropTypes.func.isRequired, clearAllNotifications: PropTypes.func.isRequired, clearSingleNotification: PropTypes.func.isRequired }; getNotifications = (items) => { let notifications; if (!items.length && !this.props.notifications.length) { notifications = <li className="no-notifications"> No notifications. </li>; } else { notifications = items .map(({key, data: notification, style}) => { return ( <NotificationPanelRow item={notification} filter={this.props.filter} clearSingleNotification={this.props.clearSingleNotification} key={key} style={style} /> ); }); } return ( <ul className="notification-list"> {notifications} </ul> ); }; getStyles = (prevItems = []) => { const styles = this.props.notifications .map(notification => { let item = prevItems.find(style => style.key === (notification.notificationId.toString())); let style = !item ? {opacity: 0, height: 0} : false; if (!style && (notification.type === this.props.filter || this.props.filter === 'all')) { style = { opacity: spring(1, presets.stiff), height: spring(61, presets.stiff) }; } else if (notification.type !== this.props.filter) { style = { opacity: spring(0, presets.stiff), height: spring(0, presets.stiff) }; } return { key: notification.notificationId.toString(), style, data: notification }; }); return styles; }; render() { if (!this.props.isVisible && this.props.style.x === 0) { // panelClasses += ' visible'; return null; } const filterClasses = { all: 'flex-body', success: 'flex-body', error: 'flex-body', info: 'flex-body' }; filterClasses[this.props.filter] += ' selected'; const maskClasses = `notification-page-mask ${((this.props.isVisible) ? ' visible' : '')}`; const panelClasses = 'notification-center-panel flex-layout flex-col visible'; return ( <div id="notification-center"> <div className={panelClasses} style={{transform: `translate(${this.props.style.x}px)`}}> <header className="flex-layout flex-row"> <span className="fonticon fonticon-bell" /> <h1 className="flex-body">Notifications</h1> <button type="button" onClick={this.props.hideNotificationCenter}>×</button> </header> <ul className="notification-filter flex-layout flex-row"> <li className={filterClasses.all} title="All notifications" data-filter="all" onClick={() => this.props.selectNotificationFilter('all')}>All</li> <li className={filterClasses.success} title="Success notifications" data-filter="success" onClick={() => this.props.selectNotificationFilter('success')}> <span className="fonticon fonticon-ok-circled" /> </li> <li className={filterClasses.error} title="Error notifications" data-filter="error" onClick={() => this.props.selectNotificationFilter('error')}> <span className="fonticon fonticon-attention-circled" /> </li> <li className={filterClasses.info} title="Info notifications" data-filter="info" onClick={() => this.props.selectNotificationFilter('info')}> <span className="fonticon fonticon-info-circled" /> </li> </ul> <div className="flex-body"> <TransitionMotion styles={this.getStyles}> {this.getNotifications} </TransitionMotion> </div> <footer> <input type="button" value="Clear All" className="btn btn-small btn-secondary" onClick={this.props.clearAllNotifications} /> </footer> </div> <div className={maskClasses} onClick={this.props.hideNotificationCenter}></div> </div> ); } }
client/main.js
jabhishek/react-express-webpack-boilerplate
import React from 'react'; import ReactDOM from 'react-dom'; import {Router } from 'react-router'; import routes from './routes'; import Main from './Main.less'; // eslint-disable-line no-unused-vars import createBrowserHistory from 'history/lib/createBrowserHistory'; ReactDOM.render( ( <Router history={createBrowserHistory()}> {routes} </Router> ), document.getElementById('root') );
app/static/js/App.js
NordicSHIFT/NordicSHIFT
// App.js import React, { Component } from 'react'; import Main from './components/Main'; class App extends Component { render() { return ( <div> <Main /> </div> ); } } export default App;
react/liveevent/components/PowerupCount.js
jaredhasenklein/the-blue-alliance
import React from 'react' import PropTypes from 'prop-types' const PowerupCount = (props) => { const { color, type, count, played, isCenter, } = props const tooltipTitle = type.charAt(0).toUpperCase() + type.slice(1) return ( <div className={`powerupCountContainer ${isCenter ? 'powerupCountContainerCenter' : ''} ${count !== 0 ? `${color}Count${count}` : ''} ${played ? color : ''}`}> <img src={`/images/2018_${type}.png`} className="powerupIcon" role="presentation" rel="tooltip" title={tooltipTitle} /> <div className={`powerCube ${count > 2 ? 'powerCubeActive' : ''}`} /> <div className={`powerCube ${count > 1 ? 'powerCubeActive' : ''}`} /> <div className={`powerCube ${count > 0 ? 'powerCubeActive' : ''}`} /> </div> ) } PowerupCount.propTypes = { color: PropTypes.string.isRequired, type: PropTypes.string.isRequired, count: PropTypes.number.isRequired, played: PropTypes.bool.isRequired, isCenter: PropTypes.bool, } export default PowerupCount
app/index.js
pengfu/react-resume
/** * Created by chang_su on 2017/5/15. */ import React from 'react'; import ReactDOM from 'react-dom'; require('./style/normalize.css') require('./style/app.css') require ('./style/fontello/css/fontello.css') require('./style/transition.css') import App from './components/App.jsx'; ReactDOM.render(<App />, document.getElementById('root'));
src/components/Calculator/Calculator.js
Dynatos/personal-website
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import NavBar from "../NavBar/NavBar"; import CalculatorButtons from "./CalculatorButtons"; export default class Calculator extends Component { handleNumberClick(operand) { this.props.pushNumber(operand); } handleOperator(operator) { this.props.setOperator(operator); } handleCalculate() { this.props.calculateValue(); } handleReset() { this.props.resetCalc(); } addPeriod() { this.props.addPeriod(); } render() { const { currentStateOfApplication } = this.props; return( <div> <NavBar /> <CalculatorButtons numberClick={(operand) => this.handleNumberClick(operand)} calculateClick={() => this.handleCalculate()} resetClick={() => this.handleReset()} setOperator={(operator) => this.handleOperator(operator)} periodClick={() => this.addPeriod()} currentState={currentStateOfApplication} /> </div> ); } } Calculator.propTypes = { pushNumber: PropTypes.func.isRequired, setOperator: PropTypes.func.isRequired, calculateValue: PropTypes.func.isRequired, resetCalc: PropTypes.func.isRequired, addPeriod: PropTypes.func.isRequired, currentStateOfApplication: PropTypes.object.isRequired };
src/components/ShareExperience/WorkExperiencesForm/WorkInfo/IsEmployed.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import RadioDefault from 'common/form/RadioDefault'; import Select from 'common/form/Select'; import Unit from 'common/form/Unit'; import InputTitle from '../../common/InputTitle'; import { isEmployedOptions, jobEndingTimeYearOptions, jobEndingTimeMonthOptions, } from '../../common/optionMap'; import styles from './IsEmployed.module.css'; const IsEmployed = ({ idPrefix4Radio, isCurrentlyEmployed, jobEndingTimeYear, jobEndingTimeMonth, onIsCurrentlyEmployed, onJobEndingTimeYear, onJobEndingTimeMonth, }) => ( <div className={styles.wrapper}> <div> <InputTitle text="你現在在職嗎?" must /> <div className={styles.radios}> {isEmployedOptions.map(option => ( <RadioDefault idPrefix={idPrefix4Radio} key={option.value} label={option.label} value={option.value} onChange={onIsCurrentlyEmployed} checked={isCurrentlyEmployed === option.value} /> ))} </div> </div> {isCurrentlyEmployed === 'no' ? ( <div> <InputTitle text="離職時間" must /> <div className={styles.selects}> <Select options={jobEndingTimeYearOptions} value={jobEndingTimeYear} onChange={e => onJobEndingTimeYear(Number(e.target.value))} /> <Unit marginRight>年</Unit> <Select options={jobEndingTimeMonthOptions} value={jobEndingTimeMonth} onChange={e => onJobEndingTimeMonth(Number(e.target.value))} /> <Unit>月</Unit> </div> </div> ) : null} </div> ); IsEmployed.propTypes = { idPrefix4Radio: PropTypes.string, isCurrentlyEmployed: PropTypes.string, jobEndingTimeYear: PropTypes.number, jobEndingTimeMonth: PropTypes.number, onIsCurrentlyEmployed: PropTypes.func, onJobEndingTimeYear: PropTypes.func, onJobEndingTimeMonth: PropTypes.func, }; export default IsEmployed;
docs/src/components/Home/Preface/Preface.js
seek-oss/seek-style-guide
import React from 'react'; import { PageBlock, Section, Columns, Text } from 'seek-style-guide/react'; export default () => ( <PageBlock> <Section header> <Text hero>A principled design process</Text> </Section> <Section> <Text> SEEK have developed 10 principles that describe the fundamental goals the design team consider when applying their minds to new design challenges or refining existing work. Their purpose is to enable the creation of content that will assist our users to complete tasks easily and hopefully enjoy the experience. </Text> </Section> <Columns> <div> <Section> <Text subheading>Design with empathy</Text> <Text> Understand our customers and end users better than they understand themselves. </Text> </Section> <Section> <Text subheading> A Seek interaction is transparent, honest and trustworthy </Text> <Text> A user experience at Seek should be true to the brand & true to how people want to be treated. “If we want users to like our software, we should design it to behave like a likeable person.” – Alan Cooper </Text> </Section> <Section> <Text subheading> Use persuasive design to achieve business goals </Text> <Text> It is not enough that our design is usable, it should be used in a way that encourages users towards the goals of SEEK. A registered user action is more valuable than an anonymous one, a searchable profile is more useful than a hidden one. </Text> </Section> <Section> <Text subheading>Content is king</Text> <Text> A person’s focus should be on their content, not on the UI. Help people work without interference. </Text> </Section> </div> <div> <Section> <Text subheading>Simplicity is powerful</Text> <Text> A minimalist form and function keeps users focused on their goals without distraction. It improves on-screen responsiveness as well as being suited to small-screen implementations. </Text> </Section> <Section> <Text subheading>Data informs design</Text> <Text> “One accurate measurement is worth more than a thousand expert opinions.” – Grace Hopper </Text> </Section> <Section> <Text subheading>Consistency matters</Text> <Text> Appearance follows behaviour (Form follows function). Designed elements should look like they behave—someone should be able to predict how an interface element will behave merely by looking at it. Embrace consistency, but not homogeneity. If something looks the same it should always act the same. </Text> </Section> <Section> <Text subheading>Accessible design is good design</Text> <Text> In principle Seek design should be usable on all devices by all of the people in all situations. Design is simple, touch friendly and clear and aims for AA accessibility. </Text> </Section> </div> <div> <Section> <Text subheading>Make it mine</Text> <Text> The jobseeking experience is highly personal one that takes place over extended periods of time. The experience should align to the way that users conduct their jobseeking, allowing them to continue where they left off. </Text> </Section> <Section> <Text subheading>Don’t make users think</Text> <Text> Observation shows that users do not read instructions. Interactions should be task focused, eliminating decision points and generally use one clear call to action. </Text> </Section> </div> </Columns> </PageBlock> );
client/src/app/components/forms/SignupForm.js
mtiger2k/graphql-tutorial
import React, { Component } from 'react'; import { reduxForm, Field } from 'redux-form'; import { renderTextField } from './formHelpers' const validate = values => { const errors = {} if (!values.dispName) { errors.dispName = 'Required' } if (!values.username) { errors.username = 'Required' } if (!values.role) { errors.role = 'Required' } if (!values.password) { errors.password = 'Required' } else if (values.password.length < 4) { errors.password = 'Must be 4 characters or more' } if (values.confirmPassword !== values.password) { errors.confirmPassword = 'Must match password' } return errors } class SignupForm extends Component { render() { const { handleSubmit, error } = this.props; return ( <div className="register-box"> <div className="register-logo"> <a href="../../index2.html"><b>Admin</b>LTE</a> </div> <div className="register-box-body"> <p className="login-box-msg">Register a new membership</p> <form onSubmit={handleSubmit}> {error && <div className="alert alert-danger">{error}</div>} <Field name="dispName" type="text" component={renderTextField} label="用户名"/> <Field name="username" type="text" component={renderTextField} label="登录名"/> <Field name="password" type="password" component={renderTextField} label="密码"/> <Field name="confirm_password" type="password" component={renderTextField} label="确认密码"/> <div className="row"> <div className="col-xs-8"> <div className="checkbox icheck"> <label> <input type="checkbox"/> I agree to the <a href="#">terms</a> </label> </div> </div> <div className="col-xs-4"> <button type="submit" className="btn btn-primary btn-block btn-flat">Register</button> </div> </div> </form> <a href="/login" className="text-center">I already have a membership</a> </div> </div> ); } } // Decorate the form component export default reduxForm({ form: 'signupForm', validate })(SignupForm);
src/components/game/ScoresTable.js
marc-ed-raffalli/geo-game
import React from 'react'; import ScoreCorrect from '../../containers/ScoreCorrect'; import ScoreError from '../../containers/ScoreError'; export default () => ( <div className="d-flex text-nowrap"> <span className="col py-2 badge badge-success"><ScoreCorrect/></span> <span className="col py-2 badge badge-danger ml-1"><ScoreError/></span> </div> );
src/components/header/newGame/NewGameModal.js
TechyFatih/Nuzlog
import React from 'react'; import { Modal, Button } from 'react-bootstrap'; import { connect } from 'react-redux'; import { actions } from 'react-redux-form'; import games from 'data/games.json'; import ConfirmModal from 'components/other/ConfirmModal'; import { RRForm, RRFControl } from 'components/form/RRF'; import { newGame, newLocation } from 'actions'; import Rules from './Rules'; class NewGameModal extends React.Component { constructor() { super(); this.state = { rules: [], confirm: false, values: null }; this.handleEnter = this.handleEnter.bind(this); this.addRule = this.addRule.bind(this); this.removeRule = this.removeRule.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleConfirm = this.handleConfirm.bind(this); } handleEnter() { this.setState({ rules: [], values: null }); this.dispatch(actions.focus('local.title')); } addRule(rule) { this.setState(({rules}) => ({ rules: [...rules, rule] })); } removeRule(index) { this.setState(({rules}) => ({ rules: [ ...rules.slice(0, index), ...rules.slice(index + 1) ] })); } handleSubmit(values) { if (!this.props.gameOpen) { this.props.onNewGame( values.title, values.game, values.name, values.location, this.state.rules ); this.props.onHide(); } else { this.setState({ confirm: true, values }); } } handleConfirm() { const {values} = this.state; this.props.onNewGame( values.title, values.game, values.name, values.location, this.state.rules ); this.props.onHide(); this.setState({values: null}); } render() { return ( <Modal show={this.props.show} onEnter={this.handleEnter} onHide={this.props.onHide}> <RRForm getDispatch={dispatch => this.dispatch = dispatch} onSubmit={this.handleSubmit}> <Modal.Header closeButton><h2>New Game</h2></Modal.Header> <Modal.Body> <RRFControl model='.title' id='new-title' label='Title*' placeholder='The Great Nuzlocke Challenge' required/> <RRFControl model='.game' component='combobox' id='new-game' label='Game*' placeholder='Pokémon Ruby' required> {games} </RRFControl> <RRFControl model='.name' id='new-name' label='Name*' placeholder='Ruby' required/> <RRFControl model='.location' id='new-locaiton' label='Initial Location' placeholder='Littleroot Town'/> <Rules rules={this.state.rules} addRule={this.addRule} removeRule={this.removeRule}/> </Modal.Body> <Modal.Footer> <Button type='submit' bsStyle='primary' bsSize='large' block> Start </Button> </Modal.Footer> </RRForm> <ConfirmModal show={this.state.confirm} onConfirm={this.handleConfirm} onHide={() => this.setState({confirm: false})}> Are you sure you want to start a new game? All unsaved progress will be lost. </ConfirmModal> </Modal> ); } } const mapStateToProps = state => { return { gameOpen: state.gameOpen }; }; const mapDispatchToProps = dispatch => { return { onNewGame: (title, game, name, location, rules) => { dispatch(newGame(title, game, name, rules)) if (location) dispatch(newLocation(location)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(NewGameModal);
src-web/js/view/History.js
kwangkim/pigment
import React from 'react'; export default class HistoryView extends React.Component { render() { return <div> <HistoryViewHeader /> </div>; } } class HistoryViewHeader extends React.Component { render() { return <span>HISTORY VIEW</span>; } }
src/routes/Counter/components/Counter.js
yoshiyoshi7/react2chv2
import React from 'react' import PropTypes from 'prop-types' export const Counter = ({ counter, increment, doubleAsync }) => ( <div style={{ margin: '0 auto' }} > <h2>Counter: {counter}</h2> <button className='btn btn-primary' onClick={increment}> Increment </button> {' '} <button className='btn btn-secondary' onClick={doubleAsync}> Double (Async) </button> </div> ) Counter.propTypes = { counter: PropTypes.number.isRequired, increment: PropTypes.func.isRequired, doubleAsync: PropTypes.func.isRequired, } export default Counter
src/routes/Music/components/MusicView.js
jhash/jhash
import './MusicView.scss' import React from 'react' import { Link } from 'react-router' export class MusicView extends React.Component { static propTypes = {} render () { return ( <div className='view--music row'> <Link to='music/tabitha'> Tabitha </Link> </div> ) } } export default MusicView
src/svg-icons/notification/event-busy.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationEventBusy = (props) => ( <SvgIcon {...props}> <path d="M9.31 17l2.44-2.44L14.19 17l1.06-1.06-2.44-2.44 2.44-2.44L14.19 10l-2.44 2.44L9.31 10l-1.06 1.06 2.44 2.44-2.44 2.44L9.31 17zM19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11z"/> </SvgIcon> ); NotificationEventBusy = pure(NotificationEventBusy); NotificationEventBusy.displayName = 'NotificationEventBusy'; NotificationEventBusy.muiName = 'SvgIcon'; export default NotificationEventBusy;
react+redux/src/js/compont/unSend.js
fruitGirl/mm
/** * Created by Administrator on 2017/8/19 0019. */ import React from 'react' const UnSend = () =>{ return ( <div className="unSend"> <span className="iconfont icon-unhappy icon-md"></span> <span>还未到配送日期</span> </div> ) } export default UnSend;
src/components/TimeAndSalary/MobileInfoButtons.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import { InfoButton } from 'common/Modal'; import styles from './MobileInfoButtons.module.css'; const MobileInfoButtons = ({ toggleInfoSalaryModal, toggleInfoTimeModal }) => ( <div className={styles.mobileInfoButtons}> <div className={styles.infoButton}> <InfoButton onClick={toggleInfoSalaryModal}>估計時薪</InfoButton> </div> <div className={styles.infoButton}> <InfoButton onClick={toggleInfoTimeModal}>參考時間</InfoButton> </div> </div> ); MobileInfoButtons.propTypes = { toggleInfoSalaryModal: PropTypes.func.isRequired, toggleInfoTimeModal: PropTypes.func.isRequired, }; export default MobileInfoButtons;
monkey/monkey_island/cc/ui/src/components/attack/techniques/T1158.js
guardicore/monkey
import React from 'react'; import ReactTable from 'react-table'; import {renderMachineFromSystemData, ScanStatus} from './Helpers'; import MitigationsComponent from './MitigationsComponent'; class T1158 extends React.Component { constructor(props) { super(props); } static getColumns() { return ([{ columns: [ { Header: 'Machine', id: 'machine', accessor: x => renderMachineFromSystemData(x.machine), style: {'whiteSpace': 'unset'}}, { Header: 'Result', id: 'result', accessor: x => x.result, style: {'whiteSpace': 'unset'}} ] }]) } render() { return ( <div> <div>{this.props.data.message_html}</div> <br/> {this.props.data.status === ScanStatus.USED ? <ReactTable columns={T1158.getColumns()} data={this.props.data.info} showPagination={false} defaultPageSize={this.props.data.info.length} /> : ''} <MitigationsComponent mitigations={this.props.data.mitigations}/> </div> ); } } export default T1158;
app/javascript/mastodon/features/ui/components/drawer_loading.js
TheInventrix/mastodon
import React from 'react'; const DrawerLoading = () => ( <div className='drawer'> <div className='drawer__pager'> <div className='drawer__inner' /> </div> </div> ); export default DrawerLoading;
frontend/js/components/commentView.js
beetwo/toucan
import twitterText from 'twitter-text' import PropTypes from 'prop-types'; import React from 'react'; import UserLink from './userLink' class Comment extends React.Component { render() { let {comment} = this.props; let mentions = twitterText.extractMentionsWithIndices(comment); let parts = []; if (mentions.length > 0) { mentions.sort(function(a,b){ return a.indices[0] - b.indices[0]; }); let begin_index = 0; let counter = 0; mentions.forEach((value, index, mentions) => { parts.push(<span key={counter++}> {comment.substring(begin_index, value.indices[0])} </span> ) let username = value.screenName, linkText = comment.substring(value.indices[0], value.indices[1]); parts.push( <UserLink key={counter++} username={username}> {linkText} </UserLink> ) begin_index = value.indices[1] }) parts.push(<span key={counter++}>{comment.substring(begin_index, comment.length)}</span>); } return <div>{parts.length > 0 ? parts : comment}</div>; } } Comment.propTypes = { comment: PropTypes.string.isRequired } export default Comment
frontend/advocatesearch/AdvocateDetail.js
datoszs/czech-lawyers
import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {Row} from 'react-bootstrap'; import translate from '../translate'; import router from '../router'; import {ADVOCATE_DETAIL} from '../routes'; import {BasicStatistics} from '../components/statistics'; import {DetailPanel} from '../components'; import {Advocate, statusMsg} from '../model'; import {search} from './modules'; import FooterColumn from './FooterColumn'; import Legend from './Legend'; const AdvocateDetailComponent = ({advocate, handleDetail, msgStatus, msgIc, href}) => ( <DetailPanel footer={ <Row> <FooterColumn value={advocate.address.city} /> <FooterColumn value={advocate.ic} label={msgIc} /> <FooterColumn value={msgStatus} /> </Row> } title={advocate.name} onClick={handleDetail} href={href} > <BasicStatistics statistics={advocate.statistics} legend={Legend} /> </DetailPanel> ); AdvocateDetailComponent.propTypes = { advocate: PropTypes.instanceOf(Advocate).isRequired, handleDetail: PropTypes.func.isRequired, msgStatus: PropTypes.string.isRequired, msgIc: PropTypes.string.isRequired, href: PropTypes.string.isRequired, }; const mapStateToProps = (state, {id}) => { const advocate = search.getResult(state, id); return { advocate, msgStatus: translate.getMessage(state, statusMsg[advocate.status]), msgIc: translate.getMessage(state, 'advocate.ic'), href: router.getHref(state, ADVOCATE_DETAIL, {id}), }; }; const mapDispatchToProps = (dispatch, {id}) => ({ handleDetail: () => dispatch(router.transition(ADVOCATE_DETAIL, {id})), }); const AdvocateDetail = connect(mapStateToProps, mapDispatchToProps)(AdvocateDetailComponent); AdvocateDetail.propTypes = { id: PropTypes.number.isRequired, }; export default AdvocateDetail;
app/javascript/src/components/FormDialog.js
michelson/chaskiq
import React from 'react' import { Transition } from '@headlessui/react' function FormDialog (props) { const [_open, setOpen] = React.useState(props.open) function handleClose () { setOpen(false) props.handleClose && props.handleClose() } React.useEffect(() => setOpen(props.open), [props.open]) return props.open ? ( <Backdrop> <Transition show={ Boolean(props.open) } enter="ease-out duration-300" enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" enterTo="opacity-100 translate-y-0 sm:scale-100" leave="ease-in duration-200" leaveFrom="opacity-100 translate-y-0 sm:scale-100" leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" className="relative bg-white dark:bg-black dark:text-gray-100 rounded-lg px-4 pt-5 pb-4 overflow-hidden--- shadow-xl transform transition-all sm:max-w-lg sm:w-full sm:p-6" > <div className="absolute top-0 right-0 pt-4 pr-4"> <button onClick={handleClose} type="button" className="text-gray-400 hover:text-gray-500 focus:outline-none focus:text-gray-500 transition ease-in-out duration-150" > <svg className="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" ></path> </svg> </button> </div> <div className="sm:flex--dis sm:items-start"> {/* <div className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10"> <svg className="h-6 w-6 text-red-600" stroke="currentColor" fill="none" viewBox="0 0 24 24"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path> </svg> </div> */} <div className="mt-3 sm:mt-0 text-left"> {props.titleContent && ( <h3 className="text-lg leading-6 font-medium text-gray-900 dark:text-gray-100"> {props.titleContent} </h3> )} <div className="mt-2">{props.formComponent}</div> </div> </div> <div className="mt-5 sm:mt-4 flex flex-row-reverse"> {props.dialogButtons} </div> </Transition> </Backdrop> ) : null } function Backdrop ({ children }) { return ( <div className="z-50 fixed bottom-0 inset-x-0 px-4 pb-6 sm:inset-0 sm:p-0 sm:flex sm:items-center sm:justify-center"> <div // x-show="open" // x-transition:enter="ease-out duration-300" // x-transition:enter-start="opacity-0" // x-transition:enter-end="opacity-100" // x-transition:leave="ease-in duration-200" // x-transition:leave-start="opacity-100" // x-transition:leave-end="opacity-0" className="fixed inset-0 transition-opacity" > <div className="absolute inset-0 bg-gray-500 opacity-75" /> </div> {children} </div> ) } /* export function AlertModal({title, message, action, onClick}){ return ( <div //x-show="open" //x-transition:enter="ease-out duration-300" //x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" //x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100" //x-transition:leave="ease-in duration-200" //x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100" //x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" className="relative bg-white rounded-lg px-4 pt-5 pb-4 overflow-hidden shadow-xl transform transition-all sm:max-w-lg sm:w-full sm:p-6"> <div className="hidden sm:block absolute top-0 right-0 pt-4 pr-4"> <button type="button" className="text-gray-400 hover:text-gray-500 focus:outline-none focus:text-gray-500 transition ease-in-out duration-150"> <svg className="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path> </svg> </button> </div> <div className="sm:flex sm:items-start"> <div className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10"> <svg className="h-6 w-6 text-red-600" stroke="currentColor" fill="none" viewBox="0 0 24 24"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path> </svg> </div> <div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left"> <h3 className="text-lg leading-6 font-medium text-gray-900"> {title} </h3> <div className="mt-2"> <p className="text-sm leading-5 text-gray-500"> {message} </p> </div> </div> </div> <div className="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse"> <span className="flex w-full rounded-md shadow-sm sm:ml-3 sm:w-auto"> <button type="button" onClick={onClick} className="inline-flex justify-center w-full rounded-md border border-transparent px-4 py-2 bg-red-600 text-base leading-6 font-medium text-white shadow-sm hover:bg-red-500 focus:outline-none focus:border-red-700 focus:shadow-outline-red transition ease-in-out duration-150 sm:text-sm sm:leading-5"> {action} </button> </span> <span className="mt-3 flex w-full rounded-md shadow-sm sm:mt-0 sm:w-auto"> <button type="button" className="inline-flex justify-center w-full rounded-md border border-gray-300 px-4 py-2 bg-white text-base leading-6 font-medium text-gray-700 shadow-sm hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline transition ease-in-out duration-150 sm:text-sm sm:leading-5"> Cancel </button> </span> </div> </div> ) } export function MessageModal({}){ return ( <div x-show="open" x-transition:enter="ease-out duration-300" x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100" x-transition:leave="ease-in duration-200" x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100" x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" className="bg-white rounded-lg px-4 pt-5 pb-4 overflow-hidden shadow-xl transform transition-all sm:max-w-lg sm:w-full sm:p-6"> <div> <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100"> <svg className="h-6 w-6 text-green-600" stroke="currentColor" fill="none" viewBox="0 0 24 24"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path> </svg> </div> <div className="mt-3 text-center sm:mt-5"> <h3 className="text-lg leading-6 font-medium text-gray-900"> Payment successful </h3> <div className="mt-2"> <p className="text-sm leading-5 text-gray-500"> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eius aliquam laudantium explicabo pariatur iste dolorem animi vitae error totam. At sapiente aliquam accusamus facere veritatis. </p> </div> </div> </div> <div className="mt-5 sm:mt-6 sm:grid sm:grid-cols-2 sm:gap-3 sm:grid-flow-row-dense"> <span className="flex w-full rounded-md shadow-sm sm:col-start-2"> <button type="button" className="inline-flex justify-center w-full rounded-md border border-transparent px-4 py-2 bg-indigo-600 text-base leading-6 font-medium text-white shadow-sm hover:bg-indigo-500 focus:outline-none focus:border-indigo-700 focus:shadow-outline-indigo transition ease-in-out duration-150 sm:text-sm sm:leading-5"> Deactivate </button> </span> <span className="mt-3 flex w-full rounded-md shadow-sm sm:mt-0 sm:col-start-1"> <button type="button" className="inline-flex justify-center w-full rounded-md border border-gray-300 px-4 py-2 bg-white text-base leading-6 font-medium text-gray-700 shadow-sm hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline transition ease-in-out duration-150 sm:text-sm sm:leading-5"> Cancel </button> </span> </div> </div> ) } */ export default FormDialog
ext/lib/site/topic-layout/topic-article/presupuesto-share/component.js
RosarioCiudad/democracyos
import React from 'react' import Pendiente from './pendiente' import Proyectado from './proyectado' export default ({ topic, forum, user, toggleVotesModal }) => ( <div className='presupuesto-container'> {topic.attrs.state === 'pendiente' && <Pendiente topic={topic} user={user} toggleVotesModal={toggleVotesModal} /> } {['proyectado', 'ejecutandose', 'terminado', 'perdedor'].includes(topic.attrs.state) && <Proyectado forum={forum} topic={topic} /> } </div> )
src/containers/Application.js
hannupekka/yabsa
// @flow import styles from 'styles/containers/Application'; import React, { Component } from 'react'; import CSSModules from 'react-css-modules'; import Header from 'components/Header'; type Props = { children: ElementType | Array<ElementType> } // eslint-disable-next-line react/prefer-stateless-function class Application extends Component { props: Props; render(): ElementType { const { children } = this.props; return ( <div> <Header /> <section styleName="content"> {children} </section> </div> ); } } export default CSSModules(Application, styles);
addons/comments/src/manager/components/CommentsPanel/index.js
nfl/react-storybook
import PropTypes from 'prop-types'; import React from 'react'; import CommentList from '../CommentList'; import CommentForm from '../CommentForm'; import style from './style'; export default function CommentsPanel(props) { if (props.loading) { return ( <div style={style.wrapper}> <div style={style.message}>loading...</div> </div> ); } if (props.appNotAvailable) { const appsUrl = 'https://hub.getstorybook.io/apps'; return ( <div style={style.wrapper}> <div style={style.message}> <a style={style.button} href={appsUrl}>Create an app for this repo on Storybook Hub</a> </div> </div> ); } return ( <div style={style.wrapper}> <CommentList key="list" {...props} /> <CommentForm key="form" {...props} /> </div> ); } CommentsPanel.defaultProps = { loading: false, appNotAvailable: false, }; CommentsPanel.propTypes = { loading: PropTypes.bool, appNotAvailable: PropTypes.bool, };
src/svg-icons/editor/format-italic.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatItalic = (props) => ( <SvgIcon {...props}> <path d="M10 4v3h2.21l-3.42 8H6v3h8v-3h-2.21l3.42-8H18V4z"/> </SvgIcon> ); EditorFormatItalic = pure(EditorFormatItalic); EditorFormatItalic.displayName = 'EditorFormatItalic'; EditorFormatItalic.muiName = 'SvgIcon'; export default EditorFormatItalic;
react-apollo/src/containers/AuthPage/index.js
strapi/strapi-examples
/** * * AuthPage * */ import React from 'react'; import PropTypes from 'prop-types'; import { findIndex, get, map, replace, set } from 'lodash'; import { Link } from 'react-router-dom'; import Button from '../../components/Button'; import FormDivider from '../../components/FormDivider'; import Input from '../../components/InputsIndex'; import Logo from '../../assets/logo_strapi.png'; import SocialLink from '../../components/SocialLink'; // Utils import auth from '../../utils/auth'; import request from '../../utils/request'; import form from './forms.json'; import './styles.css'; class AuthPage extends React.Component { state = { value: {}, errors: [], didCheckErrors: false }; componentDidMount() { this.generateForm(this.props); } componentWillReceiveProps(nextProps) { if (nextProps.match.params.authType !== this.props.match.params.authType) { this.generateForm(nextProps); } } getRequestURL = () => { let requestURL; switch (this.props.match.params.authType) { case 'login': requestURL = 'http://localhost:1337/auth/local'; break; case 'register': requestURL = 'http://localhost:1337/auth/local/register'; break; case 'reset-password': requestURL = 'http://localhost:1337/auth/reset-password'; break; case 'forgot-password': requestURL = 'http://localhost:1337/auth/forgot-password'; break; default: } return requestURL; }; generateForm = props => { const params = props.location.search ? replace(props.location.search, '?code=', '') : props.match.params.id; this.setForm(props.match.params.authType, params); }; handleChange = ({ target }) => this.setState({ value: { ...this.state.value, [target.name]: target.value }, }); handleSubmit = e => { e.preventDefault(); const body = this.state.value; const requestURL = this.getRequestURL(); // This line is required for the callback url to redirect your user to app if (this.props.match.params.authType === 'forgot-password') { set(body, 'url', 'http://localhost:3000/auth/reset-password'); } request(requestURL, { method: 'POST', body: this.state.value }) .then(response => { auth.setToken(response.jwt, body.rememberMe); auth.setUserInfo(response.user, body.rememberMe); this.redirectUser(); }) .catch(err => { // TODO handle errors for other views // This is just an example const errors = [ { name: 'identifier', errors: [err.response.payload.message] }, ]; this.setState({ didCheckErrors: !this.state.didCheckErrors, errors }); }); }; redirectUser = () => { this.props.history.push('/'); }; /** * Function that allows to set the value to be modified * @param {String} formType the auth view type ex: login * @param {String} email Optionnal */ setForm = (formType, email) => { const value = get(form, ['data', formType], {}); if (formType === 'reset-password') { set(value, 'code', email); } this.setState({ value }); }; /** * Check the URL's params to render the appropriate links * @return {Element} Returns navigation links */ renderLink = () => { if (this.props.match.params.authType === 'login') { return ( <div> <Link to="/auth/forgot-password">Forgot Password</Link> &nbsp;or&nbsp; <Link to="/auth/register">register</Link> </div> ); } return ( <div> <Link to="/auth/login">Ready to signin</Link> </div> ); }; render() { const divStyle = this.props.match.params.authType === 'register' ? { marginTop: '3.2rem' } : { marginTop: '.9rem' }; const inputs = get(form, ['views', this.props.match.params.authType], []); const providers = ['facebook', 'github', 'google', 'twitter']; // To remove a provider from the list just delete it from this array... return ( <div className="authPage"> <div className="wrapper"> <div className="headerContainer"> {this.props.match.params.authType === 'register' ? ( <span>Welcome !</span> ) : ( <img src={Logo} alt="logo" /> )} </div> <div className="headerDescription"> {this.props.match.params.authType === 'register' ? ( <span>Please register to access the app.</span> ) : ( '' )} </div> <div className="formContainer" style={divStyle}> <div className="container-fluid"> <div className="row"> <div className="col-md-12"> {providers.map(provider => ( <SocialLink provider={provider} key={provider} /> ))} </div> </div> <FormDivider /> <form onSubmit={this.handleSubmit}> <div className="row" style={{ textAlign: 'start' }}> {map(inputs, (input, key) => ( <Input autoFocus={key === 0} customBootstrapClass={get(input, 'customBootstrapClass')} didCheckErrors={this.state.didCheckErrors} errors={get( this.state.errors, [ findIndex(this.state.errors, ['name', input.name]), 'errors', ], [] )} key={get(input, 'name')} label={get(input, 'label')} name={get(input, 'name')} onChange={this.handleChange} placeholder={get(input, 'placeholder')} type={get(input, 'type')} validations={{ required: true }} value={get(this.state.value, get(input, 'name'), '')} /> ))} <div className="col-md-12 buttonContainer"> <Button label="Submit" style={{ width: '100%' }} primary type="submit" /> </div> </div> </form> </div> </div> <div className="linkContainer">{this.renderLink()}</div> </div> </div> ); } } AuthPage.defaultProps = {}; AuthPage.propTypes = { location: PropTypes.object.isRequired, match: PropTypes.object.isRequired, }; export default AuthPage;
src/components/ui/ServiceIcon.js
meetfranz/franz
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { observer } from 'mobx-react'; import injectSheet from 'react-jss'; import classnames from 'classnames'; import ServiceModel from '../../models/Service'; const styles = theme => ({ root: { height: 'auto', }, icon: { width: theme.serviceIcon.width, }, isCustomIcon: { width: theme.serviceIcon.isCustom.width, border: theme.serviceIcon.isCustom.border, borderRadius: theme.serviceIcon.isCustom.borderRadius, }, isDisabled: { filter: 'grayscale(100%)', opacity: '.5', }, }); @injectSheet(styles) @observer class ServiceIcon extends Component { static propTypes = { classes: PropTypes.object.isRequired, service: PropTypes.instanceOf(ServiceModel).isRequired, className: PropTypes.string, }; static defaultProps = { className: '', }; render() { const { classes, className, service, } = this.props; return ( <div className={classnames([ classes.root, className, ])} > <img src={service.icon} className={classnames([ classes.icon, service.isEnabled ? null : classes.isDisabled, service.hasCustomIcon ? classes.isCustomIcon : null, ])} alt="" /> </div> ); } } export default ServiceIcon;
src/svg-icons/device/signal-cellular-no-sim.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularNoSim = (props) => ( <SvgIcon {...props}> <path d="M18.99 5c0-1.1-.89-2-1.99-2h-7L7.66 5.34 19 16.68 18.99 5zM3.65 3.88L2.38 5.15 5 7.77V19c0 1.1.9 2 2 2h10.01c.35 0 .67-.1.96-.26l1.88 1.88 1.27-1.27L3.65 3.88z"/> </SvgIcon> ); DeviceSignalCellularNoSim = pure(DeviceSignalCellularNoSim); DeviceSignalCellularNoSim.displayName = 'DeviceSignalCellularNoSim'; DeviceSignalCellularNoSim.muiName = 'SvgIcon'; export default DeviceSignalCellularNoSim;
node_modules/react-bootstrap/es/SplitToggle.js
darklilium/Factigis_2
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 React from 'react'; import DropdownToggle from './DropdownToggle'; var SplitToggle = function (_React$Component) { _inherits(SplitToggle, _React$Component); function SplitToggle() { _classCallCheck(this, SplitToggle); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } SplitToggle.prototype.render = function render() { return React.createElement(DropdownToggle, _extends({}, this.props, { useAnchor: false, noCaret: false })); }; return SplitToggle; }(React.Component); SplitToggle.defaultProps = DropdownToggle.defaultProps; export default SplitToggle;
client/index.js
vudayagirivaibhav/freecodecamp
import Rx from 'rx'; import React from 'react'; import Fetchr from 'fetchr'; import debugFactory from 'debug'; import { Router } from 'react-router'; import { history } from 'react-router/lib/BrowserHistory'; import { hydrate } from 'thundercats'; import { Render } from 'thundercats-react'; import { app$ } from '../common/app'; const debug = debugFactory('fcc:client'); const DOMContianer = document.getElementById('fcc'); const catState = window.__fcc__.data || {}; const services = new Fetchr({ xhrPath: '/services' }); Rx.longStackSupport = !!debug.enabled; // returns an observable app$(history) .flatMap( ({ AppCat }) => { const appCat = AppCat(null, services); return hydrate(appCat, catState) .map(() => appCat); }, ({ initialState }, appCat) => ({ initialState, appCat }) ) .flatMap(({ initialState, appCat }) => { return Render( appCat, React.createElement(Router, initialState), DOMContianer ); }) .subscribe( () => { debug('react rendered'); }, err => { debug('an error has occured', err.stack); }, () => { debug('react closed subscription'); } );
clients/react/src/routes.js
Boychenko/sample-todo-2016
import React from 'react'; import {Route, IndexRoute} from 'react-router'; import App from './components/App'; import ItemsListPage from './components/Items/ListPage'; import ItemEdit from './components/Items/EditPage'; import AboutPage from './components/AboutPage'; import NotFoundPage from './components/NotFoundPage'; import CallbackPage from './components/CallbackPage'; import {requireAuth} from './helpers/oidcHelpers'; export default ( <Route path="/" component={App}> <IndexRoute component={AboutPage}/> <Route path="items" component={ItemsListPage} onEnter={requireAuth}/> <Route path="items/create" component={ItemEdit}/> <Route path="items/edit/:id" component={ItemEdit}/> <Route path="callback" component={CallbackPage}/> <Route path="*" component={NotFoundPage}/> </Route> );
frontend/Login/ConnectedLogin.js
fdemian/Morpheus
import React from 'react'; import { connect } from 'react-redux'; import Login from './Login'; import {updateUsernameFn, updatePasswordFn} from '../Register/Actions'; import login from './Actions'; const mapStateToProps = (state) => { return { oauthProviders: state.app.oauth, isLoggedIn: state.session.loggedIn, error: state.session.error, message: state.session.errorMessage } } const mapDispatchToProps = (dispatch, ownProps) => { return { localSignIn: (username, password) => { dispatch(login(username, password)); }, updateUsername: (username) => { dispatch(updateUsernameFn(username)); }, updatePassword: (password) => { dispatch(updatePasswordFn(password)); } } } const ConnectedLogin = connect( mapStateToProps, mapDispatchToProps )(Login) export default ConnectedLogin;
app/components/ConsoleToolbar.js
kidaa/fil
import React from 'react'; import {connect} from 'react-redux'; import {setPreference} from 'actions/preferences'; import {getExtension} from 'helpers'; import {byExtension} from 'interpreters'; class ConsoleToolbar extends React.Component { handleRunButton(event) { event.preventDefault(); this.props.onRun(); } handleLiveCodingCheckbox(event) { const checked = event.target.checked; const {dispatch} = this.props; dispatch(setPreference('liveCoding', checked)); } render() { const block = this.props.className; const {preferences, currentFile} = this.props; const extension = getExtension(currentFile); const interpreterInfo = byExtension(extension); return ( <div className={block}> <button className={block + "__run-button"} onClick={this.handleRunButton.bind(this)}> {String.fromCharCode(9654)} </button> <div className={block + "__interpreter-info"}> {interpreterInfo.description} </div> <label className={block + "__live-coding"}> <input onChange={this.handleLiveCodingCheckbox.bind(this)} checked={preferences.liveCoding} type="checkbox" /> <span className={block + "__live-coding-text"}>Live coding</span> </label> </div> ); } } function select(state) { return { preferences: state.preferences, currentFile: state.currentFile }; } export default connect(select)(ConsoleToolbar);
tools/playground/components/Section/Section.js
auth0/web-header
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames/bind'; import styles from './Section.styl'; const cx = classNames.bind(styles); const Section = ({ children, title, dark }) => <div> <h2 className="container text-center">{title}</h2> <div className={cx('section', { dark })}> <div>{children}</div> </div> </div>; Section.propTypes = { children: PropTypes.node.isRequired, title: PropTypes.string.isRequired, dark: PropTypes.bool }; export default Section;
src/routes/competition-show/competition-show.component.js
YGO/compe-frontend
import React from 'react' import Radium from 'radium' import PropTypes from 'prop-types' import LeadersBoardContainer from './leadersboard.container' import ScoreToggler from '../../components/leadersboard/score-toggler.component' import lineBtnImg from './assets/linebutton_82x20.png' import gnIconImg from './assets/gn_icon.png' import appStoreImg from './assets/appstore.svg' import playStoreImg from './assets/google_play.png' import Helmet from 'react-helmet/es/Helmet' import { alignCenter } from '../common.styles' import { style } from './competition-show.styles' import { connect } from 'react-redux' import Header from './header.component' let SHARE_URL if (process.env.NODE_ENV === 'development') { SHARE_URL = 'https://asyridxcpg.localtunnel.me/pgateaching_201709/' } else { SHARE_URL = window.location.href } const mapStateToProps = state => { const { id, title, official_url: officialUrl, club_name: clubName, club_url: clubUrl, youtube_url: youtubeUrl, term, } = state.mainApp.competition return { id, title, officialUrl, clubName, clubUrl, youtubeUrl, term, } } const CompetitionShow = ({ id, title, officialUrl, clubName, clubUrl, youtubeUrl, term, }) => ( <div style={[style.self]}> <Helmet> <title>{title}</title> </Helmet> <Header competitionId={id} title={title}/> <div className='container-fluid' style={[style.container]}> <section id='competition-info' style={[style.section]}> {youtubeUrl && <div className='row mb-4'> <div className='col-12' style={[alignCenter]}> <iframe className='youtubesize' width='560' height='315' src={youtubeUrl} frameBorder='0' allowFullScreen=''/> </div> </div> } <div className='row'> <div className='col pl-1'> <ul className='list-unstyled'> <li><a href={officialUrl}>{title}</a></li> <li><a href={clubUrl}>{clubName}</a></li> <li>{term}</li> </ul> </div> </div> </section> <section id='buttons' style={[style.section]}> <div className='row'> <div className='col-auto p-0 pl-1'> <ScoreToggler/> </div> <div className='col-auto p-0 pl-1'> <div className='fb-like' data-href={SHARE_URL} data-layout='button' data-action='like' data-size='small' data-show-faces='false' data-share='true'/> </div> <div className='col-auto p-0 pl-1'> <a href={`http://line.me/R/msg/text/?${encodeURIComponent(SHARE_URL)}`}> <img src={lineBtnImg} alt='LINE' style={style.buttons.lineBtn}/> </a> </div> </div> </section> <section id='leaders-board' style={[style.section]}> <LeadersBoardContainer/> </section> <section id='comments' style={[style.section]}> <div className='row'> <div className='col'> <div className='fb-like' data-href={SHARE_URL} data-layout='button' data-action='like' data-size='small' data-show-faces='false' data-share='true'/> </div> </div> <div className='row'> <div className='col'> <div className='fb-comments' data-href={SHARE_URL} data-numposts='5'/> </div> </div> </section> <footer style={[style.footer.self]}> <div className='row p-3' style={[style.footer.row]}> <div className='col'> このリーダーズボードは、国内ダウンロード数No.1の無料スコア管理アプリ ゴルフネットワークプラス のコンペ機能で提供しています </div> </div> <div className='row pl-3 pr-3 pb-3' style={[style.footer.row]}> <div className='col mr-auto'> <img src={gnIconImg} alt='GN+' className='mr-2 float-left' style={[style.footer.gnIcon]}/> <p className='pb-0 mb-0' style={{fontSize: '0.7em'}}> あなたのゴルフライフをもっと楽しく<br/>ダウンロード数 国内No.1 ゴルフスコア管理アプリ</p> <p>GOLF NETWORK PLUS</p> </div> <div className='col-auto'> <a className='mr-3' href='https://play.google.com/store/apps/details?id=com.asai24.golf'><img src={playStoreImg} alt='googleplay' style={[style.footer.marketIcon]}/></a> <a // eslint-disable-next-line max-len href='https://itunes.apple.com/jp/app/gorufusukoa-guan-li-gorufu/id561067103?mt=8'><img src={appStoreImg} alt='appstore' style={[style.footer.marketIcon]}/></a> </div> </div> </footer> </div> </div> ) CompetitionShow.defaultProps = { id: '', title: '', clubName: '', clubUrl: '', term: '', } CompetitionShow.propTypes = { id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, officialUrl: PropTypes.string, clubName: PropTypes.string.isRequired, clubUrl: PropTypes.string.isRequired, youtubeUrl: PropTypes.string, term: PropTypes.string.isRequired, } // noinspection JSUnusedGlobalSymbols export default connect(mapStateToProps)(Radium(CompetitionShow))
pages/index.js
falconi1812/falconi
import React, { Component } from 'react'; import ReactPixel from 'react-facebook-pixel'; import Header from 'components/Header/Header'; import Intro from 'components/Intro/Intro'; import Who from 'components/Who/Who'; import What from 'components/What/What'; import How from 'components/How/How'; import Services from 'components/Services/Services'; import CustomerTypes from 'components/CustomerTypes/CustomerTypes'; import Testimonials from 'components/Testimonials/Testimonials'; import Team from 'components/Team/Team'; import About from 'components/About/About'; import Footer from 'components/Footer/Footer'; import Calendar from 'components/Calendar/Calendar'; const nav = { home : { id: 'home', label: 'Home' }, how : { id: 'how', label: 'How we help you' }, services : { id: 'services', label: 'Services' }, customers : { id: 'customers', label: 'Customers' }, calendar : { id: 'calendar', label: 'Calendar' }, team : { id: 'our-team', label: 'Our team' }, about : { id: 'about', label: 'About' }, }; export default class App extends Component { componentDidMount() { ReactPixel.init('1883580588574747'); ReactPixel.pageView(); if (typeof window.google_trackConversion === 'function') { window.google_trackConversion({ google_conversion_id: 923014461, google_remarketing_only: true }); } } render () { // TODO make a reusable <Section> component to avoid repeat the section tag // and also enforce passing a TITLE + ID (required) return ( <main role="main" id={nav.home.id}> <Header nav={nav} /> <Intro/> <Who/> <What/> <How id={nav.how.id} /> <Services id={nav.services.id} /> <CustomerTypes id={nav.customers.id} /> <Calendar id={nav.calendar.id} /> <Team id={nav.team.id} /> <About id={nav.about.id} /> <Footer nav={nav} /> </main> ) } }
src/components/common/icons/Comment2.js
WendellLiu/GoodJobShare
import React from 'react'; /* eslint-disable */ const Comment2 = (props) => ( <svg {...props} width="148" height="148" viewBox="0 0 148 148"> <g transform="translate(0 6)"> <path d="M13.5463199,136.724864 C14.8088582,138.042797 16.5145543,138.767545 18.3425804,138.767545 C20.6922403,138.767545 23.0372839,137.615796 25.3153922,135.34692 L53.5759376,107.107148 C56.2995119,104.392806 62.2752185,101.923124 66.1136118,101.923124 L133.946768,101.923124 C141.609706,101.923124 147.841613,95.7027574 147.841613,88.0536683 L147.841613,13.9585989 C147.841613,6.3095098 141.612014,0.0868349842 133.946768,0.0868349842 L14.0125589,0.0868349842 C6.34962107,0.0868349842 0.117713804,6.30720169 0.117713804,13.9585989 L0.117713804,88.0536683 C0.117713804,95.8135469 4.87473635,101.897735 10.7996645,101.897735 L10.8481349,101.897735 C11.2936008,102.114698 12.3299439,103.695756 12.2168464,106.343162 L11.2543629,129.184256 C11.113568,132.461778 11.884478,134.996087 13.5463199,136.724864 L13.5463199,136.724864 Z M11.1458816,92.6860527 L11.0974112,92.6860527 C10.6127073,92.5014036 9.3801745,90.8511022 9.3801745,88.0513602 L9.3801745,13.9585989 C9.3801745,11.4081332 11.459785,9.335447 14.0125589,9.335447 L133.94446,9.335447 C136.494926,9.335447 138.572228,11.4058251 138.572228,13.9585989 L138.572228,88.0536683 C138.572228,90.6018259 136.497234,92.6768202 133.94446,92.6768202 L66.1136118,92.6768202 C59.7455258,92.6768202 51.5447975,96.0674394 47.0301269,100.568261 L20.6160725,126.956926 L21.4700746,106.730925 C21.6524156,102.359358 20.2883203,98.3270828 17.7401627,95.6681357 C15.8913635,93.747785 13.5232388,92.6860527 11.1458816,92.6860527 L11.1458816,92.6860527 Z"/> <path d="M27.360381 33.4275389L120.587406 33.4275389C123.142488 33.4275389 125.222098 31.3594689 125.222098 28.8043869 125.222098 26.249305 123.144796 24.181235 120.587406 24.181235L27.360381 24.181235C24.8099153 24.181235 22.7303047 26.249305 22.7303047 28.8043869 22.7303047 31.3594689 24.8099153 33.4275389 27.360381 33.4275389zM27.360381 56.5456067L120.587406 56.5456067C123.142488 56.5456067 125.222098 54.4798449 125.222098 51.9247629 125.222098 49.3696809 123.144796 47.2993028 120.587406 47.2993028L27.360381 47.2993028C24.8099153 47.2993028 22.7303047 49.3673728 22.7303047 51.9247629 22.7303047 54.482153 24.8099153 56.5456067 27.360381 56.5456067zM27.360381 79.7583073L92.6176826 79.7583073C95.1727646 79.7583073 97.2523751 77.6902373 97.2523751 75.1328472 97.2523751 72.5754571 95.1750727 70.5073871 92.6176826 70.5073871L27.360381 70.5073871C24.8099153 70.5073871 22.7303047 72.5754571 22.7303047 75.1328472 22.7303047 77.6902373 24.8099153 79.7583073 27.360381 79.7583073L27.360381 79.7583073z"/> </g> </svg> ); /* eslint-enable */ export default Comment2;
src/App.js
nihalgonsalves/react-cellular-automata
import React from 'react'; import './App.css'; import 'bulma/css/bulma.css'; import { dec2bin, ascii2bin } from './lib/util'; import AutomataIterator from './lib/AutomataIterator'; import SettingsPanel from './components/SettingsPanel'; import PlaybackPanel from './components/PlaybackPanel'; import { MAX_GENERATIONS } from './config'; let gridElement; const reusableContainer = document.createElement('div'); document.addEventListener('DOMContentLoaded', function(){ gridElement = document.getElementById('grid'); }, false); const HeaderAndProgress = ({ currentGeneration, generations, componentRefreshRand }) => <div className="hero is-primary is-bold" style={{ marginBottom: 20 }}> <div className="hero-body"> <div className="container"> <h1 className="title"> <i className="fa fa-cube" aria-hidden="true" /> Elementary Cellular Automata in 1 Dimension <span style={{ display: 'none' }}>{componentRefreshRand}</span> </h1> { currentGeneration > 0 && <progress className="progress is-large is-light" width="100%" value={currentGeneration} max={generations}></progress>} </div> </div> </div> ; const Display = ({ automataEnabled }) => <div className="box" style={{ marginLeft: 25, marginRight: 25, display: automataEnabled ? 'block' : 'none' }}> <div style={{ fontSize: 0 }} id="grid" /> </div> ; const Crypto = ({ initialState, lastState, visibleCrypto }) => <pre className="container box has-text-centered" style={{ textAlign: 'left', background: 'none', whiteSpace: 'pre-wrap', wordBreak: 'break-all', display: visibleCrypto ? 'block' : 'none' }} > {JSON.stringify({ instructions: [ 'You can use these values to generate a ciphered text with XOR (^)', 'a(c) = a(0) ^ a(k)', 'It can be deciphered using', 'a(0) = a(c) ^ a(k)', 'https://xor.pw/' ], 'a(0)': initialState, 'a(k)': lastState, }, null, 2)} </pre> ; const Diag = ({ automataState, visibleDiag }) => <pre className="container box has-text-centered" style={{ display: visibleDiag ? 'block' : 'none', textAlign: 'left', background: 'none', whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}> {JSON.stringify(automataState, (k, v) => (v instanceof Uint8Array || v instanceof Array) ? v.join('') : v, 2)} </pre> ; const Footer = ({ onToggleDiag, automataEnabled }) => <footer className="footer" style={{ display: automataEnabled ? 'none' : 'block' }}> <div className="container"> <div className="content has-text-centered"> <p> <i className="fa fa-code" /><br /> built with <strong>es6</strong>, <strong>react</strong>, <strong>bulma</strong> &amp; <strong>fontawesome</strong><br /> <a href="http://nihalgonsalv.es/">nihalgonsalv.es</a> - <a onClick={onToggleDiag}>debug</a> </p> </div> </div> </footer> ; class App extends React.Component { constructor(props) { super(props); this.state = { speed: 500, visibleCrypto: false, visibleDiag: false, displayLines: true, componentRefreshRand: undefined, } } clearAutomata = () => { this.setState({ lastState: undefined, automata: undefined }); gridElement.innerHTML = ''; } updateAutomata = () => { this.clearAutomata(); const { binaryRule, generations, random, initialState } = this.state; const automata = new AutomataIterator( binaryRule, generations, random, initialState, ); const cellWidth = 100/automata.columns; this.setState({ automata, cellWidth, cellOn: `<img style="width:${cellWidth}%" src="${process.env.PUBLIC_URL}/black.png" />`, cellOff: `<img style="width:${cellWidth}%; visibility:hidden" />`, }); } createAutomata = () => { this.updateAutomata(); this.setState({ automataEnabled: true, }); } setDefault = () => { const decimalRule = 90; this.setState({ decimalRule, binaryRule: dec2bin(decimalRule), generations: 50, random: false, }); } onToggleRandom = () => { this.setState({ random: !this.state.random, seed: undefined, initialState: undefined }); } onToggleEnabled = () => { this.setState({ automataEnabled: !this.state.automataEnabled }); } onToggleCrypto = () => { this.setState({ visibleCrypto: !this.state.visibleCrypto }); } onToggleDiag = () => { this.setState({ visibleDiag: !this.state.visibleDiag }); } onToggleLineDisplay = () => { this.setState({ displayLines: !this.state.displayLines }); } onChangeGenerations = (event) => { let generations = event.target.value; if (generations > MAX_GENERATIONS) { generations = MAX_GENERATIONS; } this.setState({ generations }); } onChangeDecimalRule = (event) => { let decimalRule = event.target.value; if (decimalRule > 255) { decimalRule = 255; } else if (decimalRule < 0) { decimalRule = 0; } this.setState({ decimalRule, binaryRule: decimalRule ? dec2bin(decimalRule) : undefined, }); } onChangeSeed = (event) => { const seed = event.target.value; if (!seed) { this.setState({ initialState: undefined, seed: undefined }); return; } const initialStateStringArray = ascii2bin(seed).split(''); const initialState = new Uint8Array(initialStateStringArray.length); initialStateStringArray.forEach((val, i) => { initialState[i] = val; }); this.setState({ seed, initialState, }); } onChangeSpeed = (event) => { this.setState({ speed: event.target.value }, () => { if (this.state.interval) { this.onPlay(); } }); } onReset = () => { this.updateAutomata(); } onPlay = () => { if (this.state.interval) { this.onPause(); } this.setState({ interval: setInterval(() => { this.iterate() }, this.state.speed), refreshInterval: setInterval(() => { this.setState({ componentRefreshRand: Math.random() }); }, 500), }); } onPause = () => { clearInterval(this.state.interval); clearInterval(this.state.refreshInterval); this.setState({ interval: undefined, refreshInterval: undefined }); } onFastForward = () => { this.onPause(); this.setState({ speed: 100 }, () => { this.onPlay() }); } iterate = () => { const { automata: { currentGeneration, generations, currentState, columns }, cellOn, cellOff, displayLines, } = this.state; const currentGenerationInt = parseInt(currentGeneration, 10); const generationsInt = parseInt(generations, 10); if (currentGenerationInt === generationsInt) { this.setState({ lastState: currentState, }); } else if((currentGenerationInt - 1) === generationsInt) { this.onPause(); return; } const cells = ['<span>']; for(let i = 0; i < columns; i++) { cells.push(currentState[i] ? cellOn : cellOff); } cells.push('<br /></span>'); if (displayLines) { reusableContainer.innerHTML = cells.join(''); gridElement.appendChild(reusableContainer.firstChild); } else { gridElement.innerHTML = cells.join(''); } this.state.automata.next(); } render() { const { state: { visibleCrypto, visibleDiag, binaryRule, decimalRule, generations, random, seed, initialState, lastState, automataEnabled, componentRefreshRand, interval, }, iterate, onToggleEnabled, onToggleCrypto, onToggleDiag, onToggleRandom, onToggleLineDisplay, onChangeDecimalRule, onChangeGenerations, onChangeSeed, onChangeSpeed, onReset, onPlay, onPause, onFastForward, createAutomata, setDefault, } = this; return <div> <HeaderAndProgress currentGeneration={this.state.automata && this.state.automata.currentGeneration} generations={generations} componentRefreshRand={componentRefreshRand} /> <Diag automataState={this.state} visibleDiag={visibleDiag}/> <SettingsPanel automataEnabled={automataEnabled} onChangeGenerations={onChangeGenerations} generations={generations} onChangeDecimalRule={onChangeDecimalRule} decimalRule={decimalRule} binaryRule={binaryRule} onToggleRandom={onToggleRandom} random={random} createAutomata={createAutomata} setDefault={setDefault} onChangeSeed={onChangeSeed} seed={seed} /> <br /> <PlaybackPanel onToggleLineDisplay={onToggleLineDisplay} onToggleEnabled={onToggleEnabled} onToggleCrypto={onToggleCrypto} visibleCrypto={visibleCrypto} automataEnabled={automataEnabled} onReset={onReset} onPlay={onPlay} onPause={onPause} onFastForward={onFastForward} isLastGeneration={this.state.automata ? (parseInt(this.state.automata.currentGeneration - 1, 10) === parseInt(generations, 10)) : false} isActive={interval} iterate={iterate} onChangeSpeed={onChangeSpeed} /> <Display automataEnabled={automataEnabled} /> <Crypto initialState={initialState ? initialState.join('') : undefined} lastState={lastState ? lastState.join('') : undefined} visibleCrypto={visibleCrypto} /> <Footer onToggleDiag={onToggleDiag} automataEnabled={automataEnabled} /> </div> } } export default App;
src/forms/AddSelection/AddSelectionForm.js
jobdoc/selections-app
import React from 'react' import { Field } from 'redux-form' import MenuItem from 'material-ui/MenuItem' import { SelectField, TextField } from 'redux-form-material-ui' export const AddSelectionForm = (props) => ( <form onSubmit={props.handleSubmit}> <Field name='item' component={TextField} hintText='Item' /> <br /> <Field name='room' component={TextField} hintText='Room' /> </form> ) AddSelectionForm.propTypes = { handleSubmit: React.PropTypes.func.isRequired } export default AddSelectionForm
app/javascript/components/MemberDetailsForm/MemberDetailsForm.js
SumOfUs/Champaign
// weak import React, { Component } from 'react'; import { FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import _ from 'lodash'; import Button from '../Button/Button'; import { updateForm } from '../../state/fundraiser/actions'; import FieldShape from '../FieldShape/FieldShape'; import ee from '../../shared/pub_sub'; export class MemberDetailsForm extends Component { static title = <FormattedMessage id="details" defaultMessage="details" />; HIDDEN_FIELDS = [ 'source', 'akid', 'referrer_id', 'rid', 'bucket', 'referring_akid', ]; constructor(props) { super(props); this.state = { errors: {}, loading: false, }; } componentDidMount() { this.prefill(); this.bindGlobalEvents(); } bindGlobalEvents() { ee.on('fundraiser:actions:validate_form', this.validate); } prefill() { const data = {}; for (const field of this.props.fields) { data[field.name] = this.props.formValues[field.name] ? this.props.formValues[field.name] : field.default_value; } for (const name of this.HIDDEN_FIELDS) { if (this.props.formValues[name]) { data[name] = this.props.formValues[name]; } } this.props.updateForm({ ...this.props.form, ...data }); } getFieldError(field) { const error = this.state.errors[field]; if (!error) return null; return <FormattedMessage {...error} />; } buttonText() { if (this.state.loading) { return ( <FormattedMessage id="form.processing" defaultMessage="Processing..." /> ); } else if (this.props.buttonText) { return this.props.buttonText; } else { return <FormattedMessage id="form.submit" defaultMessage="Submit" />; } } handleSuccess() { ee.emit('fundraiser:form:success'); this.setState({ errors: {} }, () => { if (this.props.proceed) { this.props.proceed(); } }); } handleFailure(response) { ee.emit('fundraiser:form:error', response); const errors = _.mapValues(response.errors, ([message]) => { return { id: 'errors.this_field_with_message', defaultMessage: 'This field {message}', values: { message }, }; }); this.setState({ errors }); } updateField(key, value) { this.state.errors[key] = null; // reset error message when field value changes this.props.updateForm({ ...this.props.form, [key]: value, }); } validate = () => { this.setState({ loading: true }); // TODO // Use a proper xhr lib if we want to make our lives easy. fetch(`/api/pages/${this.props.pageId}/actions/validate`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json', }, body: JSON.stringify({ ...this.props.form, form_id: this.props.formId }), }).then( response => { this.setState({ loading: false }); if (response.ok) { return response.json().then(this.handleSuccess.bind(this)); } return response.json().then(this.handleFailure.bind(this)); }, failure => { this.setState({ loading: false }); } ); }; fieldsToDisplay() { return this.props.fields.filter(field => { switch (field.display_mode) { case 'all_members': return true; case 'recognized_members_only': return this.recognizedMemberPresent(); case 'new_members_only': return !this.recognizedMemberPresent(); default: console.log( `Unknown display_mode "${field.display_mode}" for field "${field.name}"` ); return false; } }); } recognizedMemberPresent() { return !!this.props.formValues.email; } onSubmit = e => { e.preventDefault(); this.validate(); }; render() { const { loading } = this.state; return ( <div className="MemberDetailsForm-root"> <form onSubmit={this.onSubmit} className="form--big action-form"> {this.fieldsToDisplay().map(field => ( <FieldShape key={field.name} errorMessage={this.getFieldError(field.name)} onChange={value => this.updateField(field.name, value)} value={this.props.form[field.name]} field={field} /> ))} <Button type="submit" disabled={loading} className="action-form__submit-button" > {this.buttonText()} </Button> </form> </div> ); } } const mapStateToProps = state => ({ formId: state.fundraiser.formId, form: state.fundraiser.form, }); const mapDispatchToProps = dispatch => ({ updateForm: form => dispatch(updateForm(form)), }); export default connect( mapStateToProps, mapDispatchToProps )(MemberDetailsForm);
app/components/Header.js
Mikkael3/tiea207projekti2015
/* * Joonas Vilppunen, Markus Muranen, Niko Heikkinen * MIT Licence * 2015 */ import React from 'react'; import {Link} from 'react-router'; /*import FooterStore from '../stores/FooterStore'; import FooterActions from '../actions/FooterActions'; */ class Header extends React.Component { /* constructor(props) { super(props); this.state = FooterStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { FooterStore.listen(this.onChange); FooterActions. } componentWillUnmount() { FooterStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } */ render() { return ( <header className="header"> <div className="row"> <Link className="col-md-1" to='/'> <img className="logo" src={'/img/yle.png'}/> </Link> <h1 className="col-md-6 col-md-offset-4 ">Kolosseum</h1> </div> </header> ); } } export default Header;
src/svg-icons/editor/border-clear.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderClear = (props) => ( <SvgIcon {...props}> <path d="M7 5h2V3H7v2zm0 8h2v-2H7v2zm0 8h2v-2H7v2zm4-4h2v-2h-2v2zm0 4h2v-2h-2v2zm-8 0h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2V7H3v2zm0-4h2V3H3v2zm8 8h2v-2h-2v2zm8 4h2v-2h-2v2zm0-4h2v-2h-2v2zm0 8h2v-2h-2v2zm0-12h2V7h-2v2zm-8 0h2V7h-2v2zm8-6v2h2V3h-2zm-8 2h2V3h-2v2zm4 16h2v-2h-2v2zm0-8h2v-2h-2v2zm0-8h2V3h-2v2z"/> </SvgIcon> ); EditorBorderClear = pure(EditorBorderClear); EditorBorderClear.displayName = 'EditorBorderClear'; EditorBorderClear.muiName = 'SvgIcon'; export default EditorBorderClear;
src/slides/observer.js
philpl/talk-observe-the-future
import React from 'react' import { Slide, Text, CodePane } from 'spectacle' import { codeBackground } from '../constants/colors' import observerPattern from '~/assets/observer-pattern.example' export default ( <Slide transition={[ 'slide' ]}> <Text textColor='tertiary' textSize='1.8em' margin='30px'> Subject / Observer Pattern </Text> <CodePane lang='javascript' textSize='0.7em' bgColor={codeBackground} source={observerPattern}/> </Slide> )
node_modules/react-bootstrap/es/Breadcrumb.js
joekay/awebb
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 BreadcrumbItem from './BreadcrumbItem'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var Breadcrumb = function (_React$Component) { _inherits(Breadcrumb, _React$Component); function Breadcrumb() { _classCallCheck(this, Breadcrumb); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Breadcrumb.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('ol', _extends({}, elementProps, { role: 'navigation', 'aria-label': 'breadcrumbs', className: classNames(className, classes) })); }; return Breadcrumb; }(React.Component); Breadcrumb.Item = BreadcrumbItem; export default bsClass('breadcrumb', Breadcrumb);
src/components/hero/hero.js
compwhile/compwhile.io
import React, { Component } from 'react'; import { Button, Row, Col } from 'react-bootstrap'; import gitHubLogo from './github.png'; import './hero.css'; class Hero extends Component { render() { return ( <div className="hero"> <Row> <Col> <div className="text"><strong>compwhile</strong></div> <div className="minitext"> Web IDE for learning, visualizing and running computer programs. </div> </Col> </Row> <Row> <Col> <div className="main-buttons"> <Button href="#" bsStyle="warning"> Get Started </Button> <Button href="http://compwhile.readthedocs.io/en/latest/README/" bsStyle="warning"> DOCS </Button> <Button href="https://github.com/compwhile" target="_blank" bsStyle="info"> <img src={gitHubLogo} alt="compwhile at GitHub" height="20"/> GitHub </Button> </div> </Col> </Row> </div> ); } } export default Hero;
src/views/components/logos/github.js
djfrsn/dashboard-cl
import React from 'react'; export default function GitHubLogo() { return ( <svg viewBox="0 0 20 20"> <path d="M10 0C4.5 0 0 4.5 0 10c0 4.4 2.9 8.2 6.8 9.5.5.1.7-.2.7-.5v-1.9c-2.5.5-3.2-.6-3.4-1.1-.1-.3-.6-1.2-1-1.4-.4-.2-.9-.6 0-.7.8 0 1.3.7 1.5 1 .9 1.5 2.4 1.1 3 .9.1-.6.4-1.1.6-1.3-2.2-.3-4.6-1.2-4.6-5 0-1.1.4-2 1-2.7 0-.3-.4-1.3.2-2.7 0 0 .8-.3 2.8 1 .7-.2 1.6-.3 2.4-.3s1.7.1 2.5.3c1.9-1.3 2.8-1 2.8-1 .5 1.4.2 2.4.1 2.7.6.7 1 1.6 1 2.7 0 3.8-2.3 4.7-4.6 4.9.4.3.7.9.7 1.9v2.8c0 .3.2.6.7.5 4-1.3 6.8-5.1 6.8-9.5C20 4.5 15.5 0 10 0z" /> </svg> ); }
duckr/app/components/Duck/Duck.js
josedab/react-exercises
import React from 'react' import PropTypes from 'prop-types' import { formatTimestamp } from 'helpers/utils' import Reply from 'react-icons/lib/fa/mail-reply' import Star from 'react-icons/lib/fa/star' import { duckContainer, contentContainer, avatar, actionContainer, header, text, likeReplyContainer, icon, likedIcon, author, } from './Duck.css' export default function Duck(props) { const starIcon = props.isLiked === true ? likedIcon : icon; const starFn = props.isLiked === true ? props.handleDeleteLike : props.addAndHandleLike; return ( <div className={duckContainer} style={{cursor: props.hideReplyBtn === true ? 'default' : 'pointer'}} onClick={props.onClick}> <img src={props.duck.avatar} className={avatar}/> <div className={contentContainer}> <div className={header}> <div onClick={props.goToProfile} className={author}>{props.duck.name}</div> <div>{formatTimestamp(props.duck.timestamp)}</div> </div> <div className={text}>{props.duck.text}</div> <div className={likeReplyContainer}> {props.hideReplyBtn === true ? null : <Reply className={icon}/>} <div className={actionContainer}> <Star className={starIcon} onClick={(e) => starFn(props.duck.duckId, e)}/> {props.hideLikeCount === true ? null : <div>{props.numberOfLikes}</div>} </div> </div> </div> </div> ) } Duck.propTypes = { duck: PropTypes.shape({ avatar: PropTypes.string.isRequired, duckId: PropTypes.string.isRequired, name: PropTypes.string.isRequired, text: PropTypes.string.isRequired, timestamp: PropTypes.number.isRequired, uid: PropTypes.string.isRequired, }), onClick: PropTypes.func, isLiked: PropTypes.bool.isRequired, addAndHandleLike: PropTypes.func.isRequired, handleDeleteLike: PropTypes.func.isRequired, numberOfLikes: PropTypes.number, hideReplyBtn: PropTypes.bool.isRequired, hideLikeCount: PropTypes.bool.isRequired, goToProfile: PropTypes.func.isRequired, }
setup/src/universal/features/routing/hoc/HOCRedirect.js
ch-apptitude/goomi
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import _ from 'lodash'; import { selectUserStatus } from 'features/user/selectors'; import { USER_STATUS } from 'features/user/constants'; import LoginRedirect from 'features/routing/containers/LoginRedirectContainer'; import ProfileCompleteRedirect from 'features/routing/containers/ProfileCompleteRedirectContainer'; import VerifiedRedirect from 'features/routing/containers/VerifiedRedirectContainer'; import NotFound from 'features/routing/components/NotFound'; import Loader from 'features/common_ui/components/Loader'; export default function HOCRedirect(WrappedComponent, requiredStatus, excludedStatus) { const mapStateToProps = createStructuredSelector({ userStatus: selectUserStatus(), }); const Enhanced = ({ userStatus, ...etc }) => { const getRedirectComponent = () => { switch (requiredStatus) { case USER_STATUS.LOGGED_IN: return <LoginRedirect />; case USER_STATUS.PROFILE_COMPLETE: return <ProfileCompleteRedirect />; case USER_STATUS.VERIFIED: return <VerifiedRedirect />; default: return <LoginRedirect />; } }; if (userStatus.indexOf(USER_STATUS.LOADING) !== -1) { return <Loader />; } if (excludedStatus) { const exclStatus = [].concat([], excludedStatus); if (_.intersection(userStatus, exclStatus).length > 0) { return <NotFound />; } } if (requiredStatus) { if (userStatus.indexOf(requiredStatus) !== -1) { return <WrappedComponent {...etc} />; } return getRedirectComponent(); } return <WrappedComponent {...etc} />; }; Enhanced.propTypes = { userStatus: PropTypes.arrayOf(PropTypes.string).isRequired, }; return connect(mapStateToProps)(Enhanced); }
src/components/IndicHuitre.js
olivmarcel/aquack
import React, { Component } from 'react'; import { Grid, Col, Jumbotron, Button, ToggleButtonGroup, ToggleButton } from 'react-bootstrap'; import Carte from "./Carte"; export default class Indic extends Component { altIndic() { console.log("..."); } render() { const indicHuitre = [1,2,4,6,7,8,9,10]; return ( <div> <h2 className="text-center"><span className="text-primary">Milieu Physique</span> . <span className="text-success">Milieu Naturel</span> . <span className="text-warning">Usages</span></h2> <ToggleButtonGroup name="physic" type="checkbox" bsStyle="small" defaultValue={indicHuitre}> <ToggleButton name="bathy" value={1} bsSize="small" bsStyle="primary" onClick={ this.altIndic } >Bathymétrie</ToggleButton> <ToggleButton name="courants" value={2} bsSize="small" bsStyle="primary">Courants</ToggleButton> <ToggleButton name="houle" value={3} bsSize="small" bsStyle="primary">Houle</ToggleButton> <ToggleButton name="hauteur" value={4} bsSize="small" bsStyle="primary">Hauteur d eau</ToggleButton> <ToggleButton name="vents" value={5} bsSize="small" bsStyle="primary">Vents</ToggleButton> <ToggleButton name="fonds" value={6} bsSize="small" bsStyle="primary">Nature des fonds</ToggleButton> <ToggleButton name="especes" bsSize="small" bsStyle="success" value={7}>Espèces spécifiques</ToggleButton> <ToggleButton name="milieu" bsSize="small" bsStyle="success" value={8}>Qualité du milieu</ToggleButton> <ToggleButton name="peche" value={9} bsSize="small" bsStyle="warning">Cantonnements de pêche</ToggleButton> <ToggleButton name="trafic" value={10} bsSize="small" bsStyle="warning">Trafic maritime</ToggleButton> </ToggleButtonGroup> <br/> <Carte fish = {this.props.fish}/> </div> ) } }
client/src/entwine/TinyMCE_ssembed.js
open-sausages/silverstripe-assets-gallery
/* global tinymce, window */ import jQuery from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import { loadComponent } from 'lib/Injector'; import ShortcodeSerialiser from 'lib/ShortcodeSerialiser'; import InsertEmbedModal from 'components/InsertEmbedModal/InsertEmbedModal'; import i18n from 'i18n'; const InjectableInsertEmbedModal = loadComponent(InsertEmbedModal); const filter = 'div[data-shortcode="embed"]'; /** * Embed shortcodes are split into an outer <div> element and an inner <img> * placeholder based on the thumbnail url provided by the oembed shortcode provider. */ (() => { const ssembed = { init: (editor) => { const insertTitle = i18n._t('AssetAdmin.INSERT_VIA_URL', 'Insert media via URL'); const editTitle = i18n._t('AssetAdmin.EDIT_MEDIA', 'Edit media'); const contextTitle = i18n._t('AssetAdmin.MEDIA', 'Media'); editor.addButton('ssembed', { title: insertTitle, icon: 'media', cmd: 'ssembed', stateSelector: filter }); editor.addMenuItem('ssembed', { text: contextTitle, icon: 'media', cmd: 'ssembed', }); editor.addButton('ssembededit', { title: editTitle, icon: 'editimage', cmd: 'ssembed' }); editor.addContextToolbar( (embed) => editor.dom.is(embed, filter), 'alignleft aligncenter alignright | ssembededit' ); editor.addCommand('ssembed', () => { // See HtmlEditorField.js jQuery(`#${editor.id}`).entwine('ss').openEmbedDialog(); }); // Replace the tinymce default media commands with the ssembed command editor.on('BeforeExecCommand', (e) => { const cmd = e.command; const ui = e.ui; const val = e.value; if (cmd === 'mceAdvMedia' || cmd === 'mceAdvMedia') { e.preventDefault(); editor.execCommand('ssembed', ui, val); } }); editor.on('SaveContent', (o) => { const content = jQuery(`<div>${o.content}</div>`); // Transform [embed] shortcodes content .find(filter) .each(function replaceWithShortCode() { // Note: embed <div> contains placeholder <img>, and potentially caption <p> const embed = jQuery(this); // If placeholder has been removed, remove data-* properties and // convert to non-shortcode div const placeholder = embed.find('img.placeholder'); if (placeholder.length === 0) { embed.removeAttr('data-url'); embed.removeAttr('data-shortcode'); return; } // Find nested element data const caption = embed.find('.caption').text(); const width = parseInt(placeholder.attr('width'), 10); const height = parseInt(placeholder.attr('height'), 10); const url = embed.data('url'); const properties = { url, thumbnail: placeholder.prop('src'), class: embed.prop('class'), width: isNaN(width) ? null : width, height: isNaN(height) ? null : height, caption, }; const shortCode = ShortcodeSerialiser.serialise({ name: 'embed', properties, wrapped: true, content: url }); embed.replaceWith(shortCode); }); // eslint-disable-next-line no-param-reassign o.content = content.html(); }); editor.on('BeforeSetContent', (o) => { let content = o.content; // Transform [embed] tag let match = ShortcodeSerialiser.match('embed', true, content); while (match) { const data = match.properties; // Add base div const base = jQuery('<div/>') .attr('data-url', data.url || match.content) .attr('data-shortcode', 'embed') .addClass(data.class) .addClass('ss-htmleditorfield-file embed'); // Add placeholder const placeholder = jQuery('<img />') .attr('src', data.thumbnail) .addClass('placeholder'); // Set dimensions if (data.width) { placeholder.attr('width', data.width); } if (data.height) { placeholder.attr('height', data.height); } base.append(placeholder); // Add caption p tag if (data.caption) { const caption = jQuery('<p />') .addClass('caption') .text(data.caption); base.append(caption); } // Inject into code content = content.replace(match.original, (jQuery('<div/>').append(base).html())); // Search for next match match = ShortcodeSerialiser.match('embed', true, content); } // eslint-disable-next-line no-param-reassign o.content = content; }); }, }; tinymce.PluginManager.add('ssembed', (editor) => ssembed.init(editor)); })(); jQuery.entwine('ss', ($) => { $('.js-injector-boot #insert-embed-react__dialog-wrapper').entwine({ Element: null, Data: {}, onunmatch() { // solves errors given by ReactDOM "no matched root found" error. this._clearModal(); }, _clearModal() { ReactDOM.unmountComponentAtNode(this[0]); // this.empty(); }, open() { this._renderModal(true); }, close() { this.setData({}); this._renderModal(false); }, /** * Renders the react modal component * * @param {boolean} isOpen * @private */ _renderModal(isOpen) { const handleHide = () => this.close(); // Inserts embed into page const handleInsert = (...args) => this._handleInsert(...args); // Create edit form from url const handleCreate = (...args) => this._handleCreate(...args); const handleLoadingError = (...args) => this._handleLoadingError(...args); const attrs = this.getOriginalAttributes(); // create/update the react component ReactDOM.render( <InjectableInsertEmbedModal isOpen={isOpen} onCreate={handleCreate} onInsert={handleInsert} onClosed={handleHide} onLoadingError={handleLoadingError} bodyClassName="modal__dialog" className="insert-embed-react__dialog-wrapper" fileAttributes={attrs} />, this[0] ); }, _handleLoadingError() { this.setData({}); this.open(); }, /** * Handles inserting the selected file in the modal * * @param {object} data * @returns {Promise} * @private */ _handleInsert(data) { const oldData = this.getData(); this.setData(Object.assign({ Url: oldData.Url }, data)); this.insertRemote(); this.close(); }, _handleCreate(data) { this.setData(Object.assign({}, this.getData(), data)); this.open(); }, /** * Find the selected node and get attributes associated to attach the data to the form * * @returns {object} */ getOriginalAttributes() { const data = this.getData(); const $field = this.getElement(); if (!$field) { return data; } const node = $($field.getEditor().getSelectedNode()); if (!node.length) { return data; } // Find root embed shortcode const element = node.closest(filter).add(node.filter(filter)); if (!element.length) { return data; } const image = element.find('img.placeholder'); // If image has been removed then this shortcode is invalid if (image.length === 0) { return data; } const caption = element.find('.caption').text(); const width = parseInt(image.width(), 10); const height = parseInt(image.height(), 10); return { Url: element.data('url') || data.Url, CaptionText: caption, PreviewUrl: image.attr('src'), Width: isNaN(width) ? null : width, Height: isNaN(height) ? null : height, Placement: this.findPosition(element.prop('class')), }; }, /** * Calculate placement from css class */ findPosition(cssClass) { const alignments = [ 'leftAlone', 'center', 'rightAlone', 'left', 'right', ]; if (typeof cssClass !== 'string') { return ''; } const classes = cssClass.split(' '); return alignments.find((alignment) => ( classes.indexOf(alignment) > -1 )); }, insertRemote() { const $field = this.getElement(); if (!$field) { return false; } const editor = $field.getEditor(); if (!editor) { return false; } const data = this.getData(); // Add base div const base = jQuery('<div/>') .attr('data-url', data.Url) .attr('data-shortcode', 'embed') .addClass(data.Placement) .addClass('ss-htmleditorfield-file embed'); // Add placeholder image const placeholder = jQuery('<img />') .attr('src', data.PreviewUrl) .addClass('placeholder'); // Set dimensions if (data.Width) { placeholder.attr('width', data.Width); } if (data.Height) { placeholder.attr('height', data.Height); } // Add to base base.append(placeholder); // Add caption p tag if (data.CaptionText) { const caption = jQuery('<p />') .addClass('caption') .text(data.CaptionText); base.append(caption); } // Find best place to put this embed const node = $(editor.getSelectedNode()); let replacee = $(null); if (node.length) { replacee = node.filter(filter); // Find find closest existing embed if (replacee.length === 0) { replacee = node.closest(filter); } // Fail over to check if the node is an image if (replacee.length === 0) { replacee = node.filter('img.placeholder'); } } // Inject if (replacee.length) { replacee.replaceWith(base); } else { // Otherwise insert the whole HTML content editor.repaint(); editor.insertContent($('<div />').append(base.clone()).html(), { skip_undo: 1 }); } editor.addUndo(); editor.repaint(); return true; }, }); });
test/helpers/shallowRenderHelper.js
malecki/gcmeme
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
envkey-react/src/containers/invoice_list_container.js
envkey/envkey-app
import React from 'react' import { connect } from 'react-redux' import { billingFetchInvoiceList, billingFetchInvoicePdf } from 'actions' import { getInvoices, getIsLoadingInvoices, getIsLoadingInvoicePdf } from 'selectors' import InvoiceRow from 'components/billing/invoice_row' import SmallLoader from 'components/shared/small_loader' class InvoiceList extends React.Component { componentDidMount(){ if (this.props.invoices.length == 0){ this.props.onLoadInvoices() } } render(){ if (this.props.isLoadingInvoices){ return <SmallLoader /> } else if (this.props.invoices){ return <table className="invoice-list"> <thead> <tr> <th>Date</th> <th>Plan</th> <th>Active Users</th> <th>Total</th> <th>Billing Period</th> <th>Status</th> <th>Reference</th> <th></th> </tr> </thead> {this._renderInvoices()} </table> } else { return <table /> } } _renderInvoices(){ return this.props.invoices.map(invoice => { return <InvoiceRow {...this.props} invoice={invoice} /> }) } } const mapStateToProps = state => ({ invoices: getInvoices(state), isLoadingInvoices: getIsLoadingInvoices(state), isLoadingInvoicePdf: getIsLoadingInvoicePdf(state) }) const mapDispatchToProps = dispatch => ({ onLoadInvoices: () => dispatch(billingFetchInvoiceList()), onLoadInvoicePdf: id => dispatch(billingFetchInvoicePdf({id})) }) export default connect(mapStateToProps, mapDispatchToProps)(InvoiceList)
docs/src/app/components/pages/components/TextField/ExampleSimple.js
w01fgang/material-ui
import React from 'react'; import TextField from 'material-ui/TextField'; const TextFieldExampleSimple = () => ( <div> <TextField hintText="Hint Text" /><br /> <br /> <TextField hintText="The hint text can be as long as you want, it will wrap." /><br /> <TextField id="text-field-default" defaultValue="Default Value" /><br /> <TextField hintText="Hint Text" floatingLabelText="Floating Label Text" /><br /> <TextField defaultValue="Default Value" floatingLabelText="Floating Label Text" /><br /> <TextField hintText="Hint Text" floatingLabelText="Fixed Floating Label Text" floatingLabelFixed={true} /><br /> <TextField hintText="Password Field" floatingLabelText="Password" type="password" /><br /> <TextField hintText="MultiLine with rows: 2 and rowsMax: 4" multiLine={true} rows={2} rowsMax={4} /><br /> <TextField hintText="Message Field" floatingLabelText="MultiLine and FloatingLabel" multiLine={true} rows={2} /><br /> <TextField hintText="Full width" fullWidth={true} /> </div> ); export default TextFieldExampleSimple;
packages/cf-component-card/src/Card.js
koddsson/cf-ui
import React from 'react'; import PropTypes from 'prop-types'; class Card extends React.Component { render() { return ( <section id={this.props.id} className="cf-card"> {this.props.children} </section> ); } } Card.propTypes = { id: PropTypes.string, children: PropTypes.node }; export default Card;
src/app/views/logout.js
webcoding/reactui-starter
import React from 'react'; import authActions from 'actions/auth'; export default React.createClass( { componentDidMount () { authActions.logout(); }, render() { return ( <div id="logout"> <div className="jumbotron"> <h1>Logged Out</h1> </div> </div> ); } } );
app/javascript/mastodon/features/compose/components/reply_indicator.js
codl/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Avatar from '../../../components/avatar'; import IconButton from '../../../components/icon_button'; import DisplayName from '../../../components/display_name'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { isRtl } from '../../../rtl'; const messages = defineMessages({ cancel: { id: 'reply_indicator.cancel', defaultMessage: 'Cancel' }, }); @injectIntl export default class ReplyIndicator extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map, onCancel: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleClick = () => { this.props.onCancel(); } handleAccountClick = (e) => { if (e.button === 0) { e.preventDefault(); this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`); } } render () { const { status, intl } = this.props; if (!status) { return null; } const content = { __html: status.get('contentHtml') }; const style = { direction: isRtl(status.get('search_index')) ? 'rtl' : 'ltr', }; return ( <div className='reply-indicator'> <div className='reply-indicator__header'> <div className='reply-indicator__cancel'><IconButton title={intl.formatMessage(messages.cancel)} icon='times' onClick={this.handleClick} /></div> <a href={status.getIn(['account', 'url'])} onClick={this.handleAccountClick} className='reply-indicator__display-name'> <div className='reply-indicator__display-avatar'><Avatar account={status.get('account')} size={24} /></div> <DisplayName account={status.get('account')} /> </a> </div> <div className='reply-indicator__content' style={style} dangerouslySetInnerHTML={content} /> </div> ); } }
node_modules/react-router/es6/Route.js
Win-Myint/ReactChallenge2
import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var func = _React$PropTypes.func; /** * A <Route> is used to declare which components are rendered to the * page when the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is * requested, the tree is searched depth-first to find a route whose * path matches the URL. When one is found, all routes in the tree * that lead to it are considered "active" and their components are * rendered into the DOM, nested in the same order as in the tree. */ var Route = React.createClass({ displayName: 'Route', statics: { createRouteFromReactElement: createRouteFromReactElement }, propTypes: { path: string, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default Route;
example/examples/PublicMethodsExample.react.js
Neophy7e/react-bootstrap-typeahead
import React from 'react'; import {Button, ButtonToolbar} from 'react-bootstrap'; import {Typeahead} from '../../src/'; import options from '../../example/exampleData'; /* example-start */ const PublicMethodsExample = React.createClass({ render() { return ( <div> <Typeahead labelKey="name" multiple options={options} placeholder="Choose a state..." ref={ref => this._typeahead = ref} selected={options.slice(0, 4)} /> <ButtonToolbar style={{marginTop: '10px'}}> <Button onClick={() => this._typeahead.getInstance().clear()}> Clear </Button> <Button onClick={() => this._typeahead.getInstance().focus()}> Focus </Button> <Button onClick={() => { const instance = this._typeahead.getInstance(); instance.focus(); setTimeout(() => instance.blur(), 1000); }}> Focus, then blur after 1 second </Button> </ButtonToolbar> </div> ); }, }); /* example-end */ export default PublicMethodsExample;
app/components/agents/agentPageResourcesItem.js
nypl-registry/browse
import React from 'react' import { Link } from 'react-router' const AgentPageResourcesItem = React.createClass({ getInitialState: function (event) { return {errored: false} }, handleError: function (event) { this.setState({errored: true}) }, render () { var displayImg = <td /> if (!this.state.errored) { displayImg = ( <td className='agent-resources-list-item-bookcover'> <img onError={this.handleError} src={`http://s3.amazonaws.com/data.nypl.org/bookcovers/${this.props.data.idBnum}_ol.jpg`} /> </td> ) } return ( <tr className='agent-resources-list-item-row'> <td> {this.props.data.startYear} </td> {displayImg} <td className='agent-resources-list-item-title'> <Link className='agent-resources-list-item-title-link' to={`/resources/${this.props.data.uri}`}> <div> {this.props.data.title} </div> </Link> </td> <td> <Link className='agent-resources-list-item-title-link' to={`/resources/${this.props.data.uri}`}> <span className='lg-icon nypl-icon-wedge-right'></span> </Link> </td> </tr> ) } }) export default AgentPageResourcesItem
src/routes.js
KovDimaY/React-Highcharts
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/app'; import Bar from './components/charts/bar'; import Home from './components/home'; import Line from './components/charts/line'; // import NotFound from './components/notFound'; // TODO: fix router and use 404 instead of index import Other from './components/charts/other'; import Pie from './components/charts/pie'; import Playground from './components/charts/playground'; import Scattering from './components/charts/scatter'; export default ( <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="/line" component={Line} /> <Route path="/bar" component={Bar} /> <Route path="/pie" component={Pie} /> <Route path="/scatter" component={Scattering} /> <Route path="/other" component={Other} /> <Route path="/playground" component={Playground} /> <Route path="*" component={Home} /> {/* <Route path="*" component={NotFound} /> */} </Route> );
maodou/events/client/components/admin/eventsList.js
wuyang910217/meteor-react-redux-base
import React, { Component } from 'react'; import {Link} from 'react-router'; import Loading from 'client/components/common/loading'; import moment from 'moment'; import { shortText } from 'lib/helpers'; export default class EventsList extends Component { render() { const { data, status } = this.props.events; return( <div className="admin-package-wrapper row"> <div className="col-sm-12"> <h1 style={{marginBottom: '20px'}}>管理活动</h1> { status === 'ready' ? data.length > 0 ? this.renderEvents(data) : <div>抱歉,目前还没有活动!</div> : <Loading /> } </div> </div> ); } renderEvents(events) { return ( <div className="table-responsive"> <table className="table table-striped"> <thead> <tr style={{fontSize: '16px'}}> <th>活动标题</th> <th>活动日期</th> <th>活动地点</th> <th>人数限制</th> <th>发布日期</th> <th>操作</th> </tr> </thead> <tbody> {events.map((event, index) => <tr key={event._id} style={{fontSize: '16px'}}> <td style={{lineHeight: '50px'}}><Link to={`/event/${event._id}`}>{shortText(event.title)}</Link></td> <td style={{lineHeight: '50px'}}>{moment(event.time).format('YYYY-MM-DD')}</td> <td style={{lineHeight: '50px'}}>{shortText(event.location)}</td> <td style={{lineHeight: '50px'}}>{shortText(event.limit)}</td> <td style={{lineHeight: '50px'}}>{moment(event.createdAt).format('YYYY-MM-DD')}</td> <td style={{lineHeight: '50px'}}> <Link to={`/admin/event/edit/${event._id}`} className="btn btn-success" style={{marginRight: '10px'}}>编辑</Link> <button className="btn btn-danger" onClick={(e) => this.props.dispatch((this.props.deleteEvent(e, event._id)))}>删除</button> </td> </tr> )} </tbody> </table> </div> ); } }
public/app/components/player/duration-panel.js
feedm3/unhypem
/** * @author Fabian Dietenberger */ 'use strict'; import React from 'react'; import songDispatcher from '../../dispatcher/song-dispatcher'; class DurationLabel extends React.Component { constructor(props) { super(props); this.state = { duration: 0, position: 0 }; } handleCurrentSongUpdate(songInfo) { const durationInMillis = songInfo.song.duration; const positionInPercent = songInfo.position; const durationInSeconds = durationInMillis / 1000; const positionInSeconds = (durationInSeconds * positionInPercent) / 100; this.setState({ duration: durationInSeconds, position: positionInSeconds }); } render() { const position = secondFormatter(this.state.position); const duration = secondFormatter(this.state.duration); return ( <div className="duration"> <div>{position}</div> <div>{duration}</div> </div> ); } componentDidMount() { songDispatcher.registerOnCurrentSongUpdate('DurationLabel', this.handleCurrentSongUpdate.bind(this)); } } /** * Converts seconds to mm:ss. * * @param second * @returns {string} mm:ss */ function secondFormatter(second) { const sec_num = parseInt(second, 10); // don't forget the second param const hours = Math.floor(sec_num / 3600); let minutes = Math.floor((sec_num - (hours * 3600)) / 60); let seconds = sec_num - (hours * 3600) - (minutes * 60); if (minutes < 10) minutes = '0' + minutes; if (seconds < 10) seconds = '0' + seconds; return minutes + ':' + seconds; } export default DurationLabel;
client/components/Player.js
Pocket-titan/Tonlist
import React from 'react' import {Slider} from 'material-ui' import {compose, withState, mapProps} from 'recompose' import {Audio, View, Text, TextInput} from '../components' import ThemeManager from 'material-ui/lib/styles/theme-manager'; import MyRawTheme from '../components/Theme.js'; import ThemeDecorator from 'material-ui/lib/styles/theme-decorator'; let bounds = (min, max, value) => { return Math.min(max, Math.max(min, value)) } let Player = compose( ThemeDecorator(ThemeManager.getMuiTheme(MyRawTheme)), withState('volume', 'setVolume', 0.2), withState('errorTag', 'setError', 0) )(({volume, setVolume, time, URL, setError, errorTag}) => { let onWheel = e => { e.preventDefault() let {deltaY} = e let x = bounds(0, 1, volume - ((deltaY > 0 ? 1 : -1) * 0.01)) setVolume(x) } return ( <View onWheel={onWheel}> <Audio volume={volume} src={`${URL}${time}${errorTag.toString()}.mp3`} onError={() => setError(errorTag + 1)} autoPlay /> <Slider value={volume} onChange={(e, value) => setVolume(value)} style={{ marginBottom: 24 }} /> </View> ) }) export default Player
components/OverlayEngine.js
nvbf/pepper
// @flow import React from 'react'; import { gql, graphql } from 'react-apollo'; import withData from '../libs/withData'; import Scoreboard from './scoreboard/ApolloScoreboard'; import PlayerList from './playerlist/ApolloPlayerList'; /* we need a component that can subscribe to overlay updates, and change the UI accordingly */ class OverlayEngine extends React.Component { componentDidMount() { this.props.subscribeToOverlays(); } render() { if (this.props.loading) { return <div>loading</div>; } if (this.props.overlay.id === 'scoreboard') { return <Scoreboard isShowing={this.props.overlay.isShowing} matchId="123" />; } if (this.props.overlay.id === 'playerlist') { return <PlayerList showHomeTeam isShowing={this.props.overlay.isShowing} matchId="123" />; } return `Overlay:${this.props.data.Overlay.id}`; } } const GET_OVERLAY_QUERY = gql` { Overlay(id: "playerlist") { id isShowing } } `; const OVERLAY_SUBSCRIPTION = gql` subscription SubscribeOnShowing { Overlay { type overlay { id isShowing } } } `; const config = { props: ({ ownProps, data }) => { const overlay = data.Overlay; return { subscribeToOverlays: () => data.subscribeToMore({ document: OVERLAY_SUBSCRIPTION }), loading: data.loading, isShowing: ownProps.isShowing, overlay: data.Overlay, }; }, }; export default graphql(GET_OVERLAY_QUERY, config)(OverlayEngine);
ReactJS/exam prep/react-starter-kit-master/src/index.js
Martotko/JS-Web
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import { BrowserRouter as Router } from 'react-router-dom'; ReactDOM.render(( <Router> <App /> </Router>), document.getElementById('root')); registerServiceWorker();
lib/shared/elements/dynamic-list/container.js
relax/relax
import Component from 'components/component'; import isElementSelected from 'helpers/page-builder/is-element-selected'; import React from 'react'; import PropTypes from 'prop-types'; import {dataConnect} from 'relate-js'; import DynamicList from './dynamic-list'; @dataConnect( (state, props) => ({ isLinkingData: state.pageBuilder && isElementSelected(state.pageBuilder.linkingData, { id: props.relax.element.id, context: props.relax.context }) }), (props) => { const result = { variablesTypes: { schemaList: { schemaId: 'ID!', limit: 'Int' } } }; if (props.schemaId) { result.fragments = { schemaList: { _id: 1, slug: 1, schemaSlug: 1, title: 1, date: 1, publishedDate: 1, updatedDate: 1, state: 1, properties: 1 } }; result.initialVariables = { schemaList: { schemaId: props.schemaId, limit: props.limit } }; } return result; } ) export default class DynamicListContainer extends Component { static propTypes = { renderChildren: PropTypes.func.isRequired, Element: PropTypes.func.isRequired, relax: PropTypes.object.isRequired, schemaId: PropTypes.string, isLinkingData: PropTypes.bool, limit: PropTypes.number, columns: PropTypes.number, verticalGutter: PropTypes.string, horizontalGutter: PropTypes.string, elementsLinks: PropTypes.object, schemaList: PropTypes.array }; componentWillReceiveProps (nextProps) { if (this.props.schemaId !== nextProps.schemaId) { this.props.relate.refresh(nextProps); } } render () { const { relax, limit, columns, verticalGutter, horizontalGutter, isLinkingData, schemaList, schemaLinks, Element, renderChildren } = this.props; return ( <DynamicList entries={schemaList || []} relax={relax} Element={Element} renderChildren={renderChildren} elementsLinks={schemaLinks} limit={limit} columns={columns} verticalGutter={verticalGutter} horizontalGutter={horizontalGutter} isLinkingData={isLinkingData} /> ); } }
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
UnSpiraTive/radio
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
packages/reactor-kitchensink/src/examples/D3/Hierarchy/ZoomableSunburst/ZoomableSunburst.js
dbuhrman/extjs-reactor
import React, { Component } from 'react'; import { Panel } from '@extjs/ext-react'; import { D3_Sunburst } from '@extjs/ext-react-d3'; export default class ZoomableSunburst extends Component { store = Ext.create('Ext.data.TreeStore', { autoLoad: true, defaultRootText: 'd3', fields: [ 'name', 'path', 'size', { name: 'leaf', calculate: function (data) { return data.root ? false : !data.children; } }, { name: 'text', calculate: function (data) { return data.name; } } ], proxy: { type: 'ajax', url: 'resources/data/tree/tree.json' }, idProperty: 'path' }) onTooltip = (component, tooltip, node) => { const record = node.data, size = record.get('size'), n = record.childNodes.length; tooltip.setHtml(size ? Ext.util.Format.fileSize(size) : n + ' file' + (n === 1 ? '' : 's') + ' inside.' ); } render() { return ( <Panel shadow layout="fit"> <D3_Sunburst padding={20} store={this.store} tooltip={{ renderer: this.onTooltip }} transitions={{ select: false }} onSelectionChange={(sunburst, node) => sunburst.zoomInNode(node)} expandEventName={false} /> </Panel> ) } }
actor-apps/app-web/src/app/components/common/Text.react.js
berserkertdl/actor-platform
import _ from 'lodash'; import React from 'react'; import memoize from 'memoizee'; import emojify from 'emojify.js'; import hljs from 'highlight.js'; import marked from 'marked'; import emojiCharacters from 'emoji-named-characters'; emojify.setConfig({ mode: 'img', img_dir: 'assets/img/emoji' // eslint-disable-line }); const mdRenderer = new marked.Renderer(); // target _blank for links mdRenderer.link = function(href, title, text) { let external, newWindow, out; external = /^https?:\/\/.+$/.test(href); newWindow = external || title === 'newWindow'; out = '<a href=\"' + href + '\"'; if (newWindow) { out += ' target="_blank"'; } if (title && title !== 'newWindow') { out += ' title=\"' + title + '\"'; } return (out + '>' + text + '</a>'); }; const markedOptions = { sanitize: true, breaks: true, highlight: function (code) { return hljs.highlightAuto(code).value; }, renderer: mdRenderer }; const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character)); const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), function(name) { return name.replace(/\+/g, '\\+'); }); const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi'); const processText = function(text) { let markedText = marked(text, markedOptions); // need hack with replace because of https://github.com/Ranks/emojify.js/issues/127 const noPTag = markedText.replace(/<p>/g, '<p> '); let emojifiedText = emojify .replace(noPTag.replace(emojiRegexp, (match) => ':' + inversedEmojiCharacters[match] + ':')); return emojifiedText; }; const memoizedProcessText = memoize(processText, { length: 1000, maxAge: 60 * 60 * 1000, max: 10000 }); class Text extends React.Component { static propTypes = { content: React.PropTypes.object.isRequired, className: React.PropTypes.string }; constructor(props) { super(props); } render() { const { content, className } = this.props; return ( <div className={className} dangerouslySetInnerHTML={{__html: memoizedProcessText(content.text)}}> </div> ); } } export default Text;
admin/client/App/screens/Home/components/Lists.js
jstockwin/keystone
import React from 'react'; import _ from 'lodash'; import { connect } from 'react-redux'; import { plural } from '../../../../utils/string'; import ListTile from './ListTile'; export class Lists extends React.Component { render () { return ( <div className="dashboard-group__lists"> {_.map(this.props.lists, (list, key) => { // If an object is passed in the key is the index, // if an array is passed in the key is at list.key const listKey = list.key || key; const href = list.external ? list.path : `${Keystone.adminPath}/${list.path}`; const listData = this.props.listsData[list.path]; const isNoCreate = listData ? listData.nocreate : false; return ( <ListTile key={list.path} path={list.path} label={list.label} hideCreateButton={isNoCreate} href={href} count={plural(this.props.counts[listKey], '* Item', '* Items')} spinner={this.props.spinner} /> ); })} </div> ); } } Lists.propTypes = { counts: React.PropTypes.object.isRequired, lists: React.PropTypes.oneOfType([ React.PropTypes.array, React.PropTypes.object, ]).isRequired, spinner: React.PropTypes.node, }; export default connect((state) => { return { listsData: state.lists.data, }; })(Lists);
modules/dreamview/frontend/src/components/CameraParam/index.js
xiaoxq/apollo
import React, { Component } from 'react'; import ReactTooltip from 'react-tooltip'; import { inject, observer } from 'mobx-react'; import positionIcon from 'assets/images/icons/position.png'; import rotationIcon from 'assets/images/icons/rotation.png'; const ResetSvg = () => ( <svg viewBox="0 0 1024 1024" width="20" height="20" fill="#999999"> <path d="M978.637 890.58H178.116V1024L0 846.551l176.115-174.78v133.42H933.94c29.353 0 44.696-12.008 44.696-41.36V496.99l88.725-141.426V800.52a88.724 88.724 0 0 1-88.725 88.058z m-88.724-667.101H133.42c-29.352 0-44.696 12.008-44.696 42.027v268.175L0 673.105v-450.96a88.724 88.724 0 0 1 88.724-88.725h800.522V0l178.116 178.116-176.115 176.115V220.81z" /> </svg> ); const UpArrowSvg = ({ onClick }) => ( <svg viewBox="0 0 1024 1024" width="15" height="15" onClick={onClick} fill="#999999"> <path d="M820.00415442 790.08350547l-617.53286931-1e-8c-34.17530758 0-61.8167847-27.4267503-61.81678473-61.59899038 0-15.89285244 6.0951742-30.25807684 15.89285244-41.14165922l305.39062223-407.4809563c20.4634662-26.98809409 58.98852574-32.65074716 86.20054921-12.19034849 4.79147569 3.48470957 8.92343326 7.61973466 12.19034848 12.19034849L869.19806953 691.69567529c20.24260435 26.99116162 14.79774561 65.73401549-12.40814284 85.97968733C845.68548239 786.16627474 832.84481844 790.08350547 820.00415442 790.08350547L820.00415442 790.08350547z" /> </svg> ); const DownArrowSvg = ({ onClick }) => ( <svg viewBox="0 0 1024 1024" width="15" height="15" onClick={onClick} fill="#999999"> <path d="M151.477 199.554l718.53099999 0c39.763 0 71.922 31.91 71.92200002 71.674 0 18.485-7.096 35.206-18.48600001 47.872l-355.33 474.125c-23.81 31.4-68.641 37.994-100.297 14.183-5.571-4.052-10.385-8.873-14.183-14.19l-359.398-479.178c-23.547-31.407-17.217-76.48 14.43699999-100.041 12.922-9.881 27.865-14.438 42.80500001-14.439v0l0-0.007zM151.477 199.554z" /> </svg> ); const FIELDS = { Position: { X: 'x', Y: 'y', Z: 'z', }, StaticRotation: { Pitch: 'x', Yaw: 'y', Roll: 'z', }, DynamicRotation: { Pitch: 'y', Yaw: 'z', Roll: 'x', }, }; @inject('store') @observer export default class CameraParam extends Component { constructor(props) { super(props); this.resetParam = this.resetParam.bind(this); } resetParam() { this.props.store.cameraData.reset(); } renderParamRow(type) { function getDeltaColorAndText(delta) { let color = '#FFFFFF'; let text = '-'; if (delta > 0) { color = '#1C9063'; text = `+${delta}`; } else if (delta < 0) { color = '#B43131'; text = delta; } return { color, text }; } const { cameraData } = this.props.store; let step = undefined; switch (type) { case 'Position': { step = 2; break; } case 'StaticRotation': case 'DynamicRotation': { step = 3; break; } default: console.warn('Unknown parameter type:', type); return null; } const rows = Object.keys(FIELDS[type]).map((field) => { const axis = FIELDS[type][field]; const adjustStep = Math.pow(0.1, step); const value = cameraData[`init${type}`].get(axis).toFixed(step); const delta = cameraData[`delta${type}`].get(axis).toFixed(step); const { color, text } = getDeltaColorAndText(delta); return ( <div className="camera-param-row" key={`${type}_${field}`}> <div className="field">{field}</div> <div className="value">{value}</div> <div className="delta" style={{ color }}>{text}</div> <div className="action"> <UpArrowSvg onClick={() => cameraData.update( type, axis, adjustStep, )} /> <DownArrowSvg onClick={() => cameraData.update( type, axis, (-1) * adjustStep, )} /> </div> </div> ); }); return rows; } renderCameraParam() { return ( <div className="monitor-content"> <div className="section"> <div className="section-title" data-tip="Camera position in world coordinate system" data-for="param" > <img height="20px" width="20px" src={positionIcon} /> <span>Position</span> </div> <div className="section-content"> {this.renderParamRow('Position')} </div> </div> <div className="section"> <div className="section-title"> <img height="18px" width="20px" src={rotationIcon} /> <span>Rotation</span> </div> <div className="section-subtitle" data-tip="Camera rotation in IMU coordinate system, default facing to Z negative direction" data-for="param" > Static </div> <div className="section-content"> {this.renderParamRow('StaticRotation')} </div> <div className="section-subtitle" data-tip="IMU rotation in world coordinate system" data-for="param" > Dynamic </div> <div className="section-content"> {this.renderParamRow('DynamicRotation')} </div> </div> <ReactTooltip id="param" place="right" delayShow={300} multiline /> </div> ); } render() { return ( <div className="monitor camera-param"> <div className="monitor-header"> <div className="title">Camera Parameter</div> <div className="actions"> <div className="action" onClick={this.resetParam} data-tip="Reset" data-for="action" > <ResetSvg /> </div> <ReactTooltip id="action" place="left" delayShow={100} /> </div> </div> {this.renderCameraParam()} </div> ); } }
src/screens/SettingsStack/SettingsScreen.js
AzSiAz/LN-Reader
import React from 'react' import { View, AsyncStorage, Alert, StyleSheet } from 'react-native' import { List, ListItem } from 'react-native-elements' export default class SettingsScreen extends React.PureComponent { static navigationOptions = { title: 'Settings', // headerStyle: {}, headerTitleStyle: { color: 'black' } } async clearAppInfo() { await AsyncStorage.removeItem('info') Alert.alert('Done', 'Cleared App Info reload app for it to take effect', [ {text: 'OK'} ], { cancelable: false }) } render() { return ( <View style={styles.container}> <List> <ListItem hideChevron underlayColor='lightgrey' title='Clear App Information' subtitle='Reset Intro' onPress={this.clearAppInfo} /> </List> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, } })
src/routes/lossSection/participate.js
goldylucks/adamgoldman.me
/* eslint-disable react/jsx-curly-brace-presence */ import React from 'react' import { MESSENGER_LINK_WELCOME } from '../../constants' import Markdown from '../../components/Markdown' export default { title: 'Participate', description: 'Description here', html: ( <div> <Markdown source={` I (Adam) am currently at Chiang Mai, Thailand, GMT +7. I'm available in [messenger](${MESSENGER_LINK_WELCOME}) most days between 10am-11pm. When you are ready to have a more [resourceful response](/loss/resourceful-response) to your loss, [message](${MESSENGER_LINK_WELCOME}) me the following: - Brief summary of your loss - From 0-10, how strong are your feelings of loss/miss/emptiness regarding the loss - From 0-10, how resourceful you feel regarding the loss - 3 Available slots for your session - Any questions, comments, or concerns you might have [Talk soon](${MESSENGER_LINK_WELCOME}), &dash; **Adam** `} /> </div> ), }
examples/passing-props-to-children/app.js
aastey/react-router
import React from 'react' import { createHistory, useBasename } from 'history' import { Router, Route, Link, History } from 'react-router' require('./app.css') const history = useBasename(createHistory)({ basename: '/passing-props-to-children' }) const App = React.createClass({ mixins: [ History ], getInitialState() { return { tacos: [ { name: 'duck confit' }, { name: 'carne asada' }, { name: 'shrimp' } ] } }, addTaco() { let name = prompt('taco name?') this.setState({ tacos: this.state.tacos.concat({ name }) }) }, handleRemoveTaco(removedTaco) { this.setState({ tacos: this.state.tacos.filter(function (taco) { return taco.name != removedTaco }) }) this.history.pushState(null, '/') }, render() { let links = this.state.tacos.map(function (taco, i) { return ( <li key={i}> <Link to={`/taco/${taco.name}`}>{taco.name}</Link> </li> ) }) return ( <div className="App"> <button onClick={this.addTaco}>Add Taco</button> <ul className="Master"> {links} </ul> <div className="Detail"> {this.props.children && React.cloneElement(this.props.children, { onRemoveTaco: this.handleRemoveTaco })} </div> </div> ) } }) const Taco = React.createClass({ remove() { this.props.onRemoveTaco(this.props.params.name) }, render() { return ( <div className="Taco"> <h1>{this.props.params.name}</h1> <button onClick={this.remove}>remove</button> </div> ) } }) React.render(( <Router history={history}> <Route path="/" component={App}> <Route path="taco/:name" component={Taco} /> </Route> </Router> ), document.getElementById('example'))
modules/Router.js
littlefoot32/react-router
import React from 'react' import warning from 'warning' import createHashHistory from 'history/lib/createHashHistory' import { createRoutes } from './RouteUtils' import RoutingContext from './RoutingContext' import useRoutes from './useRoutes' import { routes } from './PropTypes' const { func, object } = React.PropTypes /** * A <Router> is a high-level API for automatically setting up * a router that renders a <RoutingContext> with all the props * it needs each time the URL changes. */ const Router = React.createClass({ propTypes: { history: object, children: routes, routes, // alias for children createElement: func, onError: func, onUpdate: func, parseQueryString: func, stringifyQuery: func }, getInitialState() { return { location: null, routes: null, params: null, components: null } }, handleError(error) { if (this.props.onError) { this.props.onError.call(this, error) } else { // Throw errors by default so we don't silently swallow them! throw error // This error probably occurred in getChildRoutes or getComponents. } }, componentWillMount() { let { history, children, routes, parseQueryString, stringifyQuery } = this.props let createHistory = history ? () => history : createHashHistory this.history = useRoutes(createHistory)({ routes: createRoutes(routes || children), parseQueryString, stringifyQuery }) this._unlisten = this.history.listen((error, state) => { if (error) { this.handleError(error) } else { this.setState(state, this.props.onUpdate) } }) }, componentWillReceiveProps(nextProps) { warning( nextProps.history === this.props.history, "The `history` provided to <Router/> has changed, it will be ignored." ) }, componentWillUnmount() { if (this._unlisten) this._unlisten() }, render() { let { location, routes, params, components } = this.state let { createElement } = this.props if (location == null) return null // Async match return React.createElement(RoutingContext, { history: this.history, createElement, location, routes, params, components }) } }) export default Router
app/javascript/mastodon/features/account_gallery/components/media_item.js
KnzkDev/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Icon from 'mastodon/components/icon'; import { autoPlayGif, displayMedia } from 'mastodon/initial_state'; import classNames from 'classnames'; import { decode } from 'blurhash'; import { isIOS } from 'mastodon/is_mobile'; export default class MediaItem extends ImmutablePureComponent { static propTypes = { attachment: ImmutablePropTypes.map.isRequired, displayWidth: PropTypes.number.isRequired, onOpenMedia: PropTypes.func.isRequired, }; state = { visible: displayMedia !== 'hide_all' && !this.props.attachment.getIn(['status', 'sensitive']) || displayMedia === 'show_all', loaded: false, }; componentDidMount () { if (this.props.attachment.get('blurhash')) { this._decode(); } } componentDidUpdate (prevProps) { if (prevProps.attachment.get('blurhash') !== this.props.attachment.get('blurhash') && this.props.attachment.get('blurhash')) { this._decode(); } } _decode () { const hash = this.props.attachment.get('blurhash'); const pixels = decode(hash, 32, 32); if (pixels) { const ctx = this.canvas.getContext('2d'); const imageData = new ImageData(pixels, 32, 32); ctx.putImageData(imageData, 0, 0); } } setCanvasRef = c => { this.canvas = c; } handleImageLoad = () => { this.setState({ loaded: true }); } handleMouseEnter = e => { if (this.hoverToPlay()) { e.target.play(); } } handleMouseLeave = e => { if (this.hoverToPlay()) { e.target.pause(); e.target.currentTime = 0; } } hoverToPlay () { return !autoPlayGif && ['gifv', 'video'].indexOf(this.props.attachment.get('type')) !== -1; } handleClick = e => { if (e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); if (this.state.visible) { this.props.onOpenMedia(this.props.attachment); } else { this.setState({ visible: true }); } } } render () { const { attachment, displayWidth } = this.props; const { visible, loaded } = this.state; const width = `${Math.floor((displayWidth - 4) / 3) - 4}px`; const height = width; const status = attachment.get('status'); const title = status.get('spoiler_text') || attachment.get('description'); let thumbnail = ''; let icon; if (attachment.get('type') === 'unknown') { // Skip } else if (attachment.get('type') === 'image') { const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0; const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0; const x = ((focusX / 2) + .5) * 100; const y = ((focusY / -2) + .5) * 100; thumbnail = ( <img src={attachment.get('preview_url')} alt={attachment.get('description')} title={attachment.get('description')} style={{ objectPosition: `${x}% ${y}%` }} onLoad={this.handleImageLoad} /> ); } else if (['gifv', 'video'].indexOf(attachment.get('type')) !== -1) { const autoPlay = !isIOS() && autoPlayGif; thumbnail = ( <div className={classNames('media-gallery__gifv', { autoplay: autoPlay })}> <video className='media-gallery__item-gifv-thumbnail' aria-label={attachment.get('description')} title={attachment.get('description')} role='application' src={attachment.get('url')} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} autoPlay={autoPlay} loop muted /> <span className='media-gallery__gifv__label'>GIF</span> </div> ); } if (!visible) { icon = ( <span className='account-gallery__item__icons'> <Icon id='eye-slash' /> </span> ); } return ( <div className='account-gallery__item' style={{ width, height }}> <a className='media-gallery__item-thumbnail' href={status.get('url')} target='_blank' onClick={this.handleClick} title={title}> <canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && loaded })} /> {visible && thumbnail} {!visible && icon} </a> </div> ); } }
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch04/04_03/finish/src/index.js
yevheniyc/Autodidact
import React from 'react' import { render } from 'react-dom' import './stylesheets/ui.scss' import { SkiDayCount } from './components/SkiDayCount' window.React = React render( <SkiDayCount />, document.getElementById('react-container') ) // render( // <SkiDayList days={ // [ // { // resort: "Squaw Valley", // date: new Date("1/2/2016"), // powder: true, // backcountry: false // }, // { // resort: "Kirkwood", // date: new Date("3/28/2016"), // powder: false, // backcountry: false // }, // { // resort: "Mt. Tallac", // date: new Date("4/2/2016"), // powder: false, // backcountry: true // } // ] // }/>, // document.getElementById('react-container') // )
index.js
algolia/react-nouislider
import PropTypes from 'prop-types'; import React from 'react'; import nouislider from 'nouislider'; class Nouislider extends React.Component { componentDidMount() { if (this.props.disabled) this.sliderContainer.setAttribute('disabled', true); else this.sliderContainer.removeAttribute('disabled'); this.createSlider(); } componentDidUpdate() { if (this.props.disabled) this.sliderContainer.setAttribute('disabled', true); else this.sliderContainer.removeAttribute('disabled'); this.slider.destroy(); this.createSlider(); } componentWillUnmount() { this.slider.destroy(); } createSlider() { var slider = (this.slider = nouislider.create(this.sliderContainer, { ...this.props })); if (this.props.onUpdate) { slider.on('update', this.props.onUpdate); } if (this.props.onChange) { slider.on('change', this.props.onChange); } if (this.props.onSlide) { slider.on('slide', this.props.onSlide); } if (this.props.onStart) { slider.on('start', this.props.onStart); } if (this.props.onEnd) { slider.on('end', this.props.onEnd); } if (this.props.onSet) { slider.on('set', this.props.onSet); } } render() { return ( <div ref={slider => { this.sliderContainer = slider; }} /> ); } } Nouislider.propTypes = { // http://refreshless.com/nouislider/slider-options/#section-animate animate: PropTypes.bool, // http://refreshless.com/nouislider/behaviour-option/ behaviour: PropTypes.string, // http://refreshless.com/nouislider/slider-options/#section-Connect connect: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.bool), PropTypes.bool]), // http://refreshless.com/nouislider/slider-options/#section-cssPrefix cssPrefix: PropTypes.string, // http://refreshless.com/nouislider/slider-options/#section-orientation direction: PropTypes.oneOf(['ltr', 'rtl']), // http://refreshless.com/nouislider/more/#section-disable disabled: PropTypes.bool, // http://refreshless.com/nouislider/slider-options/#section-limit limit: PropTypes.number, // http://refreshless.com/nouislider/slider-options/#section-margin margin: PropTypes.number, // http://refreshless.com/nouislider/events-callbacks/#section-change onChange: PropTypes.func, // http://refreshless.com/nouislider/events-callbacks/ onEnd: PropTypes.func, // http://refreshless.com/nouislider/events-callbacks/#section-set onSet: PropTypes.func, // http://refreshless.com/nouislider/events-callbacks/#section-slide onSlide: PropTypes.func, // http://refreshless.com/nouislider/events-callbacks/ onStart: PropTypes.func, // http://refreshless.com/nouislider/events-callbacks/#section-update onUpdate: PropTypes.func, // http://refreshless.com/nouislider/slider-options/#section-orientation orientation: PropTypes.oneOf(['horizontal', 'vertical']), // http://refreshless.com/nouislider/pips/ pips: PropTypes.object, // http://refreshless.com/nouislider/slider-values/#section-range range: PropTypes.object.isRequired, // http://refreshless.com/nouislider/slider-options/#section-start start: PropTypes.arrayOf(PropTypes.number).isRequired, // http://refreshless.com/nouislider/slider-options/#section-step step: PropTypes.number, // http://refreshless.com/nouislider/slider-options/#section-tooltips tooltips: PropTypes.oneOfType([ PropTypes.bool, PropTypes.arrayOf( PropTypes.shape({ to: PropTypes.func }) ) ]) }; module.exports = Nouislider;
public/pages/AdminOverview.js
datpham23/datndiana
import React from 'react' import {Modal,Alert} from 'react-bootstrap'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as GuestActions from '../actions/guestActions'; import Griddle from 'griddle-react'; import '../sass/admin-overview.scss'; const AdminOverview = React.createClass({ componentWillMount: function() { this.actions = bindActionCreators(GuestActions,this.props.dispatch); }, onGuestFormUpdate(e){ this.actions.updateGuestForm(e.target.value); }, render() { let {guestsStore} = this.props; let rows = guestsStore.guests.map(guest=>{ return { 'Name' : guest.name, 'Email' : guest.email, 'Phone' : guest.phone, 'Number of Guests Allowed' : guest.numberOfGuests, 'Vegetarian' : guest.vegetarian? 'YES' : 'NO', 'Status' : guest, 'Guests' : guest.guests, 'id' : guest.id, } }); var columnMeta = [ { 'columnName': 'Status', 'locked': false, 'visible': true, 'customComponent': (props)=>{ return ( <span> { props.data.hasRSVP? `REPLIED (${props.data.guests.length})` : '' } </span> ); } }, { 'columnName': 'Guests', 'locked': false, 'visible': true, 'customComponent': (props)=>{ return ( <span> { props.data? props.data.join(', ') : null } </span> ); } } ]; return ( <div className="admin-overview"> <div className="button-container"> <button className="btn btn-default" onClick={this.actions.showModal}> Import Guests </button> <button className="btn btn-default"> Export To Excel </button> <Modal show={guestsStore.showModal} onHide={this.actions.hideModal}> <Modal.Header closeButton> <Modal.Title>Import Guests</Modal.Title> </Modal.Header> <Modal.Body> <div className="guest-import"> <strong>Sample Row</strong> <div>Name, Email, Phone Number, Number of Guests</div> <br/> { guestsStore.saveGuestsError? <Alert bsStyle='danger'> {guestsStore.saveGuestsErrorMessage} </Alert> : null } { guestsStore.isSavingGuests? <div className="loader"/> : <textarea value={guestsStore.guestForm} rows="4" cols="50" onChange={this.onGuestFormUpdate}/> } </div> </Modal.Body> <Modal.Footer> <button className="btn btn-primary" onClick={this.actions.saveGuests}> Save </button> </Modal.Footer> </Modal> </div> <div> { guestsStore.isFetching? <div className="loader"/> : <div> <Griddle showFilter={true} resultsPerPage={1000} tableClassName='table table-striped table-hover' results={rows} columns={['Name', 'Email', 'Phone', 'Number of Guests Allowed','Vegetarian','Status', 'Guests']} useGriddleStyles={false} columnMetadata={columnMeta} /> </div> } </div> </div> ) } }) export default connect(state=>{ return { guestsStore : state.guests.toJS() } })(AdminOverview);
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestAndDefault.js
ontruck/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load({ id, ...rest } = { id: 0, user: { id: 42, name: '42' } }) { return [ { id: id + 1, name: '1' }, { id: id + 2, name: '2' }, { id: id + 3, name: '3' }, rest.user, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-rest-and-default"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
examples/infinite-scrolling/src/components/RepositoryCount.js
lore/lore
import React from 'react'; import createReactClass from 'create-react-class'; import PropTypes from 'prop-types'; import PayloadStates from '../constants/PayloadStates'; export default createReactClass({ displayName: 'RepositoryCount', propTypes: { pages: PropTypes.array.isRequired }, getStyles: function() { return { count: { textAlign: 'center', opacity: '0.54' } } }, render: function() { const pages = this.props.pages; const styles = this.getStyles(); const numberOfPages = pages.length; const firstPage = pages[0]; const lastPage = pages[numberOfPages - 1]; const repositoriesPerPage = firstPage.data.length; let resultCount = 0; let totalRepositories = 0; if (lastPage.state === PayloadStates.FETCHING) { resultCount = (numberOfPages - 1)*repositoriesPerPage; totalRepositories = firstPage.meta.totalCount; } else { resultCount = numberOfPages*repositoriesPerPage; totalRepositories = lastPage.meta.totalCount; } return ( <h4 style={styles.count}> Showing {resultCount} of {totalRepositories} repositories with > 1000 stars </h4> ); } });
js-old/MyTitle.js
aramay/complete-intro-to-react-v2
import React from 'react' var MyTitle = React.createClass({ render: function () { console.log(this.props) const color = {color: this.props.color} console.log(color) return ( <div> <h1 style={color}> {this.props.title} </h1> </div> ) } }) export default MyTitle
src/components/ChaptersList/ChaptersList.js
suhodolskiy/bsuir-evt-laba-2017
import React from 'react'; import { observer } from 'mobx-react'; import { SortableContainer, SortableElement } from 'react-sortable-hoc'; import './chaptersList.scss'; import ChapterCard from '../СhapterCard/ChapterCard'; export default SortableContainer( observer(({ chapters, moveChapterToBlank }) => ( <ul className="chapters-list"> {chapters.map((chapter, i) => ( <ChapterCard moveChapterToBlank={moveChapterToBlank} chapter={chapter} key={`chapter-${i}`} index={i} number={i + 1} /> ))} </ul> )) ); // function ChaptersList({ chapters }) { // // const List = SortableContainer(({ chapters }) => chapters.map((chapter, index) => <SortableItem chapter={chapter}/>)); // return ( // <SortableContainer> // {() => // chapters.map((chapter, index) => <SortableItem chapter={chapter}/>) // } // </SortableContainer> // ) // } // const { chapters } = this.props; // // if (!chapters || !chapters.length) { // return ( // <div className="chapters-list chapters-list--empty">Список пуст</div> // ); // }
app/addons/documents/index-results/components/pagination/PaginationFooter.js
popojargo/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import React from 'react'; import PagingControls from './PagingControls.js'; import PerPageSelector from './PerPageSelector.js'; import TableControls from './TableControls'; export default class PaginationFooter extends React.Component { constructor(props) { super(props); } getPageNumberText () { const { docs, pageStart, pageEnd } = this.props; if (docs.length === 0) { return <span>Showing 0 documents.</span>; } return <span>Showing document {pageStart} - {pageEnd}.</span>; } perPageChange (amount) { const { updatePerPageResults, fetchParams, queryOptionsParams } = this.props; updatePerPageResults(amount, fetchParams, queryOptionsParams); } nextClicked (event) { event.preventDefault(); const { canShowNext, fetchParams, queryOptionsParams, paginateNext, perPage } = this.props; if (canShowNext) { paginateNext(fetchParams, queryOptionsParams, perPage); } } previousClicked (event) { event.preventDefault(); const { canShowPrevious, fetchParams, queryOptionsParams, paginatePrevious, perPage } = this.props; if (canShowPrevious) { paginatePrevious(fetchParams, queryOptionsParams, perPage); } } render () { const { showPrioritizedEnabled, hasResults, prioritizedEnabled, displayedFields, perPage, canShowNext, canShowPrevious, toggleShowAllColumns } = this.props; return ( <footer className="index-pagination pagination-footer"> <PagingControls nextClicked={this.nextClicked.bind(this)} previousClicked={this.previousClicked.bind(this)} canShowNext={canShowNext} canShowPrevious={canShowPrevious} /> <div className="footer-controls"> <div className="page-controls"> {showPrioritizedEnabled && hasResults ? <TableControls prioritizedEnabled={prioritizedEnabled} displayedFields={displayedFields} toggleShowAllColumns={toggleShowAllColumns} /> : null} </div> <PerPageSelector perPageChange={this.perPageChange.bind(this)} perPage={perPage} /> <div className="current-docs"> {this.getPageNumberText()} </div> </div> </footer> ); } };
src/components/doctrine/original/DoctrineOriginal.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './DoctrineOriginal.svg' /** DoctrineOriginal */ function DoctrineOriginal({ width, height, className }) { return ( <SVGDeviconInline className={'DoctrineOriginal' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } DoctrineOriginal.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default DoctrineOriginal
src/index.js
HHPnet/frontend
import React from 'react' import ReactDOM from 'react-dom' import injectTapEventPlugin from 'react-tap-event-plugin' import App from './components/common/app/App' import 'bootstrap/dist/css/bootstrap.css' //import 'bootstrap/dist/css/bootstrap-theme.css' //import 'bootstrap-material-design/dist/css/bootstrap-material-design.css' //import 'bootstrap-material-design/dist/css/ripples.css' import './index.css' injectTapEventPlugin() ReactDOM.render( <App />, document.getElementById('root') );
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/DefaultPropsInline.js
jamesgpearce/flow
// @flow import React from 'react'; class MyComponent extends React.Component { static defaultProps: {a: number, b: number, c: number} = {a: 1, b: 2, c: 3}; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { static defaultProps: {a: number, b: number, c: number} = {a: 1, b: 2, c: 3}; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
client/views/admin/federationDashboard/OverviewSection.stories.js
VoiSmart/Rocket.Chat
import React from 'react'; import OverviewSection from './OverviewSection'; export default { title: 'admin/federationDashboard/OverviewSection', component: OverviewSection, }; export const Default = () => <OverviewSection />;
docs/app/Examples/elements/Icon/States/index.js
mohammed88/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const IconStatesExamples = () => ( <ExampleSection title='States'> <ComponentExample title='Disabled' description='An icon can show that it is disabled.' examplePath='elements/Icon/States/IconExampleDisabled' /> <ComponentExample title='Loading' description='An icon can be used as a simple loader.' examplePath='elements/Icon/States/IconExampleLoading' /> </ExampleSection> ) export default IconStatesExamples
docs-ui/components/emptyMessage.stories.js
looker/sentry
import React from 'react'; import {Panel, PanelHeader} from 'app/components/panels'; import {storiesOf} from '@storybook/react'; import {withInfo} from '@storybook/addon-info'; import Button from 'app/components/buttons/button'; import EmptyMessage from 'app/views/settings/components/emptyMessage'; storiesOf('EmptyMessage', module) .add( 'default', withInfo('Super Generic')(() => ( <div style={{background: '#fff'}}> <EmptyMessage>Nothing to see here</EmptyMessage> </div> )) ) .add( 'in panel', withInfo('Put this in a panel for maximum effect')(() => ( <Panel> <PanelHeader>Audit Log</PanelHeader> <EmptyMessage>No critical actions taken in this period</EmptyMessage> </Panel> )) ) .add( 'in panel with icon', withInfo('Put this in a panel for maximum effect')(() => ( <Panel> <PanelHeader>Members</PanelHeader> <EmptyMessage icon="icon-user" size="large"> Sentry is better with friends </EmptyMessage> </Panel> )) ) .add( 'in panel with icon and action', withInfo('Put this in a panel for maximum effect')(() => ( <Panel> <PanelHeader>Members</PanelHeader> <EmptyMessage icon="icon-user" action={<Button priority="primary">Invite Members</Button>} > Sentry is better with friends </EmptyMessage> </Panel> )) ) .add( 'in panel with sub-description', withInfo('Put this in a panel for maximum effect')(() => ( <Panel> <PanelHeader>Members</PanelHeader> <EmptyMessage title="Sentry is better with Friends" description="When you use sentry with friends, you'll find your world of possibilities expands!" /> </Panel> )) );
classic/src/scenes/wbui/ULinkOR/ULinkORAccountSection/MailboxListItem/MailboxListItemSubServiceItem.js
wavebox/waveboxapp
import React from 'react' import PropTypes from 'prop-types' import shallowCompare from 'react-addons-shallow-compare' import { ListItemSecondaryAction, Tooltip, IconButton } from '@material-ui/core' import { withStyles } from '@material-ui/core/styles' import ACAvatarCircle2 from '../../../ACAvatarCircle2' import MailboxServiceBadge from '../../../MailboxServiceBadge' import classNames from 'classnames' import TabIcon from '@material-ui/icons/Tab' import OpenInNewIcon from '@material-ui/icons/OpenInNew' import ULinkORListItem from '../../ULinkORListItem' import ULinkORListItemText from '../../ULinkORListItemText' const privAccountStore = Symbol('privAccountStore') const styles = { root: { paddingTop: 0, paddingBottom: 0, paddingRight: 84, paddingLeft: 32, height: 48 }, avatarContainer: { position: 'relative', width: 28, minWidth: 28, height: 28, minHeight: 28, marginRight: 4 }, badge: { position: 'absolute', fontWeight: process.platform === 'linux' ? 'normal' : '300', height: 18, minWidth: 18, width: 'auto', lineHeight: '18px', fontSize: '10px', top: -3, right: -7, boxShadow: ' 0px 0px 1px 0px rgba(0,0,0,0.8)' }, badgeFAIcon: { color: 'white', fontSize: '10px' }, badgeContainer: { display: 'flex', position: 'relative', justifyContent: 'center', alignItems: 'center', width: 28, height: 28 } } @withStyles(styles) class MailboxListItemSubServiceItem extends React.Component { /* **************************************************************************/ // Class /* **************************************************************************/ static propTypes = { serviceId: PropTypes.string.isRequired, accountStore: PropTypes.object.isRequired, avatarResolver: PropTypes.func.isRequired, onOpenInRunningService: PropTypes.func.isRequired, onOpenInServiceWindow: PropTypes.func.isRequired } /* **************************************************************************/ // Lifecycle /* **************************************************************************/ constructor (props) { super(props) this[privAccountStore] = this.props.accountStore // Generate state this.state = { ...this.generateServiceState(this.props.serviceId, this[privAccountStore].getState()) } } /* **************************************************************************/ // Component lifecycle /* **************************************************************************/ componentDidMount () { this[privAccountStore].listen(this.accountUpdated) } componentWillUnmount () { this[privAccountStore].unlisten(this.accountUpdated) } componentWillReceiveProps (nextProps) { if (this.props.accountStore !== nextProps.accountStore) { console.warn('Changing props.accountStore is not supported in ULinkORAccountResultListItem and will be ignored') } if (this.props.serviceId !== nextProps.serviceId) { this.setState( this.generateServiceState(nextProps.serviceId, this[privAccountStore].getState()) ) } } /* **************************************************************************/ // Data lifecycle /* **************************************************************************/ accountUpdated = (accountState) => { this.setState( this.generateServiceState(this.props.serviceId, accountState) ) } generateServiceState (serviceId, accountState) { const mailbox = accountState.getMailboxForService(serviceId) const service = accountState.getService(serviceId) const serviceData = accountState.getServiceData(serviceId) if (mailbox && service && serviceData) { const authData = accountState.getMailboxAuthForServiceId(serviceId) const isServiceSleeping = accountState.isServiceSleeping(serviceId) return { membersAvailable: true, displayName: accountState.resolvedServiceDisplayName(serviceId), serviceAvatar: accountState.getServiceAvatarConfig(serviceId), isServiceSleeping: isServiceSleeping, supportsUnreadCount: service.supportsUnreadCount, showBadgeCount: service.showBadgeCount, unreadCount: serviceData.getUnreadCount(service), hasUnreadActivity: serviceData.getHasUnreadActivity(service), supportsUnreadActivity: service.supportsUnreadActivity, showBadgeActivity: service.showBadgeActivity, badgeColor: service.badgeColor, documentTitle: serviceData.documentTitle, nextUrl: isServiceSleeping ? service.getUrlWithData(serviceData, authData) : service.url } } else { return { membersAvailable: false } } } /* **************************************************************************/ // UI Events /* **************************************************************************/ /** * Handles a click somewhere in the list item * @param evt: the event that fired */ handleListItemClick = (evt) => { const { onClick, onOpenInServiceWindow, serviceId } = this.props onOpenInServiceWindow(evt, serviceId) if (onClick) { onClick(evt) } } /** * Handles the open in account button being clicked * @param evt: the event that fired */ handleOpenInAccountClick = (evt) => { evt.preventDefault() evt.stopPropagation() const { onOpenInRunningService, serviceId } = this.props onOpenInRunningService(evt, serviceId) } /** * Handles the open in window button being clicked * @param evt: the event that fired */ handleOpenInWindowClick = (evt) => { evt.preventDefault() evt.stopPropagation() const { onOpenInServiceWindow, serviceId } = this.props onOpenInServiceWindow(evt, serviceId) } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { const { classes, serviceId, avatarResolver, accountStore, onOpenInRunningService, onOpenInServiceWindow, className, onClick, ...passProps } = this.props const { membersAvailable, displayName, serviceAvatar, isServiceSleeping, supportsUnreadCount, showBadgeCount, unreadCount, hasUnreadActivity, supportsUnreadActivity, showBadgeActivity, badgeColor, documentTitle, nextUrl } = this.state if (!membersAvailable) { return false } return ( <ULinkORListItem className={classNames(className, classes.root)} onClick={this.handleListItemClick} {...passProps}> <div className={classes.avatarContainer}> <MailboxServiceBadge badgeClassName={classes.badge} className={classes.badgeContainer} iconClassName={classes.badgeFAIcon} supportsUnreadCount={supportsUnreadCount} showUnreadBadge={showBadgeCount} unreadCount={unreadCount} supportsUnreadActivity={supportsUnreadActivity} showUnreadActivityBadge={showBadgeActivity} hasUnreadActivity={hasUnreadActivity} color={badgeColor} isAuthInvalid={false}> <ACAvatarCircle2 avatar={serviceAvatar} size={28} resolver={avatarResolver} showSleeping={isServiceSleeping} circleProps={{ showSleeping: false }} /> </MailboxServiceBadge> </div> <ULinkORListItemText primary={displayName} primaryTypographyProps={{ noWrap: true }} secondary={documentTitle && documentTitle !== displayName ? documentTitle : nextUrl} secondaryTypographyProps={{ noWrap: true }} /> <ListItemSecondaryAction> <Tooltip title='Open in existing account tab'> <IconButton onClick={this.handleOpenInAccountClick}> <TabIcon /> </IconButton> </Tooltip> <Tooltip title='Open in new Window'> <IconButton onClick={this.handleOpenInWindowClick}> <OpenInNewIcon /> </IconButton> </Tooltip> </ListItemSecondaryAction> </ULinkORListItem> ) } } export default MailboxListItemSubServiceItem
node_modules/react-router/es6/Link.js
TheeSweeney/ComplexReactReduxMiddlewareReview
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { routerShape } from './PropTypes'; var _React$PropTypes = React.PropTypes; var bool = _React$PropTypes.bool; var object = _React$PropTypes.object; var string = _React$PropTypes.string; var func = _React$PropTypes.func; var oneOfType = _React$PropTypes.oneOfType; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function createLocationDescriptor(to, _ref) { var query = _ref.query; var hash = _ref.hash; var state = _ref.state; if (query || hash || state) { return { pathname: to, query: query, hash: hash, state: state }; } return to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ var Link = React.createClass({ displayName: 'Link', contextTypes: { router: routerShape }, propTypes: { to: oneOfType([string, object]), query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func, target: string }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { if (this.props.onClick) this.props.onClick(event); if (event.defaultPrevented) return; !this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0; if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return; event.preventDefault(); var _props = this.props; var to = _props.to; var query = _props.query; var hash = _props.hash; var state = _props.state; var location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); this.context.router.push(location); }, render: function render() { var _props2 = this.props; var to = _props2.to; var query = _props2.query; var hash = _props2.hash; var state = _props2.state; var activeClassName = _props2.activeClassName; var activeStyle = _props2.activeStyle; var onlyActiveOnIndex = _props2.onlyActiveOnIndex; var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0; // Ignore if rendered outside the context of router, simplifies unit testing. var router = this.context.router; if (router) { // If user does not specify a `to` prop, return an empty anchor tag. if (to == null) { return React.createElement('a', props); } var location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); props.href = router.createHref(location); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(location, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
example/App.js
BBuzzArt/react-native-infinite
import React from 'react'; import { StyleSheet, Text, View, TouchableHighlight, ScrollView } from 'react-native'; import { StackNavigator } from 'react-navigation'; import * as src from './src'; class App extends React.Component { render() { const { props } = this; return ( <View style={css.viewport}> <ScrollView style={css.index}> <TouchableHighlight activeOpacity={1} underlayColor="rgba(0,0,0,.01)" onPress={() => props.navigation.navigate('ExampleBasic')}> <View style={css.item}> <Text style={css.item__text}>Basic / load items to infinity</Text> </View> </TouchableHighlight> <TouchableHighlight activeOpacity={1} underlayColor="rgba(0,0,0,.01)" onPress={() => props.navigation.navigate('ExampleResize')}> <View style={css.item}> <Text style={css.item__text}>Resize / resize screen event</Text> </View> </TouchableHighlight> <TouchableHighlight activeOpacity={1} underlayColor="rgba(0,0,0,.01)" onPress={() => props.navigation.navigate('ExampleScroll')}> <View style={css.item}> <Text style={css.item__text}>Scroll / scroll event method</Text> </View> </TouchableHighlight> <TouchableHighlight activeOpacity={1} underlayColor="rgba(0,0,0,.01)" onPress={() => props.navigation.navigate('ExampleGrid')}> <View style={css.item}> <Text style={css.item__text}>Grid / random size blocks</Text> </View> </TouchableHighlight> </ScrollView> </View> ); } } const css = StyleSheet.create({ viewport: { flex: 1, }, index: {}, item: { paddingVertical: 15, paddingHorizontal: 15, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: 'rgba(0,0,0,.2)', }, item__text: { fontWeight: '600', fontSize: 16, color: '#324dff', }, cardStyle: { backgroundColor: '#fff' }, headerStyle: { backgroundColor: '#fff', borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: '#aaa', }, }); export default StackNavigator({ Home: { screen: App, navigationOptions: { title: 'Demos', headerStyle: css.headerStyle } }, ExampleBasic: { screen: src.ExampleBasic, navigationOptions: { title: 'Basic', headerStyle: css.headerStyle } }, ExampleResize: { screen: src.ExampleResize, navigationOptions: { title: 'Resize', headerStyle: css.headerStyle } }, ExampleScroll: { screen: src.ExampleScroll, navigationOptions: { title: 'Scroll', headerStyle: css.headerStyle } }, ExampleGrid: { screen: src.ExampleGrid, navigationOptions: { title: 'Grid', headerStyle: css.headerStyle } }, }, { cardStyle: css.cardStyle, });
packages/react-scripts/fixtures/kitchensink/src/features/syntax/TemplateInterpolation.js
RobzDoom/frame_trap
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load(name) { return [ { id: 1, name: `${name}1` }, { id: 2, name: `${name}2` }, { id: 3, name: `${name}3` }, { id: 4, name: `${name}4` }, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load('user_'); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-template-interpolation"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
source/component/listview/userPostRow.js
togayther/react-native-cnblogs
import React, { Component } from 'react'; import { View, Text, Image, TouchableHighlight } from 'react-native'; import _ from 'lodash'; import moment from 'moment'; import PureRenderMixin from 'react-addons-pure-render-mixin'; import { decodeHTML, getBloggerAvatar } from '../../common'; import { ComponentStyles, CommonStyles, StyleConfig } from '../../style'; class UserPostRow extends Component { constructor(props) { super(props); this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this); } getPostInfo(){ let { post } = this.props; let postInfo = {}; if (post && post.Id) { postInfo.Id = post.Id; postInfo.ViewCount = post.ViewCount; postInfo.CommentCount = post.CommentCount; postInfo.Title = decodeHTML(post.Title); if (post.Description) { postInfo.Description = _.truncate(decodeHTML(post.Description), { length : 70 }); } postInfo.DateAdded = moment(post.PostDate).startOf('minute').fromNow(); postInfo.Author = decodeHTML(post.Author); postInfo.Blogger = post.BlogApp; postInfo.Avatar = getBloggerAvatar(post.Avatar); } return postInfo; } renderPostTitle(postInfo){ return ( <View style={ [ CommonStyles.m_b_1 ] }> <Text style={ [CommonStyles.text_black, CommonStyles.font_sm, CommonStyles.line_height_md ] }> { postInfo.Title } </Text> </View> ) } renderPostDescr(postInfo){ return ( <View style={ [ CommonStyles.m_b_2 ] }> <Text style={ [ CommonStyles.text_gray, CommonStyles.font_xs, CommonStyles.line_height_sm ] }> { postInfo.Description } </Text> </View> ) } renderPostMeta(postInfo){ return ( <View style={ [ CommonStyles.flexRow, CommonStyles.flexItemsBetween ] }> <Text style={ [CommonStyles.text_gray, CommonStyles.font_ms] }> { postInfo.DateAdded } </Text> <View> <Text style={ [ CommonStyles.text_primary ] }> { postInfo.CommentCount + ' / ' + postInfo.ViewCount } </Text> </View> </View> ) } render() { const postInfo = this.getPostInfo(); return ( <TouchableHighlight onPress={(e)=>{ this.props.onRowPress(postInfo) }} underlayColor={ StyleConfig.touchable_press_color } key={ postInfo.Id }> <View style={ ComponentStyles.list }> { this.renderPostTitle(postInfo) } { this.renderPostDescr(postInfo) } { this.renderPostMeta(postInfo) } </View> </TouchableHighlight> ) } } export default UserPostRow;