path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/index.js
ateev/starWars
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App/App.js'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
app/javascript/mastodon/features/ui/components/media_modal.js
dunn/mastodon
import React from 'react'; import ReactSwipeableViews from 'react-swipeable-views'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Video from 'mastodon/features/video'; import classNames from 'classnames'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import IconButton from 'mastodon/components/icon_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImageLoader from './image_loader'; import Icon from 'mastodon/components/icon'; import GIFV from 'mastodon/components/gifv'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, previous: { id: 'lightbox.previous', defaultMessage: 'Previous' }, next: { id: 'lightbox.next', defaultMessage: 'Next' }, }); export const previewState = 'previewMediaModal'; export default @injectIntl class MediaModal extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.list.isRequired, status: ImmutablePropTypes.map, index: PropTypes.number.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; static contextTypes = { router: PropTypes.object, }; state = { index: null, navigationHidden: false, }; handleSwipe = (index) => { this.setState({ index: index % this.props.media.size }); } handleNextClick = () => { this.setState({ index: (this.getIndex() + 1) % this.props.media.size }); } handlePrevClick = () => { this.setState({ index: (this.props.media.size + this.getIndex() - 1) % this.props.media.size }); } handleChangeIndex = (e) => { const index = Number(e.currentTarget.getAttribute('data-index')); this.setState({ index: index % this.props.media.size }); } handleKeyDown = (e) => { switch(e.key) { case 'ArrowLeft': this.handlePrevClick(); e.preventDefault(); e.stopPropagation(); break; case 'ArrowRight': this.handleNextClick(); e.preventDefault(); e.stopPropagation(); break; } } componentDidMount () { window.addEventListener('keydown', this.handleKeyDown, false); if (this.context.router) { const history = this.context.router.history; history.push(history.location.pathname, previewState); this.unlistenHistory = history.listen(() => { this.props.onClose(); }); } } componentWillUnmount () { window.removeEventListener('keydown', this.handleKeyDown); if (this.context.router) { this.unlistenHistory(); if (this.context.router.history.location.state === previewState) { this.context.router.history.goBack(); } } } getIndex () { return this.state.index !== null ? this.state.index : this.props.index; } toggleNavigation = () => { this.setState(prevState => ({ navigationHidden: !prevState.navigationHidden, })); }; handleStatusClick = e => { if (e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/statuses/${this.props.status.get('id')}`); } } render () { const { media, status, intl, onClose } = this.props; const { navigationHidden } = this.state; const index = this.getIndex(); let pagination = []; const leftNav = media.size > 1 && <button tabIndex='0' className='media-modal__nav media-modal__nav--left' onClick={this.handlePrevClick} aria-label={intl.formatMessage(messages.previous)}><Icon id='chevron-left' fixedWidth /></button>; const rightNav = media.size > 1 && <button tabIndex='0' className='media-modal__nav media-modal__nav--right' onClick={this.handleNextClick} aria-label={intl.formatMessage(messages.next)}><Icon id='chevron-right' fixedWidth /></button>; if (media.size > 1) { pagination = media.map((item, i) => { const classes = ['media-modal__button']; if (i === index) { classes.push('media-modal__button--active'); } return (<li className='media-modal__page-dot' key={i}><button tabIndex='0' className={classes.join(' ')} onClick={this.handleChangeIndex} data-index={i}>{i + 1}</button></li>); }); } const content = media.map((image) => { const width = image.getIn(['meta', 'original', 'width']) || null; const height = image.getIn(['meta', 'original', 'height']) || null; if (image.get('type') === 'image') { return ( <ImageLoader previewSrc={image.get('preview_url')} src={image.get('url')} width={width} height={height} alt={image.get('description')} key={image.get('url')} onClick={this.toggleNavigation} /> ); } else if (image.get('type') === 'video') { const { time } = this.props; return ( <Video preview={image.get('preview_url')} blurhash={image.get('blurhash')} src={image.get('url')} width={image.get('width')} height={image.get('height')} startTime={time || 0} onCloseVideo={onClose} detailed alt={image.get('description')} key={image.get('url')} /> ); } else if (image.get('type') === 'gifv') { return ( <GIFV src={image.get('url')} width={width} height={height} key={image.get('preview_url')} alt={image.get('description')} onClick={this.toggleNavigation} /> ); } return null; }).toArray(); // you can't use 100vh, because the viewport height is taller // than the visible part of the document in some mobile // browsers when it's address bar is visible. // https://developers.google.com/web/updates/2016/12/url-bar-resizing const swipeableViewsStyle = { width: '100%', height: '100%', }; const containerStyle = { alignItems: 'center', // center vertically }; const navigationClassName = classNames('media-modal__navigation', { 'media-modal__navigation--hidden': navigationHidden, }); return ( <div className='modal-root__modal media-modal'> <div className='media-modal__closer' role='presentation' onClick={onClose} > <ReactSwipeableViews style={swipeableViewsStyle} containerStyle={containerStyle} onChangeIndex={this.handleSwipe} index={index} > {content} </ReactSwipeableViews> </div> <div className={navigationClassName}> <IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={40} /> {leftNav} {rightNav} {status && ( <div className={classNames('media-modal__meta', { 'media-modal__meta--shifted': media.size > 1 })}> <a href={status.get('url')} onClick={this.handleStatusClick}><Icon id='comments' /> <FormattedMessage id='lightbox.view_context' defaultMessage='View context' /></a> </div> )} <ul className='media-modal__pagination'> {pagination} </ul> </div> </div> ); } }
src/component/DeveloperOptions.js
BristolPound/cyclos-mobile-3-TownPound
import React from 'react' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import { ListView, View, TouchableHighlight, Image } from 'react-native' import Colors from '@Colors/colors' import merge from '../util/merge' import { loadBusinessList, resetBusinesses } from '../store/reducer/business' import { loadTransactions, resetTransactions } from '../store/reducer/transaction' import DefaultText from './DefaultText' import { hideModal } from '../store/reducer/navigation' import { LOGIN_STATUSES } from '../store/reducer/login' import { selectServer, SERVER } from '../store/reducer/developerOptions' import { setSessionToken } from '../api/api' import Images from '@Assets/images' const INFO_FONT_SIZE = 14 const ACTION_FONT_SIZE = 18 const PADDING = 5 const style = { header: { container: { padding: PADDING, backgroundColor: Colors.gray4 }, text: { fontSize: INFO_FONT_SIZE } }, row: { container: { padding: PADDING }, label: { fontSize: INFO_FONT_SIZE }, value: { fontSize: INFO_FONT_SIZE }, action: { fontSize: ACTION_FONT_SIZE } } } // Render label / value pair. const DeveloperInfo = ({label, value, index, accessibilityLabel}) => <View key={index} style={style.row.container}> <View style={{flexDirection: 'row'}}> <DefaultText style={style.row.label}> {label} </DefaultText> <DefaultText style={style.row.value} accessibilityLabel={accessibilityLabel}> {value} </DefaultText> </View> </View> // Render clickable button const DeveloperAction = ({text, onPress, disabled, index, accessibilityLabel}) => <View key={index} style={style.row.container}> <TouchableHighlight onPress={() => !disabled && onPress()} activeOpacity={0.6} underlayColor={Colors.transparent} > <View> <DefaultText style={merge(style.row.action, disabled ? {opacity: 0.4} : {})} accessibilityLabel={accessibilityLabel} > {text} </DefaultText> </View> </TouchableHighlight> </View> const renderSectionHeader = (sectionData, sectionID) => <View key={sectionID} style={style.header.container}> <DefaultText style={style.row.text}>{sectionID}</DefaultText> </View> const DeveloperOptions = props => { let infoSource = new ListView.DataSource({ rowHasChanged: (a, b) => a.text !== b.text || a.disabled !== b.disabled, sectionHeaderHasChanged: (a, b) => a !== b }) let actionsSource = new ListView.DataSource({ rowHasChanged: (a, b) => a.text !== b.text || a.disabled !== b.disabled, sectionHeaderHasChanged: (a, b) => a !== b }) const infoRows = { 'App State': [ { label: 'Businesses: ', value: props.store.businessCount, accessibilityLabel: 'Business Count'}, { label: 'Business List Timestamp: ', value: `${props.store.businessTimestamp}`, accessibilityLabel: 'Business Timestamp'}, { label: 'Transactions: ', value: props.store.transactionCount, accessibilityLabel: 'Transaction Count'}, { label: 'Server: ', value: props.store.server, accessibilityLabel: 'Server'} ] } const actionRows = { 'Developer Actions': [{ text: 'Clear All Business Data', onPress: () => props.resetBusinesses(), accessibilityLabel: 'Clear Businesses' }, { text: 'Load Business Data', onPress: () => props.loadBusinessList(), accessibilityLabel: 'Load Businesses' }, { text: 'Clear All Transaction Data', onPress: () => props.resetTransactions(), disabled: props.loadingTransactions, accessibilityLabel: 'Clear Transactions' }, { text: 'Load Transaction Data', onPress: () => props.loadTransactions(), disabled: props.loadingTransactions || !props.loggedIn, accessibilityLabel: 'Load Transactions' }, { text: 'Switch Server To ' + (props.store.server === SERVER.STAGE ? 'Dev' : 'Stage'), onPress: () => props.selectServer(props.store.server === SERVER.STAGE ? 'DEV' : 'STAGE'), accessibilityLabel: 'Switch Server' }, { text: 'Corrupt session token', onPress: () => setSessionToken('not a valid session token'), accessibilityLabel: 'Corrupt session token' } ] } infoSource = infoSource.cloneWithRowsAndSections(infoRows, Object.keys(infoRows)) actionsSource = actionsSource.cloneWithRowsAndSections(actionRows, Object.keys(actionRows)) return ( <View style={{flex: 1}}> <View> <TouchableHighlight onPress={() => props.hideModal()} underlayColor={Colors.white} accessiblityLabel='Close Developer Options' > <Image source={Images.close} style={{margin: 20}}/> </TouchableHighlight> </View> <ListView style={{flex: 1}} dataSource={infoSource} renderRow={(accountOption, i) => <DeveloperInfo {...accountOption} index={i}/> } renderSectionHeader={renderSectionHeader} accessibilityLabel='Developer Info' removeClippedSubviews={false}/> <ListView style={{flex: 1}} dataSource={actionsSource} renderRow={(accountOption, i) => <DeveloperAction {...accountOption} index={i}/> } renderSectionHeader={renderSectionHeader} accessibilityLabel='Developer Actions' removeClippedSubviews={false}/> </View> ) } export const onPressChangeServer = props => () => { props.switchBaseUrl() if (props.loggedIn) { props.logout() } } const mapStateToProps = state => ({ store: { businessCount: state.business.businessList.length, businessTimestamp: state.business.businessListTimestamp, transactionCount: state.transaction.transactions.length, server: state.developerOptions.server }, loadingTransactions: state.transaction.loadingTransactions, loggedIn: state.login.loginStatus === LOGIN_STATUSES.LOGGED_IN }) const mapDispatchToProps = dispatch => bindActionCreators({ loadTransactions, resetTransactions, resetBusinesses, loadBusinessList, hideModal, selectServer }, dispatch) export default connect(mapStateToProps, mapDispatchToProps)(DeveloperOptions)
src/components/video_detail.js
nik149/react_test
import React from 'react'; const VideoDetail = ({video}) => { if(!video) { return <div>Loading...</div>; } const url = `https://www.youtube.com/embed/${video.id.videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); } export default VideoDetail;
docs/src/app/components/pages/components/Paper/ExampleCircle.js
rscnt/material-ui
import React from 'react'; import Paper from 'material-ui/Paper'; const style = { height: 100, width: 100, margin: 20, textAlign: 'center', display: 'inline-block', }; const PaperExampleCircle = () => ( <div> <Paper style={style} zDepth={1} circle={true} /> <Paper style={style} zDepth={2} circle={true} /> <Paper style={style} zDepth={3} circle={true} /> <Paper style={style} zDepth={4} circle={true} /> <Paper style={style} zDepth={5} circle={true} /> </div> ); export default PaperExampleCircle;
ajax/libs/react-select/1.2.1/react-select.es.js
joeyparrish/cdnjs
import AutosizeInput from 'react-input-autosize'; import classNames from 'classnames'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; var arrowRenderer = function arrowRenderer(_ref) { var onMouseDown = _ref.onMouseDown; return React.createElement('span', { className: 'Select-arrow', onMouseDown: onMouseDown }); }; arrowRenderer.propTypes = { onMouseDown: PropTypes.func }; var clearRenderer = function clearRenderer() { return React.createElement('span', { className: 'Select-clear', dangerouslySetInnerHTML: { __html: '&times;' } }); }; var map = [{ 'base': 'A', 'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g }, { 'base': 'AA', 'letters': /[\uA732]/g }, { 'base': 'AE', 'letters': /[\u00C6\u01FC\u01E2]/g }, { 'base': 'AO', 'letters': /[\uA734]/g }, { 'base': 'AU', 'letters': /[\uA736]/g }, { 'base': 'AV', 'letters': /[\uA738\uA73A]/g }, { 'base': 'AY', 'letters': /[\uA73C]/g }, { 'base': 'B', 'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g }, { 'base': 'C', 'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g }, { 'base': 'D', 'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g }, { 'base': 'DZ', 'letters': /[\u01F1\u01C4]/g }, { 'base': 'Dz', 'letters': /[\u01F2\u01C5]/g }, { 'base': 'E', 'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g }, { 'base': 'F', 'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g }, { 'base': 'G', 'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g }, { 'base': 'H', 'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g }, { 'base': 'I', 'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g }, { 'base': 'J', 'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g }, { 'base': 'K', 'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g }, { 'base': 'L', 'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g }, { 'base': 'LJ', 'letters': /[\u01C7]/g }, { 'base': 'Lj', 'letters': /[\u01C8]/g }, { 'base': 'M', 'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g }, { 'base': 'N', 'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g }, { 'base': 'NJ', 'letters': /[\u01CA]/g }, { 'base': 'Nj', 'letters': /[\u01CB]/g }, { 'base': 'O', 'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g }, { 'base': 'OI', 'letters': /[\u01A2]/g }, { 'base': 'OO', 'letters': /[\uA74E]/g }, { 'base': 'OU', 'letters': /[\u0222]/g }, { 'base': 'P', 'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g }, { 'base': 'Q', 'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g }, { 'base': 'R', 'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g }, { 'base': 'S', 'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g }, { 'base': 'T', 'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g }, { 'base': 'TZ', 'letters': /[\uA728]/g }, { 'base': 'U', 'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g }, { 'base': 'V', 'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g }, { 'base': 'VY', 'letters': /[\uA760]/g }, { 'base': 'W', 'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g }, { 'base': 'X', 'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g }, { 'base': 'Y', 'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g }, { 'base': 'Z', 'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g }, { 'base': 'a', 'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g }, { 'base': 'aa', 'letters': /[\uA733]/g }, { 'base': 'ae', 'letters': /[\u00E6\u01FD\u01E3]/g }, { 'base': 'ao', 'letters': /[\uA735]/g }, { 'base': 'au', 'letters': /[\uA737]/g }, { 'base': 'av', 'letters': /[\uA739\uA73B]/g }, { 'base': 'ay', 'letters': /[\uA73D]/g }, { 'base': 'b', 'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g }, { 'base': 'c', 'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g }, { 'base': 'd', 'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g }, { 'base': 'dz', 'letters': /[\u01F3\u01C6]/g }, { 'base': 'e', 'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g }, { 'base': 'f', 'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g }, { 'base': 'g', 'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g }, { 'base': 'h', 'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g }, { 'base': 'hv', 'letters': /[\u0195]/g }, { 'base': 'i', 'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g }, { 'base': 'j', 'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g }, { 'base': 'k', 'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g }, { 'base': 'l', 'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g }, { 'base': 'lj', 'letters': /[\u01C9]/g }, { 'base': 'm', 'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g }, { 'base': 'n', 'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g }, { 'base': 'nj', 'letters': /[\u01CC]/g }, { 'base': 'o', 'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g }, { 'base': 'oi', 'letters': /[\u01A3]/g }, { 'base': 'ou', 'letters': /[\u0223]/g }, { 'base': 'oo', 'letters': /[\uA74F]/g }, { 'base': 'p', 'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g }, { 'base': 'q', 'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g }, { 'base': 'r', 'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g }, { 'base': 's', 'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g }, { 'base': 't', 'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g }, { 'base': 'tz', 'letters': /[\uA729]/g }, { 'base': 'u', 'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g }, { 'base': 'v', 'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g }, { 'base': 'vy', 'letters': /[\uA761]/g }, { 'base': 'w', 'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g }, { 'base': 'x', 'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g }, { 'base': 'y', 'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g }, { 'base': 'z', 'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g }]; var stripDiacritics = function stripDiacritics(str) { for (var i = 0; i < map.length; i++) { str = str.replace(map[i].letters, map[i].base); } return str; }; var trim = function trim(str) { return str.replace(/^\s+|\s+$/g, ''); }; var isValid = function isValid(value) { return typeof value !== 'undefined' && value !== null && value !== ''; }; var filterOptions = function filterOptions(options, filterValue, excludeOptions, props) { if (props.ignoreAccents) { filterValue = stripDiacritics(filterValue); } if (props.ignoreCase) { filterValue = filterValue.toLowerCase(); } if (props.trimFilter) { filterValue = trim(filterValue); } if (excludeOptions) excludeOptions = excludeOptions.map(function (i) { return i[props.valueKey]; }); return options.filter(function (option) { if (excludeOptions && excludeOptions.indexOf(option[props.valueKey]) > -1) return false; if (props.filterOption) return props.filterOption.call(undefined, option, filterValue); if (!filterValue) return true; var value = option[props.valueKey]; var label = option[props.labelKey]; var hasValue = isValid(value); var hasLabel = isValid(label); if (!hasValue && !hasLabel) { return false; } var valueTest = hasValue ? String(value) : null; var labelTest = hasLabel ? String(label) : null; if (props.ignoreAccents) { if (valueTest && props.matchProp !== 'label') valueTest = stripDiacritics(valueTest); if (labelTest && props.matchProp !== 'value') labelTest = stripDiacritics(labelTest); } if (props.ignoreCase) { if (valueTest && props.matchProp !== 'label') valueTest = valueTest.toLowerCase(); if (labelTest && props.matchProp !== 'value') labelTest = labelTest.toLowerCase(); } return props.matchPos === 'start' ? valueTest && props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue || labelTest && props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue : valueTest && props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0 || labelTest && props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0; }); }; var menuRenderer = function menuRenderer(_ref) { var focusedOption = _ref.focusedOption, focusOption = _ref.focusOption, inputValue = _ref.inputValue, instancePrefix = _ref.instancePrefix, onFocus = _ref.onFocus, onOptionRef = _ref.onOptionRef, onSelect = _ref.onSelect, optionClassName = _ref.optionClassName, optionComponent = _ref.optionComponent, optionRenderer = _ref.optionRenderer, options = _ref.options, removeValue = _ref.removeValue, selectValue = _ref.selectValue, valueArray = _ref.valueArray, valueKey = _ref.valueKey; var Option = optionComponent; return options.map(function (option, i) { var isSelected = valueArray && valueArray.some(function (x) { return x[valueKey] === option[valueKey]; }); var isFocused = option === focusedOption; var optionClass = classNames(optionClassName, { 'Select-option': true, 'is-selected': isSelected, 'is-focused': isFocused, 'is-disabled': option.disabled }); return React.createElement( Option, { className: optionClass, focusOption: focusOption, inputValue: inputValue, instancePrefix: instancePrefix, isDisabled: option.disabled, isFocused: isFocused, isSelected: isSelected, key: 'option-' + i + '-' + option[valueKey], onFocus: onFocus, onSelect: onSelect, option: option, optionIndex: i, ref: function ref(_ref2) { onOptionRef(_ref2, isFocused); }, removeValue: removeValue, selectValue: selectValue }, optionRenderer(option, i, inputValue) ); }); }; menuRenderer.propTypes = { focusOption: PropTypes.func, focusedOption: PropTypes.object, inputValue: PropTypes.string, instancePrefix: PropTypes.string, onFocus: PropTypes.func, onOptionRef: PropTypes.func, onSelect: PropTypes.func, optionClassName: PropTypes.string, optionComponent: PropTypes.func, optionRenderer: PropTypes.func, options: PropTypes.array, removeValue: PropTypes.func, selectValue: PropTypes.func, valueArray: PropTypes.array, valueKey: PropTypes.string }; var blockEvent = (function (event) { event.preventDefault(); event.stopPropagation(); if (event.target.tagName !== 'A' || !('href' in event.target)) { return; } if (event.target.target) { window.open(event.target.href, event.target.target); } else { window.location.href = event.target.href; } }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var asyncGenerator = function () { function AwaitValue(value) { this.value = value; } function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; if (value instanceof AwaitValue) { Promise.resolve(value.value).then(function (arg) { resume("next", arg); }, function (arg) { resume("throw", arg); }); } else { settle(result.done ? "return" : "normal", result.value); } } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; return { wrap: function (fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; }, await: function (value) { return new AwaitValue(value); } }; }(); var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; 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; }; var inherits = function (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; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (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; }; var Option = function (_React$Component) { inherits(Option, _React$Component); function Option(props) { classCallCheck(this, Option); var _this = possibleConstructorReturn(this, (Option.__proto__ || Object.getPrototypeOf(Option)).call(this, props)); _this.handleMouseDown = _this.handleMouseDown.bind(_this); _this.handleMouseEnter = _this.handleMouseEnter.bind(_this); _this.handleMouseMove = _this.handleMouseMove.bind(_this); _this.handleTouchStart = _this.handleTouchStart.bind(_this); _this.handleTouchEnd = _this.handleTouchEnd.bind(_this); _this.handleTouchMove = _this.handleTouchMove.bind(_this); _this.onFocus = _this.onFocus.bind(_this); return _this; } createClass(Option, [{ key: 'handleMouseDown', value: function handleMouseDown(event) { event.preventDefault(); event.stopPropagation(); this.props.onSelect(this.props.option, event); } }, { key: 'handleMouseEnter', value: function handleMouseEnter(event) { this.onFocus(event); } }, { key: 'handleMouseMove', value: function handleMouseMove(event) { this.onFocus(event); } }, { key: 'handleTouchEnd', value: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; this.handleMouseDown(event); } }, { key: 'handleTouchMove', value: function handleTouchMove() { // Set a flag that the view is being dragged this.dragging = true; } }, { key: 'handleTouchStart', value: function handleTouchStart() { // Set a flag that the view is not being dragged this.dragging = false; } }, { key: 'onFocus', value: function onFocus(event) { if (!this.props.isFocused) { this.props.onFocus(this.props.option, event); } } }, { key: 'render', value: function render() { var _props = this.props, option = _props.option, instancePrefix = _props.instancePrefix, optionIndex = _props.optionIndex; var className = classNames(this.props.className, option.className); return option.disabled ? React.createElement( 'div', { className: className, onMouseDown: blockEvent, onClick: blockEvent }, this.props.children ) : React.createElement( 'div', { className: className, style: option.style, role: 'option', 'aria-label': option.label, onMouseDown: this.handleMouseDown, onMouseEnter: this.handleMouseEnter, onMouseMove: this.handleMouseMove, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove, onTouchEnd: this.handleTouchEnd, id: instancePrefix + '-option-' + optionIndex, title: option.title }, this.props.children ); } }]); return Option; }(React.Component); Option.propTypes = { children: PropTypes.node, className: PropTypes.string, // className (based on mouse position) instancePrefix: PropTypes.string.isRequired, // unique prefix for the ids (used for aria) isDisabled: PropTypes.bool, // the option is disabled isFocused: PropTypes.bool, // the option is focused isSelected: PropTypes.bool, // the option is selected onFocus: PropTypes.func, // method to handle mouseEnter on option element onSelect: PropTypes.func, // method to handle click on option element onUnfocus: PropTypes.func, // method to handle mouseLeave on option element option: PropTypes.object.isRequired, // object that is base for that option optionIndex: PropTypes.number // index of the option, used to generate unique ids for aria }; var Value = function (_React$Component) { inherits(Value, _React$Component); function Value(props) { classCallCheck(this, Value); var _this = possibleConstructorReturn(this, (Value.__proto__ || Object.getPrototypeOf(Value)).call(this, props)); _this.handleMouseDown = _this.handleMouseDown.bind(_this); _this.onRemove = _this.onRemove.bind(_this); _this.handleTouchEndRemove = _this.handleTouchEndRemove.bind(_this); _this.handleTouchMove = _this.handleTouchMove.bind(_this); _this.handleTouchStart = _this.handleTouchStart.bind(_this); return _this; } createClass(Value, [{ key: 'handleMouseDown', value: function handleMouseDown(event) { if (event.type === 'mousedown' && event.button !== 0) { return; } if (this.props.onClick) { event.stopPropagation(); this.props.onClick(this.props.value, event); return; } if (this.props.value.href) { event.stopPropagation(); } } }, { key: 'onRemove', value: function onRemove(event) { event.preventDefault(); event.stopPropagation(); this.props.onRemove(this.props.value); } }, { key: 'handleTouchEndRemove', value: function handleTouchEndRemove(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.onRemove(event); } }, { key: 'handleTouchMove', value: function handleTouchMove() { // Set a flag that the view is being dragged this.dragging = true; } }, { key: 'handleTouchStart', value: function handleTouchStart() { // Set a flag that the view is not being dragged this.dragging = false; } }, { key: 'renderRemoveIcon', value: function renderRemoveIcon() { if (this.props.disabled || !this.props.onRemove) return; return React.createElement( 'span', { className: 'Select-value-icon', 'aria-hidden': 'true', onMouseDown: this.onRemove, onTouchEnd: this.handleTouchEndRemove, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove }, '\xD7' ); } }, { key: 'renderLabel', value: function renderLabel() { var className = 'Select-value-label'; return this.props.onClick || this.props.value.href ? React.createElement( 'a', { className: className, href: this.props.value.href, target: this.props.value.target, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleMouseDown }, this.props.children ) : React.createElement( 'span', { className: className, role: 'option', 'aria-selected': 'true', id: this.props.id }, this.props.children ); } }, { key: 'render', value: function render() { return React.createElement( 'div', { className: classNames('Select-value', this.props.value.className), style: this.props.value.style, title: this.props.value.title }, this.renderRemoveIcon(), this.renderLabel() ); } }]); return Value; }(React.Component); Value.propTypes = { children: PropTypes.node, disabled: PropTypes.bool, // disabled prop passed to ReactSelect id: PropTypes.string, // Unique id for the value - used for aria onClick: PropTypes.func, // method to handle click on value label onRemove: PropTypes.func, // method to handle removal of the value value: PropTypes.object.isRequired // the option object for this value }; /*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/react-select */ var stringifyValue = function stringifyValue(value) { return typeof value === 'string' ? value : value !== null && JSON.stringify(value) || ''; }; var stringOrNode = PropTypes.oneOfType([PropTypes.string, PropTypes.node]); var stringOrNumber = PropTypes.oneOfType([PropTypes.string, PropTypes.number]); var instanceId = 1; var shouldShowValue = function shouldShowValue(state, props) { var inputValue = state.inputValue, isPseudoFocused = state.isPseudoFocused, isFocused = state.isFocused; var onSelectResetsInput = props.onSelectResetsInput; if (!inputValue) return true; if (!onSelectResetsInput) { return !(!isFocused && isPseudoFocused || isFocused && !isPseudoFocused); } return false; }; var shouldShowPlaceholder = function shouldShowPlaceholder(state, props, isOpen) { var inputValue = state.inputValue, isPseudoFocused = state.isPseudoFocused, isFocused = state.isFocused; var onSelectResetsInput = props.onSelectResetsInput; return !inputValue || !onSelectResetsInput && !isOpen && !isPseudoFocused && !isFocused; }; /** * Retrieve a value from the given options and valueKey * @param {String|Number|Array} value - the selected value(s) * @param {Object} props - the Select component's props (or nextProps) */ var expandValue = function expandValue(value, props) { var valueType = typeof value === 'undefined' ? 'undefined' : _typeof(value); if (valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') return value; var options = props.options, valueKey = props.valueKey; if (!options) return; for (var i = 0; i < options.length; i++) { if (String(options[i][valueKey]) === String(value)) return options[i]; } }; var handleRequired = function handleRequired(value, multi) { if (!value) return true; return multi ? value.length === 0 : Object.keys(value).length === 0; }; var Select$1 = function (_React$Component) { inherits(Select, _React$Component); function Select(props) { classCallCheck(this, Select); var _this = possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props)); ['clearValue', 'focusOption', 'getOptionLabel', 'handleInputBlur', 'handleInputChange', 'handleInputFocus', 'handleInputValueChange', 'handleKeyDown', 'handleMenuScroll', 'handleMouseDown', 'handleMouseDownOnArrow', 'handleMouseDownOnMenu', 'handleTouchEnd', 'handleTouchEndClearValue', 'handleTouchMove', 'handleTouchOutside', 'handleTouchStart', 'handleValueClick', 'onOptionRef', 'removeValue', 'selectValue'].forEach(function (fn) { return _this[fn] = _this[fn].bind(_this); }); _this.state = { inputValue: '', isFocused: false, isOpen: false, isPseudoFocused: false, required: false }; return _this; } createClass(Select, [{ key: 'componentWillMount', value: function componentWillMount() { this._instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId) + '-'; var valueArray = this.getValueArray(this.props.value); if (this.props.required) { this.setState({ required: handleRequired(valueArray[0], this.props.multi) }); } } }, { key: 'componentDidMount', value: function componentDidMount() { if (typeof this.props.autofocus !== 'undefined' && typeof console !== 'undefined') { console.warn('Warning: The autofocus prop has changed to autoFocus, support will be removed after [email protected]'); } if (this.props.autoFocus || this.props.autofocus) { this.focus(); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var valueArray = this.getValueArray(nextProps.value, nextProps); if (nextProps.required) { this.setState({ required: handleRequired(valueArray[0], nextProps.multi) }); } else if (this.props.required) { // Used to be required but it's not any more this.setState({ required: false }); } if (this.state.inputValue && this.props.value !== nextProps.value && nextProps.onSelectResetsInput) { this.setState({ inputValue: this.handleInputValueChange('') }); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps, prevState) { // focus to the selected option if (this.menu && this.focused && this.state.isOpen && !this.hasScrolledToOption) { var focusedOptionNode = findDOMNode(this.focused); var menuNode = findDOMNode(this.menu); var scrollTop = menuNode.scrollTop; var scrollBottom = scrollTop + menuNode.offsetHeight; var optionTop = focusedOptionNode.offsetTop; var optionBottom = optionTop + focusedOptionNode.offsetHeight; if (scrollTop > optionTop || scrollBottom < optionBottom) { menuNode.scrollTop = focusedOptionNode.offsetTop; } // We still set hasScrolledToOption to true even if we didn't // actually need to scroll, as we've still confirmed that the // option is in view. this.hasScrolledToOption = true; } else if (!this.state.isOpen) { this.hasScrolledToOption = false; } if (this._scrollToFocusedOptionOnUpdate && this.focused && this.menu) { this._scrollToFocusedOptionOnUpdate = false; var focusedDOM = findDOMNode(this.focused); var menuDOM = findDOMNode(this.menu); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom) { menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight; } else if (focusedRect.top < menuRect.top) { menuDOM.scrollTop = focusedDOM.offsetTop; } } if (this.props.scrollMenuIntoView && this.menuContainer) { var menuContainerRect = this.menuContainer.getBoundingClientRect(); if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) { window.scrollBy(0, menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight); } } if (prevProps.disabled !== this.props.disabled) { this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state this.closeMenu(); } if (prevState.isOpen !== this.state.isOpen) { this.toggleTouchOutsideEvent(this.state.isOpen); var handler = this.state.isOpen ? this.props.onOpen : this.props.onClose; handler && handler(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.toggleTouchOutsideEvent(false); } }, { key: 'toggleTouchOutsideEvent', value: function toggleTouchOutsideEvent(enabled) { if (enabled) { if (!document.addEventListener && document.attachEvent) { document.attachEvent('ontouchstart', this.handleTouchOutside); } else { document.addEventListener('touchstart', this.handleTouchOutside); } } else { if (!document.removeEventListener && document.detachEvent) { document.detachEvent('ontouchstart', this.handleTouchOutside); } else { document.removeEventListener('touchstart', this.handleTouchOutside); } } } }, { key: 'handleTouchOutside', value: function handleTouchOutside(event) { // handle touch outside on ios to dismiss menu if (this.wrapper && !this.wrapper.contains(event.target)) { this.closeMenu(); } } }, { key: 'focus', value: function focus() { if (!this.input) return; this.input.focus(); } }, { key: 'blurInput', value: function blurInput() { if (!this.input) return; this.input.blur(); } }, { key: 'handleTouchMove', value: function handleTouchMove() { // Set a flag that the view is being dragged this.dragging = true; } }, { key: 'handleTouchStart', value: function handleTouchStart() { // Set a flag that the view is not being dragged this.dragging = false; } }, { key: 'handleTouchEnd', value: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.handleMouseDown(event); } }, { key: 'handleTouchEndClearValue', value: function handleTouchEndClearValue(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Clear the value this.clearValue(event); } }, { key: 'handleMouseDown', value: function handleMouseDown(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } if (event.target.tagName === 'INPUT') { if (!this.state.isFocused) { this._openAfterFocus = this.props.openOnClick; this.focus(); } else if (!this.state.isOpen) { this.setState({ isOpen: true, isPseudoFocused: false }); } return; } // prevent default event handlers event.preventDefault(); // for the non-searchable select, toggle the menu if (!this.props.searchable) { // This code means that if a select is searchable, onClick the options menu will not appear, only on subsequent click will it open. this.focus(); return this.setState({ isOpen: !this.state.isOpen }); } if (this.state.isFocused) { // On iOS, we can get into a state where we think the input is focused but it isn't really, // since iOS ignores programmatic calls to input.focus() that weren't triggered by a click event. // Call focus() again here to be safe. this.focus(); var input = this.input; var toOpen = true; if (typeof input.getInput === 'function') { // Get the actual DOM input if the ref is an <AutosizeInput /> component input = input.getInput(); } // clears the value so that the cursor will be at the end of input when the component re-renders input.value = ''; if (this._focusAfterClear) { toOpen = false; this._focusAfterClear = false; } // if the input is focused, ensure the menu is open this.setState({ isOpen: toOpen, isPseudoFocused: false, focusedOption: null }); } else { // otherwise, focus the input and open the menu this._openAfterFocus = this.props.openOnClick; this.focus(); this.setState({ focusedOption: null }); } } }, { key: 'handleMouseDownOnArrow', value: function handleMouseDownOnArrow(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } if (this.state.isOpen) { // prevent default event handlers event.stopPropagation(); event.preventDefault(); // close the menu this.closeMenu(); } else { // If the menu isn't open, let the event bubble to the main handleMouseDown this.setState({ isOpen: true }); } } }, { key: 'handleMouseDownOnMenu', value: function handleMouseDownOnMenu(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this._openAfterFocus = true; this.focus(); } }, { key: 'closeMenu', value: function closeMenu() { if (this.props.onCloseResetsInput) { this.setState({ inputValue: this.handleInputValueChange(''), isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi }); } else { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi }); } this.hasScrolledToOption = false; } }, { key: 'handleInputFocus', value: function handleInputFocus(event) { if (this.props.disabled) return; var toOpen = this.state.isOpen || this._openAfterFocus || this.props.openOnFocus; toOpen = this._focusAfterClear ? false : toOpen; //if focus happens after clear values, don't open dropdown yet. if (this.props.onFocus) { this.props.onFocus(event); } this.setState({ isFocused: true, isOpen: !!toOpen }); this._focusAfterClear = false; this._openAfterFocus = false; } }, { key: 'handleInputBlur', value: function handleInputBlur(event) { // The check for menu.contains(activeElement) is necessary to prevent IE11's scrollbar from closing the menu in certain contexts. if (this.menu && (this.menu === document.activeElement || this.menu.contains(document.activeElement))) { this.focus(); return; } if (this.props.onBlur) { this.props.onBlur(event); } var onBlurredState = { isFocused: false, isOpen: false, isPseudoFocused: false }; if (this.props.onBlurResetsInput) { onBlurredState.inputValue = this.handleInputValueChange(''); } this.setState(onBlurredState); } }, { key: 'handleInputChange', value: function handleInputChange(event) { var newInputValue = event.target.value; if (this.state.inputValue !== event.target.value) { newInputValue = this.handleInputValueChange(newInputValue); } this.setState({ inputValue: newInputValue, isOpen: true, isPseudoFocused: false }); } }, { key: 'setInputValue', value: function setInputValue(newValue) { if (this.props.onInputChange) { var nextState = this.props.onInputChange(newValue); if (nextState != null && (typeof nextState === 'undefined' ? 'undefined' : _typeof(nextState)) !== 'object') { newValue = '' + nextState; } } this.setState({ inputValue: newValue }); } }, { key: 'handleInputValueChange', value: function handleInputValueChange(newValue) { if (this.props.onInputChange) { var nextState = this.props.onInputChange(newValue); // Note: != used deliberately here to catch undefined and null if (nextState != null && (typeof nextState === 'undefined' ? 'undefined' : _typeof(nextState)) !== 'object') { newValue = '' + nextState; } } return newValue; } }, { key: 'handleKeyDown', value: function handleKeyDown(event) { if (this.props.disabled) return; if (typeof this.props.onInputKeyDown === 'function') { this.props.onInputKeyDown(event); if (event.defaultPrevented) { return; } } switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue && this.props.backspaceRemoves) { event.preventDefault(); this.popValue(); } break; case 9: // tab if (event.shiftKey || !this.state.isOpen || !this.props.tabSelectsValue) { break; } event.preventDefault(); this.selectFocusedOption(); break; case 13: // enter event.preventDefault(); event.stopPropagation(); if (this.state.isOpen) { this.selectFocusedOption(); } else { this.focusNextOption(); } break; case 27: // escape event.preventDefault(); if (this.state.isOpen) { this.closeMenu(); event.stopPropagation(); } else if (this.props.clearable && this.props.escapeClearsValue) { this.clearValue(event); event.stopPropagation(); } break; case 32: // space if (this.props.searchable) { break; } event.preventDefault(); if (!this.state.isOpen) { this.focusNextOption(); break; } event.stopPropagation(); this.selectFocusedOption(); break; case 38: // up event.preventDefault(); this.focusPreviousOption(); break; case 40: // down event.preventDefault(); this.focusNextOption(); break; case 33: // page up event.preventDefault(); this.focusPageUpOption(); break; case 34: // page down event.preventDefault(); this.focusPageDownOption(); break; case 35: // end key if (event.shiftKey) { break; } event.preventDefault(); this.focusEndOption(); break; case 36: // home key if (event.shiftKey) { break; } event.preventDefault(); this.focusStartOption(); break; case 46: // delete if (!this.state.inputValue && this.props.deleteRemoves) { event.preventDefault(); this.popValue(); } break; } } }, { key: 'handleValueClick', value: function handleValueClick(option, event) { if (!this.props.onValueClick) return; this.props.onValueClick(option, event); } }, { key: 'handleMenuScroll', value: function handleMenuScroll(event) { if (!this.props.onMenuScrollToBottom) return; var target = event.target; if (target.scrollHeight > target.offsetHeight && target.scrollHeight - target.offsetHeight - target.scrollTop <= 0) { this.props.onMenuScrollToBottom(); } } }, { key: 'getOptionLabel', value: function getOptionLabel(op) { return op[this.props.labelKey]; } /** * Turns a value into an array from the given options * @param {String|Number|Array} value - the value of the select input * @param {Object} nextProps - optionally specify the nextProps so the returned array uses the latest configuration * @returns {Array} the value of the select represented in an array */ }, { key: 'getValueArray', value: function getValueArray(value) { var nextProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; /** support optionally passing in the `nextProps` so `componentWillReceiveProps` updates will function as expected */ var props = (typeof nextProps === 'undefined' ? 'undefined' : _typeof(nextProps)) === 'object' ? nextProps : this.props; if (props.multi) { if (typeof value === 'string') { value = value.split(props.delimiter); } if (!Array.isArray(value)) { if (value === null || value === undefined) return []; value = [value]; } return value.map(function (value) { return expandValue(value, props); }).filter(function (i) { return i; }); } var expandedValue = expandValue(value, props); return expandedValue ? [expandedValue] : []; } }, { key: 'setValue', value: function setValue(value) { var _this2 = this; if (this.props.autoBlur) { this.blurInput(); } if (this.props.required) { var required = handleRequired(value, this.props.multi); this.setState({ required: required }); } if (this.props.simpleValue && value) { value = this.props.multi ? value.map(function (i) { return i[_this2.props.valueKey]; }).join(this.props.delimiter) : value[this.props.valueKey]; } if (this.props.onChange) { this.props.onChange(value); } } }, { key: 'selectValue', value: function selectValue(value) { var _this3 = this; // NOTE: we actually add/set the value in a callback to make sure the // input value is empty to avoid styling issues in Chrome if (this.props.closeOnSelect) { this.hasScrolledToOption = false; } var updatedValue = this.props.onSelectResetsInput ? '' : this.state.inputValue; if (this.props.multi) { this.setState({ focusedIndex: null, inputValue: this.handleInputValueChange(updatedValue), isOpen: !this.props.closeOnSelect }, function () { var valueArray = _this3.getValueArray(_this3.props.value); if (valueArray.some(function (i) { return i[_this3.props.valueKey] === value[_this3.props.valueKey]; })) { _this3.removeValue(value); } else { _this3.addValue(value); } }); } else { this.setState({ inputValue: this.handleInputValueChange(updatedValue), isOpen: !this.props.closeOnSelect, isPseudoFocused: this.state.isFocused }, function () { _this3.setValue(value); }); } } }, { key: 'addValue', value: function addValue(value) { var valueArray = this.getValueArray(this.props.value); var visibleOptions = this._visibleOptions.filter(function (val) { return !val.disabled; }); var lastValueIndex = visibleOptions.indexOf(value); this.setValue(valueArray.concat(value)); if (visibleOptions.length - 1 === lastValueIndex) { // the last option was selected; focus the second-last one this.focusOption(visibleOptions[lastValueIndex - 1]); } else if (visibleOptions.length > lastValueIndex) { // focus the option below the selected one this.focusOption(visibleOptions[lastValueIndex + 1]); } } }, { key: 'popValue', value: function popValue() { var valueArray = this.getValueArray(this.props.value); if (!valueArray.length) return; if (valueArray[valueArray.length - 1].clearableValue === false) return; this.setValue(this.props.multi ? valueArray.slice(0, valueArray.length - 1) : null); } }, { key: 'removeValue', value: function removeValue(value) { var _this4 = this; var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.filter(function (i) { return i[_this4.props.valueKey] !== value[_this4.props.valueKey]; })); this.focus(); } }, { key: 'clearValue', value: function clearValue(event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } event.preventDefault(); this.setValue(this.getResetValue()); this.setState({ inputValue: this.handleInputValueChange(''), isOpen: false }, this.focus); this._focusAfterClear = true; } }, { key: 'getResetValue', value: function getResetValue() { if (this.props.resetValue !== undefined) { return this.props.resetValue; } else if (this.props.multi) { return []; } else { return null; } } }, { key: 'focusOption', value: function focusOption(option) { this.setState({ focusedOption: option }); } }, { key: 'focusNextOption', value: function focusNextOption() { this.focusAdjacentOption('next'); } }, { key: 'focusPreviousOption', value: function focusPreviousOption() { this.focusAdjacentOption('previous'); } }, { key: 'focusPageUpOption', value: function focusPageUpOption() { this.focusAdjacentOption('page_up'); } }, { key: 'focusPageDownOption', value: function focusPageDownOption() { this.focusAdjacentOption('page_down'); } }, { key: 'focusStartOption', value: function focusStartOption() { this.focusAdjacentOption('start'); } }, { key: 'focusEndOption', value: function focusEndOption() { this.focusAdjacentOption('end'); } }, { key: 'focusAdjacentOption', value: function focusAdjacentOption(dir) { var options = this._visibleOptions.map(function (option, index) { return { option: option, index: index }; }).filter(function (option) { return !option.option.disabled; }); this._scrollToFocusedOptionOnUpdate = true; if (!this.state.isOpen) { var newState = { focusedOption: this._focusedOption || (options.length ? options[dir === 'next' ? 0 : options.length - 1].option : null), isOpen: true }; if (this.props.onSelectResetsInput) { newState.inputValue = ''; } this.setState(newState); return; } if (!options.length) return; var focusedIndex = -1; for (var i = 0; i < options.length; i++) { if (this._focusedOption === options[i].option) { focusedIndex = i; break; } } if (dir === 'next' && focusedIndex !== -1) { focusedIndex = (focusedIndex + 1) % options.length; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedIndex = focusedIndex - 1; } else { focusedIndex = options.length - 1; } } else if (dir === 'start') { focusedIndex = 0; } else if (dir === 'end') { focusedIndex = options.length - 1; } else if (dir === 'page_up') { var potentialIndex = focusedIndex - this.props.pageSize; if (potentialIndex < 0) { focusedIndex = 0; } else { focusedIndex = potentialIndex; } } else if (dir === 'page_down') { var _potentialIndex = focusedIndex + this.props.pageSize; if (_potentialIndex > options.length - 1) { focusedIndex = options.length - 1; } else { focusedIndex = _potentialIndex; } } if (focusedIndex === -1) { focusedIndex = 0; } this.setState({ focusedIndex: options[focusedIndex].index, focusedOption: options[focusedIndex].option }); } }, { key: 'getFocusedOption', value: function getFocusedOption() { return this._focusedOption; } }, { key: 'selectFocusedOption', value: function selectFocusedOption() { if (this._focusedOption) { return this.selectValue(this._focusedOption); } } }, { key: 'renderLoading', value: function renderLoading() { if (!this.props.isLoading) return; return React.createElement( 'span', { className: 'Select-loading-zone', 'aria-hidden': 'true' }, React.createElement('span', { className: 'Select-loading' }) ); } }, { key: 'renderValue', value: function renderValue(valueArray, isOpen) { var _this5 = this; var renderLabel = this.props.valueRenderer || this.getOptionLabel; var ValueComponent = this.props.valueComponent; if (!valueArray.length) { var showPlaceholder = shouldShowPlaceholder(this.state, this.props, isOpen); return showPlaceholder ? React.createElement( 'div', { className: 'Select-placeholder' }, this.props.placeholder ) : null; } var onClick = this.props.onValueClick ? this.handleValueClick : null; if (this.props.multi) { return valueArray.map(function (value, i) { return React.createElement( ValueComponent, { disabled: _this5.props.disabled || value.clearableValue === false, id: _this5._instancePrefix + '-value-' + i, instancePrefix: _this5._instancePrefix, key: 'value-' + i + '-' + value[_this5.props.valueKey], onClick: onClick, onRemove: _this5.removeValue, placeholder: _this5.props.placeholder, value: value }, renderLabel(value, i), React.createElement( 'span', { className: 'Select-aria-only' }, '\xA0' ) ); }); } else if (shouldShowValue(this.state, this.props)) { if (isOpen) onClick = null; return React.createElement( ValueComponent, { disabled: this.props.disabled, id: this._instancePrefix + '-value-item', instancePrefix: this._instancePrefix, onClick: onClick, placeholder: this.props.placeholder, value: valueArray[0] }, renderLabel(valueArray[0]) ); } } }, { key: 'renderInput', value: function renderInput(valueArray, focusedOptionIndex) { var _classNames, _this6 = this; var className = classNames('Select-input', this.props.inputProps.className); var isOpen = this.state.isOpen; var ariaOwns = classNames((_classNames = {}, defineProperty(_classNames, this._instancePrefix + '-list', isOpen), defineProperty(_classNames, this._instancePrefix + '-backspace-remove-message', this.props.multi && !this.props.disabled && this.state.isFocused && !this.state.inputValue), _classNames)); var value = this.state.inputValue; if (value && !this.props.onSelectResetsInput && !this.state.isFocused) { // it hides input value when it is not focused and was not reset on select value = ''; } var inputProps = _extends({}, this.props.inputProps, { 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', 'aria-describedby': this.props['aria-describedby'], 'aria-expanded': '' + isOpen, 'aria-haspopup': '' + isOpen, 'aria-label': this.props['aria-label'], 'aria-labelledby': this.props['aria-labelledby'], 'aria-owns': ariaOwns, className: className, onBlur: this.handleInputBlur, onChange: this.handleInputChange, onFocus: this.handleInputFocus, ref: function ref(_ref) { return _this6.input = _ref; }, role: 'combobox', required: this.state.required, tabIndex: this.props.tabIndex, value: value }); if (this.props.inputRenderer) { return this.props.inputRenderer(inputProps); } if (this.props.disabled || !this.props.searchable) { var divProps = objectWithoutProperties(this.props.inputProps, []); var _ariaOwns = classNames(defineProperty({}, this._instancePrefix + '-list', isOpen)); return React.createElement('div', _extends({}, divProps, { 'aria-expanded': isOpen, 'aria-owns': _ariaOwns, 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', 'aria-disabled': '' + this.props.disabled, 'aria-label': this.props['aria-label'], 'aria-labelledby': this.props['aria-labelledby'], className: className, onBlur: this.handleInputBlur, onFocus: this.handleInputFocus, ref: function ref(_ref2) { return _this6.input = _ref2; }, role: 'combobox', style: { border: 0, width: 1, display: 'inline-block' }, tabIndex: this.props.tabIndex || 0 })); } if (this.props.autosize) { return React.createElement(AutosizeInput, _extends({ id: this.props.id }, inputProps, { minWidth: '5' })); } return React.createElement( 'div', { className: className, key: 'input-wrap', style: { display: 'inline-block' } }, React.createElement('input', _extends({ id: this.props.id }, inputProps)) ); } }, { key: 'renderClear', value: function renderClear() { var valueArray = this.getValueArray(this.props.value); if (!this.props.clearable || !valueArray.length || this.props.disabled || this.props.isLoading) return; var ariaLabel = this.props.multi ? this.props.clearAllText : this.props.clearValueText; var clear = this.props.clearRenderer(); return React.createElement( 'span', { 'aria-label': ariaLabel, className: 'Select-clear-zone', onMouseDown: this.clearValue, onTouchEnd: this.handleTouchEndClearValue, onTouchMove: this.handleTouchMove, onTouchStart: this.handleTouchStart, title: ariaLabel }, clear ); } }, { key: 'renderArrow', value: function renderArrow() { if (!this.props.arrowRenderer) return; var onMouseDown = this.handleMouseDownOnArrow; var isOpen = this.state.isOpen; var arrow = this.props.arrowRenderer({ onMouseDown: onMouseDown, isOpen: isOpen }); if (!arrow) { return null; } return React.createElement( 'span', { className: 'Select-arrow-zone', onMouseDown: onMouseDown }, arrow ); } }, { key: 'filterOptions', value: function filterOptions$$1(excludeOptions) { var filterValue = this.state.inputValue; var options = this.props.options || []; if (this.props.filterOptions) { // Maintain backwards compatibility with boolean attribute var filterOptions$$1 = typeof this.props.filterOptions === 'function' ? this.props.filterOptions : filterOptions; return filterOptions$$1(options, filterValue, excludeOptions, { filterOption: this.props.filterOption, ignoreAccents: this.props.ignoreAccents, ignoreCase: this.props.ignoreCase, labelKey: this.props.labelKey, matchPos: this.props.matchPos, matchProp: this.props.matchProp, trimFilter: this.props.trimFilter, valueKey: this.props.valueKey }); } else { return options; } } }, { key: 'onOptionRef', value: function onOptionRef(ref, isFocused) { if (isFocused) { this.focused = ref; } } }, { key: 'renderMenu', value: function renderMenu(options, valueArray, focusedOption) { if (options && options.length) { return this.props.menuRenderer({ focusedOption: focusedOption, focusOption: this.focusOption, inputValue: this.state.inputValue, instancePrefix: this._instancePrefix, labelKey: this.props.labelKey, onFocus: this.focusOption, onOptionRef: this.onOptionRef, onSelect: this.selectValue, optionClassName: this.props.optionClassName, optionComponent: this.props.optionComponent, optionRenderer: this.props.optionRenderer || this.getOptionLabel, options: options, removeValue: this.removeValue, selectValue: this.selectValue, valueArray: valueArray, valueKey: this.props.valueKey }); } else if (this.props.noResultsText) { return React.createElement( 'div', { className: 'Select-noresults' }, this.props.noResultsText ); } else { return null; } } }, { key: 'renderHiddenField', value: function renderHiddenField(valueArray) { var _this7 = this; if (!this.props.name) return; if (this.props.joinValues) { var value = valueArray.map(function (i) { return stringifyValue(i[_this7.props.valueKey]); }).join(this.props.delimiter); return React.createElement('input', { disabled: this.props.disabled, name: this.props.name, ref: function ref(_ref3) { return _this7.value = _ref3; }, type: 'hidden', value: value }); } return valueArray.map(function (item, index) { return React.createElement('input', { disabled: _this7.props.disabled, key: 'hidden.' + index, name: _this7.props.name, ref: 'value' + index, type: 'hidden', value: stringifyValue(item[_this7.props.valueKey]) }); }); } }, { key: 'getFocusableOptionIndex', value: function getFocusableOptionIndex(selectedOption) { var options = this._visibleOptions; if (!options.length) return null; var valueKey = this.props.valueKey; var focusedOption = this.state.focusedOption || selectedOption; if (focusedOption && !focusedOption.disabled) { var focusedOptionIndex = -1; options.some(function (option, index) { var isOptionEqual = option[valueKey] === focusedOption[valueKey]; if (isOptionEqual) { focusedOptionIndex = index; } return isOptionEqual; }); if (focusedOptionIndex !== -1) { return focusedOptionIndex; } } for (var i = 0; i < options.length; i++) { if (!options[i].disabled) return i; } return null; } }, { key: 'renderOuter', value: function renderOuter(options, valueArray, focusedOption) { var _this8 = this; var menu = this.renderMenu(options, valueArray, focusedOption); if (!menu) { return null; } return React.createElement( 'div', { ref: function ref(_ref5) { return _this8.menuContainer = _ref5; }, className: 'Select-menu-outer', style: this.props.menuContainerStyle }, React.createElement( 'div', { className: 'Select-menu', id: this._instancePrefix + '-list', onMouseDown: this.handleMouseDownOnMenu, onScroll: this.handleMenuScroll, ref: function ref(_ref4) { return _this8.menu = _ref4; }, role: 'listbox', style: this.props.menuStyle, tabIndex: -1 }, menu ) ); } }, { key: 'render', value: function render() { var _this9 = this; var valueArray = this.getValueArray(this.props.value); var options = this._visibleOptions = this.filterOptions(this.props.multi && this.props.removeSelected ? valueArray : null); var isOpen = this.state.isOpen; if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false; var focusedOptionIndex = this.getFocusableOptionIndex(valueArray[0]); var focusedOption = null; if (focusedOptionIndex !== null) { focusedOption = this._focusedOption = options[focusedOptionIndex]; } else { focusedOption = this._focusedOption = null; } var className = classNames('Select', this.props.className, { 'has-value': valueArray.length, 'is-clearable': this.props.clearable, 'is-disabled': this.props.disabled, 'is-focused': this.state.isFocused, 'is-loading': this.props.isLoading, 'is-open': isOpen, 'is-pseudo-focused': this.state.isPseudoFocused, 'is-searchable': this.props.searchable, 'Select--multi': this.props.multi, 'Select--rtl': this.props.rtl, 'Select--single': !this.props.multi }); var removeMessage = null; if (this.props.multi && !this.props.disabled && valueArray.length && !this.state.inputValue && this.state.isFocused && this.props.backspaceRemoves) { removeMessage = React.createElement( 'span', { id: this._instancePrefix + '-backspace-remove-message', className: 'Select-aria-only', 'aria-live': 'assertive' }, this.props.backspaceToRemoveMessage.replace('{label}', valueArray[valueArray.length - 1][this.props.labelKey]) ); } return React.createElement( 'div', { ref: function ref(_ref7) { return _this9.wrapper = _ref7; }, className: className, style: this.props.wrapperStyle }, this.renderHiddenField(valueArray), React.createElement( 'div', { ref: function ref(_ref6) { return _this9.control = _ref6; }, className: 'Select-control', onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleTouchEnd, onTouchMove: this.handleTouchMove, onTouchStart: this.handleTouchStart, style: this.props.style }, React.createElement( 'span', { className: 'Select-multi-value-wrapper', id: this._instancePrefix + '-value' }, this.renderValue(valueArray, isOpen), this.renderInput(valueArray, focusedOptionIndex) ), removeMessage, this.renderLoading(), this.renderClear(), this.renderArrow() ), isOpen ? this.renderOuter(options, valueArray, focusedOption) : null ); } }]); return Select; }(React.Component); Select$1.propTypes = { 'aria-describedby': PropTypes.string, // html id(s) of element(s) that should be used to describe this input (for assistive tech) 'aria-label': PropTypes.string, // aria label (for assistive tech) 'aria-labelledby': PropTypes.string, // html id of an element that should be used as the label (for assistive tech) arrowRenderer: PropTypes.func, // create the drop-down caret element autoBlur: PropTypes.bool, // automatically blur the component when an option is selected autoFocus: PropTypes.bool, // autofocus the component on mount autofocus: PropTypes.bool, // deprecated; use autoFocus instead autosize: PropTypes.bool, // whether to enable autosizing or not backspaceRemoves: PropTypes.bool, // whether backspace removes an item if there is no text input backspaceToRemoveMessage: PropTypes.string, // message to use for screenreaders to press backspace to remove the current item - {label} is replaced with the item label className: PropTypes.string, // className for the outer element clearAllText: stringOrNode, // title for the "clear" control when multi: true clearRenderer: PropTypes.func, // create clearable x element clearValueText: stringOrNode, // title for the "clear" control clearable: PropTypes.bool, // should it be possible to reset value closeOnSelect: PropTypes.bool, // whether to close the menu when a value is selected deleteRemoves: PropTypes.bool, // whether delete removes an item if there is no text input delimiter: PropTypes.string, // delimiter to use to join multiple values for the hidden field value disabled: PropTypes.bool, // whether the Select is disabled or not escapeClearsValue: PropTypes.bool, // whether escape clears the value when the menu is closed filterOption: PropTypes.func, // method to filter a single option (option, filterString) filterOptions: PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values]) id: PropTypes.string, // html id to set on the input element for accessibility or tests ignoreAccents: PropTypes.bool, // whether to strip diacritics when filtering ignoreCase: PropTypes.bool, // whether to perform case-insensitive filtering inputProps: PropTypes.object, // custom attributes for the Input inputRenderer: PropTypes.func, // returns a custom input component instanceId: PropTypes.string, // set the components instanceId isLoading: PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded) joinValues: PropTypes.bool, // joins multiple values into a single form field with the delimiter (legacy mode) labelKey: PropTypes.string, // path of the label value in option objects matchPos: PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: PropTypes.string, // (any|label|value) which option property to filter on menuBuffer: PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu menuContainerStyle: PropTypes.object, // optional style to apply to the menu container menuRenderer: PropTypes.func, // renders a custom menu with options menuStyle: PropTypes.object, // optional style to apply to the menu multi: PropTypes.bool, // multi-value input name: PropTypes.string, // generates a hidden <input /> tag with this field name for html forms noResultsText: stringOrNode, // placeholder displayed when there are no matching search results onBlur: PropTypes.func, // onBlur handler: function (event) {} onBlurResetsInput: PropTypes.bool, // whether input is cleared on blur onChange: PropTypes.func, // onChange handler: function (newValue) {} onClose: PropTypes.func, // fires when the menu is closed onCloseResetsInput: PropTypes.bool, // whether input is cleared when menu is closed through the arrow onFocus: PropTypes.func, // onFocus handler: function (event) {} onInputChange: PropTypes.func, // onInputChange handler: function (inputValue) {} onInputKeyDown: PropTypes.func, // input keyDown handler: function (event) {} onMenuScrollToBottom: PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options onOpen: PropTypes.func, // fires when the menu is opened onSelectResetsInput: PropTypes.bool, // whether input is cleared on select (works only for multiselect) onValueClick: PropTypes.func, // onClick handler for value labels: function (value, event) {} openOnClick: PropTypes.bool, // boolean to control opening the menu when the control is clicked openOnFocus: PropTypes.bool, // always open options menu on focus optionClassName: PropTypes.string, // additional class(es) to apply to the <Option /> elements optionComponent: PropTypes.func, // option component to render in dropdown optionRenderer: PropTypes.func, // optionRenderer: function (option) {} options: PropTypes.array, // array of options pageSize: PropTypes.number, // number of entries to page when using page up/down keys placeholder: stringOrNode, // field placeholder, displayed when there's no value removeSelected: PropTypes.bool, // whether the selected option is removed from the dropdown on multi selects required: PropTypes.bool, // applies HTML5 required attribute when needed resetValue: PropTypes.any, // value to use when you clear the control rtl: PropTypes.bool, // set to true in order to use react-select in right-to-left direction scrollMenuIntoView: PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged searchable: PropTypes.bool, // whether to enable searching feature or not simpleValue: PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false style: PropTypes.object, // optional style to apply to the control tabIndex: stringOrNumber, // optional tab index of the control tabSelectsValue: PropTypes.bool, // whether to treat tabbing out while focused to be value selection trimFilter: PropTypes.bool, // whether to trim whitespace around filter value value: PropTypes.any, // initial field value valueComponent: PropTypes.func, // value component to render valueKey: PropTypes.string, // path of the label value in option objects valueRenderer: PropTypes.func, // valueRenderer: function (option) {} wrapperStyle: PropTypes.object // optional style to apply to the component wrapper }; Select$1.defaultProps = { arrowRenderer: arrowRenderer, autosize: true, backspaceRemoves: true, backspaceToRemoveMessage: 'Press backspace to remove {label}', clearable: true, clearAllText: 'Clear all', clearRenderer: clearRenderer, clearValueText: 'Clear value', closeOnSelect: true, deleteRemoves: true, delimiter: ',', disabled: false, escapeClearsValue: true, filterOptions: filterOptions, ignoreAccents: true, ignoreCase: true, inputProps: {}, isLoading: false, joinValues: false, labelKey: 'label', matchPos: 'any', matchProp: 'any', menuBuffer: 0, menuRenderer: menuRenderer, multi: false, noResultsText: 'No results found', onBlurResetsInput: true, onCloseResetsInput: true, onSelectResetsInput: true, openOnClick: true, optionComponent: Option, pageSize: 5, placeholder: 'Select...', removeSelected: true, required: false, rtl: false, scrollMenuIntoView: true, searchable: true, simpleValue: false, tabSelectsValue: true, trimFilter: true, valueComponent: Value, valueKey: 'value' }; var propTypes = { autoload: PropTypes.bool.isRequired, // automatically call the `loadOptions` prop on-mount; defaults to true cache: PropTypes.any, // object to use to cache results; set to null/false to disable caching children: PropTypes.func.isRequired, // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element ignoreAccents: PropTypes.bool, // strip diacritics when filtering; defaults to true ignoreCase: PropTypes.bool, // perform case-insensitive filtering; defaults to true loadOptions: PropTypes.func.isRequired, // callback to load options asynchronously; (inputValue: string, callback: Function): ?Promise loadingPlaceholder: PropTypes.oneOfType([// replaces the placeholder while options are loading PropTypes.string, PropTypes.node]), multi: PropTypes.bool, // multi-value input noResultsText: PropTypes.oneOfType([// field noResultsText, displayed when no options come back from the server PropTypes.string, PropTypes.node]), onChange: PropTypes.func, // onChange handler: function (newValue) {} onInputChange: PropTypes.func, // optional for keeping track of what is being typed options: PropTypes.array.isRequired, // array of options placeholder: PropTypes.oneOfType([// field placeholder, displayed when there's no value (shared with Select) PropTypes.string, PropTypes.node]), searchPromptText: PropTypes.oneOfType([// label to prompt for search input PropTypes.string, PropTypes.node]), value: PropTypes.any // initial field value }; var defaultCache = {}; var defaultChildren = function defaultChildren(props) { return React.createElement(Select$1, props); }; var defaultProps = { autoload: true, cache: defaultCache, children: defaultChildren, ignoreAccents: true, ignoreCase: true, loadingPlaceholder: 'Loading...', options: [], searchPromptText: 'Type to search' }; var Async = function (_Component) { inherits(Async, _Component); function Async(props, context) { classCallCheck(this, Async); var _this = possibleConstructorReturn(this, (Async.__proto__ || Object.getPrototypeOf(Async)).call(this, props, context)); _this._cache = props.cache === defaultCache ? {} : props.cache; _this.state = { inputValue: '', isLoading: false, options: props.options }; _this.onInputChange = _this.onInputChange.bind(_this); return _this; } createClass(Async, [{ key: 'componentDidMount', value: function componentDidMount() { var autoload = this.props.autoload; if (autoload) { this.loadOptions(''); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.options !== this.props.options) { this.setState({ options: nextProps.options }); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this._callback = null; } }, { key: 'loadOptions', value: function loadOptions(inputValue) { var _this2 = this; var loadOptions = this.props.loadOptions; var cache = this._cache; if (cache && Object.prototype.hasOwnProperty.call(cache, inputValue)) { this._callback = null; this.setState({ isLoading: false, options: cache[inputValue] }); return; } var callback = function callback(error, data) { var options = data && data.options || []; if (cache) { cache[inputValue] = options; } if (callback === _this2._callback) { _this2._callback = null; _this2.setState({ isLoading: false, options: options }); } }; // Ignore all but the most recent request this._callback = callback; var promise = loadOptions(inputValue, callback); if (promise) { promise.then(function (data) { return callback(null, data); }, function (error) { return callback(error); }); } if (this._callback && !this.state.isLoading) { this.setState({ isLoading: true }); } } }, { key: 'onInputChange', value: function onInputChange(inputValue) { var _props = this.props, ignoreAccents = _props.ignoreAccents, ignoreCase = _props.ignoreCase, onInputChange = _props.onInputChange; var newInputValue = inputValue; if (onInputChange) { var value = onInputChange(newInputValue); // Note: != used deliberately here to catch undefined and null if (value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') { newInputValue = '' + value; } } var transformedInputValue = newInputValue; if (ignoreAccents) { transformedInputValue = stripDiacritics(transformedInputValue); } if (ignoreCase) { transformedInputValue = transformedInputValue.toLowerCase(); } this.setState({ inputValue: newInputValue }); this.loadOptions(transformedInputValue); // Return new input value, but without applying toLowerCase() to avoid modifying the user's view case of the input while typing. return newInputValue; } }, { key: 'noResultsText', value: function noResultsText() { var _props2 = this.props, loadingPlaceholder = _props2.loadingPlaceholder, noResultsText = _props2.noResultsText, searchPromptText = _props2.searchPromptText; var _state = this.state, inputValue = _state.inputValue, isLoading = _state.isLoading; if (isLoading) { return loadingPlaceholder; } if (inputValue && noResultsText) { return noResultsText; } return searchPromptText; } }, { key: 'focus', value: function focus() { this.select.focus(); } }, { key: 'render', value: function render() { var _this3 = this; var _props3 = this.props, children = _props3.children, loadingPlaceholder = _props3.loadingPlaceholder, placeholder = _props3.placeholder; var _state2 = this.state, isLoading = _state2.isLoading, options = _state2.options; var props = { noResultsText: this.noResultsText(), placeholder: isLoading ? loadingPlaceholder : placeholder, options: isLoading && loadingPlaceholder ? [] : options, ref: function ref(_ref) { return _this3.select = _ref; } }; return children(_extends({}, this.props, props, { isLoading: isLoading, onInputChange: this.onInputChange })); } }]); return Async; }(Component); Async.propTypes = propTypes; Async.defaultProps = defaultProps; var CreatableSelect = function (_React$Component) { inherits(CreatableSelect, _React$Component); function CreatableSelect(props, context) { classCallCheck(this, CreatableSelect); var _this = possibleConstructorReturn(this, (CreatableSelect.__proto__ || Object.getPrototypeOf(CreatableSelect)).call(this, props, context)); _this.filterOptions = _this.filterOptions.bind(_this); _this.menuRenderer = _this.menuRenderer.bind(_this); _this.onInputKeyDown = _this.onInputKeyDown.bind(_this); _this.onInputChange = _this.onInputChange.bind(_this); _this.onOptionSelect = _this.onOptionSelect.bind(_this); return _this; } createClass(CreatableSelect, [{ key: 'createNewOption', value: function createNewOption() { var _props = this.props, isValidNewOption = _props.isValidNewOption, newOptionCreator = _props.newOptionCreator, onNewOptionClick = _props.onNewOptionClick, _props$options = _props.options, options = _props$options === undefined ? [] : _props$options; if (isValidNewOption({ label: this.inputValue })) { var option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); var _isOptionUnique = this.isOptionUnique({ option: option, options: options }); // Don't add the same option twice. if (_isOptionUnique) { if (onNewOptionClick) { onNewOptionClick(option); } else { options.unshift(option); this.select.selectValue(option); } } } } }, { key: 'filterOptions', value: function filterOptions$$1() { var _props2 = this.props, filterOptions$$1 = _props2.filterOptions, isValidNewOption = _props2.isValidNewOption, promptTextCreator = _props2.promptTextCreator; // TRICKY Check currently selected options as well. // Don't display a create-prompt for a value that's selected. // This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array. var excludeOptions = (arguments.length <= 2 ? undefined : arguments[2]) || []; var filteredOptions = filterOptions$$1.apply(undefined, arguments) || []; if (isValidNewOption({ label: this.inputValue })) { var _newOptionCreator = this.props.newOptionCreator; var option = _newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); // TRICKY Compare to all options (not just filtered options) in case option has already been selected). // For multi-selects, this would remove it from the filtered list. var _isOptionUnique2 = this.isOptionUnique({ option: option, options: excludeOptions.concat(filteredOptions) }); if (_isOptionUnique2) { var prompt = promptTextCreator(this.inputValue); this._createPlaceholderOption = _newOptionCreator({ label: prompt, labelKey: this.labelKey, valueKey: this.valueKey }); filteredOptions.unshift(this._createPlaceholderOption); } } return filteredOptions; } }, { key: 'isOptionUnique', value: function isOptionUnique(_ref) { var option = _ref.option, options = _ref.options; var isOptionUnique = this.props.isOptionUnique; options = options || this.props.options; return isOptionUnique({ labelKey: this.labelKey, option: option, options: options, valueKey: this.valueKey }); } }, { key: 'menuRenderer', value: function menuRenderer$$1(params) { var menuRenderer$$1 = this.props.menuRenderer; return menuRenderer$$1(_extends({}, params, { onSelect: this.onOptionSelect, selectValue: this.onOptionSelect })); } }, { key: 'onInputChange', value: function onInputChange(input) { var onInputChange = this.props.onInputChange; // This value may be needed in between Select mounts (when this.select is null) this.inputValue = input; if (onInputChange) { this.inputValue = onInputChange(input); } return this.inputValue; } }, { key: 'onInputKeyDown', value: function onInputKeyDown(event) { var _props3 = this.props, shouldKeyDownEventCreateNewOption = _props3.shouldKeyDownEventCreateNewOption, onInputKeyDown = _props3.onInputKeyDown; var focusedOption = this.select.getFocusedOption(); if (focusedOption && focusedOption === this._createPlaceholderOption && shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })) { this.createNewOption(); // Prevent decorated Select from doing anything additional with this keyDown event event.preventDefault(); } else if (onInputKeyDown) { onInputKeyDown(event); } } }, { key: 'onOptionSelect', value: function onOptionSelect(option) { if (option === this._createPlaceholderOption) { this.createNewOption(); } else { this.select.selectValue(option); } } }, { key: 'focus', value: function focus() { this.select.focus(); } }, { key: 'render', value: function render() { var _this2 = this; var _props4 = this.props, refProp = _props4.ref, restProps = objectWithoutProperties(_props4, ['ref']); var children = this.props.children; // We can't use destructuring default values to set the children, // because it won't apply work if `children` is null. A falsy check is // more reliable in real world use-cases. if (!children) { children = defaultChildren$2; } var props = _extends({}, restProps, { allowCreate: true, filterOptions: this.filterOptions, menuRenderer: this.menuRenderer, onInputChange: this.onInputChange, onInputKeyDown: this.onInputKeyDown, ref: function ref(_ref2) { _this2.select = _ref2; // These values may be needed in between Select mounts (when this.select is null) if (_ref2) { _this2.labelKey = _ref2.props.labelKey; _this2.valueKey = _ref2.props.valueKey; } if (refProp) { refProp(_ref2); } } }); return children(props); } }]); return CreatableSelect; }(React.Component); var defaultChildren$2 = function defaultChildren(props) { return React.createElement(Select$1, props); }; var isOptionUnique = function isOptionUnique(_ref3) { var option = _ref3.option, options = _ref3.options, labelKey = _ref3.labelKey, valueKey = _ref3.valueKey; if (!options || !options.length) { return true; } return options.filter(function (existingOption) { return existingOption[labelKey] === option[labelKey] || existingOption[valueKey] === option[valueKey]; }).length === 0; }; var isValidNewOption = function isValidNewOption(_ref4) { var label = _ref4.label; return !!label; }; var newOptionCreator = function newOptionCreator(_ref5) { var label = _ref5.label, labelKey = _ref5.labelKey, valueKey = _ref5.valueKey; var option = {}; option[valueKey] = label; option[labelKey] = label; option.className = 'Select-create-option-placeholder'; return option; }; var promptTextCreator = function promptTextCreator(label) { return 'Create option "' + label + '"'; }; var shouldKeyDownEventCreateNewOption = function shouldKeyDownEventCreateNewOption(_ref6) { var keyCode = _ref6.keyCode; switch (keyCode) { case 9: // TAB case 13: // ENTER case 188: // COMMA return true; default: return false; } }; // Default prop methods CreatableSelect.isOptionUnique = isOptionUnique; CreatableSelect.isValidNewOption = isValidNewOption; CreatableSelect.newOptionCreator = newOptionCreator; CreatableSelect.promptTextCreator = promptTextCreator; CreatableSelect.shouldKeyDownEventCreateNewOption = shouldKeyDownEventCreateNewOption; CreatableSelect.defaultProps = { filterOptions: filterOptions, isOptionUnique: isOptionUnique, isValidNewOption: isValidNewOption, menuRenderer: menuRenderer, newOptionCreator: newOptionCreator, promptTextCreator: promptTextCreator, shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption }; CreatableSelect.propTypes = { // Child function responsible for creating the inner Select component // This component can be used to compose HOCs (eg Creatable and Async) // (props: Object): PropTypes.element children: PropTypes.func, // See Select.propTypes.filterOptions filterOptions: PropTypes.any, // Searches for any matching option within the set of options. // This function prevents duplicate options from being created. // ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean isOptionUnique: PropTypes.func, // Determines if the current input text represents a valid option. // ({ label: string }): boolean isValidNewOption: PropTypes.func, // See Select.propTypes.menuRenderer menuRenderer: PropTypes.any, // Factory to create new option. // ({ label: string, labelKey: string, valueKey: string }): Object newOptionCreator: PropTypes.func, // input change handler: function (inputValue) {} onInputChange: PropTypes.func, // input keyDown handler: function (event) {} onInputKeyDown: PropTypes.func, // new option click handler: function (option) {} onNewOptionClick: PropTypes.func, // See Select.propTypes.options options: PropTypes.array, // Creates prompt/placeholder option text. // (filterText: string): string promptTextCreator: PropTypes.func, ref: PropTypes.func, // Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option. shouldKeyDownEventCreateNewOption: PropTypes.func }; var AsyncCreatableSelect = function (_React$Component) { inherits(AsyncCreatableSelect, _React$Component); function AsyncCreatableSelect() { classCallCheck(this, AsyncCreatableSelect); return possibleConstructorReturn(this, (AsyncCreatableSelect.__proto__ || Object.getPrototypeOf(AsyncCreatableSelect)).apply(this, arguments)); } createClass(AsyncCreatableSelect, [{ key: 'focus', value: function focus() { this.select.focus(); } }, { key: 'render', value: function render() { var _this2 = this; return React.createElement( Async, this.props, function (_ref) { var ref = _ref.ref, asyncProps = objectWithoutProperties(_ref, ['ref']); var asyncRef = ref; return React.createElement( CreatableSelect, asyncProps, function (_ref2) { var ref = _ref2.ref, creatableProps = objectWithoutProperties(_ref2, ['ref']); var creatableRef = ref; return _this2.props.children(_extends({}, creatableProps, { ref: function ref(select) { creatableRef(select); asyncRef(select); _this2.select = select; } })); } ); } ); } }]); return AsyncCreatableSelect; }(React.Component); var defaultChildren$1 = function defaultChildren(props) { return React.createElement(Select$1, props); }; AsyncCreatableSelect.propTypes = { children: PropTypes.func.isRequired // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element }; AsyncCreatableSelect.defaultProps = { children: defaultChildren$1 }; Select$1.Async = Async; Select$1.AsyncCreatable = AsyncCreatableSelect; Select$1.Creatable = CreatableSelect; Select$1.Value = Value; Select$1.Option = Option; export { Async, AsyncCreatableSelect as AsyncCreatable, CreatableSelect as Creatable, Value, Option, menuRenderer as defaultMenuRenderer, arrowRenderer as defaultArrowRenderer, clearRenderer as defaultClearRenderer, filterOptions as defaultFilterOptions }; export default Select$1;
examples/js/selection/hide-selection-col-table.js
opensourcegeek/react-bootstrap-table
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function addProducts(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item name " + id, price: 2100 + i }); } } addProducts(5); var selectRowProp = { mode: "checkbox", bgColor: "pink", //you should give a bgcolor, otherwise, you can't regonize which row has been selected hideSelectColumn: true, //enable hide selection column. clickToSelect: true //you should enable clickToSelect, otherwise, you can't select column. }; export default class HideSelectionColumnTable extends React.Component{ render(){ return ( <BootstrapTable data={products} selectRow={selectRowProp}> <TableHeaderColumn dataField="id" isKey={true}>Product ID</TableHeaderColumn> <TableHeaderColumn dataField="name">Product Name</TableHeaderColumn> <TableHeaderColumn dataField="price">Product Price</TableHeaderColumn> </BootstrapTable> ); } };
src/SafeAnchor.js
apkiernan/react-bootstrap
import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; const propTypes = { href: React.PropTypes.string, onClick: React.PropTypes.func, disabled: React.PropTypes.bool, role: React.PropTypes.string, tabIndex: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string, ]), /** * this is sort of silly but needed for Button */ componentClass: elementType, }; const defaultProps = { componentClass: 'a', }; function isTrivialHref(href) { return !href || href.trim() === '#'; } /** * There are situations due to browser quirks or Bootstrap CSS where * an anchor tag is needed, when semantically a button tag is the * better choice. SafeAnchor ensures that when an anchor is used like a * button its accessible. It also emulates input `disabled` behavior for * links, which is usually desirable for Buttons, NavItems, MenuItems, etc. */ class SafeAnchor extends React.Component { constructor(props, context) { super(props, context); this.handleClick = this.handleClick.bind(this); } handleClick(event) { const { disabled, href, onClick } = this.props; if (disabled || isTrivialHref(href)) { event.preventDefault(); } if (disabled) { event.stopPropagation(); return; } if (onClick) { onClick(event); } } render() { const { componentClass: Component, disabled, ...props } = this.props; if (isTrivialHref(props.href)) { props.role = props.role || 'button'; // we want to make sure there is a href attribute on the node // otherwise, the cursor incorrectly styled (except with role='button') props.href = props.href || '#'; } if (disabled) { props.tabIndex = -1; props.style = { pointerEvents: 'none', ...props.style }; } return ( <Component {...props} onClick={this.handleClick} /> ); } } SafeAnchor.propTypes = propTypes; SafeAnchor.defaultProps = defaultProps; export default SafeAnchor;
src/js/pages/ResetPasswordPage.js
bikebaba/XcomponentsStormpath
import React from 'react'; import DocumentTitle from 'react-document-title'; import { ResetPasswordForm } from 'react-stormpath'; export default class ResetPasswordPage extends React.Component { render() { return ( <DocumentTitle title={`Login`}> <div className="container"> <div className="row"> <div className="col-xs-12"> <h3>Forgot Password</h3> <hr /> </div> </div> <ResetPasswordForm /> </div> </DocumentTitle> ); } }
src/svg-icons/image/collections.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCollections = (props) => ( <SvgIcon {...props}> <path d="M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2zm-11-4l2.03 2.71L16 11l4 5H8l3-4zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6H2z"/> </SvgIcon> ); ImageCollections = pure(ImageCollections); ImageCollections.displayName = 'ImageCollections'; ImageCollections.muiName = 'SvgIcon'; export default ImageCollections;
src/shared/components/socialMedia/socialMediaContainer/socialMediaContainer.js
tskuse/operationcode_frontend
import React from 'react'; import PropTypes from 'prop-types'; import styles from './socialMediaContainer.css'; const SocialMediaContainer = ({ children }) => ( <div className={styles.socialMediaContainer}> {children} </div> ); SocialMediaContainer.propTypes = { children: PropTypes.arrayOf(PropTypes.element).isRequired }; export default SocialMediaContainer;
src/app.js
juliogreff/1001places
import React from 'react'; import ReactDOM from 'react-dom'; import createLogger from 'redux-logger'; import fetch from 'isomorphic-fetch'; import thunk from 'redux-thunk'; import { Provider } from 'react-redux'; import { Router } from 'director'; import { applyMiddleware, createStore, compose } from 'redux'; import * as creators from './actions'; import App from './comp/app'; import appReducer from './reducers/app'; import styles from './app.css'; // debug stuff import Devtools from './comp/devtools'; var logger = createLogger({ collapsed: true }) , createStoreWithMiddleware = compose( applyMiddleware(thunk, logger), Devtools.instrument() )(createStore) , store = createStoreWithMiddleware(appReducer) , defaultLocations = ['bled', 'sintra', 'bruges', 'reykjavik', 'tromso', 'svalbard'] ; if (module.hot) { module.hot.accept('./reducers/app', () => { return store.replaceReducer(require('./reducers/app').default); }); } ReactDOM.render( <Provider store={store}> <div className={styles.fullHeight}> <App /> <Devtools /> </div> </Provider>, document.querySelector('#app') ); // initialize list of default locations for (var q of defaultLocations) { store.dispatch(creators.requestLocationInfo(q)); }
client/src/components/ResetPasswordForm.js
richb-hanover/reactathon
import React from 'react'; import ajax from 'superagent'; import { Link } from 'react-router'; import { FormErrors } from './partials'; import { AppActions } from '../actions/AppActions'; import { Input, ButtonInput } from 'react-bootstrap'; export class ResetPasswordForm extends React.Component { constructor() { super(); this.state = { newPassword: '', processing: false, passwordReset: false, errors: [] }; } handleInputChange = (e => this.setState( {newPassword: e.target.value}) ); validate = () => { var errors = []; var { newPassword } = this.state; const rules = [ { failOn: newPassword.trim().length < 5, error: 'Password must be at least 5 characters' } ]; rules.forEach((rule) => { if (rule.failOn) { errors.push(rule); } }); if (errors.length) { return { errors: errors, valid: false }; } else { return { errors: null, valid: true }; } }; handleSubmit = (e) => { let newPassword = this.state.newPassword; e.preventDefault(); var valid = this.validate(); if (valid.errors) { let article = valid.errors.length > 1 ? 'are' : 'is'; let noun = valid.errors.length > 1 ? 'errors' : 'error'; let count = valid.errors.length > 1 ? valid.errors.length : 'one'; this.setState({ error: { processing: false, message: `There ${article} ${count} ${noun}, please try again.`, data: valid.errors } }); return; } this.setState({ processing: true }); ajax.post('/api/reset') .send({password: newPassword}) .end((err, res) => { if (err || res.text !== 'ok') { AppActions.toast({ level: 'error', title: 'Server Error', message: 'Password reset token is invalid or has expired.' }); this.context.router.push('/reset'); } AppActions.toast({ level: 'success', title: 'Success', message: 'Your password has been changed.' }); this.setState({ passwordReset: true }); }); }; render() { let { processing, passwordReset, error, newPassword } = this.state; if (passwordReset) { return ( <div style={{padding: '2em'}}> <p> Password successfully reset. </p> <p><Link to="/login">Go Login</Link></p> </div> ); } else { return ( <form onSubmit={this.handleSubmit}> {error ? <FormErrors {...error} /> : ''} <fieldset> <legend> Reset Password </legend> <p> <span>Enter a new password:</span> </p> <Input required type="password" onChange={this.handleInputChange} value={newPassword} placeholder="New Password"/> <ButtonInput disabled={processing} bsStyle="primary" type="submit"> Change Password </ButtonInput> </fieldset> </form> ); } } } ResetPasswordForm.contextTypes = { router: React.PropTypes.object.isRequired };
app/scripts/main.js
rgee/Game-Editor
import React from 'react'; import ReactDOM from 'react-dom'; import AuthActions from './actions/authActions'; import Main from './components/Main'; import Store from './store'; import injectTapEventPlugin from 'react-tap-event-plugin'; /*! * * Web Starter Kit * Copyright 2015 Google Inc. All rights reserved. * * 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 * * https://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 * */ /* eslint-env browser */ (function() { 'use strict'; // Check to make sure service workers are supported in the current browser, // and that the current page is accessed from a secure origin. Using a // service worker from an insecure origin will trigger JS console errors. See // http://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features var isLocalhost = Boolean(window.location.hostname === 'localhost' || // [::1] is the IPv6 localhost address. window.location.hostname === '[::1]' || // 127.0.0.1/8 is considered localhost for IPv4. window.location.hostname.match( /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) ); if ('serviceWorker' in navigator && (window.location.protocol === 'https:' || isLocalhost)) { navigator.serviceWorker.register('service-worker.js') .then(function(registration) { // Check to see if there's an updated version of service-worker.js with // new files to cache: // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-registration-update-method if (typeof registration.update === 'function') { registration.update(); } // updatefound is fired if service-worker.js changes. registration.onupdatefound = function() { // updatefound is also fired the very first time the SW is installed, // and there's no need to prompt for a reload at that point. // So check here to see if the page is already controlled, // i.e. whether there's an existing service worker. if (navigator.serviceWorker.controller) { // The updatefound event implies that registration.installing is set: // https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event var installingWorker = registration.installing; installingWorker.onstatechange = function() { switch (installingWorker.state) { case 'installed': // At this point, the old content will have been purged and the // fresh content will have been added to the cache. // It's the perfect time to display a "New content is // available; please refresh." message in the page's interface. break; case 'redundant': throw new Error('The installing ' + 'service worker became redundant.'); default: // Ignore } }; } }; }).catch(function(e) { console.error('Error during service worker registration:', e); }); } // Needed for onTouchTap // Check this repo: // https://github.com/zilverline/react-tap-event-plugin injectTapEventPlugin(); Store.dispatch(AuthActions.listenToAuth()); ReactDOM.render(React.createElement(Main), document.getElementById('root')); })();
app/components/Box/Box.js
celikmus/MathWise
import React, { Component } from 'react'; import { Text, View, Animated, PanResponder, LayoutAnimation } from 'react-native'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { addOperand, removeOperand } from '../../actions/interactions'; import styles from './styles'; class Box extends Component { constructor(props) { super(props); this.state = { dragging: false, initialTop: props.initCoords[props.boxId].y, initialLeft: props.initCoords[props.boxId].x, offsetTop: 0, offsetLeft: 0 }; } static propTypes = { dropZones: PropTypes.array.isRequired, value: PropTypes.number.isRequired, boxId: PropTypes.number, initCoords: PropTypes.array, resetting: PropTypes.bool }; panResponder = {}; componentWillMount() { this.panResponder = PanResponder.create({ onStartShouldSetPanResponder: this.handleStartShouldSetPanResponder, onPanResponderGrant: this.handlePanResponderGrant, onPanResponderMove: this.handlePanResponderMove, onPanResponderRelease: this.handlePanResponderRelease, onPanResponderTerminate: this.handlePanResponderEnd }); } componentWillReceiveProps(nextProps) { const { resetting, boxId, initCoords } = nextProps; if (resetting) { this.setState({ initialTop: initCoords[boxId].y, initialLeft: initCoords[boxId].x }); } } componentWillUpdate() { LayoutAnimation.spring(); } getDropZone(gesture) { const { dropZones } = this.props; const zone = dropZones.find( z => gesture.moveY > z.layout.y - styles.$boxBuffer && gesture.moveY < z.layout.y + styles.$boxBuffer + z.layout.height && gesture.moveX > z.layout.x - styles.$boxBuffer && gesture.moveX < z.layout.x + styles.$boxBuffer + z.layout.width ); return zone; } handleStartShouldSetPanResponder = () => true; handlePanResponderGrant = (evt, gesture) => { this.setState({ dragging: true }); }; handlePanResponderMove = (e, gestureState) => { const zone = this.getDropZone(gestureState); const { dispatch } = this.props; if (zone && zone.isEmpty) { this.setState({ dragging: true, offsetTop: gestureState.dy, offsetLeft: gestureState.dx }); } else { // done --> drag to anywhere this.setState((prevState, props) => ({ dragging: true, offsetTop: gestureState.dy, offsetLeft: gestureState.dx })); } }; handlePanResponderRelease = (e, gesture) => { const zone = this.getDropZone(gesture); const hasMoved = gesture.dx || gesture.dy; const { dispatch, dropZones } = this.props; if (zone && hasMoved && zone.isEmpty) { this.setState(() => ({ dragging: false, initialTop: zone.layout.y - styles.$containerHeight, initialLeft: zone.layout.x, offsetTop: 0, offsetLeft: 0 })); dispatch(addOperand(zone.zoneId, this.props.boxId, this.props.value)); } else { // done --> put back to init place this.setState({ dragging: false, initialTop: this.props.initCoords[this.props.boxId].y, initialLeft: this.props.initCoords[this.props.boxId].x, offsetTop: 0, offsetLeft: 0 }); const vacatedZone = dropZones.filter( z => z.boxId === this.props.boxId )[0]; vacatedZone && dispatch(removeOperand(vacatedZone.zoneId)); } }; handlePanResponderEnd = () => true; render() { const { dragging, initialTop, initialLeft, offsetTop, offsetLeft } = this.state; const style = { backgroundColor: dragging ? styles.$draggingBackground : styles.$backgroundColor, top: initialTop + offsetTop, left: initialLeft + offsetLeft }; const { initCoords, boxId } = this.props; return ( <View> { <View style={[ styles.emptySquare, { top: initCoords[boxId].y, left: initCoords[boxId].x } ]} /> } <Animated.View {...this.panResponder.panHandlers} style={[styles.square, style]} > <Text style={styles.text}> {this.props.value} </Text> </Animated.View> </View> ); } } const select = (state, props) => { return { dropZones: state.interactions.dropZones, initCoords: state.interactions.initCoords, resetting: state.interactions.resetting }; }; export default connect(select)(Box);
assets/js/components/Home.js
nicksergeant/leather
import Footer from './Footer'; import React from 'react'; const Home = () => { return ( <div> <div className="container is-fluid"> <div className="columns is-mobile is-centered" style={{ margin: '50px 0 60px 0' }} > <article className="message"> <div className="message-body" style={{ textAlign: 'center' }}> <p>Let's do this. 🎉</p> <br /> <a className="button" href="/login"> Login </a> <br /> <br /> <a className="button" href="/signup"> Signup </a> </div> </article> </div> </div> <Footer /> </div> ); }; Home.propTypes = {}; export default Home;
app/client.js
osenvosem/react-mobx-boilerplate
import { AppContainer } from 'react-hot-loader'; import React from 'react'; import { render } from 'react-dom'; import { Router, browserHistory } from 'react-router'; import routes from './routes'; const rootEl = document.getElementById('root'); render( <AppContainer> <Router routes={routes} history={browserHistory} key={process.env.NODE_ENV !== "production" ? Math.random() : false} /> </AppContainer>, rootEl ); if (module.hot) { module.hot.accept('./routes', () => { // If you use Webpack 2 in ES modules mode, you can // use <App /> here rather than require() a <NextApp />. const routes = require('./routes').default; render( <AppContainer> <Router routes={routes} history={browserHistory} key={process.env.NODE_ENV !== "production" ? Math.random() : false} /> </AppContainer>, rootEl ); }); }
src/components/Authentication.js
nunoblue/ts-react
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; class Authentication extends Component { static propTypes = { mode: PropTypes.bool, onLogin: PropTypes.func, onRegister: PropTypes.func, } static defaultProps = { mode: true, onLogin: () => { }, onRegister: () => { }, } state = { username: '', password: '', } handleChange = (e) => { const nextState = {}; nextState[e.target.name] = e.target.value; this.setState(nextState); } handleLogin = () => { const id = this.state.username; const pw = this.state.password; this.props.onLogin(id, pw).then((success) => { if (!success) { console.log('test1'); this.setState({ password: '', }); } }); } handleRegister = () => { const id = this.state.username; const pw = this.state.password; this.props.onRegister(id, pw).then((result) => { if (!result) { this.setState({ username: '', password: '', }); } }); } handleKeyPress = (e) => { if (e.charCode === 13) { if (this.props.mode) { this.handleLogin(); } else { this.handleRegister(); } } } render() { const inputBoxes = ( <div> <div className="input-field col s12 username"> <label>Username</label> <input name="username" type="text" className="validate" onChange={this.handleChange} value={this.state.username} /> </div> <div className="input-field col s12"> <label>Password</label> <input name="password" type="password" className="validate" onChange={this.handleChange} value={this.state.password} onKeyPress={this.handleKeyPress} /> </div> </div> ); const loginView = ( <div> <div className="card-content"> <div className="row"> {inputBoxes} <a className="waves-effect waves-light btn" onClick={this.handleLogin}>SUBMIT</a> </div> </div> <div className="footer"> <div className="card-content"> <div className="right" > New Here? <Link to="/register">Create an account</Link> </div> </div> </div> </div> ); const registerView = ( <div className="card-content"> <div className="row"> {inputBoxes} <a className="waves-effect waves-light btn" onClick={this.handleRegister}>CREATE</a> </div> </div> ); return ( <div className="auth"> <div className="card"> <div className="header blue white-text center"> <div className="card-content">{this.props.mode ? 'LOGIN' : 'REGISTER'}</div> </div> {this.props.mode ? loginView : registerView } </div> </div> ); } } export default Authentication;
client/src/components/LoginForm.js
richb-hanover/reactathon
import React from 'react'; import { Link } from 'react-router'; import { FormErrors } from './partials'; import { Center, LoginWith } from './partials/Elements'; import { Button, Input, ButtonInput } from 'react-bootstrap'; import { AppActions } from '../actions/AppActions'; import { AppStore } from '../stores/AppStore'; export class LoginForm extends React.Component { constructor() { super(); this.state = { ...AppStore.getState(), username: '', password: '' }; this.onChange = this.onChange.bind(this); } componentDidMount() { AppStore.listen(this.onChange); } componentWillUnmount() { AppStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } clearState = () => { this.setState({ username: '', password: '' }); }; handleForgotPasswordClick = () => { AppActions.hideLoginModal(); }; handleUsernameChange = (e => this.onChange( {username: e.target.value}) ); handlePasswordChange = (e => this.onChange( {password: e.target.value}) ); validate = () => { var errors = []; var { username, password } = this.state; const rules = [ { failOn: username.trim().length < 4, error: 'Username must be at least 4 characters' }, { failOn: password.trim().length < 5, error: 'Password must be at least 5 characters' } ]; rules.forEach((rule) => { if (rule.failOn) { errors.push(rule); } }); if (errors.length) { return { errors: errors, valid: false }; } else { return { errors: null, valid: true }; } }; handleSubmit = (e) => { e.preventDefault(); var valid = this.validate(); if (valid.errors) { let article = valid.errors.length > 1 ? 'are' : 'is'; let noun = valid.errors.length > 1 ? 'errors' : 'error'; let count = valid.errors.length > 1 ? valid.errors.length : 'one'; this.setState({ error: { message: `There ${article} ${count} ${noun}, please try again.`, data: valid.errors } }); return; } AppActions.login({ username: this.state.username, password: this.state.password }); }; render() { // handlers let { handleSubmit, handleUsernameChange, handlePasswordChange, handleForgotPasswordClick } = this; // state let { error, username, password } = this.state; return ( <section> {error ? <FormErrors {...error} /> : ''} <form onSubmit={handleSubmit}> <Center><h4>Login with social account</h4></Center> <hr/> <LoginWith github/> <LoginWith reddit/> <LoginWith google/> <LoginWith twitter/> <LoginWith facebook/> <Center><h4>Sign in with local account</h4></Center> <hr/> <Input disabled={this.state.loginPending} type="text" label="Username" value={username} onChange={handleUsernameChange} placeholder="Enter a username" /> <Input disabled={this.state.loginPending} type="password" value={password} onChange={handlePasswordChange} label="Password" /> {this.state.signupPending ? <Button disabled>Signing up...</Button> : <ButtonInput bsStyle="success" type="submit" value="Login" /> } <Link onClick={handleForgotPasswordClick} to={{ pathname: '/reset' }}> Forgot your password? </Link> </form> </section> ); } }
src/screens/homeScreen.js
markup-app/markup
'use strict'; import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import Banner from '../components/banner'; import AppBody from '../components/appBody'; import DocumentTextSection from '../components/documentTextSection'; import Button from '../components/button'; import * as DocumentActions from '../actions/documentActions'; import * as GeneralActions from '../actions/generalActions'; import Typed from 'typed-lite'; import router from '../router'; const defaultText = `markup ------ > Create & share TeX snippets with rich math typesetting and markdown support. Supports _math_ **typesetting** like $T(n) = \\Theta (n^2)$ and markdown ~~stuff~~ features. $ f(x) = \\int_{-\\infty}^\\infty\\hat f(\\xi)\\,e^{2 \\pi i \\xi x}\\,d\\xi $`; class HomeScreen extends React.Component { constructor (props) { super(props); this.typedText = null; } componentWillMount () { this.props.documentActions.updateText(defaultText); } componentDidMount () { var nodeDOM = document.querySelector('.-dynamic-typing-area'); this.typedText = new Typed(nodeDOM, { words: ['meaningful', 'beautiful', 'powerful', 'interesting', 'unique', 'wonderful', 'radical', 'sincere', 'organic'], startDelay: 3000, timing: 65, backTiming: 40, pause: 2500, typoProbability: .05, maxTypos: 1, loop: true }); this.typedText.start(); } openInNewTab (url) { var win = window.open(url, '_blank'); win.focus(); } routeToEdit () { this.props.generalActions.unloadPage(); setTimeout(() => { router.navigate('/edit', {trigger: true}); // Slight toggle to make sure the CSS animation actually renders setTimeout(() => { this.props.generalActions.loadPage(); }, 1); }, 275); } render() { return ( <AppBody> {/* LANDING BLOCK */} <div className="-homepage-landing-block"> {/* Header */} <h1 className="-banner-title noselect">markup</h1> <h2 className="-banner-sub-title noselect"> Write something&nbsp; <span className="-dynamic-typing-area">meaningful</span> </h2> {/* Interactive example */} <div className="-landing-example-container"> <Button label={'Create a new document'} onClick={() => this.routeToEdit()} /> <div className="-landing-example-document-container"> <DocumentTextSection uniqueId={'home'} style={{float:'left'}} editable={true} text={defaultText} /> <DocumentTextSection uniqueId={'home'} style={{float:'right'}} editable={false} text={this.props.text} /> </div> </div> {/* SVG footer */} <div className="-landing-header-bottom-curve"> <CurveComponent /> </div> </div> {/* Left Sample Container */} <div className="section-with-side-sample-container"> {/* Left Sample */} <div className="section-with-left-side-sample"> <div className="-left-side"> <img src="/img/samples/sample.png" /> </div> <div className="-right-side"> <h1>Powered by KaTeX, the Fastest Math Typesetting Library on the Web</h1> <p>KaTeX renders its math synchronously and doesn’t need to reflow the page, and the layout is based on Donald Knuth’s TeX, the gold standard for math typesetting.</p> </div> </div> {/* SVG footer */} <div className="-landing-header-bottom-curve-inverted"> <CurveComponent color='#fff' /> </div> </div> {/* Right Sample Container */} <div className="section-with-side-sample-container"> {/* Right Sample */} <div className="section-with-right-side-sample"> <div className="-left-side"> <h1>Combine Markdown with KaTeX to Produce Rich Documents</h1> <p>Not only do we parse and compile KaTeX in real time, we also support markdown! You can freely combine the two formats seemlessly together and have them compile in real time as you type. </p> </div> <div className="-right-side"> <img src="/img/samples/sample.png" /> </div> </div> {/* SVG footer */} <div className="-landing-header-bottom-curve"> <CurveComponent /> </div> </div> <div className="homepage-footer"> <p>Made with ❤︎ by <a href="https://nickzuber.com/">Nick Zuber</a> and <a href="https://github.com/markup-app/markup/graphs/contributors">contributors</a></p> <a href="https://github.com/markup-app/markup">Github</a>&nbsp;∙&nbsp; <a href="https://github.com/markup-app/markup/issues">Report Issue</a>&nbsp;∙&nbsp; <a href="https://twitter.com/nick_zuber">Contact</a> </div> </AppBody> ); } }; const CurveComponent = ({color, ...props}) => <svg preserveAspectRatio="none" width="54" height="14" viewBox="0 0 54 14" version="1.1" xmlns="http://www.w3.org/2000/svg"> <path fill={color || '#02b875'} d="M 27 10C 21 12 14 14 0 14L 0 0L 54 0L 54 3C 40 3 33 8 27 10Z"></path> </svg> const actions = (dispatch) => ({ documentActions: bindActionCreators(DocumentActions, dispatch), generalActions: bindActionCreators(GeneralActions, dispatch) }); const selector = (state) => ({ text: state.document.text }); export default connect(selector, actions)(HomeScreen); // {/* Sample posts section */} // <div className="-all-samples-container"> // {/* One sample */} // <div className="-sample-container"> // <DocumentTextSection // uniqueId={'sample1'} // style={{ // width: '500px', // padding: '20px 30px' // }} // editable={false} // text={defaultText} // /> // </div> // {/* Two sample */} // <div className="-sample-container"> // <DocumentTextSection // uniqueId={'sample2'} // style={{ // width: '500px', // padding: '20px 30px' // }} // editable={false} // text={defaultText} // /> // </div> // {/* Three sample */} // <div className="-sample-container"> // <DocumentTextSection // uniqueId={'sample3'} // style={{ // width: '500px', // padding: '20px 30px' // }} // editable={false} // text={defaultText} // /> // </div> // </div>
CreateButtons.js
alangpierce/LambdaCalculusPlayground
/** * @flow */ 'use strict'; import React from 'react'; import { ToastAndroid, View, } from 'react-native'; import DialogAndroid from 'react-native-dialogs'; import FloatingActionButton from './FloatingActionButton'; import StatelessComponent from './StatelessComponent'; import store from './store'; import * as t from './types'; type CreateButtonsProps = { } export default class CreateButtons extends StatelessComponent<CreateButtonsProps> { shouldComponentUpdate() { return false; } handleCreateLambda() { const dialog = new DialogAndroid(); dialog.set({ title: 'Choose a variable name', positiveText: 'OK', negativeText: 'Cancel', input: { allowEmptyInput: false, callback: (varName) => { const error = checkDefNameErrors(varName); if (error != null) { ToastAndroid.show(error, ToastAndroid.SHORT); } else { store.dispatch(t.AddExpression.make( t.CanvasExpression.make( t.UserLambda.make(varName, null), t.CanvasPoint.make(100, 100)) )); } }, } }); dialog.show(); } handleCreateDefinition() { const dialog = new DialogAndroid(); dialog.set({ title: 'Create or show definition', positiveText: 'OK', negativeText: 'Cancel', input: { allowEmptyInput: false, type: 0x00001000, // InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS callback: (defName) => { const error = checkDefNameErrors(defName); if (error != null) { ToastAndroid.show(error, ToastAndroid.SHORT) } else { store.dispatch(t.PlaceDefinition.make( defName, t.ScreenPoint.make(100, 100), )); } }, } }); dialog.show(); } render() { return <View style={{ flexDirection: 'row', position: 'absolute', right: 0, bottom: 0, }} > <FloatingActionButton onPress={this.handleCreateLambda.bind(this)} source={require('./img/lambda.png')} style={{ marginRight: 24, marginBottom: 24, }} /> <FloatingActionButton onPress={this.handleCreateDefinition.bind(this)} source={require('./img/definition.png')} style={{ marginRight: 24, marginBottom: 24, }} /> </View>; } }; const isLowerCase = (letter: string): boolean => { return letter !== letter.toUpperCase(); }; /** * Returns an error message if the variable name is invalid, or null if the name * is valid. */ const checkVarNameErrors = (varName: string): ?string => { if (varName.length > 8) { return 'Variable names can only be up to 8 letters long.'; } for (let i = 0; i < varName.length; i++) { if (!isLowerCase(varName[i])) { return 'Variable names can only contain lower-case letters.'; } } return null; }; /** * Returns an error message if the definition name is invalid, or null if the * name is valid. */ const checkDefNameErrors = (defName: string): ?string => { if (defName.length > 8) { return 'Definition names can only be up to 8 letters long.'; } for (let i = 0; i < defName.length; i++) { if (isLowerCase(defName[i])) { return 'Definition names can only contain capital letters and symbols.'; } } return null; };
src/admin/views/navigation/teams.js
ccetc/platform
import React from 'react' import { connect } from 'react-redux' import * as actions from './actions' import { getActiveTeam } from 'admin/components/admin/selectors' import Logo from 'admin/components/logo' class Teams extends React.Component { static contextTypes = { admin: React.PropTypes.object, drawer: React.PropTypes.object, history: React.PropTypes.object } static propTypes = { team: React.PropTypes.object, teams: React.PropTypes.array } render() { const { sessions, team, teams } = this.props return ( <div className="chrome-navigation-panel"> <div className="chrome-navigation-header"> <div className="chrome-navigation-header-back"> <Logo team={ team } width="50" /> </div> <div className="chrome-navigation-header-team"> Manage Teams </div> <div className="chrome-navigation-header-next" onClick={ this._handleToggleMode.bind(this) }> <i className="chevron down icon" /> </div> </div> <div className="chrome-navigation-body"> <div className="chrome-navigation-teams"> { teams.map((team, index) => { return ( <div key={`team_${index}`}className="chrome-navigation-team"> <div className="chrome-navigation-team-logo" onClick={ this._handleChangeTeam.bind(this, index) }> <Logo team={ team } width="30" /> { sessions[team.id] && sessions[team.id].user.unread > 0 && <div className="chrome-navigation-team-label">{ sessions[team.id].user.unread }</div> } </div> <div className="chrome-navigation-team-title" onClick={ this._handleChangeTeam.bind(this, index) }> { team.title } </div> </div> ) })} </div> <div className="chrome-navigation-team-add" onClick={ this._handleAddTeam.bind(this) }> <div className="chrome-navigation-team-add-button"> <div className="chrome-navigation-team-add-button-image"> <i className="icon plus" /> </div> </div> <div className="chrome-navigation-team-add-text"> Add team </div> </div> </div> </div> ) } _handleToggleMode() { this.props.onToggleMode() } _handleChangeTeam(index) { const { onToggleMode } = this.props this.context.admin.chooseTeam(index) this.context.drawer.close() this.context.history.reset({ pathname: '/admin' }) window.setTimeout(function() { onToggleMode() }, 500) } _handleAddTeam() { this.context.drawer.close() this.context.history.push({ pathname: '/admin/signin' }) } _handleSignout(index) { if(this.props.teams.length === 1) { this.context.drawer.close() window.setTimeout(() => { this.context.admin.removeTeam(index) }, 100) } else { this.context.admin.removeTeam(index) } } } const mapStateToProps = (state, props) => ({ sessions: state.admin.sessions, team: getActiveTeam(state), teams: state.admin.teams }) const mapDispatchToProps = { onReset: actions.toggleMode, onToggleMode: actions.toggleMode } export default connect(mapStateToProps, mapDispatchToProps)(Teams)
docs/src/app/components/pages/components/Tabs/ExampleSwipeable.js
ArcanisCz/material-ui
import React from 'react'; import {Tabs, Tab} from 'material-ui/Tabs'; // From https://github.com/oliviertassinari/react-swipeable-views import SwipeableViews from 'react-swipeable-views'; const styles = { headline: { fontSize: 24, paddingTop: 16, marginBottom: 12, fontWeight: 400, }, slide: { padding: 10, }, }; export default class TabsExampleSwipeable extends React.Component { constructor(props) { super(props); this.state = { slideIndex: 0, }; } handleChange = (value) => { this.setState({ slideIndex: value, }); }; render() { return ( <div> <Tabs onChange={this.handleChange} value={this.state.slideIndex} > <Tab label="Tab One" value={0} /> <Tab label="Tab Two" value={1} /> <Tab label="Tab Three" value={2} /> </Tabs> <SwipeableViews index={this.state.slideIndex} onChangeIndex={this.handleChange} > <div> <h2 style={styles.headline}>Tabs with slide effect</h2> Swipe to see the next slide.<br /> </div> <div style={styles.slide}> slide n°2 </div> <div style={styles.slide}> slide n°3 </div> </SwipeableViews> </div> ); } }
src/components/eventplanner/Week.js
f0zze/rosemary-ui
import React from 'react'; import dates from './utils/dates'; import localizer from './localizer'; import { navigate } from './utils/constants'; import TimeGrid from './TimeGrid'; const PROPERTY_TYPES = TimeGrid.propTypes; const DEFAULT_PROPS = TimeGrid.defaultProps; class Week extends React.Component { constructor(props) { super(props); } render() { let { date } = this.props; let { start, end } = Week.range(date, this.props); return ( <TimeGrid {...this.props} start={start} end={end} eventOffset={15}/> ); } } Week.navigate = (date, action) => { switch (action) { case navigate.PREVIOUS: return dates.add(date, -1, 'week'); case navigate.NEXT: return dates.add(date, 1, 'week'); default: return date; } }; Week.range = (date, { culture }) => { let firstOfWeek = localizer.startOfWeek(culture); let start = dates.startOf(date, 'week', firstOfWeek); let end = dates.endOf(date, 'week', firstOfWeek); return { start, end }; }; Week.propTypes = PROPERTY_TYPES; Week.defaultProps = DEFAULT_PROPS; export default Week;
src/client/components/nav-menu/nav-menu-list.js
adamgruber/mochawesome-report-generator
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import isEqual from 'lodash/isEqual'; import { NavMenuItem } from 'components/nav-menu'; import classNames from 'classnames/bind'; import styles from './nav-menu.css'; const cx = classNames.bind(styles); class NavMenuList extends Component { static propTypes = { suites: PropTypes.array, showPassed: PropTypes.bool, showFailed: PropTypes.bool, showPending: PropTypes.bool, showSkipped: PropTypes.bool, }; shouldComponentUpdate(nextProps) { return !isEqual(this.props, nextProps); } render() { const { suites, showPassed, showFailed, showPending, showSkipped, } = this.props; const navItemProps = { showPassed, showFailed, showPending, showSkipped }; return ( !!suites && ( <div> {suites.map(subSuite => ( <ul key={subSuite.uuid} className={cx('list', 'sub')}> <NavMenuItem suite={subSuite} {...navItemProps} /> </ul> ))} </div> ) ); } } export default NavMenuList;
app/js/components/footer.js
pauloelias/simple-webpack-react
import React from 'react'; export default class Footer extends React.Component { render() { const currentYear = new Date().getFullYear(); return ( <div> <p><small>&copy {currentYear}.</small> This is the amazing <b>footer</b>.</p> </div> ) }; }
client/modules/app/routes.js
mantrajs/meteor-mantra-kickstarter
import React from 'react'; import {mount} from 'react-mounter'; import {Accounts} from 'meteor/accounts-base'; import { AuthCheck, LayoutDefault, Simplest, NotFound, } from '/client/configs/components.js'; import Register from './components/AccountRegister/Wrapper.jsx'; import Login from './components/AccountLogin/Wrapper.jsx'; import Password from './components/AccountPassword/Wrapper.jsx'; import Profile from './components/AccountProfile/Wrapper.jsx'; import Account from './components/AccountAccount/Wrapper.jsx'; export default function (injectDeps, {FlowRouter}) { const AuthCheckCtx = injectDeps(AuthCheck); FlowRouter.route('/', { name: 'app.home', action() { mount(AuthCheckCtx, { LayoutDefault, content: () => (<Simplest title="App main screen"/>) }); } }); FlowRouter.notFound = { action() { mount(AuthCheckCtx, { LayoutDefault, content: () => (<NotFound />) }); } }; FlowRouter.route('/register', { name: 'app.register', action() { mount(AuthCheckCtx, { LayoutDefault, content: () => (<Register />), requireNotLoggedIn: true }); } }); FlowRouter.route('/login', { name: 'app.login', action() { mount(AuthCheckCtx, { LayoutDefault, content: () => (<Login />), requireNotLoggedIn: true }); } }); FlowRouter.route('/logout', { name: 'app.logout', action() { Accounts.logout(); // Meteor.logout(() => { FlowRouter.go('/login'); // }); } }); FlowRouter.route('/password', { name: 'app.password', action() { mount(AuthCheckCtx, { LayoutDefault, content: () => (<Password />) }); } }); FlowRouter.route('/account', { name: 'app.account', action() { mount(AuthCheckCtx, { LayoutDefault, content: () => (<Account />), requireUserId: true }); } }); FlowRouter.route('/profile', { name: 'app.profile', action() { mount(AuthCheckCtx, { LayoutDefault, content: () => (<Profile />), requireUserId: true }); } }); }
src/components/App.js
calebhskim/kucc-react-boilerplate
import React from 'react'; const App = () => ( <div>Hello World!</div> ); export default App;
lts/deps/npm/docs/src/components/home/Footer.js
enclose-io/compiler
import React from 'react' import boxes from '../../images/background-boxes.svg' import styled from 'styled-components' import {Flex, Box} from 'rebass' const Container = styled(Flex)` background: center / cover no-repeat url(${boxes}); height: 380px; background-color: ${(props) => props.theme.colors.offWhite}; ` const ContentWrapper = styled(Box)` align-content: center; width: 100%; text-align: center; background-color: ${(props) => props.theme.colors.white}; ` const Footer = () => { return ( <Container> <ContentWrapper py={4} mt={'auto'}> Footer Text 🤪 </ContentWrapper> </Container> ) } export default Footer
actor-apps/app-web/src/app/components/sidebar/ContactsSectionItem.react.js
it33/actor-platform
import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import AvatarItem from 'components/common/AvatarItem.react'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class ContactsSectionItem extends React.Component { static propTypes = { contact: React.PropTypes.object }; constructor(props) { super(props); } openNewPrivateCoversation = () => { DialogActionCreators.selectDialogPeerUser(this.props.contact.uid); } render() { const contact = this.props.contact; return ( <li className="sidebar__list__item row" onClick={this.openNewPrivateCoversation}> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> </li> ); } } export default ContactsSectionItem;
src/CommentBox.js
JiLiZART/react-tutorial
'use strict'; import React from 'react'; import CommentList from './CommentList'; import CommentForm from './CommentForm'; var data = [ {author: "Pete Hunt", text: "This is one comment"}, {author: "Jordan Walke", text: "This is *another* comment"} ]; export default React.createClass({ displayName: 'CommentBox', getInitialState: function () { return {data: []}; }, componentDidMount: function () { this.loadCommentsFromServer(); //setInterval(this.loadCommentsFromServer, this.props.pollInterval); }, loadCommentsFromServer: function () { $.ajax({ url: this.props.url, dataType: 'json', cache: false }).then( function (data) { this.setState({data: data}); }.bind(this), function (xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) ); }, handleCommentSubmit: function(comment) { data.push(comment); this.setState({data: data}); }, render: function () { return ( <div className="commentBox"> <h1>Comments</h1> <CommentList data={this.state.data} /> <CommentForm onCommentSubmit={this.handleCommentSubmit} /> </div> ); } });
blueocean-material-icons/src/js/components/svg-icons/action/open-in-new.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionOpenInNew = (props) => ( <SvgIcon {...props}> <path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/> </SvgIcon> ); ActionOpenInNew.displayName = 'ActionOpenInNew'; ActionOpenInNew.muiName = 'SvgIcon'; export default ActionOpenInNew;
client/src/components/Explorer/Explorer.js
takeflight/wagtail
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import * as actions from './actions'; import ExplorerPanel from './ExplorerPanel'; const Explorer = ({ isVisible, nodes, path, pushPage, popPage, onClose, }) => { const page = nodes[path[path.length - 1]]; return isVisible ? ( <ExplorerPanel path={path} page={page} nodes={nodes} onClose={onClose} popPage={popPage} pushPage={pushPage} /> ) : null; }; Explorer.propTypes = { isVisible: PropTypes.bool.isRequired, path: PropTypes.array.isRequired, nodes: PropTypes.object.isRequired, pushPage: PropTypes.func.isRequired, popPage: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, }; const mapStateToProps = (state) => ({ isVisible: state.explorer.isVisible, path: state.explorer.path, nodes: state.nodes, }); const mapDispatchToProps = (dispatch) => ({ pushPage: (id) => dispatch(actions.pushPage(id)), popPage: () => dispatch(actions.popPage()), onClose: () => dispatch(actions.closeExplorer()), }); export default connect(mapStateToProps, mapDispatchToProps)(Explorer);
src/svg-icons/av/forward-10.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvForward10 = (props) => ( <SvgIcon {...props}> <path d="M4 13c0 4.4 3.6 8 8 8s8-3.6 8-8h-2c0 3.3-2.7 6-6 6s-6-2.7-6-6 2.7-6 6-6v4l5-5-5-5v4c-4.4 0-8 3.6-8 8zm6.8 3H10v-3.3L9 13v-.7l1.8-.6h.1V16zm4.3-1.8c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.8-.8v-.5s-.1-.2-.1-.3-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z"/> </SvgIcon> ); AvForward10 = pure(AvForward10); AvForward10.displayName = 'AvForward10'; AvForward10.muiName = 'SvgIcon'; export default AvForward10;
src/svg-icons/av/sort-by-alpha.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSortByAlpha = (props) => ( <SvgIcon {...props}> <path d="M14.94 4.66h-4.72l2.36-2.36zm-4.69 14.71h4.66l-2.33 2.33zM6.1 6.27L1.6 17.73h1.84l.92-2.45h5.11l.92 2.45h1.84L7.74 6.27H6.1zm-1.13 7.37l1.94-5.18 1.94 5.18H4.97zm10.76 2.5h6.12v1.59h-8.53v-1.29l5.92-8.56h-5.88v-1.6h8.3v1.26l-5.93 8.6z"/> </SvgIcon> ); AvSortByAlpha = pure(AvSortByAlpha); AvSortByAlpha.displayName = 'AvSortByAlpha'; AvSortByAlpha.muiName = 'SvgIcon'; export default AvSortByAlpha;
src/js/app/Navbar/Mobile.js
ludonow/ludo-beta-react
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import styled from 'styled-components'; import { baseUrl } from '../../baseurl-config'; import { StyledAnchor, StyledLink, } from '../../baseStyle'; import { cardSystemLinkInfoList, getMyCardListLinkInfoList, getSettingLinkInfoList, } from './common'; import defaultUserAvatar from '../../../images/user.svg'; const authedInfoList = [ { isExternal: true, text: "登出", url: "https://api.ludonow.com/logout" }, ]; const myCardListLinkInfoSampleList = [ { text: "個人數據", url: "myCardList?stage=1&user_id=" }, ]; const unAuthedInfoList = [ { text: "登入", url: "login" }, ]; // styled components const ButtonListWrapper = styled.div` align-items: center; background-color: rgba(0, 0, 0, 0.8); display: ${props => props.isNavbarVisible ? 'flex' : 'none'}; flex-direction: column; height: calc(100vh - 70px); justify-content: center; `; const InnerCircle = styled.div` background-color: ${props => props.isNavbarVisible ? '#F8B10E' : 'white'}; border-radius: 50%; box-shadow: ${props => props.isNavbarVisible ? '' : '0 0 1px -1px'}; height: 30px; width: 30px; `; const LinkListWrapper = styled.div` display: flex; flex-direction: column; text-align: center; `; const MobileNavbarWrapper = styled.div` bottom: 0; position: fixed; width: 100%; z-index: 3; `; const StyledListItem = styled.div` background-color: ${props => props.selected ? '#FFC645' : 'transparent'}; border: 1px solid white; border-radius: 20px; display: flex; font-weight: bold; justify-content: center; margin: 20px auto; padding: 8px 30px; &:active, &:focus { background-color: #FFC645; } `; const OutSideCircle = styled.div` align-items: center; background-color: white; border-radius: 50%; display: flex; height: 50px; justify-content: center; margin: 20px; width: 50px; img { border-radius: 50%; height: 40px; width: 40px; } `; const ToggleButtonWrapper = styled.div` bottom: 0; position: fixed; right: 0; `; // child component const DoubleCircleIcon = ({ handleClick, userPhotoUrl, }) => ( <OutSideCircle onClick={handleClick}> { userPhotoUrl && userPhotoUrl !== 'default' ? <img src={userPhotoUrl} /> : <img src={defaultUserAvatar} /> } </OutSideCircle> ); // child components const LinkList = ({ handleNavbarClose, linkInfoList, selectedIndex, startingIndex, }) => ( <LinkListWrapper> { linkInfoList.map((linkInfo, arrayIndex)=> ( linkInfo.isExternal ? <StyledAnchor href={linkInfo.url} key={linkInfo.text} > <StyledListItem> {linkInfo.text} </StyledListItem> </StyledAnchor> : <StyledLink key={linkInfo.text} onClick={handleNavbarClose} to={`${baseUrl}/${linkInfo.url}`} > <StyledListItem selected={selectedIndex === (arrayIndex + startingIndex)}> {linkInfo.text} </StyledListItem> </StyledLink> )) } </LinkListWrapper> ); class ToggleButton extends Component { constructor() { super(); this.handleClick = this.handleClick.bind(this); } handleClick(event) { event.preventDefault(); const { handleNavbarToggle, isNavbarVisible } = this.props; handleNavbarToggle(!isNavbarVisible); } render() { const { userPhotoUrl, } = this.props; return ( <ToggleButtonWrapper> <DoubleCircleIcon handleClick={this.handleClick} userPhotoUrl={userPhotoUrl} /> </ToggleButtonWrapper> ); } } const Mobile = ({ chatFuelId, currentUserId, handleNavbarClose, handleNavbarToggle, isNavbarVisible, selectedIndex, userPhotoUrl, }) => { const authInfoList = currentUserId ? authedInfoList : unAuthedInfoList; return ( <MobileNavbarWrapper> <ToggleButton handleNavbarToggle={handleNavbarToggle} isNavbarVisible={isNavbarVisible} userPhotoUrl={userPhotoUrl} /> <ButtonListWrapper isNavbarVisible={isNavbarVisible} onClick={handleNavbarClose} > <LinkList handleNavbarClose={handleNavbarClose} linkInfoList={cardSystemLinkInfoList} selectedIndex={selectedIndex} startingIndex={0} /> <LinkList handleNavbarClose={handleNavbarClose} linkInfoList={getMyCardListLinkInfoList(myCardListLinkInfoSampleList, currentUserId)} selectedIndex={selectedIndex} startingIndex={3} /> <LinkList handleNavbarClose={handleNavbarClose} linkInfoList={authInfoList} selectedIndex={selectedIndex} startingIndex={4} /> <LinkList handleNavbarClose={handleNavbarClose} linkInfoList={getSettingLinkInfoList(chatFuelId)} selectedIndex={selectedIndex} startingIndex={5} /> </ButtonListWrapper> </MobileNavbarWrapper> ); } Mobile.propTypes = { chatFuelId: PropTypes.string.isRequired, currentUserId: PropTypes.string.isRequired, handleNavbarClose: PropTypes.func.isRequired, handleNavbarToggle: PropTypes.func.isRequired, isNavbarVisible: PropTypes.bool.isRequired, selectedIndex: PropTypes.number.isRequired, userPhotoUrl: PropTypes.string.isRequired, }; export default Mobile;
css-challenges-2/src/App.js
javcasas/css-challenges
import React from 'react'; import logo from './logo.svg'; import './App.css'; import {HyperspaceIn, HyperspaceOut} from './hw-hyperspace'; function App() { return ( <div className="App"> <header className="App-header"> <HyperspaceIn> adfsdfasdfasdgdfag </HyperspaceIn> <div style={{height: "30px", width: "100%"}} /> <br /> <HyperspaceOut> adfsdfasdfasdgdfag </HyperspaceOut> </header> </div> ); } export default App;
src/Chat/ChatList/ChatList.js
DarthVictor/bank-chat
import React from 'react' import ChatMessage from '../ChatMessage' import './ChatList.scss' function formatDateHeader(date){ function twoDigits(n){ return (n < 10 ? '0' : '') + n } return `— ${twoDigits(date.getDate())}.${twoDigits(date.getMonth() + 1)}.${date.getFullYear()} —` } export default class ChatList extends React.Component { getList(){ const {messages} = this.props return messages.reduce((accMsgs, msg) => { const prevMsgDate = accMsgs.length > 0 ? new Date(accMsgs[accMsgs.length - 1].date) : null const curMsgDate = new Date(msg.date) if(prevMsgDate === null || prevMsgDate.getDate() !== curMsgDate.getDate()){ accMsgs.push({ isDateHeader: true, key: 'header_' + msg.date, text: formatDateHeader(curMsgDate) }) } accMsgs.push(msg) return accMsgs }, []) } render() { return <div className="chat-list custom-scroll"> <div className="chat-list__frame"> {this.getList().map(msg => msg.isDateHeader ? <div key={msg.key} className="chat-list__date-header"> <span className="chat-list__date-header-text">{msg.text}</span> </div> : <ChatMessage key={msg.key} msg={msg}></ChatMessage> )} </div> </div> } }
app/containers/NavigationContainer/index.js
rahsheen/scalable-react-app
/* * * NavigationContainer * */ import React from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import selectNavigationContainer from './selectors'; import styles from './styles.css'; import Navigation from '../../components/Navigation'; import { requestTopics, selectTopic, toggleDrawer } from './actions'; export class NavigationContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { requestTopics: React.PropTypes.func.isRequired, } componentWillMount() { this.props.requestTopics(); } render() { return ( <div className={styles.navigationContainer}> <Helmet title="NavigationContainer" meta={[ { name: 'description', content: 'Description of NavigationContainer' }, ]} /> <Navigation {...this.props} /> </div> ); } } const mapStateToProps = selectNavigationContainer(); function mapDispatchToProps(dispatch) { return { requestTopics: () => dispatch(requestTopics()), selectTopic: (topic) => dispatch(selectTopic(topic)), toggleDrawer: () => dispatch(toggleDrawer()), }; } export default connect(mapStateToProps, mapDispatchToProps)(NavigationContainer);
node_modules/semantic-ui-react/src/collections/Table/Table.js
SuperUncleCat/ServerMonitoring
import _ from 'lodash' import cx from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { childrenUtils, customPropTypes, getElementType, getUnhandledProps, META, SUI, useKeyOnly, useKeyOrValueAndKey, useTextAlignProp, useVerticalAlignProp, useWidthProp, } from '../../lib' import TableBody from './TableBody' import TableCell from './TableCell' import TableFooter from './TableFooter' import TableHeader from './TableHeader' import TableHeaderCell from './TableHeaderCell' import TableRow from './TableRow' /** * A table displays a collections of data grouped into rows. */ function Table(props) { const { attached, basic, celled, children, className, collapsing, color, columns, compact, definition, fixed, footerRow, headerRow, inverted, padded, renderBodyRow, selectable, singleLine, size, sortable, stackable, striped, structured, tableData, textAlign, unstackable, verticalAlign, } = props const classes = cx( 'ui', color, size, useKeyOnly(celled, 'celled'), useKeyOnly(collapsing, 'collapsing'), useKeyOnly(definition, 'definition'), useKeyOnly(fixed, 'fixed'), useKeyOnly(inverted, 'inverted'), useKeyOnly(selectable, 'selectable'), useKeyOnly(singleLine, 'single line'), useKeyOnly(sortable, 'sortable'), useKeyOnly(stackable, 'stackable'), useKeyOnly(striped, 'striped'), useKeyOnly(structured, 'structured'), useKeyOnly(unstackable, 'unstackable'), useKeyOrValueAndKey(attached, 'attached'), useKeyOrValueAndKey(basic, 'basic'), useKeyOrValueAndKey(compact, 'compact'), useKeyOrValueAndKey(padded, 'padded'), useTextAlignProp(textAlign), useVerticalAlignProp(verticalAlign), useWidthProp(columns, 'column'), 'table', className, ) const rest = getUnhandledProps(Table, props) const ElementType = getElementType(Table, props) if (!childrenUtils.isNil(children)) { return <ElementType {...rest} className={classes}>{children}</ElementType> } return ( <ElementType {...rest} className={classes}> {headerRow && <TableHeader>{TableRow.create(headerRow, { defaultProps: { cellAs: 'th' } })}</TableHeader>} <TableBody> {renderBodyRow && _.map(tableData, (data, index) => TableRow.create(renderBodyRow(data, index)))} </TableBody> {footerRow && <TableFooter>{TableRow.create(footerRow)}</TableFooter>} </ElementType> ) } Table._meta = { name: 'Table', type: META.TYPES.COLLECTION, } Table.defaultProps = { as: 'table', } Table.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Attach table to other content */ attached: PropTypes.oneOfType([ PropTypes.bool, PropTypes.oneOf(['top', 'bottom']), ]), /** A table can reduce its complexity to increase readability. */ basic: PropTypes.oneOfType([ PropTypes.oneOf(['very']), PropTypes.bool, ]), /** A table may be divided each row into separate cells. */ celled: PropTypes.bool, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** A table can be collapsing, taking up only as much space as its rows. */ collapsing: PropTypes.bool, /** A table can be given a color to distinguish it from other tables. */ color: PropTypes.oneOf(SUI.COLORS), /** A table can specify its column count to divide its content evenly. */ columns: PropTypes.oneOf(SUI.WIDTHS), /** A table may sometimes need to be more compact to make more rows visible at a time. */ compact: PropTypes.oneOfType([ PropTypes.bool, PropTypes.oneOf(['very']), ]), /** A table may be formatted to emphasize a first column that defines a rows content. */ definition: PropTypes.bool, /** * A table can use fixed a special faster form of table rendering that does not resize table cells based on content */ fixed: PropTypes.bool, /** Shorthand for a TableRow to be placed within Table.Footer. */ footerRow: customPropTypes.itemShorthand, /** Shorthand for a TableRow to be placed within Table.Header. */ headerRow: customPropTypes.itemShorthand, /** A table's colors can be inverted. */ inverted: PropTypes.bool, /** A table may sometimes need to be more padded for legibility. */ padded: PropTypes.oneOfType([ PropTypes.bool, PropTypes.oneOf(['very']), ]), /** * Mapped over `tableData` and should return shorthand for each Table.Row to be placed within Table.Body. * * @param {*} data - An element in the `tableData` array. * @param {number} index - The index of the current element in `tableData`. * @returns {*} Shorthand for a Table.Row. */ renderBodyRow: customPropTypes.every([ customPropTypes.disallow(['children']), customPropTypes.demand(['tableData']), PropTypes.func, ]), /** A table can have its rows appear selectable. */ selectable: PropTypes.bool, /** A table can specify that its cell contents should remain on a single line and not wrap. */ singleLine: PropTypes.bool, /** A table can also be small or large. */ size: PropTypes.oneOf(_.without(SUI.SIZES, 'mini', 'tiny', 'medium', 'big', 'huge', 'massive')), /** A table may allow a user to sort contents by clicking on a table header. */ sortable: PropTypes.bool, /** A table can specify how it stacks table content responsively. */ stackable: PropTypes.bool, /** A table can stripe alternate rows of content with a darker color to increase contrast. */ striped: PropTypes.bool, /** A table can be formatted to display complex structured data. */ structured: PropTypes.bool, /** Data to be passed to the renderBodyRow function. */ tableData: customPropTypes.every([ customPropTypes.disallow(['children']), customPropTypes.demand(['renderBodyRow']), PropTypes.array, ]), /** A table can adjust its text alignment. */ textAlign: PropTypes.oneOf(_.without(SUI.TEXT_ALIGNMENTS, 'justified')), /** A table can specify how it stacks table content responsively. */ unstackable: PropTypes.bool, /** A table can adjust its text alignment. */ verticalAlign: PropTypes.oneOf(SUI.VERTICAL_ALIGNMENTS), } Table.Body = TableBody Table.Cell = TableCell Table.Footer = TableFooter Table.Header = TableHeader Table.HeaderCell = TableHeaderCell Table.Row = TableRow export default Table
frontend/component/EditTopic.js
caiklaus/first-node-project
import React from 'react'; import jQuery from 'jquery'; import {addTopic} from '../lib/client'; import {redirectURL} from '../lib/utils'; import {getTopicDetail, updateTopic} from '../lib/client'; import TopicEditor from './TopicEditor'; export default class EditTopic extends React.Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { getTopicDetail(this.props.params.id) .then(topic => { this.setState({topic}); }) .catch(err => console.error(err)); } render() { if (!this.state.topic) { return ( <h3>正在加载...</h3> ); } return ( <TopicEditor title={`编辑 ${this.state.topic.title}`} topic={this.state.topic} onSave={(topic, done) => { updateTopic(this.props.params.id, topic.title, topic.tags, topic.content) .then(ret => { done(); redirectURL(`/topic/${ret._id}`); }) .catch(err => { done(); alert(err); }); }} /> ) } }
docs/app/Examples/views/Statistic/Variations/StatisticExampleHorizontal.js
clemensw/stardust
import React from 'react' import { Statistic } from 'semantic-ui-react' const StatisticExampleHorizontal = () => <Statistic horizontal value='2,204' label='Views' /> export default StatisticExampleHorizontal
util/connect/index.js
marrus-sh/mastodon-go
/*********************************************************************\ | | | CONNECT | | ======= | | | | `connect()` is a replacement function for the one with the same | | name in React-Redux. It generates a selector factory and calls | | it with a function named `go()`. | | | | The `connect()` function | | ------------------------ | | | | The arguments to `connect()` are a `stater` and a `dispatcher`, | | which are selectors of the form `function(state, ownProps)` and | | `function(go, store, props, context)`, where `ownProps`/`props` | | are the passed component props, `store` is the resultant object | | of the `stater`, and `context` holds the `intl` prop taken from | | the `injectIntl()` function. The return values of the `stater` | | and `dispatcher` are provided to the wrapped component via some | | emoji props. | | | | `reselect`'s `createStructuredSelector()` is a good tool to use | | when building `stater`s, and `dispatcher`s are typically normal | | functions. | | | | About `go()` | | ------------ | | | | `go()` is essentially a wrapper for `dispatch` which makes code | | like the following: | | | | go(fn, ...args); | | | | be evaluated as though it were instead code like the following: | | | | dispatch(fn(...args, go, current, api)); | | | | (Note that `current` is just another name for `getState`.) | | | | This means that action creators which would normally be written | | as follows: | | | | const myAction = (arg1, arg2) => (dispatch, getState) => { | | const api = apiGeneratorFunction(getState); | | // Function code | | } | | | | can instead be written more simply as: | | | | const myGoAction = (arg1, arg2, go, current, api) => { | | // Function code | | } | | | | Note also the ease at which one can dispatch the `go()`-enabled | | action creator, compared to the traditional one: | | | | dispatch(myAction(var1, var2)); // Messy | | go(myGoAction, var1, var2); // Clean | | | | Using our `connect()` function allows us to write cleaner, more | | straightforward action creators, and minimize the level of code | | duplication we have with regard to API calls in particular. It | | is a tiny bit magic and a tiny bit hack so be careful where you | | swing it around. | | | | One especially important thing to note is that `go()` will only | | (and always) provide `go`, `current`, and `api` to the function | | it is called with if the provided `...args` fail to exhaust the | | function's `length`. This helps to keep us from creating `api` | | objects that we won't use, but it does mean that every argument | | to a function must be specified explicitly. If a function were | | to be specified with too few arguments, then `go` etc. would be | | provided to the wrong argument slot, and if too many, then they | | may not be provided at all. | | | | ~ @[email protected] | | | \*********************************************************************/ // Imports // ------- // Package imports. import axios from 'axios'; import PropTypes from 'prop-types'; import React from 'react'; import { FormattedMessage, injectIntl, } from 'react-intl'; import { connectAdvanced as reduxConnect } from 'react-redux'; import shallowEqual from 'react-redux/lib/utils/shallowEqual'; import { createSelector } from 'reselect'; // * * * * * * * // // The code // -------- // `readyToGo()` transforms the `fn` and `args` it is provided with // into a new function which is able to be dispatched. If an object // is provided instead of a function, it simply clones the object. // (Note that objects are inherently dispatchable.) function readyToGo (fn, ...withArgs) { return typeof fn !== 'function' ? { ...fn } : function (dispatch, getState) { const go = fn.length > withArgs.length ? (fn, ...args) => dispatch(readyToGo(fn, ...args)) : void 0; const current = fn.length > withArgs.length + 1 ? getState : void 0; const api = fn.length > withArgs.length + 2 ? axios.create({ headers: { Authorization: `Bearer ${getState().getIn(['meta', 'accessToken'], '')}`, }, }) : void 0; const result = fn.call(void 0, ...withArgs, go, current, api); if (result) { dispatch(result); } }; } // `makeMessages()` creates our `ℳ()` function from `intl` and a // `messager` object. function makeMessages (intl, messager) { let ℳ; // Assuming we have `intl`, we can define our `messages` // function. if (intl && messager) { // This function gets our internationalization messages. ℳ = function (obj, withValues) { // If we are given a string, we return a string. if (obj instanceof String || typeof obj === 'string') { return !values ? ℳ[obj] : ℳ[obj].withValues(withValues); } // Otherwise, we assume that we're being called via JSX and // respond as a React component. const { name, values, } = obj; return name ? <FormattedMessage {...messager[name]} values={values} /> : null; }; // `messages` props. ℳ.propTypes = { name: PropTypes.string.isRequired, values: PropTypes.object, }; // This predefines our (simple) messages. This will give us quick // access to them later as well. let name; for (name in messager) { Object.defineProperty(ℳ, name, { value: new String(/(?:\\\\|[^\\]|^){[^]*?(?:\\\\|[^\\])}/.test(messager[name].defaultMessage) ? messager[name].id : intl.formatMessage(messager[name], messager[name].defaultValues)) }); ℳ[name].withValues = intl.formatMessage.bind(intl, messager[name]); } } // Return. return ℳ; } // `connect()` creates a selector factory with access to our `go()` // function—which is just `dispatch()` composed with `readyToGo()`. export default function connect (component, stater, messager, dispatcher, config) { // If we don't have a `component`, we can't connect. if (!component) { throw new TypeError('connect: Cannot connect; no component was provided'); } // If we don't have a `stater` or a `dispatcher`, we can take a // shortcut with our connecting. if (!stater && !dispatcher) { return injectIntl(function ({ intl, ...props }) { return React.createElement(component, { ...props, ℳ: makeMessages(intl, messager), '🎛': config || null, '🏪': null, '💪': null, }); }); } // `selectorFactory()` takes `dispatch()` and uses it to construct a // `go()` function, which is then handed to our `dispatcher`. const selectorFactory = dispatch => { // Generates our `go()` function. const go = (fn, ...args) => dispatch(readyToGo(fn, ...args)); // This will hold our messages function. We need `intl` to // define it, so it starts out `null`. let messages = null; // This is the selector we will use. const selector = createSelector( [ stater ? stater : () => null, (state, ownProps) => ownProps, ], (store, { intl, ...props }) => { // Makes our messages. if (!messages) { messages = makeMessages(intl, messager); } // The returned object. return { // Our props (not including `intl`). ...props, // Our messages, handlers, and store. ℳ: messages, '🎛': config || null, '💪': dispatcher ? dispatcher(go, store, props, messages) : null, '🏪': store, }; } ); // This stores our last received props for this component. let props = null; // We use `shallowEqual()` from `react-redux` to mimic the // behaviour of their `connect()`. return function (store, ownProps) { let shouldUpdate = false; if (typeof component.shouldComponentUpdate === 'function') { shouldUpdate = component.shouldComponentUpdate(ownProps, component.state); } else shouldUpdate = !shallowEqual(props, ownProps); if (!props || shouldUpdate) { props = ownProps; } return selector(store, props); }; }; // All connected functions are passed through `injectIntl`. return injectIntl(reduxConnect(selectorFactory)(component)); }
js/AppNavigator.js
leehyoumin/asuraCham
'use strict'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import _ from 'lodash/core'; import { Drawer } from 'native-base'; import { BackAndroid, Platform, StatusBar } from 'react-native'; import { closeDrawer } from './actions/drawer'; import { popRoute } from './actions/route'; import Navigator from 'Navigator'; import Login from './components/login/'; import Home from './components/home/'; import BlankPage from './components/blankPage/'; import BlankPage2 from './components/blankPage2/'; import SplashPage from './components/splashscreen/'; import SideBar from './components/sideBar'; import { statusBarColor } from "./themes/base-theme"; import Add_Project from './components/addProject/'; import Add_Lesson from './components/addLesson/'; import Search_Project from './components/search/'; import Search_Lesson from './components/search2/'; import LessonScreen from './components/lessonScreen/'; import Register from './components/register/'; import SetSkill from './components/setSkill/'; import SetSkill2 from './components/setSkill2/'; import SetupInfo from './components/SetupInfo/'; Navigator.prototype.replaceWithAnimation = function (route) { const activeLength = this.state.presentedIndex + 1; const activeStack = this.state.routeStack.slice(0, activeLength); const activeAnimationConfigStack = this.state.sceneConfigStack.slice(0, activeLength); const nextStack = activeStack.concat([route]); const destIndex = nextStack.length - 1; const nextSceneConfig = this.props.configureScene(route, nextStack); const nextAnimationConfigStack = activeAnimationConfigStack.concat([nextSceneConfig]); const replacedStack = activeStack.slice(0, activeLength - 1).concat([route]); this._emitWillFocus(nextStack[destIndex]); this.setState({ routeStack: nextStack, sceneConfigStack: nextAnimationConfigStack, }, () => { this._enableScene(destIndex); this._transitionTo(destIndex, nextSceneConfig.defaultTransitionVelocity, null, () => { this.immediatelyResetRouteStack(replacedStack); }); }); }; export var globalNav = {}; const searchResultRegexp = /^search\/(.*)$/; const reducerCreate = params=>{ const defaultReducer = Reducer(params); return (state, action)=>{ var currentState = state; if(currentState){ while (currentState.children){ currentState = currentState.children[currentState.index] } } return defaultReducer(state, action); } }; const drawerStyle = { shadowColor: '#000000', shadowOpacity: 0.8, shadowRadius: 3}; class AppNavigator extends Component { constructor(props){ super(props); } componentDidMount() { globalNav.navigator = this._navigator; this.props.store.subscribe(() => { if(this.props.store.getState().drawer.drawerState == 'opened') this.openDrawer(); if(this.props.store.getState().drawer.drawerState == 'closed') this._drawer.close(); }); BackAndroid.addEventListener('hardwareBackPress', () => { var routes = this._navigator.getCurrentRoutes(); if(routes[routes.length - 1].id == 'home' || routes[routes.length - 1].id == 'login') { return false; } else { this.popRoute(); return true; } }); } popRoute() { this.props.popRoute(); } openDrawer() { this._drawer.open(); } closeDrawer() { if(this.props.store.getState().drawer.drawerState == 'opened') { this._drawer.close(); this.props.closeDrawer(); } } render() { return ( <Drawer ref={(ref) => this._drawer = ref} type="overlay" content={<SideBar navigator={this._navigator} />} tapToClose={true} acceptPan={false} onClose={() => this.closeDrawer()} openDrawerOffset={0.2} panCloseMask={0.2} negotiatePan={true}> <StatusBar backgroundColor={statusBarColor} barStyle="light-content" /> <Navigator ref={(ref) => this._navigator = ref} configureScene={(route) => { return Navigator.SceneConfigs.FloatFromRight; }} initialRoute={{id: (Platform.OS === "android") ? 'splashscreen' : 'login', statusBarHidden: true}} renderScene={this.renderScene} /> </Drawer> ); } renderScene(route, navigator) { switch (route.id) { case 'splashscreen': return <SplashPage navigator={navigator} />; case 'login': return <Login navigator={navigator} />; case 'home': return <Home navigator={navigator} />; case 'blankPage': return <BlankPage route={route} navigator={navigator} />; case 'blankPage2': return <BlankPage2 route={route} navigator={navigator} />; case 'addProject': return <Add_Project navigator={navigator} />; case 'addLesson': return <Add_Lesson navigator={navigator} />; case 'search': return <Search_Project navigator={navigator} data={route.data} />; case 'search2': return <Search_Lesson navigator={navigator} data={route.data} />; case 'lessonScreen': return <LessonScreen navigator={navigator} />; case 'register': return <Register navigator={navigator} />; case 'setSkill': return <SetSkill navigator={navigator} />; case 'setSkill2': return <SetSkill2 navigator={navigator} />; case 'SetupInfo': return <SetupInfo navigator={navigator} />; default : return <Login navigator={navigator} />; } } } //hyeonmin var { TouchableHighlight } = React; function bindAction(dispatch) { return { closeDrawer: () => dispatch(closeDrawer()), popRoute: () => dispatch(popRoute()) } } const mapStateToProps = (state) => { return { drawerState: state.drawer.drawerState } } export default connect(mapStateToProps, bindAction) (AppNavigator);
src/browser/todos/Todos.js
robinpokorny/este
// @flow import type { State, Todo } from '../../common/types'; import React from 'react'; import todosMessages from '../../common/todos/todosMessages'; import { Box, Button, Text } from '../app/components'; import { compose, isEmpty, prop, reverse, sortBy, values } from 'ramda'; import { connect } from 'react-redux'; import { deleteTodo, toggleTodoCompleted } from '../../common/todos/actions'; import { injectIntl } from 'react-intl'; const itemStyle = { inline: true, paddingVertical: 0.5, }; const TodosItem = ({ deleteTodo, todo, toggleTodoCompleted, }) => ( <Box display="flex"> <Button {...itemStyle} bold={false} decoration={todo.completed ? 'line-through' : 'none'} onClick={() => toggleTodoCompleted(todo)} paddingHorizontal={0} transform="none" >{todo.title}</Button> <Button {...itemStyle} marginHorizontal={0.5} onClick={() => deleteTodo(todo.id)} paddingHorizontal={0.25} >×</Button> </Box> ); type TodosProps = { deleteTodo: typeof deleteTodo, intl: $IntlShape, todos: Object, toggleTodoCompleted: typeof toggleTodoCompleted, }; const Todos = ({ deleteTodo, intl, todos, toggleTodoCompleted, }: TodosProps) => { if (isEmpty(todos)) { return ( <Box> <Text> {intl.formatMessage(todosMessages.empty)} </Text> </Box> ); } // It's ok and recommended to sort things in view, but for the bigger data // leverage reactjs/reselect or bvaughn/react-virtualized. const sortedTodos: Array<Todo> = compose( reverse, sortBy(prop('createdAt')), values, )(todos); return ( <Box> {sortedTodos.map(todo => ( <TodosItem key={todo.id} deleteTodo={deleteTodo} todo={todo} toggleTodoCompleted={toggleTodoCompleted} /> ))} </Box> ); }; export default compose( connect( (state: State) => ({ todos: state.todos.all, }), { deleteTodo, toggleTodoCompleted }, ), injectIntl, )(Todos);
src/components/auth/requireAuth.js
mdunnegan/ReactFrontEndAuthentication
import React, { Component } from 'react'; import { connect } from 'react-redux'; export default function(ComposedComponent) { class Authentication extends Component { static contextTypes = { router: React.PropTypes.object } componentWillMount() { // Just checking global redux state if (!this.props.authenticated) { this.context.router.push('/'); } } // Haven't seen this method a whole lot componentWillUpdate(nextProps) { if (!nextProps.authenticated) { this.context.router.push('/'); } } render() { return <ComposedComponent {...this.props} /> } } function mapStateToProps(state) { return { authenticated: state.auth.authenticated }; } return connect(mapStateToProps)(Authentication); }
app/components/Input/Input.js
JSSolutions/Perfi
import React from 'react'; import T from 'prop-types'; import { TextInput, View, ViewPropTypes } from 'react-native'; import { MaterialCommunityIcons } from '@expo/vector-icons'; import Text from '../Text'; import { colors } from '../../styles'; import s from './styles'; const Input = ({ containerStyle, placeholderColor, secondContainerStyle, containerStyleFocus, isNotValidStyle = s.isNotValid, icon, iconRight, leftIconStyle, rightIconStyle, inputRef, label, error, labelStyle, prefix, style, isFocus, onFocus, onBlur, isNotValid, isFocusColor = colors.green, ...props }) => ( <View style={containerStyle}> {!!label && <Text style={[s.label, labelStyle]}>{label}</Text>} <View style={[ s.root, secondContainerStyle, isFocus && containerStyleFocus, isNotValid && isNotValidStyle, error && isNotValidStyle, ]} > { !!icon && <MaterialCommunityIcons color={isFocus ? isFocusColor : colors.greyDarker} style={[s.icon, leftIconStyle]} {...icon} /> } {!!prefix && <Text style={s.prefix}>{prefix}</Text>} <TextInput autoCorrect={false} placeholderTextColor={placeholderColor || colors.greyDarker} underlineColorAndroid={colors.transparent} onFocus={onFocus} onBlur={onBlur} {...props} ref={inputRef} style={[s.input, style]} /> { !!iconRight && <MaterialCommunityIcons color={isFocus ? isFocusColor : colors.greyDarker} style={[s.icon, rightIconStyle]} {...iconRight} /> } </View> {!!error && <Text style={s.error}>{error}</Text>} </View> ); Input.propTypes = { containerStyle: ViewPropTypes.style, secondContainerStyle: ViewPropTypes.style, containerStyleFocus: ViewPropTypes.style, isNotValidStyle: ViewPropTypes.style, leftIconStyle: ViewPropTypes.style, rightIconStyle: ViewPropTypes.style, placeholderColor: T.string, isFocusColor: T.string, isFocus: T.bool, isNotValid: T.bool, icon: T.object, iconRight: T.object, inputRef: T.any, label: T.string, error: T.string, labelStyle: Text.propTypes.style, prefix: T.string, style: Text.propTypes.style, onFocus: T.func, onBlur: T.func, // value: T.string, value: T.oneOfType([T.string, T.number]), }; export default Input;
src/components/Feedback/Feedback.js
zhangtiny123/casa-achievement
import React from 'react'; import styles from './Feedback.less'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
src/router.js
yyjazsf/react-study
import React from 'react' import { Switch, Route, routerRedux } from 'dva/router' import PropTypes from 'prop-types' import dynamic from 'dva/dynamic' import App from './routes/app' import AuthorizedRoute from './components/authorizedRoute' import ManinLayout from './components/layout' const { ConnectedRouter } = routerRedux const registerModel = (app, model) => { if (!(app._models.filter(m => m.namespace === model.namespace).length === 1)) { app.model(model) } } function RouterConfig({ history, app }) { registerModel(app, require('./models/auth')) const error = dynamic({ app, component: () => import('./routes/error'), }) const Login = dynamic({ app, component: () => import('./routes/login'), }) const routes = [ { path: '/app/index', models: () => [ import('./models/home'), ], component: () => import('./routes/home'), }, { path: '/app/user', models: () => [ import('./models/user'), ], component: () => import('./routes/user'), }, { path: '/app/user/:username', models: () => [ import('./models/user'), ], component: () => import('./routes/user'), }, ] const MainComponent = () => ( <ManinLayout> { routes.map(({ path, ...dynamics }, key) => ( <Route key={key} exact path={path} component={dynamic({ app, ...dynamics, // (models and) component })} /> )) } </ManinLayout> ) return ( <ConnectedRouter history={history}> <App> <Switch> <Route exact path="/" component={Login} /> <AuthorizedRoute path="/app" component={MainComponent} /> <Route component={error} /> </Switch> </App> </ConnectedRouter> ) } RouterConfig.propTypes = { history: PropTypes.object, app: PropTypes.object, } export default RouterConfig
src/components/app.js
ljones140/react_redux_weather_app
import React, { Component } from 'react'; import SearchBar from '../containers/search_bar'; import WeatherList from '../containers/weather_list'; export default class App extends Component { render() { return ( <div> <SearchBar /> <WeatherList /> </div> ); } }
examples/huge-apps/routes/Course/components/Nav.js
sprjr/react-router
import React from 'react'; import { Link } from 'react-router'; import AnnouncementsRoute from '../routes/Announcements'; import AssignmentsRoute from '../routes/Assignments'; import GradesRoute from '../routes/Grades'; const styles = {}; styles.nav = { borderBottom: '1px solid #aaa' }; styles.link = { display: 'inline-block', padding: 10, textDecoration: 'none', }; styles.activeLink = Object.assign({}, styles.link, { //color: 'red' }); class Nav extends React.Component { render () { var { course } = this.props; var pages = [ ['announcements', 'Announcements'], ['assignments', 'Assignments'], ['grades', 'Grades'], ]; return ( <nav style={styles.nav}> {pages.map((page, index) => ( <Link key={page[0]} activeStyle={index === 0 ? Object.assign({}, styles.activeLink, { paddingLeft: 0 }) : styles.activeLink} style={index === 0 ? Object.assign({}, styles.link, { paddingLeft: 0 }) : styles.link } to={`/course/${course.id}/${page[0]}`} >{page[1]}</Link> ))} </nav> ); } } export default Nav;
src/Backoffice/ButtonLayout/ButtonLayout.js
skyiea/wix-style-react
import React from 'react'; import {any, bool, oneOf} from 'prop-types'; import classNames from 'classnames'; import styles from './ButtonLayout.scss'; const ButtonLayout = props => { const {theme, hover, active, disabled, height, children} = props; const className = classNames({ [styles.button]: true, [styles[theme]]: true, [styles.hover]: hover, [styles.active]: active, [styles.disabled]: disabled, [styles[`height${height}`]]: height !== 'medium' }, children.props.className); const _style = Object.assign({}, children.props.style, { height, display: 'inline-block' } ); if (React.Children.count(children) === 1) { return React.cloneElement( children, {className, style: _style}, <div className={styles.inner}> {children.props.children} </div> ); } }; ButtonLayout.defaultProps = { height: 'medium', theme: 'fullblue' }; ButtonLayout.propTypes = { active: bool, children: any, disabled: bool, height: oneOf(['small', 'medium', 'large']), hover: bool, theme: oneOf([ 'transparent', 'fullred', 'fullgreen', 'fullpurple', 'emptyred', 'emptygreen', 'emptybluesecondary', 'emptyblue', 'emptypurple', 'fullblue', 'login', 'emptylogin', 'transparentblue', 'whiteblue', 'whiteblueprimary', 'whitebluesecondary', 'close-standard', 'close-dark', 'close-transparent', 'icon-greybackground', 'icon-standard', 'icon-standardsecondary', 'icon-white', 'icon-whitesecondary' ]) }; ButtonLayout.displayName = 'ButtonLayout'; export default ButtonLayout;
src/components/Home/Home.js
ortonomy/flingapp-frontend
import React, { Component } from 'react'; import { Jumbotron, Button } from 'react-bootstrap'; import home from './Home.module.css' class Home extends Component { render() { return( <div className={home.Home}> <Jumbotron> <h1>Hello everyone!</h1> <Button bsStyle="primary">Click me!</Button> </Jumbotron> </div> ) } } export default Home;
web-ui/src/component/BoardComponent.js
azadbolour/boardgame
/* * Copyright 2017-2018 Azad Bolour * Licensed under GNU Affero General Public License v3.0 - * https://github.com/azadbolour/boardgame/blob/master/LICENSE.md */ /** @module Board */ import React from 'react'; import PropTypes from 'prop-types'; import BoardSquareComponent from './BoardSquareComponent'; import PieceComponent from './PieceComponent'; import * as Piece from '../domain/Piece'; import {mkPoint} from '../domain/Point'; import * as Point from '../domain/Point'; import logger from "../util/Logger"; import {stringify} from "../util/Logger"; /** * A style that includes the board's overall * dimensions in pixels, and the layout of its * children (the board's squares). */ function boardStyle(dimension, squarePixels) { let pixels = dimension * squarePixels; return { width: pixels + 'px', height: pixels + 'px', display: 'flex', flexWrap: 'wrap' }; } /** * A style that includes the dimensions of a board square * in pixels. */ function squareStyle(squarePixels) { let pix = squarePixels + 'px'; return { width: pix, height: pix } } /** * User interface component representing a board. */ class BoardComponent extends React.Component { static propTypes = { /** * The board data. */ board: PropTypes.object.isRequired, /** * Positions that are currently in play by the user - i.e. occupied by pieces. */ pointsInUserPlay: PropTypes.array.isRequired, /** * Points that were just filled by the machine. */ pointsMovedInMachinePlay: PropTypes.array.isRequired, /** * Function of position that determines whether the position * is a legal destination of a move - whether a piece is allowed * to be moved to that position given the current state of the game. */ isLegalMove: PropTypes.func.isRequired, canMovePiece: PropTypes.func.isRequired, /** * The number of pixels used to represent the side of each * board square. */ squarePixels: PropTypes.number.isRequired, pointValues: PropTypes.object.isRequired, /** * The board responds to interactions. */ enabled: PropTypes.bool.isRequired }; /** * Is an row, col position currently occupied? */ positionInPlay(point) { return this.props.pointsInUserPlay.some(p => Point.eq(p, point)); } /** * Return the UI specification of the piece that goes into * a specific board square - given the square's position. */ renderPiece(point) { let piece = this.props.board.rows()[point.row][point.col].piece; let canMovePiece = this.props.canMovePiece; let enabled = this.props.enabled; // piece = (piece) ? piece : Piece.NO_PIECE; return <PieceComponent piece={piece} canMovePiece={canMovePiece} enabled={enabled} />; } /** * Return the UI specification of a single square based * on it row, col coordinates. * * A function may return the react specification of a * UI component, and these specifications may be composed. */ renderSquare(row, col) { let dimension = this.props.board.dimension; let squareKey = dimension * row + col; let isLegalMove = this.props.isLegalMove; let squarePixels = this.props.squarePixels; let point = mkPoint(row, col); let inPlay = this.props.pointsInUserPlay.some(p => Point.eq(p, point)); let justFilledByMachine = this.props.pointsMovedInMachinePlay.some(p => Point.eq(p, point)); let enabled = this.props.enabled; let pointValue = this.props.pointValues.getElement(point); let center = Math.floor(dimension/20); // let isCenterPoint = row === center && col === center; let squarePiece = this.props.board.rows()[row][col].piece; return ( <div key={squareKey} style={squareStyle({squarePixels})}> <BoardSquareComponent inPlay={inPlay} justFilledByMachine={justFilledByMachine} point={point} piece={squarePiece} isLegalMove={isLegalMove} squarePixels={squarePixels} pointValue={pointValue} enabled={enabled}> {this.renderPiece(point)} </BoardSquareComponent> </div> ); } /** * Render all the squares on the board by accumulating their * component objects in an array and interpolating the array as * the child of a div component. The div component has a style * with the correct overall size of the board. */ render() { let dimension = this.props.board.dimension; let squarePixels = this.props.squarePixels; let squares = []; for (let row = 0; row < dimension; row++) for (let col = 0; col < dimension; col++) squares.push(this.renderSquare(row, col)); return ( <div style={boardStyle(dimension, squarePixels)}> {squares} </div> ); } } export default BoardComponent;
packages/react-scripts/fixtures/kitchensink/src/features/env/ExpandEnvVariables.js
ConnectedHomes/create-react-web-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; export default () => ( <span> <span id="feature-expand-env-1">{process.env.REACT_APP_BASIC}</span> <span id="feature-expand-env-2">{process.env.REACT_APP_BASIC_EXPAND}</span> <span id="feature-expand-env-3"> {process.env.REACT_APP_BASIC_EXPAND_SIMPLE} </span> <span id="feature-expand-env-existing"> {process.env.REACT_APP_EXPAND_EXISTING} </span> </span> );
demo/src/index.js
nteract/notebook-preview
import React from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRedirect, hashHistory } from 'react-router'; import NotebookPreview from 'notebook-preview'; import { fetchFromGist } from './fetchers'; const gistIDs = [ '53f2d7bbc69936bd7a4131c0890fc61d', 'ee778e32b8e62cf634929abe229a8555', '7eadc20426451a0604e26e6f084cac02', '0a9389389ec5ff303c5d5fbfa6bea021', 'b71d96c48326a0e05904a5ad4a96d2b5', '93239f6b97237abf117a348a56afc9e2', ]; const gistID = gistIDs[Math.floor(Math.random() * gistIDs.length)]; class Notebook extends React.Component { constructor() { super(); this.state = { nbJSON: null, } } componentDidMount() { fetchFromGist(this.props.params.gistId).then((nbJSON) => { console.log(nbJSON); this.setState({ nbJSON }); }); } render() { if (this.state.nbJSON) { return <NotebookPreview notebook={this.state.nbJSON}/>; } else { return <h1>Loading Notebook...</h1>; } } } render(( <Router history={hashHistory}> <Route path="/"> <IndexRedirect to={`gist/${gistID}`} /> <Route path="gist/:gistId" component={Notebook}/> </Route> </Router> ), document.getElementById('root'));
src/index.js
steeeeee/udemy-react-redux-blog
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { Router, browserHistory } from 'react-router'; import promise from 'redux-promise' import reducers from './reducers'; import routes from './routes'; const createStoreWithMiddleware = applyMiddleware( promise )(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <Router history={browserHistory} routes={routes} /> </Provider> , document.querySelector('.container'));
node_modules/redbox-react/examples/react-transform-catch-errors/index.js
jdl031/FHIR-test-app
import React from 'react' import App from './components/App' const root = document.getElementById('root') React.render(<App />, root)
packages/material-ui-icons/src/ViewArray.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let ViewArray = props => <SvgIcon {...props}> <path d="M4 18h3V5H4v13zM18 5v13h3V5h-3zM8 18h9V5H8v13z" /> </SvgIcon>; ViewArray = pure(ViewArray); ViewArray.muiName = 'SvgIcon'; export default ViewArray;
src/main/components/Input.js
padcom/react-example-02
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import TitleActions from '../state/title'; import css from './Input.less'; /** * Input field * * @class Input * @ */ const Input = ({ /** * Title * @public * @property title * @type {string} */ title, /** * Actions object * @private * @property actions */ actions }) => { return ( <div class={css.component}> <label class={css({ label: true, green: true })}>Enter title</label> <input class={css.textbox} value={title} onChange={e => actions.changeTitle(e.target.value)} autoFocus /> </div> ) } export default connect( // map state to props state => ({ title: state.title }), // map dispatch to props dispatch => ({ actions: bindActionCreators(TitleActions, dispatch) }) )(Input);
views/decoration_toggle.js
skomski/black-screen
import React from 'react'; export default React.createClass({ getInitialState() { return {enabled: this.props.invocation.state.decorate}; }, handleClick(event) { stopBubblingUp(event); var newState = !this.state.enabled; this.setState({enabled: newState}); this.props.invocation.setState({decorate: newState}); }, render() { var classes = ['decoration-toggle']; if (!this.state.enabled) { classes.push('disabled'); } return ( <a href="#" className={classes.join(' ')} onClick={this.handleClick}> <i className="fa fa-magic"></i> </a> ); } });
tagging_interface/src/views/NewProjectView/NewProjectAnnotators.js
Michael-Stewart-Webdev/annotation-tool
import React from 'react'; import {Component} from 'react'; import NewProjectFormHelpIcon from 'views/NewProjectView/NewProjectFormHelpIcon'; import ProfileIcon from 'views/SharedComponents/ProfileIcon'; import formatDate from 'functions/formatDate' import _fetch from 'functions/_fetch'; function strIsEmail(str) { return str.indexOf("@") > 0 && str.split("@").length === 2; } class UserDetails extends Component { constructor(props) { super(props); } render() { var user = this.props.user; return ( <span className="user-details"> <ProfileIcon user={user.is_registered ? user : null}/> <span> <div className="annotator-username">{user.is_registered ? user.username : user.email}</div> <div className="annotator-registration-date">{user.is_registered ? "Joined on " + formatDate(user.created_at, { no_hours: true }) : "Not yet registered"}</div> </span> </span> ) } } class NewProjectAnnotators extends Component { constructor(props) { super(props); this.state = { data: { users: [], }, loading: true, showingSuggestions: false, userSearchResults: null, userSuggestions: [], searchTerm: '', } } async componentDidMount() { console.log('x', this.props.data); await this.setState({ data: this.props.data, }); // var recentUsers = await this.queryRecentUsers(); var suggestedUsers = this.props.data.suggested_users; this.setState({ loading: false, data: this.props.data, userSuggestions: suggestedUsers, userSearchResults: suggestedUsers.length > 0 ? suggestedUsers : null, showingSuggestions: suggestedUsers.length > 0 ? true : false, }); this.props.updateFormPageData(this.state.data); } // async queryRecentUsers() { // var d = await _fetch('http://localhost:3000/api/projects/new/getSuggestedUsers', 'GET', this.props.setErrorCode, false, false, 200); // return Promise.resolve(d.users); // } async queryAPI() { await this.setState({ loading: true, }) if(this.state.searchTerm.length === 0) { this.setState({ loading: false, userSearchResults: this.state.userSuggestions.length > 0 ? this.state.userSuggestions : null, showingSuggestions: this.state.userSuggestions.length > 0 ? true : false, }) return; } var searchTerm = this.state.searchTerm var isEmail = strIsEmail(searchTerm); var d = await _fetch('projects/new/searchUsers?searchTerm=' + searchTerm + "&isEmail=" + isEmail, 'GET', this.props.setErrorCode, false, false, 200); var result = d.users; if(isEmail && d.users.length === 0) { result = [{ is_registered: false, email: searchTerm, }]; } this.setState({ loading: false, userSearchResults: result, showingSuggestions: false, }); } // Update the search term in the input box. changeSearchTerm(e) { var value = e.target.value; this.setState({ searchTerm: value, }) } submitViaEnter(e) { console.log(e, "EEE"); e.preventDefault(); this.queryAPI(); } onKeyDown(e) { if(e.keyCode === 13) { e.preventDefault(); this.queryAPI(); } } // Check whether the specified user has been added to this.state.data.users. alreadyAddedUser(user) { for(var u of this.state.data.users) { if(user.username && u.username === user.username) { return true; } if(user.email && u.email === user.email) { return true; } } return false; } // Remove the user at the specified index removeUser(index) { var users = [...this.state.data.users]; users.splice(index, 1); this.setState({ data: { ...this.state.data, users: users, } }, () => this.props.updateFormPageData(this.state.data)); } // Adds the user to this.state.data.users (i.e. puts them in the table on the right). addUser(user) { var users = [...this.state.data.users]; users.push(user); this.setState({ data: { ...this.state.data, users: users, } }, () => this.props.updateFormPageData(this.state.data)); return null; } // Highlight the row at the specified index via the delete-hover class (makes it go red). deleteHighlightRow(index) { document.getElementById("annotator-num-" + index).classList.add('delete-hover'); } // Remove the highlighting. removeHighlightRow() { var eles = document.getElementsByClassName("annotator"); for(var ele of eles) { ele.classList.remove("delete-hover"); } } render() { var help = (<div> <h2>Annotators</h2> <p>Please specify the annotators of this project.</p> <p>You can search for annotators by username via the left-side window. Click "add" to add them to this project. An invitation to join your project will be sent to them once the project is created.</p> <p>You can also enter an email address into the search bar. If no account with the email address exists, you can still them as an annotator - Redcoat will send them an invitation to register and join your project once your project has been created.</p> <p>If no search term has been entered, Redcoat will suggest annotators for you based on your recent projects.</p> <p>You can remove annotators using the trash icon in the right-side window. At present you cannot remove yourself from the annotation task.</p> </div> ) /* If input search length < 3, clear search results so that there is nothing in the box If input search length >= 3 and input[:3] !== apiSearchTerm[:3], set apiSearchTerm to input and query API for search results Search results = for loop over api search results to check for matches if input search length > 3 */ //console.log(this.state.data.users, this.state.userSearchResults, this.state.searchTerm.length); return ( <div> <h2>Annotators <NewProjectFormHelpIcon onClick={() => this.props.toggleFormHelp(help)} /></h2> <div className="flex-columns flex-columns-2"> <div className={"flex-column flex-column-33" + (this.state.loading ? " loading-prevent-action" : "")}> <div className="annotators-box"> <div className="annotators-box-header">Annotator lookup</div> <div className="annotators-box-body"> <div className="input-row"> <input id="annotator-name" placeholder="Username or email address" value={this.state.searchTerm} onKeyDown={(e) => this.onKeyDown(e)} onChange={this.changeSearchTerm.bind(this)}> </input> <button onClick={this.queryAPI.bind(this)} className="annotate-button" type="button"><i className="fa fa-search"></i>Search</button> </div> <div className="annotators-box-list search-results"> { this.state.userSearchResults === null && <div className="not-searched-yet">Enter a username or email address above to search for annotators.</div> } { (this.state.userSearchResults && this.state.userSearchResults.length === 0) && <div className="no-search-results">No results found.</div> } { (this.state.userSearchResults && this.state.userSearchResults.length > 0) && <div className="search-results-found"> { this.state.showingSuggestions ? <h4>Suggestions ({this.state.userSearchResults.length})</h4> : <h4>Search results ({this.state.userSearchResults.length})</h4> } { this.state.userSearchResults.map((user, index) => <div className="annotator search-result"> <UserDetails user={user}/> { this.alreadyAddedUser(user) ? <div className="annotate-button user-added">Added<i className="right fa fa-check"></i></div> : <div className="annotate-button" onClick={this.addUser.bind(this, user)}>Add <i className="right fa fa-chevron-right"></i></div> } </div> )} </div> } </div> </div> </div> </div> <div className="flex-column flex-column-66"> <div className="annotators-box"> <div className="annotators-box-header">Annotators to invite</div> <div className="annotators-box-body"> <div className="annotators-box-list "> { this.state.data.users.map((user, index) => <div className="annotator" id={"annotator-num-" + index}> <UserDetails user={user}/> { index > 0 && <span className="delete-button-container"><span className="delete-button" onClick={this.removeUser.bind(this, index)} onMouseEnter={() => this.deleteHighlightRow(index)} onMouseLeave={this.removeHighlightRow} ><i className="fa fa-trash"></i></span></span> } </div> )} </div> </div> </div> </div> </div> </div> ) } } export default NewProjectAnnotators;
src/svg-icons/action/open-in-browser.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionOpenInBrowser = (props) => ( <SvgIcon {...props}> <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h4v-2H5V8h14v10h-4v2h4c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm-7 6l-4 4h3v6h2v-6h3l-4-4z"/> </SvgIcon> ); ActionOpenInBrowser = pure(ActionOpenInBrowser); ActionOpenInBrowser.displayName = 'ActionOpenInBrowser'; ActionOpenInBrowser.muiName = 'SvgIcon'; export default ActionOpenInBrowser;
crowdpact/static/js/apps/pact/home/components/PactHomeApp.js
joshmarlow/crowdpact
import React from 'react'; class PactHomeApp extends React.Component { render() { return ( <div> <h1> Welcome to CrowdPact {this.props.pageData.get('user').get('username')}! </h1> <a href={this.props.pageData.get('logout_url')}>Logout</a> </div> ); } } export default PactHomeApp;
tutorials05/module/b.js
Ivanwangcy/webpack-tutorials
import React from 'react'; var Content = React.createClass({ render: function() { return ( <div>App Content <div className="container"></div> </div> ); } }) export default Content;
docs/src/app/components/pages/components/DropDownMenu/Page.js
hai-cea/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import dropDownMenuReadmeText from './README'; import DropDownMenuSimpleExample from './ExampleSimple'; import dropDownMenuSimpleExampleCode from '!raw!./ExampleSimple'; import DropDownMenuOpenImmediateExample from './ExampleOpenImmediate'; import dropDownMenuOpenImmediateExampleCode from '!raw!./ExampleOpenImmediate'; import DropDownMenuLongMenuExample from './ExampleLongMenu'; import dropDownMenuLongMenuExampleCode from '!raw!./ExampleLongMenu'; import DropDownMenuLabeledExample from './ExampleLabeled'; import dropDownMenuLabeledExampleCode from '!raw!./ExampleLabeled'; import dropDownMenuCode from '!raw!material-ui/DropDownMenu/DropDownMenu'; const descriptions = { simple: '`DropDownMenu` is implemented as a controlled component, with the current selection set through the ' + '`value` property.', openImmediate: 'With `openImmediately` property set, the menu will open on mount.', long: 'With the `maxHeight` property set, the menu will be scrollable if the number of items causes the height ' + 'to exceed this limit.', label: 'With a `label` applied to each `MenuItem`, `DropDownMenu` displays a complementary description ' + 'of the selected item.', }; const DropDownMenuPage = () => ( <div> <Title render={(previousTitle) => `Drop Down Menu - ${previousTitle}`} /> <MarkdownElement text={dropDownMenuReadmeText} /> <CodeExample title="Simple example" description={descriptions.simple} code={dropDownMenuSimpleExampleCode} > <DropDownMenuSimpleExample /> </CodeExample> <CodeExample title="Open Immediate example" description={descriptions.openImmediate} code={dropDownMenuOpenImmediateExampleCode} > <DropDownMenuOpenImmediateExample /> </CodeExample> <CodeExample title="Long example" description={descriptions.long} code={dropDownMenuLongMenuExampleCode} > <DropDownMenuLongMenuExample /> </CodeExample> <CodeExample title="Label example" description={descriptions.label} code={dropDownMenuLabeledExampleCode} > <DropDownMenuLabeledExample /> </CodeExample> <PropTypeDescription code={dropDownMenuCode} /> </div> ); export default DropDownMenuPage;
app/javascript/mastodon/features/ui/components/media_modal.js
palon7/mastodon
import React from 'react'; import ReactSwipeableViews from 'react-swipeable-views'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ExtendedVideoPlayer from '../../../components/extended_video_player'; import { defineMessages, injectIntl } from 'react-intl'; import IconButton from '../../../components/icon_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImageLoader from './image_loader'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, previous: { id: 'lightbox.previous', defaultMessage: 'Previous' }, next: { id: 'lightbox.next', defaultMessage: 'Next' }, }); @injectIntl export default class MediaModal extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.list.isRequired, index: PropTypes.number.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { index: null, }; handleSwipe = (index) => { this.setState({ index: (index) % this.props.media.size }); } handleNextClick = () => { this.setState({ index: (this.getIndex() + 1) % this.props.media.size }); } handlePrevClick = () => { this.setState({ index: (this.props.media.size + this.getIndex() - 1) % this.props.media.size }); } handleKeyUp = (e) => { switch(e.key) { case 'ArrowLeft': this.handlePrevClick(); break; case 'ArrowRight': this.handleNextClick(); break; } } componentDidMount () { window.addEventListener('keyup', this.handleKeyUp, false); } componentWillUnmount () { window.removeEventListener('keyup', this.handleKeyUp); } getIndex () { return this.state.index !== null ? this.state.index : this.props.index; } render () { const { media, intl, onClose } = this.props; const index = this.getIndex(); const leftNav = media.size > 1 && <button tabIndex='0' className='modal-container__nav modal-container__nav--left' onClick={this.handlePrevClick} aria-label={intl.formatMessage(messages.previous)}><i className='fa fa-fw fa-chevron-left' /></button>; const rightNav = media.size > 1 && <button tabIndex='0' className='modal-container__nav modal-container__nav--right' onClick={this.handleNextClick} aria-label={intl.formatMessage(messages.next)}><i className='fa fa-fw fa-chevron-right' /></button>; const content = media.map((image) => { const width = image.getIn(['meta', 'original', 'width']) || null; const height = image.getIn(['meta', 'original', 'height']) || null; if (image.get('type') === 'image') { return <ImageLoader previewSrc={image.get('preview_url')} src={image.get('url')} width={width} height={height} key={image.get('preview_url')} />; } else if (image.get('type') === 'gifv') { return <ExtendedVideoPlayer src={image.get('url')} muted controls={false} width={width} height={height} key={image.get('preview_url')} />; } return null; }).toArray(); return ( <div className='modal-root__modal media-modal'> {leftNav} <div className='media-modal__content'> <IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={16} /> <ReactSwipeableViews onChangeIndex={this.handleSwipe} index={index} animateHeight> {content} </ReactSwipeableViews> </div> {rightNav} </div> ); } }
platform/ui/src/components/radioButtonList/RadioButtonList.js
OHIF/Viewers
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './RadioButtonList.css'; export class RadioButtonList extends Component { static className = 'RadioButtonList'; //TODO: Add fields to propTypes.description? //These would be label (required), id (required), and checked (optional). static propTypes = { description: PropTypes.arrayOf( PropTypes.shape({ label: PropTypes.string.isRequired, id: PropTypes.string.isRequired, checked: PropTypes.bool, }) ), }; constructor(props) { super(props); this.state = {}; for (let button of props.description) { if (button.checked) { this.state.checked = button.id; } } } handleChange(e) { this.setState({ checked: e.target.value }); } render() { let buttons = this.props.description.map(button => { let input = ( <input type="radio" checked={this.state.checked === button.id} onChange={e => { this.handleChange(e); }} value={button.id} /> ); //needed to style the custom radio check let inputSpan; if (this.state.checked === button.id) { inputSpan = ( <span className="ohif-radio-button ohif-selected">{input}</span> ); } else { inputSpan = <span className="ohif-radio-button">{input}</span>; } return ( <span className="ohif-radio-button-container" key={button.id}> <label className="ohif-radio-button-label"> {inputSpan} {button.label} </label> </span> ); }); return ( <div className="ohif-radio-button-group"> <form>{buttons}</form> </div> ); } }
src/svg-icons/image/movie-filter.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageMovieFilter = (props) => ( <SvgIcon {...props}> <path d="M18 4l2 3h-3l-2-3h-2l2 3h-3l-2-3H8l2 3H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4zm-6.75 11.25L10 18l-1.25-2.75L6 14l2.75-1.25L10 10l1.25 2.75L14 14l-2.75 1.25zm5.69-3.31L16 14l-.94-2.06L13 11l2.06-.94L16 8l.94 2.06L19 11l-2.06.94z"/> </SvgIcon> ); ImageMovieFilter = pure(ImageMovieFilter); ImageMovieFilter.displayName = 'ImageMovieFilter'; ImageMovieFilter.muiName = 'SvgIcon'; export default ImageMovieFilter;
src/index.js
guanzhou-zhao/calculate-cabinet-plan
import React from 'react' import { render } from 'react-dom' import App from './components/App' // import App from './meta/App' // Try fs in electron // import fs from 'fs' // import path from 'path' // var filePath = path.resolve(__dirname, '..', 'README.md'); // fs.readFile(filePath, 'utf8', (err, data) => { // if (err) throw err; // console.log(data); // }); var element = document.createElement('div'); document.body.appendChild(element); render(<App />, element)
frontend/src/pages/NetworkOverview.js
esarafianou/rupture
import React from 'react'; import { Link } from 'react-router'; import axios from 'axios'; import _ from 'lodash'; import AttackListDetails from '../containers/AttackListDetails'; import NotStartedVictims from '../containers/NotStartedVictims'; import WifiScan from '../containers/Wifiscan'; import GhostPc from '../img/ghost_pc.png'; export default class NetworkOverview extends React.Component { constructor() { super(); this.state = { attacks: [], victims: [] }; } onScan = (victims) => { this.setState({ victims: victims }); } scanForVictims = () => { return( <div className='welcomemessage' > <a href onClick={ this.handleClick }> Scan for new victims </a> or <Link to='attackconfig'> add a custom one</Link> </div> ); } handleClick = () => { axios.get('/breach/victim/notstarted') .then(res => { let victims = res.data['new_victims']; this.onScan(victims); }) .catch(error => { console.log(error); }); } getVictims = () => { axios.get('/breach/victim') .then(res => { let results = _.partition(res.data['victims'], { state: 'discovered' }); this.setState({ victims: results[0], attacks: results[1] }) }) .catch(error => { console.log(error); }); } componentDidMount() { this.getVictims(); } render() { return( <div> <div className='container-fluid'> <h1> Network Overview </h1> <div className='row'> <div id='mainpage' className='col-md-8 col-xs-12 col-sm-6 col-lg-8'> { this.state.attacks.length > 0 ? <AttackListDetails attacks={ this.state.attacks } onReload={ this.getVictims }/> : null} { this.state.victims.length > 0 ? <NotStartedVictims victims={ this.state.victims }/> : null} { this.state.victims.length === 0 && this.state.attacks.length === 0 ? this.scanForVictims() : null} </div> <div className='button col-md-4 col-xs-6 col-lg-4'> <WifiScan onUpdate={ this.onScan }/> <div className='ghost'> <Link to='attackconfig'> <img src={GhostPc} alt='A Ghost PC' title='Add a custom victim' className='nooutline'/> <span className='line leftpadding'>Add custom victim</span> </Link> </div> </div> </div> </div> </div> ); } }
js/views/XAutosuggest.js
acthp/ucsc-xena-client
/** * UCSC Xena Client * http://xena.ucsc.edu * * Standard Xena autosuggest, with UI/UX based on Material Design's full-width inputs. Light wrapper around * react-autosuggest package. * * All props with the exception of the state and actions specified below, are passed directly to Autosuggest. * * State * ----- * value - Current selected value. * * Actions * ------- * onClear - Called on click of clear (X) button. */ /* * Unfortunate behaviors of react-autosuggest * ghost suggestions * https://github.com/moroshko/react-autosuggest/issues/596 * escape clears input * This is part of ARIA specification, but react-autosuggest implements it * at variance with the spec (an editable autosuggest should clear the * suggested text, not all text), and in practice the prescribed AIRA * behavior is not usable, because escape also closes suggestions, making * it very common to lose input accidentally. * */ // Core dependencies, components import React from 'react'; import Autosuggest from 'react-autosuggest'; // Styles import autosuggestTheme from './AutosuggestTheme.module.css'; import compStyles from './XAutosuggest.module.css'; class XAutosuggest extends React.Component { callInputRef = autosuggest => { var {inputRef, autosuggestRef} = this.props; if (inputRef) { inputRef(autosuggest && autosuggest.input); } if (autosuggestRef) { autosuggestRef(autosuggest); } } render() { var {value, onClear, ...autoProps} = this.props; return ( <div className={compStyles.XAutosuggest}> <Autosuggest {...autoProps} ref={this.callInputRef} theme={autosuggestTheme}/> {value ? <i className='material-icons' onClick={onClear}>close</i> : null} </div> ); } } export default XAutosuggest;
intro-manager/src/main/resources/static/js/src/lib/view/Introduction.js
suzukiyo/ddd
import React from 'react'; export default class Introduction extends React.Component { constructor(props) { super(props); } componentWillMount() { } render() { } componentDidMount() { } }
src/parser/druid/feral/modules/racials/Shadowmeld.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import RACES from 'game/RACES'; import Analyzer from 'parser/core/Analyzer'; import Abilities from 'parser/core/modules/Abilities'; const BUFF_WINDOW_TIME = 60; /** * The Night Elf racial ability Shadowmeld can be used by as a DPS cooldown for Feral druids. * The stealth provided by Shadowmeld doubles the damage of a Rake cast while it's active. * This analyzer checks how often Shadowmeld is being to buff Rake's damage. */ class Shadowmeld extends Analyzer { static dependencies = { abilities: Abilities, }; wastedDuringStealth = 0; correctUses = 0; totalUses = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.race === RACES.NightElf; } on_byPlayer_cast(event) { if (event.ability.guid === SPELLS.RAKE.id && this.selectedCombatant.hasBuff(SPELLS.SHADOWMELD.id, null, BUFF_WINDOW_TIME)) { // using Rake when Shadowmeld is active means Shadowmeld was used correctly this.correctUses += 1; return; } if (event.ability.guid !== SPELLS.SHADOWMELD.id) { return; } this.totalUses += 1; if (this.selectedCombatant.hasBuff(SPELLS.INCARNATION_KING_OF_THE_JUNGLE_TALENT.id) || this.selectedCombatant.hasBuff(SPELLS.PROWL.id, null, BUFF_WINDOW_TIME) || this.selectedCombatant.hasBuff(SPELLS.PROWL_INCARNATION.id, null, BUFF_WINDOW_TIME)) { // using Shadowmeld when the player already has a stealth (or stealth-like) effect active is almost always a mistake this.wastedDuringStealth += 1; } } get possibleUses() { const cooldown = this.abilities.getAbility(SPELLS.SHADOWMELD.id).cooldown * 1000; return Math.floor(this.owner.fightDuration / cooldown) + 1; } get efficiencyThresholds() { return { actual: this.correctUses / this.possibleUses, isLessThan: { minor: 0.90, average: 0.80, major: 0.70, }, style: 'percentage', }; } get wastedDuringStealthThresholds() { return { actual: this.wastedDuringStealth / this.totalUses, isGreaterThan: { minor: 0.0, average: 0.10, major: 0.20, }, style: 'percentage', }; } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.SHADOWMELD.id} />} value={`${formatPercentage(this.correctUses / this.possibleUses)}%`} label="Shadowmeld used to buff Rake" tooltip={( <> You used Shadowmeld <strong>{this.correctUses}</strong> times to increase Rake's damage.<br /> <ul> <li>You could have used it <strong>{this.possibleUses}</strong> times.</li> <li>You used it <strong>{this.totalUses}</strong> times (<strong>{this.totalUses - this.correctUses}</strong> didn't buff Rake.)</li> <li>You used Shadowmeld while already benefiting from a stealth effect <strong>{this.wastedDuringStealth}</strong> times.</li> </ul> </> )} position={STATISTIC_ORDER.OPTIONAL()} /> ); } suggestions(when) { when(this.efficiencyThresholds).addSuggestion((suggest, actual, recommended) => { return suggest( <React.Fragment> You could be using <SpellLink id={SPELLS.SHADOWMELD.id} /> to increase your <SpellLink id={SPELLS.RAKE.id} /> damage more often. Activating <SpellLink id={SPELLS.SHADOWMELD.id} /> and immediately using <SpellLink id={SPELLS.RAKE.id} /> will cause it to deal double damage. </React.Fragment>, ) .icon(SPELLS.SHADOWMELD.icon) .actual(`${(actual * 100).toFixed(0)}% cast efficiency.`) .recommended(`>${(recommended * 100).toFixed(0)}% is recommended`); }); when(this.wastedDuringStealthThresholds).addSuggestion((suggest, actual, recommended) => { return suggest( <React.Fragment> You are wasting <SpellLink id={SPELLS.SHADOWMELD.id} /> by using it when you already have a stealth effect active. </React.Fragment>, ) .icon(SPELLS.SHADOWMELD.icon) .actual(`${this.wastedDuringStealth} cast${this.wastedDuringStealth === 1 ? '' : 's'} when already stealthed.`) .recommended('0 is recommended'); }); } } export default Shadowmeld;
app/assets/javascripts/components/EditorHeader.js
rnplay/rnplay-web
'use strict'; import React, { Component } from 'react'; import classNames from 'classnames'; import AppName from './AppName'; import MainMenu from './MainMenu'; import GitModal from './git_modal'; const maybeCallMethod = (obj, method, ...args) => { obj[method] && obj[method](...args); }; export default class EditorHeader extends Component { constructor(props) { super(props); this.state = { gitModalIsVisible: null, isMenuOpen: false }; } onMenuToggle() { this.setState({ isMenuOpen: !this.state.isMenuOpen }); } onUpdateName = (e) => { e.preventDefault(); maybeCallMethod(this.props, 'onUpdateName', e.target.value); } handleOnSubmit = (e) => { e.preventDefault(); e.preventPropagation(); } onSave = (e) => { e.preventDefault(); maybeCallMethod(this.props, 'onSave'); } onFork = (e) => { e.preventDefault(); maybeCallMethod(this.props, 'onFork'); } onPick = (e) => { e.preventDefault(); maybeCallMethod(this.props, 'onPick'); } onUpdateBuild = (value) => { maybeCallMethod(this.props, 'onUpdateBuild', value); } currentUserIsAdmin() { const { currentUser } = this.props; return currentUser && currentUser.admin; } isUserLoggedIn() { const { currentUser } = this.props; return !!currentUser; } showGitModal = (e) => { e.preventDefault(); this.setState({gitModalIsVisible: true}); } hideGitModal = (e) => { e.preventDefault(); this.setState({gitModalIsVisible: false}); } renderGitModal = () => { if (this.props.belongsToCurrentUser()) { return ( <GitModal app={this.props.app} token={this.props.currentUser.authentication_token} onClickBackdrop={this.hideGitModal} isOpen={this.state.gitModalIsVisible} /> ) } } renderGitButton() { if ( ! this.props.belongsToCurrentUser()) { return ( <button onClick={this.showGitModal} className="editor-header__button"> Clone </button> ); } } renderForkButton() { return ( <button onClick={this.onFork} type="button" className="editor-header__button"> <i className="fa fa-code-fork"></i> Fork </button> ); } renderPickButton() { if (this.currentUserIsAdmin()) { const icon = this.props.appIsPicked ? 'fa-star' : 'fa-star-o'; const iconClasses = `fa ${icon}`; return ( <button onClick={this.onPick} className="editor-header__button"> <i className={iconClasses}></i> {this.props.appIsPicked ? 'Unpick' : 'Pick'} </button> ); } } getAppName() { const { name } = this.props; return name && name.length > 0 ? name : 'Unnamed App'; } render() { const disabled = ! this.props.belongsToCurrentUser(); const { creator } = this.props; const classes = classNames({ 'editor-header__bar': true, 'editor-header': true, }); return ( <div className={classes}> <MainMenu isOpen={this.state.isMenuOpen} isUserLoggedIn={this.isUserLoggedIn()} onMenuToggle={this.onMenuToggle.bind(this)} /> <button className="editor-header__button editor-header__menu-toggle" onClick={this.onMenuToggle.bind(this)} title="Open Menu"> <i className="fa fa-bars"></i> </button> <AppName isDisabled={disabled} appName={this.getAppName()} onUpdateName={this.onUpdateName.bind(this)} creator={creator} /> <div className="editor-header__actions"> {this.renderForkButton()} {this.renderPickButton()} </div> {this.renderGitModal()} </div> ); } }
node_modules/eslint-config-airbnb/test/test-react-order.js
tausifmuzaffar/bisApp
import test from 'tape'; import { CLIEngine } from 'eslint'; import eslintrc from '../'; import reactRules from '../rules/react'; import reactA11yRules from '../rules/react-a11y'; const cli = new CLIEngine({ useEslintrc: false, baseConfig: eslintrc, rules: { // It is okay to import devDependencies in tests. 'import/no-extraneous-dependencies': [2, { devDependencies: true }], }, }); function lint(text) { // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles // @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext const linter = cli.executeOnText(text); return linter.results[0]; } function wrapComponent(body) { return ` import React from 'react'; export default class MyComponent extends React.Component { /* eslint no-empty-function: 0, class-methods-use-this: 0 */ ${body} } `; } test('validate react prop order', (t) => { t.test('make sure our eslintrc has React and JSX linting dependencies', (t) => { t.plan(2); t.deepEqual(reactRules.plugins, ['react']); t.deepEqual(reactA11yRules.plugins, ['jsx-a11y', 'react']); }); t.test('passes a good component', (t) => { t.plan(3); const result = lint(wrapComponent(` componentWillMount() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} someMethod() {} renderDogs() {} render() { return <div />; } `)); t.notOk(result.warningCount, 'no warnings'); t.notOk(result.errorCount, 'no errors'); t.deepEquals(result.messages, [], 'no messages in results'); }); t.test('order: when random method is first', (t) => { t.plan(2); const result = lint(wrapComponent(` someMethod() {} componentWillMount() {} componentDidMount() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); }); t.test('order: when random method after lifecycle methods', (t) => { t.plan(2); const result = lint(wrapComponent(` componentWillMount() {} componentDidMount() {} someMethod() {} setFoo() {} getFoo() {} setBar() {} renderDogs() {} render() { return <div />; } `)); t.ok(result.errorCount, 'fails'); t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort'); }); });
src/components/Panel/Panel.js
pavelsuraba/react-animations
/* eslint-disable no-unused-vars */ import React, { Component } from 'react'; import styled from 'styled-components'; /* eslint-enable no-unused-vars */ const Panel = styled.div` width: 300px; height: 100%; position: fixed; top: 0; right: ${props => props.direction === 'right' ? 0 : 'auto' }; left: ${props => props.direction === 'left' ? 0 : 'auto' }; background-color: #3498db; color: #fff; text-align: center; padding: 30px; will-change: transform; `; export default class extends Component { getDom() { return this.el; } render() { return ( <Panel innerRef={c => this.el = c} direction={this.props.direction}>Text</Panel> ); } }
src/components/PageDropdownContainer.js
ttrentham/Griddle
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from '../utils/griddleConnect'; import compose from 'recompose/compose'; import mapProps from 'recompose/mapProps'; import getContext from 'recompose/getContext'; import { currentPageSelector, maxPageSelector, classNamesForComponentSelector, stylesForComponentSelector } from '../selectors/dataSelectors'; const enhance = ( connect((state, props) => ({ maxPages: maxPageSelector(state, props), currentPage: currentPageSelector(state, props), className: classNamesForComponentSelector(state, 'PageDropdown'), style: stylesForComponentSelector(state, 'PageDropdown'), })) ); export default enhance;
packages/material-ui-icons/src/SignalCellular2BarTwoTone.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M2 22h20V2L2 22z" /><path d="M14 10L2 22h12V10z" /></React.Fragment> , 'SignalCellular2BarTwoTone');
docs/pages/getting-started/example-projects.js
lgollut/material-ui
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'getting-started/example-projects'; const requireDemo = require.context( 'docs/src/pages/getting-started/example-projects', false, /\.(js|tsx)$/, ); const requireRaw = require.context( '!raw-loader!../../src/pages/getting-started/example-projects', false, /\.(js|md|tsx)$/, ); export default function Page({ demos, docs }) { return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
src/svg-icons/action/polymer.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPolymer = (props) => ( <SvgIcon {...props}> <path d="M19 4h-4L7.11 16.63 4.5 12 9 4H5L.5 12 5 20h4l7.89-12.63L19.5 12 15 20h4l4.5-8z"/> </SvgIcon> ); ActionPolymer = pure(ActionPolymer); ActionPolymer.displayName = 'ActionPolymer'; export default ActionPolymer;
app/jsx/grade_summary/SelectMenu.js
djbender/canvas-lms
/* * Copyright (C) 2017 - 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 PropTypes from 'prop-types' import React from 'react' import Select from '@instructure/ui-core/lib/components/Select' export default function SelectMenu(props) { const options = props.options.map(option => { const text = option[props.textAttribute] const value = option[props.valueAttribute] return ( <option key={value} value={value}> {text} </option> ) }) return ( <Select defaultValue={props.defaultValue} disabled={props.disabled} id={props.id} inline label={props.label} onChange={props.onChange} width="15rem" > {options} </Select> ) } SelectMenu.propTypes = { defaultValue: PropTypes.string.isRequired, disabled: PropTypes.bool.isRequired, id: PropTypes.string.isRequired, label: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, options: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.array, PropTypes.object])).isRequired, textAttribute: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, valueAttribute: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired }
src/svg-icons/action/note-add.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionNoteAdd = (props) => ( <SvgIcon {...props}> <path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 14h-3v3h-2v-3H8v-2h3v-3h2v3h3v2zm-3-7V3.5L18.5 9H13z"/> </SvgIcon> ); ActionNoteAdd = pure(ActionNoteAdd); ActionNoteAdd.displayName = 'ActionNoteAdd'; ActionNoteAdd.muiName = 'SvgIcon'; export default ActionNoteAdd;
boxroom/archive/backup-js-glow-2018-01-28/boxroom/archive/js-glow-2018-01-21/src/performance/dbmon/react/app.js
js-works/js-surface
/** @jsx React.createElement */ import ENV from '../shared/env.js'; import React from 'react'; import ReactDOM from 'react-dom'; export default class DBMon extends React.Component { constructor(props) { super(props); this.state = { databases: [] }; } loadSamples() { this.setState({ databases: ENV.generateData().toArray() }); Monitoring.renderRate.ping(); setTimeout(this.loadSamples, ENV.timeout); } componentDidMount() { this.loadSamples(); } render() { return ( <div> <table className="table table-striped latest-data"> <tbody> { this.state.databases.map(function(database) { return ( <tr key={database.dbname}> <td className="dbname"> {database.dbname} </td> <td className="query-count"> <span className={database.lastSample.countClassName}> {database.lastSample.nbQueries} </span> </td> { database.lastSample.topFiveQueries.map(function(query, index) { return ( <td className={ "Query " + query.elapsedClassName}> {query.formatElapsed} <div className="popover left"> <div className="popover-content">{query.query}</div> <div className="arrow"/> </div> </td> ); }) } </tr> ); }) } </tbody> </table> </div> ); } } ReactDOM.render(<DBMon />, document.getElementById('dbmon'));
test/appwraper-test.js
miktown/wordpress-reactjs
'use strict' import test from 'ava' import React from 'react' import { shallow, mount } from 'enzyme' import 'jsdom-global/register' import AppWrapper from '../app/containers/app' test('shallow unit component <AppWrapper />', t => { let mock = {} mock.name = 'moo' const wrapper = shallow(<AppWrapper />) const wrapperMoo = shallow(<AppWrapper name={mock.name} />) t.is(wrapper.contains(<p>Hello <strong>World</strong></p>), true) t.is(wrapperMoo.contains(<p>Hello <strong>{mock.name}</strong></p>), true) }) test('mount <AppWrapper />', t => { const wrapper = mount(<AppWrapper />) const fooInner = wrapper.find('p') t.is(fooInner.length, 1, 'Tiene un único strong') }) test('<AppWrapper /> -> setNameFromProps set name hello + name', t => { let appWrapper = new AppWrapper() let result = {} let mock = {} mock.text = 'mooo' mock.number = 123 mock.voidString = '' result.paramText = appWrapper.setNameFromProps(mock.text) result.paramVoid = appWrapper.setNameFromProps() result.paramNumber = appWrapper.setNameFromProps(mock.number) result.paramVoidString = appWrapper.setNameFromProps(mock.voidString) t.is(typeof appWrapper.setNameFromProps, 'function', 'setNameFromProps is function') t.is(result.paramText, mock.text, 'Param shold return param') t.is(result.paramVoid, 'World', 'Default void param shold return World') t.is(result.paramNumber, 'World', 'Not String returns World') t.is(result.paramVoidString, 'World', 'void string returns World') })
app/javascript/mastodon/features/keyboard_shortcuts/index.js
codl/mastodon
import React from 'react'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ heading: { id: 'keyboard_shortcuts.heading', defaultMessage: 'Keyboard Shortcuts' }, }); @injectIntl export default class KeyboardShortcuts extends ImmutablePureComponent { static propTypes = { intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; render () { const { intl } = this.props; return ( <Column icon='question' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <div className='keyboard-shortcuts scrollable optionally-scrollable'> <table> <thead> <tr> <th><FormattedMessage id='keyboard_shortcuts.hotkey' defaultMessage='Hotkey' /></th> <th><FormattedMessage id='keyboard_shortcuts.description' defaultMessage='Description' /></th> </tr> </thead> <tbody> <tr> <td><kbd>r</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.reply' defaultMessage='to reply' /></td> </tr> <tr> <td><kbd>m</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.mention' defaultMessage='to mention author' /></td> </tr> <tr> <td><kbd>f</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.favourite' defaultMessage='to favourite' /></td> </tr> <tr> <td><kbd>b</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.boost' defaultMessage='to boost' /></td> </tr> <tr> <td><kbd>enter</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.enter' defaultMessage='to open status' /></td> </tr> <tr> <td><kbd>up</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.up' defaultMessage='to move up in the list' /></td> </tr> <tr> <td><kbd>down</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.down' defaultMessage='to move down in the list' /></td> </tr> <tr> <td><kbd>1</kbd>-<kbd>9</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.column' defaultMessage='to focus a status in one of the columns' /></td> </tr> <tr> <td><kbd>n</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.compose' defaultMessage='to focus the compose textarea' /></td> </tr> <tr> <td><kbd>alt</kbd>+<kbd>n</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.toot' defaultMessage='to start a brand new toot' /></td> </tr> <tr> <td><kbd>backspace</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.back' defaultMessage='to navigate back' /></td> </tr> <tr> <td><kbd>s</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.search' defaultMessage='to focus search' /></td> </tr> <tr> <td><kbd>esc</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.unfocus' defaultMessage='to un-focus compose textarea/search' /></td> </tr> <tr> <td><kbd>?</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.legend' defaultMessage='to display this legend' /></td> </tr> </tbody> </table> </div> </Column> ); } }
src/svg-icons/notification/airline-seat-legroom-extra.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatLegroomExtra = (props) => ( <SvgIcon {...props}> <path d="M4 12V3H2v9c0 2.76 2.24 5 5 5h6v-2H7c-1.66 0-3-1.34-3-3zm18.83 5.24c-.38-.72-1.29-.97-2.03-.63l-1.09.5-3.41-6.98c-.34-.68-1.03-1.12-1.79-1.12L11 9V3H5v8c0 1.66 1.34 3 3 3h7l3.41 7 3.72-1.7c.77-.36 1.1-1.3.7-2.06z"/> </SvgIcon> ); NotificationAirlineSeatLegroomExtra = pure(NotificationAirlineSeatLegroomExtra); NotificationAirlineSeatLegroomExtra.displayName = 'NotificationAirlineSeatLegroomExtra'; NotificationAirlineSeatLegroomExtra.muiName = 'SvgIcon'; export default NotificationAirlineSeatLegroomExtra;
app/javascript/mastodon/features/standalone/community_timeline/index.js
Arukas/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../../ui/containers/status_list_container'; import { refreshCommunityTimeline, expandCommunityTimeline, } from '../../../actions/timelines'; import Column from '../../../components/column'; import ColumnHeader from '../../../components/column_header'; import { defineMessages, injectIntl } from 'react-intl'; import { connectCommunityStream } from '../../../actions/streaming'; const messages = defineMessages({ title: { id: 'standalone.public_title', defaultMessage: 'A look inside...' }, }); @connect() @injectIntl export default class CommunityTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } componentDidMount () { const { dispatch } = this.props; dispatch(refreshCommunityTimeline()); this.disconnect = dispatch(connectCommunityStream()); } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } handleLoadMore = () => { this.props.dispatch(expandCommunityTimeline()); } render () { const { intl } = this.props; return ( <Column ref={this.setRef}> <ColumnHeader icon='users' title={intl.formatMessage(messages.title)} onClick={this.handleHeaderClick} /> <StatusListContainer timelineId='community' loadMore={this.handleLoadMore} scrollKey='standalone_public_timeline' trackScroll={false} /> </Column> ); } }
app/assets/javascripts/components/pages/EventsDetailPageView.js
loggingroads/onboarding
'use strict'; import React from 'react'; import DataTableView from './../DataTableView'; import Map from './../../containers/MapContainer'; class EventsDetailView extends React.Component { constructor(props) { super(props); const path = window.location.pathname.split('/'); this.eventId = path[path.length - 1]; this.state = { activeTab: "tab1", currentEvent: this.eventId }; } componentDidMount() { //All mapathons this.props.setEventDetail(this.eventId); } changeTab(tab) { this.setState({activeTab: tab}); } render() { /* Slug must match with column name from API. */ const taskTable = ( <DataTableView identity="tasks" base_url="/tasks" data={this.props.eventDetail && this.props.eventDetail.tasks} columns={[ { title: 'Deadline', slug: 'deadline' }, { title: 'Task Name', slug: 'name' }, { title: 'Type', slug: 'task_type' }, { title: 'State', slug: 'status' } ]} /> ); return ( <div> <Map tasksList={this.props.eventDetail && this.props.eventDetail.tasks} campaignId={this.props.eventDetail && this.props.eventDetail.campaign_id} eventId={this.props.eventDetail && this.props.eventDetail.id} /> </div> ); } } export default EventsDetailView;
docs/app/Examples/elements/List/Types/ListExampleOrderedValue.js
koenvg/Semantic-UI-React
import React from 'react' import { List } from 'semantic-ui-react' const ListExampleOrderedValue = () => ( <List as='ol'> <List.Item as='li' value='*'>Signing Up</List.Item> <List.Item as='li' value='*'>User Benefits</List.Item> <List.Item as='li' value='*'> User Types <List.Item as='ol'> <List.Item as='li' value='-'>Admin</List.Item> <List.Item as='li' value='-'>Power User</List.Item> <List.Item as='li' value='-'>Regular User</List.Item> </List.Item> </List.Item> <List.Item as='li' value='*'>Deleting Your Account</List.Item> </List> ) export default ListExampleOrderedValue
src/Components/Header/index.js
arthurflachs/react-webpack-config
import React from 'react' import styles from './styles.css' import HomeIcon from '../HomeIcon' export default function Header() { return ( <div className={styles.Header}> <div className={styles.Title}> <HomeIcon /> </div> <div className={styles.Actions}> </div> </div> ) }
src/examples/TimeTravel.js
steos/elmar.js
import R from 'ramda' import React from 'react' import {forward, mapEffects, message, targetValue} from '../elmar' const init = component => (...args) => { const [model, effects] = component.init(...args) return [{ component: model, lastAction: performance.now(), history: [], future: [], time: 0, realtime: false, speed: 200 }, mapEffects(Action.UpdateComponent(component), effects)] } const timeDelta = start => { const now = performance.now() return [now, now - start] } const Action = { UpdateComponent: component => action => model => { const [componentModel, effects] = component.update(action, model.component) const [now, elapsed] = timeDelta(model.lastAction) return [{...model, component: componentModel, history: R.append([elapsed, model.component], model.history), future: [], lastAction: now, }, mapEffects(Action.UpdateComponent(component), effects)] }, Undo: model => { const [time, component] = R.last(model.history) return [{...model, component, time, future: R.append([model.time, model.component], model.future), history: R.dropLast(1, model.history), lastAction: performance.now() }, []] }, Redo: model => { const [time, component] = R.last(model.future) return [{...model, component, time, future: R.dropLast(1, model.future), history: R.append([model.time, model.component], model.history), lastAction: performance.now() }, []] }, Rewind: model => { const [time, component] = R.head(model.history) return [{...model, component, time, future: model.future.concat([[model.time, model.component]], R.drop(1, model.history).reverse()), history: [], lastAction: performance.now() }, []] }, Replay: model => { if (model.future.length > 0) { const nextModel = R.head(update(Action.Redo, model)) return [ nextModel, [delayAction(Action.Replay, model.realtime ? nextModel.time : model.speed)] ] } else { return [model, []] } }, ToggleRealtime: model => [{...model, lastAction: performance.now(), realtime: !model.realtime }, []], ChangeSpeed: value => model => [{...model, lastAction: performance.now(), speed: Math.max(100, Math.min(1000, parseInt(value, 10))) }, []] } const delayAction = (action, delay) => () => new Promise(resolve => setTimeout(() => resolve(action), delay)) const update = (action, model) => action(model) const view = component => (signal, model) => ( <div> <div style={{background:'#ccc', padding:'.2em'}}> <strong>TimeTravelContainer</strong> <div> <button disabled={model.history.length < 1} onClick={signal(Action.Undo)}>Undo</button> <button disabled={model.future.length < 1} onClick={signal(Action.Redo)}>Redo</button> <button disabled={model.future.length < 1} onClick={signal(Action.Replay)}>Replay</button> <button disabled={model.history.length < 1} onClick={signal(Action.Rewind)}>Rewind</button> <label>Speed:</label> <input type="number" min="100" max="1000" step="100" value={model.realtime ? model.time : model.speed} disabled={model.realtime} onChange={message(signal, R.compose(Action.ChangeSpeed, targetValue))}/> <span>ms</span> <input type="checkbox" checked={model.realtime} onChange={signal(Action.ToggleRealtime)}/> <label>Realtime</label> </div> </div> <table width="100%" style={{borderSpacing:2}}> <tbody> <tr> <td width="50%" style={{border:'2px solid #999', verticalAlign:'top'}}> {component.view(forward(signal, Action.UpdateComponent(component)), model.component)} </td> <td style={{border:'2px solid #999', verticalAlign:'top'}}> <textarea spellCheck={false} autoComplete={false} rows={10} value={JSON.stringify(model.component)} readOnly={true} style={{width:'99%', border:0}}/> </td> </tr> </tbody> </table> </div> ) export default component => ({ init: init(component), update, view: view(component) })
index.ios.js
mutualmobile/Brazos
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import StackNavigator from './src/components/app/StackNavigator'; AppRegistry.registerComponent('Brazos', () => StackNavigator);
src/redux/utils/createDevToolsWindow.js
llukasxx/school-organizer-front
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import DevTools from '../../containers/DevToolsWindow' export default function createDevToolsWindow (store) { const win = window.open( null, 'redux-devtools', // give it a name so it reuses the same window `width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no` ) // reload in case it's reusing the same window with the old content win.location.reload() // wait a little bit for it to reload, then render setTimeout(() => { // Wait for the reload to prevent: // "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element." win.document.write('<div id="react-devtools-root"></div>') win.document.body.style.margin = '0' ReactDOM.render( <Provider store={store}> <DevTools /> </Provider> , win.document.getElementById('react-devtools-root') ) }, 10) }
src/svg-icons/notification/network-check.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationNetworkCheck = (props) => ( <SvgIcon {...props}> <path d="M15.9 5c-.17 0-.32.09-.41.23l-.07.15-5.18 11.65c-.16.29-.26.61-.26.96 0 1.11.9 2.01 2.01 2.01.96 0 1.77-.68 1.96-1.59l.01-.03L16.4 5.5c0-.28-.22-.5-.5-.5zM1 9l2 2c2.88-2.88 6.79-4.08 10.53-3.62l1.19-2.68C9.89 3.84 4.74 5.27 1 9zm20 2l2-2c-1.64-1.64-3.55-2.82-5.59-3.57l-.53 2.82c1.5.62 2.9 1.53 4.12 2.75zm-4 4l2-2c-.8-.8-1.7-1.42-2.66-1.89l-.55 2.92c.42.27.83.59 1.21.97zM5 13l2 2c1.13-1.13 2.56-1.79 4.03-2l1.28-2.88c-2.63-.08-5.3.87-7.31 2.88z"/> </SvgIcon> ); NotificationNetworkCheck = pure(NotificationNetworkCheck); NotificationNetworkCheck.displayName = 'NotificationNetworkCheck'; NotificationNetworkCheck.muiName = 'SvgIcon'; export default NotificationNetworkCheck;
Tutorial/js/project/2.MeiTuan/Component/Main/XMGLaunchImage.js
onezens/react-native-repo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Image } from 'react-native'; /**----导入外部的组件----**/ var Main = require('./XMGMain'); var Launch = React.createClass({ render() { return ( <Image source={{uri: 'launchimage'}} style={styles.launchImageStyle}/> ); }, // 复杂的操作:定时器\网络请求 componentDidMount(){ // 定时: 隔2s切换到Main setTimeout(()=>{ // 页面的切换 this.props.navigator.replace({ component: Main, // 具体路由的版块 }); }, 1500); } }); const styles = StyleSheet.create({ launchImageStyle:{ flex:1 } }); // 输出组件类 module.exports = Launch;
docs-ui/components/iconSet.stories.js
beeftornado/sentry
import React from 'react'; import {withInfo} from '@storybook/addon-info'; import styled from '@emotion/styled'; import * as newIconset from 'app/icons'; export default { title: 'Core/Style/Icons', }; export const IconSet = withInfo('Replace `InlineSvg` with icon components')(() => { return ( <SwatchWrapper> <Header>Icon Set</Header> <Swatches> {Object.entries(newIconset).map(([key, Icon]) => ( <Swatch key={key}> <Icon /> <LabelWrapper>{key}</LabelWrapper> </Swatch> ))} </Swatches> </SwatchWrapper> ); }); const Header = styled('h5')` margin-bottom: 16px; `; const LabelWrapper = styled('div')` font-size: 14px; margin-left: 16px; `; const SwatchWrapper = styled('div')` border: 1px solid ${p => p.theme.border}; padding: 24px; `; const Swatches = styled('div')` display: grid; grid-template-columns: repeat(auto-fill, 160px); grid-gap: 8px; `; const Swatch = styled('div')` display: flex; align-items: center; min-height: 32px; svg { min-width: 32px; } `;
src/containers/ImportReviews/individualsCrawlerForm/UpWorkForm.js
ChluNetwork/chlu-demo
import React from 'react' import { Grid } from '@material-ui/core' import { Field } from 'redux-form' import CustomInput from 'components/Form/CustomInput' import { InputAdornment, withStyles } from '@material-ui/core' import FaceIcon from '@material-ui/icons/Face'; import EmailIcon from '@material-ui/icons/Email'; import HttpsIcon from '@material-ui/icons/Https'; const style = { gridRow: { margin: '12px 0', } } class UpWorkForm extends React.Component { render() { const { classes } = this.props return ( <Grid item xs={12} md={12} > <Grid container justify='center'> <Grid item xs={12} md={8} className={classes.gridRow}> <h5>Import UpWork reviews</h5> <Field component={CustomInput} labelText={<span>UpWork profile URL</span>} name='upwork-url' formControlProps={{ fullWidth: true }} inputProps={{ endAdornment: ( <InputAdornment position='end' className={classes.inputAdornment}> <FaceIcon className={classes.inputAdornmentIcon} /> </InputAdornment> ) }} /> </Grid> </Grid> <Grid container justify='center'> {this.renderLogin()} </Grid> </Grid> ) } renderLogin() { const { classes } = this.props return ( <Grid item xs={12} md={8} className={classes.gridRow}> <Grid container justify='space-between' spacing={8} style={{ marginTop: -24 }}> <Grid item xs={12} sm={12} md={6} className={classes.gridRow}> <Field component={CustomInput} labelText={<span>UpWork e-mail <small>(optional)</small></span>} name='upwork-user' formControlProps={{ fullWidth: true }} inputProps={{ endAdornment: ( <InputAdornment position='end' className={classes.inputAdornment}> <EmailIcon className={classes.inputAdornmentIcon} /> </InputAdornment> ) }} /> </Grid> <Grid item xs={12} sm={12} md={6} className={classes.gridRow}> <Field component={CustomInput} labelText={<span>UpWork password <small>(optional)</small></span>} id='upwork-password' name='upwork-password' formControlProps={{ fullWidth: true }} inputProps={{ type: 'password', endAdornment: ( <InputAdornment position='end' className={classes.inputAdornment}> <HttpsIcon className={classes.inputAdornmentIcon} /> </InputAdornment> ) }} /> </Grid> </Grid> </Grid> ) } /** * @param {string} url */ isUpWorkProfileUrlValid(url) { if (!url) return false; url = url.toLowerCase(); if (url.indexOf("upwork.com") === 0) return true; if (url.indexOf("www.upwork.com") === 0) return true; if (url.indexOf("http://upwork.com") === 0) return true; if (url.indexOf("https://upwork.com") === 0) return true; if (url.indexOf("http://www.upwork.com") === 0) return true; if (url.indexOf("https://www.upwork.com") === 0) return true; return false; } } export default withStyles(style)(UpWorkForm)
react-webpack/src/Comment.js
hzzly/react-getting-started
import React, { Component } from 'react'; class Comment extends Component { render() { return ( <div className="comment"> <div className="ui comments"> <div className="comment"> <a className="avatar"> <img src="/src/assets/images/avatar.jpg" /> </a> <div className="content"> <a className="author">{this.props.author}</a> <div className="metadata"> <div className="date">{this.props.date}</div> </div> <div className="text">{this.props.children}</div> </div> </div> </div> </div> ); } } export default Comment;
client/index.js
nextinnovation-corp/gacha
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import App from './containers/App'; import store from './store'; ReactDOM.render( <Provider store={store}> <App /> </Provider> , document.getElementById('app'));