path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
node_modules/react-bootstrap/es/Alert.js
yeshdev1/Everydays-project
import _Object$values from 'babel-runtime/core-js/object/values'; 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 PropTypes from 'prop-types'; import { bsClass, bsStyles, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; import { State } from './utils/StyleConfig'; var propTypes = { onDismiss: PropTypes.func, closeLabel: PropTypes.string }; var defaultProps = { closeLabel: 'Close alert' }; var Alert = function (_React$Component) { _inherits(Alert, _React$Component); function Alert() { _classCallCheck(this, Alert); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Alert.prototype.renderDismissButton = function renderDismissButton(onDismiss) { return React.createElement( 'button', { type: 'button', className: 'close', onClick: onDismiss, 'aria-hidden': 'true', tabIndex: '-1' }, React.createElement( 'span', null, '\xD7' ) ); }; Alert.prototype.renderSrOnlyDismissButton = function renderSrOnlyDismissButton(onDismiss, closeLabel) { return React.createElement( 'button', { type: 'button', className: 'close sr-only', onClick: onDismiss }, closeLabel ); }; Alert.prototype.render = function render() { var _extends2; var _props = this.props, onDismiss = _props.onDismiss, closeLabel = _props.closeLabel, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['onDismiss', 'closeLabel', 'className', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var dismissable = !!onDismiss; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'dismissable')] = dismissable, _extends2)); return React.createElement( 'div', _extends({}, elementProps, { role: 'alert', className: classNames(className, classes) }), dismissable && this.renderDismissButton(onDismiss), children, dismissable && this.renderSrOnlyDismissButton(onDismiss, closeLabel) ); }; return Alert; }(React.Component); Alert.propTypes = propTypes; Alert.defaultProps = defaultProps; export default bsStyles(_Object$values(State), State.INFO, bsClass('alert', Alert));
components/index.js
volodalexey/spachat
import React from 'react' import {Router, Route, browserHistory} from 'react-router' import localization from '../js/localization.js' import users_bus from '../js/users_bus.js' import Login from '../components/login' import Chat_App from '../components/chat_app' const requireAuth = function(nextState, replace) { users_bus.checkLoginState(); if (!users_bus.getUserId()) { redirectToLogin(nextState, replace); } }, noMatchRedirect = function(nextState, replace) { users_bus.checkLoginState(); if (users_bus.getUserId()) { replace('/chat'); } else { replace('/account'); } }, redirectToLogin = function(nextState, replace) { if(nextState.location.search){ browserHistory.desired_path = nextState.location.pathname; browserHistory.desired_search = nextState.location.search; } replace('/account'); }, Index = React.createClass({ componentWillMount(){ var language = localStorage.getItem('language'); if (language && localization.lang !== language) { localization.setLanguage(language); } }, render() { return ( <Router history={browserHistory}> <Route path="/" onEnter={noMatchRedirect}/> <Route path="/"> <Route path="account" component={Login}/> <Route path="chat" component={Chat_App} onEnter={requireAuth}/> </Route> <Route path="*" onEnter={noMatchRedirect}/> </Router> ) } }); export default Index;
src/MainPage.js
Mathannus/porvoonkuntoajot
import React, { Component } from 'react'; import {Link} from 'react-router-dom'; import './MainPage.css' class MainPage extends Component { render() { return ( <div className="mainPage"> <div className="filler-div">&nbsp;</div> <div className="contentBox"> <h1>PORVOON KUNTOAJOT 4.8. 2019 KLO 10.00</h1> Tervetuloa polkemaan idyllinen kuntoajo Itä-Uudenmaan kauniisiin jokilaaksoihin ja kumpuileviin maalaismaisemiin sunnuntaina 4.8.2019 Ajajilta suurta kiitosta saaneissa Porvoon Kuntoajoissa on kaksi eri matkaa: <ul> <li>Pidempi reitti on 110 kilometriä ja luonteeltaan mäkinen ja vaativa.</li> <li>Lyhyempi on 55 kilometriä ja reittinä helpompi ja sopii kaikille kuntoilijoille.</li> </ul> <p> Kaikkien sarjojen lähdöt toteutetaan yhteislähtöinä, joten tunnelmaa on suurten ajojen tyyliin lähdöstä maaliin asti. </p> <p> Varaa paikkasi ajoissa, sillä vain 400 ensimmäistä lunastaa paikkansa.<br/> Startti ja maali on Porvoon Amistolla, Perämiehentie 6, 06100 Porvoo. </p> <div id="ilmoittautuminen"> <h2>Ilmoittautuminen</h2> <!-- <p> Ennakkoon ilmoittautuneiden lähtölistat julkaistu: <Link to="/lahtolista">Lähtölistat</Link> </p> --> <p>Ilmoittaudu mukaan <a href="https://porvoonakilles.tapahtumiin.fi/">tästä</a> </p> <p>Maksutapana nyt myös liikunta- ja kulttuurisetelit. Lähtöpaikalla maksuna käy käteinen tai pankki- ja luottokortti. </p> </div> <div id="hinnat"> <h2>Hinnat</h2> <p>Ilmoittaudu ajoissa ja hyödynnä early-bird etusi!</p> <table className="price-table"> <thead> <tr> <th>Matka</th> <th className="price">Ennen 21.5</th> <th className="price">Ennen 22.7</th> <th className="price">Alkaen 22.7</th> <th className="price">Käteinen lähtöpaikalla</th> </tr> </thead> <tbody> <tr> <td>110 km</td> <td className="price">50 €</td> <td className="price">60 €</td> <td className="price">70 €</td> <td className="price">70 € (tasaraha)</td> </tr> <tr> <td>55 km</td> <td className="price">40 €</td> <td className="price">50 €</td> <td className="price">60 €</td> <td className="price">60 € (tasaraha)</td> </tr> </tbody> </table> </div> </div> <div className="filler-div">&nbsp;</div> </div> ) } } export default MainPage
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Generators.js
HelpfulHuman/helpful-react-scripts
/** * 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(limit) { let i = 1; while (i <= limit) { yield { id: i, name: i }; i++; } } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } componentDidMount() { const users = []; for (let user of load(4)) { users.push(user); } this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-generators"> {this.state.users.map(user => <div key={user.id}> {user.name} </div> )} </div> ); } }
admin/client/components/Lightbox.js
riyadhalnur/keystone
import React from 'react'; import blacklist from 'blacklist'; import Portal from './Portal'; import Transition from 'react-addons-css-transition-group'; const BODY = document.getElementsByTagName('body')[0]; var Lightbox = React.createClass({ displayName: 'Lightbox', propTypes: { backdropClosesModal: React.PropTypes.bool, className: React.PropTypes.string, enableKeyboardInput: React.PropTypes.bool, height: React.PropTypes.number, images: React.PropTypes.array, initialImage: React.PropTypes.number, isOpen: React.PropTypes.bool, onCancel: React.PropTypes.func, showCloseButton: React.PropTypes.bool, width: React.PropTypes.number, }, getDefaultProps () { return { backdropClosesModal: true, enableKeyboardInput: true, initialImage: 0, height: 600, width: 900, }; }, getInitialState () { return { currentImage: this.props.initialImage, }; }, componentWillReceiveProps (nextProps) { this.setState({ currentImage: nextProps.initialImage, }); if (nextProps.isOpen && nextProps.enableKeyboardInput) { window.addEventListener('keydown', this.handleKeyboardInput); } else { window.removeEventListener('keydown', this.handleKeyboardInput); } if (nextProps.isOpen) { BODY.style.overflow = 'hidden'; } else { BODY.style.overflow = null; } }, handleKeyboardInput (event) { if (event.keyCode === 37) { this.gotoPrevious(); } else if (event.keyCode === 39) { this.gotoNext(); } else if (event.keyCode === 27) { this.props.onCancel(); } else { return false; } }, gotoPrevious () { if (this.state.currentImage === 0) return; this.setState({ currentImage: this.state.currentImage - 1, }); }, gotoNext () { if (this.state.currentImage === (this.props.images.length - 1)) return; this.setState({ currentImage: this.state.currentImage + 1, }); }, renderArrowPrev () { return ( <Transition transitionName="react-transitiongroup-fade" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {(this.state.currentImage > 0) && <button type="button" style={Object.assign({}, styles.arrow, styles.arrowPrev)} onClick={this.gotoPrevious} className="octicon octicon-chevron-left" />} </Transition> ); }, renderArrowNext () { return ( <Transition transitionName="react-transitiongroup-fade" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {(this.state.currentImage < (this.props.images.length - 1)) && <button type="button" style={Object.assign({}, styles.arrow, styles.arrowNext)} onClick={this.gotoNext} className="octicon octicon-chevron-right" />} </Transition> ); }, renderBackdrop () { if (!this.props.isOpen) return; return <div key="backdrop" style={styles.backdrop} onClick={this.props.backdropClosesModal ? this.props.onCancel : null} />; }, renderCloseButton () { if (!this.props.showCloseButton) return; return <button key="close" style={styles.close} onClick={this.props.onCancel}>Close</button>; }, renderDialog () { if (!this.props.isOpen) return; return ( <div key="dialog" style={Object.assign({}, styles.dialog, { height: this.props.height, width: this.props.width })}> {this.renderImages()} {this.renderArrowPrev()} {this.renderArrowNext()} {this.renderCloseButton()} </div> ); }, renderImages () { let { images } = this.props; let { currentImage } = this.state; if (!images || !images.length) return; return ( <Transition transitionName="react-transitiongroup-fade" style={styles.imageContainer} component="div" transitionEnterTimeout={200} transitionLeaveTimeout={200}> <img key={'image' + currentImage} src={images[currentImage]} style={styles.image} /> </Transition> ); }, render () { let props = blacklist(this.props, 'backdropClosesModal', 'initialImage', 'height', 'images', 'isOpen', 'onCancel', 'showCloseButton', 'width'); return ( <Portal {...props}> <Transition transitionName="react-transitiongroup-fade" component="div" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {this.renderDialog()} </Transition> <Transition transitionName="react-transitiongroup-fade" component="div" transitionEnterTimeout={200} transitionLeaveTimeout={200}> {this.renderBackdrop()} </Transition> </Portal> ); }, }); const styles = { arrow: { background: 'none', border: 'none', bottom: 0, color: 'white', fontSize: 48, right: 0, outline: 'none', padding: 0, position: 'absolute', top: 0, width: '10%', zIndex: 1002, // disable user select WebkitTouchCallout: 'none', WebkitUserSelect: 'none', MozUserSelect: 'none', msUserSelect: 'none', userSelect: 'none', }, arrowNext: { right: 0, }, arrowPrev: { left: 0, }, backdrop: { backgroundColor: 'rgba(0,0,0,0.66)', bottom: 0, left: 0, position: 'fixed', right: 0, top: 0, zIndex: 1000, }, close: { background: 'none', border: 'none', bottom: -32, color: 'white', fontSize: 16, height: 32, left: 0, marginLeft: 'auto', marginRight: 'auto', outline: 'none', padding: 0, position: 'absolute', right: 0, textAlign: 'center', textTransform: 'uppercase', width: 100, }, dialog: { // backgroundColor: 'rgba(255,255,255,0.26)', left: 0, lineHeight: 1, marginLeft: 'auto', marginRight: 'auto', maxHeight: '100%', maxWidth: '100%', position: 'fixed', right: 0, top: '50%', zIndex: 1001, WebkitTransform: 'translateY(-50%)', MozTransform: 'translateY(-50%)', msTransform: 'translateY(-50%)', transform: 'translateY(-50%)', }, image: { boxShadow: '0 1px 4px rgba(0,0,0,0.25)', maxHeight: '100%', maxWidth: '80%', position: 'absolute', // center the image within the dialog left: '50%', top: '50%', WebkitTransform: 'translate(-50%, -50%)', MozTransform: 'translate(-50%, -50%)', msTransform: 'translate(-50%, -50%)', transform: 'translate(-50%, -50%)', // disable user select WebkitTouchCallout: 'none', WebkitUserSelect: 'none', MozUserSelect: 'none', msUserSelect: 'none', userSelect: 'none', }, }; module.exports = Lightbox;
src/js/pages/Proposals/Experience/PreviewPage.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import translate from '../../../i18n/Translate'; import TopNavBar from '../../../components/TopNavBar/TopNavBar.js'; import '../../../../scss/pages/proposals/experience/preview.scss'; import CreatingProposalStore from "../../../stores/CreatingProposalStore"; import connectToStores from "../../../utils/connectToStores"; import StepsBar from "../../../components/ui/StepsBar/StepsBar"; import FilterStore from "../../../stores/FilterStore"; import ProposalFilterPreview from "../../../components/ui/ProposalFilterPreview/ProposalFilterPreview"; import ProposalStore from "../../../stores/ProposalStore"; import * as ProposalActionCreators from '../../../actions/ProposalActionCreators'; import ProposalIcon from "../../../components/ui/ProposalIcon/ProposalIcon"; import AvailabilityPreview from "../../../components/ui/AvailabilityPreview/AvailabilityPreview"; function getState() { const proposal = CreatingProposalStore.proposal; const title = proposal.fields.title; const description = proposal.fields.description; const type = proposal.type; const typeValues = proposal.fields.typeValues; const availability = CreatingProposalStore.availability; const participantLimit = proposal.fields.participantLimit; const proposalFilters = proposal.filters.userFilters; const filters = FilterStore.filters; return { title, description, type, typeValues, availability, participantLimit, proposalFilters, filters, }; } @translate('ProposalsLeisurePreviewPage') @connectToStores([CreatingProposalStore, FilterStore, ProposalStore], getState) export default class PreviewPage extends Component { static propTypes = { // Injected by @translate: strings : PropTypes.object, canContinue : PropTypes.bool, // Injected by @connectToStores: title : PropTypes.string, description : PropTypes.string, type : PropTypes.string, typeValues : PropTypes.array, availability : PropTypes.object, participantLimit : PropTypes.number, proposalFilters : PropTypes.object, filters : PropTypes.object, }; static contextTypes = { router: PropTypes.object.isRequired }; constructor(props) { super(props); this.handleTitleChange = this.handleTitleChange.bind(this); this.handleResumeChange = this.handleResumeChange.bind(this); this.topNavBarRightLinkClick = this.topNavBarRightLinkClick.bind(this); this.topNavBarLeftLinkClick = this.topNavBarLeftLinkClick.bind(this); this.handleStepsBarClick = this.handleStepsBarClick.bind(this); } componentWillMount() { } handleTitleChange(event) { this.setState({title: event}); } handleResumeChange(event) { this.setState({resume: event}); } topNavBarLeftLinkClick() { this.context.router.push('/proposals-experience-features'); } topNavBarRightLinkClick() { ProposalActionCreators.cleanCreatingProposal(); this.context.router.push('/proposals'); } handleStepsBarClick() { const proposal = CreatingProposalStore.getFinalProposal(); ProposalActionCreators.createProposal(proposal) .then(() => { ProposalActionCreators.cleanCreatingProposal(); this.context.router.push('/proposals'); }, () => { // TODO: Handle error }); } render() { const {strings, title, description, type, typeValues, availability, participantLimit, proposalFilters} = this.props; return ( <div className="views"> <div className="view view-main proposals-experience-preview-view"> <TopNavBar position={'absolute'} background={'transparent'} iconLeft={'arrow-left'} firstIconRight={'icon-experiencia'} textSize={'small'} onLeftLinkClickHandler={this.topNavBarLeftLinkClick} onRightLinkClickHandler={this.topNavBarRightLinkClick}/> <div className="proposals-experience-preview-wrapper"> <div className={'image-wrapper'}> <img src={'https://via.placeholder.com/480x240'} alt={'https://via.placeholder.com/480x240'}/> <h2 className={'bottom-left'}>{title}</h2> </div> <div className={'content-wrapper'}> <p className={'category'}>{type}</p> <p>{description}</p> <div className={'information-wrapper'}> <div className={'rounded-icon-wrapper'}> <ProposalIcon size={'medium-small'} icon={'sectors'} background={'white'}/> </div> <div className={'text-wrapper'}> <div className={'title small'}>{strings.profession}</div> {typeValues.map((item, index) => <div className={'small'} key={index}> {item} </div> )} </div> </div> <div className={'information-wrapper'}> <AvailabilityPreview availability={availability}/> </div> <div className={'information-wrapper'}> <div className={'rounded-icon-wrapper'}> <ProposalIcon size={'medium-small'} icon={'participants'} background={'white'}/> </div> <div className={'text-wrapper'}> <div className={'title small'}>{strings.numberOfMembers}</div> <div className={'resume small'}>{participantLimit} {strings.people}</div> </div> </div> <ProposalFilterPreview proposalFilters={proposalFilters}/> </div> </div> </div> <StepsBar color={'green'} canContinue={true} continueText={strings.publishProposal} totalSteps={0} onClickHandler={this.handleStepsBarClick}/> </div> ); } } PreviewPage.defaultProps = { strings: { publishProposal : 'Publish proposal', project : 'Project', sectors : 'Sectors', skills : 'Habilities', availability : 'Availability', numberOfMembers: 'Number of members', filterText : 'Filters to your proposal target', basics : 'Basics', culture : 'Culture and languages', drugs : 'Drugs and other services', familiar : 'Familiar aspects', people : 'people', years : 'years', withinRadioOf : 'within radio of' } };
tests/react_16_6/Suspense.js
samwgoldman/flow
// @flow import React from 'react'; const {Suspense} = React; function Loading() { return <div>Loading...</div>; } { <Suspense fallback={Loading} /> // Error: function is incompatible with exact React.Element } { <Suspense fallback={<Loading/>} /> } { <Suspense fallback={<Loading/>}> <div>Hello</div> </Suspense> } { <Suspense fallback={<Loading/>}> <Suspense /> </Suspense> } { <Suspense fallback={<Loading/>}> <Suspense fallback={undefined} /> </Suspense> } { <Suspense fallback={<Loading/>}> <Suspense fallback={null} /> </Suspense> }
app/javascript/mastodon/features/ui/util/reduced_motion.js
PlantsNetwork/mastodon
// Like react-motion's Motion, but reduces all animations to cross-fades // for the benefit of users with motion sickness. import React from 'react'; import Motion from 'react-motion/lib/Motion'; import PropTypes from 'prop-types'; const stylesToKeep = ['opacity', 'backgroundOpacity']; const extractValue = (value) => { // This is either an object with a "val" property or it's a number return (typeof value === 'object' && value && 'val' in value) ? value.val : value; }; class ReducedMotion extends React.Component { static propTypes = { defaultStyle: PropTypes.object, style: PropTypes.object, children: PropTypes.func, } render() { const { style, defaultStyle, children } = this.props; Object.keys(style).forEach(key => { if (stylesToKeep.includes(key)) { return; } // If it's setting an x or height or scale or some other value, we need // to preserve the end-state value without actually animating it style[key] = defaultStyle[key] = extractValue(style[key]); }); return ( <Motion style={style} defaultStyle={defaultStyle}> {children} </Motion> ); } } export default ReducedMotion;
src/pages/moduleHomePage/essence/Essence.js
HeliumLau/Hoop-react
import React from 'react'; import ArticleList from 'components/ArticleList.js'; export default class Essence extends React.Component { constructor(props) { super(props); this.state = { articlelist: [ { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 }, { title: '惊!安东尼签约火箭竟只为他!', author: 'Helium', time: '刚刚', recommend: 1, like: 100, comment: 1221 } ] } } render() { return ( <ArticleList list={this.state.articlelist} /> ) } }
pathfinder/vtables/csmoperations/src/common/Link.js
leanix/leanix-custom-reports
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Link extends Component { constructor(props) { super(props); this._handleClick = this._handleClick.bind(this); } _handleClick(e) { e.preventDefault(); lx.openLink(this.props.link, this.props.target); } render() { if (!this.props.link || !this.props.target || !this.props.text) { return null; } switch (this.props.target) { case '_blank': return ( <a href={this.props.link} title='Opens a new tab/window.' target={this.props.target} onClick={this._handleClick} >{this.props.text}</a> ); default: return ( <a href={this.props.link} target={this.props.target} onClick={this._handleClick} >{this.props.text}</a> ); } } } Link.propTypes = { link: PropTypes.string.isRequired, target: PropTypes.string.isRequired, text: PropTypes.string.isRequired }; export default Link;
src/svg-icons/content/content-copy.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentContentCopy = (props) => ( <SvgIcon {...props}> <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/> </SvgIcon> ); ContentContentCopy = pure(ContentContentCopy); ContentContentCopy.displayName = 'ContentContentCopy'; ContentContentCopy.muiName = 'SvgIcon'; export default ContentContentCopy;
src/components/enquiry/EnquiryButton.js
tutorcruncher/socket-frontend
import React from 'react' import {Link, Route} from 'react-router-dom' import EnquiryModal from './EnquiryModal' const EnquiryButton = ({root, config}) => ( <div className="tcs-app"> <div className="tcs-enquiry-modal"> <Link to={root.url('enquiry')} className="tcs-button tcs-enquiry-button"> {config.get_text('enquiry_button')} </Link> <Route path={root.url('enquiry')} render={props => ( <EnquiryModal root={root} config={config} history={props.history}/> )}/> </div> </div> ) export default EnquiryButton
src/components/Modal-Wrapper.js
MichaelLSmith/recipeBox
import React, { Component } from 'react'; import { Button, ButtonToolbar, Modal } from 'react-bootstrap'; import RecipeForm from '../containers/Recipe-Form'; export default class ModalWrapper extends Component { //props: //isOpen = bool //onCloseRequest = function --> closeModal as defined in App.js renderTitle(type) { switch(type) { case 'EDIT': return <Modal.Title className="text-center">Edit Recipe</Modal.Title>; case 'ADD': { return <Modal.Title className="text-center">Create New Recipe</Modal.Title>; } } } render(){ // console.log(this.props); const { isOpen, onCloseRequest, buttonType, recipe } = this.props; return ( <div> <Modal show={isOpen} onHide={onCloseRequest} > <Modal.Header> {this.renderTitle(buttonType)} </Modal.Header> <Modal.Body> <RecipeForm recipe={recipe} buttonType={buttonType} onCloseRequest={onCloseRequest} /> </Modal.Body> <Modal.Footer> <Button onClick={onCloseRequest}>Close</Button> </Modal.Footer> </Modal> </div> ) } }
web/src/containers/Login.js
miaolz123/samaritan
import { ResetError } from '../actions'; import { UserLogin } from '../actions/user'; import React from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import { Button, Form, Input, Icon, Tooltip, notification } from 'antd'; class Login extends React.Component { constructor(props) { super(props); this.state = { windowHeight: window.innerHeight || 720, messageErrorKey: '', }; this.handleSubmit = this.handleSubmit.bind(this); } componentWillReceiveProps(nextProps) { const { dispatch } = this.props; const { messageErrorKey } = this.state; const { user } = nextProps; if (!messageErrorKey && user.message) { this.setState({ messageErrorKey: 'userLoginError', }); notification['error']({ key: 'userLoginError', message: 'Error', description: String(user.message), onClose: () => { if (this.state.messageErrorKey) { this.setState({ messageErrorKey: '' }); } dispatch(ResetError()); }, }); } if (!user.loading && user.token) { if (this.state.messageErrorKey) { this.setState({ messageErrorKey: '' }); notification.close(this.state.messageErrorKey); } browserHistory.push('/'); } } componentWillUnmount() { const { dispatch } = this.props; dispatch(ResetError()); } handleSubmit(e) { const { form, dispatch } = this.props; if (e) { e.preventDefault(); } form.validateFields((errors, values) => { if (errors) { return; } dispatch(UserLogin(values.cluster, values.username, values.password)); }); } render() { const { windowHeight } = this.state; const { getFieldDecorator } = this.props.form; const formItemLayout = { wrapperCol: { offset: 9, span: 6 }, }; const cluster = localStorage.getItem('cluster') || document.URL.slice(0, -6); return ( <div style={{ paddingTop: windowHeight > 600 ? (windowHeight - 500) / 2 : windowHeight > 400 ? (windowHeight - 350) / 2 : 25 }}> <h1 style={{ margin: 24, fontSize: '30px', textAlign: 'center', }}>Samaritan</h1> <Form horizontal onSubmit={this.handleSubmit}> <Form.Item {...formItemLayout} > <Tooltip placement="right" title="Cluster URL"> {getFieldDecorator('cluster', { rules: [{ type: 'url', required: true }], initialValue: cluster, })( <Input addonBefore={<Icon type="link" />} placeholder="http://127.0.0.1:9876" /> )} </Tooltip> </Form.Item> <Form.Item {...formItemLayout} > <Tooltip placement="right" title="Username"> {getFieldDecorator('username', { rules: [{ required: true }], })( <Input addonBefore={<Icon type="user" />} placeholder="username" /> )} </Tooltip> </Form.Item> <Form.Item {...formItemLayout} > <Tooltip placement="right" title="Password"> {getFieldDecorator('password', { rules: [{ required: true }], })( <Input addonBefore={<Icon type="lock" />} type="password" placeholder="password" /> )} </Tooltip> </Form.Item> <Form.Item wrapperCol={{ span: 6, offset: 9 }} style={{ marginTop: 24 }}> <Button type="primary" htmlType="submit" className="login-form-button">Login</Button> </Form.Item> </Form> </div> ); } } const mapStateToProps = (state) => ({ user: state.user, }); export default Form.create()(connect(mapStateToProps)(Login));
app/components/Account.js
deepakpster/Dinder
import React, { Component } from 'react'; import { Content, Footer, Button, InputGroup, Input, View, Icon, Text, Spinner } from 'native-base'; import AuthStore from './../stores/authStore' const authStore = new AuthStore() export default class Account extends Component { render() { const {state} = this.props.navigation; return ( <Content> <Text>{state.params.auth.authUser.email}</Text> <Footer> <Button rounded block onPress={this.signOut.bind(this)}> <Text>Sign Out</Text> </Button> </Footer> </Content> ) } signOut() { const { navigate } = this.props.navigation; authStore.signOut() navigate("Home") } }
client/app/components/List/index.js
jjt/ffsssshh
import React from 'react'; import styles from './styles.css'; class List extends React.Component { render() { return ( <div className={ styles.listWrapper }> <ul className={ styles.list }> {this.props.items.map((item, index) => { return ( <this.props.render key={'item-' + index } item={item} /> ); })} </ul> </div> ); } } export default List;
src/components/NPCInfoBrowser.js
kristyjy/battleplan
import React from 'react'; //import { Button } from 'reactstrap'; //import './InitiativePanel.scss' class NPCInfoBrowser extends React.Component { constructor(props, context) { super(props, context); } render() { return ( <div className="npc-info-browser"> NPC Info </div> ); } } NPCInfoBrowser.propTypes = { combatants : React.PropTypes.array.isRequired, actions : React.PropTypes.object.isRequired }; export default NPCInfoBrowser;
packages/insights-web/src/scenes/explorer/filter/index.js
mariusandra/insights
import './styles.scss' import React from 'react' import { useValues } from 'kea' import { Icon } from 'antd' import OneFilter from './one-filter' import explorerLogic from 'scenes/explorer/logic' export default function Filter () { const { filter } = useValues(explorerLogic) let i = 0 return ( <div className='insights-filter'> <div className='filter-header'> <span className='filter-preview'> {filter.map(({ key, value }) => ( <OneFilter key={`${i}.${key}`} filterPrefix={`...filters.${i}`} column={key} value={value} index={i++} /> ))} {filter.length === 0 ? ( <span className='filter-placeholder'>Click on <Icon type='filter' /> icons to add filters</span> ) : null} </span> </div> </div> ) }
src/components/secrets/SecretUserListNew.js
secretin/secretin-app
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import * as MetadataActions from 'slices/MetadataSlice'; import Secret from 'models/Secret'; import User, { UserRights, userRightLabel } from 'models/User'; import { confirm } from 'components/utilities/Confirm'; import Input from 'components/utilities/Input'; import Select from 'components/utilities/Select'; import Button from 'components/utilities/Button'; import Icon from 'components/utilities/Icon'; class SecretUserListNew extends Component { static propTypes = { knownFriendList: PropTypes.array, secret: PropTypes.instanceOf(Secret), errors: PropTypes.object, dispatch: PropTypes.func, }; constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.state = { user: new User(), }; } handleChange({ name, value }) { this.setState({ user: this.state.user.merge({ [name]: value }), }); } handleSubmit() { const { secret } = this.props; const { user } = this.state; const accessRights = [ 'read access', 'read and write access', 'read, write and share access', ]; const rights = accessRights[user.rights]; const to = user.username; const on = secret.title; confirm({ title: 'Are you sure?', text: ( <span> You are about to give <b>{rights}</b> to <b>{to}</b> on <b>{on}</b>. </span> ), acceptLabel: 'Share the secret', cancelLabel: 'Cancel', onAccept: () => { this.props.dispatch( MetadataActions.createSecretUserRights({ secret: this.props.secret, user: this.state.user, rights: this.state.user.rights, }) ); this.setState({ user: new User(), }); }, onCancel: () => ({}), }); } render() { return ( <div className="secret-users-list-new"> <Input name="username" placeholder="User name..." value={this.state.user.username} size="small" onChange={this.handleChange} autoCompleteFromList={this.props.knownFriendList} error={this.props.errors.username} /> <Select name="rights" value={this.state.user.rights} size="small" onChange={this.handleChange} options={UserRights.map(rights => [rights, userRightLabel(rights)])} /> <Button buttonStyle="icon" onClick={this.handleSubmit} disabled={!this.state.user.isValid()} size="small" iconOnly > <Icon id="add" /> </Button> </div> ); } } const mapStateToProps = state => { const { knownFriendList } = state.Metadata; return { knownFriendList, }; }; export default connect(mapStateToProps)(SecretUserListNew);
src/views/Footer.js
romanantl/aws-js-self-updater
import React from 'react'; export default class Footer extends React.Component { render() { return ( this.props.html ? <div dangerouslySetInnerHTML={{__html: this.props.html}}></div> : <div>Actual footer</div> ) } }
video_browser/src/components/video_list_item.js
williampuk/ReduxCasts
import React from 'react'; const VideoListItem = ({video, onVideoSelect}) => { const imageUrl = video.snippet.thumbnails.default.url; return ( <li onClick={() => onVideoSelect(video)} className="list-group-item"> <div className="video-list media"> <div className="media-left"> <img className="media-object" src={imageUrl} /> </div> <div className="media-body"> <div className="media-heading">{video.snippet.title}</div> </div> </div> </li> ); }; export default VideoListItem;
examples/js/column-filter/select-filter-with-default-value.js
neelvadgama-hailo/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; const qualityType = { 0: 'good', 1: 'bad', 2: 'unknown' }; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, quality: i % 3 }); } } addProducts(5); function enumFormatter(cell, row, enumObject) { return enumObject[cell]; } export default class SelectFilterWithDefaultValue extends React.Component { render() { return ( <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='quality' filterFormatted dataFormat={ enumFormatter } formatExtraData={ qualityType } filter={ { type: 'SelectFilter', options: qualityType, defaultValue: 1 } }>Product Quality</TableHeaderColumn> </BootstrapTable> ); } }
docs/src/components/UsePictureSlideshow.js
HsuTing/cat-components
'use strict'; import React from 'react'; import radium from 'radium'; import PictureSlideshow from 'cat-components/lib/picture-slideshow'; import Button from 'cat-components/lib/button'; import * as style from './style/usePictureSlideshow'; const imgs = [{ src: 'https://scontent-tpe1-1.cdninstagram.com/t51.2885-15/e35/17493450_397169997321386_4423519579884486656_n.jpg' }, { src: 'https://scontent-tpe1-1.cdninstagram.com/t51.2885-15/e35/16465237_160262967811059_8777509647905980416_n.jpg' }, { src: 'https://scontent-tpe1-1.cdninstagram.com/t51.2885-15/e35/16906239_1371447262875968_9128363095364730880_n.jpg' }]; @radium export default class UsePictureSlideshow extends React.Component { constructor(props) { super(props); this.state = { index: 0 }; this.onClick = this.onClick.bind(this); } render() { const {index} = this.state; return ( <div> <h5>Type: img</h5> <PictureSlideshow index={index} imgs={imgs} type='img' /> <h5>Type: div</h5> <PictureSlideshow index={index} imgs={imgs} /> {imgs.map((img, imgIndex) => ( <Button key={imgIndex} style={imgIndex === index ? style.isClicked : {}} onClick={this.onClick(imgIndex)} >{imgIndex}</Button> ))} </div> ); } onClick(index) { return e => { this.setState({index}); }; } }
app/components/Dish.js
rondobley/meal-planner
import React from 'react'; import { Link } from 'react-router'; import DishStore from '../stores/DishStore'; import DishActions from '../actions/DishActions'; import Modal from './Modal'; var s = require('underscore.string'); class Dish extends React.Component { constructor(props) { super(props); this.state = DishStore.getState(); this.onChange = this.onChange.bind(this); this.handleShowModal.bind(this); this.handleEdit = this.handleEdit.bind(this); this.updateNameInput = this.updateNameInput.bind(this); this.updateReferenceInput = this.updateReferenceInput.bind(this); this.updateTagToAddInput = this.updateTagToAddInput.bind(this); this.deleteTagClick = this.deleteTagClick.bind(this); } componentDidMount() { DishStore.listen(this.onChange); DishActions.getDish(this.props.params.name); } componentWillUnmount() { DishStore.unlisten(this.onChange); } componentDidUpdate() { if(this.state.isEdited) { $('.modal').modal('hide'); } } onChange(state) { this.setState(state); } handleHideModal() { DishActions.hideModal(); } handleShowModal(e) { let form = e.currentTarget.getAttribute('data-form'); let params = {form: form}; DishActions.showModal(params); } handleEdit(e) { e.preventDefault(); let dishId = e.currentTarget.getAttribute('data-dish-id'); let dishName = this.state.name.trim(); let dishReference = this.state.reference.trim(); let dishTags = this.state.tags; if(dishName == '') { this.setState({ modalFormValidationState:'has-error', helpBlock: 'You must enter a dish name' }); } if(dishName) { DishActions.editDish({ dishId: dishId, dishName: dishName, dishReference: dishReference, dishTags: dishTags, history: this.props.history }); } } handleAddTag(e) { e.preventDefault(); let dishId = e.currentTarget.getAttribute('data-dish-id'); let dishName = this.state.name.trim(); let tagToAdd = s(this.state.tagToAdd).toLowerCase().value(); let dishTags = this.state.tags; if(dishTags.indexOf(tagToAdd) > -1) { this.setState({modalFormValidationState: 'has-error', helpBlock: 'Tag already exists'}); } else if(tagToAdd == '') { this.setState({ modalFormValidationState:'has-error', helpBlock: 'You must enter a tag' }); } else { dishTags.push(tagToAdd); DishActions.editDish({ dishId: dishId, dishName: dishName, dishTags: dishTags, history: this.props.history }); } } handleDeleteTag(e) { e.preventDefault(); let dishId = e.currentTarget.getAttribute('data-dish-id'); let dishName = this.state.name.trim(); let tagToDelete = this.state.tagToDelete; let dishTags = this.state.tags; dishTags.splice(dishTags.indexOf(tagToDelete), 1); DishActions.editDish({ dishId: dishId, dishName: dishName, dishTags: dishTags, history: this.props.history }); } updateNameInput(name) { this.setState({ name: name }); } updateReferenceInput(reference) { this.setState({ reference: reference }); } updateTagToAddInput(tag) { this.setState({ tagToAdd: tag }); } deleteTagClick(e) { e.preventDefault(); let tagToDelete = e.currentTarget.getAttribute('data-tag-to-delete'); this.setState({tagToDelete: tagToDelete}); this.handleShowModal(e); } render() { let addTagButton = null; let editDishButton= null; let deleteDishButton = null; let modal = null; let tags = []; if(this.state.tags) { tags = this.state.tags.map((tag, index) => { let displayTag = s(tag).titleize().value(); return ( <span className="label label-info" key={index} data-form='deleteTagFromDish' data-tag-to-delete={tag} onClick={(e) => this.deleteTagClick(e)}> {displayTag} <span className='glyphicon glyphicon-trash'></span></span> ); }); } if(this.state.loaded) { addTagButton = <button type='button' className='btn btn-primary btn-xs' data-form='addTagToDish' onClick={(e) => this.handleShowModal(e)} >Add Tag <span className='glyphicon glyphicon-plus'></span></button>; editDishButton = <button type='button' className='btn btn-primary btn-xs' data-form='editDish' onClick={(e) => this.handleShowModal(e)} >Edit Dish <span className='glyphicon glyphicon-pencil'></span></button>; deleteDishButton = <button type='button' className='btn btn-danger btn-xs' data-form='deleteDish' onClick={(e) => this.handleShowModal(e)}> Delete Dish <span className='glyphicon glyphicon-trash'></span></button>; } if(this.state.showModal) { switch(this.state.showModal) { case 'editDish': modal = <Modal title="Edit Dish" form="editDish" handleHideModal={this.handleHideModal} dishId={this.state._id} dishName={this.state.name} dishReference={this.state.reference} modalFormValidationState={this.state.modalFormValidationState} helpBlock={this.state.helpBlock} handleEdit={(e) => this.handleEdit(e)} onNameInputChange={this.updateNameInput} onReferenceInputChange={this.updateReferenceInput} />; break; case 'deleteDish': modal = <Modal title="Delete Dish" form="deleteDish" dishId={this.state._id} dishName={this.state.name} handleHideModal={this.handleHideModal} />; break; case 'addTagToDish': modal = <Modal title="Add Tag" form="addTagToDish" handleHideModal={this.handleHideModal} dishId={this.state._id} tagToAdd={this.state.tagToAdd} modalFormValidationState={this.state.modalFormValidationState} helpBlock={this.state.helpBlock} handleAddTag={(e) => this.handleAddTag(e)} onChange={this.updateTagToAddInput} />; break; case 'deleteTagFromDish': modal = <Modal title="Delete Tag" form="deleteTagFromDish" handleHideModal={this.handleHideModal} dishId={this.state._id} tagToDelete={this.state.tagToDelete} modalFormValidationState={this.state.modalFormValidationState} helpBlock={this.state.helpBlock} handleDeleteTag={(e) => this.handleDeleteTag(e)} />; break; } } return ( <div className='container'> <div className='row'> <div className='col-sm-12 dishes-container'> <ol className="breadcrumb"> <li><Link to="/dishes">Dishes</Link></li> <li className="active">Dish</li> </ol> <h1>{this.state.name}</h1> <p>Recipe: {this.state.reference}</p> {tags} <hr></hr> {addTagButton}{editDishButton}{deleteDishButton} </div> </div> <div className='row'> <div className='col-sm-12'> {modal} </div> </div> </div> ); } } export default Dish;
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
dadams85/dadams85.github.io
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'));
node_modules/react-icons/fa/group.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const FaGroup = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m12.3 20q-3.4 0.1-5.5 2.7h-2.8q-1.7 0-2.8-0.9t-1.2-2.4q0-7.4 2.6-7.4 0.1 0 0.9 0.5t2 0.8 2.5 0.5q1.4 0 2.7-0.5-0.1 0.8-0.1 1.4 0 2.9 1.7 5.3z m22.3 13.2q0 2.5-1.6 4t-4 1.4h-18.1q-2.6 0-4.1-1.4t-1.5-4q0-1.1 0.1-2.1t0.3-2.3 0.5-2.2 0.9-2.1 1.3-1.6 1.8-1.2 2.3-0.4q0.2 0 0.9 0.5t1.5 1 2.2 1 2.8 0.4 2.8-0.4 2.3-1 1.5-1 0.9-0.5q1.2 0 2.3 0.4t1.8 1.2 1.2 1.6 0.9 2.1 0.6 2.2 0.3 2.3 0.1 2.1z m-21.3-26.5q0 2.2-1.6 3.8t-3.7 1.5-3.8-1.5-1.5-3.8 1.5-3.7 3.8-1.6 3.7 1.6 1.6 3.7z m14.6 8q0 3.3-2.3 5.6t-5.7 2.4-5.6-2.4-2.3-5.6 2.3-5.7 5.6-2.3 5.7 2.3 2.3 5.7z m12 4.7q0 1.6-1.2 2.4t-2.9 0.9h-2.7q-2.2-2.6-5.5-2.7 1.6-2.4 1.6-5.3 0-0.6-0.1-1.4 1.4 0.5 2.8 0.5 1.2 0 2.5-0.5t2-0.8 0.9-0.5q2.6 0 2.6 7.4z m-2.7-12.7q0 2.2-1.5 3.8t-3.8 1.5-3.8-1.5-1.5-3.8 1.5-3.7 3.8-1.6 3.8 1.6 1.5 3.7z"/></g> </Icon> ) export default FaGroup
src/components/GeolocationComponents/index.js
joelvoss/react-gmaps
import React from 'react'; import styled from 'styled-components'; import Loader from 'components/LoadingOverlay/Loader'; /** * Simple loading component. * @param {object} props - Component properties. */ export const GeolocationLoading = props => { const LoadingWrap = styled.div` display: ${props => props.visible ? 'inline-flex' : 'none'}; flex-direction: row; align-items: center; justify-content: center; `; const SmallLoader = styled(Loader)` width: 20px !important; height: 20px !important; `; const LoadingText = styled.p` margin: 0 1em; padding: 0; color: ${props => props.theme.colors.default.primary}; font-weight: 700; `; return ( <LoadingWrap visible={props.visible}> <SmallLoader /> <LoadingText>{props.message}</LoadingText> </LoadingWrap> ); }; /** * Simple error component. * @param {object} props - Component properties. */ export const GeolocationError = props => { const ErrorWrap = styled.div` display: ${props => props.visible ? 'inline-flex' : 'none'}; flex-direction: row; align-items: center; justify-content: center; `; const ErrorText = styled.p` margin: 0 1em; padding: 0; color: ${props => props.theme.colors.default.pink}; font-weight: 700; a { font-weight: 400; color: ${props => props.theme.colors.default.pink}; } `; return ( <ErrorWrap visible={props.visible}> <ErrorText dangerouslySetInnerHTML={{__html: props.message}}></ErrorText> </ErrorWrap> ); };
packages/react-scripts/fixtures/kitchensink/src/features/webpack/NoExtInclusion.js
prometheusresearch/create-react-app
/** * 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 from 'react' import aFileWithoutExt from './assets/aFileWithoutExt' const text = aFileWithoutExt.includes('base64') ? atob(aFileWithoutExt.split('base64,')[1]).trim() : aFileWithoutExt export default () => ( <p id="feature-no-ext-inclusion">{text}.</p> )
examples/universal/server/server.js
JoeStanton/redux
/* eslint-disable no-console, no-use-before-define */ import path from 'path' import Express from 'express' import qs from 'qs' import webpack from 'webpack' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' import webpackConfig from '../webpack.config' import React from 'react' import { renderToString } from 'react-dom/server' import { Provider } from 'react-redux' import configureStore from '../common/store/configureStore' import App from '../common/containers/App' import { fetchCounter } from '../common/api/counter' const app = new Express() const port = 3000 // Use this middleware to set up hot module reloading via webpack. const compiler = webpack(webpackConfig) app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath })) app.use(webpackHotMiddleware(compiler)) // This is fired every time the server side receives a request app.use(handleRender) function handleRender(req, res) { // Query our mock API asynchronously fetchCounter(apiResult => { // Read the counter from the request, if provided const params = qs.parse(req.query) const counter = parseInt(params.counter, 10) || apiResult || 0 // Compile an initial state const initialState = { counter } // Create a new Redux store instance const store = configureStore(initialState) // Render the component to a string const html = renderToString( <Provider store={store}> <App /> </Provider> ) // Grab the initial state from our Redux store const finalState = store.getState() // Send the rendered page back to the client res.send(renderFullPage(html, finalState)) }) } function renderFullPage(html, initialState) { return ` <!doctype html> <html> <head> <title>Redux Universal Example</title> </head> <body> <div id="app">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)} </script> <script src="/static/bundle.js"></script> </body> </html> ` } app.listen(port, (error) => { if (error) { console.error(error) } else { console.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`) } })
src/icons/IosCheckmarkEmpty.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosCheckmarkEmpty extends React.Component { render() { if(this.props.bare) { return <g> <g> <path d="M223.9,329.7c-2.4,2.4-5.8,4.4-8.8,4.4s-6.4-2.1-8.9-4.5l-56-56l17.8-17.8l47.2,47.2l124.8-125.7l17.5,18.1L223.9,329.7z"></path> </g> </g>; } return <IconBase> <g> <path d="M223.9,329.7c-2.4,2.4-5.8,4.4-8.8,4.4s-6.4-2.1-8.9-4.5l-56-56l17.8-17.8l47.2,47.2l124.8-125.7l17.5,18.1L223.9,329.7z"></path> </g> </IconBase>; } };IosCheckmarkEmpty.defaultProps = {bare: false}
src/containers/AppContainer/index.js
LamouchiMS/adintel
// Subscribe to store here import React from 'react'; import {Router, Route, IndexRoute, browserHistory} from 'react-router'; import Layout from '../../containers/Layout'; import First from '../../components/First'; import Database from '../../containers/Database'; import MassComm from '../../containers/MassComm'; import Projects from '../../containers/Projects'; import Scraper from '../../containers/Scraper'; import Statistics from '../../containers/Statistics'; import Talks from '../../containers/Talks'; import CreateProject from '../../components/CreateProject'; const AppContainer = () => ( <div> <Router history={browserHistory} path={'/'}> <Route path={'/'} component={Layout}> <IndexRoute component={First}/> <Route path={'database'} component={Database}/> <Route path={'masscomm'} component={MassComm}/> <Route path={'projects'} component={Projects}/> <Route path={'scraper'} component={Scraper}/> <Route path={'statistics'} component={Statistics}/> <Route path={'talks'} component={Talks}/> <Route path={'createProject'} component={CreateProject}/> </Route> </Router> </div> ); export default AppContainer;
src/components/NotebookListItem/TagList.js
anibali/showoff
import React from 'react'; const contrastBW = (hex) => { hex = hex.replace(/^\s*#|\s*$/g, ''); const r = parseInt(hex.substr(0, 2), 16); const g = parseInt(hex.substr(2, 2), 16); const b = parseInt(hex.substr(4, 2), 16); const luminance = (0.299 * r) + (0.587 * g) + (0.114 * b); return luminance > 150 ? '#000000' : '#ffffff'; }; const textToColour = (text) => { let hash = 17; for(let i = 0; i < text.length; ++i) { hash = text.charCodeAt(i) + ((hash << 5) - hash); } const c = (hash & 0x00FFFFFF).toString(16).toUpperCase(); return `#${'00000'.substring(0, 6 - c.length) + c}`; }; const TagList = ({ tags }) => { const children = tags.map(tag => { const backgroundColor = textToColour(tag.attributes.name); const style = { backgroundColor, color: contrastBW(backgroundColor) }; return <span key={tag.id} className="label" style={style}>{tag.attributes.name}</span>; }); return <span>{children}</span>; }; export default TagList;
app/app.js
thomasmichaelwallace/network-be
import React from 'react'; import { Provider } from 'react-redux'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import ChannelFinder from './containers/ChannelFinder'; const app = ({ store }) => ( <Provider store={store}> <MuiThemeProvider muiTheme={getMuiTheme()}> <ChannelFinder /> </MuiThemeProvider> </Provider> ); app.propTypes = { store: React.PropTypes.object.isRequired, }; export default app;
src/components/graphs/spider-graph.js
marcusdarmstrong/mockdraftable-web
// @flow import React from 'react'; import { round } from 'lodash'; import type { Point } from '../../types/graphing'; import type { Color } from '../../types/domain'; type Props = { points: Point[], factors: number[], className: string, scale: number, offset: number, color?: Color, }; const SpiderGraph = ({ points, factors, className, scale, offset, color }: Props) => { let i = 0; const pointStrings = []; factors.forEach((factor) => { const x = round((factor * points[i].x) + scale + offset, 2); const y = round((factor * points[i].y) + scale + offset, 2); pointStrings.push(`${x},${y}`); i += 1; }); return color ? (<polygon className={className} points={pointStrings.join(' ')} style={{ fill: color, stroke: color }} />) : <polygon className={className} points={pointStrings.join(' ')} />; }; SpiderGraph.defaultProps = { color: undefined, }; export default SpiderGraph;
src/components/Form/InputGroup.js
antoinechalifour/Reddix
import React from 'react' import styled from 'styled-components' const Outer = styled.div` & + & { margin-top: 24px; } ` const InputGroup = ({ children }) => { return ( <Outer> {children} </Outer> ) } export default InputGroup
examples/04 Sortable/Simple/Container.js
randrianov/react-dnd
import React, { Component } from 'react'; import update from 'react/lib/update'; import Card from './Card'; import { DragDropContext } from 'react-dnd'; import HTML5Backend from 'react-dnd/modules/backends/HTML5'; const style = { width: 400 }; @DragDropContext(HTML5Backend) export default class Container extends Component { constructor(props) { super(props); this.moveCard = this.moveCard.bind(this); this.state = { cards: [{ id: 1, text: 'Write a cool JS library' }, { id: 2, text: 'Make it generic enough' }, { id: 3, text: 'Write README' }, { id: 4, text: 'Create some examples' }, { id: 5, text: 'Spam in Twitter and IRC to promote it (note that this element is taller than the others)' }, { id: 6, text: '???' }, { id: 7, text: 'PROFIT' }] }; } moveCard(id, afterId) { const { cards } = this.state; const card = cards.filter(c => c.id === id)[0]; const afterCard = cards.filter(c => c.id === afterId)[0]; const cardIndex = cards.indexOf(card); const afterIndex = cards.indexOf(afterCard); this.setState(update(this.state, { cards: { $splice: [ [cardIndex, 1], [afterIndex, 0, card] ] } })); } render() { const { cards } = this.state; return ( <div style={style}> {cards.map((card, i) => { return ( <Card key={card.id} index={i} id={card.id} text={card.text} moveCard={this.moveCard} /> ); })} </div> ); } }
src/calendar-body/CalendarDate.js
topcatcreatives/react-date-scroll
import React, { Component } from 'react'; import './styles/calendar-date.css'; class CalendarDate extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { if (this.props.date !== null) { this.props.dateClick(this.props.date); } } render() { let date = this.props.date, formattedDate = (date === null) ? '' : date.format('D'), classNames = 'calendar-date'; if (date !== null) { if (this.props.startDate !== null && this.props.startDate.isSame(this.props.date)) { classNames += ' calendar-date-selected' } if (this.props.endDate !== null && this.props.endDate.isSame(this.props.date)) { classNames += ' calendar-date-selected' } if (this.props.startDate !== null && this.props.endDate !== null) { if (date.isAfter(this.props.startDate) && date.isBefore(this.props.endDate)) { classNames += ' calendar-date-in-range' } } } return ( <div className={classNames} onClick={this.handleClick}> <div className="calendar-date-content-wrapper"> <div className="calendar-date-content"> {formattedDate} </div> </div> </div> ); } } export default CalendarDate;
src/components/Tabs.js
rackt/react-tabs
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { childrenPropType, onSelectPropType, selectedIndexPropType, } from '../helpers/propTypes'; import UncontrolledTabs from './UncontrolledTabs'; import { getTabsCount } from '../helpers/count'; const MODE_CONTROLLED = 0; const MODE_UNCONTROLLED = 1; export default class Tabs extends Component { static defaultProps = { defaultFocus: false, forceRenderTabPanel: false, selectedIndex: null, defaultIndex: null, environment: null, disableUpDownKeys: false, }; static propTypes = { children: childrenPropType, direction: PropTypes.oneOf(['rtl', 'ltr']), className: PropTypes.oneOfType([ PropTypes.string, PropTypes.array, PropTypes.object, ]), defaultFocus: PropTypes.bool, defaultIndex: PropTypes.number, disabledTabClassName: PropTypes.string, disableUpDownKeys: PropTypes.bool, domRef: PropTypes.func, forceRenderTabPanel: PropTypes.bool, onSelect: onSelectPropType, selectedIndex: selectedIndexPropType, selectedTabClassName: PropTypes.string, selectedTabPanelClassName: PropTypes.string, environment: PropTypes.object, }; constructor(props) { super(props); this.state = Tabs.copyPropsToState(this.props, {}, props.defaultFocus); } static getDerivedStateFromProps(props, state) { return Tabs.copyPropsToState(props, state); } static getModeFromProps(props) { return props.selectedIndex === null ? MODE_UNCONTROLLED : MODE_CONTROLLED; } handleSelected = (index, last, event) => { const { onSelect } = this.props; const { mode } = this.state; // Call change event handler if (typeof onSelect === 'function') { // Check if the change event handler cancels the tab change if (onSelect(index, last, event) === false) return; } const state = { // Set focus if the change was triggered from the keyboard focus: event.type === 'keydown', }; if (mode === MODE_UNCONTROLLED) { // Update selected index state.selectedIndex = index; } this.setState(state); }; // preserve the existing selectedIndex from state. // If the state has not selectedIndex, default to the defaultIndex or 0 static copyPropsToState(props, state, focus = false) { if ( process.env.NODE_ENV !== 'production' && state.mode !== undefined && state.mode !== Tabs.getModeFromProps(props) ) { throw new Error( `Switching between controlled mode (by using \`selectedIndex\`) and uncontrolled mode is not supported in \`Tabs\`. For more information about controlled and uncontrolled mode of react-tabs see https://github.com/reactjs/react-tabs#controlled-vs-uncontrolled-mode.`, ); } const newState = { focus, mode: Tabs.getModeFromProps(props), }; if (newState.mode === MODE_UNCONTROLLED) { const maxTabIndex = Math.max(0, getTabsCount(props.children) - 1); let selectedIndex = null; if (state.selectedIndex != null) { selectedIndex = Math.min(state.selectedIndex, maxTabIndex); } else { selectedIndex = props.defaultIndex || 0; } newState.selectedIndex = selectedIndex; } return newState; } render() { const { children, defaultIndex, defaultFocus, ...props } = this.props; const { focus, selectedIndex } = this.state; props.focus = focus; props.onSelect = this.handleSelected; if (selectedIndex != null) { props.selectedIndex = selectedIndex; } return <UncontrolledTabs {...props}>{children}</UncontrolledTabs>; } } Tabs.tabsRole = 'Tabs';
app/javascript/mastodon/features/getting_started/index.js
Kirishima21/mastodon
import React from 'react'; import Column from '../ui/components/column'; import ColumnLink from '../ui/components/column_link'; import ColumnSubheading from '../ui/components/column_subheading'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { me, profile_directory, showTrends } from '../../initial_state'; import { fetchFollowRequests } from 'mastodon/actions/accounts'; import { List as ImmutableList } from 'immutable'; import NavigationContainer from '../compose/containers/navigation_container'; import Icon from 'mastodon/components/icon'; import LinkFooter from 'mastodon/features/ui/components/link_footer'; import TrendsContainer from './containers/trends_container'; const messages = defineMessages({ home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' }, notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' }, public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' }, settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' }, community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' }, direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' }, bookmarks: { id: 'navigation_bar.bookmarks', defaultMessage: 'Bookmarks' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' }, lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' }, discover: { id: 'navigation_bar.discover', defaultMessage: 'Discover' }, personal: { id: 'navigation_bar.personal', defaultMessage: 'Personal' }, security: { id: 'navigation_bar.security', defaultMessage: 'Security' }, menu: { id: 'getting_started.heading', defaultMessage: 'Getting started' }, profile_directory: { id: 'getting_started.directory', defaultMessage: 'Profile directory' }, }); const mapStateToProps = state => ({ myAccount: state.getIn(['accounts', me]), columns: state.getIn(['settings', 'columns']), unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size, }); const mapDispatchToProps = dispatch => ({ fetchFollowRequests: () => dispatch(fetchFollowRequests()), }); const badgeDisplay = (number, limit) => { if (number === 0) { return undefined; } else if (limit && number >= limit) { return `${limit}+`; } else { return number; } }; const NAVIGATION_PANEL_BREAKPOINT = 600 + (285 * 2) + (10 * 2); export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class GettingStarted extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { intl: PropTypes.object.isRequired, myAccount: ImmutablePropTypes.map.isRequired, columns: ImmutablePropTypes.list, multiColumn: PropTypes.bool, fetchFollowRequests: PropTypes.func.isRequired, unreadFollowRequests: PropTypes.number, unreadNotifications: PropTypes.number, }; componentDidMount () { const { fetchFollowRequests, multiColumn } = this.props; if (!multiColumn && window.innerWidth >= NAVIGATION_PANEL_BREAKPOINT) { this.context.router.history.replace('/home'); return; } fetchFollowRequests(); } render () { const { intl, myAccount, columns, multiColumn, unreadFollowRequests } = this.props; const navItems = []; let height = (multiColumn) ? 0 : 60; if (multiColumn) { navItems.push( <ColumnSubheading key='header-discover' text={intl.formatMessage(messages.discover)} />, <ColumnLink key='community_timeline' icon='users' text={intl.formatMessage(messages.community_timeline)} to='/public/local' />, <ColumnLink key='public_timeline' icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/public' />, ); height += 34 + 48*2; if (profile_directory) { navItems.push( <ColumnLink key='directory' icon='address-book' text={intl.formatMessage(messages.profile_directory)} to='/directory' />, ); height += 48; } navItems.push( <ColumnSubheading key='header-personal' text={intl.formatMessage(messages.personal)} />, ); height += 34; } else if (profile_directory) { navItems.push( <ColumnLink key='directory' icon='address-book' text={intl.formatMessage(messages.profile_directory)} to='/directory' />, ); height += 48; } if (multiColumn && !columns.find(item => item.get('id') === 'HOME')) { navItems.push( <ColumnLink key='home' icon='home' text={intl.formatMessage(messages.home_timeline)} to='/home' />, ); height += 48; } navItems.push( <ColumnLink key='direct' icon='envelope' text={intl.formatMessage(messages.direct)} to='/conversations' />, <ColumnLink key='bookmark' icon='bookmark' text={intl.formatMessage(messages.bookmarks)} to='/bookmarks' />, <ColumnLink key='favourites' icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />, <ColumnLink key='lists' icon='list-ul' text={intl.formatMessage(messages.lists)} to='/lists' />, ); height += 48*4; if (myAccount.get('locked') || unreadFollowRequests > 0) { navItems.push(<ColumnLink key='follow_requests' icon='user-plus' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />); height += 48; } if (!multiColumn) { navItems.push( <ColumnSubheading key='header-settings' text={intl.formatMessage(messages.settings_subheading)} />, <ColumnLink key='preferences' icon='gears' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' />, ); height += 34 + 48; } return ( <Column bindToDocument={!multiColumn} label={intl.formatMessage(messages.menu)}> {multiColumn && <div className='column-header__wrapper'> <h1 className='column-header'> <button> <Icon id='bars' className='column-header__icon' fixedWidth /> <FormattedMessage id='getting_started.heading' defaultMessage='Getting started' /> </button> </h1> </div>} <div className='getting-started'> <div className='getting-started__wrapper' style={{ height }}> {!multiColumn && <NavigationContainer />} {navItems} </div> {!multiColumn && <div className='flex-spacer' />} <LinkFooter withHotkeys={multiColumn} /> </div> {multiColumn && showTrends && <TrendsContainer />} </Column> ); } }
src/app/development/trc/MajorDevelopmentDashboard.js
cityofasheville/simplicity2
import React from 'react'; // import SectionNav from './SectionNav'; import { Link } from 'react-router'; import Accordion from '../../../shared/Accordion'; import ErrorBoundary from '../../../shared/ErrorBoundary'; import { devDashSections } from './textContent'; const introductoryContent = ( <header style={{paddingBottom: "32px"}}> <h1>Large-Scale Development in Asheville</h1> <p>There is a lot of private land development happening in Asheville. This tool can help you:</p> <ul> <li> Understand the development process from the first permit application to breaking ground </li> <li> Understand your role in the process and how your voice can be heard </li> <li> <a href="https://notifications.ashevillenc.gov" target="_blank" rel="noopener noreferrer" >Sign up to be notified</a> when someone applies for a permit to build something near you </li> </ul> <p>Do you have ideas for how this tool could be updated or refined to better serve our community? If so, please <a href="https://forms.gle/kSRTZidJUtNdZ8Rz7" target="_blank" rel="noopener noreferrer">send us your feedback</a>!</p> </header> ); class MajorDevelopmentDashboard extends React.Component { constructor() { super(); // Should re-render when screen size is changed to allow it to conditionally render this.state = { width: window.innerWidth, }; this.updateWindowWidth = this.updateWindowWidth.bind(this); // Assign each a ref so that we can know the size // this.sections = devDashSections.map((d) => { // const rObj = Object.assign({}, d); // rObj.ref = React.createRef(); // return rObj; // }); } componentDidMount() { this.updateWindowWidth(); window.addEventListener('resize', this.updateWindowWidth); } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowWidth); } updateWindowWidth() { this.setState({ width: window.innerWidth }); } render() { // Iterate over sections, make the selected one whichever one is in the URL // const thisLocation = location.hash.replace('#', ''); // this.sections = this.sections.map(d => Object.assign( // d, // { selected: d.linkId === thisLocation } // )); // Make it less overwhelming/scrolly for smaller screens // Breaking at 1120 after setting side nav to min-width of 200 if (this.state.width < 1120) { return ( <main id="majorDevDash"> {introductoryContent} <Accordion data={devDashSections} componentId="top-level" classes="top-level-accordion" onPanelHeaderClick={(sectionData, opening) => { // When someone opens a panel header, change the URL if (opening) { history.replaceState( {}, sectionData.linkId, `${location.pathname}${location.search}#${sectionData.linkId}` ); } }} /> </main> ); } // return ( // <div id="majorDevDash"> // <SectionNav // links={this.sections} // /> // <main> // {introductoryContent} // {this.sections.map(section => ( // <section id={section.linkId} ref={section.ref} key={section.linkId} style={{ overflow: 'auto' }}> // <h2>{section.header}</h2> // <ErrorBoundary> // {section.body} // </ErrorBoundary> // </section> // ))} // </main> // </div> // ); return ( <div id="majorDevDash" className="container-fluid h-100"> <nav> <ul className="sectionNav" > <li><a href="#types" className="linkItem-not-selected">Project Types</a></li> <li><a href="#process" className="linkItem-not-selected">Process</a></li> <li> <Link to='/permits/search' className="linkItem-not-selected">Development &amp; Permit Search</Link> </li> <li><a href="#notifications" className="linkItem-not-selected">Get Notifications</a></li> <li><a href="#data" className="linkItem-not-selected">Project Details</a></li> <li><a href="#participate" className="linkItem-not-selected">Get Involved</a></li> <li><a href="#faq" className="linkItem-not-selected">Frequently Asked Questions</a></li> </ul> </nav> <main> <div style={{margin: "0 auto"}}> {introductoryContent} {devDashSections.map(section => ( <section id={section.linkId} key={section.linkId} style={{ overflow: 'auto' }}> <h2>{section.header}</h2> <ErrorBoundary> {section.body} </ErrorBoundary> </section> ))} </div> </main> </div> ); } } export default MajorDevelopmentDashboard;
src/svg-icons/editor/attach-file.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorAttachFile = (props) => ( <SvgIcon {...props}> <path d="M16.5 6v11.5c0 2.21-1.79 4-4 4s-4-1.79-4-4V5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6H10v9.5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V5c0-2.21-1.79-4-4-4S7 2.79 7 5v12.5c0 3.04 2.46 5.5 5.5 5.5s5.5-2.46 5.5-5.5V6h-1.5z"/> </SvgIcon> ); EditorAttachFile = pure(EditorAttachFile); EditorAttachFile.displayName = 'EditorAttachFile'; EditorAttachFile.muiName = 'SvgIcon'; export default EditorAttachFile;
src/svg-icons/action/trending-up.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTrendingUp = (props) => ( <SvgIcon {...props}> <path d="M16 6l2.29 2.29-4.88 4.88-4-4L2 16.59 3.41 18l6-6 4 4 6.3-6.29L22 12V6z"/> </SvgIcon> ); ActionTrendingUp = pure(ActionTrendingUp); ActionTrendingUp.displayName = 'ActionTrendingUp'; ActionTrendingUp.muiName = 'SvgIcon'; export default ActionTrendingUp;
src/main.js
rumblesan/web-befunge
/* global Two: false */ import 'babel-polyfill'; import * as Befunge from './befunge'; import * as Grid from './befunge/grid'; import * as GridGFX from './befunge/gridGfx'; import * as Interpreter from './befunge/interpreter'; import * as PointerGFX from './befunge/pointerGfx'; import * as Terminal from './ui/terminal'; import * as CellGfx from './ui/cellGfx'; import NavBar from './ui/navbar'; import React from 'react'; import ReactDOM from 'react-dom'; import {cellCreationMenu} from './befunge/creationMenu'; const gridConfig = { xCells: 80, yCells: 25, cellSize: 40, style: { stroke: 'black', background: 'white', linewidth: 2 } }; const menuConfig = { buttonWidth: 50, buttonHeight: 50, buttonColumns: 5, linewidth: 2 }; const cellStyle = { normal: { fill: '#FF8000', stroke: 'orangered', }, modified: { fill: 'red', stroke: 'orangered', }, linewidth: 5, textSize: gridConfig.cellSize * 0.7, cellSize: gridConfig.cellSize * 0.8 }; const pointerStyle = { noFill: true, stroke: 'blue', linewidth: 5 }; const displayCellCreationMenu = (befunge) => { return (e) => { e.preventDefault(); const coords = Grid.getCoordinates(befunge.grid, befunge.two.scene, e.clientX, e.clientY); const menu = cellCreationMenu(befunge, coords, menuConfig); menu.svg.translation.set(coords.cX, coords.cY); befunge.two.update(); }; }; const addGridInteractivity = (two, befunge) => { befunge.gridGfx._renderer.elem.addEventListener('dblclick', displayCellCreationMenu(befunge) ); befunge.gridGfx._renderer.elem.addEventListener('mousedown', function (e) { e.preventDefault(); const sceneOffset = two.scene.translation; const xOffset = e.clientX - sceneOffset.x; const yOffset = e.clientY - sceneOffset.y; const drag = function (e) { e.preventDefault(); two.scene.translation.set(e.clientX - xOffset, e.clientY - yOffset); }; const dragEnd = function (e) { e.preventDefault(); window.removeEventListener('mousemove', drag); window.removeEventListener('mouseup', dragEnd); }; window.addEventListener('mousemove', drag); window.addEventListener('mouseup', dragEnd); }); }; (function () { const two = new Two({ type: Two.Types['svg'], fullscreen: true, autostart: true }).appendTo(document.getElementById('app')); const grid = Grid.create(gridConfig); const gridGfx = GridGFX.create(two, gridConfig); const cellGfx = CellGfx.create(two, cellStyle); const pointerGfx = PointerGFX.create(two, gridConfig, pointerStyle); const terminal = Terminal.create( document.getElementById('console') ); const interpreter = Interpreter.create(); const befunge = Befunge.create(two, interpreter, grid, gridGfx, cellGfx, pointerGfx, terminal); const cellConstructor = (instruction, coords) => { Befunge.newCell(befunge, instruction, coords, false); }; ReactDOM.render( <NavBar startStop={() => { befunge.running ? Befunge.stop(befunge) : Befunge.start(befunge); }} step={() => { if (befunge.running) { Befunge.stop(befunge); } Befunge.step(befunge); }} reset={() => { Terminal.message(terminal, 'Resetting'); Befunge.reset(befunge); }} updateprogram={(text) => { Terminal.message(terminal, 'Loading new program'); Befunge.updateProgram(befunge, text, cellConstructor); }} speedUp={() => { Terminal.message(terminal, 'Speed up'); Interpreter.speedUp(interpreter); }} slowDown={() => { Terminal.message(terminal, 'Slow down'); Interpreter.slowDown(interpreter); }} befunge={befunge} running={befunge.running} />, document.getElementById('header'), ); two.update(); addGridInteractivity(two, befunge); })();
packages/vx-legend/src/legends/Legend.js
Flaque/vx
import React from 'react'; import cx from 'classnames'; import PropTypes from 'prop-types'; import LegendItem from './LegendItem'; import LegendLabel from './LegendLabel'; import LegendShape from './LegendShape'; import valueOrIdentity from '../util/valueOrIdentity'; Legend.propTypes = { className: PropTypes.string, style: PropTypes.object, scale: PropTypes.oneOfType([PropTypes.func, PropTypes.object]) .isRequired, shapeWidth: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), shapeHeight: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), shapeMargin: PropTypes.string, labelMargin: PropTypes.string, itemMargin: PropTypes.string, direction: PropTypes.string, itemDirection: PropTypes.string, fill: PropTypes.func, shape: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), labelFormat: PropTypes.func, labelTransform: PropTypes.func, }; export default function Legend({ className, style, shapeStyle, scale, shape, domain, fill = valueOrIdentity, size = valueOrIdentity, labelFormat = valueOrIdentity, labelTransform = defaultTransform, shapeWidth = 15, shapeHeight = 15, shapeMargin = '2px 4px 2px 0', labelAlign = 'left', labelMargin = '0 4px', itemMargin = '0', direction = 'column', itemDirection = 'row', ...restProps }) { domain = domain || scale.domain(); const labels = domain.map(labelTransform({ scale, labelFormat })); return ( <div className={cx('vx-legend', className)} style={style} style={{ display: 'flex', flexDirection: direction, }} > {labels.map((label, i) => { const { text } = label; return ( <LegendItem key={`legend-${label}-${i}`} margin={itemMargin} flexDirection={itemDirection} > <LegendShape shape={shape} height={shapeHeight} width={shapeWidth} margin={shapeMargin} label={label} fill={fill} size={size} shapeStyle={shapeStyle} /> <LegendLabel label={text} margin={labelMargin} align={labelAlign} /> </LegendItem> ); })} </div> ); } function defaultTransform({ scale, labelFormat }) { return (d, i) => { return { datum: d, index: i, text: `${labelFormat(d, i)}`, value: scale(d), }; }; }
app/client.js
sagnikm95/internship-portal
import ReactDOM from 'react-dom'; import React from 'react'; import { Router } from 'react-router-dom'; import { Grid } from 'semantic-ui-react'; import Routes from './routes'; import browserHistory from './history'; import './globals.scss'; ReactDOM.render( <Router history={browserHistory}> {/* Responsive grid based layout. */} <Grid> {/* Empty Grind to center the content column. */} <Grid.Column width={1} /> {/* Content Column. */} <Grid.Column width={14}> <Routes /> </Grid.Column> </Grid> </Router>, document.getElementById('app'), );
src/svg-icons/action/settings-input-antenna.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsInputAntenna = (props) => ( <SvgIcon {...props}> <path d="M12 5c-3.87 0-7 3.13-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.87-3.13-7-7-7zm1 9.29c.88-.39 1.5-1.26 1.5-2.29 0-1.38-1.12-2.5-2.5-2.5S9.5 10.62 9.5 12c0 1.02.62 1.9 1.5 2.29v3.3L7.59 21 9 22.41l3-3 3 3L16.41 21 13 17.59v-3.3zM12 1C5.93 1 1 5.93 1 12h2c0-4.97 4.03-9 9-9s9 4.03 9 9h2c0-6.07-4.93-11-11-11z"/> </SvgIcon> ); ActionSettingsInputAntenna = pure(ActionSettingsInputAntenna); ActionSettingsInputAntenna.displayName = 'ActionSettingsInputAntenna'; ActionSettingsInputAntenna.muiName = 'SvgIcon'; export default ActionSettingsInputAntenna;
client/src/javascript/components/modals/feeds-modal/FeedsTab.js
jfurrow/flood
import _ from 'lodash'; import {defineMessages, FormattedMessage, injectIntl} from 'react-intl'; import { Button, Checkbox, Form, FormError, FormRow, FormRowGroup, FormRowItem, Select, SelectItem, Textbox, } from 'flood-ui-kit'; import formatUtil from '@shared/util/formatUtil'; import React from 'react'; import Edit from '../../icons/Edit'; import Close from '../../icons/Close'; import EventTypes from '../../../constants/EventTypes'; import FeedMonitorStore from '../../../stores/FeedMonitorStore'; import ModalFormSectionHeader from '../ModalFormSectionHeader'; import * as validators from '../../../util/validators'; import UIActions from '../../../actions/UIActions'; import connectStores from '../../../util/connectStores'; const MESSAGES = defineMessages({ mustSpecifyURL: { id: 'feeds.validation.must.specify.valid.feed.url', defaultMessage: 'You must specify a valid feed URL.', }, mustSpecifyLabel: { id: 'feeds.validation.must.specify.label', defaultMessage: 'You must specify a label.', }, intervalNotPositive: { id: 'feeds.validation.interval.not.positive', defaultMessage: 'The interval must be a positive integer.', }, min: { id: 'feeds.time.min', defaultMessage: 'Minutes', }, hr: { id: 'feeds.time.hr', defaultMessage: 'Hours', }, day: { id: 'feeds.time.day', defaultMessage: 'Days', }, url: { id: 'feeds.url', defaultMessage: 'URL', }, label: { id: 'feeds.label', defaultMessage: 'Label', }, interval: { id: 'feeds.interval', defaultMessage: 'Interval', }, tags: { id: 'feeds.tags', defaultMessage: 'Tags', }, search: { id: 'feeds.search', defaultMessage: 'Search term', }, }); const defaultFeed = { label: '', interval: 5, url: '', }; class FeedsTab extends React.Component { formRef = null; manualAddingFormRef = null; validatedFields = { url: { isValid: validators.isURLValid, error: this.props.intl.formatMessage(MESSAGES.mustSpecifyURL), }, label: { isValid: validators.isNotEmpty, error: this.props.intl.formatMessage(MESSAGES.mustSpecifyLabel), }, interval: { isValid: validators.isPositiveInteger, error: this.props.intl.formatMessage(MESSAGES.intervalNotPositive), }, }; state = { errors: {}, intervalmultipliers: [ { displayName: this.props.intl.formatMessage(MESSAGES.min), value: 1, }, { displayName: this.props.intl.formatMessage(MESSAGES.hr), value: 60, }, { displayName: this.props.intl.formatMessage(MESSAGES.day), value: 1440, }, ], currentlyEditingFeed: null, selectedFeed: null, }; checkFieldValidity = _.throttle((fieldName, fieldValue) => { const {errors} = this.state; if (this.state.errors[fieldName] && this.validatedFields[fieldName].isValid(fieldValue)) { delete errors[fieldName]; this.setState({errors}); } }, 150); getAmendedFormData() { const formData = this.formRef.getFormData(); formData.interval = (formData.interval * formData.intervalMultiplier).toString(); delete formData.intervalMultiplier; return formData; } getIntervalSelectOptions() { return this.state.intervalmultipliers.map(interval => ( <SelectItem key={interval.value} id={interval.value}> {interval.displayName} </SelectItem> )); } getAvailableFeedsOptions() { const {feeds} = this.props; if (!feeds.length) { return [ <SelectItem key="empty" id="placeholder" placeholder> <em> <FormattedMessage id="feeds.no.feeds.available" defaultMessage="No feeds available." /> </em> </SelectItem>, ]; } return feeds.reduce( (feedOptions, feed) => feedOptions.concat( <SelectItem key={feed._id} id={feed._id}> {feed.label} </SelectItem>, ), [ <SelectItem key="select-feed" id="placeholder" placeholder> <em> <FormattedMessage id="feeds.select.feed" defaultMessage="Select feed" /> </em> </SelectItem>, ], ); } getModifyFeedForm(feed) { const isDayInterval = feed.interval % 1440; const minutesDivisor = feed.interval % 60 ? 1 : 60; const defaultIntervalTextValue = feed.interval / isDayInterval ? minutesDivisor : 1440; const defaultIntervalMultiplierId = isDayInterval ? minutesDivisor : 1440; return ( <FormRowGroup> <FormRow> <Textbox id="label" label={this.props.intl.formatMessage(MESSAGES.label)} placeholder={this.props.intl.formatMessage(MESSAGES.label)} defaultValue={feed.label} /> <Textbox id="interval" label={this.props.intl.formatMessage({ id: 'feeds.select.interval', defaultMessage: 'Interval', })} placeholder={this.props.intl.formatMessage(MESSAGES.interval)} defaultValue={defaultIntervalTextValue} width="one-eighth" /> <Select labelOffset defaultID={defaultIntervalMultiplierId} id="intervalMultiplier" width="one-eighth"> {this.getIntervalSelectOptions()} </Select> </FormRow> <FormRow> <Textbox id="url" label={this.props.intl.formatMessage({ id: 'feeds.url', defaultMessage: 'URL', })} placeholder={this.props.intl.formatMessage(MESSAGES.url)} defaultValue={feed.url} /> <Button labelOffset onClick={() => this.setState({currentlyEditingFeed: null})}> <FormattedMessage id="button.cancel" defaultMessage="Cancel" /> </Button> <Button labelOffset type="submit"> <FormattedMessage id="button.save.feed" defaultMessage="Save" /> </Button> </FormRow> </FormRowGroup> ); } getFeedsListItem(feed) { const matchedCount = feed.count || 0; return ( <li className="interactive-list__item interactive-list__item--stacked-content feed-list__feed" key={feed._id}> <div className="interactive-list__label"> <ul className="interactive-list__detail-list"> <li className="interactive-list__detail-list__item interactive-list__detail--primary"> {feed.label} </li> <li className="interactive-list__detail-list__item interactive-list__detail-list__item--overflow interactive-list__detail interactive-list__detail--secondary"> <FormattedMessage id="feeds.match.count" defaultMessage="{count, plural, =1 {# match} other {# matches}}" values={{count: matchedCount}} /> </li> {feed === this.state.currentlyEditingFeed && ( <li className="interactive-list__detail-list__item interactive-list__detail--primary"> Modifying </li> )} </ul> <ul className="interactive-list__detail-list"> <li className="interactive-list__detail-list__item interactive-list__detail interactive-list__detail--tertiary"> {formatUtil.minToHumanReadable(feed.interval)} </li> <li className="interactive-list__detail-list__item interactive-list__detail-list__item--overflow interactive-list__detail interactive-list__detail--tertiary"> <a href={feed.url} rel="noopener noreferrer" target="_blank"> {feed.url} </a> </li> </ul> </div> <span className="interactive-list__icon interactive-list__icon--action" onClick={() => this.handleModifyFeedClick(feed)}> <Edit /> </span> <span className="interactive-list__icon interactive-list__icon--action interactive-list__icon--action--warning" onClick={() => this.handleRemoveFeedClick(feed)}> <Close /> </span> </li> ); } getFeedAddForm(errors) { return ( <Form className="inverse" onChange={this.handleFormChange} onSubmit={this.handleFormSubmit} ref={ref => { this.formRef = ref; }}> <ModalFormSectionHeader> <FormattedMessage id="feeds.existing.feeds" defaultMessage="Existing Feeds" /> </ModalFormSectionHeader> {errors} <FormRow> <FormRowItem>{this.getFeedsList()}</FormRowItem> </FormRow> {this.state.currentlyEditingFeed ? ( this.getModifyFeedForm(this.state.currentlyEditingFeed) ) : ( <FormRow> <FormRowItem width="auto" /> <Button onClick={() => this.handleAddFeedClick()}> <FormattedMessage id="button.new" defaultMessage="New" /> </Button> </FormRow> )} </Form> ); } getFeedsList() { const {feeds} = this.props; if (feeds.length === 0) { return ( <ul className="interactive-list"> <li className="interactive-list__item"> <FormattedMessage defaultMessage="No feeds defined." id="feeds.no.feeds.defined" /> </li> </ul> ); } const feedsList = feeds.map(feed => this.getFeedsListItem(feed)); return <ul className="interactive-list feed-list">{feedsList}</ul>; } getFeedItemsForm() { return ( <Form className="inverse" onChange={this.handleBrowseFeedChange} onSubmit={this.handleBrowseFeedSubmit} ref={ref => { this.manualAddingFormRef = ref; }}> <ModalFormSectionHeader> <FormattedMessage id="feeds.browse.feeds" defaultMessage="Browse feeds" /> </ModalFormSectionHeader> <FormRow> <Select disabled={!this.props.feeds.length} grow={false} id="feedID" label={this.props.intl.formatMessage({ id: 'feeds.select.feed', defaultMessage: 'Select feed', })} width="three-eighths"> {this.getAvailableFeedsOptions()} </Select> {this.renderSearchField()} {this.renderDownloadButton()} </FormRow> {this.state.selectedFeed && <FormRow>{this.getFeedItemsList()}</FormRow>} </Form> ); } getFeedItemsList() { const {items} = this.props; if (items.length === 0) { return ( <ul className="interactive-list"> <li className="interactive-list__item"> <div className="interactive-list__label"> <FormattedMessage defaultMessage="No items matching search term." id="feeds.no.items.matching" /> </div> </li> </ul> ); } const itemsList = items.map((item, index) => ( <li className="interactive-list__item interactive-list__item--stacked-content feed-list__feed" key={item.title}> <div className="interactive-list__label feed-list__feed-label">{item.title}</div> <Checkbox id={index} /> </li> )); return <ul className="interactive-list feed-list">{itemsList}</ul>; } handleFormSubmit = () => { const {errors, isValid} = this.validateForm(); if (!isValid) { this.setState({errors}); } else { const currentFeed = this.state.currentlyEditingFeed; const formData = this.getAmendedFormData(); if (currentFeed === defaultFeed) { FeedMonitorStore.addFeed(formData); } else { FeedMonitorStore.modifyFeed(currentFeed._id, formData); } this.formRef.resetForm(); this.setState({currentlyEditingFeed: null}); } }; handleFormChange = ({event, formData}) => { this.checkFieldValidity(event.target.name, formData[event.target.name]); }; handleRemoveFeedClick = feed => { FeedMonitorStore.removeFeed(feed._id); if (feed === this.state.currentlyEditingFeed) { this.setState({currentlyEditingFeed: null}); } }; handleAddFeedClick = () => { this.setState({currentlyEditingFeed: defaultFeed}); }; handleModifyFeedClick = feed => { this.setState({currentlyEditingFeed: feed}); }; handleBrowseFeedChange = input => { if (input.event.target.type !== 'checkbox') { this.setState({selectedFeed: input.formData.feedID}); FeedMonitorStore.fetchItems({params: {id: input.formData.feedID, search: input.formData.search}}); } }; handleBrowseFeedSubmit = () => { const formData = this.manualAddingFormRef.getFormData(); const downloadedTorrents = this.props.items .filter((item, index) => formData[index]) .map((torrent, index) => ({id: index, value: torrent.link})); UIActions.displayModal({id: 'add-torrents', torrents: downloadedTorrents}); }; validateForm() { const formData = this.formRef.getFormData(); const errors = Object.keys(this.validatedFields).reduce((memo, fieldName) => { const fieldValue = formData[fieldName]; if (!this.validatedFields[fieldName].isValid(fieldValue)) { memo[fieldName] = this.validatedFields[fieldName].error; } return memo; }, {}); return {errors, isValid: !Object.keys(errors).length}; } renderSearchField = () => { const {selectedFeed} = this.state; if (selectedFeed == null) return null; return ( <Textbox id="search" label={this.props.intl.formatMessage({ id: 'feeds.search.term', defaultMessage: 'Search term', })} placeholder={this.props.intl.formatMessage(MESSAGES.search)} /> ); }; renderDownloadButton = () => { const {selectedFeed} = this.state; if (selectedFeed == null) return null; return ( <Button key="button" type="submit" labelOffset> <FormattedMessage id="button.download" defaultMessage="Download" /> </Button> ); }; render() { const errors = Object.keys(this.state.errors).map(errorID => ( <FormRow key={errorID}> <FormError>{this.state.errors[errorID]}</FormError> </FormRow> )); return ( <div> {this.getFeedAddForm(errors)} {this.getFeedItemsForm()} </div> ); } } const ConnectedFeedsTab = connectStores(injectIntl(FeedsTab), () => { return [ { store: FeedMonitorStore, event: EventTypes.SETTINGS_FEED_MONITORS_FETCH_SUCCESS, getValue: ({store}) => { return { feeds: store.getFeeds(), }; }, }, { store: FeedMonitorStore, event: EventTypes.SETTINGS_FEED_MONITOR_ITEMS_FETCH_SUCCESS, getValue: ({store}) => { return { items: store.getItems() || [], }; }, }, ]; }); export default ConnectedFeedsTab;
client/node_modules/uu5g03/doc/main/server/public/data/source/uu5-forms-v3-internal-item-list.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import {BaseMixin, ElementaryMixin, SectionMixin, Tools} from './../../common/common.js'; import './item-list.less'; export default React.createClass({ //@@viewOn:mixins mixins: [ BaseMixin, ElementaryMixin, SectionMixin ], //@@viewOff:mixins //@@viewOn:statics statics: { tagName: "UU5.Forms.ItemList", classNames: { main: "uu5-forms-item-list", header: "uu5-forms-item-list-header", body: "uu5-forms-item-list-body", footer: "uu5-forms-item-list-footer", selectedItem: "uu5-forms-item-list-selected uu5-common-bg" }, defaults: { childTagName: 'UU5.Forms.Select.option' } }, //@@viewOff:statics //@@viewOn:propTypes propTypes: { allowTags: React.PropTypes.array }, //@@viewOff:propTypes //@@viewOn:getDefaultProps getDefaultProps: function () { return { allowTags: [] }; }, //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle //@@viewOff:standardComponentLifeCycle //@@viewOn:interface changeValue (index, e, setStateCallback) { if (typeof this.props.onChange === 'function') { this.props.onChange({value: index, event: e, component: this, setStateCallback: setStateCallback}); } }, //@@viewOff:interface //@@viewOn:overridingMethods shouldChildRender_: function (child) { var childTagName = Tools.getChildTagName(child); var childTagNames = this.props.allowTags.concat(this.getDefault().childTagName); return childTagNames.indexOf(childTagName) > -1; }, expandChildProps_: function (child, i) { var props = Tools.mergeDeep({}, child.props); if (this.props.value && this.props.value.indexOf(i) > -1) { props.selected = true; props.className = props.className ? props.className + ' ' + this.getClassName().selectedItem : this.getClassName().selectedItem; props.colorSchema = 'info'; } props.mainAttrs = props.mainAttrs || {}; props.mainAttrs.id = this.getId() + '-item-' + i; var childOnClick = props.onClick; props.onClick = (opt) => { this.changeValue(opt.value, opt.event, childOnClick); }; return props; }, //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers _getHeader(){ let result; if(this.props.header) { result = <div className={this.getClassName().header}> {this.getHeader()} </div>; } return result; }, _getFooter(){ let result; if(this.props.footer) { result = <div className={this.getClassName().footer}> {this.getFooter()} </div>; } return result; }, //@@viewOff:componentSpecificHelpers //@@viewOn:render render: function () { return ( <div {...this.getMainAttrs()}> {this._getHeader()} <div className={this.getClassName().body}> {this.getChildren()} </div> {this._getFooter()} </div> ); } //@@viewOn:render });
src/util/RichTextTagger.js
Hylozoic/hylo-redux
import React from 'react' import { getKeyCode, keyMap } from '../util/textInput' import { exitNode, insertJSX, removeCurrentNode, replaceNodeWithJSX, selectCurrentNode } from '../util/tinymce' import { includes, some } from 'lodash' export const hashtagAttribute = 'data-autocompleting' export const justCreatedAttribute = 'data-just-created' const nbsp = String.fromCharCode(160) // non-breaking space const triggerKeyCodes = [keyMap.HASH, keyMap.AT_SIGN] const triggers = ['#', '@'] const template = keyCode => { const attrs = { [hashtagAttribute]: true, [justCreatedAttribute]: true, spellCheck: false, autoComplete: false, autoCorrect: false } // FIXME autoComplete and autoCorrect don't appear even though they are valid // in React -- probably being stripped by tinymce? return <a {...attrs}>{String.fromCharCode(keyCode)}</a> } const Mention = ({ person }) => <a data-user-id={person.id} href={'/u/' + person.id}> {person.name} </a> export class RichTextTagger { constructor (editor, autocomplete) { this.editor = editor this.autocomplete = autocomplete } // if in a text node, will return its parent domNode () { return this.editor.selection.getNode() } search (term) { if (term === this.lastSearch) return this.lastSearch = term this.autocomplete(term, this.domNode()) } isInTag () { return !!this.domNode().getAttribute(hashtagAttribute) } isInReplacedTag () { return !!this.domNode().getAttribute('data-user-id') } tagValue () { return this.editor.selection.getNode().innerHTML } tagValueIsEmpty () { return some(triggers, t => t === this.tagValue()) } canStartTag () { const { selection } = this.editor const rng = selection.getRng(true) const pos = rng.startOffset if (pos === 0) return true const char = rng.startContainer.textContent.slice(pos - 1)[0] return includes([nbsp, ' '], char) // Chrome & Firefox respectively } finishTag (choice, event) { const keyCode = getKeyCode(event) if (keyCode === keyMap.ENTER) { // this is a workaround for the fact that we can't suppress the insertion // of a new linebreak due to Enter in TinyMCE. (well, it's alleged that // you can, but only by defining a callback when first initializing // TinyMCE.) // // so we assume a new paragraph has been inserted, backtrack to the node // we were trying to replace, and remove the new paragraph. const extraP = window.tinymce.$(this.domNode()) const origP = extraP.prev() const node = origP.find(`[${hashtagAttribute}]`).last()[0] origP.append(extraP.contents()) this.editor.dom.remove(extraP) this.editor.selection.select(node) } // sort of a dumb heuristic: users have avatar_urls and tags don't if (choice.avatar_url) { replaceNodeWithJSX(<Mention person={choice} />, this.editor) } else { // for hashtags, we just update the text in the tag instead of replacing // anything, so it can always be edited, autocompleted, or saved as a new // hashtag as-is this.domNode().textContent = '#' + choice.name this.search(null) exitNode(this.editor, keyMap.SPACE) } } handleKeyUp = event => { const keyCode = getKeyCode(event) // select the whole tag when backspacing up to it so it's easy to delete all // at once if (keyCode === keyMap.BACKSPACE && this.isInReplacedTag()) { selectCurrentNode(this.editor) return } this.updateSearch(event) } handleKeyDown = event => { const keyCode = getKeyCode(event) switch (keyCode) { case keyMap.SPACE: if (this.isInTag()) { exitNode(this.editor, keyCode) event.preventDefault() } break case keyMap.BACKSPACE: // remove the tag entirely if backspacing over its first character if (this.tagValueIsEmpty()) { removeCurrentNode(this.editor) event.preventDefault() } } } // you can prevent the appearance of the character you typed by calling // event.preventDefault() handleKeyPress = event => { const keyCode = getKeyCode(event) // create an empty tag when a trigger character is typed if (includes(triggerKeyCodes, keyCode) && this.canStartTag()) { event.preventDefault() insertJSX(template(keyCode), this.editor) // if the cursor is not in the tag that was just created (this happens on // Firefox), we have to move it there const node = this.domNode() if (node.tagName !== 'A') { // there's probably a simpler way to find the tag than this... const tag = window.tinymce.$(node).find(`[${justCreatedAttribute}]`)[0] this.editor.selection.setCursorLocation(tag, 1) tag.removeAttribute(justCreatedAttribute) } else { node.removeAttribute(justCreatedAttribute) } } } updateSearch = event => { const keyCode = getKeyCode(event) if (this.isInTag()) { // trigger or reset typeahead const value = keyCode === keyMap.ESC ? null : this.tagValue() this.search(value) } else { // always reset typeahead if not inside a tag if (this.lastSearch) this.search(null) } } } export default RichTextTagger
cerberus-dashboard/src/components/SDBMetadata/SDBMetadata.js
Nike-Inc/cerberus-management-service
/* * Copyright (c) 2020 Nike, inc. * * 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 {Component} from 'react' import './SDBMetadata.scss' export default class SDBMetadata extends Component { render() { const {sdbMetadata} = this.props return ( <div className="sdb-metadata-container"> <div className="sdb-metadata"> <div className="sdb-metadata-kv"> <div className="sdb-metadata-label ncss-brand">Name:</div> <div className="sdb-metadata-value">{sdbMetadata.name}</div> </div> <div className="sdb-metadata-kv"> <div className="sdb-metadata-label ncss-brand">Secret Path:</div> <div className="sdb-metadata-value">{sdbMetadata.path}</div> </div> <div className="sdb-metadata-kv"> <div className="sdb-metadata-label ncss-brand">Owner:</div> <div className="sdb-metadata-value">{sdbMetadata.owner}</div> </div> </div> <div className="sdb-metadata"> <div className="sdb-metadata-kv"> <div className="sdb-metadata-label ncss-brand">Created By:</div> <div className="sdb-metadata-value">{sdbMetadata.created_by}</div> </div> <div className="sdb-metadata-kv"> <div className="sdb-metadata-label ncss-brand">Created:</div> <div className="sdb-metadata-value">{sdbMetadata.created_ts}</div> </div> </div> <div className="sdb-metadata"> <div className="sdb-metadata-kv"> <div className="sdb-metadata-label ncss-brand">Last Updated By:</div> <div className="sdb-metadata-value">{sdbMetadata.last_updated_by}</div> </div> <div className="sdb-metadata-kv"> <div className="sdb-metadata-label ncss-brand">Last Updated:</div> <div className="sdb-metadata-value">{sdbMetadata.last_updated_ts}</div> </div> </div> <div className="sdb-metadata"> <div className="sdb-metadata-kv"> <div className="sdb-metadata-label ncss-brand">Description:</div> <div className="sdb-metadata-value desc">{sdbMetadata.description}</div> </div> </div> <div className="sdb-metadata"> <div className="sdb-metadata-kv"> <div className="sdb-metadata-label ncss-brand">User Group Permissions:</div> <div className="sdb-metadata-value"> { getPermissionsAsString(sdbMetadata.user_group_permissions) } </div> </div> </div> <div className="sdb-metadata"> <div className="sdb-metadata-kv"> <div className="sdb-metadata-label ncss-brand">IAM Principal Permissions:</div> <div className="sdb-metadata-value"> { getPermissionsAsString(sdbMetadata.iam_role_permissions) } </div> </div> </div> </div> ) } } const getPermissionsAsString = (permissions) => { let string = Object.keys(permissions).map((key) => { return `${key}: ${permissions[key]}` }).join("\n") return string ? string : "No permissions defined" }
assets/jqwidgets/demos/react/app/complexinput/fluidsize/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxComplexInput from '../../../jqwidgets-react/react_jqxcomplexinput.js'; class App extends React.Component { render() { return ( <JqxComplexInput ref='myComplexInput' width={'30%'} height={25} value={'1000 + 2i'} spinButtons={true} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
example/src/index.js
ionutmilica/redux-modal-container
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './store'; import App from './app'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root'), );
front/src/components/icons/WifiIcon.js
MichaelKostin/mars-rover
import React from 'react'; import PropTypes from 'prop-types'; const WifiIcon = ({ quality }) => ( <svg xmlns="http://www.w3.org/2000/svg" height="50px" viewBox="0 0 466 466.47546" width="50px"> <path fill="#d6f6e9" d="m115.449219 351.132812c4.042969 4.003907 9.910156 5.554688 15.40625 4.078126l-19.488281-19.488282c-1.476563 5.496094.078124 11.363282 4.082031 15.410156zm0 0" /> <path fill={quality >= 30 ? '#d6f6e9' : '#5d6661'} d="m64.59375 359.949219c.09375.796875.214844 1.597656.351562 2.398437.136719.800782.296876 1.777344.488282 2.648438.222656 1.007812.503906 2 .796875 2.992187.195312.671875.378906 1.34375.601562 2 .390625 1.167969.855469 2.304688 1.335938 3.429688.214843.496093.398437.992187.625 1.480469.574219 1.234374 1.230469 2.402343 1.917969 3.625.210937.367187.394531.753906.617187 1.121093.800781 1.269531 1.640625 2.496094 2.542969 3.695313.191406.253906.351562.527344.546875.800781 1.125 1.445313 2.335937 2.828125 3.621093 4.136719 3.359376 3.410156 7.214844 6.285156 11.441407 8.535156 7.023437 3.761719 14.871093 5.730469 22.839843 5.734375.457032 0 .921876-.070313 1.382813-.085937.640625 0 1.273437 0 1.914063-.066407.109374 0 .199218-.070312.304687-.078125.917969-.074218 1.832031-.066406 2.75-.183594 4.382813-.59375 7.453125-4.625 6.859375-9.003906-.589844-4.382812-4.621094-7.453125-9.003906-6.863281-.65625.097656-1.320313.113281-1.984375.160156-4.621094.300781-9.253907-.375-13.597657-1.972656l-.183593-.074219c-2.042969-.769531-3.996094-1.75-5.832031-2.925781-.152344-.097656-.296876-.21875-.449219-.3125-1.808594-1.1875-3.488281-2.558594-5.015625-4.089844l-.097656-.121093c-1.644532-1.699219-3.09375-3.578126-4.320313-5.597657-.398437-.664062-.65625-1.390625-1.007813-2.082031-.765624-1.390625-1.425781-2.839844-1.984374-4.328125-.34375-1.015625-.503907-2.070313-.75-3.117187-.324219-1.222657-.574219-2.460938-.753907-3.714844-.101562-1.261719-.128906-2.53125-.085937-3.796875-.0625-1.503907-.019532-3.007813.136718-4.503907.453126-2.84375-.652343-5.714843-2.898437-7.511718-2.246094-1.800782-5.289063-2.253906-7.964844-1.1875-2.671875 1.0625-4.570312 3.484375-4.960937 6.335937-.144532.9375-.167969 1.882813-.257813 2.824219 0 .066406-.046875.121094-.054687.183594v.648437c-.089844 1.273438-.128906 2.539063-.121094 3.800781 0 .59375 0 1.183594.054688 1.777344.019531 1.09375.097656 2.191406.195312 3.289063zm0 0" /> <path fill={quality >= 60 ? '#d6f6e9' : '#5d6661'} d="m112.207031 434.484375c1.914063 0 3.839844-.074219 5.761719-.21875 2.910156-.121094 5.527344-1.816406 6.824219-4.425781 1.300781-2.609375 1.078125-5.71875-.582031-8.117188-1.65625-2.394531-4.488282-3.703125-7.386719-3.40625-18.675781 1.375-37.011719-5.515625-50.160157-18.84375-13.148437-13.332031-19.789062-31.757812-18.160156-50.414062.1875-2.117188-.476562-4.21875-1.84375-5.847656-1.367187-1.625-3.328125-2.640626-5.445312-2.824219-2.121094-.214844-4.238282.4375-5.867188 1.808593-1.632812 1.375-2.632812 3.351563-2.78125 5.480469-1.941406 22.3125 5.574219 44.417969 20.71875 60.921875 15.144532 16.5 36.523438 25.886719 58.921875 25.863282zm0 0" /> <path fill={quality >= 90 ? '#d6f6e9' : '#5d6661'} d="m119.089844 450.21875c-2.53125.183594-5.105469.265625-7.554688.257812-26.765625-.148437-52.25-11.484374-70.285156-31.261718-18.035156-19.78125-26.976562-46.199219-24.65625-72.867188.371094-4.398437-2.890625-8.269531-7.289062-8.648437-2.121094-.222657-4.242188.429687-5.875 1.804687-1.632813 1.375-2.632813 3.355469-2.773438 5.484375-2.699219 31.109375 7.730469 61.929688 28.769531 85.003907 21.039063 23.074218 50.765625 36.304687 81.992188 36.484374h.886719c2.640624 0 5.304687-.105468 8-.304687 2.898437-.148437 5.488281-1.855469 6.765624-4.460937 1.28125-2.601563 1.050782-5.695313-.597656-8.082032-1.652344-2.382812-4.464844-3.691406-7.351562-3.410156zm0 0"/> <path fill="#d6f6e9" d="m454.863281 11.714844c-15.621093-15.621094-40.945312-15.621094-56.566406 0l-16.96875 16.96875 56.566406 56.566406 16.96875-16.964844c15.621094-15.621094 15.621094-40.949218 0-56.570312zm0 0" /> <path fill={quality === 0 ? '#5d6661': '#d6f6e9'} d="m341.734375 116.851562c-2.121094 0-4.160156.839844-5.664063 2.34375l-124.445312 124.449219c-3.117188 3.121094-3.117188 8.179688 0 11.304688 3.15625 3.035156 8.152344 3.035156 11.3125 0l124.453125-124.441407c2.289063-2.289062 2.972656-5.730468 1.734375-8.71875-1.238281-2.988281-4.152344-4.9375-7.390625-4.9375zm0 0" /> <path fill="#d6f6e9" d="m358.695312 254.957031-45.253906-45.25 113.144532-113.144531-56.570313-56.566406-113.144531 113.144531-45.246094-45.257813 50.910156-50.910156-33.941406-33.945312-113.144531 113.136718 33.941406 33.945313 50.914063-50.914063 45.246093 45.257813-84.839843 84.847656 22.625 22.628907-34.558594 34.5625c-13.359375-8.816407-30.6875-8.835938-44.066406-.046876l55.425781 55.421876c8.785156-13.378907 8.765625-30.703126-.046875-44.0625l34.558594-34.5625 22.632812 22.625 84.847656-84.847657 45.253906 45.246094-50.910156 50.921875 33.945313 33.953125 113.132812-113.152344-33.941406-33.945312zm-141.414062 18.34375c-9.707031-.003906-18.457031-5.851562-22.167969-14.816406-3.714843-8.96875-1.664062-19.289063 5.199219-26.152344l124.449219-124.457031c9.371093-9.375 24.570312-9.375 33.945312-.003906 9.375 9.375 9.378907 24.574218.003907 33.949218l-124.460938 124.445313c-4.492188 4.519531-10.601562 7.050781-16.96875 7.035156zm0 0" /> </svg> ); WifiIcon.propTypes = { quality: PropTypes.number.isRequired }; export default WifiIcon;
src/components/footer/footer.js
jdaio/jdaio.github.io
/** * Footer Component * * @description Renders the global site footer. */ import React from 'react'; import { useStaticQuery, graphql } from 'gatsby'; import PropTypes from 'prop-types'; import Wrapper from '../wrapper/wrapper'; import style from './footer.module.scss'; function Footer({ id }) { /** * Get the site title and email address from Gatsby site config. */ const { site } = useStaticQuery( graphql` query siteFooter { site { siteMetadata { title social { email } source { provider url } } } } ` ); return ( <footer className={style.globalFooter} id={id}> <Wrapper> <div className={`${style.globalFooter__upper}`}> <div className={`${style.globalFooter__title}`}> Let&rsquo;s Talk <span className={`${style.globalFooter__titleHighlight}`} > . </span> <span className={`${style.globalFooter__titleIcon}`} role="img" aria-label="wave" > 👋 </span> </div> <div className={`${style.globalFooter__content}`}> <p> Want to work together? I&rsquo;m currently accepting new projects and can be reached at{' '} <a href={`mailto:${site.siteMetadata.social.email}?subject=Hello! 👋 Let's Work Together.`} title={`Shoot me an email at ${site.siteMetadata.social.email}.`} > {site.siteMetadata.social.email} </a> . </p> </div> </div> <div className={`${style.globalFooter__lower}`}> <p className={`${style.globalFooter__copyright}`}> &copy; {` ${new Date().getFullYear()} `} {site.siteMetadata.title} </p> <a className={`${style.globalFooter__sourceLink}`} href={site.siteMetadata.source.url} title={`View this site on ${site.siteMetadata.source.provider}`} target="_blank" rel="noopener noreferrer" > <span className={`${style.globalFooter__sourceLinkText}`} > Source on Github </span> <span className={`${style.globalFooter__sourceLinkIcon}`} > <svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" > <title>GitHub</title> <path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" /> </svg> </span> </a> </div> </Wrapper> </footer> ); } Footer.defaultProps = { id: 'footer', }; Footer.propTypes = { id: PropTypes.string, }; export default Footer;
app/app.js
CarlaCrandall/DoItNow
import React, { Component } from 'react'; import { addNavigationHelpers, NavigationActions } from 'react-navigation'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { BackAndroid, View } from 'react-native'; import * as actions from './actions'; import { AppContainerStyles } from './styles/containers'; import { AppNavigator } from './navigators'; export class App extends Component { componentDidMount() { BackAndroid.addEventListener('backPress', () => this.handleBackPress(this.props)); } componentWillReceiveProps({ navigation, SWIPEOUT_TASK }) { const currentRoute = this.props.navigation.currentRoute, nextRoute = navigation.currentRoute; // Close any open swipeout tasks when navigating if (currentRoute !== nextRoute && this.props.tasks.swipeoutTask) { SWIPEOUT_TASK(null); } } componentWillUnmount() { BackAndroid.removeEventListener('backPress'); } handleBackPress({ dispatch, navigation }) { // Close the app if no route to go back to if (navigation.index === 0) return false; dispatch(NavigationActions.back()); return true; } render() { const { dispatch, navigation, tasks, ...actionProps } = this.props, navigationHelpers = addNavigationHelpers({ state: navigation, dispatch }); return ( <View style={AppContainerStyles.container}> <AppNavigator screenProps={{ ...tasks, ...actionProps }} navigation={navigationHelpers} /> </View> ); } } const mapStateToProps = state => ({ navigation: state.navigation, tasks: state.tasks }), mapDispatchToProps = dispatch => ({ ...bindActionCreators(actions, dispatch), dispatch }); export default connect(mapStateToProps, mapDispatchToProps)(App);
src/containers/DevTools.js
879479119/Github-Mobile
import React from 'react' // 从redux-devtools中引入createDevTools import { createDevTools } from 'redux-devtools' // 显示包是单独的,要额外指定 import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' // 创建DevTools组件 const DevTools = createDevTools(( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q" > <LogMonitor theme="tomorrow" /> </DockMonitor> )) export default DevTools
views/containers/AppointmentsView.js
gvaldambrini/madam
import React from 'react'; import moment from 'moment'; import BaseAppointmentsView from './BaseAppointmentsView'; // The appointments main container used in the customers section. export default React.createClass({ propTypes: { params: React.PropTypes.shape({ id: React.PropTypes.string.isRequired }).isRequired }, editAppointmentPath: function(app) { const date = moment(app.date, config.date_format); if (app.planned) { return `/customers/edit/${this.props.params.id}/appointments/planned/${date.format('YYYY-MM-DD')}/${app.appid}`; } return `/customers/edit/${this.props.params.id}/appointments/edit/${app.appid}`; }, render: function() { return ( <BaseAppointmentsView {...this.props} newAppointmentPath={`/customers/edit/${this.props.params.id}/appointments/new`} editAppointmentPath={this.editAppointmentPath}/> ); } });
packages/containers/src/ComponentForm/fields/MultiSelect/MultiSelect.component.js
Talend/ui
import PropTypes from 'prop-types'; import React from 'react'; import MultiSelect from '@talend/react-components/lib/MultiSelect'; import Form from '@talend/react-forms'; const FieldTemplate = Form.UIForm.FieldTemplate; export default class MultiSelectField extends React.Component { constructor(props) { super(props); this.state = {}; this.onTrigger = this.onTrigger.bind(this); this.onTriggerResult = this.onTriggerResult.bind(this); this.onChange = this.onChange.bind(this); this.getTitleMap = this.getTitleMap.bind(this); } componentDidMount() { this.onTrigger({ type: 'didMount' }); } onTrigger(event) { Form.UIForm.callTrigger(event, { eventNames: [event.type], triggersDefinitions: this.props.schema.triggers, onTrigger: this.onTriggerResult, onLoading: isLoading => this.setState({ isLoading }), onResponse: data => this.setState(data), }); } onTriggerResult(event, trigger) { return this.props.onTrigger(event, { trigger, schema: this.props.schema, errors: this.props.errors, properties: this.props.properties, }); } onChange(event, selected) { const payload = { schema: { ...this.props.schema, titleMap: this.getTitleMap() }, value: selected, }; this.props.onChange(event, payload); this.props.onFinish(event, payload); } getTitleMap() { if (this.state.titleMap) { return this.state.titleMap; } const { titleMap } = this.props.schema; if (titleMap && Object.keys(titleMap).length > 0) { return titleMap; } const { value = [] } = this.props; const names = this.props.resolveName(value); return value.map((nextVal, index) => ({ name: names[index], value: nextVal, })); } getChildrenErrorMessage() { const { errors } = this.props.errors; if (!errors || errors.length === 0) { return undefined; } const key = this.props.schema.key.toString(); return Object.entries(errors) .filter(entry => entry[0].startsWith(key)) .map(entry => entry[1]) .join(', '); } render() { const { generateDescriptionId, generateErrorId } = Form.UIForm.Message.utils; const { id, isValid, errorMessage, schema } = this.props; const descriptionId = generateDescriptionId(id); const errorId = generateErrorId(id); const errorMsg = errorMessage || this.getChildrenErrorMessage(); const isDeepValid = isValid && !errorMsg; return ( <FieldTemplate description={schema.description} descriptionId={descriptionId} errorId={errorId} errorMessage={errorMsg} id={id} isValid={isDeepValid} label={schema.title} required={schema.required} > <MultiSelect id={id} autoFocus={schema.autoFocus} disabled={schema.disabled} required={schema.required} placeholder={schema.placeholder} readOnly={schema.readOnly} restricted={schema.restricted} onBlur={this.onTrigger} onChange={this.onChange} onFocus={this.onTrigger} options={this.getTitleMap()} selected={this.props.value} isLoading={this.state.isLoading} /> </FieldTemplate> ); } } if (process.env.NODE_ENV !== 'production') { MultiSelectField.propTypes = { id: PropTypes.string, isValid: PropTypes.bool, errorMessage: PropTypes.string, errors: PropTypes.object, onChange: PropTypes.func.isRequired, onFinish: PropTypes.func.isRequired, onTrigger: PropTypes.func.isRequired, properties: PropTypes.object, resolveName: PropTypes.func, schema: PropTypes.shape({ autoFocus: PropTypes.bool, description: PropTypes.string, disabled: PropTypes.bool, key: PropTypes.array, placeholder: PropTypes.string, readOnly: PropTypes.bool, required: PropTypes.bool, restricted: PropTypes.bool, title: PropTypes.string, titleMap: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string.isRequired, value: PropTypes.string.isRequired, }), ), triggers: PropTypes.arrayOf( PropTypes.shape({ onEvent: PropTypes.string, }), ), }), value: PropTypes.arrayOf(PropTypes.string), }; } MultiSelectField.defaultProps = { isValid: true, schema: {}, value: [], resolveName: value => value, };
src1/common/messageComponent/view/Message.react.js
Cron-J/CSV-REE
import React from 'react'; import * as MessageAction from '../actions/messageActions'; import NotificationSystem from 'react-notification-system'; import { Button, Modal } from 'react-bootstrap'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; class Message extends React.Component { constructor(props) { super(props); const { message, dispatch } = this.props; this.state = message; this.actions = bindActionCreators(MessageAction, dispatch); this._notificationSystem = null; this.style = { Containers: { DefaultStyle: { width: '60%' }, tc: { left: '20%', marginLeft: '20%' } } }; } componentDidMount() { this._notificationSystem = this.refs.notificationSystem; } componentWillReceiveProps(nextProps) { this.props = nextProps; if (!this.props.message.confirmation) { if (this.props.message.showmessages) { this._addNotification(); } else { this._removeNotification(); } } else { this._removeNotification(); } } _onConfirmation = () => { if (this.props.message.onSuccess !== null) { this.actions.execute(this.props.message.onSuccess(this.props.message.confirmationParameters)); } else { this._close(); } } _onConfirmationCancel = () => { if (this.props.message.onFailure !== null) { this.actions.execute(this.props.message.onFailure()); } this._close(); } _addNotification = () => { this._notificationSystem.addNotification({ message: this.props.message.message, title: this.props.message.title, position: 'tc', uid: this.props.message.messageType, autoDismiss: 3, onRemove: this._hidemessage, dismissible: true, level: this.props.message.messageType }); } _removeNotification = () => { this._notificationSystem.removeNotification(this.props.message.messageType); } _close = () => { this.actions.clear(); } _hidemessage = () => { this.actions.hidemessages(); } render() { return ( <div> <NotificationSystem ref="notificationSystem" style={this.style} /> <Modal show={this.props.message.confirmation}> <Modal.Header> <Modal.Title>{this.props.message.title}</Modal.Title> </Modal.Header> <Modal.Body> {this.props.message.message} </Modal.Body> <Modal.Footer> <Button bsStyle="primary" onClick={this._onConfirmation}>Yes</Button> <Button onClick={this._onConfirmationCancel}>No</Button> </Modal.Footer> </Modal> </div> ); } } function mapStateToProps(state) { const { message } = state; return { message }; } Message.propTypes = { message: React.PropTypes.object, dispatch: React.PropTypes.func.isRequired }; export default connect(mapStateToProps)(Message);
src/svg-icons/action/chrome-reader-mode.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionChromeReaderMode = (props) => ( <SvgIcon {...props}> <path d="M13 12h7v1.5h-7zm0-2.5h7V11h-7zm0 5h7V16h-7zM21 4H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 15h-9V6h9v13z"/> </SvgIcon> ); ActionChromeReaderMode = pure(ActionChromeReaderMode); ActionChromeReaderMode.displayName = 'ActionChromeReaderMode'; ActionChromeReaderMode.muiName = 'SvgIcon'; export default ActionChromeReaderMode;
src/client/components/devtools-cursore/index.js
kevinhikaruevans/uojs2
import React, { Component } from 'react'; import style from './style' class DevtoolsCursore extends Component { static displayName = '[component] devtools-cursore'; state = { x : 150, y : 150, cursor : 'default', list : [ 'col-resize', 'default', 'help', 'move', 'nesw-resize', 'not-allowed', 'nwse-resize', 'pen', 'row-resize', 'target', 'text', 'wait', 'war-mode' ] }; onMouseMove = (e) => { const offset = { left : e.currentTarget.offsetLeft + 200, top : e.currentTarget.offsetTop }; this.setState({ x : e.clientX - offset.left, y : e.clientY - offset.top }); }; onClick = (cursor) => (e) => { e.preventDefault(); this.setState({ cursor }) }; render() { return( <div className={style['devtools-cursore']}> <div className={style['devtools-cursore__list']}> {this.state.list.map((item, index) => { return <div key={index} className={style['devtools-cursore__list-item']} data-cursor={item} data-selected={this.state.cursor === item} onClick={this.onClick(item)} /> })} </div> <div className={style['devtools-cursore__canvas']} data-cursor={this.state.cursor} onMouseMove={this.onMouseMove}> <div className={style['devtools-cursore__cross']} style={{ left : `${this.state.x}px`, top : `${this.state.y}px` }} /> </div> </div> ) } } export { DevtoolsCursore as default, style };
test/helpers/shallowRenderHelper.js
js-for-fun/wishcorn-frontend
/** * 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(); }
app/jsx/outcomes/OutcomeAlignmentDeleteLink.js
djbender/canvas-lms
/* * Copyright (C) 2015 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import PropTypes from 'prop-types' import I18n from 'i18n!OutcomeAlignmentDeleteLink' import $ from 'jquery' class OutcomeAlignmentDeleteLink extends React.Component { static propTypes = { url: PropTypes.string.isRequired, has_rubric_association: PropTypes.string } static defaultProps = { has_rubric_association: null } handleClick = e => { const $li = $(e.target).parents('li.alignment') e.preventDefault() $(e.target).confirmDelete({ success() { $li.fadeOut('slow', function() { this.remove() }) }, url: this.props.url }) } hasRubricAssociation() { return this.props.has_rubric_association } render() { if (this.hasRubricAssociation()) { return ( <span className="locked_alignment_link"> <i className="icon-lock" aria-hidden="true" /> <span className="screenreader-only"> {' '} {I18n.t(` Can't delete alignments based on rubric associations. To remove these associations you need to remove the row from the asset's rubric" `)}{' '} </span> </span> ) } return ( // eslint-disable-next-line jsx-a11y/anchor-is-valid <a className="delete_alignment_link no-hover" href="" onClick={this.handleClick}> <i className="icon-end" aria-hidden="true" /> <span className="screenreader-only">{I18n.t('Delete alignment')}</span> </a> ) } } export default OutcomeAlignmentDeleteLink
src/svg-icons/av/videocam.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvVideocam = (props) => ( <SvgIcon {...props}> <path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/> </SvgIcon> ); AvVideocam = pure(AvVideocam); AvVideocam.displayName = 'AvVideocam'; AvVideocam.muiName = 'SvgIcon'; export default AvVideocam;
src/containers/SearchView/FilterView.js
JamesJin038801/CampID
import { Text, View, Platform, Image, ScrollView, StyleSheet } from 'react-native'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import I18n from 'react-native-i18n'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import NavigationBar from 'react-native-navbar'; import { setHomeTab } from '@actions/globals'; import { openDrawer } from '@actions/drawer'; import { replaceRoute, popRoute, pushNewRoute } from '@actions/route'; import Constants from '@src/constants'; import { Metrics, Styles, Colors, Fonts, Icon, Images } from '@theme/'; import styles from './styles'; import CommonWidgets from '@components/CommonWidgets'; import ScrollableTabView, { DefaultTabBar } from 'react-native-scrollable-tab-view'; import SearchBar from 'react-native-searchbar'; import SearchCell from '@components/SearchView/SearchCell'; import Collapsible from '@components/Collapsible/Collapsible'; import Accordion from '@components/Collapsible/Accordion'; const SECTIONS = [ { title: 'First', content: 'Lorem ipsum...', }, ]; class FilterView extends Component { _renderHeader(section) { return ( CommonWidgets.renderFilterHeader(Images.imgLeftBtn, section.title, Images.imgRightBtn) ); } _renderContent(section) { return ( <View style={styles1.content}> <Text>{section.content}</Text> </View> ); } constructor(props) { super(props); } render() { return ( <View style={{ flex: 1, backgroundColor: 'white' }}> { CommonWidgets.renderStatusBar(Colors.brandPrimary) } <NavigationBar style={Styles.navBarStyle} title={CommonWidgets.renderNavBarHeader(I18n.t('FILTER'))} tintColor={Colors.brandSecondary} leftButton={CommonWidgets.renderNavBarLeftButton(() => this.props.popRoute())} rightButton={(<View style={{ flexDirection: 'row', justifyContent: 'space-around' }}> {CommonWidgets.renderRightButton(I18n.t('CLEAR'), { color: Colors.textSecondary }, null)} </View>)} /> {CommonWidgets.renderSpacer(100)} <Accordion sections={SECTIONS} underlayColor='transparent' renderHeader={this._renderHeader} renderContent={this._renderContent} /> {/*<View style={Styles.center}> {CommonWidgets.renderMaterialButton('Apply', Colors.brandPrimary, null)} </View>*/} </View> ); } } FilterView.propTypes = { dispatch: React.PropTypes.func.isRequired, setHomeTab: React.PropTypes.func.isRequired, replaceRoute: React.PropTypes.func.isRequired, openDrawer: React.PropTypes.func.isRequired, popRoute: React.PropTypes.func.isRequired, pushNewRoute: React.PropTypes.func.isRequired, }; function mapDispatchToProps(dispatch) { return { dispatch, setHomeTab: homeTab => dispatch(setHomeTab(homeTab)), openDrawer: () => dispatch(openDrawer()), replaceRoute: route => dispatch(replaceRoute(route)), pushNewRoute: route => dispatch(pushNewRoute(route)), popRoute: () => dispatch(popRoute()), }; } function mapStateToProps(state) { const globals = state.get('globals'); return { globals }; } export default connect(mapStateToProps, mapDispatchToProps)(FilterView); const styles1 = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', backgroundColor: '#F5FCFF', }, title: { textAlign: 'center', fontSize: 22, fontWeight: '300', marginBottom: 20, }, header: { backgroundColor: '#F5FCFF', padding: 10, }, headerText: { textAlign: 'center', fontSize: 16, fontWeight: '500', }, content: { padding: 20, backgroundColor: '#fff', }, active: { backgroundColor: 'rgba(255,255,255,1)', }, inactive: { backgroundColor: 'rgba(245,252,255,1)', }, selectors: { marginBottom: 10, flexDirection: 'row', justifyContent: 'center', }, selector: { backgroundColor: '#F5FCFF', padding: 10, }, activeSelector: { fontWeight: 'bold', }, selectTitle: { fontSize: 14, fontWeight: '500', padding: 10, }, });
redux-weather-forecast/src/index.js
andreassiegel/react-redux
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import ReduxPromise from 'redux-promise'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
frontend/src/components/slidez/Arrows.js
viewportvr/daysinvr
import React from 'react'; import './Slideshow.css'; const Arrows = function(props) { return ( <div className="arrows"> <span onClick={props.decreaseCount} className="arrow btn-arrow btn-arrow-left" /> <span onClick={props.increaseCount} className="arrow btn-arrow btn-arrow-right" /> </div> ); }; export default Arrows;
app/components/ToggleOption/index.js
likesalmon/likesalmon-react-boilerplate
/** * * ToggleOption * */ import React from 'react'; import { injectIntl, intlShape } from 'react-intl'; const ToggleOption = ({ value, message, intl }) => ( <option value={value}> {message ? intl.formatMessage(message) : value} </option> ); ToggleOption.propTypes = { value: React.PropTypes.string.isRequired, message: React.PropTypes.object, intl: intlShape.isRequired, }; export default injectIntl(ToggleOption);
src/index.js
bogdanovroman/booklist-redux
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import configureStore from './store/configureStore'; import App from './components/app'; const store = configureStore(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
examples/with-url-object-routing/pages/index.js
dizlexik/next.js
import React from 'react' import Link from 'next/link' const href = { pathname: '/about', query: { name: 'next' } } const as = { pathname: '/about/next', hash: 'title-1' } export default () => ( <div> <h1>Home page</h1> <Link href={href} as={as}> <a>Go to /about/next</a> </Link> </div> )
app/javascript/mastodon/features/list_editor/components/account.js
kirakiratter/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { makeGetAccount } from '../../../selectors'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import IconButton from '../../../components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import { removeFromListEditor, addToListEditor } from '../../../actions/lists'; const messages = defineMessages({ remove: { id: 'lists.account.remove', defaultMessage: 'Remove from list' }, add: { id: 'lists.account.add', defaultMessage: 'Add to list' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, { accountId, added }) => ({ account: getAccount(state, accountId), added: typeof added === 'undefined' ? state.getIn(['listEditor', 'accounts', 'items']).includes(accountId) : added, }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { accountId }) => ({ onRemove: () => dispatch(removeFromListEditor(accountId)), onAdd: () => dispatch(addToListEditor(accountId)), }); export default @connect(makeMapStateToProps, mapDispatchToProps) @injectIntl class Account extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, intl: PropTypes.object.isRequired, onRemove: PropTypes.func.isRequired, onAdd: PropTypes.func.isRequired, added: PropTypes.bool, }; static defaultProps = { added: false, }; render () { const { account, intl, onRemove, onAdd, added } = this.props; let button; if (added) { button = <IconButton icon='times' title={intl.formatMessage(messages.remove)} onClick={onRemove} />; } else { button = <IconButton icon='plus' title={intl.formatMessage(messages.add)} onClick={onAdd} />; } return ( <div className='account'> <div className='account__wrapper'> <div className='account__display-name'> <div className='account__avatar-wrapper'><Avatar account={account} size={36} /></div> <DisplayName account={account} /> </div> <div className='account__relationship'> {button} </div> </div> </div> ); } }
app/containers/Header/index.js
gitlab-classroom/classroom-web
/* * * Header * */ import React from 'react'; import { connect } from 'react-redux'; import selectHeader from './selectors'; import AppBar from 'material-ui/AppBar'; import styled from 'styled-components'; const AppBarContainer = styled.div` position: fixed; left: 0; top: 0; right: 0; zIndex: 10; `; export class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { appbarArgs: React.PropTypes.object, } render() { const { appbarArgs } = this.props; if (appbarArgs.hide) { return null; } return <AppBarContainer><AppBar {...appbarArgs} /></AppBarContainer>; } } const mapStateToProps = selectHeader(); function mapDispatchToProps(dispatch) { return { dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(Header);
lib/component-library-slides/DevEnvironment.js
RallySoftware/rally-present
import React from 'react'; const imgSrc = require('./images/kitt.gif'); export default class Slide extends React.Component { render() { return ( <div> <h1>Use a separate environment for development</h1> <img src={ imgSrc } /> </div> ); } }
src/components/common/svg-icons/navigation/more-horiz.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationMoreHoriz = (props) => ( <SvgIcon {...props}> <path d="M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); NavigationMoreHoriz = pure(NavigationMoreHoriz); NavigationMoreHoriz.displayName = 'NavigationMoreHoriz'; NavigationMoreHoriz.muiName = 'SvgIcon'; export default NavigationMoreHoriz;
packages/mineral-ui-icons/src/IconBrightness2.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconBrightness2(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M10 2c-1.82 0-3.53.5-5 1.35C7.99 5.08 10 8.3 10 12s-2.01 6.92-5 8.65C6.47 21.5 8.18 22 10 22c5.52 0 10-4.48 10-10S15.52 2 10 2z"/> </g> </Icon> ); } IconBrightness2.displayName = 'IconBrightness2'; IconBrightness2.category = 'image';
src/AddTask.js
mikadamsterdam/react_for_project
import React from 'react'; import jQuery from 'jquery'; class AddTask extends React.Component { onSubmit(event){ // if we don't call event.preventDefault, the browser will think we want to submit the form event.preventDefault(); this.props.onSubmit(this.refs.newTask.value, this.refs.newDescription.value); } createTask(event){ event.preventDefault(); let component = this; let title = this.refs.newTask.value; let description = this.refs.newDescription.value; let newTask = { id: null, title: title, description: description, status: false }; jQuery.ajax({ type: "POST", url: "https://taskpool.herokuapp.com/projects/1/task.json", data: JSON.stringify({ task: newTask }), contentType: "application/json", dataType: "json" }) .done(function(data) { component.refs.newTask.value = ""; component.refs.newDescription.value = ""; component.props.onChange(); }) .fail(function(error) { console.log(error); }); } render() { return ( <form onSubmit={this.createTask.bind(this)}> <input ref="newTask" placeholder="Title of the task" /> <input ref="newDescription" placeholder="Description of the task" /> <button>Add Task</button> </form> ); } } export default AddTask;
src/client.js
leviluo/oneToone
import React from 'react' import ReactDOM from 'react-dom' import createBrowserHistory from 'history/lib/createBrowserHistory' import { useRouterHistory, match } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import createStore from './store/createStore' import AppContainer from './containers/AppContainer' import layout from '../config/layout' // ======================================================== // Browser History Setup // ======================================================== const browserHistory = useRouterHistory(createBrowserHistory)({ basename: __BASENAME__ }) // ======================================================== // Store and History Instantiation // ======================================================== // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the routerKey "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.___INITIAL_STATE__ const store = createStore(initialState, browserHistory) const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: (state) => state.router }) // ======================================================== // Developer Tools Setup // ======================================================== if (0 && __DEBUG__) { if (window.devToolsExtension) { window.devToolsExtension.open() } } // ======================================================== // Render Setup // ======================================================== const MOUNT_NODE = document.getElementById('root') let render = (routerKey = null) => { const routes = require('./routes/index').default(store) match({ history, routes }, (error, redirectLocation, renderProps) => { // todo: Error handling should be improved if (error) { console.log(error) return } ReactDOM.render( <AppContainer {...renderProps} store={store} history={history} routes={routes} routerKey={routerKey} layout={{...layout, ...(window.___LAYOUT__ || {})}} />, MOUNT_NODE ) }) } // Enable HMR and catch runtime errors in RedBox // This code is excluded from production bundle if (__DEV__ && module.hot) { const renderApp = render const renderError = (error) => { const RedBox = require('redbox-react').default ReactDOM.render(<RedBox error={error} />, MOUNT_NODE) } render = () => { try { renderApp(Math.random()) } catch (error) { renderError(error) } } module.hot.accept(['./routes/index'], () => render()) } // ======================================================== // Go! // ======================================================== render()
renderer/components/header.js
trainto/Catalogger
'use strict'; import React from 'react'; import {Button, Glyphicon, form, Checkbox, Dropdown, MenuItem, Badge} from 'react-bootstrap'; import {dispatcher} from '../dispatcher'; import './styles/header.css'; class Header extends React.Component { constructor(props) { super(props); this.state = { isStarted: false, isLoading: false, selectedDevice: undefined, textForDeviceDropdown: 'No devices', deviceList: [], rows: 0 }; } _createDeviceList(event) { if (event === true) { dispatcher.getDevices((devices) => { if (devices && devices.length !== 0) { this.setState({ textForDeviceDropdown: 'Select a device' }); let items = []; for (let i = 0; i < devices.length; i++) { items.push(<MenuItem eventKey={i}>{devices[i]}</MenuItem>); } this.setState({ deviceList: items }); } else { this.setState({ selectedDevice: undefined, textForDeviceDropdown: 'No devices', deviceList: [] }); } }); } } _selectDevice(selected) { let device = this.state.deviceList[selected].props.children; this.setState({ selectedDevice: device }); dispatcher.focusToLogTable(); } getSelectedDevice() { return this.state.selectedDevice; } setRowsNumber(rowsNumber) { this.setState({ rows: rowsNumber }); } render() { let isStarted = this.state.isStarted; let isLoading = this.state.isLoading; return ( <div id="header" onDoubleClick={dispatcher.onDoubleClickHeader}> <div id="command-buttons" style={process.platform === 'darwin' ? {top: '25px'} : undefined} onDoubleClick={(event) => {event.preventDefault();}}> <Button onClick={dispatcher.onClickClear}> <Glyphicon glyph="trash"/> </Button> <Button onClick={dispatcher.onClickStartStop} disabled={isLoading}> {isLoading ? <Glyphicon glyph="hourglass"/> : (isStarted ? <Glyphicon bsSize="large"glyph="stop"/> : <Glyphicon glyph="play"/>)} </Button> <Dropdown id="dropdown-devices" disabled={isStarted} onToggle={(event) => this._createDeviceList(event)} onSelect={(event) => this._selectDevice(event)}> <Dropdown.Toggle> {this.state.selectedDevice ? this.state.selectedDevice : this.state.textForDeviceDropdown} </Dropdown.Toggle> <Dropdown.Menu> {[this.state.deviceList]} </Dropdown.Menu> </Dropdown> </div> <div id="autoscroll"> <form> <Checkbox onChange={dispatcher.onAutoscrollChanged}> Auto scroll </Checkbox> </form> </div> <div id="status-bar"> <p>rows: <Badge>{this.state.rows}</Badge></p> </div> </div> ); } } export default Header;
example/src/server/index.js
tizmagik/react-csjs
import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import App from '../components/App'; import { getStyle } from 'react-csjs'; const server = express(); const clientAssets = require(KYT.ASSETS_MANIFEST); server.use(express.static(path.join(process.cwd(), KYT.PUBLIC_DIR))); // Render the app const renderedApp = ReactDOM.renderToString(<App />); // Gather the generated CSS const renderedStyles = getStyle(); server.get('/', (req, res) => { res.send(` <html> <head> <style id="ssr-styles">${renderedStyles}</style> <title>react-csjs example app</title> </head> <body> <div id="root">${renderedApp}</div> <script src="${clientAssets.main.js}"></script> </body> </html> `); }); server.listen(parseInt(KYT.SERVER_PORT, 10));
src/highOrderComponents/Redux.js
lapanoid/redux-as-component
import React, { Component } from 'react'; import R from 'ramda'; import _ReduxOptions from './ReduxOptions'; import _ReduxHolder from './ReduxHolder'; export default R.curry((callbacksSelectorsMap, changedPropKeyAcMap, methodsMap, createReduxFunc, reduxOptions, _Component)=>{ const ReduxHolder = _ReduxHolder(createReduxFunc, _Component); const ReduxOptions = _ReduxOptions(callbacksSelectorsMap, changedPropKeyAcMap, methodsMap, reduxOptions, ReduxHolder); return ReduxOptions; })
src/components/cards/left-container/sidebar-header.js
vFujin/HearthLounge
import React from 'react'; import _ from 'lodash'; import Button from "../../buttons/button"; const SidebarHeader = ({filters, inExtensions, inDeckCreation, handleFilterViewToggle, handleFilterReset}) =>{ return ( <h3 className="sidebar__header"> Filters <div> {!_.isEmpty(filters) &&<Button handleClick={handleFilterReset} type="default--active" dataAttr="clearAll" text="Clear filters"/>} {(inExtensions || inDeckCreation) && <Button handleClick={handleFilterViewToggle} type="default--active" text="Hide filters" />} </div> </h3> ) }; export default SidebarHeader;
Example/DynamicExample.js
skv-headless/react-native-scrollable-tab-view
import React from 'react'; import { Text, TouchableHighlight, } from 'react-native'; import TimerMixin from 'react-timer-mixin'; import ScrollableTabView, { ScrollableTabBar, } from 'react-native-scrollable-tab-view'; import createReactClass from 'create-react-class'; const Child = createReactClass({ onEnter() { console.log('enter: ' + this.props.i); // eslint-disable-line no-console }, onLeave() { console.log('leave: ' + this.props.i); // eslint-disable-line no-console }, render() { const i = this.props.i; return <Text key={i}>{`tab${i}`}</Text>; }, }); export default createReactClass({ mixins: [TimerMixin, ], children: [], getInitialState() { return { tabs: [1, 2], }; }, componentDidMount() { this.setTimeout( () => { this.setState({ tabs: [1, 2, 3, 4, 5, 6, ], }); }, 100 ); }, handleChangeTab({i, ref, from, }) { this.children[i].onEnter(); this.children[from].onLeave(); }, renderTab(name, page, isTabActive, onPressHandler, onLayoutHandler) { return <TouchableHighlight key={`${name}_${page}`} onPress={() => onPressHandler(page)} onLayout={onLayoutHandler} style={{flex: 1, width: 100, }} underlayColor="#aaaaaa" > <Text>{name}</Text> </TouchableHighlight>; }, render() { return <ScrollableTabView style={{marginTop: 20, }} renderTabBar={() => <ScrollableTabBar renderTab={this.renderTab}/>} onChangeTab={this.handleChangeTab} > {this.state.tabs.map((tab, i) => { return <Child ref={(ref) => (this.children[i] = ref)} tabLabel={`tab${i}`} i={i} key={i} />; })} </ScrollableTabView>; }, });
docs/src/app/components/pages/discover-more/RelatedProjects.js
nathanmarks/material-ui
import React from 'react'; import Title from 'react-title-component'; import MarkdownElement from '../../MarkdownElement'; import relatedProjectsText from './related-projects.md'; const RelatedProjects = () => ( <div> <Title render={(previousTitle) => `Related Projects - ${previousTitle}`} /> <MarkdownElement text={relatedProjectsText} /> </div> ); export default RelatedProjects;
src/js/Components/Score/Team.js
gabsprates/facomp-quiz
import React, { Component } from 'react'; export default function Team(props) { return ( <div className={`team ${props.team}`}> <span className='score'> { props.score } </span> </div> ); }
packages/stockflux-container/src/index.js
ScottLogic/StockFlux
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
node_modules/react-router/es/Router.js
chenjic215/search-doctor
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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import warning from 'warning'; import invariant from 'invariant'; import React from 'react'; import PropTypes from 'prop-types'; /** * The public API for putting history on context. */ var Router = function (_React$Component) { _inherits(Router, _React$Component); function Router() { var _temp, _this, _ret; _classCallCheck(this, Router); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = { match: _this.computeMatch(_this.props.history.location.pathname) }, _temp), _possibleConstructorReturn(_this, _ret); } Router.prototype.getChildContext = function getChildContext() { return { router: _extends({}, this.context.router, { history: this.props.history, route: { location: this.props.history.location, match: this.state.match } }) }; }; Router.prototype.computeMatch = function computeMatch(pathname) { return { path: '/', url: '/', params: {}, isExact: pathname === '/' }; }; Router.prototype.componentWillMount = function componentWillMount() { var _this2 = this; var _props = this.props, children = _props.children, history = _props.history; invariant(children == null || React.Children.count(children) === 1, 'A <Router> may have only one child element'); // Do this here so we can setState when a <Redirect> changes the // location in componentWillMount. This happens e.g. when doing // server rendering using a <StaticRouter>. this.unlisten = history.listen(function () { _this2.setState({ match: _this2.computeMatch(history.location.pathname) }); }); }; Router.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { warning(this.props.history === nextProps.history, 'You cannot change <Router history>'); }; Router.prototype.componentWillUnmount = function componentWillUnmount() { this.unlisten(); }; Router.prototype.render = function render() { var children = this.props.children; return children ? React.Children.only(children) : null; }; return Router; }(React.Component); Router.propTypes = { history: PropTypes.object.isRequired, children: PropTypes.node }; Router.contextTypes = { router: PropTypes.object }; Router.childContextTypes = { router: PropTypes.object.isRequired }; export default Router;
src/parser/hunter/beastmastery/modules/talents/KillerInstinct.js
FaideWW/WoWAnalyzer
import React from 'react'; import SpellLink from 'common/SpellLink'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import StatisticListBoxItem from 'interface/others/StatisticListBoxItem'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import SPELLS from 'common/SPELLS'; import Analyzer from 'parser/core/Analyzer'; import { formatNumber } from 'common/format'; const KILLER_INSTINCT_TRESHOLD = 0.35; const KILLER_INSTINCT_CONTRIBUTION = 0.5; /** * Kill Command deals 50% increased damage against enemies below 35% health. * * Example log: https://www.warcraftlogs.com/reports/CznQpdmRFBJkjg4w/#fight=40&source=16&type=damage-done */ class KillerInstinct extends Analyzer { casts = 0; castsWithExecute = 0; damage = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.KILLER_INSTINCT_TALENT.id); } on_byPlayerPet_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.KILL_COMMAND_PET.id) { return; } this.casts++; const enemyHealthPercent = (event.hitPoints / event.maxHitPoints); if (enemyHealthPercent <= KILLER_INSTINCT_TRESHOLD) { this.castsWithExecute++; const traitDamage = calculateEffectiveDamage(event, KILLER_INSTINCT_CONTRIBUTION); this.damage += traitDamage; } } statistic() { return ( <TalentStatisticBox talent={SPELLS.KILLER_INSTINCT_TALENT.id} value={<>{formatNumber(this.castsWithExecute)} casts at &lt;35% health</>} tooltip={`You cast a total of ${this.casts} Kill Commands, of which ${this.castsWithExecute} were on enemies with less than 35% of their health remaining. These ${this.castsWithExecute} casts provided you a total of ${formatNumber(this.damage)} extra damage throughout the fight.`} /> ); } subStatistic() { return ( <StatisticListBoxItem title={<SpellLink id={SPELLS.KILLER_INSTINCT_TALENT.id} />} value={<ItemDamageDone amount={this.damage} />} /> ); } } export default KillerInstinct;
src/containers/search_bar.js
dushyant/ReactWeatherApp
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchWeather } from '../actions/index'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: ''}; this.onInputChange = this.onInputChange.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); } onInputChange(e) { this.setState({ term: e.target.value}); } onFormSubmit(e) { e.preventDefault(); // fetch weather data this.props.fetchWeather(this.state.term); // set search term to empty string this.setState({ term: '' }); } render() { return ( <form onSubmit={this.onFormSubmit} className="input-group"> <input placeholder="Enter city name" className="form-control" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Submit</button> </span> </form> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar);
docs/app/Examples/views/Comment/Content/CommentExampleAvatar.js
vageeshb/Semantic-UI-React
import React from 'react' import { Comment } from 'semantic-ui-react' const CommentExampleAvatar = () => ( <Comment.Group> <Comment> <Comment.Avatar src='http://semantic-ui.com/images/avatar/small/elliot.jpg' /> <Comment.Content> <Comment.Author as='a'>Elliot Fu</Comment.Author> </Comment.Content> </Comment> </Comment.Group> ) export default CommentExampleAvatar
src/packages/@ncigdc/modern_components/DownloadClinicalButton/DownloadClinicalButton.js
NCI-GDC/portal-ui
/* @flow */ import React from 'react'; import { compose, withState } from 'recompose'; import DownloadButton from '@ncigdc/components/DownloadButton'; import { makeFilter } from '@ncigdc/utils/filters'; import Dropdown from '@ncigdc/uikit/Dropdown'; import DownloadIcon from '@ncigdc/theme/icons/Download'; import Spinner from '@ncigdc/theme/icons/Spinner'; import Button from '@ncigdc/uikit/Button'; import timestamp from '@ncigdc/utils/timestamp'; import { withTheme, theme } from '@ncigdc/theme'; const styles = { dropdownContainer: { top: '100%', whiteSpace: 'nowrap', marginTop: '2px', minWidth: '90px', left: '0', }, common: theme => ({ backgroundColor: 'transparent', color: theme.greyScale2, justifyContent: 'flex-start', ':hover': { backgroundColor: theme.greyScale6, }, }), button: theme => ({ borderRadius: '0px', marginLeft: '0px', ...styles.common(theme), '[disabled]': styles.common(theme), }), }; export default compose( withState('state', 'setState', { tsvDownloading: false, jsonDownloading: false, }), withTheme, )( ({ isLoading, dropdownStyle, active, state, setState, projectId, viewer, button, }) => { const projectFilter = [ { field: 'cases.project.project_id', value: projectId, }, ]; const dataExportFilters = makeFilter(projectFilter); const clinicalCount = viewer.repository.cases.hits.total; return ( <Dropdown button={ <Button leftIcon={isLoading ? <Spinner /> : <DownloadIcon />}> {state.jsonDownloading || state.tsvDownloading ? 'Processing' : 'Clinical'} </Button> } dropdownStyle={styles.dropdownContainer} > <DownloadButton className="data-download-clinical-tsv" disabled={!clinicalCount} size={clinicalCount} style={styles.button(theme)} endpoint="/clinical_tar" format={'TSV'} activeText="Processing" inactiveText="TSV" altMessage={false} setParentState={currentState => setState(s => ({ ...s, tsvDownloading: currentState, }))} active={state.tsvDownloading} filters={dataExportFilters} filename={`clinical.project-${projectId}.${timestamp()}.tar.gz`} /> <DownloadButton className="data-download-clinical" disabled={!clinicalCount} size={clinicalCount} style={styles.button(theme)} endpoint="/cases" activeText="Processing" inactiveText="JSON" altMessage={false} setParentState={currentState => setState(s => ({ ...s, jsonDownloading: currentState, }))} active={state.jsonDownloading} filters={dataExportFilters} fields={['case_id']} dataExportExpands={[ 'demographic', 'diagnoses', 'diagnoses.treatments', 'family_histories', 'exposures', ]} filename={`clinical.project-${projectId}.${timestamp()}.json`} /> </Dropdown> ); }, );
node_modules/react-bootstrap/es/PaginationButton.js
cmccandless/SolRFrontEnd
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; // TODO: This should be `<Pagination.Item>`. // TODO: This should use `componentClass` like other components. var propTypes = { componentClass: elementType, className: React.PropTypes.string, eventKey: React.PropTypes.any, onSelect: React.PropTypes.func, disabled: React.PropTypes.bool, active: React.PropTypes.bool, onClick: React.PropTypes.func }; var defaultProps = { componentClass: SafeAnchor, active: false, disabled: false }; var PaginationButton = function (_React$Component) { _inherits(PaginationButton, _React$Component); function PaginationButton(props, context) { _classCallCheck(this, PaginationButton); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } PaginationButton.prototype.handleClick = function handleClick(event) { var _props = this.props, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; PaginationButton.prototype.render = function render() { var _props2 = this.props, Component = _props2.componentClass, active = _props2.active, disabled = _props2.disabled, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = _objectWithoutProperties(_props2, ['componentClass', 'active', 'disabled', 'onClick', 'className', 'style']); if (Component === SafeAnchor) { // Assume that custom components want `eventKey`. delete props.eventKey; } delete props.onSelect; return React.createElement( 'li', { className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(Component, _extends({}, props, { disabled: disabled, onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return PaginationButton; }(React.Component); PaginationButton.propTypes = propTypes; PaginationButton.defaultProps = defaultProps; export default PaginationButton;
packages/react-router-native/examples/RouteConfig.js
d-oliveros/react-router
import React from 'react' import { StyleSheet, Text, AppRegistry, View } from 'react-native' import { NativeRouter, Route, Link } from 'react-router-native' // Some folks find value in a centralized route config. // A route config is just data. React is great at mapping // data into components, and <Route> is a component. //////////////////////////////////////////////////////////// // first our route components const Main = () => <Text style={styles.header}>Main</Text> const Sandwiches = () => <Text style={styles.header}>Sandwiches</Text> const Tacos = ({ routes }) => ( <View> <Text style={styles.header}>Tacos</Text> <View style={styles.nav}> <Link to="/tacos/bus" style={styles.navItem} underlayColor='#f0f4f7'> <Text>Bus</Text> </Link> <Link to="/tacos/cart" style={styles.navItem} underlayColor='#f0f4f7'> <Text>Cart</Text> </Link> </View> {routes.map((route, i) => ( <RouteWithSubRoutes key={i} {...route}/> ))} </View> ) const Bus = () => <Text style={styles.subHeader}>Bus</Text> const Cart = () => <Text style={styles.subHeader}>Cart</Text> //////////////////////////////////////////////////////////// // then our route config const routes = [ { path: '/sandwiches', component: Sandwiches }, { path: '/tacos', component: Tacos, routes: [ { path: '/tacos/bus', component: Bus }, { path: '/tacos/cart', component: Cart } ] } ] // wrap <Route> and use this everywhere instead, then when // sub routes are added to any route it'll work const RouteWithSubRoutes = (route) => ( <Route path={route.path} render={props => ( // pass the sub-routes down to keep nesting <route.component {...props} routes={route.routes}/> )}/> ) const RouteConfig = () => ( <NativeRouter> <View style={styles.container}> <View style={styles.nav}> <Link to="/tacos" underlayColor='#f0f4f7' style={styles.navItem}> <Text>Tacos</Text> </Link> <Link to="/sandwiches" underlayColor='#f0f4f7' style={styles.navItem}> <Text>Sandwiches</Text> </Link> </View> {routes.map((route, i) => ( <RouteWithSubRoutes key={i} {...route}/> ))} </View> </NativeRouter> ) const styles = StyleSheet.create({ container: { marginTop: 25, padding: 10, }, header: { fontSize: 20, }, nav: { flexDirection: 'row', justifyContent: 'space-around' }, navItem: { flex: 1, alignItems: 'center', padding: 10, }, subHeader: { fontSize: 15 } }) export default RouteConfig
src/svg-icons/notification/phone-paused.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPhonePaused = (props) => ( <SvgIcon {...props}> <path d="M17 3h-2v7h2V3zm3 12.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 3v7h2V3h-2z"/> </SvgIcon> ); NotificationPhonePaused = pure(NotificationPhonePaused); NotificationPhonePaused.displayName = 'NotificationPhonePaused'; NotificationPhonePaused.muiName = 'SvgIcon'; export default NotificationPhonePaused;
src/components/Overdrive/index.js
KNETIC-KRPF/KNETIC-CLIENT
import React, { Component } from 'react'; import Knob from '../Knob'; import RockerSwitch from '../RockerSwitch'; import './Overdrive.css'; class Overdrive extends Component { constructor(props) { super(props) this.state = { isToggleOn: false } this.handleClick = this.handleClick.bind(this) } handleClick() { this.setState(prevState => ({ isToggleOn: !prevState.isToggleOn })); } render() { const efxProp = this.props.patch.effectBus; const findOverdrive = efx => efx.type === "overdrive"; const overdrive = efxProp.find(findOverdrive); const overdriveComponent = ( <div className="overdrive-grid"> <div className="controller"> <Knob patchState={overdrive.drive} sendDispatch={this.props.sendDispatch} type="overdrive" property="drive" min={0} max={1} step={0.1} /> <label htmlFor="overdrive-control">DRIVE</label> </div> <div className="controller"> <Knob patchState={overdrive.outputGain} sendDispatch={this.props.sendDispatch} type="overdrive" property="output_gain" min={0} max={1} step={0.1} /> <label htmlFor="overdrive-control">GAIN</label> </div> <div className="controller"> <Knob patchState={overdrive.curveAmount} sendDispatch={this.props.sendDispatch} type="overdrive" property="curve_amount" min={0} max={1} step={0.1} /> <label htmlFor="overdrive-control">CURVE AMOUNT</label> </div> <div className="controller"> <Knob patchState={overdrive.algorithmIndex} sendDispatch={this.props.sendDispatch} type="overdrive" property="algorithm_index" min={0} max={5} step={1} /> <label htmlFor="overdrive-control">ALGORITHM INDEX</label> </div> {/*<div className="controller"> <Knob patchState={overdrive.bypass} sendDispatch={this.props.sendDispatch} type="overdrive" property="bypass" min={0} max={1} step={1} /> <label htmlFor="overdrive-control">BYPASS</label> </div>*/} </div> ); return( <div> <div className="bypass-container"> <h4 className="expand-efx" onClick={this.handleClick}>OVERDRIVE<span className="arrow-down"></span></h4> <RockerSwitch patchState={overdrive.bypass} sendDispatch={this.props.sendDispatch} type="overdrive" property="bypass" name={overdrive.type} /> </div> {this.state.isToggleOn && overdriveComponent} <hr/> </div> ); } } export default Overdrive;
src/svg-icons/maps/terrain.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsTerrain = (props) => ( <SvgIcon {...props}> <path d="M14 6l-3.75 5 2.85 3.8-1.6 1.2C9.81 13.75 7 10 7 10l-6 8h22L14 6z"/> </SvgIcon> ); MapsTerrain = pure(MapsTerrain); MapsTerrain.displayName = 'MapsTerrain'; export default MapsTerrain;
src/decorators/view-port.js
ecasilla/flux-starter
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from '../../node_modules/react/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { static displayName = (ComposedComponent.displayName && ComposedComponent.displayName.indexOf('.') !== -1 ? ComposedComponent.displayName.substr(0, ComposedComponent.displayName.indexOf('.')) : ComposedComponent.name) + '.' + WithViewport.name; constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on('resize', this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); } }; } export default withViewport;
src/EventEndingRow.js
manishksmd/react-scheduler-smartdata
import PropTypes from 'prop-types' import React from 'react' import EventRowMixin from './EventRowMixin' import { eventLevels } from './utils/eventLevels' import message from './utils/messages' import range from 'lodash/range' let isSegmentInSlot = (seg, slot) => seg.left <= slot && seg.right >= slot let eventsInSlot = (segments, slot) => segments.filter(seg => isSegmentInSlot(seg, slot)).length class EventEndingRow extends React.Component { static propTypes = { segments: PropTypes.array, slots: PropTypes.number, messages: PropTypes.object, onShowMore: PropTypes.func, ...EventRowMixin.propTypes, } static defaultProps = { ...EventRowMixin.defaultProps, } render() { let { segments, slots: slotCount } = this.props let rowSegments = eventLevels(segments).levels[0] let current = 1, lastEnd = 1, row = [] while (current <= slotCount) { let key = '_lvl_' + current let { event, left, right, span } = rowSegments.filter(seg => isSegmentInSlot(seg, current) )[0] || {} //eslint-disable-line if (!event) { current++ continue } let gap = Math.max(0, left - lastEnd) if (this.canRenderSlotEvent(left, span)) { let content = EventRowMixin.renderEvent(this.props, event) if (gap) { row.push(EventRowMixin.renderSpan(this.props, gap, key + '_gap')) } row.push(EventRowMixin.renderSpan(this.props, span, key, content)) lastEnd = current = right + 1 } else { if (gap) { row.push(EventRowMixin.renderSpan(this.props, gap, key + '_gap')) } row.push( EventRowMixin.renderSpan( this.props, 1, key, this.renderShowMore(segments, current) ) ) lastEnd = current = current + 1 } } return ( <div className="rbc-row"> {row} </div> ) } S canRenderSlotEvent(slot, span) { let { segments } = this.props return range(slot, slot + span).every(s => { let count = eventsInSlot(segments, s) return count === 1 }) } renderShowMore(segments, slot) { let messages = message(this.props.messages) let count = eventsInSlot(segments, slot) return count ? <a key={'sm_' + slot} href="#" className={'rbc-show-more'} onClick={e => this.showMore(slot, e)} > {messages.showMore(count)} </a> : false } showMore(slot, e) { e.preventDefault() this.props.onShowMore(slot) } } export default EventEndingRow
frontend/src/Section.js
googleinterns/step78-2020
import React from 'react'; import TextField from '@material-ui/core/TextField'; import {Input, Card, CardContent} from '@material-ui/core'; import FormLabel from '@material-ui/core/FormLabel'; import FormGroup from '@material-ui/core/FormGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Checkbox from '@material-ui/core/Checkbox'; import IconButton from '@material-ui/core/IconButton'; import DeleteIcon from '@material-ui/icons/Delete'; class Section extends React.Component { constructor(props) { super(props); this.handleProfessorChange = this.handleProfessorChange.bind(this); this.handleStartTimeChange = this.handleStartTimeChange.bind(this); this.handleEndTimeChange = this.handleEndTimeChange.bind(this); this.handleDayChange = this.handleDayChange.bind(this); this.handleDeleteSection = this.handleDeleteSection.bind(this); } handleProfessorChange(event) { this.props.updateSectionProfessor(this.props.id, event.target.value); } handleStartTimeChange(event) { this.props.updateSectionStartTime(this.props.id, event.target.value); } handleEndTimeChange(event) { this.props.updateSectionEndTime(this.props.id, event.target.value); } handleDayChange(day) { this.props.updateSectionDays(this.props.id, day); } handleDeleteSection() { this.props.deleteSection(this.props.id); } render() { return ( <Card> <CardContent> <Input placeholder="Professor" value={this.props.professor} onChange={this.handleProfessorChange} /> <TextField label="Start time: " type="time" onChange={this.handleStartTimeChange} InputLabelProps={{shrink: true}} value={this.props.startTime} inputProps={{step: 300}} /> <TextField label="End time: " type="time" onChange={this.handleEndTimeChange} InputLabelProps={{shrink: true}} value={this.props.endTime} inputProps={{step: 300}} /> <IconButton aria-label="delete" onClick={this.handleDeleteSection}> <DeleteIcon /> </IconButton> <FormLabel component="legend">Days of Week</FormLabel> <FormGroup row> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(0)} />} label="Sun" /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(1)} />} label="Mon" /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(2)} />} label="Tues" /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(3)} />} label="Wed" /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(4)} />} label="Thurs" /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(5)} />} label="Fri" /> <FormControlLabel control={<Checkbox onChange={() => this.handleDayChange(6)} />} label="Sat" /> </FormGroup> </CardContent> </Card> ); } } export default Section;
src/routes/dashboard/index.js
zsu13579/whatsgoinontonight
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import Dashboard from './Dashboard'; export default { path: '/dashboard', async action() { return { title: 'Dashboard', component: <Layout><Dashboard /></Layout>, }; }, };
src/components/Home.js
hrasoa/rsk
import React from 'react'; import PostListing from './Posts/PostListing'; export default props => ( <div> <h2>Latest Posts</h2> <PostListing {...props} /> </div> );