path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
scripts/pages/TrainingDetail.js
zupzup/reactgym
'use strict'; import React from 'react'; import TrainingStore from '../stores/TrainingStore.js'; import _ from 'lodash'; import SimpleHeaderMixin from '../mixins/SimpleHeaderMixin'; let TrainingDetail = React.createClass({ header: { title: 'Detail' }, mixins: [React.addons.PureRenderMixin, SimpleHeaderMixin], contextTypes: { router: React.PropTypes.func.isRequired }, getInitialState() { return {}; }, render() { let training = TrainingStore.getTrainingForId(this.context.router.getCurrentQuery().training); if (training) { let exercises = training.getIn(['workout', 'exercises']); training = training.toJS(); let sets = _.map(training.sets, (set, exercise) => { let innerSets = set.map((item, idx) => { return (<div className='set' key={idx}><span className='count'>#{idx + 1}</span> <span className='repsweight'>Reps: {item.reps} / Weight: {item.weight}</span></div>); }); return ( <div className='exercise' key={exercise}> <div><strong>{exercises.find(e => e.get('id') == exercise).get('label')}</strong></div> <div>{innerSets}</div> </div>); }); return ( <div className='page trainingdetail'> <h2>{training.workout.label}</h2> <div className='date'><i className='ion-calendar'> </i> {new Date(training.dateStart).toLocaleString()}</div> <div className='duration'><i className='ion-android-time'> </i> {this.formatMinutes(training.dateStart, training.dateEnd)} minutes</div> {sets} </div> ); } else { return ( <div className='page trainingdetail'> invalid Id </div> ); } }, formatMinutes(from, to) { return Math.floor((new Date(to) - new Date(from)) / 1000 / 60); } }); module.exports = TrainingDetail;
src/components/comment_box.js
manjarb/ReduxSimpleStarter
import React, { Component } from 'react'; import { connect } from 'react-redux' import * as actions from '../actions' class CommentBox extends Component { constructor() { super() this.state = { comment: '' } } handleChange(event) { this.setState({comment: event.target.value}) } handleSubmit(event) { event.preventDefault() this.props.saveComment(this.state.comment) this.setState({ comment: '' }) } render() { return ( <form onSubmit={this.handleSubmit.bind(this)} className="comment-box"> <h4>Add a comment</h4> <textarea value={this.state.comment} onChange={this.handleChange.bind(this)}/> <div> <button action="submit">Submit Comment</button> </div> </form> ); } } export default connect(null,actions)(CommentBox)
website/core/WebPlayer.js
DanielMSchmidt/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule WebPlayer */ 'use strict'; var Prism = require('Prism'); var React = require('React'); var WEB_PLAYER_VERSION = '1.2.6'; /** * Use the WebPlayer by including a ```ReactNativeWebPlayer``` block in markdown. * * Optionally, include url parameters directly after the block's language. For * the complete list of url parameters, see: https://github.com/dabbott/react-native-web-player * * E.g. * ```ReactNativeWebPlayer?platform=android * import React from 'react'; * import { AppRegistry, Text } from 'react-native'; * * const App = () => <Text>Hello World!</Text>; * * AppRegistry.registerComponent('MyApp', () => App); * ``` */ var WebPlayer = React.createClass({ parseParams: function(paramString) { var params = {}; if (paramString) { var pairs = paramString.split('&'); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); params[pair[0]] = pair[1]; } } return params; }, render: function() { var hash = `#code=${encodeURIComponent(this.props.children)}`; if (this.props.params) { hash += `&${this.props.params}`; } return ( <div className={'web-player'}> <Prism>{this.props.children}</Prism> <iframe style={{marginTop: 4}} width="880" height={this.parseParams(this.props.params).platform === 'android' ? '425' : '420'} data-src={`//cdn.rawgit.com/dabbott/react-native-web-player/gh-v${WEB_PLAYER_VERSION}/index.html${hash}`} frameBorder="0" /> </div> ); }, }); module.exports = WebPlayer;
src/index.android.js
pabloalonsos/react-cross-platform
/** * 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 react_cross_platform 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.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('react_cross_platform', () => react_cross_platform);
index.js
intrepion/blog-spa-reactjs
import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import App from './containers/App' import configureStore from './store/configureStore' const store = configureStore() render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
src/routes/AboutMe/components/AboutMe.js
larsdolvik/portfolio
import React from 'react' // import DuckImage from '../assets/Duck.jpg' import './AboutMe.scss' export const AboutMe = () => ( <div> <h3>About me</h3> <div className="pageContainer"> <p> Ipsum is unattractive, both inside and out. I fully understand why it’s former users left it for something else. They made a good decision. I think the only card she has is the Lorem card. An 'extremely credible source' has called my office and told me that Lorem Ipsum's birth certificate is a fraud. I'm speaking with myself, number one, because I have a very good brain and I've said a lot of things. I will write some great placeholder text – and nobody writes better placeholder text than me, believe me – and I’ll write it very inexpensively. I will write some great, great text on your website’s Southern border, and I will make Google pay for that text. Mark my words. We have so many things that we have to do better... and certainly ipsum is one of them. Ipsum is the single greatest threat. We are not - we are not keeping up with other websites. My text is long and beautiful, as, it has been well documented, are various other parts of my website. An ‘extremely credible source’ has called my office and told me that Barack Obama’s placeholder text is a fraud. placeholder text is gonna be HUGE. An 'extremely credible source' has called my office and told me that Lorem Ipsum's birth certificate is a fraud. We are going to make placeholder text great again. Greater than ever before. concept of Lorem Ipsum was created by and for the Chinese in order to make U.S. design jobs non-competitive. You're telling the enemy exactly what you're going to do. No wonder you've been fighting Lorem Ipsum your entire adult life. I’m the best thing that ever happened to placeholder text. My placeholder text, I think, is going to end up being very good with women. The best taco bowls are made in Trump Tower Grill. I love Hispanics! </p> </div> {/* <img alt='This is a duck, because Redux!' className='duck' src={DuckImage} /> */} </div> ) export default AboutMe
examples/counter/index.js
nickhudkins/redux
import React from 'react'; import Root from './containers/Root'; React.render( <Root />, document.getElementById('root') );
src/muiThemeable.js
gobadiah/material-ui
import React from 'react'; import DefaultRawTheme from './styles/raw-themes/light-raw-theme'; import ThemeManager from './styles/theme-manager'; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function muiThemeable(WrappedComponent) { const MuiComponent = (props, {muiTheme = ThemeManager.getMuiTheme(DefaultRawTheme)}) => { return <WrappedComponent {...props} muiTheme={muiTheme} />; }; MuiComponent.displayName = getDisplayName(WrappedComponent); MuiComponent.contextTypes = { muiTheme: React.PropTypes.object, }; MuiComponent.childContextTypes = { muiTheme: React.PropTypes.object, }; return MuiComponent; }
jenkins-design-language/src/js/components/material-ui/svg-icons/image/view-compact.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageViewCompact = (props) => ( <SvgIcon {...props}> <path d="M3 19h6v-7H3v7zm7 0h12v-7H10v7zM3 5v6h19V5H3z"/> </SvgIcon> ); ImageViewCompact.displayName = 'ImageViewCompact'; ImageViewCompact.muiName = 'SvgIcon'; export default ImageViewCompact;
src/hot.dev.js
gaearon/react-hot-loader
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import hoistNonReactStatic from 'hoist-non-react-statics'; import { getComponentDisplayName } from './internal/reactUtils'; import configuration from './configuration'; import AppContainer from './AppContainer.dev'; import reactHotLoader from './reactHotLoader'; import { isOpened as isModuleOpened, hotModule, getLastModuleOpened } from './global/modules'; import logger from './logger'; import { clearExceptions, logException } from './errorReporter'; import { createQueue } from './utils/runQueue'; import { enterHotUpdate, getHotGeneration, increment } from './global/generation'; /* eslint-disable camelcase, no-undef */ const requireIndirect = typeof __webpack_require__ !== 'undefined' ? __webpack_require__ : require; /* eslint-enable */ const chargeFailbackTimer = id => setTimeout(() => { const error = `hot update failed for module "${id}". Last file processed: "${getLastModuleOpened()}".`; logger.error(error); logException({ toString: () => error, }); // 100 ms more "code" tolerant that 0, and would catch error in any case }, 100); const clearFailbackTimer = timerId => clearTimeout(timerId); const createHoc = (SourceComponent, TargetComponent) => { hoistNonReactStatic(TargetComponent, SourceComponent); TargetComponent.displayName = `HotExported${getComponentDisplayName(SourceComponent)}`; return TargetComponent; }; const runInRequireQueue = createQueue(); const runInRenderQueue = createQueue(cb => { if (ReactDOM.unstable_batchedUpdates) { ReactDOM.unstable_batchedUpdates(cb); } else { cb(); } }); const makeHotExport = (sourceModule, moduleId) => { const updateInstances = possibleError => { if (possibleError && possibleError instanceof Error) { console.error(possibleError); return; } const module = hotModule(moduleId); const deepUpdate = () => { // force flush all updates runInRenderQueue(() => { enterHotUpdate(); const gen = getHotGeneration(); module.instances.forEach(inst => inst.forceUpdate()); if (configuration.trackTailUpdates) { let runLimit = 0; const checkTailUpdates = () => { setTimeout(() => { if (getHotGeneration() !== gen) { // we know that some components were updated, but not tracking which ones // even if their updates might be incorporated automatically (like lazy) // we dont know which one should be tracked, and which updates are important logger.warn( 'React-Hot-Loader: some components were updated out-of-bound. Updating your app to reconcile the changes.', ); // increment generator for cache-busting existing tree increment(); deepUpdate(); } else if (++runLimit < 5) { checkTailUpdates(); } }, 16); }; checkTailUpdates(); } }); }; // require all modules runInRequireQueue(() => { try { // webpack will require everything by this time // but let's double check... requireIndirect(moduleId); } catch (e) { console.error('React-Hot-Loader: error detected while loading', moduleId); console.error(e); } }).then(deepUpdate); }; if (sourceModule.hot) { // Mark as self-accepted for Webpack (callback is an Error Handler) // Update instances for Parcel (callback is an Accept Handler) sourceModule.hot.accept(updateInstances); // Webpack way if (sourceModule.hot.addStatusHandler) { if (sourceModule.hot.status() === 'idle') { sourceModule.hot.addStatusHandler(status => { if (status === 'apply') { clearExceptions(); updateInstances(); } }); } } } else { logger.warn('React-hot-loader: Hot Module Replacement is not enabled'); } }; const hot = sourceModule => { if (!sourceModule) { // this is fatal throw new Error('React-hot-loader: `hot` was called without any argument provided'); } const moduleId = sourceModule.id || sourceModule.i || sourceModule.filename; if (!moduleId) { console.error('`module` provided', sourceModule); throw new Error('React-hot-loader: `hot` could not find the `name` of the the `module` you have provided'); } const module = hotModule(moduleId); makeHotExport(sourceModule, moduleId); clearExceptions(); const failbackTimer = chargeFailbackTimer(moduleId); let firstHotRegistered = false; // TODO: Ensure that all exports from this file are react components. return (WrappedComponent, props) => { clearFailbackTimer(failbackTimer); // register proxy for wrapped component // only one hot per file would use this registration if (!firstHotRegistered) { firstHotRegistered = true; reactHotLoader.register(WrappedComponent, getComponentDisplayName(WrappedComponent), `RHL${moduleId}`); } return createHoc( WrappedComponent, class ExportedComponent extends Component { componentDidMount() { module.instances.push(this); } componentWillUnmount() { if (isModuleOpened(sourceModule)) { const componentName = getComponentDisplayName(WrappedComponent); logger.error( `React-hot-loader: Detected AppContainer unmount on module '${moduleId}' update.\n` + `Did you use "hot(${componentName})" and "ReactDOM.render()" in the same file?\n` + `"hot(${componentName})" shall only be used as export.\n` + `Please refer to "Getting Started" (https://github.com/gaearon/react-hot-loader/).`, ); } module.instances = module.instances.filter(a => a !== this); } render() { return ( <AppContainer {...props}> <WrappedComponent {...this.props} /> </AppContainer> ); } }, ); }; }; reactHotLoader.register(AppContainer, 'AppContainer', 'hot-dev'); export default hot;
src/components/ParallaxBackground/index.js
r1cebank/react-native-boilerplate
/* eslint-disable import/no-unresolved */ import React from 'react'; import { Animated, View, Image, Dimensions } from 'react-native'; import Styles from './resources/styles'; import resolveAssetSource from 'resolveAssetSource'; const HEIGHT = Dimensions.get('window').height > 600 ? 200 : 150; const SCREEN_WIDTH = Dimensions.get('window').width; class ParallaxBackground extends React.Component { static propTypes = { backgroundShift: React.PropTypes.number, minHeight: React.PropTypes.number, maxHeight: React.PropTypes.number, offset: React.PropTypes.object, backgroundColor: React.PropTypes.string, backgroundImage: React.PropTypes.number, children: React.PropTypes.element }; constructor(props) { super(props); this.state = { shift: new Animated.Value(props.backgroundShift || 0) }; } componentDidUpdate(prevProps) { if (prevProps.backgroundShift !== this.props.backgroundShift) { Animated.timing(this.state.shift, { toValue: this.props.backgroundShift, duration: 300 }).start(); } } render() { const { minHeight, maxHeight, offset, backgroundColor } = this.props; const buffer = 10; // To reduce visual lag when scrolling const height = offset.interpolate({ inputRange: [0, maxHeight - minHeight], outputRange: [maxHeight + buffer, minHeight + buffer], extrapolateRight: 'clamp' }); return ( <Animated.View style={[Styles.container, { height, backgroundColor }]}> {this.renderBackgroundImage()} {this.renderContent()} </Animated.View> ); } renderBackgroundImage() { const { backgroundImage, minHeight, maxHeight, offset } = this.props; if (!backgroundImage) { return null; } const source = resolveAssetSource(backgroundImage); if (!source) { return null; } const { width } = source; const translateX = this.state.shift.interpolate({ inputRange: [0, 1], outputRange: [0, SCREEN_WIDTH - width], extrapolate: 'clamp' }); const length = maxHeight - minHeight; const translateY = offset.interpolate({ inputRange: [0, length / 2, length], outputRange: [0, -length / 2, -length / 1.5], extrapolate: 'clamp' }); // Sometimes image width is smaller than device's width const initialScale = Math.max(SCREEN_WIDTH / width * 2 - 1, 1); const scale = offset.interpolate({ inputRange: [-length, 0], outputRange: [2, initialScale], extrapolateRight: 'clamp' }); const transforms = { transform: [{ translateX }, { translateY }, { scale }] }; return ( <Animated.Image source={backgroundImage} style={transforms} /> ); } renderContent() { if (React.Children.count(this.props.children) === 0) { return null; } const content = React.Children.only(this.props.children); const { minHeight, maxHeight, offset } = this.props; const length = maxHeight - minHeight; const opacity = offset.interpolate({ inputRange: [0, length - 40], outputRange: [1, 0], extrapolate: 'clamp' }); const translateY = offset.interpolate({ inputRange: [0, length], outputRange: [-32, -(length / 2) - 32], extrapolate: 'clamp' }); const transforms = { opacity, transform: [{ translateY }] }; return ( <Animated.View style={[Styles.contentContainer, transforms]}> {content} </Animated.View> ); } } // TODO: Remove this magic numbers ParallaxBackground.HEIGHT = HEIGHT; module.exports = ParallaxBackground;
kitchen-sink/react/src/app.js
AdrianV/Framework7
import React from 'react'; import ReactDOM from 'react-dom/cjs/react-dom.production.min'; import Framework7 from 'framework7/framework7.esm.bundle'; import Framework7React from 'framework7-react'; import App from './app.jsx'; Framework7.use(Framework7React); // Mount React App ReactDOM.render( React.createElement(App), document.getElementById('app'), );
src/mixins/color-mixin.js
WaldoJeffers/react-dc
import React from 'react' import {withProps} from '../utils' const {arrayOf, func, number, string} = React.PropTypes export default withProps({ colorAccessor: func, colorDomain: arrayOf(string), colors: func, // TO DO : shape a scale linearColors: arrayOf(number), ordinalColors: arrayOf(string) })
front/reducers/index.js
bigkangtheory/wanderly
import React from 'react'; import { combineReducers } from 'redux'; import { routerReducer } from 'react-router-redux'; //import reducers here: import mapReducer from './map-reducer'; import itineraryReducer from './itinerary-reducer'; import destinationReducer from './destination-reducer'; import profileReducer from './profile-reducer'; import userReducer from './user-reducer'; const allReducers = combineReducers({ //Upon import, reducers should go below: destinationReducer, mapReducer, itineraryReducer, profileReducer, routing: routerReducer, userReducer }); export default allReducers;
client/src/components/Title.js
StereoPT/TwitterAI
import React from 'react'; export default function Title({ title }) { return ( <div className="row"> <div className="col-12 mx-auto my-2"> <h1 className="text-capitalize font-weight-bold">{ title }</h1> </div> </div> ); }
src/Video/Video.js
brz0/chart-suite
import React from 'react'; import Modal from 'react-modal'; // Svg import Play from './play.svg'; import Close from './close.svg'; import chartsHome from './chartshome.svg'; import VideoPhotoPath from './videobg.jpg'; const VideoPhoto = {backgroundImage: 'url(' + VideoPhotoPath + ')'} const customStyles = { overlay: { backgroundColor: 'rgba(23, 29, 28, 0.7)' }, content: { top: '50%', left: '50%', right: 'auto', bottom: 'auto', marginRight: '-50%', transform: 'translate(-50%, -50%)', width: '100%', maxWidth: '700px', background: 'transparent', border: 'none' } }; class Video extends React.Component { constructor() { super(); this.state = { modalIsOpen: false, }; this.openModal = this.openModal.bind(this); this.afterOpenModal = this.afterOpenModal.bind(this); this.closeModal = this.closeModal.bind(this); } openModal() { this.setState({ modalIsOpen: true }); } afterOpenModal() {} closeModal() { this.setState({ modalIsOpen: false }); } render() { return ( <div className="root"> <img src={chartsHome} className="chartsHome" alt="Charts" /> <div className="videoWrap" style={VideoPhoto}><a name="intro"></a> <div className="videoInner"> <button className="playBtn" onClick={this.openModal}> <img src={Play} className="play" alt="Play Video" /> <div>See How it Works</div> </button> <Modal isOpen={this.state.modalIsOpen} onAfterOpen={this.afterOpenModal} onRequestClose={this.closeModal} style={customStyles} contentLabel="Video" > <img src={Close} className="closeBtn" onClick={this.closeModal} alt="Close Video" /> <div> <div className="embedContainer"> <iframe src='https://www.youtube.com/embed/VFEWd_Gdifw' frameBorder='0' allowFullScreen></iframe> </div> </div> </Modal> </div> </div> </div> ); } } export default Video;
e2e-tests/production-runtime/src/pages/paths.js
ChristopherBiscardi/gatsby
import { Router } from '@reach/router' import React from 'react' const App = () => <h1>App Page</h1> const NotFound = () => <h1>Not Found in App</h1> const AppPage = () => ( <Router> <App path="/paths/app" /> <NotFound default /> </Router> ) export default AppPage
examples/huge-apps/routes/Profile/components/Profile.js
ThibWeb/react-router
import React from 'react'; class Profile extends React.Component { render () { return ( <div> <h2>Profile</h2> </div> ); } } export default Profile;
form/RangeField.js
ExtPoint/yii2-frontend
import React from 'react'; import PropTypes from 'prop-types'; import _get from 'lodash-es/get'; import {types, view} from 'components'; export default class RangeField extends React.Component { static propTypes = { metaItem: PropTypes.object.isRequired, input: PropTypes.shape({ name: PropTypes.string, value: PropTypes.any, onChange: PropTypes.func, }), component: PropTypes.func, attributesMap: PropTypes.object, fromProps: PropTypes.object, toProps: PropTypes.object, }; constructor() { super(...arguments); this.renderField = this.renderField.bind(this); } render() { const {fromProps, toProps, attributesMap, labelProps, errorProps, hintProps, ...props} = this.props; const RangeFieldView = this.props.view || view.getFormView('RangeFieldView'); return ( <RangeFieldView {...props} labelProps={labelProps} errorProps={errorProps} hintProps={hintProps} fromProps={{ attribute: this.props.attribute, input: _get(this.props, attributesMap[this.props.attribute]).input, ...props, ...fromProps, }} toProps={{ attribute: this.props.metaItem.refAttribute, input: _get(this.props, attributesMap[this.props.metaItem.refAttribute]).input, ...props, ...toProps, }} renderField={this.renderField} /> ); } renderField(props) { // Get input field config const fieldConfig = types.getFieldConfig(this.props.metaItem.subAppType); // Get input component const FieldCompoent = this.props.component || types.getFieldComponent(fieldConfig.component || 'StringField'); delete fieldConfig.component; return ( <FieldCompoent {...props} {...fieldConfig} layout='inline' /> ); } }
js/components/taskEdit/tabComments.js
bsusta/HelpdeskAppTemplate
import React, { Component } from 'react'; import { Input, Label, Button, Icon, Item, Footer, FooterTab, Thumbnail, Container, Content, Card, CardItem, Text, ListItem, List, Left, Body, Right } from 'native-base'; import { Actions } from 'react-native-router-flux'; import styles from './styles'; import { ActivityIndicator } from 'react-native'; import { addedCommentsSubscription } from './taskEdit.gquery'; import I18n from '../../translations/'; class TabComments extends Component { // eslint-disable-line constructor(props){ super(props); } componentWillMount(){ this.props.subscribeToMore({ document: addedCommentsSubscription, updateQuery: () => { this.props.refetch(); return; }, }); } render() { // eslint-disable-line if(this.props.loading){ return (<ActivityIndicator animating size={ 'large' } color='#007299' />); } return ( <Container> <Content padder style={{ marginTop: 0 }}> <List dataArray={this.props.allComments} renderRow={data => <ListItem avatar> <Left> <Thumbnail/> </Left> <Body> <Text note>{data.user?data.user.firstName:'Nikto'}</Text> <Text>{data.content}</Text> </Body> <Right> <Text note>{data.createdAt}</Text> </Right> </ListItem> } > </List> <Button block primary style={styles.mb15} onPress={this.props.getMore}> <Text>Load more...</Text> </Button> </Content> <Footer> <FooterTab> <Button onPress={()=>{Actions.commentAdd({id:this.props.id})}} iconLeft style={{ flexDirection: 'row', borderColor: 'white', borderWidth: 0.5 }}> <Icon active style={{ color: 'white' }} name="md-add" /> <Text style={{ color: 'white' }} >{I18n.t('taskEditComment')}</Text> </Button> </FooterTab> </Footer> </Container> ); } } export default TabComments;
definitions/npm/react-i18next_v1.10.x/test_react-i18next_v1.10.x.js
mkscrg/flow-typed
// @flow import React from 'react' import { loadNamespaces, translate, I18nextProvider, Interpolate, } from 'react-i18next' import type { TFunction, Translator } from 'react-i18next' const i18n = { loadNamespaces: () => {} }; <I18nextProvider i18n={ i18n } children={ <div /> } />; // $ExpectError - missing children prop <I18nextProvider i18n={ i18n } />; // $ExpectError - missing i18n prop <I18nextProvider children={ <div /> } />; // passing loadNamespaces({ components: [], i18n }); loadNamespaces({ components: [() => <div />], i18n }); // $ExpectError - too few arguments loadNamespaces(); // $ExpectError - wrong type loadNamespaces(''); // $ExpectError - wrong component type loadNamespaces({ components: [{}], i18n }); type OwnProps = { s: string }; type Props = OwnProps & { t: TFunction }; const Comp = ({ s, t }: Props) => ( <div prop1={ t('') } prop2={ ' ' + s } /> ); class ClassComp extends React.Component { props: Props; render() { const { s, t } = this.props; return <div prop={ t('') } />; } } // $ExpectError - wrong argument type const FlowErrorComp = ({ s, t }: Props) => ( <div prop1={ t('', '') } // misuse of t() prop2={ ' ' + s } /> ); class FlowErrorClassComp extends React.Component { props: Props; render() { // $ExpectError - wrong argument type const { s, t } = this.props; return <div prop={ t({}) } />; // misuse of t() } } // $ExpectError - too few arguments translate(); // $ExpectError - wrong argument type translate({}); const translator: Translator<OwnProps, Props> = translate(''); const WrappedStatelessComp = translator(Comp); // passing <WrappedStatelessComp s="" />; // $ExpectError - missing prop "s" <WrappedStatelessComp />; // $ExpectError - wrong type <WrappedStatelessComp s={ 1 } />; const WrappedClassComp = translator(ClassComp); // passing <WrappedClassComp s="" />; // $ExpectError - missing prop "s" <WrappedClassComp />; // $ExpectError - wrong type <WrappedClassComp s={ 1 } />; // passing <Interpolate />; <Interpolate children={ <div /> } className="string" />; // $ExpectError - className prop wrong type <Interpolate className={ null } />; // $ExpectError - children prop wrong type <Interpolate children={ {} } />;
src/Checkbox.js
react-mdl/react-mdl
import React from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import classNames from 'classnames'; import mdlUpgrade from './utils/mdlUpgrade'; const propTypes = { checked: PropTypes.bool, className: PropTypes.string, disabled: PropTypes.bool, label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]), onChange: PropTypes.func, ripple: PropTypes.bool }; class Checkbox extends React.Component { componentDidUpdate(prevProps) { if (this.props.disabled !== prevProps.disabled) { const fnName = this.props.disabled ? 'disable' : 'enable'; findDOMNode(this).MaterialCheckbox[fnName](); } if (this.props.checked !== prevProps.checked) { const fnName = this.props.checked ? 'check' : 'uncheck'; findDOMNode(this).MaterialCheckbox[fnName](); } } render() { const { className, label, ripple, ...inputProps } = this.props; const classes = classNames('mdl-checkbox mdl-js-checkbox', { 'mdl-js-ripple-effect': ripple }, className); return ( <label className={classes}> <input type="checkbox" className="mdl-checkbox__input" { ...inputProps } /> {label && <span className="mdl-checkbox__label">{label}</span>} </label> ); } } Checkbox.propTypes = propTypes; export default mdlUpgrade(Checkbox, true);
app/containers/LanguageProvider/index.js
Dattaya/react-boilerplate-object
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: PropTypes.string, messages: PropTypes.object, children: PropTypes.element.isRequired, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); export default connect(mapStateToProps)(LanguageProvider);
src/components/views/open-account-progress-view.js
HuangXingBin/goldenEast
import React from 'react'; import { Table,Button } from 'antd'; import { Link } from 'react-router'; const OpenAccountProgressTable = React.createClass({ getColumns(){ var tableTitleChange = this.props.tableTitleChange == 0 ? '提交资料时间' : '注册时间'; const columns = [{ title: '姓名', dataIndex: 'user_name', key: 'user_name', render(text, row, index) { var firstName = !row.wechat_avatar ? text.slice(0,1) : ''; return ( <div className="user-avatar-bar"> <span className="user-avatar" style={{backgroundImage:'url('+ row.wechat_avatar +')'}}> {firstName} </span> <div className="user-avatar-bar-text"> <p className="name">{text}</p> </div> </div> ); }, }, { title: '手机号码', dataIndex: 'cellphone', key: 'cellphone', }, { title: '账号', dataIndex: 'account_status', key: 'account_status', render(text,row,index) { const styles = { display: 'linline-block', padding: '4px 8px', background: '#FF5B5B', borderRadius: '4px', color: '#fff', } if(text == 0 || text == 1){ return (<span style={styles}>{row.type_name}未开户</span>) }else{ return <span>{row.account}</span> } }, }, { title: tableTitleChange, dataIndex: 'update_time', key: 'update_time', }]; return columns; }, onChange(page){ this.props.onPageChange(page) }, render(){ const columns = this.getColumns(); const pagination = { defaultPageSize : 12, onChange : this.onChange, total : this.props.total, current : parseInt(this.props.currentPage) }; return( <Table pagination={pagination} size="middle" columns={columns} dataSource={this.props.dataSource} bordered loading={this.props.loading} /> ) } }); export default OpenAccountProgressTable;
node_modules/react-bootstrap/es/Grid.js
rblin081/drafting-client
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import elementType from 'prop-types-extra/lib/elementType'; import { bsClass, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * Turn any fixed-width grid layout into a full-width layout by this property. * * Adds `container-fluid` class. */ fluid: PropTypes.bool, /** * You can use a custom element for this component */ componentClass: elementType }; var defaultProps = { componentClass: 'div', fluid: false }; var Grid = function (_React$Component) { _inherits(Grid, _React$Component); function Grid() { _classCallCheck(this, Grid); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Grid.prototype.render = function render() { var _props = this.props, fluid = _props.fluid, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['fluid', 'componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = prefix(bsProps, fluid && 'fluid'); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Grid; }(React.Component); Grid.propTypes = propTypes; Grid.defaultProps = defaultProps; export default bsClass('container', Grid);
admin/client/views/home.js
qwales1/keystone
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import { Container } from 'elemental'; import xhr from 'xhr'; import { plural } from '../utils'; import Footer from '../components/Footer'; import MobileNavigation from '../components/Navigation/MobileNavigation'; import PrimaryNavigation from '../components/Navigation/PrimaryNavigation'; var listsByKey = {}; Keystone.lists.forEach((list) => { listsByKey[list.key] = list; }); var ListTile = React.createClass({ propTypes: { count: React.PropTypes.string, href: React.PropTypes.string, label: React.PropTypes.string, path: React.PropTypes.string, }, render () { var opts = { 'data-list-path': this.props.path, }; return ( <div className="dashboard-group__list" {...opts}> <span className="dashboard-group__list-inner"> <a href={this.props.href} className="dashboard-group__list-tile"> <div className="dashboard-group__list-label">{this.props.label}</div> <div className="dashboard-group__list-count">{this.props.count}</div> </a> <a href={this.props.href + '?create'} className="dashboard-group__list-create octicon octicon-plus" title="Create" tabIndex="-1" /> </span> </div> ); }, }); var HomeView = React.createClass({ displayName: 'HomeView', getInitialState () { return { counts: {}, }; }, componentDidMount () { this.loadCounts(); }, loadCounts () { xhr({ url: `${Keystone.adminPath}/api/counts`, }, (err, resp, body) => { try { body = JSON.parse(body); } catch (e) { console.log('Error parsing results json:', e, body); return; } if (body && body.counts) { if (!this.isMounted()) return; this.setState({ counts: body.counts, }); } }); }, getHeadingIconClasses (navSectionKey) { const icons = [ { icon: 'book', sections: ['books', 'posts', 'blog', 'blog-posts', 'stories', 'news-stories', 'content'] }, { icon: 'briefcase', sections: ['businesses', 'companies', 'listings', 'organizations', 'partners'] }, { icon: 'calendar', sections: ['events', 'dates'] }, { icon: 'clock', sections: ['classes', 'hours', 'times'] }, { icon: 'file-media', sections: ['gallery', 'galleries', 'images', 'photos', 'pictures'] }, { icon: 'file-text', sections: ['attachments', 'docs', 'documents', 'files'] }, { icon: 'location', sections: ['locations', 'markers', 'places'] }, { icon: 'mail', sections: ['emails', 'enquiries'] }, { icon: 'megaphone', sections: ['broadcasts', 'jobs', 'talks'] }, { icon: 'organization', sections: ['contacts', 'customers', 'groups', 'members', 'people', 'speakers', 'teams', 'users'] }, { icon: 'package', sections: ['boxes', 'items', 'packages', 'parcels'] }, { icon: 'tag', sections: ['tags'] }, ]; const classes = icons .filter(obj => obj.sections.indexOf(navSectionKey) !== -1) .map(obj => `octicon-${obj.icon}`); if (!classes.length) { classes.push('octicon-primitive-dot'); } return ['dashboard-group__heading-icon', 'octicon', ...classes].join(' '); }, renderFlatNav () { const lists = this.props.navLists.map((list) => { var href = list.external ? list.path : `${Keystone.adminPath}/${list.path}`; return <ListTile key={list.path} path={list.path} label={list.label} href={href} count={plural(this.state.counts[list.key], '* Item', '* Items')} />; }); return <div className="dashboard-group__lists">{lists}</div>; }, renderGroupedNav () { return ( <div> {this.props.navSections.map((navSection) => { return ( <div className="dashboard-group" data-section-label={navSection.label} key={navSection.key}> <div className="dashboard-group__heading"> <span className={this.getHeadingIconClasses(navSection.key)} /> {navSection.label} </div> <div className="dashboard-group__lists"> {navSection.lists.map((list) => { var href = list.external ? list.path : `${Keystone.adminPath}/${list.path}`; return <ListTile key={list.path} path={list.path} label={list.label} href={href} count={plural(this.state.counts[list.key], '* Item', '* Items')} />; })} </div> </div> ); })} {this.renderOrphanedLists()} </div> ); }, renderOrphanedLists () { if (!this.props.orphanedLists.length) return; let sectionLabel = 'Other'; return ( <div className="dashboard-group" data-section-label={sectionLabel}> <div className="dashboard-group__heading"> <span className="dashboard-group__heading-icon octicon octicon-database" /> {sectionLabel} </div> <div className="dashboard-group__lists"> {this.props.orphanedLists.map((list) => { var href = list.external ? list.path : `${Keystone.adminPath}/${list.path}`; return <ListTile key={list.path} path={list.path} label={list.label} href={href} count={plural(this.state.counts[list.key], '* Item', '* Items')} />; })} </div> </div> ); }, render () { return ( <div className="keystone-wrapper"> <header className="keystone-header"> <MobileNavigation brand={this.props.brand} currentSectionKey="dashboard" sections={this.props.nav.sections} signoutUrl={this.props.signoutUrl} /> <PrimaryNavigation brand={this.props.brand} currentSectionKey="dashboard" sections={this.props.nav.sections} signoutUrl={this.props.signoutUrl} /> </header> <div className="keystone-body"> <Container> <div className="dashboard-header"> <div className="dashboard-heading">{this.props.brand}</div> </div> <div className="dashboard-groups"> {this.props.navIsFlat ? this.renderFlatNav() : this.renderGroupedNav()} </div> </Container> </div> <Footer appversion={this.props.appversion} backUrl={this.props.backUrl} brand={this.props.brand} User={this.props.User} user={this.props.user} version={this.props.version} /> </div> ); }, }); ReactDOM.render( <HomeView appversion={Keystone.appversion} backUrl={Keystone.backUrl} brand={Keystone.brand} nav={Keystone.nav} navIsFlat={Keystone.nav.flat} navLists={Keystone.lists} navSections={Keystone.nav.sections} orphanedLists={Keystone.orphanedLists} signoutUrl={Keystone.signoutUrl} User={Keystone.User} user={Keystone.user} version={Keystone.version} />, document.getElementById('home-view') );
src/components/Walk/Walk.js
fxghqc/walk
import React from 'react' import classNames from 'classnames/bind'; import classes from './Walk.scss' let cx = classNames.bind(classes) export class Walk extends React.Component { propTypes: { walk: React.PropTypes.object.isRequired, nextAsync: React.PropTypes.func.isRequired, next: React.PropTypes.func.isRequired } constructor (props) { super(props) this.runBtnClick = this.runBtnClick.bind(this) } componentDidUpdate () { // move!!! if (this.props.walk.goOn) { setTimeout(() => { this.props.runGo() }, 1000) } } runBtnClick () { this.props.runGo() } render () { const {next, nextAsync, walk} = this.props let imgClass = cx({ imgSrc: !walk.isRunning, imgTar: walk.isRunning }) return ( <div> <h2 className={classes.counterContainer}> {walk.status} </h2> <button className='btn btn-default' onClick={next}> next </button> {' '} <button className='btn btn-default' onClick={nextAsync}> next (Async) </button> <button className='btn btn-default' onClick={this.runBtnClick}> run </button> <div className={imgClass}> <img src={`${walk.index}.png`} style={{width: '180px'}} /> </div> </div> ) } } Walk.componentDidUpdate export default Walk
src/svg-icons/maps/near-me.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsNearMe = (props) => ( <SvgIcon {...props}> <path d="M21 3L3 10.53v.98l6.84 2.65L12.48 21h.98L21 3z"/> </SvgIcon> ); MapsNearMe = pure(MapsNearMe); MapsNearMe.displayName = 'MapsNearMe'; MapsNearMe.muiName = 'SvgIcon'; export default MapsNearMe;
src/client/react/user/views/Challenges/ChallengeList.js
bwyap/ptc-amazing-g-race
import React from 'react'; import PropTypes from 'prop-types'; import { NonIdealState } from '@blueprintjs/core'; import { connect } from 'react-redux'; import LoadingSpinner from '../../../components/LoadingSpinner'; import ChallengeCard from './ChallengeCard'; const mapStateToProps = (state) => { return { challengeLoadWasSuccessful: state.state.challengeLoadWasSuccessful }; } @connect(mapStateToProps) class ChallengeList extends React.Component { static propTypes = { challengesQuery: PropTypes.shape({ getChallenges: PropTypes.array, loading: PropTypes.bool.isRequired, error: PropTypes.object }).isRequired } render() { const { getChallenges, loading, error } = this.props.challengesQuery; let noChallengeTitle = 'No challenges' let noChallengeDescription = 'No challenges are currently available.'; let noChallengeVisual = 'flag'; if (getChallenges && this.props.challengeLoadWasSuccessful) { if (getChallenges.length > 0) { return getChallenges.map((challenge) => { return <ChallengeCard key={challenge.key} order={challenge.order} challenge={challenge}/>; }) .sort((a, b) => { if (a.props.order > b.props.order) return 1; else if (a.props.order < b.props.order) return -1; else return 0; }); } // No challenges available: return default message } else if (loading) { return <LoadingSpinner/>; } else { if (error) { if (error.toString() === 'Error: GraphQL error: You are not in a team.') { noChallengeTitle = 'You are not in a team' noChallengeDescription = 'Once you are part of a team, you will be able to access the challenges available to your team.'; noChallengeVisual = 'people'; } else { noChallengeTitle = 'Unable to retrieve challenges' noChallengeDescription = error.toString(); noChallengeVisual = 'error'; } } } return ( <div style={{margin:'3rem 0'}}> <NonIdealState title={noChallengeTitle} description={noChallengeDescription} visual={noChallengeVisual}/> </div> ); } } export default ChallengeList;
frontend/src/Settings/Notifications/Notifications/EditNotificationModalContentConnector.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { saveNotification, setNotificationFieldValue, setNotificationValue, testNotification } from 'Store/Actions/settingsActions'; import createProviderSettingsSelector from 'Store/Selectors/createProviderSettingsSelector'; import EditNotificationModalContent from './EditNotificationModalContent'; function createMapStateToProps() { return createSelector( (state) => state.settings.advancedSettings, createProviderSettingsSelector('notifications'), (advancedSettings, notification) => { return { advancedSettings, ...notification }; } ); } const mapDispatchToProps = { setNotificationValue, setNotificationFieldValue, saveNotification, testNotification }; class EditNotificationModalContentConnector extends Component { // // Lifecycle componentDidUpdate(prevProps, prevState) { if (prevProps.isSaving && !this.props.isSaving && !this.props.saveError) { this.props.onModalClose(); } } // // Listeners onInputChange = ({ name, value }) => { this.props.setNotificationValue({ name, value }); }; onFieldChange = ({ name, value }) => { this.props.setNotificationFieldValue({ name, value }); }; onSavePress = () => { this.props.saveNotification({ id: this.props.id }); }; onTestPress = () => { this.props.testNotification({ id: this.props.id }); }; // // Render render() { return ( <EditNotificationModalContent {...this.props} onSavePress={this.onSavePress} onTestPress={this.onTestPress} onInputChange={this.onInputChange} onFieldChange={this.onFieldChange} /> ); } } EditNotificationModalContentConnector.propTypes = { id: PropTypes.number, isFetching: PropTypes.bool.isRequired, isSaving: PropTypes.bool.isRequired, saveError: PropTypes.object, item: PropTypes.object.isRequired, setNotificationValue: PropTypes.func.isRequired, setNotificationFieldValue: PropTypes.func.isRequired, saveNotification: PropTypes.func.isRequired, testNotification: PropTypes.func.isRequired, onModalClose: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(EditNotificationModalContentConnector);
examples/sidebar/app.js
AnSavvides/react-router
import React from 'react'; import { Router, Route, Link } from 'react-router'; import data from './data'; var Category = React.createClass({ render() { var category = data.lookupCategory(this.props.params.category); return ( <div> <h1>{category.name}</h1> {this.props.children || ( <p>{category.description}</p> )} </div> ); } }); var CategorySidebar = React.createClass({ render() { var category = data.lookupCategory(this.props.params.category); return ( <div> <Link to="/">◀︎ Back</Link> <h2>{category.name} Items</h2> <ul> {category.items.map((item, index) => ( <li key={index}> <Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link> </li> ))} </ul> </div> ); } }); var Item = React.createClass({ render() { var { category, item } = this.props.params; var menuItem = data.lookupItem(category, item); return ( <div> <h1>{menuItem.name}</h1> <p>${menuItem.price}</p> </div> ); } }); var Index = React.createClass({ render() { return ( <div> <h1>Sidebar</h1> <p> Routes can have multiple components, so that all portions of your UI can participate in the routing. </p> </div> ); } }); var IndexSidebar = React.createClass({ render() { return ( <div> <h2>Categories</h2> <ul> {data.getAll().map((category, index) => ( <li key={index}> <Link to={`/category/${category.name}`}>{category.name}</Link> </li> ))} </ul> </div> ); } }); var App = React.createClass({ render() { var { children } = this.props; return ( <div> <div className="Sidebar"> {children ? children.sidebar : <IndexSidebar />} </div> <div className="Content"> {children ? children.content : <Index />} </div> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="category/:category" components={{content: Category, sidebar: CategorySidebar}}> <Route path=":item" component={Item} /> </Route> </Route> </Router> ), document.getElementById('example'));
app/javascript/mastodon/features/ui/components/zoomable_image.js
pixiv/mastodon
import React from 'react'; import PropTypes from 'prop-types'; const MIN_SCALE = 1; const MAX_SCALE = 4; const getMidpoint = (p1, p2) => ({ x: (p1.clientX + p2.clientX) / 2, y: (p1.clientY + p2.clientY) / 2, }); const getDistance = (p1, p2) => Math.sqrt(Math.pow(p1.clientX - p2.clientX, 2) + Math.pow(p1.clientY - p2.clientY, 2)); const clamp = (min, max, value) => Math.min(max, Math.max(min, value)); export default class ZoomableImage extends React.PureComponent { static propTypes = { alt: PropTypes.string, src: PropTypes.string.isRequired, width: PropTypes.number, height: PropTypes.number, onClick: PropTypes.func, } static defaultProps = { alt: '', width: null, height: null, }; state = { scale: MIN_SCALE, } removers = []; container = null; image = null; lastTouchEndTime = 0; lastDistance = 0; componentDidMount () { let handler = this.handleTouchStart; this.container.addEventListener('touchstart', handler); this.removers.push(() => this.container.removeEventListener('touchstart', handler)); handler = this.handleTouchMove; // on Chrome 56+, touch event listeners will default to passive // https://www.chromestatus.com/features/5093566007214080 this.container.addEventListener('touchmove', handler, { passive: false }); this.removers.push(() => this.container.removeEventListener('touchend', handler)); } componentWillUnmount () { this.removeEventListeners(); } removeEventListeners () { this.removers.forEach(listeners => listeners()); this.removers = []; } handleTouchStart = e => { if (e.touches.length !== 2) return; this.lastDistance = getDistance(...e.touches); } handleTouchMove = e => { const { scrollTop, scrollHeight, clientHeight } = this.container; if (e.touches.length === 1 && scrollTop !== scrollHeight - clientHeight) { // prevent propagating event to MediaModal e.stopPropagation(); return; } if (e.touches.length !== 2) return; e.preventDefault(); e.stopPropagation(); const distance = getDistance(...e.touches); const midpoint = getMidpoint(...e.touches); const scale = clamp(MIN_SCALE, MAX_SCALE, this.state.scale * distance / this.lastDistance); this.zoom(scale, midpoint); this.lastMidpoint = midpoint; this.lastDistance = distance; } zoom(nextScale, midpoint) { const { scale } = this.state; const { scrollLeft, scrollTop } = this.container; // math memo: // x = (scrollLeft + midpoint.x) / scrollWidth // x' = (nextScrollLeft + midpoint.x) / nextScrollWidth // scrollWidth = clientWidth * scale // scrollWidth' = clientWidth * nextScale // Solve x = x' for nextScrollLeft const nextScrollLeft = (scrollLeft + midpoint.x) * nextScale / scale - midpoint.x; const nextScrollTop = (scrollTop + midpoint.y) * nextScale / scale - midpoint.y; this.setState({ scale: nextScale }, () => { this.container.scrollLeft = nextScrollLeft; this.container.scrollTop = nextScrollTop; }); } handleClick = e => { // don't propagate event to MediaModal e.stopPropagation(); const handler = this.props.onClick; if (handler) handler(); } setContainerRef = c => { this.container = c; } setImageRef = c => { this.image = c; } render () { const { alt, src } = this.props; const { scale } = this.state; const overflow = scale === 1 ? 'hidden' : 'scroll'; return ( <div className='zoomable-image' ref={this.setContainerRef} style={{ overflow }} > <img role='presentation' ref={this.setImageRef} alt={alt} src={src} style={{ transform: `scale(${scale})`, transformOrigin: '0 0', }} onClick={this.handleClick} /> </div> ); } }
app/views/STF/Voting/Panels/Budget/Budget.js
RcKeller/STF-Refresh
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { Table, Tooltip, Icon } from 'antd' import { makeManifestByID } from '../../../../../selectors' import { Loading } from '../../../../../components' const currency = value => `$${Number.parseInt(value).toLocaleString()}` const columns = [ { title: <span> <Tooltip placement='right' title='Some proposals have author supplied priority numbers that stack-rank items by importance.'> Name&nbsp; <Icon type='question-circle-o' /> </Tooltip> </span>, dataIndex: 'name', key: 'name', render: (text, record) => <b>{ record.priority ? `${record.priority}: ${text}` : text }</b>, sorter: (a, b) => (b.priority) - (a.priority) }, { title: <span> <Tooltip placement='left' title='Tax Included. Hover for item subtotals.'> Price/ea&nbsp; <Icon type='question-circle-o' /> </Tooltip> </span>, dataIndex: 'price', key: 'price', render: (text, record) => <Tooltip placement='left' title={`Subtotal: ${currency(record.tax ? record.price * record.quantity * (1 + record.tax / 100) : record.price * record.quantity)}`}> {currency(record.price * (1 + record.tax / 100))} </Tooltip>, sorter: (a, b) => a.price - b.price, width: 120, padding: 0 }, { title: 'Q', dataIndex: 'quantity', key: 'quantity', width: 50 } ] const expandedRowRender = ({ price, tax, description } = {}) => { return <span> <em>{Number.parseFloat(tax) > 0 ? `${tax}% tax applied to base cost (${currency(price)})` : 'Untaxed or taxed separately'}</em> <p>{description || <em>No description provided</em>}</p> </span> } /* BUDGET PANEL: A concise view of the manifest in question */ @connect( // Might seem counterintuitive, but we're connecting to a manifest and pulling its proposal data. (state, props) => { const manifest = makeManifestByID(props.id)(state) return { manifest, screen: state.screen } } ) class Budget extends React.Component { static propTypes = { id: PropTypes.string.isRequired, manifest: PropTypes.object, user: PropTypes.object } render ( { screen, manifest } = this.props ) { const { type, title, body, items, total } = manifest const footer = () => <span><h2>{`Grand Total: ${currency(total || 0)}`}</h2><h6>Tax Included in Calculation</h6></span> return ( <section> <Loading render={manifest} title='Budget Panel'> <div> {type === 'supplemental' && <div> <h1>Supplemental Information</h1> <h3>{title || 'Untitled Supplemental'}</h3> <p>{body || 'No information provided by the author'}</p> </div> } <Table dataSource={items || []} sort size='middle' columns={columns} rowKey={record => record._id} // The above will throw an error if using faker data, since duplicates are involved. expandedRowRender={screen.greaterThan.medium ? expandedRowRender : false} defaultExpandAllRows={screen.greaterThan.medium} pagination={false} footer={footer} /> </div> </Loading> </section> ) } } export default Budget
components/time-picker/combobox.js
TDFE/td-ui
/** * @Author: Zhengfeng.Yao <yzf> * @Date: 2017-06-21 09:57:42 * @Last modified by: yzf * @Last modified time: 2017-06-21 09:57:44 */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Select from './select'; const formatOption = (option, disabledOptions) => { let value = `${option}`; if (option < 10) { value = `0${option}`; } let disabled = false; if (disabledOptions && disabledOptions.indexOf(option) >= 0) { disabled = true; } return { value, disabled }; }; class Combobox extends Component { static propTypes = { format: PropTypes.string, defaultOpenValue: PropTypes.object, prefixCls: PropTypes.string, value: PropTypes.object, onChange: PropTypes.func, showHour: PropTypes.bool, showMinute: PropTypes.bool, showSecond: PropTypes.bool, hourOptions: PropTypes.array, minuteOptions: PropTypes.array, secondOptions: PropTypes.array, disabledHours: PropTypes.func, disabledMinutes: PropTypes.func, disabledSeconds: PropTypes.func, onCurrentSelectPanelChange: PropTypes.func, use12Hours: PropTypes.bool }; onItemChange = (type, itemValue) => { const { onChange, defaultOpenValue, use12Hours } = this.props; const value = (this.props.value || defaultOpenValue).clone(); if (type === 'hour') { if (use12Hours) { if (this.isAM()) { value.hour(+itemValue % 12); } else { value.hour((+itemValue % 12) + 12); } } else { value.hour(+itemValue); } } else if (type === 'minute') { value.minute(+itemValue); } else if (type === 'ampm') { const ampm = itemValue.toUpperCase(); if (use12Hours) { if (ampm === 'PM' && value.hour() < 12) { value.hour((value.hour() % 12) + 12); } if (ampm === 'AM') { if (value.hour() >= 12) { value.hour(value.hour() - 12); } } } } else { value.second(+itemValue); } onChange(value); } onEnterSelectPanel = (range) => { this.props.onCurrentSelectPanelChange(range); } getHourSelect(hour) { const { prefixCls, hourOptions, disabledHours, showHour, use12Hours } = this.props; if (!showHour) { return null; } const disabledOptions = disabledHours(); let hourOptionsAdj; let hourAdj; if (use12Hours) { hourOptionsAdj = [12].concat(hourOptions.filter(h => h < 12 && h > 0)); hourAdj = (hour % 12) || 12; } else { hourOptionsAdj = hourOptions; hourAdj = hour; } return ( <Select prefixCls={prefixCls} options={hourOptionsAdj.map(option => formatOption(option, disabledOptions))} selectedIndex={hourOptionsAdj.indexOf(hourAdj)} type="hour" onSelect={this.onItemChange} onMouseEnter={this.onEnterSelectPanel.bind(this, 'hour')} /> ); } getMinuteSelect(minute) { const { prefixCls, minuteOptions, disabledMinutes, defaultOpenValue, showMinute } = this.props; if (!showMinute) { return null; } const value = this.props.value || defaultOpenValue; const disabledOptions = disabledMinutes(value.hour()); return ( <Select prefixCls={prefixCls} options={minuteOptions.map(option => formatOption(option, disabledOptions))} selectedIndex={minuteOptions.indexOf(minute)} type="minute" onSelect={this.onItemChange} onMouseEnter={this.onEnterSelectPanel.bind(this, 'minute')} /> ); } getSecondSelect(second) { const { prefixCls, secondOptions, disabledSeconds, showSecond, defaultOpenValue } = this.props; if (!showSecond) { return null; } const value = this.props.value || defaultOpenValue; const disabledOptions = disabledSeconds(value.hour(), value.minute()); return ( <Select prefixCls={prefixCls} options={secondOptions.map(option => formatOption(option, disabledOptions))} selectedIndex={secondOptions.indexOf(second)} type="second" onSelect={this.onItemChange} onMouseEnter={this.onEnterSelectPanel.bind(this, 'second')} /> ); } getAMPMSelect() { const { prefixCls, use12Hours, format } = this.props; if (!use12Hours) { return null; } const AMPMOptions = ['am', 'pm'] // If format has A char, then we should uppercase AM/PM .map(c => format.match(/\sA/) ? c.toUpperCase() : c) .map(c => ({ value: c })); const selected = this.isAM() ? 0 : 1; return ( <Select prefixCls={prefixCls} options={AMPMOptions} selectedIndex={selected} type="ampm" onSelect={this.onItemChange} onMouseEnter={this.onEnterSelectPanel.bind(this, 'ampm')} /> ); } isAM() { const value = (this.props.value || this.props.defaultOpenValue); return value.hour() >= 0 && value.hour() < 12; } render() { const { prefixCls, defaultOpenValue } = this.props; const value = this.props.value || defaultOpenValue; return ( <div className={`${prefixCls}-combobox`}> {this.getHourSelect(value.hour())} {this.getMinuteSelect(value.minute())} {this.getSecondSelect(value.second())} {this.getAMPMSelect(value.hour())} </div> ); } } export default Combobox;
src/svg-icons/action/play-for-work.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPlayForWork = (props) => ( <SvgIcon {...props}> <path d="M11 5v5.59H7.5l4.5 4.5 4.5-4.5H13V5h-2zm-5 9c0 3.31 2.69 6 6 6s6-2.69 6-6h-2c0 2.21-1.79 4-4 4s-4-1.79-4-4H6z"/> </SvgIcon> ); ActionPlayForWork = pure(ActionPlayForWork); ActionPlayForWork.displayName = 'ActionPlayForWork'; export default ActionPlayForWork;
node_modules/react-router/es6/Route.js
jwhite4870/moreReactRedux
import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement } from './RouteUtils'; import { component, components } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var func = _React$PropTypes.func; /** * A <Route> is used to declare which components are rendered to the * page when the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is * requested, the tree is searched depth-first to find a route whose * path matches the URL. When one is found, all routes in the tree * that lead to it are considered "active" and their components are * rendered into the DOM, nested in the same order as in the tree. */ var Route = React.createClass({ displayName: 'Route', statics: { createRouteFromReactElement: createRouteFromReactElement }, propTypes: { path: string, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default Route;
app/javascript/mastodon/features/ui/components/mute_modal.js
NS-Kazuki/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { injectIntl, FormattedMessage } from 'react-intl'; import Toggle from 'react-toggle'; import Button from '../../../components/button'; import { closeModal } from '../../../actions/modal'; import { muteAccount } from '../../../actions/accounts'; import { toggleHideNotifications } from '../../../actions/mutes'; const mapStateToProps = state => { return { isSubmitting: state.getIn(['reports', 'new', 'isSubmitting']), account: state.getIn(['mutes', 'new', 'account']), notifications: state.getIn(['mutes', 'new', 'notifications']), }; }; const mapDispatchToProps = dispatch => { return { onConfirm(account, notifications) { dispatch(muteAccount(account.get('id'), notifications)); }, onClose() { dispatch(closeModal()); }, onToggleNotifications() { dispatch(toggleHideNotifications()); }, }; }; export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class MuteModal extends React.PureComponent { static propTypes = { isSubmitting: PropTypes.bool.isRequired, account: PropTypes.object.isRequired, notifications: PropTypes.bool.isRequired, onClose: PropTypes.func.isRequired, onConfirm: PropTypes.func.isRequired, onToggleNotifications: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; componentDidMount() { this.button.focus(); } handleClick = () => { this.props.onClose(); this.props.onConfirm(this.props.account, this.props.notifications); } handleCancel = () => { this.props.onClose(); } setRef = (c) => { this.button = c; } toggleNotifications = () => { this.props.onToggleNotifications(); } render () { const { account, notifications } = this.props; return ( <div className='modal-root__modal mute-modal'> <div className='mute-modal__container'> <p> <FormattedMessage id='confirmations.mute.message' defaultMessage='Are you sure you want to mute {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} /> </p> <div> <label htmlFor='mute-modal__hide-notifications-checkbox'> <FormattedMessage id='mute_modal.hide_notifications' defaultMessage='Hide notifications from this user?' /> {' '} <Toggle id='mute-modal__hide-notifications-checkbox' checked={notifications} onChange={this.toggleNotifications} /> </label> </div> </div> <div className='mute-modal__action-bar'> <Button onClick={this.handleCancel} className='mute-modal__cancel-button'> <FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' /> </Button> <Button onClick={this.handleClick} ref={this.setRef}> <FormattedMessage id='confirmations.mute.confirm' defaultMessage='Mute' /> </Button> </div> </div> ); } }
frontend/src/SubjectPreference.js
googleinterns/step78-2020
import React from 'react'; import {CardContent, Input} from '@material-ui/core'; import Typography from '@material-ui/core/Typography'; class SubjectPreference extends React.Component { constructor(props) { super(props); this.handleSubjectChange = this.handleSubjectChange.bind(this); } handleSubjectChange(event) { this.props.updateSubjectPreference(event.target.value); } render() { return ( <CardContent> <Typography variant="subtitle1" gutterBottom> Preferred Subject: </Typography> <Input placeholder="Subject" value={this.props.subject} onChange={this.handleSubjectChange} /> </CardContent> ); } } export default SubjectPreference;
app/components/Footer/index.js
ESTEBANMURUZABAL/bananaCatReact
import React from 'react'; import { FormattedMessage } from 'react-intl'; import A from 'components/A'; import LocaleToggle from 'containers/LocaleToggle'; import Wrapper from './Wrapper'; import messages from './messages'; function Footer() { return ( <Wrapper> <section> <FormattedMessage {...messages.licenseMessage} /> </section> <section> <LocaleToggle /> </section> <section> <FormattedMessage {...messages.authorMessage} values={{ author: <A href="https://twitter.com/mxstbr">Max Stoiber</A>, }} /> </section> </Wrapper> ); } export default Footer;
docs/tutorial/DO_NOT_TOUCH/06/src/components/App/index.js
idream3/cerebral
import React from 'react' import {connect} from 'cerebral/react' import {state, signal} from 'cerebral/tags' import Toast from '../Toast' export default connect({ title: state`title`, subTitle: state`subTitle`, buttonClicked: signal`buttonClicked` }, function App (props) { return ( <div className='o-container o-container--medium'> <h1>{props.title}</h1> <h3>{props.subTitle}</h3> <button className='c-button c-button--info c-button--block' onClick={() => props.buttonClicked({ message: 'Toast me!' })} > Update state </button> <Toast /> </div> ) } )
react/TickIcon/TickIcon.js
seek-oss/seek-style-guide
import svgMarkup from './TickIcon.svg'; import React from 'react'; import Icon from '../private/Icon/Icon'; export default function TickIcon(props) { return <Icon markup={svgMarkup} {...props} />; } TickIcon.displayName = 'TickIcon';
app/screens/components/buyer/cart-item.js
yiyinsong/react-native-example-jdh
import React, { Component } from 'react'; import { View, Text, Image, TouchableOpacity, TouchableHighlight, ScrollView, DeviceEventEmitter, TextInput } from 'react-native'; import styles from '../../../css/styles'; export default class BuyerCartItemComponent extends Component { constructor(props) { super(props); this.state = { index: this.props.index, pindex: this.props.pindex, checked: false, num: this.props.data.qty } } componentWillMount() { this.listener_check = DeviceEventEmitter.addListener('buyerCartCheck', (r) => { if(!r.all && this.state.pindex !== r.index) return; this.setState({checked: r.checked}); }); } componentWillUnmount() { this.listener_check && this.listener_check.remove(); } render() { let _data = this.props.data; return ( <View style={styles.cart.item}> <TouchableOpacity activeOpacity={.8} onPress={this._checkedItem}> {this.state.checked ? <Image source={require('../../../images/icon-checked.png')} style={styles.control.checked}/> : <View style={[styles.control.checkbox]}></View> } </TouchableOpacity> <View style={[styles.common.flex]}> <Image source={{uri: _data.sku.small_img}} style={styles.cart.img}/> <View style={styles.common.flexv}> <Text numberOfLines={2} style={styles.cart.goodsName}>{_data.sku.goods_name}</Text> <Text style={styles.cart.attr} numberOfLines={1}>{_data.sku.attr_name}</Text> <View style={[styles.common.flexDirectionRow, styles.common.flexCenterv]}> <Text style={[styles.common.flex, styles.cart.price]}>¥{_data.price}</Text> <View style={[styles.common.flexDirectionRow, styles.cart.num]}> <TouchableHighlight underlayColor='#f5f5f5' onPress={this._sub}> <Text style={styles.cart.calSub}>-</Text> </TouchableHighlight> <TextInput onChangeText={(text) => {_data.qty=text;this.setState({num: text})}} underlineColorAndroid="transparent" value={_data.qty.toString()} style={styles.cart.numInput} keyboardType='numeric' onBlur={this._blur}/> <TouchableHighlight underlayColor='#f5f5f5' onPress={this._add}> <Text style={styles.cart.calAdd}>+</Text> </TouchableHighlight> </View> </View> </View> </View> </View> ) } _checkedItem = () => { let _ori = !this.state.checked; this.setState({ checked: _ori }); this.props.checkFunc && this.props.checkFunc(_ori, this.state.index, this.state.pindex); } _sub = () => { if(this.props.data.qty < 2) return; this.props.sub && this.props.sub(); } _add = () => { this.props.add && this.props.add(); } _blur = () => { if(!/^\d+$/.test(this.props.data.qty)) { this.props.data.qty = 1; this.setState({num: 1}); } this.props.blur && this.props.blur(); } }
index.js
weslylaboy/react-native-scroll-to-top
/** * Scroll to Top * * <ScrollToTop rootView={this.listview} icon={<Icon raised name="arrow-upward" />} /> * */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { TouchableOpacity, Dimensions, StyleSheet, Text } from 'react-native'; /* Styles ==================================================================== */ const styles = StyleSheet.create({ Top: { flex: 1, position: 'absolute', alignItems: 'center', justifyContent: 'center', }, }); /* Component ==================================================================== */ class ScrollToTop extends Component { static propTypes = { isRadius: PropTypes.bool, width: PropTypes.number, height: PropTypes.number, left: PropTypes.number, top: PropTypes.number, borderRadius: PropTypes.number, backgroundColor: PropTypes.string, color: PropTypes.string, fontSize: PropTypes.number, icon: PropTypes.element, text: PropTypes.string, rootView: PropTypes.objectOf(PropTypes.shape).isRequired, ListView: PropTypes.bool }; static defaultProps = { isRadius: true, width: 60, height: 60, left: Dimensions.get('window').width - 80, top: Dimensions.get('window').height - 170, borderRadius: 30, backgroundColor: null, color: '#ffffff', fontSize: 12, icon: null, text: 'Scroll to Top', ListView: false, }; onPress() { if(this.props.ListView) this.props.rootView.scrollTo({ x: 0, y: 0, animated: true }); else this.props.rootView.scrollToOffset({offset: 0, animated: true}); } getBackgroundColor = () => { if (this.props.backgroundColor) { return this.props.backgroundColor; } if (this.props.text && !this.props.icon) { return '#546e7a'; } return null; }; render = () => ( <TouchableOpacity onPress={() => this.onPress()} style={[ styles.Top, { borderRadius: this.props.isRadius ? this.props.borderRadius : 0, backgroundColor: this.getBackgroundColor(), width: this.props.width, height: this.props.height, left: this.props.left, top: Dimensions.get('window').height - this.props.top, }, ]} > {this.props.icon ? { ...this.props.icon } : <Text style={{ color: this.props.color, fontSize: this.props.fontSize, textAlign: 'center', }} > {this.props.text} </Text>} </TouchableOpacity> ); } ScrollToTop.componentName = 'ScrollToTop'; /* Export Component ==================================================================== */ export default ScrollToTop;
app/components/animatedButtons/index.js
CKPalk/PA-POC-Video-Contoller
import React from 'react' import AnimatedButton, { TYPES } from './AnimatedButton' // export default Object.entries(TYPES).reduce( // (modules, [name, type]) => { // const moduleName = `Animated${name.charAt(0).toUpperCase()}${name.slice(1).toLowerCase()}` // return ({ // ...modules, // [moduleName]: props => <moduleName type={type} {...props} /> // }) // } // , {}) export const AnimatedAccept = props => <AnimatedButton type={TYPES.accept} {...props} /> export const AnimatedReject = props => <AnimatedButton type={TYPES.reject} {...props} /> export const AnimatedCaution = props => <AnimatedButton type={TYPES.caution} {...props} />
src/src/routes/Login/containers/LoginContainer.js
alexberriman/local-deals
import React from 'react' import { connect } from 'react-redux' import { login } from '../modules/login' import LoginForm from '../components/Login' class LoginContainer extends React.Component { /** * Sets up the component. * * @param props */ constructor(props) { super(props) this.LoginForm = LoginForm(login, '/advertiser') } /** * Renders the login component. * * @returns {XML} */ render() { return ( <this.LoginForm {...this.props} /> ) } } LoginContainer.propTypes = { location: React.PropTypes.object.isRequired } const mapStateToProps = state => ({ email: state.user.id }) export default connect(mapStateToProps)(LoginContainer)
src/icons/PhonelinkLockIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class PhonelinkLockIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 1H9c-1.1 0-2 .9-2 2v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm-8.2 10V9.5C10.8 8.1 9.4 7 8 7S5.2 8.1 5.2 9.5V11c-.6 0-1.2.6-1.2 1.2v3.5c0 .7.6 1.3 1.2 1.3h5.5c.7 0 1.3-.6 1.3-1.2v-3.5c0-.7-.6-1.3-1.2-1.3zm-1.3 0h-3V9.5c0-.8.7-1.3 1.5-1.3s1.5.5 1.5 1.3V11z"/></svg>;} };
src/Table/Table.js
react-fabric/react-fabric
import React from 'react' import cx from 'classnames' import fabricComponent from '../fabricComponent' import style from './Table.scss' const Table = ({ children, fixed, ...props }) => ( <table data-fabric="Table" {...props } styleName={cx('ms-Table', { 'ms-Table--fixed': fixed, })}> { children } </table> ) Table.displayName = 'Table' Table.propTypes = { children: React.PropTypes.node, fixed: React.PropTypes.bool } Table.defaultProps = { fixed: false } export default fabricComponent(Table, style)
src/components/Back/Back.js
Grusteam/spark-in-me
import React from 'react'; import cx from 'classnames'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Back.css'; import Link from '../Link'; import history from '../../core/history'; class Back extends React.Component { handleClick() { history.goBack(); } render() { return ( <div className={s.root}> <div className="container"> <div className="row"> <div className="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <ul className={cx(s.pagerBack, 'pager')}> <li className="prev"> <Link to="/" onClick={this.handleClick}>&larr; Back</Link> </li> </ul> </div> </div> </div> </div> ); } } export default withStyles(s)(Back);
packages/react-scripts/fixtures/kitchensink/src/features/syntax/CustomInterpolation.js
IamJoseph/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; const styled = ([style]) => style .trim() .split(/\s*;\s*/) .map(rule => rule.split(/\s*:\s*/)) .reduce((rules, rule) => ({ ...rules, [rule[0]]: rule[1] }), {}); function load() { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { const veryInlineStyle = styled` background: palevioletred; color: papayawhip; `; return ( <div id="feature-custom-interpolation"> {this.state.users.map(user => ( <div key={user.id} style={veryInlineStyle}> {user.name} </div> ))} </div> ); } }
src/encoded/static/components/genome_browser.js
ENCODE-DCC/encoded
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'underscore'; import { filterForVisualizableFiles } from './objectutils'; import Tooltip from '../libs/ui/tooltip'; import GeneSearch from './gene_search'; /** * Maps long annotation_type values to shorter versions for Valis track labels. Any not included * remain unchanged. */ export const annotationTypeMap = { 'candidate Cis-Regulatory Elements': 'cCRE', 'representative DNase hypersensitivity sites (rDHSs)': 'rDHS', }; const GV_COORDINATES_KEY = 'ENCODE-GV-coordinates'; const MAX_CHAR_PER_LINE = 26; // used to determine if GV_COORDINATES_KEY should be used const GV_COORDINATES_ASSEMBLY = 'ENCODE-GV-assembly'; const GV_COORDINATES_ANNOTATION = 'ENCODE-GV-annotation'; const colorChromatinState = { 'Active TSS': '#ff0000', 'Flanking TSS': '#ff4400', 'Flanking TSS upstream': '#ff4500', 'Flanking TSS downstream': '#ff4500', 'Strong transcription': '#008000', 'Weak transcription': '#006400', 'Genic enhancer 1': '#c4e105', 'Genic enhancer 2': '#c4e105', 'Active enhancer 1': '#ffc44d', 'Active enhancer 2': '#ffc44d', 'Weak enhancer': '#ffff00', 'ZNF genes & repeats': '#66cdaa', Heterochromatin: '#8a91d0', 'Bivalent/Poised TSS': '#cd5c5c', 'Bivalent enhancer': '#bdb86b', 'Repressed PolyComb': '#808080, #8937df', 'Weak Repressed PolyComb': '#c0c0c0, #9750e3', 'Quiescent/Low': '#ffffff', }; const colorCCREs = { 'Promoter-like': '#ff0000', 'Proximal enhancer-like': '#ffa700', 'Distal enhancer-like': '#ffcd00', 'DNase-H3K4me3': '#ffaaaa', 'CTCF-only': '#00b0f0', 'DNase-only': '#06da93', 'Low-DNase': '#e1e1e1', Unclassified: '#8c8c8c', }; const colorGenome = { 'Nucleobase A': '#0c7489', 'Nucleobase T': '#f9ce70', 'Nucleobase G': '#0fa3b1', 'Nucleobase C': '#c14953', 'GC-low': '#0c7489', 'GC-rich': '#f9ce70', }; const colorGenes = { Transcript: '#cfd7c7', 'Protein coding': '#575f5a', 'Non-protein coding': '#f9ce70', UTR: '#c14953', }; /** * Returns Valis coordinates off the bar user inputs data in * * @param {string} scrollLocation, in format: "chr{contig} {x0}bp to {x1}bp, where contig, x0 and x2 and numbers. Note, the unit can also be Mbp" * @returns {x0, x1, contig} */ const readGenomeBrowserLabelCoordinates = () => { const scrollLocation = document.querySelector('.valis-browser .hpgv_panel-header span'); if (!scrollLocation || !scrollLocation.innerText) { return {}; } const splitScrollLocation = scrollLocation.innerText.split(' '); const contig = splitScrollLocation[0]; const x0 = (splitScrollLocation[1].indexOf('Mbp') > -1) ? +splitScrollLocation[1].replace('Mbp', '') * 1e6 : +splitScrollLocation[1].replace('bp', ''); const x1 = (splitScrollLocation[3].indexOf('Mbp') > -1) ? +splitScrollLocation[3].replace('Mbp', '') * 1e6 : +splitScrollLocation[3].replace('bp', ''); return { x0, x1, contig }; }; /** * Get default coordinates to the genome browser * * @param {string} assemblyAnnotation Assembly information * @param {boolean} [ignoreCache=false] True to not look into cache, false to use cache * @returns Default coordinates */ const getDefaultCoordinates = (defaultLocation, assembly, annotation, ignoreCache = false) => { // Files to be displayed on all genome browser results let pinnedFiles = []; let contig = null; let x0 = null; let x1 = null; const gVState = ignoreCache ? null : window.sessionStorage.getItem(GV_COORDINATES_KEY); const gVAssembly = window.sessionStorage.getItem(GV_COORDINATES_ASSEMBLY); const gVAnnotation = window.sessionStorage.getItem(GV_COORDINATES_ANNOTATION); if (gVState && gVAssembly === assembly && gVAnnotation === annotation) { const savedState = gVState ? JSON.parse(gVState) : {}; ({ contig } = savedState); ({ x0, x1, pinnedFiles } = savedState); } else if (assembly === 'GRCh38') { pinnedFiles = [ { file_format: 'vdna-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/GRCh38/GRCh38.vdna-dir', }, { file_format: 'vgenes-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/GRCh38/GRCh38.vgenes-dir', title: 'GENCODE V29', }, { title: 'dbSNP (153)', file_format: 'variant', path: 'https://encoded-build.s3.amazonaws.com/browser/GRCh38/GRCh38-dbSNP153.vvariants-dir', }, { file_format: 'bigBed', href: '/files/ENCFF998GAH/@@download/ENCFF998GAH.bigBed', dataset: '/annotations/ENCSR890YQQ/', title: 'representative DNase hypersensitivity sites', }, { file_format: 'bigBed', href: '/files/ENCFF081NFZ/@@download/ENCFF081NFZ.bigBed', dataset: '/annotations/ENCSR487PRC/', title: 'cCRE, all', }, ]; if (annotation === 'V33') { pinnedFiles = [ { file_format: 'vdna-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/GRCh38/GRCh38.vdna-dir', }, { file_format: 'vgenes-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/GRCh38/gencode.v33.GRCh38.p13.annotation.vgenes-dir', title: 'GENCODE V33', }, { title: 'dbSNP (153)', file_format: 'variant', path: 'https://encoded-build.s3.amazonaws.com/browser/GRCh38/GRCh38-dbSNP153.vvariants-dir', }, { file_format: 'bigBed', href: '/files/ENCFF998GAH/@@download/ENCFF998GAH.bigBed', dataset: '/annotations/ENCSR890YQQ/', title: 'representative DNase hypersensitivity sites', }, { file_format: 'bigBed', href: '/files/ENCFF081NFZ/@@download/ENCFF081NFZ.bigBed', dataset: '/annotations/ENCSR487PRC/', title: 'cCRE, all', }, ]; } contig = 'chr1'; x0 = 11102837; x1 = 11267747; } else if (assembly === 'hg19' || assembly === 'GRCh37') { pinnedFiles = [ { file_format: 'vdna-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/hg19/hg19.vdna-dir', }, { file_format: 'vgenes-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/hg19/hg19.vgenes-dir', title: 'GENCODE V19', }, ]; contig = 'chr21'; x0 = 33031597; x1 = 33041570; } else if (assembly === 'GRCm39') { pinnedFiles = [ { file_format: 'vdna-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/mm39/mm39.vdna-dir', }, { file_format: 'vgenes-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/mm39/gencode.vM26.GRCm39.annotation.vgenes-dir', title: 'GENCODE M26', }, ]; contig = 'chr7'; x0 = 72938479; x1 = 73220239; } else if (assembly === 'mm10' || assembly === 'mm10-minimal' || assembly === 'GRCm38') { pinnedFiles = [ { file_format: 'vdna-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/mm10/mm10.vdna-dir', }, { file_format: 'vgenes-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/mm10/mm10.vgenes-dir', title: 'GENCODE M21', }, { file_format: 'bigBed', href: '/files/ENCFF846RAN/@@download/ENCFF846RAN.bigBed', dataset: '/annotations/ENCSR127YRL/', title: 'representative DNase hypersensitivity sites', }, { file_format: 'bigBed', href: '/files/ENCFF074AWA/@@download/ENCFF074AWA.bigBed', dataset: '/annotations/ENCSR906ZUZ/', title: 'cCRE, all', }, ]; contig = 'chr12'; x0 = 56694976; x1 = 56714605; } else if (assembly === 'mm9' || assembly === 'GRCm37') { pinnedFiles = []; contig = 'chr12'; x0 = 57795963; x1 = 57815592; } else if (assembly === 'dm6') { pinnedFiles = [ { file_format: 'vdna-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/dm6/dm6.vdna-dir', }, { file_format: 'vgenes-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/dm6/Drosophila_melanogaster.BDGP6.22.96.vgenes-dir', title: 'FlyBase Annotation 6.04', }, ]; contig = 'chr2L'; x0 = 2420509; x1 = 2467686; } else if (assembly === 'dm3') { pinnedFiles = [ { file_format: 'vdna-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/dm3/dm3.vdna-dir', }, { file_format: 'vgenes-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/dm3/dmel-all-r5.12.sorted.trimmed.chrM_fixed.vgenes-dir', title: 'FlyBase Annotation 5.12', }, ]; contig = 'chr2L'; x0 = 2428372; x1 = 2459823; } else if (assembly === 'ce11') { pinnedFiles = [ { file_format: 'vdna-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/ce11/ce11.vdna-dir', }, { file_format: 'vgenes-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/ce11/Caenorhabditis_elegans.WBcel235.96.vgenes-dir', title: 'WormBase Annotation WS235', }, ]; contig = 'chrII'; x0 = 232292; x1 = 238909; } else if (assembly === 'ce10') { pinnedFiles = [ { file_format: 'vdna-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/ce10/ce10.vdna-dir', }, { file_format: 'vgenes-dir', href: 'https://encoded-build.s3.amazonaws.com/browser/ce10/c_elegans.WS220.annotations.sorted_chr_fixed.vgenes-dir', title: 'WormBase Annotation WS220', }, ]; contig = 'chrII'; x0 = 232475; x1 = 237997; } if (defaultLocation) { contig = defaultLocation.chromosome; x0 = defaultLocation.start; x1 = defaultLocation.end; } window.sessionStorage.setItem(GV_COORDINATES_ASSEMBLY, assembly); window.sessionStorage.setItem(GV_COORDINATES_ANNOTATION, annotation); return { x0, x1, contig, pinnedFiles }; }; // Files to be displayed for local version of browser const dummyFiles = [ { file_format: 'bigWig', output_type: 'minus strand signal of all reads', accession: 'ENCFF425LKJ', '@id': '/files/ENCFF425LKJ', href: '/files/ENCFF425LKJ/@@download/ENCFF425LKJ.bigWig', assembly: 'GRCh38', file_type: 'bigWig', assay_term_name: 'shRNA knockdown followed by RNA-seq', dataset: '/experiments/ENCSR585KOJ/', biosample_ontology: { term_name: 'HepG2', }, lab: { title: 'ENCODE Processing Pipeline', }, status: 'released', title: 'ENCFF425LKJ', biological_replicates: [1], simple_biosample_summary: 'male (34 years)', }, { file_format: 'bigWig', output_type: 'plus strand signal of all reads', accession: 'ENCFF638QHN', '@id': '/files/ENCFF638QHN', href: '/files/ENCFF638QHN/@@download/ENCFF638QHN.bigWig', assembly: 'GRCh38', file_type: 'bigWig', assay_term_name: 'shRNA knockdown followed by RNA-seq', dataset: '/experiments/ENCSR585KOJ/', biosample_ontology: { term_name: 'HepG2', }, lab: { title: 'ENCODE Processing Pipeline', }, status: 'released', title: 'ENCFF638QHN', biological_replicates: [2], simple_biosample_summary: 'mild cognitive impairment', }, { file_format: 'bigWig', output_type: 'plus strand signal of unique reads', accession: 'ENCFF541XFO', '@id': '/files/ENCFF541XFO', href: '/files/ENCFF541XFO/@@download/ENCFF541XFO.bigWig', assembly: 'GRCh38', file_type: 'bigWig', dataset: '/experiments/ENCSR585KOJ/', assay_term_name: 'shRNA knockdown followed by RNA-seq', biosample_ontology: { term_name: 'HepG2', }, lab: { title: 'ENCODE Processing Pipeline', }, origin_batches: ['/biosamples/ENCBS087RNA/', '/biosamples/ENCBS888CRI/'], status: 'released', title: 'ENCFF541XFO', biological_replicates: [1], simple_biosample_summary: 'male adult (35 years) treated with 5 μg/mL Interferon-gamma antibody , 100 ng/mL Interleukin-4 , anti-CD3 and anti-CD28 coated beads', }, { file_format: 'bigBed bedRNAElements', output_type: 'transcription start sites', accession: 'ENCFF517WSY', '@id': '/files/ENCFF517WSY', href: '/files/ENCFF517WSY/@@download/ENCFF517WSY.bigBed', assembly: 'GRCh38', file_type: 'bigBed tss_peak', dataset: '/experiments/ENCSR000CIS/', assay_term_name: 'shRNA knockdown followed by RNA-seq', origin_batches: ['/biosamples/ENCBS087RNA/'], biosample_ontology: { term_name: 'HepG2', }, lab: { title: 'ENCODE Processing Pipeline', }, status: 'released', title: 'ENCFF517WSY', biological_replicates: [1], simple_biosample_summary: 'mild cognitive impairment', }, { file_format: 'bigBed', output_type: 'peaks', accession: 'ENCFF026DAN', '@id': '/files/ENCFF026DAN', href: '/files/ENCFF026DAN/@@download/ENCFF026DAN.bigBed', assembly: 'hg19', file_type: 'bigBed narrowPeak', dataset: '/experiments/ENCSR683CSF/', assay_term_name: 'ChIP-seq', biosample_ontology: { term_name: 'HepG2', }, lab: { title: 'ENCODE Processing Pipeline', }, status: 'released', title: 'ENCFF026DAN', biological_replicates: [2], simple_biosample_summary: 'mild cognitive impairment', }, { file_format: 'bigBed', output_type: 'peaks', accession: 'ENCFF847CBY', '@id': '/files/ENCFF847CBY', href: '/files/ENCFF847CBY/@@download/ENCFF847CBY.bigBed', assembly: 'hg19', file_type: 'bigBed narrowPeak', dataset: '/experiments/ENCSR683CSF/', assay_term_name: 'ChIP-seq', biosample_ontology: { term_name: 'HepG2', }, lab: { title: 'ENCODE Processing Pipeline', }, status: 'released', title: 'ENCFF847CBY', biological_replicates: [1, 2], simple_biosample_summary: 'mild cognitive impairment', }, ]; // Fetch gene coordinate file export function getCoordinateData(geneLink, fetch) { return fetch(geneLink, { method: 'GET', headers: { Accept: 'application/json', }, }).then((response) => { if (response.ok) { return response.json(); } throw new Error('not ok'); }).catch((e) => { console.log('OBJECT LOAD ERROR: %s', e); }); } const getAssemblyWithoutGenomeAnnotationOrMinimal = (assembly) => assembly.split(' ')[0].replace('-minimal', ''); function mapGenome(inputAssembly) { let genome = inputAssembly.split(' ')[0]; if (genome === 'hg19') { genome = 'GRCh37'; } else if (genome === 'mm9') { genome = 'GRCm37'; } else if (genome === 'mm10') { genome = 'GRCm38'; } return genome; } // Map the name of a sort parameter to a file object property and convert to form that can be compared // Ordering by replicate is like this: 'Rep 1,2' -> 'Rep 1,3,...' -> 'Rep 2,3,...' -> 'Rep 1' -> 'Rep 2' -> 'Rep N' // Multiplication by 1000 orders the replicates with a single replicate at the end const sortLookUp = (obj, param) => { switch (param) { case 'Replicates': return obj.biological_replicates.length > 1 ? +obj.biological_replicates.join('') : +obj.biological_replicates * 1000; case 'Output type': return obj.output_type.toLowerCase(); case 'File type': return obj.file_type.toLowerCase(); case 'Assay term name': return obj.assay_term_name.toLowerCase(); case 'Biosample term name': return obj.biosample_ontology ? obj.biosample_ontology.term_name.toLowerCase() : null; case 'Annotation type': return obj.annotation_type.toLowerCase(); default: return null; } }; const LegendLabel = () => ( <div className="legend-label"> <div className="legend-color-container"> <div className="legend-swatch" style={{ background: `${colorGenome['Nucleobase A']}` }} /> <div className="legend-swatch" style={{ background: `${colorGenome['Nucleobase T']}` }} /> <div className="legend-swatch" style={{ background: `${colorGenome['Nucleobase C']}` }} /> <div className="legend-swatch" style={{ background: `${colorGenome['Nucleobase G']}` }} /> </div> <div className="legend-name">Legend</div> </div> ); /** * Display a legend */ const GenomeLegend = (props) => ( <Tooltip trigger={<LegendLabel />} tooltipId="genome-legend" css="legend-button" size="large" columnCount={props.colorBlock.length + 2} > <div className="legend-container"> <div className="legend-block"> <h5>Genome</h5> {Object.keys(colorGenome).map((nucleobase) => ( <div className="legend-element" key={nucleobase}> <div className={`legend-swatch ${colorGenome[nucleobase] === '#ffffff' ? 'with-border' : ''}`} style={{ background: `${colorGenome[nucleobase]}` }} /> <div className="legend-label">{nucleobase}</div> </div> ))} </div> <div className="legend-block"> <h5>Genes</h5> {Object.keys(colorGenes).map((gene) => ( <div className="legend-element" key={gene}> <div className={`legend-swatch ${colorGenes[gene] === '#ffffff' ? 'with-border' : ''}`} style={{ background: `${colorGenes[gene]}` }} /> <div className="legend-label">{gene}</div> </div> ))} </div> {(props.colorBlock.indexOf('ccres') > -1) ? <div className="legend-block"> <h5>CCREs</h5> {Object.keys(colorCCREs).map((ccre) => ( <div className="legend-element" key={ccre}> <div className={`legend-swatch ${colorCCREs[ccre] === '#ffffff' ? 'with-border' : ''}`} style={{ background: `${colorCCREs[ccre]}` }} /> <div className="legend-label">{ccre}</div> </div> ))} </div> : null} {(props.colorBlock.indexOf('chromatin') > -1) ? <div className="legend-block"> <h5>Chromatin</h5> {Object.keys(colorChromatinState).map((state) => ( <div className="legend-element" key={state}> {(colorChromatinState[state].indexOf(', ') === -1) ? <div className={`legend-swatch ${colorChromatinState[state] === '#ffffff' ? 'with-border' : ''}`} style={{ background: `${colorChromatinState[state]}` }} /> : <div className={`legend-swatch ${colorChromatinState[state] === '#ffffff' ? 'with-border' : ''}`} style={{ 'background-image': `-webkit-linear-gradient(45deg, ${colorChromatinState[state].split(', ')[0]} 50%, ${colorChromatinState[state].split(', ')[1]} 50%)` }} /> } <div className="legend-label">{state}</div> </div> ))} </div> : null} </div> </Tooltip> ); GenomeLegend.propTypes = { colorBlock: PropTypes.array.isRequired, }; /** * Retrieve the target from the given file. Some files have a `targets` array, in which case return * the first target from this array. * @param {object} file File included in browser * @returns {object} `target` or first `targets` object from file. */ const getFileTarget = (file) => { let fileTarget = file.targets && file.targets[0]; if (!fileTarget) { fileTarget = file.target; } return fileTarget; }; /** * Display a label for a file’s track. */ const TrackLabel = ({ file, label, supplementalShortLabel, long }) => { const biologicalReplicates = file.biological_replicates && file.biological_replicates.join(', '); const splitDataset = file.dataset.split('/'); const datasetName = splitDataset[splitDataset.length - 2]; // For Valis in carts, build the short string. let cartShortLabel; const fileTarget = getFileTarget(file); if (label === 'cart') { cartShortLabel = _.compact([ fileTarget && fileTarget.label, file.assay_term_name, file.biosample_ontology && file.biosample_ontology.term_name, file.annotation_subtype, supplementalShortLabel, ]).join(', '); } const originBatchesList = file.origin_batches ? `batch${file.origin_batches.length > 1 ? 'es' : ''}: ${file.origin_batches.map((batch) => batch.split('/')[2]).join(', ')}` : ''; return ( <> {(label === 'cart') ? <ul className="gb-info"> {cartShortLabel !== '' ? cartShortLabel : <span>{file.output_type}</span>} {long ? <> <li><a href={file.dataset} className="gb-accession">{datasetName}<span className="sr-only">{`Details for dataset ${datasetName}`}</span></a></li> <li><a href={file['@id']} className="gb-accession">{file.title}<span className="sr-only">{`Details for file ${file.title}`}</span></a></li> {cartShortLabel !== '' ? <li>{file.output_type}</li> : null} {file.origin_batches ? <li>{originBatchesList}</li> : null} {file.simple_biosample_summary ? <li>{file.simple_biosample_summary}</li> : null} {biologicalReplicates ? <li>{`rep ${biologicalReplicates}`}</li> : null} {file.biochemical_inputs ? <li>{(file.biochemical_inputs).join(', ')}</li> : null} </> : null} </ul> : <ul className="gb-info"> <li> <a href={file['@id']} className="gb-accession">{file.title}<span className="sr-only">{`Details for file ${file.title}`}</span></a> {(biologicalReplicates && biologicalReplicates !== '') ? <span>{` (rep ${biologicalReplicates})`}</span> : null} {supplementalShortLabel ? <span>{` ${supplementalShortLabel}`}</span> : null} </li> {long ? <> {file.biosample_ontology && file.biosample_ontology.term_name ? <li>{file.biosample_ontology.term_name}</li> : null} {file.target ? <li>{file.target.label}</li> : null} {file.assay_term_name ? <li>{file.assay_term_name}</li> : null} {file.origin_batches ? <li>{originBatchesList}</li> : null} {file.simple_biosample_summary ? <li>{file.simple_biosample_summary}</li> : null} <li>{file.output_type}</li> {file.annotation_subtype ? <li>{(file.annotation_subtype)}</li> : null} {file.biochemical_inputs ? <li>{(file.biochemical_inputs).join(', ')}</li> : null} </> : null} </ul> } </> ); }; TrackLabel.propTypes = { /** File object being displayed in the track */ file: PropTypes.object.isRequired, /** Determines what label to display */ label: PropTypes.string.isRequired, /** Additional non-file-based label to display when track collapsed */ supplementalShortLabel: PropTypes.string, /** True to generate a long version of the label */ long: PropTypes.bool, }; TrackLabel.defaultProps = { supplementalShortLabel: null, long: false, }; class GenomeBrowser extends React.Component { constructor(props, context) { super(props, context); this.state = { trackList: [], visualizer: null, genome: '', annotation: '', contig: 'chr1', x0: 0, x1: 59e6, pinnedFiles: [], sortToggle: this.props.sortParam.map(() => true), // Indicates ascending or descending order for each sort parameter; true is descending and false is ascending primarySort: this.props.sortParam[0] || 'Replicates', // Indicates the final (primary) sort applied to the list of files colorBlock: [], // Legend entries }; this.setBrowserDefaults = this.setBrowserDefaults.bind(this); this.clearBrowserMemory = this.clearBrowserMemory.bind(this); this.filesToTracks = this.filesToTracks.bind(this); this.drawTracks = this.drawTracks.bind(this); this.drawTracksResized = this.drawTracksResized.bind(this); this.handleGeneSearchResultClick = this.handleGeneSearchResultClick.bind(this); this.scrollToGeneLocation = this.scrollToGeneLocation.bind(this); this.setGenomeAndTracks = this.setGenomeAndTracks.bind(this); this.resetLocation = this.resetLocation.bind(this); this.sortFiles = this.sortFiles.bind(this); this.sortAndRefresh = this.sortAndRefresh.bind(this); } componentDidMount() { // Load GenomeVisualizer library // We have to wait for the component to mount because the library relies on window variable require.ensure(['genome-visualizer'], (require) => { this.GV = require('genome-visualizer'); // Determine pinned files based on genome, filter and sort files, compute and draw tracks this.setGenomeAndTracks(); }); } /* eslint-disable react/no-did-update-set-state */ componentDidUpdate(prevProps, prevState) { if (this.GV) { const contigUpdate = this.state.contig !== prevState.contig; const assemblyUpdate = this.props.assembly !== prevProps.assembly || this.props.annotation !== prevProps.annotation; const filesUpdate = !(_.isEqual(this.props.files, prevProps.files)); const sizeUpdate = this.props.expanded !== prevProps.expanded; if (contigUpdate) { if (this.state.visualizer) { this.state.visualizer.setLocation({ contig: this.state.contig, x0: this.state.x0, x1: this.state.x1 }); } } if (assemblyUpdate) { // Determine pinned files based on genome, filter and sort files, compute and draw tracks this.setGenomeAndTracks(); } // If the parent container changed size, we need to update the browser width if (sizeUpdate) { setTimeout(this.drawTracksResized, 1000); } if (filesUpdate) { const primarySortIndex = this.props.sortParam.indexOf(this.state.primarySort); const primarySortToggle = this.state.sortToggle[primarySortIndex]; this.sortAndRefresh(this.state.primarySort, primarySortToggle, primarySortIndex, false); } } } /* eslint-enable react/no-did-update-set-state */ componentWillUnmount() { // Recommendation from George of Valis to clear web-browser memory used by Valis. this.clearBrowserMemory(); if (this.state.visualizer) { this.state.visualizer.appCanvasRef.componentWillUnmount(); } // save co-ordinates to be used to restore location if user comes back to genome_browser tab/area const { x0, x1, contig } = readGenomeBrowserLabelCoordinates(); window.sessionStorage.setItem(GV_COORDINATES_KEY, JSON.stringify({ contig, x0, x1, pinnedFiles: this.state.pinnedFiles, })); } handleGeneSearchResultClick(gene) { this.scrollToGeneLocation(gene); } setBrowserDefaults(assembly, annotation, resolve) { const { contig, x0, x1, pinnedFiles } = getDefaultCoordinates(this.props.defaultLocation, assembly, annotation); this.setState({ contig, x0, x1, pinnedFiles }, () => { if (resolve) { resolve('success!'); } }); } setGenomeAndTracks() { const genome = mapGenome(this.props.assembly); const { annotation } = this.props; this.setState({ genome, annotation }); // Determine genome and Gencode pinned files for selected assembly const genomePromise = new Promise((resolve) => { this.setBrowserDefaults(genome, annotation, resolve); }); // Make sure that we have these pinned files before we convert the files to tracks and chart them genomePromise.then(() => { const primarySortIndex = this.props.sortParam.indexOf(this.state.primarySort); const primarySortToggle = this.state.sortToggle[primarySortIndex]; this.sortAndRefresh(this.state.primarySort, primarySortToggle, primarySortIndex, false); }); } scrollToGeneLocation(gene) { this.state.visualizer.setLocation( gene.locationForVisualization( getAssemblyWithoutGenomeAnnotationOrMinimal( this.props.assembly ) ) ); } /** * Clear any remains of memory Valis has used within the web browser. */ clearBrowserMemory() { if (this.state.visualizer) { this.state.visualizer.stopFrameLoop(); this.state.visualizer.clearCaches(); } } // Sort file object by an arbitrary number of sort parameters // "primarySort" is the primary sort parameter // "sortDirection" refers to ascending or descending order // "sortIdx" keeps track of the index of the primarySort in this.state.sortToggle // "toggleFlag" indicates whether the primarySort has changed and if its sortDirection should be reversed // (i.e., whether this function is being called upon initialization or upon the user clicking on a sort button) sortFiles(primarySort, sortDirection, sortIdx, toggleFlag) { let propsFiles = []; const domain = `${window.location.protocol}//${window.location.hostname}`; // Make sure that the sorting parameter "primarySort" is the last element in the sort array const orderedSortParam = [...this.props.sortParam]; const fromIdx = orderedSortParam.indexOf(primarySort); orderedSortParam.splice((orderedSortParam.length - 1), 0, orderedSortParam.splice(fromIdx, 1)[0]); // The sort button for "Output type" is secretly also a sort button for "File type", so that all the bigWigs and bigBeds are grouped with each other // Here we add "File type" to the sort array if it's not already there and make sure that it is the sort parameter after "Output type" const fileIdx = orderedSortParam.indexOf('File type'); const outputIdx = orderedSortParam.indexOf('Output type'); if (fileIdx > -1) { orderedSortParam.splice((outputIdx + 1), 0, orderedSortParam.splice(fileIdx, 1)[0]); } else { orderedSortParam.splice((outputIdx + 1), 0, 'File type'); } // Initialize files if (domain.includes('localhost')) { propsFiles = dummyFiles; } else { // Filter files to include only bigWig and bigBed formats, and not 'bigBed bedMethyl' formats and only released or in progress files propsFiles = filterForVisualizableFiles(this.props.files); } let files = propsFiles; // Apply sort parameters if (this.props.displaySort) { orderedSortParam.forEach((param) => { files = _.chain(files) .sortBy((obj) => sortLookUp(obj, param)); }); files = files.value(); } // sortBy sorts in ascending order and sortDirection is true if descending // We want to reverse the sort order when the sort is toggled and ascending (to make it descending) if (sortDirection && toggleFlag) { files = files.reverse(); } // Update state if function has been triggered by button click and sort and sort direction are new if (toggleFlag) { this.setState((state) => { const newSortToggle = [...state.sortToggle]; newSortToggle[sortIdx] = !newSortToggle[sortIdx]; return { primarySort, sortToggle: newSortToggle, }; }); } return files; } // Call sortFiles() to sort file object by an arbitrary number of sort parameters // Re-draw the tracks on the genome browser sortAndRefresh(primarySort, sortDirection, sortIdx, toggleFlag) { _.defer(() => { let files = []; let newFiles = []; const domain = `${window.location.protocol}//${window.location.hostname}`; files = this.sortFiles(primarySort, sortDirection, sortIdx, toggleFlag).filter((file) => file.assembly === this.props.assembly); newFiles = [...this.state.pinnedFiles, ...files]; newFiles = _.uniq(newFiles, (file) => file.href); let tracks = []; if (files.length > 0) { const maxCharPerLine = this.props.maxCharPerLine || MAX_CHAR_PER_LINE; tracks = this.filesToTracks(newFiles, this.props.label, domain, maxCharPerLine); } let { contig, x0, x1 } = this.state; if (this.chartdisplay) { const coordinates = readGenomeBrowserLabelCoordinates(); ({ x0, x1, contig } = coordinates); } this.setState({ trackList: tracks, contig, x0, x1, }, () => { if (this.chartdisplay && tracks.length > 0) { this.drawTracks(this.chartdisplay); } }); }); } filesToTracks(files, label, domain, maxCharPerLine) { const tracks = files.map((file) => { if (file.output_type === 'candidate Cis-Regulatory Elements' && this.state.colorBlock.indexOf('ccres') === -1) { this.setState((prevState) => ({ colorBlock: [...prevState.colorBlock, 'ccres'], })); } if ((file.output_type === 'semi-automated genome annotation' || file.output_type === 'HMM predicted chromatin state') && this.state.colorBlock.indexOf('chromatin') === -1) { this.setState((prevState) => ({ colorBlock: [...prevState.colorBlock, 'chromatin'], })); } const supplementalShortLabel = this.props.supplementalShortLabels && this.props.supplementalShortLabels[file.dataset]; const defaultHeight = 30; const defaultExtHeight = 130; const extraLineHeight = 14; let labelLength = file.title ? Math.floor(file.title.length / maxCharPerLine) : 0; let extLabelLength = labelLength; // Some labels on the cart which have a target, assay name, and biosample are too long for one line (some actually extend to three lines) // Here we do some approximate math to try to figure out how many lines the labels extend to assuming that ~30 characters fit on one line // Labels on the experiment pages are short enough to fit on one line (they contain less information) so we can bypass these calculations for those pages if (label === 'cart') { file.annotation_type = file.annotation_type === 'candidate Cis-Regulatory Elements' ? 'cCRE' : file.annotation_type; const fileTarget = getFileTarget(file); labelLength += fileTarget && fileTarget.label ? fileTarget.label.length + 2 : 0; labelLength += file.assay_term_name ? file.assay_term_name.length + 2 : 0; labelLength += file.biosample_ontology && file.biosample_ontology.term_name ? file.biosample_ontology.term_name.length + 2 : 0; labelLength += file.annotation_subtype ? file.annotation_subtype.length : 0; labelLength += supplementalShortLabel ? supplementalShortLabel.length : 0; extLabelLength += file.output_type ? file.output_type.length : 0; extLabelLength += file.simple_biosample_summary ? file.simple_biosample_summary.length : 0; extLabelLength += file.origin_batches ? (file.origin_batches.length * 11) : 0; extLabelLength += file.biological_replicates ? file.biological_replicates.length : 0; extLabelLength += file.biochemical_inputs ? file.biochemical_inputs.length : 0; labelLength = Math.floor(labelLength / maxCharPerLine); extLabelLength = Math.floor(extLabelLength / maxCharPerLine); } if (file.name) { const trackObj = {}; trackObj.name = <div className="gb-info"><i>{file.name}</i></div>; trackObj.type = 'signal'; trackObj.path = file.href; trackObj.heightPx = labelLength > 0 ? (defaultHeight + (extraLineHeight * labelLength)) : defaultHeight; trackObj.expandedHeightPx = extLabelLength > 0 ? (defaultExtHeight + (extraLineHeight * extLabelLength)) : defaultExtHeight; return trackObj; } if (file.file_format === 'bigWig') { const trackObj = {}; trackObj.name = <TrackLabel label={label} supplementalShortLabel={supplementalShortLabel} file={file} />; trackObj.longname = <TrackLabel label={label} file={file} long />; trackObj.type = 'signal'; trackObj.path = domain + file.href; trackObj.heightPx = labelLength > 0 ? (defaultHeight + (extraLineHeight * labelLength)) : defaultHeight; trackObj.expandedHeightPx = extLabelLength > 0 ? (defaultExtHeight + (extraLineHeight * extLabelLength)) : defaultExtHeight; return trackObj; } if (file.file_format === 'vdna-dir') { const trackObj = {}; trackObj.name = <ul className="gb-info"><li>{this.props.assembly.split(' ')[0]}</li></ul>; trackObj.type = 'sequence'; trackObj.path = file.href; trackObj.heightPx = 35; trackObj.expandable = false; return trackObj; } if (file.file_format === 'vgenes-dir') { const trackObj = {}; trackObj.name = <ul className="gb-info"><li>{file.title}</li></ul>; trackObj.type = 'annotation'; trackObj.path = file.href; trackObj.heightPx = 115; trackObj.expandable = false; trackObj.displayLabels = true; return trackObj; } if (file.title === 'representative DNase hypersensitivity sites' || file.title === 'cCRE, all') { const trackObj = {}; trackObj.name = <ul className="gb-info"><li>{file.title}</li></ul>; trackObj.type = 'annotation'; trackObj.path = file.href; trackObj.heightPx = file.title === 'representative DNase hypersensitivity sites' ? 50 : 30; trackObj.expandable = false; trackObj.displayLabels = false; return trackObj; } if (file.file_format === 'variant') { const trackObj = {}; trackObj.name = <ul className="gb-info"><li>{file.title}</li></ul>; trackObj.type = 'variant'; trackObj.path = file.href || file.path; // some titles like dBSNP set path trackObj.heightPx = 40; trackObj.expandable = true; trackObj.displayLabels = true; return trackObj; } const trackObj = {}; // bigBeds trackObj.name = <TrackLabel file={file} label={label} supplementalShortLabel={this.props.supplementalShortLabels && this.props.supplementalShortLabels[file.dataset]} />; trackObj.longname = <TrackLabel file={file} label={label} long />; trackObj.type = 'annotation'; trackObj.path = domain + file.href; trackObj.expandable = true; trackObj.displayLabels = false; trackObj.heightPx = labelLength > 0 ? (defaultHeight + (extraLineHeight * labelLength)) : defaultHeight; trackObj.expandedHeightPx = extLabelLength > 0 ? (defaultExtHeight + (extraLineHeight * extLabelLength)) : defaultExtHeight; trackObj.fileFormatType = file.file_format_type; // bigBed bedRNAElements, bigBed peptideMapping, bigBed bedExonScore, bed12, and bed9 have two tracks and need extra height // Convert to lower case in case of inconsistency in the capitalization of the file format in the data if (file.file_format_type && (['bedrnaelements', 'peptidemapping', 'bedexonscore', 'bed12', 'bed9'].indexOf(file.file_format_type.toLowerCase()) > -1)) { const openedOutputTypes = [ 'predicted transcription start sites', 'contigs', 'splice junctions', 'clusters', 'exon quantifications', 'unfiltered peptide quantification', 'filtered peptide quantification', ]; const opened = openedOutputTypes.includes(file.output_type); trackObj.name = <TrackLabel file={file} label={label} long={opened} />; trackObj.heightPx = opened ? 95 : trackObj.heightPx; } else if (file.output_type && file.output_type === 'guide locations') { trackObj.name = <TrackLabel file={file} label={label} long />; trackObj.heightPx = 95; } return trackObj; }); return tracks; } drawTracksResized() { if (this.chartdisplay) { this.state.visualizer.render({ width: this.chartdisplay.clientWidth, height: this.state.visualizer.getContentHeight(), }, this.chartdisplay); } } drawTracks(container) { const { contig, x0, x1, trackList } = this.state; const visualizer = new this.GV.GenomeVisualizer({ clampToTracks: true, reorderTracks: true, removableTracks: false, panels: [{ location: { contig, x0, x1 }, }], tracks: trackList, }); this.setState({ visualizer }); this.clearBrowserMemory(); visualizer.render({ width: this.chartdisplay.clientWidth, height: visualizer.getContentHeight(), }, container); visualizer.addEventListener('track-resize', this.drawTracksResized); window.addEventListener('resize', this.drawTracksResized); } resetLocation() { const { contig, x0, x1 } = getDefaultCoordinates(this.props.defaultLocation, this.state.genome, this.state.annotation, true); this.state.visualizer.setLocation({ contig, x0, x1 }); } render() { return ( <> {(this.state.trackList.length > 0 && this.state.genome !== null) ? <> <div className="gene-search"> <i className="icon icon-search" /> <div className="search-instructions">Search for a gene</div> <GeneSearch assembly={ getAssemblyWithoutGenomeAnnotationOrMinimal( this.props.assembly ) } handleClick={this.handleGeneSearchResultClick} /> </div> <div className="horizontal-control-container"> {this.props.displaySort ? <> <div className="sort-label">Sort by: </div> {this.props.sortParam.map((param, paramIdx) => <button type="button" className={`sort-button ${param === this.state.primarySort ? 'active' : ''}`} key={param.replace(/\s/g, '_')} onClick={() => this.sortAndRefresh(param, this.state.sortToggle[paramIdx], paramIdx, true)}><i className={this.state.sortToggle[paramIdx] ? 'tcell-desc' : 'tcell-asc'} /><div className="sort-label">{param}</div></button>)} </> : null} <GenomeLegend colorBlock={this.state.colorBlock} /> </div> <div className="browser-container"> <button type="button" className="reset-browser-button" onClick={this.resetLocation}> <i className="icon icon-undo" /> <span className="reset-title">Reset coordinates</span> </button> <div ref={(div) => { this.chartdisplay = div; }} className="valis-browser" /> </div> </> : <div className="browser-error valis-browser">There are no visualizable results.</div> } </> ); } } GenomeBrowser.propTypes = { files: PropTypes.array.isRequired, expanded: PropTypes.bool.isRequired, assembly: PropTypes.string.isRequired, annotation: PropTypes.string, label: PropTypes.string.isRequired, sortParam: PropTypes.array, displaySort: PropTypes.bool, maxCharPerLine: PropTypes.number, /** File's dataset @id map to supplemental label for that dataset */ supplementalShortLabels: PropTypes.object, defaultLocation: PropTypes.object, }; GenomeBrowser.defaultProps = { annotation: '', sortParam: ['Replicates', 'Output type'], // Array of parameters for sorting file object displaySort: false, // Determines if sort buttons should be displayed maxCharPerLine: null, supplementalShortLabels: {}, defaultLocation: null, }; GenomeBrowser.contextTypes = { location_href: PropTypes.string, navigate: PropTypes.func, fetch: PropTypes.func, }; export default GenomeBrowser;
src/docs/ComponentPage.js
tlraridon/ps-react-train-tlr
import React from 'react'; import PropTypes from 'prop-types'; import Example from './Example'; import Props from './Props'; const ComponentPage = ({component}) => { const {name, description, props, examples} = component; return ( <div className="componentpage"> <h2>{name}</h2> <p>{description}</p> <h3>Example{examples.length > 1 && "s"}</h3> { examples.length > 0 ? examples.map( example => <Example key={example.name} example={example} componentName={name} /> ) : "No examples exist." } <h3>Props</h3> { props ? <Props props={props} /> : "This component accepts no props." } </div> ) }; ComponentPage.propTypes = { component: PropTypes.object.isRequired }; export default ComponentPage;
app/screen/Login.js
shuiszhang/fanfou
/** * Created by shuis on 2017/5/27. */ import React, { Component } from 'react'; import { Button, View, Image, TextInput, StyleSheet } from 'react-native'; import Toast from 'react-native-root-toast'; import {auth} from '../api/api'; import {parse_auth} from '../util/util' class Login extends Component{ static navigationOptions = ({ navigation }) => ({ headerTitle: '登录' }); constructor(props){ super(props); this.state = { username: '', password: '', }; } _onChangeUsername = (value) => { this.setState({ username: value, }) }; _onChangePassword = (value) => { this.setState({ password: value, }) }; _onPress = async () => { try { console.log(this.state); let res = await auth(this.state); if (!res) { //登录失败 let toast = Toast.show('用户名或密码错误', { duration: Toast.durations.LONG, position: Toast.positions.BOTTOM, shadow: true, animation: true, hideOnPress: true, delay: 0, }); } else { //save token console.log('1111111'); console.log(res); console.log(parse_auth(res)); storage.save({ key: 'authToken', data: parse_auth(res), expires: null, }) } } catch (err) { let toast = Toast.show('用户名或密码错误', { duration: Toast.durations.LONG, position: Toast.positions.BOTTOM, shadow: true, animation: true, hideOnPress: true, delay: 0, }); console.log(err); if (err.status == '401') { //账号或密码错误 } } }; render(){ return ( <View> <View style={style.cell}> <Image source={require('../img/email.png')}/> <TextInput placeholder={'邮箱'} autoCapitalize={'none'} style={style.input} underlineColorAndroid="transparent" value={this.state.username} onChangeText={this._onChangeUsername}/> </View> <View style={style.cell}> <Image source={require('../img/password.png')}/> <TextInput placeholder={'密码'} autoCapitalize={'none'} style={style.input} underlineColorAndroid="transparent" value={this.state.password} onChangeText={this._onChangePassword}/> </View> <Button title="登录" onPress={this._onPress}/> </View> ) } } const style = StyleSheet.create({ cell: { flexDirection: 'row', alignItems: 'center', padding: 10, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: '#c7d0d5' }, input: { width:200, height:30, paddingLeft: 10, padding: 0, } }); export default Login;
examples/huge-apps/routes/Course/routes/Announcements/routes/Announcement/components/Announcement.js
limarc/react-router
import React from 'react'; class Announcement extends React.Component { render () { var { courseId, announcementId } = this.props.params; var { title, body } = COURSES[courseId].announcements[announcementId]; return ( <div> <h4>{title}</h4> <p>{body}</p> </div> ); } } export default Announcement;
src/parser/warlock/demonology/CHANGELOG.js
fyruna/WoWAnalyzer
import React from 'react'; import { Chizu, Gwelican } from 'CONTRIBUTORS'; import SpellLink from 'common/SpellLink'; import SPELLS from 'common/SPELLS'; export default [ { date: new Date('2019-04-03'), changes: <>Add <SpellLink id={SPELLS.DEMONIC_CONSUMPTION_TALENT.id} /> power tracker. </>, contributors: [Gwelican], }, { date: new Date('2019-04-02'), changes: 'Fixed a bug where pets showed up as they were summoned before the pull.', contributors: [Gwelican], }, { date: new Date('2018-12-29'), changes: 'Fixed a bug that caused a crash when player was wearing trinket that summons pets (like Vanquished Tendril of G\'huun).', contributors: [Chizu], }, { date: new Date('2018-12-23'), changes: <>Added support for <SpellLink id={SPELLS.BALEFUL_INVOCATION.id} /> trait. Also fixed <SpellLink id={SPELLS.DEMONBOLT.id} /> icon in Soul Shard tab. </>, contributors: [Chizu], }, { date: new Date('2018-12-23'), changes: 'Changed display of damage in various places. Now shows % of total damage done and DPS with raw values in tooltip.', contributors: [Chizu], }, { date: new Date('2018-12-10'), changes: 'Updated for patch 8.1 changes.', contributors: [Chizu], }, { date: new Date('2018-11-23'), changes: <>Fixed <SpellLink id={SPELLS.GRIMOIRE_FELGUARD_TALENT.id} /> cooldown</>, contributors: [Chizu], }, { date: new Date('2018-11-19'), changes: 'Consolidated various talent boxes into one Talents statistic box.', contributors: [Chizu], }, { date: new Date('2018-11-16'), changes: <>Added <SpellLink id={SPELLS.SACRIFICED_SOULS_TALENT.id} />, <SpellLink id={SPELLS.DEMONIC_CONSUMPTION_TALENT.id} /> and <SpellLink id={SPELLS.NETHER_PORTAL_TALENT.id} /> modules.</>, contributors: [Chizu], }, { date: new Date('2018-11-16'), changes: <>Added <SpellLink id={SPELLS.SOUL_CONDUIT_TALENT.id} /> and <SpellLink id={SPELLS.INNER_DEMONS_TALENT.id} /> modules. Fixed the Pet Timeline if it encounters an unknown pet.</>, contributors: [Chizu], }, { date: new Date('2018-11-16'), changes: <>Added talent modules for <SpellLink id={SPELLS.FROM_THE_SHADOWS_TALENT.id} />, <SpellLink id={SPELLS.SOUL_STRIKE_TALENT.id} /> and <SpellLink id={SPELLS.SUMMON_VILEFIEND_TALENT.id} />.</>, contributors: [Chizu], }, { date: new Date('2018-11-15'), changes: <>Added <SpellLink id={SPELLS.POWER_SIPHON_TALENT.id} /> talent module and modified <SpellLink id={SPELLS.DOOM_TALENT.id} /> module to also show damage done by the talent.</>, contributors: [Chizu], }, { date: new Date('2018-11-15'), changes: <>Updated Checklist rules and added talent modules for the first row - <SpellLink id={SPELLS.DREADLASH_TALENT.id} />, <SpellLink id={SPELLS.DEMONIC_STRENGTH_TALENT.id} /> and <SpellLink id={SPELLS.BILESCOURGE_BOMBERS_TALENT.id} /></>, contributors: [Chizu], }, { date: new Date('2018-11-15'), changes: <>Fixed <SpellLink id={SPELLS.DEMONIC_CALLING_TALENT.id} /> and <SpellLink id={SPELLS.GRIMOIRE_FELGUARD_TALENT.id} /> modules.</>, contributors: [Chizu], }, { date: new Date('2018-11-12'), changes: 'Certain buffs or debuffs now show in timeline.', contributors: [Chizu], }, { date: new Date('2018-11-10'), changes: <>Added a Pet Timeline tab, allowing you to see your demons' lifespans and highlighting important casts, such as <SpellLink id={SPELLS.NETHER_PORTAL_TALENT.id} />, <SpellLink id={SPELLS.SUMMON_DEMONIC_TYRANT.id} /> and <SpellLink id={SPELLS.IMPLOSION_CAST.id} />.</>, contributors: [Chizu], }, { date: new Date('2018-11-08'), changes: <>Reworked pet tracking system, fixed <SpellLink id={SPELLS.GRIMOIRE_FELGUARD_TALENT.id} /> talent module.</>, contributors: [Chizu], }, { date: new Date('2018-09-21'), changes: 'Removed all legendaries and tier set modules.', contributors: [Chizu], }, ];
examples/CardReveal.js
react-materialize/react-materialize
import React from 'react'; import Card from '../src/Card'; import CardTitle from '../src/CardTitle'; import Icon from '../src/Icon'; export default <Card header={<CardTitle reveal image={"img/office.jpg"} waves='light'/>} title="Card Title" reveal={<p>Here is some more information about this product that is only revealed once clicked on.</p>}> <p><a href="#">This is a link</a></p> </Card>;
src/App.js
betoesquivel/intertech-lenon-positweet-ui
import React, { Component } from 'react'; import logo from './logo.png'; import './App.css'; import Login from './Login.js'; class App extends Component { constructor() { super(); const current_url = typeof location !== 'undefined' ? location.toString() : ''; const queryMatch = current_url.match(/\?(.+)$/); window.queryMatch = queryMatch; const query = queryMatch !== null ? queryMatch[queryMatch.length-1].split("&") : ''; window.query = query; let parameters = {}; let parameter; for (var i = 0; i < query.length; i++) { parameter = query[i].split("="); if (parameter.length === 1) { parameter[1] = ""; } parameters[decodeURIComponent(parameter[0])] = decodeURIComponent(parameter[1]); } if (typeof parameters.oauth_verifier !== "undefined") { console.log(`Came from a callback with: ${JSON.stringify(parameters)}`); let cb = new window.Codebird(); cb.setConsumerKey(process.env.REACT_APP_CONSUMER_KEY, process.env.REACT_APP_CONSUMER_SECRET); if (typeof Storage !== 'undefined') { cb.setToken( localStorage.getItem('oauth_token'), localStorage.getItem('oauth_token_secret') ); cb.__call( "oauth_accessToken", { oauth_verifier: parameters.oauth_verifier }, function (reply) { cb.setToken(reply.oauth_token, reply.oauth_token_secret); console.log(`Done: ${JSON.stringify(reply)}`); if(localStorage.getItem("firebase:previous_websocket_failure")!=null) localStorage.getItem("firebase:previous_websocket_failure").toString(); else { localStorage.removeItem("firebase:previous_websocket_failure"); } window.firebase.database().ref('positweeters/' + reply.user_id).set({ token: reply.oauth_token, token_secret: reply.oauth_token_secret, screen_name: reply.screen_name }); window.cb = cb; const changeLoc = () => window.location = "https://positweet-ebff4.firebaseapp.com/?#"; setTimeout(changeLoc, 3000); } ); } else { console.log("ERROR: No local storage support"); } } } render() { return ( <div className="App" style={{display:'flex', flexDirection:'column', justifyContent:'space-between', height: '100%'}}> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> </div> <div className="container"> <div className="row"> <Login {...this.props} /> </div> </div> </div> ); } } export default App;
pgpilot-webapp/client/main.js
dperetti/PGPilot
import { Meteor } from 'meteor/meteor' // eslint-disable-line import React from 'react' import { render } from 'react-dom'; import PGNodes from './imports/PGNodes.jsx' import MainNavBar from './imports/NavBar.jsx' Meteor.startup(() => { // #Cypuu# render(<MainNavBar />, document.getElementById('navbar')); render(<PGNodes />, document.getElementById('nodes')); // We don't use React for the console at the moment, still use Blaze. // render(<Console />, document.getElementById("console")); });
InstitutionalApp/src/components/navBar.js
michelmarcondes/ReactNativeStudies
import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class NavBar extends Component { render() { return ( <View style={[styles.container, this.props.backgroundColor]}> <Text style={styles.title}>XYZ Consulting</Text> </View> ); } } const styles = StyleSheet.create({ container: { backgroundColor: '#ccc', padding: 10, paddingTop: 35, height: 80 }, title: { flex: 1, fontSize: 18, textAlign: 'center', color: '#000', fontWeight: 'bold' } });
src/HorizonGraph.js
ornl-sava/vis-react-components
import React from 'react' import PropTypes from 'prop-types' import { TransitionGroup } from 'react-transition-group' import * as d3 from 'd3' import { setEase } from './util/d3' import SVGComponent from './SVGComponent' import BrushX from './BrushX' class HorizonGraph extends React.Component { constructor (props) { super(props) this.onMouseMove = this.onMouseMove.bind(this) this.binarySearch = this.binarySearch.bind(this) this.xScale = null } onMouseMove (event) { let bounds = event.target.getBoundingClientRect() let x = event.clientX - bounds.left let target = this.xScale.invert(x) let index = this.binarySearch(target, 0, this.props.data.length - 1) if (index !== this.props.selectedIndex) { this.props.handleSelection(index) } } binarySearch (target, left, right) { let xAccess = this.props.xAccessor let data = this.props.data let mid = Math.floor((left + right) / 2) let min = xAccess(data[left], left) let max = xAccess(data[right], right) let lowDist = target - min let highDist = max - target let goLeft = lowDist <= highDist if (left === mid) { return goLeft ? left : right } else { return goLeft ? this.binarySearch(target, left, mid) : this.binarySearch(target, mid, right) } } render () { let data = this.props.data let numBands = this.props.numBands let xAccess = this.props.xAccessor let yAccess = this.props.yAccessor let w = this.props.chartWidth ? this.props.chartWidth : this.props.width let h = this.props.chartHeight ? this.props.chartHeight : this.props.height var xmin = Infinity var xmax = -Infinity var ymax = -Infinity let mid = this.props.mid ? this.props.mid : 0 data.map((d, i) => { let x = xAccess(d, i) let y = yAccess(d) - mid if (x < xmin) { xmin = x } if (x > xmax) { xmax = x } if (Math.abs(y) > ymax) { ymax = Math.abs(y) } }) if (this.props.domainHeight) { ymax = this.props.domainHeight } let xScale = d3.scaleLinear().domain([xmin, xmax]).range([0, w]) this.xScale = xScale let yScale = d3.scaleLinear().domain([0, ymax]).range([0, h * numBands]) let points = d3.area() .curve(d3.curveLinear) .x((d, i) => { return xScale(xAccess(d, i)) }) .y0(h * numBands) .y1((d) => { return h * numBands - yScale(yAccess(d) - mid) })(data) let levels = d3.range(-1, -numBands - 1, -1).concat(d3.range(1, numBands + 1)) let horizonTransform = this.props.mode === 'offset' ? (d) => { return 'translate(0,' + (d + (d < 0) - numBands) * h + ')' } : (d) => { return (d < 0 ? 'scale(1,-1)' : '') + 'translate(0,' + (d - numBands) * h + ')' } let colors = this.props.colors var color = d3.scaleLinear() .domain(numBands > 1 ? [-numBands, -1, 1, numBands] : [-1, 0, 0, 1]) .range(numBands > 1 ? colors : [colors[1], colors[0], colors[3], colors[2]]) var selectionX = null var labelX = null var labelText = null let si = this.props.selectedIndex if ((si || si === 0) && si < data.length) { selectionX = xScale(xAccess(data[si], si)) labelText = this.props.labelFormat(data[si]) let labelWidth = 7 * labelText.length if (w - selectionX < labelWidth + 5) { labelX = w - labelWidth - 5 } else { labelX = selectionX + 5 } } let pathTransition = { func: (transition, props) => { transition .delay(0) .duration(500) .ease(setEase('linear')) .attr('d', props.d) .attr('fill', props.fill) return transition } } let boxTransition = { func: (transition, props) => { transition .delay(0) .duration(500) .ease(setEase('linear')) .attr('x', props.x) .attr('y', props.y) .attr('width', props.width) .attr('height', props.height) .attr('fill', props.fill) return transition } } let lineTransition = { func: (transition, props) => { transition .delay(0) .duration(0) .ease(setEase('linear')) .attr('x1', props.x1) .attr('y1', props.y1) .attr('x2', props.x2) .attr('y2', props.y2) return transition } } let textTransition = { func: (transition, props) => { transition .delay(0) .duration(0) .ease(setEase('linear')) .attr('x', props.x) .attr('y', props.y) return transition } } let result = <TransitionGroup component='g'> <SVGComponent Component='svg' x={'0px'} y={'0px'} width={w + 'px'} height={h + 'px'} key='horizonSvg' onUpdate={boxTransition} onMouseMove={this.onMouseMove} > <SVGComponent Component='rect' x={'0px'} y={'0px'} width={w + 'px'} height={h + 'px'} fill={this.props.bgColor} key='horizonBackground' onUpdate={boxTransition} /> { levels.map((d) => { return ( <SVGComponent Component='path' key={'level-' + d} d={points} transform={horizonTransform(d)} fill={color(d)} onUpdate={pathTransition} /> ) }) } {selectionX !== null && <SVGComponent Component='g'> <SVGComponent Component='line' key='selectionLine' x1={selectionX} y1={0} x2={selectionX} y2={h} stroke='black' pointerEvents='none' onUpdate={lineTransition} /> <SVGComponent Component='text' key='selectionLabel' x={labelX} y={this.props.labelY} pointerEvents='none' onUpdate={textTransition} stroke={this.props.labelColor} fill={this.props.labelColor} fontSize={this.props.labelFontSize} >{labelText}</SVGComponent> </SVGComponent> } </SVGComponent> </TransitionGroup> if (this.props.brushID && data.length > 1) { let interval = Math.abs(xAccess(data[1]) - xAccess(data[0])) return ( <BrushX brushID={this.props.brushID} hideBrushSelection width={w} height={h} interval={interval} scale={xScale} onMouseMove={this.onMouseMove} onBrush={this.props.onBrush} > {result} </BrushX> ) } return result } } HorizonGraph.defaultProps = { mode: 'offset', numBands: 2, data: [], colors: ['#bdd7e7', '#08519c', '#006d2c', '#bae4b3'], bgColor: 'white', xAccessor: (d, i) => { return i }, yAccessor: (d) => { return d }, labelFormat: (d) => { return '' + d }, labelColor: 'black', labelFontSize: 12, labelY: 16, brushID: 'default', onBrush: () => {} } HorizonGraph.propTypes = { width: PropTypes.number, height: PropTypes.number, chartWidth: PropTypes.number, chartHeight: PropTypes.number, numBands: PropTypes.number, mode: PropTypes.string, data: PropTypes.array, colors: PropTypes.array, bgColor: PropTypes.string, xAccessor: PropTypes.func, yAccessor: PropTypes.func, mid: PropTypes.number, domainHeight: PropTypes.number, selectedIndex: PropTypes.number, handleSelection: PropTypes.func, labelFormat: PropTypes.func, labelColor: PropTypes.string, labelFontSize: PropTypes.number, labelY: PropTypes.number, brushID: PropTypes.string, onBrush: PropTypes.func } export default HorizonGraph
examples/huge-apps/components/Dashboard.js
zipongo/react-router
import React from 'react' import { Link } from 'react-router' class Dashboard extends React.Component { render() { const { courses } = this.props return ( <div> <h2>Super Scalable Apps</h2> <p> Open the network tab as you navigate. Notice that only the amount of your app that is required is actually downloaded as you navigate around. Even the route configuration objects are loaded on the fly. This way, a new route added deep in your app will not affect the initial bundle of your application. </p> <h2>Courses</h2>{' '} <ul> {courses.map(course => ( <li key={course.id}> <Link to={`/course/${course.id}`}>{course.name}</Link> </li> ))} </ul> </div> ) } } export default Dashboard
src/components/DraggableList.js
tuomashatakka/tool-bar-gui
'use babel' import React from 'react' import { CompositeDisposable, Disposable } from 'atom' import ListItem from '../components/ListItemComponent' import DisposableEvent from '../util/DisposableEvent' import prop from 'prop-types' const { abs, min, max, sqrt } = Math const SNAP_CLICK_DISTANCE = 4 let index let beginIndex let draggedItem let draggedElement let boundParent let subscriptions = new CompositeDisposable() let handleClick = () => {} let handleMove = () => {} let x = 0, y = 0, allowMove = false function getElementIndex (el, bounds) { if (!el) return bounds ? bounds[1] : 0 if (!bounds) bounds = [ 0, el.parentElement.childElementCount ] let group = [...el.parentElement.children] let index = group.findIndex(o => o == el) if (index === -1) index = bounds[1] return max(bounds[0], min(index, bounds[1])) } function onDragStart (item, event) { draggedElement = event.nativeEvent.path.find(o => o.tagName === 'LI') if (!draggedElement) return subscriptions.dispose() allowMove = false draggedItem = item boundParent = draggedElement.parentElement if (!boundParent) return beginIndex = getElementIndex(draggedElement) subscriptions = new CompositeDisposable() subscriptions.add( new Disposable(() => document.body.classList.remove('disable-selection')), new DisposableEvent(document, 'mouseup', onDragEnd), new DisposableEvent(document, 'mousemove', onDragMove), ) document.body.classList.add('disable-selection') event.preventDefault() } function onDragEnd (event) { event.preventDefault() subscriptions.dispose() if (allowMove) handleMove(draggedItem, index, beginIndex) else handleClick(draggedItem) allowMove = false draggedElement = null } function distance (x0, y0, x1, y1) { let x = abs(x1 - x0) let y = abs(y1 - y0) return sqrt(x * x + y * y) } function onDragMove (event) { if (!draggedElement) return let el = event.path.find(o => o.tagName==='LI') if (el && el.parentElement !== boundParent) return if (!allowMove) { let { clientX: x1, clientY: y1 } = event if (distance(x, y, x1, y1) > SNAP_CLICK_DISTANCE) allowMove = true } if (allowMove) { index = getElementIndex(el, [ 0, boundParent.childElementCount ]) try { boundParent.insertBefore(draggedElement, el) } catch (e) { boundParent.appendChild(draggedElement) } } event.preventDefault() } const ListComponent = ({ items, onMoveItem, onClick, onRemoveItem }) => { handleMove = onMoveItem handleClick = onClick return <ul className='select-list list-group padded'> {list( items, onDragStart, onRemoveItem )} </ul> } export const list = (items, onMouseDown, removeItem) => items.map((item, n) => <ListItem key={n} text={item.name} action={item.action} iconset={item.iconset} icon={item.icon} remove={removeItem.bind(null, item)} onMouseDown={onMouseDown.bind(null, item)} />) ListComponent.propTypes = { items: prop.oneOf([prop.array, prop.null]).isRequired, onRemoveItem: prop.func.isRequired, onMoveItem: prop.func.isRequired, onClick: prop.func.isRequired, } export default ListComponent
EventEmitter.Client/src/components/Header/Header.js
Stelmashenko-A/EventEmitter
import React from 'react' import { Link } from 'react-router' import './Header.scss' import { Header, Navigation } from 'react-mdl' export const EHeader = (props) => ( <Header title={<span><Link to='/'>Event Emitter</Link></span>}> <Navigation> <Link className={(!props.user.login ? '' : 'hidden')} to='/login' activeClassName='route--active'>Login</Link> <Link className={(props.user.login ? '' : 'hidden')} to='/newEvent' activeClassName='route--active'>New Event</Link> <Link className={(props.user.login ? '' : 'hidden')} to='/calendar' activeClassName='route--active'>New Event</Link> <Link className={(props.user.login ? '' : 'hidden')} to='/admin/users' activeClassName='route--active'>Administrate System</Link> <li className={(props.user.login ? '' : 'hidden')} onClick={props.logout}>Log Out</li> </Navigation> </Header> ) EHeader.propTypes = { switchMobileMenu: React.PropTypes.func.isRequired, header: React.PropTypes.bool.isRequired, user: React.PropTypes.object, logout: React.PropTypes.func.isRequired } export default EHeader
src/examples/example-toolbox/example-toolbox.js
smollweide/react-speed-dial
import React from 'react'; import PropTypes from 'prop-types'; import { grey800, grey200, teal300, cyan900 } from 'material-ui/styles/colors'; import IconPlay from 'material-ui/svg-icons/av/play-arrow'; import IconPause from 'material-ui/svg-icons/av/pause'; import IconRewind from 'material-ui/svg-icons/av/fast-rewind'; import IconForwards from 'material-ui/svg-icons/av/fast-forward'; import { BottomNavigation, BottomNavigationItem } from 'material-ui/BottomNavigation'; import transitions from 'material-ui/styles/transitions'; import { SpeedDial } from '../../speed-dial'; const list = { items: [ { id: '0', icon: <IconForwards color={cyan900} />, }, { id: '1', icon: <IconPause color={cyan900} />, }, { id: '2', icon: <IconRewind color={cyan900} />, }, ], }; const styles = { main: { margin: '0 0 50px 0', backgroundColor: '#23566a', height: 332, overflow: 'hidden', }, stage: { width: '100%', height: '200px', background: grey800, }, progress: { position: 'absolute', width: '100%', height: 16, top: -16, background: grey200, }, progressBar: { position: 'absolute', width: 2, left: '20%', height: '100%', background: '#245467', }, title: { transition: transitions.easeOut(), background: '#23566a', color: '#f2ffff', padding: '36px 24px', fontSize: 28, lineHeight: 1.1, minHeight: 60, }, titleOpen: { transition: transitions.easeOut(), background: '#23566a', color: '#f2ffff', padding: '26px 24px', minHeight: 24, }, }; const Toolbox = ({ onClickCloseToolbox }) => ( <div style={{ position: 'relative' }}> <div style={styles.progress}> <div style={styles.progressBar} /> </div> <BottomNavigation style={{ background: teal300 }}> {[] .concat(list.items) .reverse() .map(item => { return <BottomNavigationItem key={item.id} onClick={onClickCloseToolbox} {...item} />; })} </BottomNavigation> </div> ); Toolbox.propTypes = { onClickCloseToolbox: PropTypes.func, }; /** * Class ExampleToolbox */ class ExampleToolbox extends React.Component { /** * @param {Object} props - component props * @returns {void} */ constructor(props) { super(props); this.state = { isOpen: false, isInTransition: false, wasOpened: false, }; this.handleSpeedDialChangeState = this.handleSpeedDialChangeState.bind(this); } /** * @param {Object} newState - the new state * @returns {void} */ handleSpeedDialChangeState(newState) { this.setState(Object.assign({}, this.state, newState)); } /** * @returns {XML} returns the component */ render() { return ( <section style={{ maxWidth: 1024, margin: '0 auto' }}> <div style={styles.main}> <div style={styles.stage} /> <SpeedDial floatingActionButtonProps={{ backgroundColor: teal300, iconStyle: { fill: cyan900, }, }} icon={<IconPlay />} positionV="inline" toolbox={{ className: 'toolbox', classNameMorphButton: 'morph-btn', height: 56, }} onChangeState={this.handleSpeedDialChangeState} > <Toolbox /> </SpeedDial> <div style={this.state.isOpen ? styles.titleOpen : styles.title}>Kodaline / In A Perfect World</div> </div> </section> ); } } ExampleToolbox.displayName = 'ExampleToolbox'; export default ExampleToolbox;
src/components/Posts/Posts.js
jonirrings/react-stack
/** * react-stack react-stack * * Copyright © 2016. JonirRings. * * 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 PropTypes from 'prop-types'; import withStyle from 'isomorphic-style-loader/lib/withStyles'; import cx from 'classnames'; import Glance from '../Glance'; import s from './Posts.css'; import Footer from '../Footer'; const propTypes = { route: PropTypes.shape().isRequired, viewer: PropTypes.shape({ user: PropTypes.object, // eslint-disable-line react/no-unused-prop-types }).isRequired, }; function Posts(props) { const { viewer, route } = props; const postClass = route.path === 'posts' ? s.posts : cx(s.posts, s.init); return ( <div className={postClass}> <div className={s.postsContainer}> <ul className={s.postList}> { viewer.posts.edges.map(edge => <Glance post={edge.node} key={edge.cursor} />) } </ul> <Footer /> </div> </div> ); } Posts.propTypes = propTypes; export default withStyle(s)(Posts);
app/imports/client/Components/SearchInput/index.js
FractalFlows/Emergence
/* * Built by Astrocoders * @flow */ //Modules import React from 'react' import ReactDOM from 'react-dom' import { Meteor } from 'meteor/meteor' import styled from 'styled-components' import { CircularProgress } from 'material-ui' import SearchIcon from 'material-ui/svg-icons/action/search' import CloseIcon from 'material-ui/svg-icons/navigation/close' import { white, cyan500, grey100, grey200, grey400, grey500, grey800, } from 'material-ui/styles/colors' // Containers import { redux as SearchContainer } from '/imports/client/Pages/Search/container' // Components import ArticleItem from './article_item' // Styled Components const SearchInputWrapper = styled.div` background-color: ${grey100}; padding: 0 16px 0 10px; display: flex; alignItems: center; transition: .1s; &.focus { box-shadow: 0 1px 3px ${grey400}; background-color: ${white}; } ` const SearchInput = styled.input` flex-grow: 99999; padding: 15px 15px; border: none; background-color: transparent; color: ${grey800}; &:focus { outline: none; } ` const ResultsDropdown = styled.div` background-color: #FFF; width: 100%; position: absolute; top: calc(100% + 1px); box-shadow: 0 1px 3px ${grey400}; max-height: 500px; overflow-y: auto; ` const NoResults = styled.div` padding: 15px; display: block; ` class SearchInputHolder extends React.Component { constructor(props) { super(props) this.state = { showDropdown: false, } } render() { const { searchState, clearSearch, fetchSelectedArticle, } = this.props const { showDropdown } = this.state return ( <div style={{ width: '100%', position: 'relative', }} > <SearchInputWrapper ref="searchInputWrapper" className={showDropdown ? 'focus' : ''} > <SearchIcon color={grey500} style={{ height: 25, }} /> <SearchInput type="text" placeholder="Enter an article DOI, title, author or keywords" onInput={(event) => { const val = event.target.value if(!val){ this.props.clearSearch() } else { this.props.fetchSearch({ searchText: val }) } }} onKeyDown={this._searchSelect} onFocus={this.onFocus} onBlur={this.onBlur} disabled={searchState.isFetchingSelectedArticle} innerRef={ref => this.searchInputEl = ref} /> <CircularProgress size={17} thickness={2} color={cyan500} style={{ visibility: ( searchState.isSearching || searchState.isFetchingSelectedArticle )? 'visible' : 'hidden', marginRight: 7, }} /> <CloseIcon color={grey500} style={{ visibility: searchState.searchText ? 'visible' : 'hidden', cursor: 'pointer', height: 25, padding: 5, }} onClick={this.clearSearch} /> </SearchInputWrapper> <ResultsDropdown className="dropdown-article-list" style={{ display: showDropdown ? 'block' : 'none', }} > { searchState.articlesFromSearch.map(result => ( <ArticleItem key={result.DOI} info={result} searchText={searchState.searchText} onClick={() => fetchSelectedArticle({ DOI: result.DOI, source: result.source })} /> )) } {(searchState.searchText && searchState.articlesFromSearch.length === 0 && !searchState.isSearching) && ( <NoResults> <h5>No results</h5> </NoResults> )} </ResultsDropdown> </div> ) } onBlur = (event) => { this.props.onBlur && this.props.onBlur(event) setTimeout(() => this.setState({ showDropdown: false }), 100) } onFocus = (event) => { this.props.onFocus && this.props.onFocus(event) this.setState({ showDropdown: true }) } clearSearch = (event) => { this.searchInputEl.value = '' this.props.clearSearch() this.setState({ showDropdown: false }) } _searchSelect = ({ which: key }) => { //Arrow Down if (key === 40) { const hoveredResult = document.querySelector('.dropdown-article-item:hover') if (hoveredResult) return const currentResultSelected = document.querySelector('.dropdown-article-item.hover') if (currentResultSelected) { const { nextSibling } = currentResultSelected if (nextSibling) { currentResultSelected.classList.remove('hover') nextSibling.classList.add('hover') document.querySelector('.dropdown-article-list') .scrollTop = nextSibling.offsetTop } } else { const firstResult = document.querySelector('.dropdown-article-item') if (firstResult) { firstResult.classList.add('hover') document.querySelector('.dropdown-article-list').scrollTop = 0 } } //Arrow Up } else if (key === 38) { const currentResultSelected = document.querySelector('.dropdown-article-item.hover') if (currentResultSelected) { currentResultSelected.classList.remove('hover') const { previousSibling } = currentResultSelected if (previousSibling) { previousSibling.classList.add('hover') document.querySelector('.dropdown-article-list') .scrollTop = previousSibling.offsetTop } } //Enter } else if (key === 13) { const currentResultSelected = document.querySelector('.dropdown-article-item.hover a') if (currentResultSelected) { currentResultSelected.click() currentResultSelected.parentElement.classList.remove('hover') ReactDOM.findDOMNode(this.refs.searchInput).blur() } else if (!this.state.showDropdown) { this.setState({ showDropdown: true }) } //Esc } else if (key === 27) { if (this.state.showDropdown) { this.setState({ showDropdown: false }) } else { ReactDOM.findDOMNode(this.refs.searchInput).blur() } } } } export default SearchContainer(SearchInputHolder)
js/index.js
cotyembry/webpackBoilerplate
import React from 'react'; import ReactDOM from 'react-dom'; import $ from 'jquery'; import App from './components/App.jsx'; $(document).ready(function() { ReactDOM.render(<App />, document.getElementById('App')) })
app/javascript/mastodon/features/blocks/index.js
narabo/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import LoadingIndicator from '../../components/loading_indicator'; import { ScrollContainer } from 'react-router-scroll'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import AccountContainer from '../../containers/account_container'; import { fetchBlocks, expandBlocks } from '../../actions/blocks'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ heading: { id: 'column.blocks', defaultMessage: 'Blocked users' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'blocks', 'items']), }); class Blocks extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(fetchBlocks()); } handleScroll = (e) => { const { scrollTop, scrollHeight, clientHeight } = e.target; if (scrollTop === scrollHeight - clientHeight) { this.props.dispatch(expandBlocks()); } } render () { const { intl, accountIds } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column icon='ban' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollContainer scrollKey='blocks'> <div className='scrollable' onScroll={this.handleScroll}> {accountIds.map(id => <AccountContainer key={id} id={id} /> )} </div> </ScrollContainer> </Column> ); } } export default connect(mapStateToProps)(injectIntl(Blocks));
src/index.js
vxsx/nearest-color-app
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import 'react-toolbox/lib/commons'; ReactDOM.render(<App />, document.getElementById('root'));
app/components/Header/index.js
abasalilov/react-boilerplate
import React from 'react'; import { FormattedMessage } from 'react-intl'; import A from './A'; import Img from './Img'; import NavBar from './NavBar'; import HeaderLink from './HeaderLink'; import Banner from './banner.png'; import messages from './messages'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div className="headerLink1" style={{marginTop:'3rem'}}> <Img src={Banner} alt="react-boilerplate - Logo" /> <NavBar> <HeaderLink to="/"> <FormattedMessage {...messages.home} /> </HeaderLink> <HeaderLink className="headerLink2" to="/concepts"> <FormattedMessage {...messages.features} /> </HeaderLink> </NavBar> </div> ); } } export default Header;
src/svg-icons/action/stars.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionStars = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm4.24 16L12 15.45 7.77 18l1.12-4.81-3.73-3.23 4.92-.42L12 5l1.92 4.53 4.92.42-3.73 3.23L16.23 18z"/> </SvgIcon> ); ActionStars = pure(ActionStars); ActionStars.displayName = 'ActionStars'; ActionStars.muiName = 'SvgIcon'; export default ActionStars;
src/svg-icons/image/iso.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageIso = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5.5 7.5h2v-2H9v2h2V9H9v2H7.5V9h-2V7.5zM19 19H5L19 5v14zm-2-2v-1.5h-5V17h5z"/> </SvgIcon> ); ImageIso = pure(ImageIso); ImageIso.displayName = 'ImageIso'; ImageIso.muiName = 'SvgIcon'; export default ImageIso;
app/features/settings/device/panels/SettingsDevicePanelReconnecting.js
squatsandsciencelabs/OpenBarbellApp
import React, { Component } from 'react'; import { Text, View, Image } from 'react-native'; import { SETTINGS_PANEL_STYLES } from 'app/appearance/styles/GlobalStyles'; // displays connecting device info class SettingsDevicePanelReconnecting extends Component { render() { return ( <View style={ [SETTINGS_PANEL_STYLES.panel, { flex: 1 }] }> <View style={ SETTINGS_PANEL_STYLES.header }> <Text style={ SETTINGS_PANEL_STYLES.headerText }> Reconnecting... </Text> </View> <View style={ SETTINGS_PANEL_STYLES.content }> <Image source={require('app/appearance/images/icon_bluetooth_connecting.png')} /> </View> <View style={ SETTINGS_PANEL_STYLES.footer }> <Text style={ SETTINGS_PANEL_STYLES.footerCancelText } onPress={ () => this.props.stopReconnect() }> CANCEL </Text> </View> </View> ); } } export default SettingsDevicePanelReconnecting;
project-templates/reactfiber/externals/react-fiber/fixtures/fiber-debugger/src/index.js
ItsAsbreuk/itsa-cli
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
src/svg-icons/editor/border-left.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderLeft = (props) => ( <SvgIcon {...props}> <path d="M11 21h2v-2h-2v2zm0-4h2v-2h-2v2zm0-12h2V3h-2v2zm0 4h2V7h-2v2zm0 4h2v-2h-2v2zm-4 8h2v-2H7v2zM7 5h2V3H7v2zm0 8h2v-2H7v2zm-4 8h2V3H3v18zM19 9h2V7h-2v2zm-4 12h2v-2h-2v2zm4-4h2v-2h-2v2zm0-14v2h2V3h-2zm0 10h2v-2h-2v2zm0 8h2v-2h-2v2zm-4-8h2v-2h-2v2zm0-8h2V3h-2v2z"/> </SvgIcon> ); EditorBorderLeft = pure(EditorBorderLeft); EditorBorderLeft.displayName = 'EditorBorderLeft'; EditorBorderLeft.muiName = 'SvgIcon'; export default EditorBorderLeft;
web/src/components/Calendar/Popup.js
AcrylicInc/totalblu
import PropTypes from 'prop-types'; import React from 'react'; import getOffset from 'dom-helpers/query/offset'; import getScrollTop from 'dom-helpers/query/scrollTop'; import getScrollLeft from 'dom-helpers/query/scrollLeft'; import EventCell from 'components/Calendar/components/Events/EventCell'; import { isSelected } from './utils/selection'; import localizer from './localizer'; import { elementType, dateFormat } from './utils/propTypes'; const propTypes = { position: PropTypes.object, popupOffset: PropTypes.number, events: PropTypes.array, selected: PropTypes.object, eventComponent: elementType, eventWrapperComponent: elementType, dayHeaderFormat: dateFormat } class Popup extends React.Component { componentDidMount(){ let { popupOffset = 5 } = this.props , { top, left, width, height } = getOffset(this.refs.root) , viewBottom = window.innerHeight + getScrollTop(window) , viewRight = window.innerWidth + getScrollLeft(window) , bottom = top + height , right = left + width if (bottom > viewBottom || right > viewRight) { let topOffset, leftOffset; if (bottom > viewBottom) topOffset = bottom - viewBottom + (popupOffset.y || +popupOffset || 0) if (right > viewRight) leftOffset = right - viewRight + (popupOffset.x || +popupOffset || 0) this.setState({ topOffset, leftOffset }) //eslint-disable-line } } render() { let { events, selected, eventComponent, eventWrapperComponent, ...props } = this.props; let { left, width, top } = this.props.position , topOffset = (this.state || {}).topOffset || 0 , leftOffset = (this.state || {}).leftOffset || 0; let style = { top: top - topOffset, left: left - leftOffset, minWidth: width + (width / 2) } return ( <div ref='root' style={style} className='rbc-overlay'> <div className='rbc-overlay-header'> { localizer.format(props.slotStart, props.dayHeaderFormat, props.culture) } </div> { events.map((event, idx) => <EventCell key={idx} {...props} event={event} eventComponent={eventComponent} eventWrapperComponent={eventWrapperComponent} selected={isSelected(event, selected)} /> ) } </div> ) } } Popup.propTypes = propTypes; export default Popup;
frontend/src/js/app.js
terryx/react-gulp
'use strict'; import React from 'react'; import Main from './components/Main'; class App extends React.Component { constructor(props) { super(props); } componentWillMount() {} componentWillUnmount() {} componentDidMount() {} render() { return ( <div>Hello React World</div> ) } } React.render(<App/>, document.body);
src/components/Account/ResourceList/ListActions/index.js
ndlib/usurper
import React from 'react' import PropTypes from 'prop-types' import RenewButton from './RenewButton' import ExportButton from './ExportButton' import DeleteButton from './DeleteButton' import typeConstants from '../constants' import styles from './style.module.css' const ListActions = (props) => { const config = typeConstants[props.listType] return ( <div className={styles.itemListGlobalActions}> {config.renewButton && ( <RenewButton items={props.list} className={styles.globalRenew} /> )} {config.exportButton && ( <ExportButton items={props.list} className={styles.globalExport} /> )} {config.deleteButton && ( <DeleteButton items={props.list} className={styles.globalDelete} /> )} </div> ) } ListActions.propTypes = { list: PropTypes.array.isRequired, listType: PropTypes.string.isRequired, } export default ListActions
src/styles/Cards/cardClassName.js
GKotsovos/WebPoker
import React from 'react'; import classNames from 'classnames'; import Styles from './cards.css' const ranks = { 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, 11: 'J', 12: 'Q', 13:'K', 14: 'A' } export const cardClassName = { front: (rank, suit) => classNames( Styles.card, Styles['rank-' + rank.toString().toLowerCase()], Styles[suit], ), back: classNames(Styles.card, Styles.back), }; export default cardClassName;
src/components/MainNav/NavDivider/NavDivider.js
folio-org/stripes-core
import React from 'react'; import PropTypes from 'prop-types'; import css from './NavDivider.css'; const propTypes = { md: PropTypes.string, // Temporary as we work out the responsiveness of the header. }; function NavDivider(props) { function getClass() { const base = css.navDivider; const hide = props.md === 'hide' ? css.hideMed : null; return `${base} ${hide}`; } return <div className={getClass()} />; } NavDivider.propTypes = propTypes; export default NavDivider;
src/components/MobHeader/MobHeader.js
malinowsky/dataroot_03
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import Link from '../Link'; import s from './MobHeader.scss'; import logoUrl from './logo.png'; import logoUrl2x from './[email protected]'; class MobHeader extends React.Component { constructor(props) { super(props); this.state = { condition: false } this.showMenu = this.showMenu.bind(this); this.hideMenu = this.hideMenu.bind(this); } hideMenu = (e) => { this.setState({condition: false}) } showMenu = (e) => { this.setState({condition: true}) } render(){ return( <div className={s.mob_header}> <div className={this.state.condition ? s.show : s.hidden}> <div className={s.menuVertical}> <div className={s.cancel}> <button className={s.cancelBtn} onClick={this.hideMenu}> <span className={s.xLine}></span> <span className={s.xLine}></span> </button> </div> <div className={s.menuInfo}> <div className={s.header}> <img src={logoUrl} srcSet={`${logoUrl2x} 2x`} width="48px" height="133px" alt="Logo" /> <div className={s.card}> <h3 className={s.title}>Майстерня</h3> <a href="tel:+380664455900" className={s.contactNom}>+38 066 445 59 00</a> <div className={s.address}>м. Мукачево, вул. Переяславська, 1</div> </div> </div> <nav className={s.nav}> <ul> <li><Link className={s.link} to="/catalog">Каталог продукції</Link></li> <li><Link className={s.link} to="/about">Про нас</Link></li> <li><Link className={s.link} to="/gallery">Наші роботи</Link></li> </ul> </nav> </div> <div className={s.contactBtn}> <Link className={s.btn} to="/contact">Зв’язатись з нами</Link> </div> </div> </div> <h4><Link className={s.title} to="/">Майстерня</Link></h4> <button className={s.menuBtn} onClick={this.showMenu}> <span className={s.line}></span> <span className={s.line}></span> <span className={s.line}></span> </button> </div> ) } } export default withStyles(s)(MobHeader);
packages/react-router/modules/Switch.js
goblortikus/react-router
import React from 'react' import PropTypes from 'prop-types' import warning from 'warning' import matchPath from './matchPath' /** * The public API for rendering the first <Route> that matches. */ class Switch extends React.Component { static contextTypes = { router: PropTypes.shape({ route: PropTypes.object.isRequired }).isRequired } static propTypes = { children: PropTypes.node, location: PropTypes.object } componentWillReceiveProps(nextProps) { warning( !(nextProps.location && !this.props.location), '<Switch> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.' ) warning( !(!nextProps.location && this.props.location), '<Switch> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.' ) } render() { const { route } = this.context.router const { children } = this.props const location = this.props.location || route.location let match, child React.Children.forEach(children, element => { if (!React.isValidElement(element)) return const { path: pathProp, exact, strict, from } = element.props const path = pathProp || from if (match == null) { child = element match = path ? matchPath(location.pathname, { path, exact, strict }) : route.match } }) return match ? React.cloneElement(child, { location, computedMatch: match }) : null } } export default Switch
fields/components/columns/CloudinaryImageSummary.js
kumo/keystone
import React from 'react'; // import CloudinaryImage from 'react-cloudinary-img'; import ItemsTableValue from '../../../admin/client/components/ItemsTableValue'; const linkStyle = { marginRight: 8, }; const boxStyle = { borderRadius: 3, display: 'inline-block', height: 18, overflow: 'hidden', verticalAlign: 'middle', width: 18, }; const imageStyle = { display: 'block', height: 18, left: '50%', position: 'relative', WebkitTransform: 'translateX(-50%)', MozTransform: 'translateX(-50%)', msTransform: 'translateX(-50%)', transform: 'translateX(-50%)', }; const textStyle = { color: '#888', display: 'inline-block', fontSize: '.8rem', marginLeft: 8, verticalAlign: 'middle' }; var CloudinaryImageSummary = React.createClass({ displayName: 'CloudinaryImageSummary', propTypes: { label: React.PropTypes.oneOf(['dimensions', 'publicId']), image: React.PropTypes.object.isRequired, }, renderLabel () { if (!this.props.label) return; let { label, image } = this.props; let text; if (label === 'dimensions') { text = `${image.width} × ${image.height}`; } else { text = `${image.public_id}.${image.format}`; } return ( <span style={textStyle}> {text} </span> ); }, render () { let { image } = this.props; return ( <span style={linkStyle}> <span style={boxStyle}> <img src={image.url} style={imageStyle} /> </span> {this.renderLabel()} </span> ); } }); module.exports = CloudinaryImageSummary;
src/app/core/atoms/icon/icons/house.js
blowsys/reservo
import React from 'react'; const House = (props) => <svg {...props} viewBox="0 0 24 24"><g><g><polygon points="6.00058581 10.9998 6 11 6 19.9998 11 19.9998 11 16.0009 13 16.0009 13 19.9998 18 19.9998 18 11 17.9994142 10.9998 18.0027466 10.9998 12.0003 4.9998 6.0003 10.9998"/></g></g></svg>; export default House;
packages/react-native-renderer/src/ReactNativeComponent.js
TheBlasfem/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ import type { MeasureInWindowOnSuccessCallback, MeasureLayoutOnSuccessCallback, MeasureOnSuccessCallback, NativeMethods, ReactNativeBaseComponentViewConfig, } from './ReactNativeTypes'; import React from 'react'; // Modules provided by RN: import { TextInputState, UIManager, } from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'; import {create} from './ReactNativeAttributePayload'; import {mountSafeCallback_NOT_REALLY_SAFE} from './NativeMethodsMixinUtils'; import warningWithoutStack from 'shared/warningWithoutStack'; export default function( findNodeHandle: any => ?number, findHostInstance: any => any, ) { /** * Superclass that provides methods to access the underlying native component. * This can be useful when you want to focus a view or measure its dimensions. * * Methods implemented by this class are available on most default components * provided by React Native. However, they are *not* available on composite * components that are not directly backed by a native view. For more * information, see [Direct Manipulation](docs/direct-manipulation.html). * * @abstract */ class ReactNativeComponent<Props, State = void> extends React.Component< Props, State, > { /** * Due to bugs in Flow's handling of React.createClass, some fields already * declared in the base class need to be redeclared below. */ props: Props; state: State; /** * Removes focus. This is the opposite of `focus()`. */ blur(): void { TextInputState.blurTextInput(findNodeHandle(this)); } /** * Requests focus. The exact behavior depends on the platform and view. */ focus(): void { TextInputState.focusTextInput(findNodeHandle(this)); } /** * Measures the on-screen location and dimensions. If successful, the callback * will be called asynchronously with the following arguments: * * - x * - y * - width * - height * - pageX * - pageY * * These values are not available until after natives rendering completes. If * you need the measurements as soon as possible, consider using the * [`onLayout` prop](docs/view.html#onlayout) instead. */ measure(callback: MeasureOnSuccessCallback): void { let maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. try { maybeInstance = findHostInstance(this); } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. if (maybeInstance == null) { return; } if (maybeInstance.canonical) { // We can't call FabricUIManager here because it won't be loaded in paper // at initialization time. See https://github.com/facebook/react/pull/15490 // for more info. nativeFabricUIManager.measure( maybeInstance.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback), ); } else { UIManager.measure( findNodeHandle(this), mountSafeCallback_NOT_REALLY_SAFE(this, callback), ); } } /** * Measures the on-screen location and dimensions. Even if the React Native * root view is embedded within another native view, this method will give you * the absolute coordinates measured from the window. If successful, the * callback will be called asynchronously with the following arguments: * * - x * - y * - width * - height * * These values are not available until after natives rendering completes. */ measureInWindow(callback: MeasureInWindowOnSuccessCallback): void { let maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. try { maybeInstance = findHostInstance(this); } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. if (maybeInstance == null) { return; } if (maybeInstance.canonical) { // We can't call FabricUIManager here because it won't be loaded in paper // at initialization time. See https://github.com/facebook/react/pull/15490 // for more info. nativeFabricUIManager.measureInWindow( maybeInstance.node, mountSafeCallback_NOT_REALLY_SAFE(this, callback), ); } else { UIManager.measureInWindow( findNodeHandle(this), mountSafeCallback_NOT_REALLY_SAFE(this, callback), ); } } /** * Similar to [`measure()`](#measure), but the resulting location will be * relative to the supplied ancestor's location. * * Obtain a native node handle with `ReactNative.findNodeHandle(component)`. */ measureLayout( relativeToNativeNode: number | Object, onSuccess: MeasureLayoutOnSuccessCallback, onFail?: () => void /* currently unused */, ): void { let maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. try { maybeInstance = findHostInstance(this); } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. if (maybeInstance == null) { return; } if (maybeInstance.canonical) { warningWithoutStack( false, 'Warning: measureLayout on components using NativeMethodsMixin ' + 'or ReactNative.NativeComponent is not currently supported in Fabric. ' + 'measureLayout must be called on a native ref. Consider using forwardRef.', ); return; } else { let relativeNode; if (typeof relativeToNativeNode === 'number') { // Already a node handle relativeNode = relativeToNativeNode; } else if (relativeToNativeNode._nativeTag) { relativeNode = relativeToNativeNode._nativeTag; } if (relativeNode == null) { warningWithoutStack( false, 'Warning: ref.measureLayout must be called with a node handle or a ref to a native component.', ); return; } UIManager.measureLayout( findNodeHandle(this), relativeNode, mountSafeCallback_NOT_REALLY_SAFE(this, onFail), mountSafeCallback_NOT_REALLY_SAFE(this, onSuccess), ); } } /** * This function sends props straight to native. They will not participate in * future diff process - this means that if you do not include them in the * next render, they will remain active (see [Direct * Manipulation](docs/direct-manipulation.html)). */ setNativeProps(nativeProps: Object): void { // Class components don't have viewConfig -> validateAttributes. // Nor does it make sense to set native props on a non-native component. // Instead, find the nearest host component and set props on it. // Use findNodeHandle() rather than ReactNative.findNodeHandle() because // We want the instance/wrapper (not the native tag). let maybeInstance; // Fiber errors if findNodeHandle is called for an umounted component. // Tests using ReactTestRenderer will trigger this case indirectly. // Mimicking stack behavior, we should silently ignore this case. // TODO Fix ReactTestRenderer so we can remove this try/catch. try { maybeInstance = findHostInstance(this); } catch (error) {} // If there is no host component beneath this we should fail silently. // This is not an error; it could mean a class component rendered null. if (maybeInstance == null) { return; } if (maybeInstance.canonical) { warningWithoutStack( false, 'Warning: setNativeProps is not currently supported in Fabric', ); return; } const nativeTag = maybeInstance._nativeTag || maybeInstance.canonical._nativeTag; const viewConfig: ReactNativeBaseComponentViewConfig<> = maybeInstance.viewConfig || maybeInstance.canonical.viewConfig; const updatePayload = create(nativeProps, viewConfig.validAttributes); // Avoid the overhead of bridge calls if there's no update. // This is an expensive no-op for Android, and causes an unnecessary // view invalidation for certain components (eg RCTTextInput) on iOS. if (updatePayload != null) { UIManager.updateView( nativeTag, viewConfig.uiViewClassName, updatePayload, ); } } } // eslint-disable-next-line no-unused-expressions (ReactNativeComponent.prototype: NativeMethods); return ReactNativeComponent; }
webpack/ForemanTasks/Components/TaskDetails/Components/Raw.js
theforeman/foreman-tasks
import React from 'react'; import PropTypes from 'prop-types'; import { translate as __ } from 'foremanReact/common/I18n'; import { durationInWords } from './TaskHelper'; const Raw = ({ id, label, startedAt, endedAt, input, output, externalId }) => ( <div> <div> <span className="param-name list-group-item-heading">{__('Id')}:</span> <span className="param-value">{id}</span> </div> <div> <span className="param-name list-group-item-heading">{__('Label')}:</span> <span className="param-value">{label}</span> </div> <div> <span className="param-name list-group-item-heading"> {__('Duration')}: </span> <span className="param-value" title={durationInWords(startedAt, endedAt || new Date()).tooltip} > {durationInWords(startedAt, endedAt || new Date()).text} </span> </div> <div> <span className="param-name list-group-item-heading"> {__('Raw input')}: </span> <span className="param-value"> <pre>{JSON.stringify(input, null, ' ')}</pre> </span> </div> <div> <span className="param-name list-group-item-heading"> {__('Raw output')}: </span> <span className="param-value"> <pre>{JSON.stringify(output, null, ' ')}</pre> </span> </div> <div> <span className="param-name list-group-item-heading"> {__('External Id')}: </span> <span className="param-value">{externalId}</span> </div> </div> ); Raw.propTypes = { id: PropTypes.string, label: PropTypes.string, startedAt: PropTypes.string, endedAt: PropTypes.string, input: PropTypes.oneOfType([PropTypes.array, PropTypes.shape({})]), output: PropTypes.shape({}), externalId: PropTypes.string, }; Raw.defaultProps = { id: '', label: '', startedAt: '', endedAt: '', input: [], output: {}, externalId: '', }; export default Raw;
server/sonar-web/src/main/js/apps/permission-templates/app.js
abbeyj/sonarqube
import React from 'react'; import Main from './main'; import '../../helpers/handlebars-helpers'; window.sonarqube.appStarted.then(options => { var el = document.querySelector(options.el); React.render(<Main topQualifiers={options.rootQualifiers}/>, el); });
src/compos/Conversation.js
Blacktoviche/RNChat
import React, { Component } from 'react'; import { connect } from 'react-redux'; import uuid from 'react-native-uuid'; import * as backend from '../backend/Mediator'; import { sendTextMessage, setupConversation, addContact, changeReceiverContactStatus, showImageModal, hideImageModal, imageMessageTextChanged, sendImageMessage, startRecordingAudio, stopRecordingAudio, sendAudioMessage } from '../core/actions'; import { Container, Content, Header, Footer, Card, CardItem, ListItem, Item, Input, Icon, Button, Text, Left, Body, Right, Title, Spinner, Fab } from 'native-base'; import { Platform, View, StyleSheet, Modal, Image } from 'react-native'; import { GiftedChat, Actions, Bubble, InputToolbar } from 'react-native-gifted-chat'; import { MenuContext, Menu, MenuOptions, MenuOption, MenuTrigger, renderers } from 'react-native-popup-menu'; import ImagePicker from 'react-native-image-crop-picker'; import CustomMessage from './CustomMessage'; import * as CONSTANTS from '../utils/GlobaleStaticVars'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view' class Conversation extends Component { static navigationOptions = { title: ({ state }) => `${state.params.receiver.username}`, header: { visible: false } }; constructor(props) { super(props); this.renderCustomActions = this.renderCustomActions.bind(this); } componentWillMount() { const { uid, username } = this.props.navigation.state.params.receiver; let oldMsgs = backend.getMessages(this.props.loggedinUser.uid, uid); console.log('old messages: ' + oldMsgs.length); this.props.setupConversation(username, uid, GiftedChat, this.props.loggedinUser, oldMsgs); this.props.changeReceiverContactStatus(backend.isContact(uid)); const { email, photo } = this.props.navigation.state.params.receiver; this.props.addContact(uid, username, email, photo); } onSendTextMessage(messages = []) { const { loggedinUser, receiverUID, receiverName, networkStatus } = this.props; messages.forEach((message) => { message.title = receiverName; message.uidFrom = loggedinUser.uid; message.uidTo = receiverUID; this.props.sendTextMessage(message, networkStatus); }); } onSendImageMessage() { const { loggedinUser, receiverUID, receiverName, networkStatus } = this.props; let message = { _id: uuid.v4(), text: this.props.imageMessageText, createdAt: new Date(), user: { _id: 1, name: this.props.loggedinUser.username }, image: this.props.imagePath, imageName: this.props.imagePath.substring(this.props.imagePath.lastIndexOf('/') + 1), title: receiverName, uidFrom: loggedinUser.uid, uidTo: receiverUID }; this.props.sendImageMessage(message, networkStatus); } onAddContact() { //const { uid, username, email, photo } = this.props.navigation.state.params.receiver; //this.props.addContact(uid, username, email); } onOpenImagePicker() { console.log('image picker opens'); ImagePicker.openPicker({ width: 300, height: 400, mediaType: 'photo' }).then(image => { console.log(image); this.props.showImageModal(image.path); }).catch(err => { console.log('cancel image picker: ' + err); }); } onOpenCameraPicker() { console.log('camera picker opens'); ImagePicker.openCamera({ width: 300, height: 400, mediaType: 'photo' }).then(image => { console.log(image); this.props.showImageModal(image.path); }).catch(err => { alert('Camera use permission required!'); console.log('cancel image picker: ' + err); }); } onOpenVideoPicker() { console.log('video picker opens'); ImagePicker.openPicker({ width: 300, height: 400, }).then(video => { console.log(video); //this.props.showImageModal(video.path); }).catch(err => { console.log('cancel video picker: ' + err); }); } onOpenVideoCameraPicker() { console.log('video camera picker opens'); ImagePicker.openCamera({ width: 300, height: 400, mediaType: 'video' }).then(video => { console.log(video); //this.props.showImageModal(video.path); }).catch(err => { alert('Camera use permission required!'); console.log('cancel video picker: ' + err); }); } onRecordingAudio() { console.log('on recording audio'); if (this.props.recordStatus === CONSTANTS.RECORD_STATUS_STARTED) { this.props.stopRecordingAudio(); } else if (this.props.recordStatus === CONSTANTS.RECORD_STATUS_STOPED) { this.props.startRecordingAudio(); } } renderAttachmentButton() { return (<Button onPress={this.onOpenImagePicker.bind(this)}> <Icon name='attach' /> </Button>); } onCloseImageModal() { this.props.hideImageModal(); } onImageMessageTextChanged(imageMessageText) { this.props.imageMessageTextChanged(imageMessageText); } renderCustomActions(props) { if (this.props.recordStatus == CONSTANTS.RECORD_STATUS_STARTED) { return (<Button onPress={this.onRecordingAudio.bind(this)} danger> <Icon name="ios-recording" /> </Button >); } else if (this.props.recordStatus == CONSTANTS.RECORD_STATUS_HOLD) { return (<Button onPress={this.onRecordingAudio.bind(this)} dark> <Icon name="ios-stopwatch" /> </Button >); } else if (this.props.recordStatus == CONSTANTS.RECORD_STATUS_STOPED) { return (<Button onPress={this.onRecordingAudio.bind(this)} success> <Icon name="microphone" /> </Button >); } } renderProgress(props) { return ( <CustomMessage {...props} /> ); } renderBubble(props) { return ( <Bubble {...props} wrapperStyle={{ left: { backgroundColor: '#f0f0f0', } }} /> ); } renderToolbar(props) { if (this.props.isRecording === true) { return (<Input></Input>); } else { return ( <InputToolbar {...props} /> ); } } /** * <MenuOption onSelect={() => this.onOpenVideoCameraPicker()} customStyles={{ flex: 1, alignItems: 'center', }}> <Icon name='ios-videocam' /> </MenuOption> <MenuOption onSelect={() => this.onOpenVideoPicker()} customStyles={{ flex: 1, alignItems: 'center', }}> <Icon name='ios-videocam' /> </MenuOption> */ render() { const { uid, username, email } = this.props.navigation.state.params.receiver; return ( <MenuContext customStyles={menuContextStyles} render={renderers.SlideInMenu}> <Container> <Header> <Left> <Button transparent onPress={() => this.props.navigation.goBack()}> <Icon name='arrow-back' /> </Button> </Left> <Body> <Title>{username}</Title> </Body> <Right> <Menu> <MenuTrigger customStyles={{ flex: 1 }}> <Icon name='ios-attach' /> </MenuTrigger> <MenuOptions customStyles={optionsStyles}> <MenuOption onSelect={() => this.onOpenCameraPicker()} customStyles={{ flex: 1, alignItems: 'center', }}> <Icon name='ios-camera' /> </MenuOption> <MenuOption onSelect={() => this.onOpenImagePicker()} customStyles={{ flex: 1, alignItems: 'center', }}> <Icon name='ios-photos' /> </MenuOption> </MenuOptions> </Menu> </Right> </Header> <Modal animationType={"slide"} transparent={true} visible={this.props.imageModalVisible} onRequestClose={() => { this.onCloseImageModal() }}> <KeyboardAwareScrollView> <View style={imageModalStyle}> <Image source={{ uri: this.props.imagePath }} style={imagePreviewStyle} resizeMode='contain' /> <View style={imageViewStyle}> <Input style={inputTextStyle} placeholder='Type a message..' value={this.props.imageMessageText} onChangeText={this.onImageMessageTextChanged.bind(this)} /> <Button style={{ flex: 2 }} rounded outline light bordered onPress={() => this.onSendImageMessage()}> <Text style={{ alignItems: 'center' }}>Send</Text> <Icon name='ios-send' /> </Button> </View> </View> </KeyboardAwareScrollView> </Modal> <GiftedChat messages={this.props.messages} onSend={this.onSendTextMessage.bind(this)} user={{ _id: 1, name: this.props.loggedinUser.username }} //renderBubble={this.renderBubble} renderCustomView={this.renderProgress} //renderInputToolbar={this.renderToolbar} renderActions={this.renderCustomActions} /> </Container> </MenuContext> ); } } const optionsStyles = { optionsContainer: { padding: 5, width: 50, flexDirection: 'row', borderRadius: 10, borderWidth: 1, borderColor: '#fff' }, optionsWrapper: { }, optionWrapper: { margin: 5, }, optionTouchable: { activeOpacity: 70, }, optionText: { }, }; const styles = StyleSheet.create({ footerContainer: { marginTop: 5, marginLeft: 10, marginRight: 10, marginBottom: 10, }, footerText: { fontSize: 14, color: '#aaa', }, container: { flexDirection: 'row', }, backdrop: { opacity: 0.5, }, }); const inputTextStyle = { flex: 10, borderBottomWidth: 1, marginLeft: 4, color: 'white' }; const imagePreviewStyle = { width: 300, height: 400, flex: 8, alignItems: 'center' }; const imageViewStyle = { flex: 2, flexDirection: 'row' }; const imageModalStyle = { flex: 1, flexDirection: 'column', alignItems: 'center', backgroundColor: 'rgba(0,0,0,0.7)' } const menuContextStyles = { menuContextWrapper: styles.container, backdrop: styles.backdrop, }; const mapStateToProps = ({ conversReducer }) => { const { currentChat, typingText, messages, message, receiverName, receiverUID, isContact, loggedinUser, networkStatus, imageModalVisible, imagePath, imageMessageText, viewProgress, recordStatus } = conversReducer; return { currentChat, typingText, messages, message, receiverName, receiverUID, isContact, loggedinUser, networkStatus, imageModalVisible, imagePath, imageMessageText, viewProgress, recordStatus }; }; export default connect(mapStateToProps, { sendTextMessage, setupConversation, addContact, changeReceiverContactStatus, showImageModal, hideImageModal, imageMessageTextChanged, sendImageMessage, startRecordingAudio, stopRecordingAudio, sendAudioMessage })(Conversation);
app/src/components/Technologies/TechnologyGridItem.js
RyanCCollins/ryancollins.io
import React, { Component } from 'react'; import { Column, Thumbnail } from 'react-foundation'; import './TechnologyGridItem.scss'; import elementInViewport from '../../../lib/isVisible'; class TechnologyGridItem extends Component { constructor(props) { super(props); this.state = { needsAnimation: true, isAnimating: false, animationName: 'isFading' }; this.handleScroll = this.handleScroll.bind(this); } componentDidMount() { window.addEventListener('scroll', this.handleScroll) } componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll); } handleScroll(event) { const selector = `technology-grid-item-${this.props.technology.id}`; const element = document.getElementById(selector); if (elementInViewport(element)) { if (this.state.needsAnimation === true) { this.setState({ needsAnimation: false, isAnimating: true }); } } } render() { const { technology } = this.props; return ( <Column isColumn className="technology-grid-item-wrapper"> <div className={ this.state.isAnimating ? `callout technology-grid-item ${this.state.animationName}` : 'callout technology-grid-item' } id={`technology-grid-item-${technology.id}`} > <Thumbnail className="technology-grid-item__image" src={technology.imageUrl} /> <h4 className="technology-grid-item__caption">{technology.name}</h4> </div> </Column> ); } } export default TechnologyGridItem;
src/modules/Register/components/RegisterType.js
hdngr/mantenuto
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import Helmet from 'react-helmet'; import RegisterForm from './RegisterForm'; import { register, login } from '../redux'; import { notifSend } from '../../Notifs/redux'; // import { getCodes } from './redux'; @connect(null, { push, notifSend, register, login }) export default class RegisterType extends Component { static propTypes = { location: PropTypes.object.isRequired, register: PropTypes.func.isRequired, notifSend: PropTypes.func.isRequired, push: PropTypes.func.isRequired } componentDidMount() { // this.props.getCodes(); } getInitialValues = () => { const { location } = this.props; return location.state && location.state.oauth; } register = data => { const newUser = data; newUser.verification = data.verification[0]; this.props.register(data) .then(this.success) }; success = () => { this.props.notifSend({ message: 'You\'re now registered !', kind: 'success', dismissAfter: 5000 }); this.props.push('/registered'); } render() { const styles = require('./RegisterType.scss'); return ( <div className={styles.wrapper}> <Helmet title="Register" /> <div className={styles.masthead}> <div className={styles.width}> <h1 className={styles.heading}>Register</h1> <RegisterForm onSubmit={this.register} initialValues={this.getInitialValues()} /> </div> </div> </div> ); } }
pages/404.js
Kudrik/ReactTest
import React, { Component } from 'react'; import AffiliateScheme from '../components/AffiliateScheme'; import Terms from '../components/Terms'; import Link from '../components/Link'; export default class extends Component { render() { return ( <div> <AffiliateScheme /> <h1>Not Found</h1> <p> The page you're looking for was not found.<br /> <Link to='/' href='/'>Your profile</Link> </p> <Terms /> </div> ); } }
docs/src/PageFooter.js
thealjey/react-bootstrap
import React from 'react'; import packageJSON from '../../package.json'; let version = packageJSON.version; if (/docs/.test(version)) { version = version.split('-')[0]; } const PageHeader = React.createClass({ render() { return ( <footer className="bs-docs-footer" role="contentinfo"> <div className="container"> <div className="bs-docs-social"> <ul className="bs-docs-social-buttons"> <li> <iframe className="github-btn" src="https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=watch&count=true" width={95} height={20} title="Star on GitHub" /> </li> <li> <iframe className="github-btn" src="https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=fork&count=true" width={92} height={20} title="Fork on GitHub" /> </li> <li> <iframe src="https://platform.twitter.com/widgets/follow_button.html?screen_name=react_bootstrap&show_screen_name=true" width={230} height={20} allowTransparency="true" frameBorder="0" scrolling="no"> </iframe> </li> </ul> </div> <p>Code licensed under <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/LICENSE" target="_blank">MIT</a>.</p> <ul className="bs-docs-footer-links muted"> <li>Currently v{version}</li> <li>·</li> <li><a href="https://github.com/react-bootstrap/react-bootstrap/">GitHub</a></li> <li>·</li> <li><a href="https://github.com/react-bootstrap/react-bootstrap/issues?state=open">Issues</a></li> <li>·</li> <li><a href="https://github.com/react-bootstrap/react-bootstrap/releases">Releases</a></li> </ul> </div> </footer> ); } }); export default PageHeader;
apps/react-redux/components/NotFound.js
router5/examples
import React from 'react'; export default function NotFound(props) { return <div className='not-found'>Purposely Not found (not a bug)</div>; }
app/main.js
shawnxusy/git-dashboard
import React from 'react'; import Router from 'react-router'; import ReactDOM from 'react-dom'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import routes from './routes'; import Navbar from './components/Navbar'; let history = createBrowserHistory(); ReactDOM.render(<Router history={history}>{routes}</Router>, document.getElementById('app'));
cache/react-native-example/App.js
sharkspeed/dororis
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class App extends React.Component { render() { return ( <View style={styles.container}> <Text>Open up App.js to start working on your app!</Text> <Text>Changes you make will automatically reload.</Text> <Text>Shake your phone to open the developer menu.</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, });
react_lifecycle_sample/setup.js
devSC/react-native
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import LifecycleComponent from './LifecycleComponent' export default class setup extends Component { constructor(props) { super(props) this.state= { remove: false } } render() { var view = this.state.remove ? null : <LifecycleComponent/>; var text = this.state.remove ? "复活" : "销毁"; return ( <View style={styles.container}> <Text style={{fontSize: 20}} onPress={()=>{ this.setState({ remove: !this.state.remove }) }} >{text}</Text> {view} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF', marginTop: 64 }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
app/javascript/mastodon/features/ui/components/bundle_modal_error.js
mstdn-jp/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import IconButton from '../../../components/icon_button'; const messages = defineMessages({ error: { id: 'bundle_modal_error.message', defaultMessage: 'Something went wrong while loading this component.' }, retry: { id: 'bundle_modal_error.retry', defaultMessage: 'Try again' }, close: { id: 'bundle_modal_error.close', defaultMessage: 'Close' }, }); class BundleModalError extends React.PureComponent { static propTypes = { onRetry: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, } handleRetry = () => { this.props.onRetry(); } render () { const { onClose, intl: { formatMessage } } = this.props; // Keep the markup in sync with <ModalLoading /> // (make sure they have the same dimensions) return ( <div className='modal-root__modal error-modal'> <div className='error-modal__body'> <IconButton title={formatMessage(messages.retry)} icon='refresh' onClick={this.handleRetry} size={64} /> {formatMessage(messages.error)} </div> <div className='error-modal__footer'> <div> <button onClick={onClose} className='error-modal__nav onboarding-modal__skip' > {formatMessage(messages.close)} </button> </div> </div> </div> ); } } export default injectIntl(BundleModalError);
src/index.js
natcreates/react-learning
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; // BrowserRouter talks to the History library, which parses changes in url // Route is a React component we render inside React components that tells // React-router which url its display corresponds to import { BrowserRouter, Route, Switch } from 'react-router-dom'; import promise from 'redux-promise'; import PostsIndex from './container/PostsIndex'; import PostsNew from './components/PostsNew'; import PostsShow from './components/PostsShow'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(promise)(createStore); // the Switch component from React-router // looks at routes and will render the first matching url // this means you need the most specific at the top // otherwise React-router uses fuzzy matching, so will render root // as well as others with forward slashes // note that react-router will pass whatever the wildcard is - :id - as prop ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <div> <Switch> <Route path="/posts/new" component={PostsNew}/> <Route path="/posts/:id" component={PostsShow}/> <Route path="/" component={PostsIndex}/> </Switch> </div> </BrowserRouter> </Provider> , document.querySelector('.container'));
app/containers/HomePage/index.js
hukid/litaff
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/svg-icons/hardware/mouse.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareMouse = (props) => ( <SvgIcon {...props}> <path d="M13 1.07V9h7c0-4.08-3.05-7.44-7-7.93zM4 15c0 4.42 3.58 8 8 8s8-3.58 8-8v-4H4v4zm7-13.93C7.05 1.56 4 4.92 4 9h7V1.07z"/> </SvgIcon> ); HardwareMouse = pure(HardwareMouse); HardwareMouse.displayName = 'HardwareMouse'; HardwareMouse.muiName = 'SvgIcon'; export default HardwareMouse;
src/server/index.js
sanchitgangwar/remind-plus
import express from 'express'; // import exphbs from 'express-handlebars'; // import React from 'react'; // import { renderToString } from 'react-dom/server'; // import { RouterContext, match } from 'react-router'; // import { Provider } from 'react-redux'; // import thunkMiddleware from 'redux-thunk'; // import { createStore, applyMiddleware } from 'redux'; // import path from 'path'; import fetch from 'node-fetch'; // import favicon from 'serve-favicon'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import bunyan from 'bunyan'; import logger from 'express-bunyan-logger'; import apiEndpoints from './api'; import authMiddleware from './authMiddleware'; // import routes from '../client/routes'; // import rootReducer from '../client/reducers'; // import initializeStore from '../client/stores/initializeStore'; const log = bunyan.createLogger({ name: 'app' }); global.fetch = fetch; const app = express(); // app.use(favicon(path.resolve('./assets/icons/favicon-96x96.png'))); // Change Default template engine to handlebars for res.render app.use(express.static('dist/')); // app.engine('.hbs', exphbs({ // extname: '.hbs' // })); // app.set('views', path.join('../../dist')); // app.set('view engine', '.hbs'); app.use(logger({ name: 'app' })); app.disable('x-powered-by'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(cookieParser()); app.use((req, res, next) => { res.header('Cache-Control', 'private, no-cache, must-revalidate'); res.header('Control-Security-Policy', 'default-src "self";'); res.header('X-Frame-Options', 'SAMEORIGIN'); res.header('Strict-Transport-Security', 'max-age=31536000;preload'); res.header('X-Content-Type-Options', 'nosniff'); next(); }); app.use('/api', authMiddleware); app.use('/api', apiEndpoints); app.use('*', express.static('dist/')); // The handler for page requests // app.use((req, res) => { // const store = createStore( // rootReducer, // applyMiddleware(thunkMiddleware) // ); // res.header('X-Frame-Options', 'SAMEORIGIN'); // try { // match( // { routes, location: req.url }, // (error, redirectLocation, renderProps) => { // if (error) { // res.send(500); // } else if (redirectLocation) { // res.redirect(302, redirectLocation.pathname + redirectLocation.search); // } else if (renderProps) { // store.dispatch(initializeStore(req)).then(() => { // const InitialView = ( // <Provider store={store}> // <RouterContext {...renderProps} /> // </Provider> // ); // const componentHTML = renderToString(InitialView); // const initialState = store.getState(); // return { // html: componentHTML, // initialState: initialState && JSON.stringify(initialState) || '{}', // title: 'Gamoly' // }; // }) // .then((data) => res.status(200).render('index.hbs', data)) // .catch((err) => { // req.log.error('Error: ', err); // }); // } // } // ); // } catch (exception) { // req.log.error('exception: ', exception); // } // }); const PORT = process.env.PORT || 12000; app.listen(PORT, () => { log.info(`Server listening on port ${PORT}`); });