path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
test/components/App-test.js
primozs/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import {test} from 'tape'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import App from '../../src/js/components/App'; import CSSClassnames from '../../src/js/utils/CSSClassnames'; const CLASS_ROOT = CSSClassnames.APP; test('loads a basic App', (t) => { t.plan(1); const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(App)); const appElement = shallowRenderer.getRenderOutput(); if (appElement.props.className.indexOf(CLASS_ROOT) > -1) { t.pass('App has class'); } else { t.fail('App does not have app class'); } }); test('loads an inline App', (t) => { t.plan(1); const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(App, {inline: true})); const appElement = shallowRenderer.getRenderOutput(); if (appElement.props.className.indexOf(`${CLASS_ROOT}--inline`) > -1) { t.pass('App has inline class'); } else { t.fail('App does not have inline class'); } }); test('loads a custom className App', (t) => { t.plan(1); const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(App, {className: 'testing'})); const appElement = shallowRenderer.getRenderOutput(); if (appElement.props.className.indexOf('testing') > -1) { t.pass('App has testing class'); } else { t.fail('App does not have testing class'); } }); test('loads an App with body', (t) => { t.plan(2); const shallowRenderer = TestUtils.createRenderer(); var AppWithBody = ( <App><h2>App Body</h2></App> ); shallowRenderer.render( AppWithBody ); const appElement = shallowRenderer.getRenderOutput(); if (appElement.props.className.indexOf(CLASS_ROOT) > -1) { t.pass('App has class'); } else { t.fail('App does not have app class'); } t.equal( appElement.props.children[0].props.children, 'App Body', 'App has body' ); });
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
marcoshtm/counselors
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/index.js
asdelday/redux-boilerplate
import React from 'react'; import ReactDom from 'react-dom'; import App from './components/App'; ((window) => { const app = document.createElement('div'); window.document.body.appendChild(app); ReactDom.render(<App />, app); })(window);
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SassModulesInclusion.js
timlogemann/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import styles from './assets/sass-styles.module.sass'; import indexStyles from './assets/index.module.sass'; export default () => ( <div> <p className={styles.sassModulesInclusion}>SASS Modules are working!</p> <p className={indexStyles.sassModulesIndexInclusion}> SASS Modules with index are working! </p> </div> );
src/packages/@ncigdc/modern_components/SampleType/SampleType.relay.js
NCI-GDC/portal-ui
import React from 'react'; import { graphql } from 'react-relay'; import { compose, withPropsOnChange } from 'recompose'; import { makeFilter } from '@ncigdc/utils/filters'; import { withRouter } from 'react-router-dom'; import { BaseQuery } from '@ncigdc/modern_components/Query'; const fieldMap = { sample: 'cases.samples.sample_id', portion: 'cases.samples.portions.portion_id', analyte: 'cases.samples.portions.analytes.analyte_id', aliquot: 'cases.samples.portions.analytes.aliquots.aliquot_id', slide: 'cases.samples.portions.slides.slide_id', }; export default (Component: ReactClass<*>) => compose( withRouter, withPropsOnChange(['entityType, entityId'], ({ entityType, entityId }) => { return { variables: { filters: makeFilter([ { field: fieldMap[entityType], value: entityId, }, ]), }, }; }), )((props: Object) => { return ( <BaseQuery name="SampleType" parentProps={props} variables={props.variables} Component={Component} query={graphql` query SampleType_relayQuery($filters: FiltersArgument) { repository { cases { hits(first: 1, filters: $filters) { edges { node { samples { hits(first: 1, filters: $filters) { edges { node { sample_type } } } } } } } } } } `} /> ); });
app/javascript/mastodon/features/ui/components/focal_point_modal.js
kazh98/social.arnip.org
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { connect } from 'react-redux'; import classNames from 'classnames'; import { changeUploadCompose } from '../../../actions/compose'; import { getPointerPosition } from '../../video'; import { FormattedMessage, defineMessages, injectIntl } from 'react-intl'; import IconButton from 'mastodon/components/icon_button'; import Button from 'mastodon/components/button'; import Video from 'mastodon/features/video'; import Audio from 'mastodon/features/audio'; import Textarea from 'react-textarea-autosize'; import UploadProgress from 'mastodon/features/compose/components/upload_progress'; import CharacterCounter from 'mastodon/features/compose/components/character_counter'; import { length } from 'stringz'; import { Tesseract as fetchTesseract } from 'mastodon/features/ui/util/async-components'; import GIFV from 'mastodon/components/gifv'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, apply: { id: 'upload_modal.apply', defaultMessage: 'Apply' }, placeholder: { id: 'upload_modal.description_placeholder', defaultMessage: 'A quick brown fox jumps over the lazy dog' }, }); const mapStateToProps = (state, { id }) => ({ media: state.getIn(['compose', 'media_attachments']).find(item => item.get('id') === id), }); const mapDispatchToProps = (dispatch, { id }) => ({ onSave: (description, x, y) => { dispatch(changeUploadCompose(id, { description, focus: `${x.toFixed(2)},${y.toFixed(2)}` })); }, }); const removeExtraLineBreaks = str => str.replace(/\n\n/g, '******') .replace(/\n/g, ' ') .replace(/\*\*\*\*\*\*/g, '\n\n'); const assetHost = process.env.CDN_HOST || ''; class ImageLoader extends React.PureComponent { static propTypes = { src: PropTypes.string.isRequired, width: PropTypes.number, height: PropTypes.number, }; state = { loading: true, }; componentDidMount() { const image = new Image(); image.addEventListener('load', () => this.setState({ loading: false })); image.src = this.props.src; } render () { const { loading } = this.state; if (loading) { return <canvas width={this.props.width} height={this.props.height} />; } else { return <img {...this.props} alt='' />; } } } export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class FocalPointModal extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.map.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { x: 0, y: 0, focusX: 0, focusY: 0, dragging: false, description: '', dirty: false, progress: 0, loading: true, }; componentWillMount () { this.updatePositionFromMedia(this.props.media); } componentWillReceiveProps (nextProps) { if (this.props.media.get('id') !== nextProps.media.get('id')) { this.updatePositionFromMedia(nextProps.media); } } componentWillUnmount () { document.removeEventListener('mousemove', this.handleMouseMove); document.removeEventListener('mouseup', this.handleMouseUp); } handleMouseDown = e => { document.addEventListener('mousemove', this.handleMouseMove); document.addEventListener('mouseup', this.handleMouseUp); this.updatePosition(e); this.setState({ dragging: true }); } handleTouchStart = e => { document.addEventListener('touchmove', this.handleMouseMove); document.addEventListener('touchend', this.handleTouchEnd); this.updatePosition(e); this.setState({ dragging: true }); } handleMouseMove = e => { this.updatePosition(e); } handleMouseUp = () => { document.removeEventListener('mousemove', this.handleMouseMove); document.removeEventListener('mouseup', this.handleMouseUp); this.setState({ dragging: false }); } handleTouchEnd = () => { document.removeEventListener('touchmove', this.handleMouseMove); document.removeEventListener('touchend', this.handleTouchEnd); this.setState({ dragging: false }); } updatePosition = e => { const { x, y } = getPointerPosition(this.node, e); const focusX = (x - .5) * 2; const focusY = (y - .5) * -2; this.setState({ x, y, focusX, focusY, dirty: true }); } updatePositionFromMedia = media => { const focusX = media.getIn(['meta', 'focus', 'x']); const focusY = media.getIn(['meta', 'focus', 'y']); const description = media.get('description') || ''; if (focusX && focusY) { const x = (focusX / 2) + .5; const y = (focusY / -2) + .5; this.setState({ x, y, focusX, focusY, description, dirty: false, }); } else { this.setState({ x: 0.5, y: 0.5, focusX: 0, focusY: 0, description, dirty: false, }); } } handleChange = e => { this.setState({ description: e.target.value, dirty: true }); } handleKeyDown = (e) => { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { e.preventDefault(); e.stopPropagation(); this.setState({ description: e.target.value, dirty: true }); this.handleSubmit(); } } handleSubmit = () => { this.props.onSave(this.state.description, this.state.focusX, this.state.focusY); this.props.onClose(); } setRef = c => { this.node = c; } handleTextDetection = () => { const { media } = this.props; this.setState({ detecting: true }); fetchTesseract().then(({ TesseractWorker }) => { const worker = new TesseractWorker({ workerPath: `${assetHost}/packs/ocr/worker.min.js`, corePath: `${assetHost}/packs/ocr/tesseract-core.wasm.js`, langPath: `${assetHost}/ocr/lang-data`, }); let media_url = media.get('url'); if (window.URL && URL.createObjectURL) { try { media_url = URL.createObjectURL(media.get('file')); } catch (error) { console.error(error); } } worker.recognize(media_url) .progress(({ progress }) => this.setState({ progress })) .finally(() => worker.terminate()) .then(({ text }) => this.setState({ description: removeExtraLineBreaks(text), dirty: true, detecting: false })) .catch(() => this.setState({ detecting: false })); }).catch(() => this.setState({ detecting: false })); } render () { const { media, intl, onClose } = this.props; const { x, y, dragging, description, dirty, detecting, progress } = this.state; const width = media.getIn(['meta', 'original', 'width']) || null; const height = media.getIn(['meta', 'original', 'height']) || null; const focals = ['image', 'gifv'].includes(media.get('type')); const previewRatio = 16/9; const previewWidth = 200; const previewHeight = previewWidth / previewRatio; let descriptionLabel = null; if (media.get('type') === 'audio') { descriptionLabel = <FormattedMessage id='upload_form.audio_description' defaultMessage='Describe for people with hearing loss' />; } else if (media.get('type') === 'video') { descriptionLabel = <FormattedMessage id='upload_form.video_description' defaultMessage='Describe for people with hearing loss or visual impairment' />; } else { descriptionLabel = <FormattedMessage id='upload_form.description' defaultMessage='Describe for the visually impaired' />; } return ( <div className='modal-root__modal report-modal' style={{ maxWidth: 960 }}> <div className='report-modal__target'> <IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={16} /> <FormattedMessage id='upload_modal.edit_media' defaultMessage='Edit media' /> </div> <div className='report-modal__container'> <div className='report-modal__comment'> {focals && <p><FormattedMessage id='upload_modal.hint' defaultMessage='Click or drag the circle on the preview to choose the focal point which will always be in view on all thumbnails.' /></p>} <label className='setting-text-label' htmlFor='upload-modal__description'> {descriptionLabel} </label> <div className='setting-text__wrapper'> <Textarea id='upload-modal__description' className='setting-text light' value={detecting ? '…' : description} onChange={this.handleChange} onKeyDown={this.handleKeyDown} disabled={detecting} autoFocus /> <div className='setting-text__modifiers'> <UploadProgress progress={progress * 100} active={detecting} icon='file-text-o' message={<FormattedMessage id='upload_modal.analyzing_picture' defaultMessage='Analyzing picture…' />} /> </div> </div> <div className='setting-text__toolbar'> <button disabled={detecting || media.get('type') !== 'image'} className='link-button' onClick={this.handleTextDetection}><FormattedMessage id='upload_modal.detect_text' defaultMessage='Detect text from picture' /></button> <CharacterCounter max={1500} text={detecting ? '' : description} /> </div> <Button disabled={!dirty || detecting || length(description) > 1500} text={intl.formatMessage(messages.apply)} onClick={this.handleSubmit} /> </div> <div className='focal-point-modal__content'> {focals && ( <div className={classNames('focal-point', { dragging })} ref={this.setRef} onMouseDown={this.handleMouseDown} onTouchStart={this.handleTouchStart}> {media.get('type') === 'image' && <ImageLoader src={media.get('url')} width={width} height={height} alt='' />} {media.get('type') === 'gifv' && <GIFV src={media.get('url')} width={width} height={height} />} <div className='focal-point__preview'> <strong><FormattedMessage id='upload_modal.preview_label' defaultMessage='Preview ({ratio})' values={{ ratio: '16:9' }} /></strong> <div style={{ width: previewWidth, height: previewHeight, backgroundImage: `url(${media.get('preview_url')})`, backgroundSize: 'cover', backgroundPosition: `${x * 100}% ${y * 100}%` }} /> </div> <div className='focal-point__reticle' style={{ top: `${y * 100}%`, left: `${x * 100}%` }} /> <div className='focal-point__overlay' /> </div> )} {media.get('type') === 'video' && ( <Video preview={media.get('preview_url')} blurhash={media.get('blurhash')} src={media.get('url')} detailed inline editable /> )} {media.get('type') === 'audio' && ( <Audio src={media.get('url')} duration={media.getIn(['meta', 'original', 'duration'], 0)} height={150} preload editable /> )} </div> </div> </div> ); } }
src/components/button.js
cereigido/react-native-ez-layouts
import React from 'react'; import { Text, TouchableOpacity } from 'react-native'; const Button = ({ children, onPress, inverse }) => { const gstyles = global.ezstyles || {}; const containerStyle = { alignSelf: 'stretch', backgroundColor: (inverse ? gstyles.buttonBackgroundColorInverse || '#555' : gstyles.buttonBackgroundColor || '#ccc'), height: gstyles.buttonHeight || 60, padding: gstyles.buttonPadding || 16, }; const textStyle = { alignSelf: 'center', flex: 1, fontFamily: gstyles.buttonTextFontFamily, justifyContent: 'center', color: (inverse ? gstyles.buttonTextColorInverse || '#fff' : gstyles.buttonTextColor || '#777'), fontSize: gstyles.buttonTextFontSize || 18, }; return ( <TouchableOpacity onPress={onPress} style={containerStyle}> <Text style={textStyle}>{children}</Text> </TouchableOpacity> ); }; export { Button };
src/Parser/WindwalkerMonk/CombatLogParser.js
mwwscott0/WoWAnalyzer
import React from 'react'; import SuggestionsTab from 'Main/SuggestionsTab'; import Tab from 'Main/Tab'; import Talents from 'Main/Talents'; import CoreCombatLogParser from 'Parser/Core/CombatLogParser'; // Features import DamageDone from 'Parser/Core/Modules/DamageDone'; import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting'; import CastEfficiency from './Modules/Features/CastEfficiency'; import CooldownTracker from './Modules/Features/CooldownTracker'; // Talents import HitCombo from './Modules/Talents/HitCombo'; class CombatLogParser extends CoreCombatLogParser { static specModules = { // Features damageDone: [DamageDone, { showStatistic: true }], alwaysBeCasting: AlwaysBeCasting, castEfficiency: CastEfficiency, cooldownTracker: CooldownTracker, // Talents: hitCombo: HitCombo, // Legendaries: }; generateResults() { const results = super.generateResults(); results.tabs = [ { title: 'Suggestions', url: 'suggestions', render: () => ( <SuggestionsTab issues={results.issues} /> ), }, { title: 'Talents', url: 'talents', render: () => ( <Tab title="Talents"> <Talents combatant={this.modules.combatants.selected} /> </Tab> ), }, ...results.tabs, ]; return results; } } export default CombatLogParser;
app/javascript/mastodon/features/ui/components/bundle_column_error.js
palon7/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import Column from './column'; import ColumnHeader from './column_header'; import ColumnBackButtonSlim from '../../../components/column_back_button_slim'; import IconButton from '../../../components/icon_button'; const messages = defineMessages({ title: { id: 'bundle_column_error.title', defaultMessage: 'Network error' }, body: { id: 'bundle_column_error.body', defaultMessage: 'Something went wrong while loading this component.' }, retry: { id: 'bundle_column_error.retry', defaultMessage: 'Try again' }, }); class BundleColumnError extends React.Component { static propTypes = { onRetry: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, } handleRetry = () => { this.props.onRetry(); } render () { const { intl: { formatMessage } } = this.props; return ( <Column> <ColumnHeader icon='exclamation-circle' type={formatMessage(messages.title)} /> <ColumnBackButtonSlim /> <div className='error-column'> <IconButton title={formatMessage(messages.retry)} icon='refresh' onClick={this.handleRetry} size={64} /> {formatMessage(messages.body)} </div> </Column> ); } } export default injectIntl(BundleColumnError);
frontend/src/components/dashboard/agencyDashboard/partnerDecisions.js
unicef/un-partner-portal
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import Typography from 'material-ui/Typography'; import R from 'ramda'; import Grid from 'material-ui/Grid'; import Paper from 'material-ui/Paper'; import { withStyles } from 'material-ui/styles'; import { loadApplicationDecisions } from '../../../reducers/applicationsDecisions'; import SpreadContent from '../../common/spreadContent'; import PaddedContent from '../../common/paddedContent'; import CustomGridColumn from '../../common/grid/customGridColumn'; import { formatDateForPrint } from '../../../helpers/dates'; import Pagination from '../../common/pagination'; import TextWithBackground from '../../common/textWithColorBackground'; import Loader from '../../common/loader'; const messages = { title: 'Partner Decisions From Past 5 Days', decisionDate: 'Decision date', accepted: 'accepted', declined: 'declined', }; const styleSheet = () => ({ name: { flexBasis: '40%' }, status: { flexBasis: '40%' }, }); const SingleDecisionBase = ({ classes, id, partner: { legal_name }, eoi: { title }, modified, did_accept, }) => ( <Paper> <PaddedContent> <SpreadContent> <div className={classes.name}> <Typography type="body2"> {legal_name} </Typography> <Typography type="caption"> {`${id} | ${title}`} </Typography> </div> <div className={classes.status}> <TextWithBackground text={did_accept ? messages.accepted : messages.declined} type="button" color={did_accept ? 'green' : 'red'} /> </div> <div> <Typography type="caption"> {`${messages.decisionDate}:`} </Typography> <Typography> {formatDateForPrint(modified)} </Typography> </div> </SpreadContent> </PaddedContent> </Paper>); const SingleDecision = withStyles(styleSheet, { name: 'SingleDecision' })(SingleDecisionBase); class PartnerDecisions extends Component { constructor() { super(); this.state = { params: { page: 1, page_size: 5, }, }; this.handleChangePage = this.handleChangePage.bind(this); this.handleChangeRowsPerPage = this.handleChangeRowsPerPage.bind(this); } componentWillMount() { this.props.loadDecisions(this.state.params); } shouldComponentUpdate(nextProps, nextState) { if (!R.equals(nextState.params, this.state.params)) { this.props.loadDecisions(nextState.params); return false; } if (R.isEmpty(nextProps.decisions)) return false; return true; } handleChangePage(event, page) { this.setState({ params: { ...this.state.params, page } }); } handleChangeRowsPerPage(event) { this.setState({ params: { ...this.state.params, page_size: event.target.value } }); } render() { const { decisions, loading, count } = this.props; const { params: { page, page_size } } = this.state; return ( <Loader loading={loading} > <CustomGridColumn> <Typography type="headline">{messages.title}</Typography> {decisions.map(decision => React.createElement(SingleDecision, {...decision, key: decision.id}))} <Grid container justify="center" > <Grid item> <Pagination count={count} rowsPerPage={page_size} page={page} onChangePage={this.handleChangePage} onChangeRowsPerPage={this.handleChangeRowsPerPage} /> </Grid> </Grid> </CustomGridColumn> </Loader> ); } } PartnerDecisions.propTypes = { loading: PropTypes.bool, decisions: PropTypes.array, loadDecisions: PropTypes.func, count: PropTypes.number, }; const mapStateToProps = state => ({ loading: state.applicationDecisions.loading, decisions: state.applicationDecisions.decisions, count: state.applicationDecisions.count, }); const mapDispatchToProps = dispatch => ({ loadDecisions: params => dispatch(loadApplicationDecisions(params)), }); export default connect(mapStateToProps, mapDispatchToProps)(PartnerDecisions);
src/App.js
funki-chicken/simple-tunes
import React, { Component } from 'react'; import ReactPlayer from 'react-player'; import fetch from 'node-fetch'; import Forwards from 'react-icons/lib/md/arrow-forward'; import Backwards from 'react-icons/lib/md/arrow-back'; const openInTab = (url) => { var win = window.open(url, '_blank'); win.focus(); }; const fetchLinks = (keyword) => { return new Promise((resolve, reject) => { const jsonUri = `https://www.reddit.com/r/listentothis/${keyword}/.json`; fetch(jsonUri) .then((res) => res.json()) .then((json) => resolve(json.data.children.map(child => ({ url: child.data.url, title: child.data.title })))) .catch(err => reject(err)) }) }; const buttonStandard = () => { return { cursor: "pointer", margin: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", height: 30, width: 60, backgroundColor: "white", outline: "none", borderWidth: 0, borderRadius: 2, color: "white" } }; const circleButtonStandard = () => { return { cursor: "pointer", margin: 0, height: 50, width: 50, backgroundColor: "white", borderWidth: 1, borderColor: "rgba(0, 0, 0, .2)", borderStyle: "solid", borderRadius: 25 } }; class App extends Component { constructor(props) { super(props); this.state = { loading: true, listkey: 'hot', track: 0, time: 0, links: [] } } componentDidMount() { const state = this.stateCache(); if (state) { this.setState(state) } else { this.stateLoader('hot') } this.handleKeyboardEvents() } handleKeyboardEvents() { document.addEventListener('keydown', (event) => { const keyName = event.key; if (keyName === 'Control') { return; } if (keyName === 'ArrowRight') { this.start(this.state.track + 1) return } if (keyName === 'ArrowLeft') { this.start(this.state.track - 1) return } }, false); } stateCache() { let cachedStateString = window.localStorage.getItem('player-state'); let cachedState = cachedStateString ? JSON.parse(cachedStateString) : null; let shouldFetch = false; if (!cachedState) { shouldFetch = true } if (cachedState && (new Date(cachedState.timestamp).getTime() < (new Date().getTime() - 3600000000000))) { shouldFetch = true } if (!shouldFetch) { return cachedState.state } else { return null } } stateLoader(keyword) { window.scrollTo(0, 0); this.setState({ loading: true, links: [], time: 0, track: 0, listkey: keyword }, () => { fetchLinks(keyword) .then(links => this.setState({ loading: false, links })) .catch(err => this.setState({ loading: false })) }) } onProgress(index, playedTime) { this.setState({ time: playedTime }, () => this.cacheState()) } cacheState() { window.localStorage.setItem('player-state', JSON.stringify({ timestamp: new Date().toString(), state: this.state })) } onEnded(lastIndex) { const track = this.state.track; this.start(track + 1) } start(startIndex) { const saveTrackIndex = this.state.track; this.setState({ track: startIndex, time: 0 }) } render() { const leftColor = 'rgb(33,150,243)'; const rightColor = 'rgb(33,150,243)'; const unselectedTabColor = 'rgb(227,242,253)'; const selectedTabColor = 'rgb(33,150,243)'; return ( <div style={{ display: "flex", flexDirection: "column", padding: 10, paddingTop: 40 }}> <div style={{ display: "flex", justifyContent: "space-between", position: "fixed", top: 0, left: 0, backgroundColor: "white", width: "100%", borderWidth: 0, borderBottomWidth: 1, borderColor: "rgba(0, 0, 0, .1)", borderStyle: "solid", boxShadow: "3px 3px 4px rgba(0, 0, 0, .1)" }}> <div style={{ display: "flex", margin: 10, marginLeft: 20 }}> <div style={{ display: "flex", flexDirection: "column" }}> <button style={Object.assign({}, buttonStandard(), { marginRight: 10, backgroundColor: this.state.listkey === 'hot' ? selectedTabColor : unselectedTabColor, color: this.state.listkey === 'hot' ? unselectedTabColor : selectedTabColor })} onClick={() => this.stateLoader('hot')}> <div style={{ display: "flex", flex: 1, alignItems: "center", justifyContent: "center" }}> <p style={{ color: "white" }}>Hot</p> </div> </button> </div> <div style={{ display: "flex", flexDirection: "column" }}> <button style={Object.assign({}, buttonStandard(), { marginRight: 10, backgroundColor: this.state.listkey === 'top' ? selectedTabColor : unselectedTabColor, color: this.state.listkey === 'top' ? selectedTabColor : unselectedTabColor })} onClick={() => this.stateLoader('top')}> <div style={{ display: "flex", flex: 1, alignItems: "center", justifyContent: "center" }}> <p style={{ color: "white" }}>Top</p> </div> </button> </div> </div> <div style={{ display: "flex", margin: 10, marginRight: 20 }}> <button onClick={() => this.start(this.state.track - 1)} style={Object.assign({}, buttonStandard(), { color: "white", borderWidth: 0,backgroundColor: leftColor })}> <div style={{ display: "flex", flex: 1, alignItems: "center", justifyContent: "center" }}> <Backwards size={15} /> </div> </button> <button onClick={() => this.start(this.state.track + 1)} style={Object.assign({}, buttonStandard(), { marginLeft: 15, color: "white", borderWidth: 0,backgroundColor: rightColor })}> <div style={{ display: "flex", flex: 1, alignItems: "center", justifyContent: "center" }}> <Forwards size={15} /> </div> </button> </div> </div> { this.state.loading ? null : this.state.links.filter(link => !link.url.includes('reddit')).map(({ url, title }, i) => { if (url.includes('bandcamp')) { return( <button onClick={() => openInTab(url)} style={{ cursor: "pointer", borderWidth: 0, borderColor: "transparent", backgroundColor: "transparent", display: "flex", flexDirection: "column", marginTop: 20 }}> <h3 style={{ margin: 0, marginBottom: 5, marginTop: 5 }}>{title}</h3> <div style={{ display: "flex" }}> <p style={{ margin: 0 }}>{url}</p> </div> </button> ) } else { if (this.state.track === i) { return( <div style={{ display: "flex", flexDirection: "column", marginTop: 20 }}> <ReactPlayer fileConfig={{ attributes: { autoPlay: true }}} width={'100%'} height={window.innerHeight - 200} onEnded={() => this.onEnded(i)} onStart={() => this.start(i)} onProgress={({ playedSeconds }) => this.onProgress(i, playedSeconds)} url={url} controls playing={this.state.track === i ? true : false} youtubeConfig={{ playerVars: { start: Math.round(this.state.time), autoplay: 1 } }}/> </div> ) } else { return( <button onClick={() => this.start(i)} style={{ cursor: "pointer", borderWidth: 0, borderColor: "transparent", backgroundColor: "transparent", display: "flex", flexDirection: "column", margin: 0, marginLeft: -5, marginTop: 20 }}> <h3 style={{ textAlign: "left", margin: 0, marginBottom: 5, marginTop: 5 }}>{title}</h3> <div style={{ display: "flex" }}> <p style={{ textAlign: "left", margin: 0 }}>{url}</p> </div> </button> ) } } }) } </div> ); } } export default App;
admin/client/App/shared/Portal.js
joerter/keystone
/** * Used by the Popout component and the Lightbox component of the fields for * popouts. Renders a non-react DOM node. */ import React from 'react'; import ReactDOM from 'react-dom'; module.exports = React.createClass({ displayName: 'Portal', portalElement: null, // eslint-disable-line react/sort-comp componentDidMount () { const el = document.createElement('div'); document.body.appendChild(el); this.portalElement = el; this.componentDidUpdate(); }, componentWillUnmount () { document.body.removeChild(this.portalElement); }, componentDidUpdate () { ReactDOM.render(<div {...this.props} />, this.portalElement); }, getPortalDOMNode () { return this.portalElement; }, render () { return null; }, });
src/stories/table/table-with-clickable-row.js
kemuridama/rectangle
import React from 'react'; export default class TableWithClickableRow extends React.Component { render() { const { onClick } = this.props; return ( <div className="con"> <div className="p"> <div className="p__body p__body--without-padding"> <table className="tbl"> <thead className="tbl__header"> <tr> <th className="tbl__col">Head 1</th> <th className="tbl__col">Head 2</th> <th className="tbl__col">Head 3</th> <th className="tbl__col">Head 4</th> <th className="tbl__col">Head 5</th> </tr> </thead> <tbody> <tr className="tbl__row tbl__row--clickable" onClick={onClick.bind(this)}> <td className="tbl__col">Data 1</td> <td className="tbl__col">Data 2</td> <td className="tbl__col">Data 3</td> <td className="tbl__col">Data 4</td> <td className="tbl__col">Data 5</td> </tr> <tr className="tbl__row tbl__row--clickable" onClick={onClick.bind(this)}> <td className="tbl__col">Data 1</td> <td className="tbl__col">Data 2</td> <td className="tbl__col">Data 3</td> <td className="tbl__col">Data 4</td> <td className="tbl__col">Data 5</td> </tr> <tr className="tbl__row tbl__row--clickable" onClick={onClick.bind(this)}> <td className="tbl__col">Data 1</td> <td className="tbl__col">Data 2</td> <td className="tbl__col">Data 3</td> <td className="tbl__col">Data 4</td> <td className="tbl__col">Data 5</td> </tr> <tr className="tbl__row tbl__row--clickable" onClick={onClick.bind(this)}> <td className="tbl__col">Data 1</td> <td className="tbl__col">Data 2</td> <td className="tbl__col">Data 3</td> <td className="tbl__col">Data 4</td> <td className="tbl__col">Data 5</td> </tr> </tbody> </table> </div> </div> </div> ); } }
src/svg-icons/action/bookmark.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBookmark = (props) => ( <SvgIcon {...props}> <path d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionBookmark = pure(ActionBookmark); ActionBookmark.displayName = 'ActionBookmark'; export default ActionBookmark;
frontend/node_modules/recharts/es6/component/ResponsiveContainer.js
justdotJS/rowboat
import _debounce from 'lodash/debounce'; 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 _class, _temp; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @fileOverview Wrapper component to make charts adapt to the size of parent * DOM */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import ReactResizeDetector from 'react-resize-detector'; import { isPercent } from '../util/DataUtils'; import { warn } from '../util/LogUtils'; var ResponsiveContainer = (_temp = _class = function (_Component) { _inherits(ResponsiveContainer, _Component); function ResponsiveContainer(props) { _classCallCheck(this, ResponsiveContainer); var _this = _possibleConstructorReturn(this, (ResponsiveContainer.__proto__ || Object.getPrototypeOf(ResponsiveContainer)).call(this, props)); _this.updateDimensionsImmediate = function () { if (!_this.mounted) { return; } var newSize = _this.getContainerSize(); if (newSize) { var _this$state = _this.state, oldWidth = _this$state.containerWidth, oldHeight = _this$state.containerHeight; var containerWidth = newSize.containerWidth, containerHeight = newSize.containerHeight; if (containerWidth !== oldWidth || containerHeight !== oldHeight) { _this.setState({ containerWidth: containerWidth, containerHeight: containerHeight }); } } }; _this.state = { containerWidth: -1, containerHeight: -1 }; _this.handleResize = props.debounce > 0 ? _debounce(_this.updateDimensionsImmediate, props.debounce) : _this.updateDimensionsImmediate; return _this; } /* eslint-disable react/no-did-mount-set-state */ _createClass(ResponsiveContainer, [{ key: 'componentDidMount', value: function componentDidMount() { this.mounted = true; var size = this.getContainerSize(); if (size) { this.setState(size); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.mounted = false; } }, { key: 'getContainerSize', value: function getContainerSize() { if (!this.container) { return null; } return { containerWidth: this.container.clientWidth, containerHeight: this.container.clientHeight }; } }, { key: 'renderChart', value: function renderChart() { var _state = this.state, containerWidth = _state.containerWidth, containerHeight = _state.containerHeight; if (containerWidth < 0 || containerHeight < 0) { return null; } var _props = this.props, aspect = _props.aspect, width = _props.width, height = _props.height, minWidth = _props.minWidth, minHeight = _props.minHeight, maxHeight = _props.maxHeight, children = _props.children; warn(isPercent(width) || isPercent(height), 'The width(%s) and height(%s) are both fixed numbers,\n maybe you don\'t need to use a ResponsiveContainer.', width, height); warn(!aspect || aspect > 0, 'The aspect(%s) must be greater than zero.', aspect); var calculatedWidth = isPercent(width) ? containerWidth : width; var calculatedHeight = isPercent(height) ? containerHeight : height; if (aspect && aspect > 0) { // Preserve the desired aspect ratio calculatedHeight = calculatedWidth / aspect; // if maxHeight is set, overwrite if calculatedHeight is greater than maxHeight if (maxHeight && calculatedHeight > maxHeight) { calculatedHeight = maxHeight; } } warn(calculatedWidth > 0 || calculatedHeight > 0, 'The width(%s) and height(%s) of chart should be greater than 0,\n please check the style of container, or the props width(%s) and height(%s),\n or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the\n height and width.', calculatedWidth, calculatedHeight, width, height, minWidth, minHeight, aspect); return React.cloneElement(children, { width: calculatedWidth, height: calculatedHeight }); } }, { key: 'render', value: function render() { var _this2 = this; var _props2 = this.props, minWidth = _props2.minWidth, minHeight = _props2.minHeight, width = _props2.width, height = _props2.height, maxHeight = _props2.maxHeight, id = _props2.id, className = _props2.className; var style = { width: width, height: height, minWidth: minWidth, minHeight: minHeight, maxHeight: maxHeight }; return React.createElement( 'div', { id: id, className: classNames('recharts-responsive-container', className), style: style, ref: function ref(node) { _this2.container = node; } }, this.renderChart(), React.createElement(ReactResizeDetector, { handleWidth: true, handleHeight: true, onResize: this.handleResize }) ); } }]); return ResponsiveContainer; }(Component), _class.displayName = 'ResponsiveContainer', _class.propTypes = { aspect: PropTypes.number, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), minHeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), minWidth: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), maxHeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), children: PropTypes.node.isRequired, debounce: PropTypes.number, id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), className: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) }, _class.defaultProps = { width: '100%', height: '100%', debounce: 0 }, _temp); export default ResponsiveContainer;
docs/src/pages/system/positions/ZIndex.js
lgollut/material-ui
import React from 'react'; import Typography from '@material-ui/core/Typography'; import Box from '@material-ui/core/Box'; export default function ZIndex() { return ( <Typography component="div" variant="body1" style={{ height: 100, width: '100%', position: 'relative' }} > <Box bgcolor="grey.700" color="white" p={2} position="absolute" top={40} left="40%" zIndex="tooltip" > z-index tooltip </Box> <Box bgcolor="background.paper" color="text.primary" p={2} position="absolute" top={0} left="43%" zIndex="modal" > z-index modal </Box> </Typography> ); }
src/components/HeaderUserTip.js
BinaryCool/LaceShop
require('styles/HeaderUserTip.scss'); import React from 'react'; export default class HeaderUserTip extends React.Component { render() { return ( <a className="header-user-tip-item" href="javascript:;"> <img alt={this.props.title} src={this.props.src}/> </a> ); } }
app/javascript/mastodon/components/avatar_overlay.js
riku6460/chikuwagoddon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { autoPlayGif } from '../initial_state'; export default class AvatarOverlay extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, friend: ImmutablePropTypes.map.isRequired, animate: PropTypes.bool, }; static defaultProps = { animate: autoPlayGif, }; render() { const { account, friend, animate } = this.props; const baseStyle = { backgroundImage: `url(${account.get(animate ? 'avatar' : 'avatar_static')})`, }; const overlayStyle = { backgroundImage: `url(${friend.get(animate ? 'avatar' : 'avatar_static')})`, }; return ( <div className='account__avatar-overlay'> <div className='account__avatar-overlay-base' style={baseStyle} /> <div className='account__avatar-overlay-overlay' style={overlayStyle} /> </div> ); } }
src/packages/@ncigdc/routes/Login.js
NCI-GDC/portal-ui
import React from 'react'; import { connect } from 'react-redux'; import { compose, pure, setDisplayName, } from 'recompose'; import queryString from 'query-string'; import { fetchUser } from '@ncigdc/dux/auth'; import awgLogo from '@ncigdc/theme/images/logo-GDC-AWG-portal.png'; import Button from '@ncigdc/uikit/Button'; import { Row } from '@ncigdc/uikit/Flex'; import { createAWGSession } from '@ncigdc/utils/auth/awg'; import { AUTH, FENCE } from '@ncigdc/utils/constants'; import openAuthWindow from '@ncigdc/utils/openAuthWindow'; import withRouter from '@ncigdc/utils/withRouter'; const styles = { errorMessage: { color: 'rgb(191, 34, 58)', fontSize: 16, }, loginButton: { color: 'white', fontSize: 16, fontWeight: 200, letterSpacing: 2, padding: '12px 30px', textTransform: 'uppercase', width: 140, }, title: { color: 'rgb(38, 89, 134)', fontSize: 22, fontWeight: 400, letterSpacing: 4, textTransform: 'uppercase', }, }; const AWGLoginButton = compose( setDisplayName('EnhancedAWGLoginButton'), connect(state => state.auth), withRouter, pure, )(({ dispatch, push }) => ( <Button onClick={async () => { const loginParams = queryString.stringify({ redirect: window.location.origin, }); try { await openAuthWindow({ name: 'AWG', pollInterval: 200, winUrl: `${AUTH}?next=${FENCE}/login/fence?${loginParams}`, }); } catch (err) { if (err === 'window closed manually') { return; } if (err === 'login_error') { return (window.location.href = '/login?error=no_fence_projects'); } } const createdSession = await createAWGSession(); if (createdSession) { await dispatch(fetchUser()); push({ pathname: '/repository' }); } }} style={styles.loginButton} > Login </Button> )); const LoginRoute = () => ( <div style={{ alignItems: 'center', backgroundColor: 'white', display: 'flex', flexDirection: 'column', height: '100vh', justifyContent: 'center', left: 0, position: 'fixed', top: 0, width: '100vw', zIndex: 1000, }} > <div style={{ alignItems: 'center', flexDirection: 'column', height: '400px', justifyContent: 'center', textAlign: 'center', }} > <div> <img alt="NCI GDC AWG Portal" src={awgLogo} style={{ width: 525 }} /> </div> <br /> <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', }} > <h1 style={styles.title}>Analysis Working Group</h1> <h1 style={{ ...styles.title, margin: '0 0 20px', }} > Data Portal </h1> <div style={{ color: 'rgb(38, 89, 134)', fontSize: '3em', }} > <i className="fa fa-users" /> </div> {window.location.search.includes('error=no_fence_projects') && ( <div> <br /> <br /> <span style={styles.errorMessage}> You have not been granted access to any AWG projects by the AWG Admin. Please contact the AWG administrator to request access. </span> </div> )} {window.location.search.includes('error=timeout') && ( <div> <br /> <br /> <span style={styles.errorMessage}> Session timed out or not authorized. </span> </div> )} {( window.location.search.includes('error=no_nih_projects') || window.location.search.includes('error=no_intersection') ) && ( <div> <br /> <br /> {'You do not have access to any AWG projects in dbGaP. More information about obtaining access to controlled-access data can be found '} <a href="https://gdc.cancer.gov/access-data/obtaining-access-controlled-data">here</a> . </div> )} <Row style={{ justifyContent: 'center', marginTop: '1.5rem', }} > <AWGLoginButton /> </Row> </div> </div> </div> ); export default connect(({ auth }) => ({ error: auth.error, user: auth.user, }))(LoginRoute);
src/shared/SellerProfile/Row.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react'; import styles from './SellerProfile.css'; // eslint-disable-line no-unused-vars const Row = ({ title, children, marginBot, show }) => { if (!show) { return null; } return ( <div className="row" styleName={marginBot ? "styles.row rowNoMargin" : "styles.row"}> <hr /> <div className="col-sm-3 col-xs-12"> <h2 className="seller-profile__section-title au-display-lg">{title}</h2> </div> <div className="col-sm-8 col-sm-push-1 col-xs-12"> {children} </div> </div> ) } export default Row;
frontend/src/index.js
pschlan/cron-job.org
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import { store } from './redux'; import { Provider } from 'react-redux'; import { BrowserRouter } from 'react-router-dom'; import { ThemeProvider, createTheme } from '@material-ui/core'; const theme = createTheme({ palette: { primary: { main: '#c33d1b', light: '#fc6e46', dark: '#8b0000' }, secondary: { main: '#ed7b16', light: '#ffab4b', dark: '#b44d00' } } }); ReactDOM.render( <React.StrictMode> <Provider store={store}> <ThemeProvider theme={theme}> <BrowserRouter> <App /> </BrowserRouter> </ThemeProvider> </Provider> </React.StrictMode>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
src/shared/form/Textarea.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react'; import PropTypes from 'prop-types' import { Control, controls } from 'react-redux-form'; import StatefulError from './StatefulError'; import TextareaComponent from '../Textarea'; import { limitWords, validCharacters } from '../../validators'; const Textarea = (props) => { let { name, id, label, model, validators, messages, description, showMessagesDuringFocus = false, controlProps = {}, mapProps } = props; if (controlProps.limit) { validators = { ...validators, limitWords: limitWords(controlProps.limit) } messages = { limitWords: `${label} has exceeded the word limit.`, ...messages } } validators = { validCharacters, ...validators } if (!messages || !messages.validCharacters) { messages = { validCharacters: `Your draft content for '${label}' contains invalid characters. This usually happens when you copy and paste from an external document. We recommend to type in your response.`, ...messages } } return ( <div className="field"> <label id={`${id}-label`} className="question-heading" htmlFor={id}>{label}</label> {description && ( <p className="hint" id={`${id}-hint`}>{description}</p> )} {messages && <StatefulError model={model} messages={messages} id={id} showMessagesDuringFocus={showMessagesDuringFocus} />} <Control id={id} model={model} controlProps={{ name, id, describedby: description ? `${id}-hint` : `${id}-label`, hint: description, ...controlProps}} validators={validators} component={TextareaComponent} mapProps={{ className: ({ fieldValue }) => !fieldValue.valid && fieldValue.touched ? 'invalid' : '', value: (props) => props.viewValue, ...mapProps, ...controls.default, }} /> </div> ) }; Textarea.defaultProps = { mapProps: {} } Textarea.propTypes = { name: PropTypes.string.isRequired, id: PropTypes.string.isRequired, label: PropTypes.string.isRequired, model: PropTypes.oneOfType([ PropTypes.func, PropTypes.string, ]).isRequired, validators: PropTypes.object, messages: PropTypes.object, description: PropTypes.string, controlProps: PropTypes.object, mapProps: PropTypes.oneOfType([ PropTypes.func, PropTypes.object, ]), }; export default Textarea;
packages/mineral-ui-icons/src/IconAlarm.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconAlarm(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37V8zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9a9 9 0 0 0 0-18zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/> </g> </Icon> ); } IconAlarm.displayName = 'IconAlarm'; IconAlarm.category = 'action';
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
JacksonLee2019/CS341-VolunteerSchedule
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
fields/types/date/DateFilter.js
Pylipala/keystone
import _ from 'underscore'; import classNames from 'classnames'; import React from 'react'; import { FormField, FormInput, FormRow, FormSelect, SegmentedControl } from 'elemental'; const TOGGLE_OPTIONS = [ { label: 'Matches', value: false }, { label: 'Does NOT Match', value: true } ]; const MODE_OPTIONS = [ { label: 'On', value: 'on' }, { label: 'After', value: 'after' }, { label: 'Before', value: 'before' }, { label: 'Between', value: 'between' } ]; var NumberFilter = React.createClass({ getInitialState () { return { modeValue: MODE_OPTIONS[0].value, // 'on' modeLabel: MODE_OPTIONS[0].label, // 'On' inverted: TOGGLE_OPTIONS[0].value, value: '' }; }, componentDidMount () { // focus the text input React.findDOMNode(this.refs.input).focus(); }, toggleInverted (value) { this.setState({ inverted: value }); }, selectMode (mode) { // TODO: implement w/o underscore this.setState({ modeValue: mode, modeLabel: _.findWhere(MODE_OPTIONS, { value: mode }).label }); // focus the text input after a mode selection is made React.findDOMNode(this.refs.input).focus(); }, renderToggle () { return ( <FormField> <SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.state.inverted} onChange={this.toggleInverted} /> </FormField> ); }, renderControls () { let controls; let { field } = this.props; let { modeLabel, modeValue } = this.state; let placeholder = field.label + ' is ' + modeLabel.toLowerCase() + '...'; if (modeValue === 'between') { controls = ( <FormRow> <FormField width="one-half"> <FormInput ref="input" placeholder="From" /> </FormField> <FormField width="one-half"> <FormInput placeholder="To" /> </FormField> </FormRow> ); } else { controls = ( <FormField> <FormInput ref="input" placeholder={placeholder} /> </FormField> ); } return controls; }, render () { let { modeLabel, modeValue } = this.state; return ( <div> {this.renderToggle()} <FormSelect options={MODE_OPTIONS} onChange={this.selectMode} value={modeValue} /> {this.renderControls()} </div> ); } }); module.exports = NumberFilter;
src/client/home/index.react.js
hsrob/league-este
import Component from '../components/component.react'; import DocumentTitle from 'react-document-title'; import React from 'react'; import {FormattedHTMLMessage} from 'react-intl'; import {Link} from 'react-router'; export default class HomeIndex extends Component { static propTypes = { msg: React.PropTypes.object.isRequired } render() { const {msg: {home: msg}} = this.props; return ( <DocumentTitle title={msg.title}> <div className="home-page"> <p> <FormattedHTMLMessage message={msg.infoHtml} />{' '} <Link to="todos">{msg.todos}</Link>. </p> </div> </DocumentTitle> ); } }
src/svg-icons/content/sort.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentSort = (props) => ( <SvgIcon {...props}> <path d="M3 18h6v-2H3v2zM3 6v2h18V6H3zm0 7h12v-2H3v2z"/> </SvgIcon> ); ContentSort = pure(ContentSort); ContentSort.displayName = 'ContentSort'; ContentSort.muiName = 'SvgIcon'; export default ContentSort;
public/js/components/profile/visitor/Photo.react.js
TRomesh/Coupley
import React from 'react'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; import Paper from 'material-ui/lib/paper'; import GridList from 'material-ui/lib/grid-list/grid-list'; import GridTile from 'material-ui/lib/grid-list/grid-tile'; import IconButton from 'material-ui/lib/icon-button'; const styles = { root: { marginRight: "40" }, gridList: { width: 500, height: 225, }, }; const Photo = React.createClass({ render: function() { return ( <div> <div className="col-lg-3" style={styles.root}> <GridList cellHeight={200} style={styles.gridList} > <GridTile key={this.props.path} > <img src={'img/activityFeedPics/' + this.props.path} /> </GridTile> </GridList> </div> </div> ); } }); export default Photo;
www/src/components/GitHubEditLink.js
TaitoUnited/taito-cli
import React from 'react'; import { MdModeEdit } from 'react-icons/md'; import styled from '@emotion/styled'; import { IS_BROWSER } from '../constants'; const GitHubEditLink = ({ path }) => { const pathname = IS_BROWSER && window.location.pathname.replace(/\/+$/, ''); const filename = path ? path : pathname; const url = `https://github.com/TaitoUnited/taito-cli/edit/dev/docs${filename}.md`; return ( <Wrapper> <MdModeEdit /> <a href={url} alt={url}> Edit this page on GitHub </a> </Wrapper> ); }; const Wrapper = styled.div` display: flex; `; export default GitHubEditLink;
node_modules/react-navigation/src/TypeDefinition.js
gunaangs/Feedonymous
/* @flow */ import React from 'react'; // @todo when we split types into common, native and web, // we can properly change Animated.Value to its real value type AnimatedValue = *; export type HeaderMode = 'float' | 'screen' | 'none'; export type HeaderProps = NavigationSceneRendererProps & { mode: HeaderMode, router: NavigationRouter< NavigationState, NavigationAction, NavigationStackScreenOptions >, getScreenDetails: NavigationScene => NavigationScreenDetails< NavigationStackScreenOptions >, style: Style, }; /** * NavigationState is a tree of routes for a single navigator, where each child * route may either be a NavigationScreenRoute or a NavigationRouterRoute. * NavigationScreenRoute represents a leaf screen, while the * NavigationRouterRoute represents the state of a child navigator. * * NOTE: NavigationState is a state tree local to a single navigator and * its child navigators (via the routes field). * If we're in navigator nested deep inside the app, the state will only be the * state for that navigator. * The state for the root navigator of our app represents the whole navigation * state for the whole app. */ export type NavigationState = { /** * Index refers to the active child route in the routes array. */ index: number, routes: Array<NavigationRoute>, }; export type NavigationRoute = NavigationLeafRoute | NavigationStateRoute; export type NavigationLeafRoute = { /** * React's key used by some navigators. No need to specify these manually, * they will be defined by the router. */ key: string, /** * For example 'Home'. * This is used as a key in a route config when creating a navigator. */ routeName: string, /** * Path is an advanced feature used for deep linking and on the web. */ path?: string, /** * Params passed to this route when navigating to it, * e.g. `{ car_id: 123 }` in a route that displays a car. */ params?: NavigationParams, }; export type NavigationStateRoute = NavigationLeafRoute & { index: number, routes: Array<NavigationRoute>, }; export type NavigationScreenOptionsGetter<Options, Action> = ( navigation: NavigationScreenProp<NavigationRoute, Action>, screenProps?: {} ) => Options; export type NavigationRouter<State, Action, Options> = { /** * The reducer that outputs the new navigation state for a given action, with * an optional previous state. When the action is considered handled but the * state is unchanged, the output state is null. */ getStateForAction: (action: Action, lastState: ?State) => ?State, /** * Maps a URI-like string to an action. This can be mapped to a state * using `getStateForAction`. */ getActionForPathAndParams: ( path: string, params?: NavigationParams ) => ?Action, getPathAndParamsForState: ( state: State ) => { path: string, params?: NavigationParams, }, getComponentForRouteName: (routeName: string) => NavigationComponent, getComponentForState: (state: State) => NavigationComponent, /** * Gets the screen navigation options for a given screen. * * For example, we could get the config for the 'Foo' screen when the * `navigation.state` is: * * {routeName: 'Foo', key: '123'} */ getScreenOptions: NavigationScreenOptionsGetter<Options, Action>, }; export type NavigationScreenOption<T> = | T | (( navigation: NavigationScreenProp<NavigationRoute, NavigationAction>, config: T ) => T); export type Style = | { [key: string]: any } | number | false | null | void | Array<Style>; export type NavigationScreenDetails<T> = { options: T, state: NavigationRoute, navigation: NavigationScreenProp<NavigationRoute, NavigationAction>, }; export type NavigationScreenOptions = { title?: string, }; export type NavigationScreenConfigProps = { navigation: NavigationScreenProp<NavigationRoute, NavigationAction>, screenProps: Object, }; export type NavigationScreenConfig<Options> = | Options | (NavigationScreenConfigProps & (({ navigationOptions: NavigationScreenProp< NavigationRoute, NavigationAction >, }) => Options)); export type NavigationComponent = | NavigationScreenComponent<*, *> | NavigationNavigator<*, *, *, *>; export type NavigationScreenComponent<T, Options> = ReactClass<T> & { navigationOptions?: NavigationScreenConfig<Options>, }; export type NavigationNavigator<T, State, Action, Options> = ReactClass<T> & { router?: NavigationRouter<State, Action, Options>, navigationOptions?: NavigationScreenConfig<Options>, }; export type NavigationParams = { [key: string]: string, }; export type NavigationNavigateAction = { type: 'Navigation/NAVIGATE', routeName: string, params?: NavigationParams, // The action to run inside the sub-router action?: NavigationNavigateAction, }; export type NavigationBackAction = { type: 'Navigation/BACK', key?: ?string, }; export type NavigationSetParamsAction = { type: 'Navigation/SET_PARAMS', // The key of the route where the params should be set key: string, // The new params to merge into the existing route params params?: NavigationParams, }; export type NavigationInitAction = { type: 'Navigation/INIT', params?: NavigationParams, }; export type NavigationResetAction = { type: 'Navigation/RESET', index: number, key?: ?string, actions: Array<NavigationNavigateAction>, }; export type NavigationUriAction = { type: 'Navigation/URI', uri: string, }; export type NavigationStackViewConfig = { mode?: 'card' | 'modal', headerMode?: HeaderMode, cardStyle?: Style, transitionConfig?: () => TransitionConfig, onTransitionStart?: () => void, onTransitionEnd?: () => void, }; export type NavigationStackScreenOptions = NavigationScreenOptions & { header?: ?(React.Element<*> | (HeaderProps => React.Element<*>)), headerTitle?: string | React.Element<*>, headerTitleStyle?: Style, headerTintColor?: string, headerLeft?: React.Element<*>, headerBackTitle?: string, headerTruncatedBackTitle?: string, headerBackTitleStyle?: Style, headerPressColorAndroid?: string, headerRight?: React.Element<*>, headerStyle?: Style, gesturesEnabled?: boolean, }; export type NavigationStackRouterConfig = { initialRouteName?: string, initialRouteParams?: NavigationParams, paths?: NavigationPathsConfig, navigationOptions?: NavigationScreenConfig<NavigationStackScreenOptions>, }; export type NavigationStackAction = | NavigationInitAction | NavigationNavigateAction | NavigationBackAction | NavigationSetParamsAction | NavigationResetAction; export type NavigationTabAction = | NavigationInitAction | NavigationNavigateAction | NavigationBackAction; export type NavigationAction = | NavigationInitAction | NavigationStackAction | NavigationTabAction; export type NavigationRouteConfig<T> = T & { navigationOptions?: NavigationScreenConfig<*>, path?: string, }; export type NavigationScreenRouteConfig = | { screen: NavigationComponent, } | { getScreen: () => NavigationComponent, }; export type NavigationPathsConfig = { [routeName: string]: string, }; export type NavigationTabRouterConfig = { initialRouteName?: string, paths?: NavigationPathsConfig, navigationOptions?: NavigationScreenConfig<NavigationTabScreenOptions>, order?: Array<string>, // todo: type these as the real route names rather than 'string' // Does the back button cause the router to switch to the initial tab backBehavior?: 'none' | 'initialRoute', // defaults `initialRoute` }; export type NavigationTabScreenOptions = NavigationScreenOptions & { tabBarIcon?: | React.Element<*> | ((options: { tintColor: ?string, focused: boolean }) => ?React.Element< * >), tabBarLabel?: | string | React.Element<*> | ((options: { tintColor: ?string, focused: boolean }) => ?React.Element< * >), tabBarVisible?: boolean, }; export type NavigationDrawerScreenOptions = NavigationScreenOptions & { drawerIcon?: | React.Element<*> | ((options: { tintColor: ?string, focused: boolean }) => ?React.Element< * >), drawerLabel?: | React.Element<*> | ((options: { tintColor: ?string, focused: boolean }) => ?React.Element< * >), }; export type NavigationRouteConfigMap = { [routeName: string]: NavigationRouteConfig<*>, }; export type NavigationDispatch<A> = (action: A) => boolean; export type NavigationProp<S, A> = { state: S, dispatch: NavigationDispatch<A>, }; export type NavigationScreenProp<S, A> = { state: S, dispatch: NavigationDispatch<A>, goBack: (routeKey?: ?string) => boolean, navigate: ( routeName: string, params?: NavigationParams, action?: NavigationAction ) => boolean, setParams: (newParams: NavigationParams) => boolean, }; export type NavigationNavigatorProps<T> = { navigation: NavigationProp<T, NavigationAction>, screenProps: *, navigationOptions: *, }; /** * Gestures, Animations, and Interpolators */ export type NavigationGestureDirection = 'horizontal' | 'vertical'; export type NavigationLayout = { height: AnimatedValue, initHeight: number, initWidth: number, isMeasured: boolean, width: AnimatedValue, }; export type NavigationScene = { index: number, isActive: boolean, isStale: boolean, key: string, route: NavigationRoute, }; export type NavigationTransitionProps = { // The layout of the screen container layout: NavigationLayout, // The destination navigation state of the transition navigation: NavigationScreenProp<NavigationState, NavigationAction>, // The progressive index of the transitioner's navigation state. position: AnimatedValue, // The value that represents the progress of the transition when navigation // state changes from one to another. Its numberic value will range from 0 // to 1. // progress.__getAnimatedValue() < 1 : transtion is happening. // progress.__getAnimatedValue() == 1 : transtion completes. progress: AnimatedValue, // All the scenes of the transitioner. scenes: Array<NavigationScene>, // The active scene, corresponding to the route at // `navigation.state.routes[navigation.state.index]`. When rendering // NavigationSceneRendererPropsIndex, the scene does not refer to the active // scene, but instead the scene that is being rendered. The index always // is the index of the scene scene: NavigationScene, index: number, screenProps?: {}, }; // The scene renderer props are nearly identical to the props used for rendering // a transition. The exception is that the passed scene is not the active scene // but is instead the scene that the renderer should render content for. export type NavigationSceneRendererProps = NavigationTransitionProps; export type NavigationTransitionSpec = { duration?: number, // An easing function from `Easing`. easing?: (t: number) => number, // A timing function such as `Animated.timing`. timing?: (value: AnimatedValue, config: any) => any, }; /** * Describes a visual transition from one screen to another. */ export type TransitionConfig = { // The basics properties of the animation, such as duration and easing transitionSpec?: NavigationTransitionSpec, // How to animate position and opacity of the screen // based on the value generated by the transitionSpec screenInterpolator?: (props: NavigationSceneRendererProps) => Object, }; export type NavigationAnimationSetter = ( position: AnimatedValue, newState: NavigationState, lastState: NavigationState ) => void; export type NavigationSceneRenderer = () => ?React.Element<*>; export type NavigationStyleInterpolator = ( props: NavigationSceneRendererProps ) => Style; export type LayoutEvent = { nativeEvent: { layout: { x: number, y: number, width: number, height: number, }, }, };
src/svg-icons/notification/airline-seat-flat-angled.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatFlatAngled = (props) => ( <SvgIcon {...props}> <path d="M22.25 14.29l-.69 1.89L9.2 11.71l2.08-5.66 8.56 3.09c2.1.76 3.18 3.06 2.41 5.15zM1.5 12.14L8 14.48V19h8v-1.63L20.52 19l.69-1.89-19.02-6.86-.69 1.89zm5.8-1.94c1.49-.72 2.12-2.51 1.41-4C7.99 4.71 6.2 4.08 4.7 4.8c-1.49.71-2.12 2.5-1.4 4 .71 1.49 2.5 2.12 4 1.4z"/> </SvgIcon> ); NotificationAirlineSeatFlatAngled = pure(NotificationAirlineSeatFlatAngled); NotificationAirlineSeatFlatAngled.displayName = 'NotificationAirlineSeatFlatAngled'; NotificationAirlineSeatFlatAngled.muiName = 'SvgIcon'; export default NotificationAirlineSeatFlatAngled;
src/index.js
AihuishouFE/AiChat
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import 'antd/dist/antd.css'; ReactDOM.render(<App />, document.getElementById('root'));
docs/Banner.js
jxnblk/cxs
import React from 'react' import cxs from 'cxs/component' const Banner = cxs('header')(props => ({ display: 'flex', flexDirection: 'column' })) export default Banner
examples/huge-apps/components/GlobalNav.js
gdi2290/react-router
import React from 'react'; import { Link } from 'react-router'; const styles = {}; class GlobalNav extends React.Component { static defaultProps = { user: { id: 1, name: 'Ryan Florence' } }; constructor (props, context) { super(props, context); this.logOut = this.logOut.bind(this); } logOut () { alert('log out'); } render () { var { user } = this.props; return ( <div style={styles.wrapper}> <div style={{float: 'left'}}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link}>Calendar</Link>{' '} <Link to="/grades" style={styles.link}>Grades</Link>{' '} <Link to="/messages" style={styles.link}>Messages</Link>{' '} </div> <div style={{float: 'right'}}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ); } } styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: 'hsl(200, 20%, 20%)', color: '#fff' }; styles.link = { padding: 10, color: '#fff', fontWeight: 200 } export default GlobalNav;
src/components/DataTable/DataTable.js
miaoji/guojibackend
import React from 'react' import PropTypes from 'prop-types' import { Table } from 'antd' import { request } from '../../utils' import lodash from 'lodash' import './DataTable.less' class DataTable extends React.Component { constructor (props) { super(props) const { dataSource, pagination = { showSizeChanger: true, showQuickJumper: true, showTotal: total => `共 ${total} 条`, current: 1, total: 100 }, } = props this.state = { loading: false, dataSource, fetchData: {}, pagination, } } componentDidMount () { if (this.props.fetch) { this.fetch() } } componentWillReceiveProps (nextProps) { const staticNextProps = lodash.cloneDeep(nextProps) delete staticNextProps.columns const { columns, ...otherProps } = this.props if (!lodash.isEqual(staticNextProps, otherProps)) { this.props = nextProps this.fetch() } } handleTableChange = (pagination, filters, sorter) => { const pager = this.state.pagination pager.current = pagination.current this.setState({ pagination: pager, fetchData: { results: pagination.pageSize, page: pagination.current, sortField: sorter.field, sortOrder: sorter.order, ...filters, }, }, () => { this.fetch() }) } fetch = () => { const { fetch: { url, data, dataKey } } = this.props const { fetchData } = this.state this.setState({ loading: true }) this.promise = request({ url, data: { ...data, ...fetchData, }, }).then((result) => { if (!this.refs.DataTable) { return } const { pagination } = this.state pagination.total = result.total || pagination.total this.setState({ loading: false, dataSource: dataKey ? result[dataKey] : result.data, pagination, }) }) } render () { const { fetch, ...tableProps } = this.props const { loading, dataSource, pagination } = this.state return (<Table ref="DataTable" bordered loading={loading} onChange={this.handleTableChange} {...tableProps} pagination={pagination} dataSource={dataSource} />) } } DataTable.propTypes = { fetch: PropTypes.object, rowKey: PropTypes.string, pagination: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.object, ]), columns: PropTypes.array, dataSource: PropTypes.array, } export default DataTable
app/components/ClubCard/index.js
NathanBWaters/jb_club
/** * * ClubCard * */ import React from 'react'; import styles from './styles.css'; import { Col, Grid, Button } from 'react-bootstrap'; class ClubCard extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { title: React.PropTypes.string, }; render() { return ( <div className={styles.clubCard}> <header className={styles.headerContainer}> <h4>{this.props.title}</h4> </header> <Grid className={styles.main}> <Col className={styles.column} xs={6} sm={6} md={6}> <img className={styles.logo} src = { this.props.logo } /> </Col> <Col xs={6} sm={6} md={6}> <p><b>About:</b><br />lorem ipsum</p> <p><b>Facebook:</b><br />lorem ipsum</p> </Col> </Grid> <section className={styles.buttonContainer}> <Button >Learn More</Button> </section> </div> ); } } export default ClubCard;
app/javascript/mastodon/features/ui/components/tabs_bar.js
h-izumi/mastodon
import React from 'react'; import NavLink from 'react-router-dom/NavLink'; import { FormattedMessage } from 'react-intl'; class TabsBar extends React.Component { render () { return ( <div className='tabs-bar'> <NavLink className='tabs-bar__link primary' activeClassName='active' to='/statuses/new'><i className='fa fa-fw fa-pencil' /><FormattedMessage id='tabs_bar.compose' defaultMessage='Compose' /></NavLink> <NavLink className='tabs-bar__link primary' activeClassName='active' to='/timelines/home'><i className='fa fa-fw fa-home' /><FormattedMessage id='tabs_bar.home' defaultMessage='Home' /></NavLink> <NavLink className='tabs-bar__link primary' activeClassName='active' to='/notifications'><i className='fa fa-fw fa-bell' /><FormattedMessage id='tabs_bar.notifications' defaultMessage='Notifications' /></NavLink> <NavLink className='tabs-bar__link secondary' activeClassName='active' to='/timelines/public/local'><i className='fa fa-fw fa-users' /><FormattedMessage id='tabs_bar.local_timeline' defaultMessage='Local' /></NavLink> <NavLink className='tabs-bar__link secondary' activeClassName='active' exact to='/timelines/public'><i className='fa fa-fw fa-globe' /><FormattedMessage id='tabs_bar.federated_timeline' defaultMessage='Federated' /></NavLink> <NavLink className='tabs-bar__link primary' activeClassName='active' style={{ flexGrow: '0', flexBasis: '30px' }} to='/getting-started'><i className='fa fa-fw fa-asterisk' /></NavLink> </div> ); } } export default TabsBar;
docs/app/Examples/collections/Table/Variations/TableExampleSingleLine.js
clemensw/stardust
import React from 'react' import { Table } from 'semantic-ui-react' const TableExampleSingleLine = () => { return ( <Table singleLine> <Table.Header> <Table.Row> <Table.HeaderCell>Name</Table.HeaderCell> <Table.HeaderCell>Registration Date</Table.HeaderCell> <Table.HeaderCell>E-mail address</Table.HeaderCell> <Table.HeaderCell>Premium Plan</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>John Lilki</Table.Cell> <Table.Cell>September 14, 2013</Table.Cell> <Table.Cell>[email protected]</Table.Cell> <Table.Cell>No</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie Harington</Table.Cell> <Table.Cell>January 11, 2014</Table.Cell> <Table.Cell>[email protected]</Table.Cell> <Table.Cell>Yes</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill Lewis</Table.Cell> <Table.Cell>May 11, 2014</Table.Cell> <Table.Cell>[email protected]</Table.Cell> <Table.Cell>Yes</Table.Cell> </Table.Row> </Table.Body> </Table> ) } export default TableExampleSingleLine
src/routes/index.js
mortondev/rapport
import ReactDOM from 'react-dom'; import React from 'react'; import { Router, Route } from 'react-router'; import Html from '../components/Html.jsx'; import App from '../components/App.jsx'; import Login from '../components/Login.jsx'; const routes = ( <Route path="/" component={App}> <Route path="login" component={Login} /> </Route> ); export default routes;
src/Accordion.js
wjb12/react-bootstrap
import React from 'react'; import PanelGroup from './PanelGroup'; const Accordion = React.createClass({ render() { return ( <PanelGroup {...this.props} accordion> {this.props.children} </PanelGroup> ); } }); export default Accordion;
app/react-icons/fa/y-combinator.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaYCombinator extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m21.1 22.4l5.9-11.1h-2.5l-3.5 6.9q-0.5 1.1-1 2.1l-0.9-2.1-3.5-6.9h-2.7l5.9 11v7.2h2.3v-7.1z m16.2-19.5v34.2h-34.3v-34.2h34.3z"/></g> </IconBase> ); } }
src/components/DictList/Props.js
GuramDuka/reorders
//------------------------------------------------------------------------------ import React, { Component } from 'react'; import connect from 'react-redux-connect'; import * as Sui from 'semantic-ui-react'; import disp, { sscat } from '../../store'; import BACKEND_URL, { transform, serializeURIParams } from '../../backend'; //------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ class Props extends Component { static mapStateToProps(state, ownProps) { return state.mapIn(ownProps.path); } static connectOptions = { withRef: true }; state = { numr : {}, rows : [], grps : [] }; reload = (options) => { const obj = this; const { link } = obj.props; obj.setState({ isLoading: true }); return state => { const opts = { method : options && options.refresh ? 'PUT' : 'GET', credentials : 'omit', mode : 'cors', cache : 'default' }; const r = { r : { type : 'Номенклатура', link : link }, m : 'props', f : 'get' }; if( opts.method === 'PUT' ) opts.body = JSON.stringify(r); const url = BACKEND_URL + (opts.method === 'GET' ? '?' + serializeURIParams({r:r}) : ''); fetch(url, opts).then(response => { const contentType = response.headers.get('content-type'); if( contentType ) { if( contentType.includes('application/json') ) return response.json(); if( contentType.includes('text/') ) return response.text(); } // will be caught below throw new TypeError('Oops, we haven\'t right type of response! Status: ' + response.status + ', ' + response.statusText); }).then(json => { if( json === undefined || json === null || (json.constructor !== Object && json.constructor !== Array) ) throw new TypeError('Oops, we haven\'t got JSON!' + (json && json.constructor === String ? ' ' + json : '')); json = transform(json); const data = { numr : json.numeric, rows : json.rows }; obj.setState({...data, isLoading: false}); }) .catch(error => { if( process.env.NODE_ENV === 'development' ) console.log(error); obj.setState({ isLoading: false }); }); return state; }; }; componentWillMount() { disp(this.reload(), true); } render() { const { props, state } = this; if( process.env.NODE_ENV === 'development' ) console.log('render Props: ' + props.link); const data = []; if( state.rows ) state.rows.map(row => data.push(row.СвойствоПредставление + ': ' + row.ЗначениеПредставление)); return ( <Sui.Dimmer.Dimmable as={Sui.Container} dimmed={state.isLoading}> <Sui.Dimmer active={state.isLoading} inverted> <Sui.Loader>Загрузка свойств...</Sui.Loader> </Sui.Dimmer> {state.rows ? <span>{sscat(', ', ...data)}</span> : null} </Sui.Dimmer.Dimmable>); } } //------------------------------------------------------------------------------ export default connect(Props); //------------------------------------------------------------------------------
examples/with-ioc/pages/blog.js
BlancheXu/test
import React from 'react' import { provide, types } from 'ioc' import { Link, Router } from '../routes' import Component1 from '../components/component1' const posts = [ { slug: 'hello-world', title: 'Hello world' }, { slug: 'another-blog-post', title: 'Another blog post' }, ] @provide({ @types.func.isRequired Link, @types.object Router, }) export default class extends React.Component { static async getInitialProps({ query, res }) { const post = posts.find(post => post.slug === query.slug) if (!post && res) { res.statusCode = 404 } return { post } } render() { const { post } = this.props if (!post) return <h1>Post not found</h1> return ( <div> <h1>{post.title}</h1> <Component1 /> </div> ) } }
app/javascript/mastodon/components/attachment_list.js
Craftodon/Craftodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; const filename = url => url.split('/').pop().split('#')[0].split('?')[0]; export default class AttachmentList extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.list.isRequired, }; render () { const { media } = this.props; return ( <div className='attachment-list'> <div className='attachment-list__icon'> <i className='fa fa-link' /> </div> <ul className='attachment-list__list'> {media.map(attachment => <li key={attachment.get('id')}> <a href={attachment.get('remote_url')} target='_blank' rel='noopener'>{filename(attachment.get('remote_url'))}</a> </li> )} </ul> </div> ); } }
ui/src/js/profile/NoTeamAvailable.js
Dica-Developer/weplantaforest
import counterpart from 'counterpart'; import React, { Component } from 'react'; import IconButton from '../common/components/IconButton'; export default class NoTeamAvailable extends Component { constructor() { super(); this.state = { isLoggedIn: localStorage.getItem('jwt') != null && localStorage.getItem('jwt') != '' }; } goToCreateTeam() { this.props.openCreateTeamPart(); } render() { let createTeamButton; if (this.state.isLoggedIn && this.props.isMyProfile) { createTeamButton = ( <div className="row align-center bottomButton"> <IconButton text={counterpart.translate('TEAM_CREATE')} glyphIcon="glyphicon glyphicon-plus" onClick={this.goToCreateTeam.bind(this)} /> </div> ); } else { createTeamButton = ''; } let noTeamMessage = counterpart.translate('NO_TEAM_VISITOR'); if (this.props.isMyProfile) { noTeamMessage = counterpart.translate('NO_TEAM_ME'); } return ( <div> <h1>{noTeamMessage}</h1> {createTeamButton} </div> ); } } /* vim: set softtabstop=2:shiftwidth=2:expandtab */
client/util/react-intl-test-helper.js
vladmokryi/Nation-Forecast
/** * Components using the react-intl module require access to the intl context. * This is not available when mounting single components in Enzyme. * These helper functions aim to address that and wrap a valid, * English-locale intl context around them. */ import React from 'react'; import { IntlProvider, intlShape } from 'react-intl'; import { mount, shallow } from 'enzyme'; // You can pass your messages to the IntlProvider. Optional: remove if unneeded. const messages = require('../../Intl/localizationData/en'); // Create the IntlProvider to retrieve context for wrapping around. const intlProvider = new IntlProvider({ locale: 'en', messages }, {}); export const { intl } = intlProvider.getChildContext(); /** * When using React-Intl `injectIntl` on components, props.intl is required. */ const nodeWithIntlProp = node => { return React.cloneElement(node, { intl }); }; export const shallowWithIntl = node => { return shallow(nodeWithIntlProp(node), { context: { intl } }); }; export const mountWithIntl = node => { return mount(nodeWithIntlProp(node), { context: { intl }, childContextTypes: { intl: intlShape }, }); };
src/routes/Wheels/components/Wheels.js
k2data/svg-react-playground
// @flow import React from 'react' import Route from 'react-router-dom/Route' import { Wheel1, Wheel2 } from 'components/Wheels' import styles from './Wheels.css' type Props = {} const Wheel = (props: Props) => ( <div className={styles['wheels']}> <Route path='/wheels/1' component={Wheel1} exact /> <Route path='/wheels/2' component={Wheel2} exact /> </div> ) export default Wheel
src/node.js
zjfjiayou/react-native-mind
import React, { Component } from 'react'; import {emitter} from './core/utils'; import {G} from 'react-native-svg'; import Connect from './connect'; import Expand from './expand'; import Title from './nodeExt/title'; import Image from './nodeExt/image'; import File from './nodeExt/file'; import Content from './nodeExt/content'; import command from './core/command'; class Node extends Component { constructor(props) { super(props); this.hideChildren = this.hideChildren.bind(this); } hideChildren(expand){ this.props.nodeData.postTraverse((node)=>{ node.data.expand = expand; node._chenged = true; },true); command.exec('redraw',this.props.nodeData.root.data.node_id); } shouldComponentUpdate(nextProps, nextState) { if (nextProps.nodeData._chenged){ nextProps.nodeData._chenged = false; return true; } return false; } render(){ let node; const {nodeData} = this.props; //节点类型分类 switch (nodeData.data.content_type){ case 'content.builtin.image': node = <Image nodeData={nodeData} />; break; case 'content.builtin.attachment': node = <File nodeData={nodeData} />; break; case 'content.builtin.text': node = <Content nodeData={nodeData} />; break; default: node = <Title nodeData={nodeData} />; break; } //判断节点是否展开 if (!nodeData.isRoot() && nodeData.data.expand === false){ return <G />; } return ( <G y={nodeData.point.y} x={nodeData.point.x} > <Connect nodeData={nodeData}/> <G id={nodeData.data.node_id} onPress={(evn)=>{ emitter.emit('node.press',nodeData); }} > {node} </G> <Expand nodeData={nodeData} hideChildren={this.hideChildren} /> </G> ); } } export default Node;
src/components/historical-prices/price-list.js
SupasitC/Pricetrolley
import React from 'react' import { Row, Col } from 'react-bootstrap' export default class PriceList extends React.Component { render() { const style = require('./price-list.scss'); return ( <div className={style.priceList}> <Row> <Col md={3}> <span className={style.price}>$400,000</span> </Col> <Col md={9}> <span className={style.date}>16/12/2016</span> </Col> </Row> </div> ) } }
js/account/src/components/Registry/RegistryNone.js
fogfish/oauth2
import React from 'react' import { H5, Button, Intent } from '@blueprintjs/core' const RegistryNone = ({ showRegistrar }) => ( <div> <H5>No OAuth applications in your account...</H5> <p>OAuth applications are used to access REST API.</p> <Button intent={Intent.PRIMARY} onClick={() => showRegistrar(true)}> Register New OAuth App </Button> </div> ) export default RegistryNone
src/pages/ImportExport.js
oglimmer/linky
import React from 'react'; import { connect } from 'react-redux'; import { Button, FormGroup } from 'react-bootstrap'; import { Form } from 'react-redux-form'; import PropTypes from 'prop-types'; import UIInputElement from '../components/UIInputElement'; import { importBookmarks, exportBookmarks } from '../redux/actions'; const ImportExportPage = ({ onSubmit, onExport, buttonsDisable }) => ( <div> <Form className="form-horizontal" model="importExport" onSubmit={onSubmit}> <FormGroup controlId="row1controls"> <UIInputElement label="NETSCAPE-Bookmark-file-1" model="bookmarks" placeholder="!DOCTYPE NETSCAPE-Bookmark-file-1" autoComplete="off" componentClass="textarea" cols={11} /> </FormGroup> <FormGroup controlId="row2controls"> <UIInputElement label="Tag Prefix" model="tagPrefix" placeholder="Leave blank if you want to import all tags as given or use this field to prefix all imported tags" autoComplete="off" cols={11} /> </FormGroup> <FormGroup controlId="row3controls"> <UIInputElement label="Root node for tags" model="importNode" placeholder="When blank all imported tags go under 'root'. Recommended to use 'import'." autoComplete="off" cols={11} /> </FormGroup> <div> <Button disabled={buttonsDisable} type="submit">Import</Button>{' '} <Button disabled={buttonsDisable} onClick={onExport}>Export</Button> </div> </Form> </div> ); ImportExportPage.propTypes = { onSubmit: PropTypes.func.isRequired, onExport: PropTypes.func.isRequired, buttonsDisable: PropTypes.bool.isRequired, }; const mapStateToProps = state => ({ buttonsDisable: state.importExport.buttonsDisable, }); const mapDispatchToProps = dispatch => ({ onSubmit: formData => dispatch(importBookmarks(formData.bookmarks, formData.tagPrefix, formData.importNode)), onExport: () => dispatch(exportBookmarks()), }); export default connect(mapStateToProps, mapDispatchToProps)(ImportExportPage);
docs/src/app/components/pages/components/Stepper/CustomIcon.js
ngbrown/material-ui
import React from 'react'; import { Step, Stepper, StepLabel, } from 'material-ui/Stepper'; import WarningIcon from 'material-ui/svg-icons/alert/warning'; import {red500} from 'material-ui/styles/colors'; /** * Custom icons can be used to create different visual states. */ class CustomIcon extends React.Component { state = { stepIndex: 0, }; handleNext = () => { const {stepIndex} = this.state; if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } }; handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } }; getStepContent(stepIndex) { switch (stepIndex) { case 0: return 'Select campaign settings...'; case 1: return 'What is an ad group anyways?'; case 2: return 'This is the bit I really care about!'; default: return 'You\'re a long way from home sonny jim!'; } } render() { return ( <div style={{width: '100%', maxWidth: 700, margin: 'auto'}}> <Stepper linear={false}> <Step completed={false}> <StepLabel> Select campaign settings </StepLabel> </Step> <Step completed={false}> <StepLabel icon={<WarningIcon color={red500} />} style={{color: red500}} > Create an ad group </StepLabel> </Step> <Step completed={false}> <StepLabel> Create an ad </StepLabel> </Step> </Stepper> </div> ); } } export default CustomIcon;
src/deposit/DepositMobile.js
qingweibinary/binary-next-gen
import React from 'react'; import MobilePage from '../containers/MobilePage'; import DepositContainer from './DepositContainer'; export default (props) => ( <MobilePage toolbarShown={false} backBtnBarTitle="Deposit"> <DepositContainer {...props} /> </MobilePage> );
modules/gui/src/app/home/body/tasks/tasks.js
openforis/sepal
import {Button} from 'widget/button' import {ButtonGroup} from 'widget/buttonGroup' import {Content, SectionLayout, TopBar} from 'widget/sectionLayout' import {HoverDetector, HoverOverlay} from 'widget/hover' import {Progress} from 'widget/progress' import {Scrollable, ScrollableContainer} from 'widget/scrollable' import {Shape} from 'widget/shape' import {compose} from 'compose' import {connect} from 'store' import {msg} from 'translate' import React from 'react' import api from 'api' import clipboard from 'clipboard' import look from 'style/look.module.css' import styles from './tasks.module.css' const mapStateToProps = state => ({ tasks: state.tasks, }) class Tasks extends React.Component { constructor(props) { super(props) this.state = {tasks: props.tasks || []} } renderOverlay(task) { return ( <div className={styles.overlay}> {['FAILED', 'COMPLETED', 'CANCELED'].includes(task.status) ? ( <ButtonGroup layout='vertical'> <Button icon='copy' label={msg('button.copyToClipboard')} onClick={() => this.copyToClipboard(task)}/> <Button look={'cancel'} icon='times' label={msg('button.remove')} onClick={() => this.removeTask(task)}/> </ButtonGroup> ) : ['PENDING', 'ACTIVE'].includes(task.status) ? <Button className={styles.stop} icon='stop' label={msg('button.stop')} onClick={() => this.stopTask(task)}/> : null} </div> ) } renderTask(task) { return ( <HoverDetector key={task.id} className={[styles.task, look.look, look.transparent].join(' ')}> <div className={styles.name}>{task.name}</div> <Progress className={styles.progress} status={task.status}/> <div className={styles.statusDescription}>{this.getDescription(task)}</div> <HoverOverlay> {this.renderOverlay(task)} </HoverOverlay> </HoverDetector> ) } renderTasks() { const {tasks} = this.state return tasks.length ? ( <ScrollableContainer> <Scrollable className={styles.tasks}> {tasks.map(task => this.renderTask(task))} </Scrollable> </ScrollableContainer> ) : ( <div className={styles.noTasks}> <Shape look='transparent' shape='pill' size='normal' air='more'> {msg('tasks.none')} </Shape> </div> ) } renderToolbar() { return ( <div className={styles.toolbar}> <Button chromeless size='large' icon='trash' label={msg('tasks.removeAll.label')} tooltip={msg('tasks.removeAll.tooltip')} tooltipPlacement='bottom' onClick={() => this.removeAllTasks()} disabled={!this.inactiveTasks().length}/> </div> ) } render() { return ( <SectionLayout> <TopBar label={msg('home.sections.tasks')}> {this.renderToolbar()} </TopBar> <Content horizontalPadding verticalPadding menuPadding> {this.renderTasks()} </Content> </SectionLayout> ) } getDescription(task) { let description try { description = JSON.parse(task.statusDescription) } catch(e) { description = task.statusDescription } if (typeof description === 'string') { return description } else if (description.messageKey) { return msg(description.messageKey, description.messageArgs, description.defaultMessage) } else if (description.defaultMessage) { return description.defaultMessage } else { return msg('tasks.status.executing') } } componentDidUpdate(prevProps) { const {stream} = this.props const notActive = !['REMOVE_TASK', 'REMOVE_ALL_TASKS', 'STOP_TASK'] .find(action => stream(action).active) if (prevProps.tasks !== this.props.tasks && notActive) this.setState({tasks: this.props.tasks}) } copyToClipboard(task) { clipboard.copy(JSON.stringify(task, null, ' ')) } removeTask(task) { const {stream} = this.props const {tasks} = this.state this.setState({ tasks: tasks.filter(t => t.id !== task.id) }) stream('REMOVE_TASK', api.tasks.remove$(task.id) ) } removeAllTasks() { const {stream} = this.props this.setState({tasks: this.activeTasks()}) stream('REMOVE_ALL_TASK', api.tasks.removeAll$() ) } activeTasks() { const {tasks} = this.state return tasks.filter(({status}) => ['PENDING', 'ACTIVE'].includes(status)) } inactiveTasks() { const {tasks} = this.state return tasks.filter(({status}) => !['PENDING', 'ACTIVE'].includes(status)) } stopTask(task) { const {stream} = this.props this.updateTaskInState(task, () => ({ ...task, status: 'CANCELED', statusDescription: 'Stopping...' })) stream('STOP_TASK', api.tasks.cancel$(task.id) ) } updateTaskInState(task, onUpdate) { const {tasks} = this.state this.setState({ tasks: tasks.map(t => t.id === task.id ? onUpdate() : t ) }) } } export default compose( Tasks, connect(mapStateToProps) )
src/components/Header/Header.js
CarlTheLandlord/spotify-checker
import React from 'react' import { IndexLink, Link } from 'react-router' import './Header.scss' export const Header = () => ( <div> <h1>React Redux</h1> <IndexLink to='/' activeClassName='route--active'> Home </IndexLink> {' · '} <Link to='/spotify' activeClassName='route--active'> Spotify User Info </Link> {' · '} <Link to='/login' activeClassName='route--active'> Login </Link> </div> ) export default Header
src/svg-icons/notification/sd-card.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSdCard = (props) => ( <SvgIcon {...props}> <path d="M18 2h-8L4.02 8 4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-6 6h-2V4h2v4zm3 0h-2V4h2v4zm3 0h-2V4h2v4z"/> </SvgIcon> ); NotificationSdCard = pure(NotificationSdCard); NotificationSdCard.displayName = 'NotificationSdCard'; NotificationSdCard.muiName = 'SvgIcon'; export default NotificationSdCard;
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
tessy2728/Angular2Sample
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
src/js/components/WorldMap/stories/Simple.js
HewlettPackard/grommet
import React from 'react'; import { Box, WorldMap } from 'grommet'; export const Simple = () => ( <Box align="center" pad="large"> <WorldMap /> </Box> ); Simple.parameters = { // chromatic disabled because snapshot is the same as SelectPlace chromatic: { disable: true }, }; export default { title: 'Visualizations/WorldMap/Simple', };
pages/index.js
sakulstra/firebase-nextjs-mobx
import React from 'react' import { initializePage } from '~/utils' import { BaseLayout } from '~/ui/layouts' const Home = () => ( <BaseLayout> I bims de home page. </BaseLayout> ) export default initializePage(Home)
packages/icons/src/dv/CodePen.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function DvCodePen(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M43.985 17.682c.009.074.015.148.015.224v12.187c0 .076-.006.15-.015.226l-.014.073a1.646 1.646 0 0 1-.03.144c-.008.029-.018.056-.027.083-.014.042-.028.085-.044.127-.012.028-.026.056-.039.083a1.565 1.565 0 0 1-.058.114l-.05.08a1.58 1.58 0 0 1-.072.104c-.019.026-.039.05-.059.074a1.655 1.655 0 0 1-.085.093c-.023.023-.045.046-.069.067a1.944 1.944 0 0 1-.097.082l-.078.06-.028.02-18.282 12.188a1.72 1.72 0 0 1-1.907 0L4.766 31.523l-.03-.02a1.568 1.568 0 0 1-.175-.14l-.068-.069a1.506 1.506 0 0 1-.216-.272 2.197 2.197 0 0 1-.05-.079 2.117 2.117 0 0 1-.058-.114c-.013-.027-.027-.055-.039-.083a1.978 1.978 0 0 1-.044-.127c-.009-.027-.019-.054-.027-.083-.012-.047-.02-.096-.03-.144-.004-.024-.01-.05-.013-.073A1.678 1.678 0 0 1 4 30.093V17.906c0-.076.006-.15.016-.224.003-.025.01-.05.013-.075.01-.048.018-.097.03-.144.008-.028.018-.056.027-.083a1.71 1.71 0 0 1 .083-.21 1.614 1.614 0 0 1 .324-.464c.023-.024.045-.047.07-.068a1.711 1.711 0 0 1 .174-.14l.028-.022L23.046 4.29a1.718 1.718 0 0 1 1.907 0l18.282 12.187c.01.007.018.015.028.021l.078.06c.033.025.066.053.097.081.024.021.046.045.069.068a1.701 1.701 0 0 1 .144.167c.026.034.05.068.073.104l.049.08c.021.037.04.075.058.114.013.027.027.055.039.084.016.04.03.083.044.125.009.027.02.055.026.083.013.048.022.096.03.144l.015.075zM25.719 8.931v8.017l7.452 4.984 6.015-4.024-13.467-8.977zm-3.438 0L8.814 17.908l6.016 4.024 7.45-4.984V8.93zM7.437 21.123v5.753l4.3-2.876-4.3-2.877zM22.281 39.07v-8.017l-7.451-4.984-6.016 4.023L22.28 39.07zM24 28.066L30.079 24l-6.08-4.067L17.92 24 24 28.066zm1.719 11.003l13.467-8.978-6.015-4.023-7.452 4.984v8.017zm14.843-12.193v-5.753L36.262 24l4.3 2.876z" /> </IconBase> ); } export default DvCodePen;
app/containers/DevTools.js
leofle/electron_manifesto
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q" > <LogMonitor /> </DockMonitor> );
src/components/graphlist/graphlistitem.js
jamjar919/bork
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; const GraphListItem = props => ( <li className={`graphListItem ${props.className}`}> <Link to={`/${props.id}`}>{props.name}</Link> - <Link to={`/${props.id}/edit`}>Edit</Link> </li> ); GraphListItem.propTypes = { className: PropTypes.string, id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, }; export default GraphListItem;
src/react/components/Buttons/index.js
formtools/core
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import MButton from '@material-ui/core/Button'; // primary buttons styles for default green theme only const useStyles = makeStyles(() => ({ primary: { margin: '8px 4px 8px 0', boxShadow: 'none', textTransform: 'none', letterSpacing: 'normal', background: 'linear-gradient(80deg, #5FB66F 30%, #54a863 90%)', padding: '4px 12px', '&:hover': { background: 'linear-gradient(80deg, #54a863 30%, #459353 90%)' } }, danger: { margin: '8px 4px 8px 0', boxShadow: 'none', textTransform: 'none', letterSpacing: 'normal', background: 'linear-gradient(80deg, #ce0e0e 30%, #b70707 90%)', padding: '4px 12px', '&:hover': { background: 'linear-gradient(80deg, #b70707 30%, #ad0606 90%)' } }, info: { margin: '8px 4px 8px 0', boxShadow: 'none', textTransform: 'none', letterSpacing: 'normal', background: 'linear-gradient(80deg, #d5eaef 30%, #ccdee2 90%)', padding: '4px 12px', '&:hover': { background: 'linear-gradient(80deg, #ccdee2 30%, #c3d4d8 90%)' } }, label: { color: 'white' }, labelDark: { color: '#3d4344' } })); const Button = ({ children, buttonType, ...otherProps }) => { const styles = useStyles(); const label = (buttonType === 'info') ? styles.labelDark : styles.label; return ( <MButton classes={{ root: styles[buttonType], label: label }} variant="contained" {...otherProps}> {children} </MButton> ); }; Button.defaultProps = { buttonType: 'primary' // 'primary', 'error', 'info' }; export default Button;
src/Parser/Monk/Mistweaver/Modules/Spells/SoothingMist.js
enragednuke/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; import Combatants from 'Parser/Core/Modules/Combatants'; import Analyzer from 'Parser/Core/Analyzer'; const debug = false; class SoothingMist extends Analyzer { static dependencies = { combatants: Combatants, }; soomTicks = 0; on_byPlayer_heal(event) { const spellId = event.ability.guid; if (spellId === SPELLS.SOOTHING_MIST.id) { this.soomTicks += 1; } } on_finished() { if (debug) { console.log(`SooM Ticks: ${this.soomTicks}`); console.log('SooM Perc Uptime: ', (this.soomTicks * 2 / this.owner.fightDuration * 1000)); console.log('SooM Buff Update: ', this.combatants.selected.getBuffUptime(SPELLS.SOOTHING_MIST.id), ' Percent: ', this.combatants.selected.getBuffUptime(SPELLS.SOOTHING_MIST.id) / this.owner.fightDuration); } } get soomTicksPerDuration() { return (this.soomTicks * 2 / this.owner.fightDuration * 1000) || 0; } get suggestionThresholds() { return { actual: this.soomTicksPerDuration, isGreaterThan: { minor: .75, average: 1, major: 1.5, }, style: 'number', }; } suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest( <Wrapper> You are allowing <SpellLink id={SPELLS.SOOTHING_MIST.id} /> to channel for an extended period of time. <SpellLink id={SPELLS.SOOTHING_MIST.id} /> does little healing, so your time is better spent DPS'ing throug the use of <SpellLink id={SPELLS.TIGER_PALM.id} /> and <SpellLink id={SPELLS.BLACKOUT_KICK.id} />. </Wrapper> ) .icon(SPELLS.SOOTHING_MIST.icon) .actual(`${this.soomTicksPerDuration.toFixed(2)} ticks per second`) .recommended(`<${recommended} ticks per second is recommended`); }); } } export default SoothingMist;
packages/material-ui-icons/src/FormatAlignRight.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let FormatAlignRight = props => <SvgIcon {...props}> <path d="M3 21h18v-2H3v2zm6-4h12v-2H9v2zm-6-4h18v-2H3v2zm6-4h12V7H9v2zM3 3v2h18V3H3z" /> </SvgIcon>; FormatAlignRight = pure(FormatAlignRight); FormatAlignRight.muiName = 'SvgIcon'; export default FormatAlignRight;
src/parser/hunter/marksmanship/modules/spells/PreciseShots.js
fyruna/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS/hunter'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import SpellIcon from 'common/SpellIcon'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import StatisticListBoxItem from 'interface/others/StatisticListBoxItem'; import SpellLink from 'common/SpellLink'; import ItemDamageDone from 'interface/others/ItemDamageDone'; /** * Aimed Shot causes your next 1-2 Arcane Shots or Multi-Shots to deal 100% more damage. */ //TODO: Add a suggestion for Aimed Shotting when Precise Shots is active + some conditionals, but wait for 8.1 for Marksmanship minor rework before doing so. const ASSUMED_PROCS = 2; //Logs give no indication whether we gain 1 or 2 stacks - we assume 2 and work from there. const PRECISE_SHOTS_MODIFIER = 0.75; const MAX_TRAVEL_TIME = 500; class PreciseShots extends Analyzer { damage = 0; buffsActive = 0; buffsGained = 0; minOverwrittenProcs = 0; maxOverwrittenProcs = 0; buffedShotInFlight = null; on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.PRECISE_SHOTS.id) { return; } this.buffsActive = ASSUMED_PROCS; } on_byPlayer_removebuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.PRECISE_SHOTS.id) { return; } this.buffsGained += 1; this.buffsActive = 0; } on_byPlayer_applybuffstack(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.PRECISE_SHOTS.id) { return; } this.minOverwrittenProcs += 1; this.maxOverwrittenProcs += 2; this.buffsActive = ASSUMED_PROCS; } on_byPlayer_removebuffstack(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.PRECISE_SHOTS.id) { return; } this.buffsGained += 1; this.buffsActive -= 1; } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (!this.selectedCombatant.hasBuff(SPELLS.PRECISE_SHOTS.id) || (spellId !== SPELLS.ARCANE_SHOT.id && spellId !== SPELLS.MULTISHOT_MM.id)) { return; } this.buffedShotInFlight = event.timestamp; } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (this.buffedShotInFlight && this.buffedShotInFlight > event.timestamp + MAX_TRAVEL_TIME) { this.buffedShotInFlight = null; } if (spellId !== SPELLS.ARCANE_SHOT.id && spellId !== SPELLS.MULTISHOT_MM.id) { return; } if (this.buffedShotInFlight && this.buffedShotInFlight < event.timestamp + MAX_TRAVEL_TIME) { this.damage += calculateEffectiveDamage(event, PRECISE_SHOTS_MODIFIER); } if (spellId === SPELLS.ARCANE_SHOT.id) { this.buffedShotInFlight = null; } } statistic() { return ( <StatisticBox position={STATISTIC_ORDER.CORE(17)} icon={<SpellIcon id={SPELLS.PRECISE_SHOTS.id} />} value={`${this.buffsGained} buffs used`} label="Precise Shots" tooltip={`You wasted between ${this.minOverwrittenProcs} and ${this.maxOverwrittenProcs} Precise Shots procs by casting Aimed Shot when you already had Precise Shots active`} /> ); } subStatistic() { return ( <StatisticListBoxItem title={<SpellLink id={SPELLS.PRECISE_SHOTS.id} />} value={<ItemDamageDone amount={this.damage} />} /> ); } } export default PreciseShots;
src/issues/IssueCard.js
easyCZ/open-sourcery
import React from 'react'; import { Button, Card, Image } from 'semantic-ui-react' import { Header } from 'semantic-ui-react' import { Icon, Label } from 'semantic-ui-react' const IssueCard = ({ img, owner, name, description, stars, language }) => ( <Card style={{ minWidth: '400px' }}> <Card.Content style={{ display: 'flex', alignItems: 'center' }}> <Image style={{ objectFit: 'cover', margin: '0 1em 0 0' }} size='tiny' floated='left' src={img} width='100px' height='100px' shape='rounded' /> <div> <Header size='medium'> <span style={{ color: 'rgba(0, 0, 0, 0.3)' }}>{owner}/</span> <span>{name}</span> </Header> <p>{description}</p> </div> </Card.Content> <Card.Content extra> { language ? <Label as='a' basic> {language}</Label> : null } <Label as='a' basic> <Icon name='star' /> {stars}</Label> </Card.Content> </Card> ); export default IssueCard
roguelike-dungeon-crawler-game/src/index.js
mstoyanovca/front-end
import React from 'react'; import ReactDOM from 'react-dom'; import './css/index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/components/App/App.js
joshwcomeau/framework.js
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; import './App.less'; import React from 'react'; import invariant from 'react/lib/invariant'; import AppActions from '../../actions/AppActions'; import NavigationMixin from './NavigationMixin'; import AppStore from '../../stores/AppStore'; import NotFoundPage from '../NotFoundPage'; import Hero from '../Hero'; import Shuffle from '../Shuffle'; var frameworkNames = ['Artichoke', 'Jeez', 'Walrus', 'Monopoly', 'Pizza', 'Fingers', 'Stringcheese', 'RedBull']; var frameworkAdjectives = ['superheroic', 'hyper-vigilant', 'fantastical', 'bewildering', 'lackadaisical', 'delightful', 'robust', 'colossal']; var frameworkDescriptions = [ "revolutionizes multi-dimensional data distribution through coaxial binding techniques, so you can do more with less.", "supercharges your development IDE by adding symbols everywhere, whether you want them or not.", "bypasses the DOM bottleneck by manipulating your users's eyeballs with 3D autostereoscopy instead.", "obediently organizes your assets into logical partitions for hassle-free asset pipelining.", "adds <marquee> tags haphazardly for maximum attention-grabbing potential. ROI+++++.", "provides cheery fortune cookie alert() popups to keep your visitors positive and engaged.", ]; var Application = React.createClass({ mixins: [NavigationMixin], propTypes: { path: React.PropTypes.string.isRequired, onSetTitle: React.PropTypes.func.isRequired, onSetMeta: React.PropTypes.func.isRequired, onPageNotFound: React.PropTypes.func.isRequired }, // Initialize with null data. On creation, we'll fetch data from the server. getInitialState: function() { return {data: { name: null, adjective: null, description: null }}; }, // Called when the component gets mounted, and when the user hits shuffle. fetchFrameworkData: function() { // Replace me with an API call to the server. this.setState({ data: { name: _.sample(frameworkNames), adjective: _.sample(frameworkAdjectives), description: _.sample(frameworkDescriptions) } }); }, componentDidMount: function() { this.fetchFrameworkData(); }, render: function() { var page = AppStore.getPage(this.props.path); invariant(page !== undefined, 'Failed to load page content.'); this.props.onSetTitle(page.title); if (page.type === 'notfound') { this.props.onPageNotFound(); return React.createElement(NotFoundPage, page); } return ( /* jshint ignore:start */ <div className="App"> <Hero data={this.state.data} /> <Shuffle shuffle={this.fetchFrameworkData} /> </div> /* jshint ignore:end */ ); } }); module.exports = Application;
src/components/Header/Moves/index.js
tasos14/reactQueens
import React from 'react'; import styled from 'styled-components'; import { useQueensContext } from 'components/App/context'; const Wrapper = styled.div` min-height: 2.5em; min-width: 5em; position: relative; background: #c0a58b; font-size: 25px; height: 25px; line-height: 47px; font-weight: 700; border-radius: 3px; color: #fff; text-align: center; @media (max-width: 470px) { align-self: flex-end; } `; const Moves = () => { const { moves } = useQueensContext(); return ( <Wrapper> <h4>Moves</h4> <h4>{moves}</h4> </Wrapper> ); }; Moves.propTypes = {}; export default Moves;
src/js/components/MovieThumbnail.js
nicholasodonnell/moonshine
import React from 'react'; import Truncate from 'react-truncate'; class MovieThumbnail extends React.Component { constructor() { super(); } componentWillMount() { } render() { const { movie } = this.props; const { genre, poster, title } = movie; return ( <a class='c-movie-thumbnail c-movie-thumbnail--loaded' href="#"> <div class="c-movie-thumbnail__header"> {poster && <img class="c-movie-thumbnail__poster" src={poster} />} </div> <div class="c-movie-thumbnail__main"> <h3 class="c-movie-thumbnail__title"> <Truncate lines={2} ellipsis={'…'}> {title} </Truncate> </h3> {genre && <h3 class="c-movie-thumbnail__genre">{genre}</h3>} </div> </a> ); } } export default MovieThumbnail;
src/pages/signup.js
guzmonne/mcp
import React from 'react' import SignupForm from '../components/signup/form.signup.js' import RowColXS12 from '../components/bootstrap/row.col-xs-12.js' import Logo from '../components/helpers/logo.helper.js' export default class Signup extends React.Component { render(){ return ( <div className="Signup"> <RowColXS12 className="text-center"> <Logo logo={this.props.location.query.client} className="Signup__logo"/> </RowColXS12> <RowColXS12> <SignupForm /> </RowColXS12> </div> ) } }
admin/client/App/elemental/ScreenReaderOnly/index.js
frontyard/keystone
import React from 'react'; import { css } from 'glamor'; function ScreenReaderOnly ({ className, ...props }) { props.className = css(classes.srOnly, className); return <span {...props} />; }; const classes = { srOnly: { border: 0, clip: 'rect(0,0,0,0)', height: 1, margin: -1, overflow: 'hidden', padding: 0, position: 'absolute', width: 1, }, }; module.exports = ScreenReaderOnly;
src/routes.js
harouf/react-redux-searchportal
import React from 'react'; import {Route} from 'react-router'; import { App, Chat, Home, Widgets, About, Login, LoginSuccess, Survey, NotFound, } from 'containers'; export default (store) => { const requireLogin = (nextState, replaceState) => { const { auth: { user }} = store.getState(); if (!user) { // oops, not logged in, so can't be here! replaceState(null, '/'); } }; return ( <Route component={App}> <Route path="/" component={Home}/> <Route path="/widgets" component={Widgets}/> <Route path="/about" component={About}/> <Route path="/login" component={Login}/> <Route onEnter={requireLogin}> <Route path="/chat" component={Chat}/> <Route path="/loginSuccess" component={LoginSuccess}/> </Route> <Route path="/survey" component={Survey}/> <Route path="*" component={NotFound} status={404} /> </Route> ); };
src/components/AboutBox.js
nm-t/STS
import React from 'react'; import InfoBox from './InfoBox'; const HowToUseBox = ({open, onRequestClose}) => ( <InfoBox title="About" open={open} onRequestClose={onRequestClose}> <h3>Background</h3> Sequential study designs are an important approach in pioneer (first-in-human) drug safety and effectiveness research. <p/> A sequential trial typically includes a number of stages, defined by a pre-specified number of individuals who are exposed to a new medication or a next higher dose-level of the medication under investigation. Depending on the number of individuals who experience a certain critical (or beneficial) event at the end of a stage, the trial is either stopped for futility or proceeds with the next stage (inclusion of further individuals and re-evaluation of pre-defined stopping criteria). <p/> If a substance (or dose) successfully passes all predefined stages of the sequential trial, the medication (or dose) is claimed to be acceptably safe and/or efficient. <p/> This application allows the visualisation of the stochastic properties of an arbitrary sequential study, helping investigators design and plan first-in-human trials whilst balancing patient safety and overall cost-effectiveness. <h3>Implementation</h3> All code is at <a href="https://github.com/nm-t/sts">https://github.com/nm-t/sts</a>. <p/> This application was initially implemented over three days for Health Hack 2015 by <b>Alex</b>, <b>Joash</b>, <b>Louis</b>, <b>Nathalia</b>, and <b>Nathan</b> for the problem owner <b>Dr. Tibor Schuster</b> of the Murdoch Childrens Research Institute, Melbourne Children's Trials Centre. <p/> The initial implementation used nvd3, d3.js, Bootstrap, AngularJS, and jstat. <p/> It was later completely reimplemented by <b>Joash</b> using React, Redux, reselect, redux-undo, nvd3, Material UI, jstat and react-number-editor. </InfoBox> ); export default HowToUseBox;
webpack/components/TemplateSyncResult/components/SyncedTemplate/EmptyInfoItem.js
theforeman/foreman_templates
import React from 'react'; import PropTypes from 'prop-types'; import InfoItem from './InfoItem'; import { itemIteratorId } from './helpers'; const EmptyInfoItem = ({ template, attr }) => ( <InfoItem itemId={itemIteratorId(template, attr)} /> ); EmptyInfoItem.propTypes = { template: PropTypes.object.isRequired, attr: PropTypes.string.isRequired, }; export default EmptyInfoItem;
src/components/ForecastNext5DayWeather/ForecastNext5DayWeather.js
Andumino/SimpleWeatherApp
import React from 'react'; import {connect} from 'react-redux'; import LoadingIndicator from 'react-loading-indicator'; class ForecastNext5DayWeather extends React.Component { getTimeStr(dt) { const options = { day: 'numeric', month: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric', hour12: false }; return (new Date(dt * 1000)).toLocaleString('ua-UA', options); } renderNextDay(list) { const today = (new Date()).getDate(); // console.log('nextDay = ', nextDay); return list.filter((day) => { const curDay = (new Date(day.dt * 1000)).getDate(); // console.log(day.dt_txt, ';', (new Date(day.dt * 1000)), ';', (curDay === nextDay)); return (curDay !== today); }).map((day) => { return ( <tr key={day.dt}> <td>{this.getTimeStr(day.dt)}</td> <td>{day.main.temp}&#8451;</td> <td>{day.main.humidity}%</td> <td>{day.wind.speed} м/с</td> <td>{day.weather[0].description}</td> </tr> ); }); } render() { const {isFetchingForecast, weather} = this.props; if (weather.error) { return ( <p>Помилка : {weather.error}</p> ); } if (!weather.forecast || isFetchingForecast) { return ( <LoadingIndicator /> ); } return ( <table> <thead> <tr> <th>Дата та час</th> <th>Температура</th> <th>Вологість</th> <th>Вітер</th> <th>Прогноз</th> </tr> </thead> <tbody> {this.renderNextDay(weather.forecast.list)} </tbody> </table> ); } } const mapStateToProps = (state) => { const {weather} = state; return { weather }; }; ForecastNext5DayWeather = connect(mapStateToProps)(ForecastNext5DayWeather); export default ForecastNext5DayWeather;
client/src/components/dashboard/Community/SocialLinks.js
no-stack-dub-sack/alumni-network
import { hoverTransition } from '../../../styles/style-utils'; import React from 'react'; import styled from 'styled-components'; export const Icon = styled.i` color: grey; ${ hoverTransition() } `; const IconLinks = ({ user, handleClick }) => { const { social } = user; return( <div> <a href={user.personal.profileUrl} onClick={handleClick} rel="noreferrer noopener" target="_blank" > <Icon className="github icon" /> </a> <a href={`https://www.freecodecamp.org/${user.username}`} onClick={handleClick} rel="noreferrer noopener" target="_blank" > <Icon className="free code camp icon" /> </a> { /* will only render the following links if user has entered info for these fields */ } { social.codepen && <a href={`https://www.codepen.io/${social.codepen}`} onClick={handleClick} rel="noreferrer noopener" target="_blank" > <Icon className="codepen icon" /> </a> } { social.linkedin && <a href={`https://www.linkedin.com/search/results/index/?keywords=${encodeURIComponent(social.linkedin)}&origin=GLOBAL_SEARCH_HEADER`} onClick={handleClick} rel="noreferrer noopener" target="_blank" > <Icon className="linkedin icon" /> </a> } { social.twitter && <a href={`https://www.twitter.com/${social.twitter}`} onClick={handleClick} rel="noreferrer noopener" target="_blank" > <Icon className="twitter icon" /> </a> } </div> ); } export default IconLinks;
index.ios.js
budasuyasa/warungapp
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class warungapp extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('warungapp', () => warungapp);
modules/react-docs/src/components/MarkdownTitle.js
Scratch-it/react-color
/* jshint node: true, esnext: true */ "use strict"; import React from 'react'; import ReactCSS from 'reactcss'; class MarkdownTitle extends ReactCSS.Component { constructor() { super(); this.state = { hover: false, }; this.handleHover = this.handleHover.bind(this); } classes() { return { 'default': { link: { opacity: '0', textDecoration: 'none', fill: this.props.primaryColor, transition: 'opacity 200ms linear', }, }, 'hovered': { link: { opacity: '1', }, }, }; } styles() { return this.css({ 'hovered': this.state.hover, }); } handleHover(e) { if (e.type === 'mouseenter') { this.setState({ hover: true }); } else if (e.type === 'mouseleave') { this.setState({ hover: false }); } } render() { var linkSvg = { __html: ` <svg style="width:24px;height:24px" viewBox="0 0 24 24"> <path d="M10.59,13.41C11,13.8 11,14.44 10.59,14.83C10.2,15.22 9.56,15.22 9.17,14.83C7.22,12.88 7.22,9.71 9.17,7.76V7.76L12.71,4.22C14.66,2.27 17.83,2.27 19.78,4.22C21.73,6.17 21.73,9.34 19.78,11.29L18.29,12.78C18.3,11.96 18.17,11.14 17.89,10.36L18.36,9.88C19.54,8.71 19.54,6.81 18.36,5.64C17.19,4.46 15.29,4.46 14.12,5.64L10.59,9.17C9.41,10.34 9.41,12.24 10.59,13.41M13.41,9.17C13.8,8.78 14.44,8.78 14.83,9.17C16.78,11.12 16.78,14.29 14.83,16.24V16.24L11.29,19.78C9.34,21.73 6.17,21.73 4.22,19.78C2.27,17.83 2.27,14.66 4.22,12.71L5.71,11.22C5.7,12.04 5.83,12.86 6.11,13.65L5.64,14.12C4.46,15.29 4.46,17.19 5.64,18.36C6.81,19.54 8.71,19.54 9.88,18.36L13.41,14.83C14.59,13.66 14.59,11.76 13.41,10.59C13,10.2 13,9.56 13.41,9.17Z" /> </svg> `, }; var title; if (this.props.isHeadline) { title = <h1>{ this.props.title } <a is="link" href={ '#' + this.props.link } dangerouslySetInnerHTML={ linkSvg } /></h1>; } else { title = <h2>{ this.props.title } <a is="link" href={ '#' + this.props.link } dangerouslySetInnerHTML={ linkSvg } /></h2>; } return ( <div onMouseEnter={ this.handleHover } onMouseLeave={ this.handleHover }> { title } </div> ); } }; export default MarkdownTitle;
src/svg-icons/maps/local-mall.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalMall = (props) => ( <SvgIcon {...props}> <path d="M19 6h-2c0-2.76-2.24-5-5-5S7 3.24 7 6H5c-1.1 0-1.99.9-1.99 2L3 20c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-7-3c1.66 0 3 1.34 3 3H9c0-1.66 1.34-3 3-3zm0 10c-2.76 0-5-2.24-5-5h2c0 1.66 1.34 3 3 3s3-1.34 3-3h2c0 2.76-2.24 5-5 5z"/> </SvgIcon> ); MapsLocalMall = pure(MapsLocalMall); MapsLocalMall.displayName = 'MapsLocalMall'; MapsLocalMall.muiName = 'SvgIcon'; export default MapsLocalMall;
src/components/subscription/subscription.js
modestack/modestack.github.io
import React from 'react'; import PropTypes from 'prop-types'; import styles from './subscription.module.scss'; import BadgeIcon from '../icons/airplane-badge'; import {SecondaryButton, SecondaryLink} from '../common/link/link'; import closeIconSVG from '../../assets/svgs/ic_close_white_24px.svg'; class Subscription extends React.Component { render() { const {removeSubscriptionBox} = this.props; return ( <div className={styles.subscription}> <div className={styles.topSection}> <span> <h3 className={styles.header}>Subscribe today</h3> <p>By subscribing to our weekly newsletter you will get the latest resources to improve user engagement of your website </p> </span> <div className={styles.badgeContainer} onClick={removeSubscriptionBox}> <img style={{ margin: '0', position: 'absolute', top: '0', right: '0', cursor: 'pointer', padding: '10px', }} src={closeIconSVG} alt=""/> <div> <BadgeIcon/> </div> </div> </div> <div className={styles.navigation}> <span> <input style={{height: '100%'}} type="text"/> </span> <span> <SecondaryButton clickHandler={this.subscribe} title="Subscribe" /> </span> </div> </div> ); } subscribe() { console.log('subscribing'); } } Subscription.propTypes = { removeSubscriptionBox: PropTypes.func }; export default Subscription;
node_modules/enzyme/src/version.js
vietvd88/developer-crawler
import React from 'react'; export const VERSION = React.version; export const REACT013 = VERSION.slice(0, 4) === '0.13'; export const REACT014 = VERSION.slice(0, 4) === '0.14'; export const REACT15 = VERSION.slice(0, 3) === '15.';
fields/types/date/DateField.js
everisARQ/keystone
import DateInput from '../../components/DateInput'; import Field from '../Field'; import moment from 'moment'; import React from 'react'; import { Button, InputGroup, FormInput } from 'elemental'; /* TODO: Implement yearRange Prop, or deprecate for max / min values (better) */ const DEFAULT_INPUT_FORMAT = 'YYYY-MM-DD'; const DEFAULT_FORMAT_STRING = 'Do MMM YYYY'; module.exports = Field.create({ displayName: 'DateField', propTypes: { formatString: React.PropTypes.string, inputFormat: React.PropTypes.string, label: React.PropTypes.string, note: React.PropTypes.string, onChange: React.PropTypes.func, path: React.PropTypes.string, value: React.PropTypes.string, }, getDefaultProps () { return { formatString: DEFAULT_FORMAT_STRING, inputFormat: DEFAULT_INPUT_FORMAT, }; }, valueChanged ({ value }) { this.props.onChange({ path: this.props.path, value: value, }); }, moment (value) { var m = moment(value); if (this.props.isUTC) m.utc(); return m; }, isValid (value) { return this.moment(value, this.inputFormat).isValid(); }, format (value) { return value ? this.moment(value).format(this.props.formatString) : ''; }, setToday () { this.valueChanged({ value: this.moment(new Date()).format(this.props.inputFormat), }); }, renderValue () { return <FormInput noedit>{this.format(this.props.value)}</FormInput>; }, renderField () { let value = this.moment(this.props.value); value = this.props.value && value.isValid() ? value.format(this.props.inputFormat) : this.props.value; return ( <InputGroup> <InputGroup.Section grow> <DateInput ref="dateInput" name={this.props.path} format={this.props.inputFormat} value={value} onChange={this.valueChanged} /> </InputGroup.Section> <InputGroup.Section> <Button onClick={this.setToday}>Today</Button> </InputGroup.Section> </InputGroup> ); }, });
src/containers/Home/Home.js
dskliarov/aotweb
import React, { Component } from 'react'; import Helmet from 'react-helmet'; import InternalCarousel from '../Carousel/Carousel'; export default class Home extends Component { render() { const styles = require('./Home.scss'); // require the logo image both from client and server return ( <div> <InternalCarousel /> <Helmet title="Home"/> <div className={styles.marketing}> <div className={'container ' + styles.marketing}> <div className="row"> <div className={'col-lg-4 ' + styles.colLg}> <img className={styles.bubble_img} src={require('./img/bubble_one.png')} alt="Generic placeholder image"/> <h3>Code Once, Run Anywhere</h3> <p> "Develop portable controls applications at a systems level using platform independent, reusable components. Develop applications across multiple devices and run-time operating systems without recompilation." </p> </div> <div className={'col-lg-4 ' + styles.colLg}> <img className={styles.bubble_img} src={require('./img/bubble_two.png')} alt="Generic placeholder image"/> <h3>Automate Testing</h3> <p> "Test entire control systems virtually using built-in automated testing capabilities. Add hardware in-the-loop testing prior to final deployment." </p> </div> <div className={'col-lg-4 ' + styles.colLg}> <img className={styles.bubble_img} src={require('./img/bubble_three.png')} alt="Generic placeholder image"/> <h3>Manage Deployment</h3> <p> "Centrally manage and remotely deploy, update, and manage real-time and non-real time controls applications across multiple devices from a centralized location. Create libraries of portable, hardware-independent, off-the-shelf applications." </p> </div> <div className="row"> <div className={'col-lg-12 ' + styles.colLg}> <p> <a className="btn btn-default" href="#" role="button">View details</a> </p> </div> </div> </div> <hr className={styles.featuretteDivider}/> <div className={'row ' + styles.featurette}> <div className="col-md-7"> <h2 className={styles.featuretteHeading}> First feature heading. <span className="text-muted"> It'll blow your mind.</span> </h2> <p className="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> </div> <div className="col-md-5"> <img className="featurette-image img-responsive center-block" data-src="holder.js/500x500/auto" alt="500x500" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iNTAwIiBoZWlnaHQ9IjUwMCIgdmlld0JveD0iMCAwIDUwMCA1MDAiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjwhLS0KU291cmNlIFVSTDogaG9sZGVyLmpzLzUwMHg1MDAvYXV0bwpDcmVhdGVkIHdpdGggSG9sZGVyLmpzIDIuNi4wLgpMZWFybiBtb3JlIGF0IGh0dHA6Ly9ob2xkZXJqcy5jb20KKGMpIDIwMTItMjAxNSBJdmFuIE1hbG9waW5za3kgLSBodHRwOi8vaW1za3kuY28KLS0+PGRlZnM+PHN0eWxlIHR5cGU9InRleHQvY3NzIj48IVtDREFUQVsjaG9sZGVyXzE1MmMyMDMwZmFiIHRleHQgeyBmaWxsOiNBQUFBQUE7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LWZhbWlseTpBcmlhbCwgSGVsdmV0aWNhLCBPcGVuIFNhbnMsIHNhbnMtc2VyaWYsIG1vbm9zcGFjZTtmb250LXNpemU6MjVwdCB9IF1dPjwvc3R5bGU+PC9kZWZzPjxnIGlkPSJob2xkZXJfMTUyYzIwMzBmYWIiPjxyZWN0IHdpZHRoPSI1MDAiIGhlaWdodD0iNTAwIiBmaWxsPSIjRUVFRUVFIi8+PGc+PHRleHQgeD0iMTg1LjEyNSIgeT0iMjYxLjEiPjUwMHg1MDA8L3RleHQ+PC9nPjwvZz48L3N2Zz4=" data-holder-rendered="true"/> </div> </div> <hr className={styles.featuretteDivider}/> <div className={'row ' + styles.featurette}> <div className="col-md-5"> <img className="featurette-image img-responsive center-block" data-src="holder.js/500x500/auto" alt="500x500" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iNTAwIiBoZWlnaHQ9IjUwMCIgdmlld0JveD0iMCAwIDUwMCA1MDAiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjwhLS0KU291cmNlIFVSTDogaG9sZGVyLmpzLzUwMHg1MDAvYXV0bwpDcmVhdGVkIHdpdGggSG9sZGVyLmpzIDIuNi4wLgpMZWFybiBtb3JlIGF0IGh0dHA6Ly9ob2xkZXJqcy5jb20KKGMpIDIwMTItMjAxNSBJdmFuIE1hbG9waW5za3kgLSBodHRwOi8vaW1za3kuY28KLS0+PGRlZnM+PHN0eWxlIHR5cGU9InRleHQvY3NzIj48IVtDREFUQVsjaG9sZGVyXzE1MmMyMDMwZmFiIHRleHQgeyBmaWxsOiNBQUFBQUE7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LWZhbWlseTpBcmlhbCwgSGVsdmV0aWNhLCBPcGVuIFNhbnMsIHNhbnMtc2VyaWYsIG1vbm9zcGFjZTtmb250LXNpemU6MjVwdCB9IF1dPjwvc3R5bGU+PC9kZWZzPjxnIGlkPSJob2xkZXJfMTUyYzIwMzBmYWIiPjxyZWN0IHdpZHRoPSI1MDAiIGhlaWdodD0iNTAwIiBmaWxsPSIjRUVFRUVFIi8+PGc+PHRleHQgeD0iMTg1LjEyNSIgeT0iMjYxLjEiPjUwMHg1MDA8L3RleHQ+PC9nPjwvZz48L3N2Zz4=" data-holder-rendered="true"/> </div> <div className="col-md-7"> <h2 className={styles.featuretteHeading}> Another feature heading. <span className="text-muted"> It'll blow your mind.</span> </h2> <p className="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> </div> </div> <hr className={styles.featuretteDivider}/> <div className={'row ' + styles.featurette}> <div className="col-md-7"> <h2 className={styles.featuretteHeading}> Last feature heading. <span className="text-muted"> It'll blow your mind.</span> </h2> <p className="lead">Donec ullamcorper nulla non metus auctor fringilla. Vestibulum id ligula porta felis euismod semper. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Fusce dapibus, tellus ac cursus commodo.</p> </div> <div className="col-md-5"> <img className="featurette-image img-responsive center-block" data-src="holder.js/500x500/auto" alt="500x500" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iNTAwIiBoZWlnaHQ9IjUwMCIgdmlld0JveD0iMCAwIDUwMCA1MDAiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjwhLS0KU291cmNlIFVSTDogaG9sZGVyLmpzLzUwMHg1MDAvYXV0bwpDcmVhdGVkIHdpdGggSG9sZGVyLmpzIDIuNi4wLgpMZWFybiBtb3JlIGF0IGh0dHA6Ly9ob2xkZXJqcy5jb20KKGMpIDIwMTItMjAxNSBJdmFuIE1hbG9waW5za3kgLSBodHRwOi8vaW1za3kuY28KLS0+PGRlZnM+PHN0eWxlIHR5cGU9InRleHQvY3NzIj48IVtDREFUQVsjaG9sZGVyXzE1MmMyMDMwZmFiIHRleHQgeyBmaWxsOiNBQUFBQUE7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LWZhbWlseTpBcmlhbCwgSGVsdmV0aWNhLCBPcGVuIFNhbnMsIHNhbnMtc2VyaWYsIG1vbm9zcGFjZTtmb250LXNpemU6MjVwdCB9IF1dPjwvc3R5bGU+PC9kZWZzPjxnIGlkPSJob2xkZXJfMTUyYzIwMzBmYWIiPjxyZWN0IHdpZHRoPSI1MDAiIGhlaWdodD0iNTAwIiBmaWxsPSIjRUVFRUVFIi8+PGc+PHRleHQgeD0iMTg1LjEyNSIgeT0iMjYxLjEiPjUwMHg1MDA8L3RleHQ+PC9nPjwvZz48L3N2Zz4=" data-holder-rendered="true"/> </div> </div> <hr className={styles.featuretteDivider}/> </div> </div> </div> ); } }
src/components/SearchResults.js
kmcarter/karaoke-song-lister
import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as types from '../constants/searchTypes'; import * as appActions from '../actions/appActions'; import * as searchActions from '../actions/searchActions'; import Pagination from './common/Pagination'; import SongTitleList from './common/SongTitleList'; import SongApi from '../api/songApi'; class SearchResults extends React.Component { constructor(props) { super(props); this.getSearchData = this.getSearchData.bind(this); this.getPaginatedData = this.getPaginatedData.bind(this); this.onPageChange = this.onPageChange.bind(this); this.onPerPageChange = this.onPerPageChange.bind(this); this.state = { page: 0 }; } componentWillMount() { if (!this.props.searchCache.hasOwnProperty(this.props.searchTerm)) { this.getSearchData(); } } getSearchData(page = 0, perPage = this.props.resultsPerPage) { const thisComp = this; const searchTerm = this.props.searchTerm; this.props.appActions.loading(true); const search = getSongApiCall(thisComp.props.searchType); search(searchTerm, page, perPage).then(response => { saveSearchResults(thisComp.props, { searchTerm, response: response.data }); thisComp.props.appActions.loading(false); }).catch(error => { throw (error); }); } getPaginatedData(lookup) { if (!lookup || lookup.pagination.count == 0) { return []; } const pageInfo = lookup.pagination; if (pageInfo.count <= this.props.resultsPerPage) { return lookup.results; } const startIndex = this.state.page * this.props.resultsPerPage; const endIndex = startIndex + this.props.resultsPerPage; const filteredResults = lookup.results.filter(val => { return val.Index >= startIndex && val.Index < endIndex; }); if (filteredResults.length == 0) { this.getSearchData(this.state.page); } return filteredResults; } onPageChange(e, newPage) { this.setState({ page: newPage }); } onPerPageChange(e, newPerPage) { this.props.searchActions.invalidateCache(); this.props.appActions.setResultsPerPage(newPerPage); this.getSearchData(this.state.page, newPerPage); } render() { const lookup = this.props.searchCache[this.props.searchTerm]; const data = this.getPaginatedData(lookup); const count = lookup ? lookup.pagination.count : data.length; if (count == 0) { return <p className="alert alert-warning" role="alert">No results found.</p>; } return ( <div> <Pagination count={count} page={this.state.page} perPage={this.props.resultsPerPage} onClick={this.onPageChange} onPerPageChange={this.onPerPageChange} /> <SongTitleList data={data} /> <Pagination count={count} page={this.state.page} perPage={this.props.resultsPerPage} onClick={this.onPageChange} onPerPageChange={this.onPerPageChange} /> </div> ); } } SearchResults.propTypes = { appActions: PropTypes.object.isRequired, searchActions: PropTypes.object.isRequired, searchCache: PropTypes.object, searchTerm: PropTypes.string.isRequired, searchType: PropTypes.oneOf(types.TYPES).isRequired, resultsPerPage: PropTypes.number.isRequired }; function getResultsCache(state, type) { switch (type) { case types.TYPE_SEARCH: return state.search; case types.TYPE_ARTIST: return state.artist; case types.TYPE_TITLE: return state.title; default: throw("Invalid search type passed to SearchResults component."); } } function saveSearchResults(props, data) { switch (props.searchType) { case types.TYPE_SEARCH: props.searchActions.saveSearchResults(data); break; case types.TYPE_ARTIST: props.searchActions.saveArtistResults(data); break; case types.TYPE_TITLE: props.searchActions.saveTitleResults(data); break; default: throw("Invalid search type passed to SearchResults component."); } } function getSongApiCall(type) { switch (type) { case types.TYPE_SEARCH: return SongApi.searchSongs; case types.TYPE_ARTIST: return SongApi.lookupSongsByArtist; case types.TYPE_TITLE: return SongApi.lookupSongsByTitle; default: throw("Invalid search type passed to SearchResults component."); } } function mapStateToProps(state, ownProps) { return { searchCache: getResultsCache(state.searchCache, ownProps.searchType), resultsPerPage: state.app.resultsPerPage }; } function mapDispatchToProps(dispatch) { return { appActions: bindActionCreators(appActions, dispatch), searchActions: bindActionCreators(searchActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(SearchResults);
client/src/pages/account/AccountSettingForm.js
ccwukong/lfcommerce-react
import React from 'react'; import { Formik, Form } from 'formik'; import * as Yup from 'yup'; import { FormattedMessage } from 'react-intl'; import { Col, Row, FormGroup, Label, Card, CardHeader, CardBody, Input, Button, } from 'reactstrap'; import { MdSave } from 'react-icons/md'; const accountSettingValidation = Yup.object().shape({ name: Yup.string().required('Required'), email: Yup.string().required('Required'), contactNo: Yup.string().required('Required'), }); const AccountSettingForm = props => { return ( <Formik enableReinitialize onSubmit={(values, { setSubmitting }) => { setSubmitting(true); this.onSubmit(values); setSubmitting(false); }} validationSchema={accountSettingValidation} > {({ values: { name = '', email = '', contactNo = '' }, handleChange, isSubmitting, errors, }) => ( <Form> <Row> <Col sm="12"> <Button type="submit" size="sm" color="primary" className="pull-right" disabled={isSubmitting} > <MdSave /> &nbsp; <FormattedMessage id="sys.save" /> </Button> <br /> <br /> </Col> </Row> <Row> <Col md={6}> <Card> <CardHeader> <FormattedMessage id="sys.basicInfo" /> </CardHeader> <CardBody> <FormGroup row> <Label for="name" sm={3}> <FormattedMessage id="sys.name" /> <span className="text-danger mandatory-field">*</span> </Label> <Col sm={9}> <Input name="name" id="name" value={name} onChange={handleChange} /> {errors.name && ( <div className="text-danger">{errors.name}</div> )} </Col> </FormGroup> <FormGroup row> <Label for="email" sm={3}> <FormattedMessage id="sys.email" /> <span className="text-danger mandatory-field">*</span> </Label> <Col sm={9}> <Input name="email" id="email" value={email} onChange={handleChange} readOnly /> {errors.email && ( <div className="text-danger">{errors.email}</div> )} </Col> </FormGroup> <FormGroup row> <Label for="contact-no" sm={3}> <FormattedMessage id="sys.contactNo" /> </Label> <Col sm={9}> <Input name="contactNo" id="contact-no" value={contactNo} onChange={handleChange} readOnly /> </Col> </FormGroup> </CardBody> </Card> </Col> </Row> </Form> )} </Formik> ); }; export default AccountSettingForm;
src/js/components/icons/base/SocialAmazon.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-social-amazon`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'social-amazon'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="#F90" fillRule="evenodd" d="M11.9924596,23.9397465 C8.83711397,23.9185077 6.03567124,22.8789612 3.53203329,20.9850151 C2.63838806,20.3088366 1.82646601,19.5437784 1.08564773,18.7032301 C1.0593301,18.6732188 1.01408224,18.6445926 1.01108111,18.6122727 C0.999538287,18.4963828 1.00253942,18.3793386 1,18.2627561 C1.10019169,18.278916 1.21815932,18.2662189 1.29780479,18.3156222 C1.96751928,18.7327798 2.61183957,19.1935692 3.29817573,19.5802537 C5.2872347,20.7005999 7.41480753,21.4266434 9.67581537,21.7720046 C10.8557226,21.9520726 12.0409395,22.0114027 13.2256946,21.9426075 C15.4894728,21.8114811 17.6530592,21.2481914 19.7120677,20.2936001 C20.0373444,20.1428508 20.3561571,19.9780193 20.6756624,19.8152656 C20.8303362,19.7363127 20.9829323,19.7039928 21.1142896,19.8425066 C21.2530343,19.9886387 21.247032,20.165013 21.1503032,20.3279977 C21.0948977,20.4217254 21.0106351,20.5020634 20.9279885,20.5757066 C19.0869085,22.2092467 16.9334797,23.2123179 14.5316495,23.6788787 C13.7001046,23.8404782 12.8480135,23.8958838 12.0051567,24 C12.0010013,23.9799155 11.996615,23.959831 11.9924596,23.9397465 M20.882048,18.8454608 C20.4263375,18.8890927 19.9207619,18.9387268 19.4149554,18.9848981 C19.3041444,18.9950558 19.1914864,19.0015197 19.0806753,18.9948249 C18.9532426,18.9872066 18.9329272,18.9087155 19.0026459,18.8159112 C19.0442,18.7605056 19.1065313,18.718028 19.1653996,18.6783207 C19.7005248,18.3191081 20.3062921,18.1618949 20.9339907,18.0787866 C21.5298312,17.9998337 22.124979,18.0183022 22.7074298,18.1743612 C23.1005783,18.2796317 23.186226,18.3269573 23.1569073,18.7845147 C23.0793395,19.9902778 22.691039,21.086615 21.8167857,21.9673322 C21.7719996,22.0125801 21.7297528,22.0707559 21.6743473,22.0926873 C21.6004732,22.1217752 21.5148255,22.1213135 21.4342566,22.1335489 C21.4361035,22.0601365 21.4208669,21.9809528 21.4427983,21.9142353 C21.6512617,21.2800727 21.8689593,20.6489112 22.0762683,20.0145177 C22.1178225,19.8873158 22.1335207,19.750418 22.1494498,19.6165213 C22.2002382,19.1887443 22.0291736,18.9735861 21.575079,18.9070995 C21.3631528,18.8761647 21.1479946,18.8683156 20.882048,18.8454608 M13.9965473,9.42010077 C13.1377614,9.41525279 12.3166051,9.45242067 11.5310007,9.71582785 C11.142931,9.84603088 10.7495517,10.0110932 10.4155024,10.2426422 C9.49276931,10.8818837 9.25267863,11.8334739 9.32863039,12.8935666 C9.36879941,13.4550094 9.53755546,13.9746672 9.95171189,14.381898 C10.5401649,14.9604242 11.5307698,15.0363759 12.3260702,14.5663522 C13.0193321,14.1565821 13.4325651,13.5242663 13.7008203,12.7873726 C14.0960465,11.7021166 13.9716148,10.5713818 13.9965473,9.42010077 M14.6290939,15.7725771 C14.3204389,16.0535293 14.0353312,16.3183217 13.744683,16.5768809 C12.627107,17.5707178 11.3066083,18.0146547 9.82427914,18.0444352 C9.01951364,18.0605951 8.22929209,17.9998799 7.47600757,17.7023059 C6.13427002,17.1720287 5.2787161,16.1915815 4.93173889,14.8002098 C4.5009608,13.0722494 4.64640035,11.4084672 5.66886346,9.89797358 C6.4246874,8.7815519 7.51779258,8.11783967 8.77988467,7.71153236 C9.86283216,7.36293915 10.983871,7.2101122 12.1092961,7.08406459 C12.726837,7.01480766 13.3450705,6.953169 13.9928536,6.88506635 C13.9734617,6.11169732 14.0833494,5.33578887 13.8116313,4.5880449 C13.5708481,3.92571782 13.0622714,3.58520459 12.3976357,3.43283935 C11.3913326,3.20221378 10.250671,3.57758633 9.70977435,4.37103986 C9.52624349,4.64044931 9.41404727,4.9684963 9.31547158,5.28407703 C9.17649601,5.72870651 8.97195721,5.87345349 8.51024436,5.81850966 C7.60782659,5.71162313 6.70333111,5.62297427 5.80091334,5.51747288 C5.35328272,5.46483761 5.17575413,5.20997212 5.26301786,4.77503861 C5.65986006,2.79567561 6.80629307,1.4123839 8.67207471,0.684262729 C10.8742142,-0.174984891 13.1252952,-0.241702398 15.3569843,0.578992199 C17.2063751,1.25909523 18.2221434,2.61445331 18.3574252,4.59243118 C18.402904,5.26006796 18.4093679,5.9311676 18.4121382,6.60088209 C18.4192948,8.33299786 18.4276056,10.0651136 18.4093679,11.7969985 C18.3992103,12.7615167 18.6667729,13.6175323 19.2531482,14.3791277 C19.3939706,14.5624277 19.5366399,14.7461894 19.6559926,14.9433408 C19.8538366,15.2702335 19.8009705,15.5181733 19.5149394,15.7649588 C18.7780456,16.4007374 18.0425371,17.0383629 17.3074902,17.67645 C16.9027989,18.0275826 16.6223083,18.0227347 16.2153085,17.6799129 C15.679029,17.2281268 15.2385549,16.6964645 14.8583344,16.1110126 C14.7890775,16.0043569 14.715896,15.9002407 14.6290939,15.7725771" stroke="none"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'SocialAmazon'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/packages/@ncigdc/routes/RepositoryRoute.js
NCI-GDC/portal-ui
/* @flow */ /* eslint fp/no-class:0 */ import React from 'react'; import Relay from 'react-relay/classic'; import { connect } from 'react-redux'; import { parse } from 'query-string'; import { handleStateChange } from '@ncigdc/dux/relayProgress'; import RepositoryPage from '@ncigdc/containers/RepositoryPage'; import { parseIntParam, parseFilterParam, parseJSONParam, } from '@ncigdc/utils/uri'; import { viewerQuery } from './queries'; class RepositoryRoute extends Relay.Route { static routeName = 'RepositoryRoute'; static queries = viewerQuery; static prepareParams = ({ location: { search } }) => { const q = parse(search); return { cases_offset: parseIntParam(q.cases_offset, 0), cases_size: parseIntParam(q.cases_size, 20), cases_sort: parseJSONParam(q.cases_sort, null), files_offset: parseIntParam(q.files_offset, 0), files_size: parseIntParam(q.files_size, 20), files_sort: parseJSONParam(q.files_sort, null), filters: parseFilterParam(q.filters, null), }; }; } export default connect()((props: mixed) => ( <Relay.Renderer Container={RepositoryPage} queryConfig={new RepositoryRoute(props)} environment={Relay.Store} onReadyStateChange={handleStateChange(props)} /> ));
src/components/common/svg-icons/editor/vertical-align-bottom.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorVerticalAlignBottom = (props) => ( <SvgIcon {...props}> <path d="M16 13h-3V3h-2v10H8l4 4 4-4zM4 19v2h16v-2H4z"/> </SvgIcon> ); EditorVerticalAlignBottom = pure(EditorVerticalAlignBottom); EditorVerticalAlignBottom.displayName = 'EditorVerticalAlignBottom'; EditorVerticalAlignBottom.muiName = 'SvgIcon'; export default EditorVerticalAlignBottom;
src/client/components/comments/CommentWrapper.component.js
DBCDK/content-first
import React from 'react'; import {connect} from 'react-redux'; import ProfileImage from '../general/ProfileImage.component'; import { UPDATE_COMMENT, TOGGLE_EDIT_COMMENT, DELETE_COMMENT, FETCH_COMMENTS } from '../../redux/comment.reducer'; import Spinner from '../general/Spinner/Spinner.component'; import {timestampToLongDate} from '../../utils/dateTimeFormat'; import CommentInput from './CommentInput.component'; import Text from '../base/Text'; import T from '../base/T'; import ContextMenu, {ContextMenuAction} from '../base/ContextMenu'; export class CommentWrapper extends React.Component { constructor(props) { super(props); this.state = { editing: false, comment: this.props.comment.comment }; } toggleEdit = value => { if (this.props.onChange) { this.props.onChange(); } this.setState({editing: value}); }; editComment = () => { this.props.editComment({ ...this.props.comment, comment: this.state.comment }); this.toggleEdit(false); }; onChange = value => { this.setState({comment: value}); if (this.props.onChange) { this.props.onChange(); } }; updateComments = () => { if (this.props.fetchComments && this.props.comment._key) { this.props.fetchComments(this.props.comment._key); } }; render() { const { comment, user, _id, saving, error, _created = Date.now() / 1000 } = this.props.comment; const isSmallScreen = window.innerWidth < 768; return ( <div key={_id} className="comment-wrapper"> {saving ? ( <div className="comment-saving"> <Spinner size="30px" /> </div> ) : ( '' )} {this.props.user && this.props.user.openplatformId === user.openplatformId && (!isSmallScreen || !this.state.editing) && ( <ContextMenu className="comment-wrapper-context-menu"> <ContextMenuAction title={T({component: 'post', name: 'editComment'})} // icon="edit" onClick={() => { this.toggleEdit(!this.state.editing); this.updateComments(); }} /> <ContextMenuAction title={T({component: 'post', name: 'deleteComment'})} icon="delete" onClick={() => { this.props.deleteComment(this.props.comment); }} /> </ContextMenu> )} <div className="d-flex align-items-center mb-3 w-100"> <div style={{flexGrow: 1}}> {this.state.editing ? ( <CommentInput editing={this.state.editing} autoFocus={true} user={this.props.user} value={this.state.comment} onSubmit={this.editComment} onCancel={() => this.toggleEdit(false)} onDelete={() => this.props.deleteComment(this.props.comment)} onChange={this.onChange} disabled={saving} error={error || null} /> ) : ( <div className="comment d-flex"> <ProfileImage id={user.openplatformId} style={{marginRight: '15px', marginTop: '10px'}} size="40" /> <div className="d-flex flex-column w-100"> <Text type="small" variant="color-due" className="mb-1"> {timestampToLongDate(_created)} </Text> <div className="comment-nameComment-wrap"> <Text type="large" className="d-inline"> {user.name || ''} </Text> <div className="d-inline ml-2">{comment}</div> </div> </div> </div> )} </div> </div> </div> ); } } const mapStateToProps = state => ({ user: state.userReducer }); export const mapDispatchToProps = dispatch => ({ editComment: comment => dispatch({type: UPDATE_COMMENT, comment}), deleteComment: comment => dispatch({type: DELETE_COMMENT, comment}), toggleEdit: ({comment, editing}) => dispatch({type: TOGGLE_EDIT_COMMENT, comment, editing}), fetchComments: id => dispatch({type: FETCH_COMMENTS, id}) }); export default connect(mapStateToProps, mapDispatchToProps)(CommentWrapper);
src/components/TeamItem.js
mariovalney/mariovalney-app
import React from 'react'; import PropTypes from 'prop-types'; import { StyleSheet, Text, Image, TouchableOpacity, } from 'react-native'; import { withNavigation } from 'react-navigation'; const styles = StyleSheet.create({ flag: { borderWidth: 1, borderColor: '#c7c6c6', flex: 1, height: 22, width: 32, }, item: { flex: 3, paddingLeft: 10, }, itemContainer: { alignItems: 'center', backgroundColor: '#fff', flex: 1, flexDirection: 'row', marginBottom: 10, marginRight: 10, paddingLeft: 10, paddingRight: 10, paddingVertical: 10, }, }); const TeamItem = ({ item, navigation }) => { const goToDetails = teamCode => navigation.navigate('TeamDetails', { teamCode }); return ( <TouchableOpacity onPress={() => goToDetails(item.code)} style={styles.itemContainer}> <Image style={styles.flag} source={{ uri: item.flag }} /> <Text style={styles.item}>{item.name}</Text> </TouchableOpacity> ); }; TeamItem.propTypes = { item: PropTypes.shape({ flag: PropTypes.string, name: PropTypes.string, code: PropTypes.string, }).isRequired, navigation: PropTypes.shape({ navigate: PropTypes.func, }), }; TeamItem.defaultProps = { navigation: undefined, }; export default withNavigation(TeamItem);
src/components/Weui/cell/cells_title.js
ynu/res-track-wxe
/* eslint-disable */ import React from 'react'; import classNames from 'classnames'; export default class CellsTitle extends React.Component { render() { const {className, children, ...others} = this.props; const cls = classNames({ 'weui-cells__title': true, [className]: className }); return ( <div className={cls} {...others}>{children}</div> ); } };
app/static/src/diagnostic/TestTypeResultForm_modules/VisualTestForm.js
SnowBeaver/Vision
import React from 'react'; import Form from 'react-bootstrap/lib/Form'; import Panel from 'react-bootstrap/lib/Panel'; import Button from 'react-bootstrap/lib/Button'; import FormControl from 'react-bootstrap/lib/FormControl'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import ControlLabel from 'react-bootstrap/lib/ControlLabel'; import Checkbox from 'react-bootstrap/lib/Checkbox'; import HelpBlock from 'react-bootstrap/lib/HelpBlock'; import {NotificationContainer, NotificationManager} from 'react-notifications'; var SelectField = React.createClass({ handleChange: function(event, index, value){ this.setState({ value: event.target.value }); }, getInitialState: function () { return { items: [], isVisible: false, value: -1 }; }, isVisible: function(){ return this.state.isVisible; }, componentDidMount: function(){ var source = '/api/v1.0/' + this.props.source + '/'; this.serverRequest = $.authorizedGet(source, function (result){ this.setState({ items: (result['result']) }); }.bind(this), 'json'); }, componentWillUnmount: function() { this.serverRequest.abort(); }, setVisible: function(){ this.state.isVisible = true; }, render: function() { var label = (this.props.label != null) ? this.props.label: ""; var name = (this.props.name != null) ? this.props.name: ""; var value = (this.props.value != null) ? this.props.value: ""; var validationState = (this.props.errors[name]) ? 'error' : null; var error = this.props.errors[name]; var menuItems = []; for (var key in this.state.items) { menuItems.push(<option key={this.state.items[key].id} value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>); } return ( <FormGroup validationState={validationState}> <ControlLabel>{label}</ControlLabel> <FormControl componentClass="select" onChange={this.handleChange} name={name} value={value} > {menuItems} </FormControl> <HelpBlock className="warning">{error}</HelpBlock> </FormGroup> ); } }); const TextField = React.createClass({ render: function() { var label = (this.props.label != null) ? this.props.label: ""; var name = (this.props.name != null) ? this.props.name: ""; var value = (this.props.value != null) ? this.props.value: ""; var type = (this.props["data-type"] != null) ? this.props["data-type"]: undefined; var len = (this.props["data-len"] != null) ? this.props["data-len"]: undefined; var validationState = (this.props.errors[name]) ? 'error' : null; var error = this.props.errors[name]; return ( <FormGroup validationState={validationState}> <ControlLabel>{label}</ControlLabel> <FormControl type="text" placeholder={label} name={name} value={value} data-type={type} data-len={len} /> <HelpBlock className="warning">{error}</HelpBlock> <FormControl.Feedback /> </FormGroup> ); } }); const CheckBox = React.createClass({ render: function () { var name = (this.props.name != null) ? this.props.name: ""; var checked = (this.props.value != null) ? this.props.value: false; var is_checked = (checked) ? 'checked': ''; return ( <Checkbox checked={is_checked} name={name}> <span className="glyphicon glyphicon-menu-left"> </span> </Checkbox> ); } }); var VisualTestForm = React.createClass({ getInitialState: function () { return { loading: false, errors: {}, fields: ["tank_cover_gasket_id", "tank_pressure_unit_id", "tank_pressure", "tank_manhole_gasket_id", "tank_overpressure_valve_id", "tank_gas_relay_id", "tank_sampling_valve_id", "tank_oil_level_id", "tank_oil_pump_id", "tank_winding_temp_max", "tank_winding_temp_actual", "tank_gas_analyser", "tank_oil_temp_max", "tank_oil_temp_actual", "tank_overall_condition_id", "tank_oil_flag", "tank_winding_flag", "misc_foundation_id", "misc_temp_ambiant", "misc_load", "grounding_value", "grounding_connection_id", "tap_changer_gasket_id", "tap_changer_overpressure_valve_id", "tap_changer_oil_level_id", "tap_changer_sampling_valve_id", "tap_changer_operation_counter", "tap_changer_temp_max", "tap_changer_temp_actual", "tap_changer_counter_id", "tap_changer_pressure_unit_id", "tap_changer_pressure_max", "tap_changer_pressure_actual", "tap_changer_filter_id", "tap_changer_tap_position", "tap_changer_overall_condition_id", "exp_tank_pipe_gasket_id", "exp_tank_oil_level_id", "exp_tank_paint_id", "exp_tank_overall_condition_id", "radiator_fan_id", "radiator_gasket_id", "radiator_overall_condition_id", "control_cab_connection_id", "control_cab_heating_id", "control_cab_overall_condition_id", "bushing_gasket_id", "bushing_oil_level_id", "bushing_overall_condition_id", "notes" ] } }, componentDidMount: function () { var source = '/api/v1.0/' + this.props.tableName + '/?test_result_id=' + this.props.testResultId; this.serverRequest = $.authorizedGet(source, function (result) { var res = (result['result']); if (res.length > 0) { var fields = this.state.fields; fields.push('id'); var data = res[0]; var state = {}; for (var i = 0; i < fields.length; i++) { var key = fields[i]; if (data.hasOwnProperty(key)) { state[key] = data[key]; } } this.setState(state); } }.bind(this), 'json'); }, _create: function () { var fields = this.state.fields; var data = {test_result_id: this.props.testResultId}; var url = '/api/v1.0/' + this.props.tableName + '/'; for (var i = 0; i < fields.length; i++) { var key = fields[i]; data[key] = this.state[key]; } if ('id' in this.state) { url += this.state['id']; delete data.id; } return $.authorizedAjax({ url: url, type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), beforeSend: function () { this.setState({loading: true}); }.bind(this) }) }, _onSubmit: function (e) { e.preventDefault(); // Do not propagate the submit event of the main form e.stopPropagation(); if (!this.is_valid()){ NotificationManager.error('Please correct the errors'); e.stopPropagation(); return false; } var xhr = this._create(); xhr.done(this._onSuccess) .fail(this._onError) .always(this.hideLoading) }, hideLoading: function () { this.setState({loading: false}); }, _onSuccess: function (data) { // this.setState(this.getInitialState()); NotificationManager.success('Test values have been saved successfully.'); if ($.isNumeric(data.result)) { this.setState({id: data.result}); } }, _onError: function (data) { var message = "Failed to create"; var res = data.responseJSON; if (res.message) { message = data.responseJSON.message; } if (res.error) { // We get list of errors if (data.status >= 500) { message = res.error.join(". "); } else if (res.error instanceof Object){ // We get object of errors with field names as key for (var field in res.error) { var errorMessage = res.error[field]; if (Array.isArray(errorMessage)) { errorMessage = errorMessage.join(". "); } res.error[field] = errorMessage; } this.setState({ errors: res.error }); } else { message = res.error; } } NotificationManager.error(message); }, _onChange: function (e) { var state = {}; state[e.target.name] = $.trim(e.target.value); var errors = this._validate(e); state = this._updateFieldErrors(e.target.name, state, errors); this.setState(state); }, _validate: function (e) { var errors = []; var error; error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type")); if (error){ errors.push(error); } error = this._validateFieldLength(e.target.value, e.target.getAttribute("data-len")); if (error){ errors.push(error); } return errors; }, _validateFieldType: function (value, type){ var error = ""; if (type != undefined && value){ var typePatterns = { "float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/, "int": /^(-|\+)?(0|[1-9]\d*)$/ }; if (!typePatterns[type].test(value)){ error = "Invalid " + type + " value"; } } return error; }, _validateFieldLength: function (value, length){ var error = ""; if (value && length){ if (value.length > length){ error = "Value should be maximum " + length + " characters long" } } return error; }, _updateFieldErrors: function (fieldName, state, errors){ // Clear existing errors related to the current field as it has been edited state.errors = this.state.errors; delete state.errors[fieldName]; // Update errors with new ones, if present if (Object.keys(errors).length){ state.errors[fieldName] = errors.join(". "); } return state; }, is_valid: function () { return (Object.keys(this.state.errors).length <= 0); }, render: function() { return ( <div className="col-md-12"> <h3>Visual inspection</h3> <form method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}> <div className="tab_row text-center"> <div className="row"> <div className="col-md-8 "> <div className="row"> <div > <Panel header="Tank"> </Panel> </div> </div> <div className="row"> <div className="col-md-6 "> <SelectField name="tank_cover_gasket_id" source="gasket_condition" label="Cover gasket" value={this.state.tank_cover_gasket_id} errors={this.state.errors}/> </div> <div className="col-md-2"> <b>Pressure</b> </div> <div className="col-md-2"> <SelectField name="tank_pressure_unit_id" source="pressure_unit" label="" value={this.state.tank_pressure_unit_id} errors={this.state.errors}/> </div> <div className="col-md-2"> <TextField name="tank_pressure" label="" value={this.state.tank_pressure} data-type="float" errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-6 "> <SelectField name="tank_manhole_gasket_id" source="gasket_condition" label="Manhole gasket" value={this.state.tank_manhole_gasket_id} errors={this.state.errors}/> </div> <div className="col-md-6 "> <SelectField name="tank_overpressure_valve_id" source="valve_condition" label="Sud.Pres.Valve" value={this.state.tank_overpressure_valve_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-6 "> <SelectField name="tank_gas_relay_id" source="gas_relay" label="Gas relay" value={this.state.tank_gas_relay_id} errors={this.state.errors}/> </div> <div className="col-md-6 "> <SelectField name="tank_sampling_valve_id" source="valve_condition" label="Sampling Valves" value={this.state.tank_sampling_valve_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-6 "> <SelectField name="tank_oil_level_id" source="fluid_level" label="Oil level" value={this.state.tank_oil_level_id} errors={this.state.errors}/> </div> <div className="col-md-6 "> <SelectField name="tank_oil_pump_id" source="pump_condition" label="Oil Pump" value={this.state.tank_oil_pump_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-2"><b>Winding Temp.</b></div> <div className="col-md-2"> <TextField name="tank_winding_temp_max" label="Max" value={this.state.tank_winding_temp_max} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <TextField name="tank_winding_temp_actual" label="Actual" value={this.state.tank_winding_temp_actual} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <b>Ctc</b><CheckBox name="tank_winding_flag" value={this.state.tank_winding_flag}/> </div> <div className="col-md-3 nopadding"> <TextField name="tank_gas_analyser" label="Diss. Gas Analyzer" value={this.state.tank_gas_analyser} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-1 nopadding"> <b>ppm</b> </div> </div> <div className="row"> <div className="col-md-2"><b>Oil Temp.</b></div> <div className="col-md-2"> <TextField name="tank_oil_temp_max" label="Max" value={this.state.tank_oil_temp_max} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <TextField name="tank_oil_temp_actual" label="Actual" value={this.state.tank_oil_temp_actual} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <b>Ctc</b><CheckBox name="tank_oil_flag" value={this.state.tank_oil_flag}/> </div> <div className="col-md-4"> <SelectField name="tank_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.tank_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> <div className="col-md-4 "> <div className="row"> <div className="col-md-11 col-md-offset-1"> <Panel header="Miscelaneous"> </Panel> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="misc_foundation_id" source="foundation_condition" label="Foundation" value={this.state.misc_foundation_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <TextField name="misc_temp_ambiant" label="Ambient temp.(C)" value={this.state.misc_temp_ambiant} errors={this.state.errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <TextField name="misc_load" label="Load(MVA)" value={this.state.misc_load} errors={this.state.errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <Panel header="Grounding"> </Panel> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <TextField name="grounding_value" label="Value" value={this.state.grounding_value} errors={this.state.errors} data-type="float"/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="grounding_connection_id" source="connection_condition" label="Connection" value={this.state.grounding_connection_id} errors={this.state.errors}/> </div> </div> </div> </div> <div className="row"> <div className="col-md-8 "> <div className="row"> <div > <Panel header="Tap Charger"> </Panel> </div> </div> <div className="row"> <div className="col-md-6"> <SelectField name="tap_changer_gasket_id" source="gasket_condition" label="Gasket" value={this.state.tap_changer_gasket_id} errors={this.state.errors}/> </div> <div className="col-md-6 "> <SelectField name="tap_changer_overpressure_valve_id" source="valve_condition" label="Sud Pres. Valve" value={this.state.tap_changer_overpressure_valve_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-6 "> <SelectField name="tap_changer_oil_level_id" source="fluid_level" label="Oil Level" value={this.state.tap_changer_oil_level_id} errors={this.state.errors}/> </div> <div className="col-md-6 "> <SelectField name="tap_changer_sampling_valve_id" source="valve_condition" label="Sampling Valves" value={this.state.tap_changer_sampling_valve_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-6 col-md-offset-6"> <TextField name="tap_changer_operation_counter" label="No. of Operations" value={this.state.tap_changer_operation_counter} errors={this.state.errors} data-type="int"/> </div> </div> <div className="row"> <div className="col-md-2"><b>Temperature(C)</b></div> <div className="col-md-2 col-md-offset-2"> <TextField name="tap_changer_temp_max" label="Max" value={this.state.tap_changer_temp_max} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <TextField name="tap_changer_temp_actual" label="Actual" value={this.state.tap_changer_temp_actual} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-4 "> <SelectField name="tap_changer_counter_id" source="tap_counter_status" label="Counter" value={this.state.tap_changer_counter_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-2"><b>Pressure</b></div> <div className="col-md-2 "> <SelectField name="tap_changer_pressure_unit_id" source="pressure_unit" label="Counter" value={this.state.tap_changer_pressure_unit_id} errors={this.state.errors}/> </div> <div className="col-md-2"> <TextField name="tap_changer_pressure_max" label="Max" value={this.state.tap_changer_pressure_max} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-2"> <TextField name="tap_changer_pressure_actual" label="Actual" value={this.state.tap_changer_pressure_actual} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-4"> <SelectField name="tap_changer_filter_id" source="tap_filter_condition" label="Filter" value={this.state.tap_changer_filter_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-2"><b>Position of NLTC</b></div> <div className="col-md-2 col-md-offset-4"> <TextField name="tap_changer_tap_position" label="Actual" value={this.state.tap_changer_tap_position} errors={this.state.errors} data-type="float"/> </div> <div className="col-md-4"> <SelectField name="tap_changer_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.tap_changer_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> <div className="col-md-4 "> <div className="row"> <div className="col-md-11 col-md-offset-1"> <Panel header="Expansion Conservation Tank"> </Panel> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="exp_tank_pipe_gasket_id" source="gasket_condition" label="Pipe Tightness" value={this.state.exp_tank_pipe_gasket_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="exp_tank_oil_level_id" source="fluid_level" label="Oil Level" value={this.state.exp_tank_oil_level_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="exp_tank_paint_id" source="paint_types" label="Silica Gel Breather" value={this.state.exp_tank_paint_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-11 col-md-offset-1"> <SelectField name="exp_tank_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.exp_tank_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> </div> <div className="row"> <div className="col-md-4"> <div className="row"> <div className="col-md-12 "> <Panel header="Radiator"> </Panel> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="radiator_fan_id" source="fan_condition" label="Fan" value={this.state.radiator_fan_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="radiator_gasket_id" source="gasket_condition" label="Gasket" value={this.state.radiator_gasket_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="radiator_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.radiator_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> <div className="col-md-4"> <div className="row"> <div className="col-md-12 "> <Panel header="Control Cabinet"> </Panel> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="control_cab_connection_id" source="connection_condition" label="Connection" value={this.state.control_cab_connection_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="control_cab_heating_id" source="heating_condition" label="Heating" value={this.state.control_cab_heating_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="control_cab_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.control_cab_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> <div className="col-md-4"> <div className="row"> <div className="col-md-12 "> <Panel header="Bushing+arrester"> </Panel> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="bushing_gasket_id" source="gasket_condition" label="Gasket" value={this.state.bushing_gasket_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="bushing_oil_level_id" source="fluid_level" label="Oil Level" value={this.state.bushing_oil_level_id} errors={this.state.errors}/> </div> </div> <div className="row"> <div className="col-md-12 "> <SelectField name="bushing_overall_condition_id" source="overall_condition" label="Overall Condition" value={this.state.bushing_overall_condition_id} errors={this.state.errors}/> </div> </div> </div> </div> <div className="row"> <div className="col-md-12"> <FormGroup validationState={this.state.errors.notes ? 'error' : null}> <FormControl componentClass="textarea" placeholder="Notes" multiple name="notes" value={this.state.notes} data-len="1000"/> <HelpBlock className="warning">{this.state.errors.notes}</HelpBlock> <FormControl.Feedback /> </FormGroup> </div> </div> </div> <div className="row"> <div className="col-md-12 "> <Button bsStyle="success" className="pull-right" type="submit">Save</Button> &nbsp; <Button bsStyle="danger" className="pull-right margin-right-xs" onClick={this.props.handleClose} >Cancel</Button> </div> </div> </form> </div> ); } }); export default VisualTestForm;
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js
MattSPalmer/react-router
import React from 'react'; import { Link } from 'react-router'; export default class AnnouncementsSidebar extends React.Component { render () { var announcements = COURSES[this.props.params.courseId].announcements; return ( <div> <h3>Sidebar Assignments</h3> <ul> {announcements.map(announcement => ( <li key={announcement.id}> <Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}> {announcement.title} </Link> </li> ))} </ul> </div> ); } }
packages/bonde-admin/src/pages/admin/mobilizations/widgets/container.js
ourcities/rebu-client
import React from 'react' import { connect } from 'react-redux' import { Route } from 'react-router-dom' // Components import { Loading } from '@/components/await' // Redux import { selectWidget } from '@/mobrender/redux/action-creators' import MobSelectors from '@/mobrender/redux/selectors' // Pages import Donation from './donation' import Form from './form' import Pressure from './pressure' const stateToProps = state => ({ widget: MobSelectors(state).getWidget() }) const actionsToProps = { select: selectWidget } export default connect(stateToProps, actionsToProps)(class extends React.Component { componentDidMount () { const { widget, select, match: { params: { widget_id: id } } } = this.props if (!widget && id) { return Promise.all([select(id)]) } } render () { const { match: { path }, widget } = this.props return !widget ? <Loading /> : ( <React.Fragment> <Route path={`${path}/donation`} component={Donation} /> <Route path={`${path}/form`} component={Form} /> <Route path={`${path}/pressure`} component={Pressure} /> </React.Fragment> ) } })
src/components/button/index.js
rangle/react-redux-starter
import React from 'react'; import classNames from 'classnames'; function Button({ children, className, type = 'button', onClick, ...props }) { const buttonClasses = classNames('btn', 'btn-primary', className); return ( <button type={ type } className={ buttonClasses } onClick={ onClick } {...props}> { children } </button> ); } Button.propTypes = { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, type: React.PropTypes.oneOf(['button', 'submit', 'reset']), onClick: React.PropTypes.func, }; export default Button;
src/react/BaseApp.js
laundree/laundree
// @flow import React from 'react' import { Switch, Route } from 'react-router' import Support from './Support' import StateCheckRedirectRoute from './StateCheckRedirectRoute' import NotFound from './NotFound' import LeftNav from './LeftNav' import UserSettings from './UserSettings' import Home from './Home' import LandingPage from './LandingPage' import type { User, State } from 'laundree-sdk/lib/redux' import TopNav from './TopNav' import { connect } from 'react-redux' import LaundryAdder from './LaundryAdder' import { Meta } from './intl' type BaseAppProps = { children?: *, user: ?User } const BaseApp = (props: BaseAppProps) => { return ( <div> <Meta title={'document-title.base'} description={'meta.description'} /> {props.user ? <LaundryAdder /> : null} <Route component={TopNav} /> { props.user ? ( <Switch> <Route exact path={'/'} component={Home} /> <StateCheckRedirectRoute test={({currentUser}) => Boolean(currentUser)} path={'/support'} redirectTo={'/'} component={Support} /> <StateCheckRedirectRoute test={({currentUser}) => Boolean(currentUser)} path={'/laundries/:laundryId'} redirectTo={'/auth'} component={LeftNav} /> <StateCheckRedirectRoute test={({currentUser}) => Boolean(currentUser)} path={'/users/:userId/settings'} redirectTo={'/auth'} component={UserSettings} /> <Route component={NotFound} /> </Switch> ) : ( <LandingPage /> ) } </div>) } export default connect(({users, currentUser}: State): BaseAppProps => ({ user: (currentUser && users[currentUser]) || null }))(BaseApp)
src/js/routes.js
7sleepwalker/addicted-to-mnt
import React from 'react'; // import propTypes from "prop-types"; import { Switch, Route, BrowserRouter } from 'react-router-dom'; import HomePage from './Containers/HomePage'; import Error404 from './Containers/error404'; import App from './Containers/App'; import About from './Containers/About'; import Gallery from './Containers/Gallery'; import TripPlaner from './Containers/TripPlaner'; import Dashboard from './_Dashboard/DashboardLogIn'; import DashboardPanel from './_Dashboard/DashboardPanel'; export const Routes = (store) => { const authRequired = (state) => { const user = store.store.getState().dashboard.user; if (!user) { return true; } else { state.history.push('/404'); } // user ? ( // return <Redirect to={state.match.path} /> ; // ) : ( // return <Redirect to="/404" />; // ); }; return ( <BrowserRouter> <Switch> <Route path="/Dashboard" exact component={Dashboard} /> <Route path="/Dashboard/Panel" render={(props) => {authRequired(props); return <DashboardPanel />;}} /> <Route path="/" exact render={(props) => <HomePage />} /> <Route path="/404" render={(props) => <Error404 />} /> <Route path="/App" render={(props) => <App />} /> <Route path="/About" render={(props) => <About />} /> <Route path="/tripPlaner" render={(props) => <TripPlaner />} /> <Route path="/BlogGallery/:id" render={(props) => <Gallery match={props.match}/> } /> </Switch> </BrowserRouter> ); } // // Routes.contextTypes = { // router: propTypes.object // };
src/svg-icons/action/note-add.js
andrejunges/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;