path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
examples/count-undo/index.js
cycgit/dva
import React from 'react'; import dva from '../../src/index'; import { connect } from '../../index'; import { Router, Route, useRouterHistory } from '../../router'; import { createHashHistory } from 'history'; import undoable, { ActionCreators } from 'redux-undo'; // 1. Initialize const app = dva({ onReducer: reducer => { return (state, action) => { const undoOpts = {}; const newState = undoable(reducer, undoOpts)(state, action); return { ...newState, routing: newState.present.routing }; }; }, }); // 2. Model app.model({ namespace: 'count', state: 0, reducers: { add (count) { return count + 1 }, minus(count) { return count - 1 }, }, }); // 3. View const App = connect(state => ({ count: state.present.count, }))(function(props) { return ( <div> <h2>{ props.count }</h2> <button key="add" onClick={() => { props.dispatch({type: 'count/add'})}}>+</button> <button key="minus" onClick={() => { props.dispatch({type: 'count/minus'})}}>-</button> <button key="undo" onClick={() => { props.dispatch(ActionCreators.undo())}}>undo</button> </div> ); }); // 4. Router app.router(({ history }) => <Router history={history}> <Route path="/" component={App} /> </Router> ); // 5. Start app.start('#root');
src/frontend/src/components/GMUser.js
blengerich/GenAMap
import React from 'react' import AppBar from 'material-ui/AppBar' import IconMenu from 'material-ui/IconMenu' import MenuItem from 'material-ui/MenuItem' import IconButton from 'material-ui/IconButton' import FontIcon from 'material-ui/FontIcon' var GMUser = React.createClass({ render: function () { return ( <AppBar title={this.props.user} showMenuIconButton={false} /> ) } }) export default GMUser
packages/mcs-lite-ui/src/LazyloadOnce/LazyloadOnce.js
MCS-Lite/mcs-lite
/* global window */ import React from 'react'; import PropTypes from 'prop-types'; import Waypoint from 'react-waypoint'; import rafThrottle from 'raf-throttle'; class LazyloadOnce extends React.PureComponent { static propTypes = { children: PropTypes.node, height: PropTypes.number, component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), waypointConfig: PropTypes.object, }; static defaultProps = { component: 'div', waypointConfig: { topOffset: -500, bottomOffset: -500, fireOnRapidScroll: true, }, }; state = { isShow: false }; componentWillUnmount = () => this.onEnter.cancel(); onEnter = rafThrottle(() => { if (!this.state.isShow) this.setState({ isShow: true }); }); render() { const { children, height, component: Component, waypointConfig, ...otherProps } = this.props; const { isShow } = this.state; const { onEnter } = this; return ( <Component style={{ height }} {...otherProps}> {isShow ? ( children ) : ( <Waypoint scrollableAncestor={window} onEnter={onEnter} {...waypointConfig} /> )} </Component> ); } } export default LazyloadOnce;
src/app/Home.js
cityofasheville/coa-converse
import React from 'react'; import { Query, Mutation } from 'react-apollo'; import EmployeeHome from './EmployeeHome'; import LoadingAnimation from '../shared/LoadingAnimation'; import Error from '../shared/Error'; import { UPDATE_AUTHMODAL } from '../utilities/auth/graphql/authMutations'; import { getUser } from '../utilities/auth/graphql/authQueries'; const Homepage = props => ( <Query query={getUser}> {({ loading, error, data }) => { if (loading) return <LoadingAnimation />; if (error) return <Error message={error.message} />; if (!data.user.loggedIn) { return ( <Mutation mutation={UPDATE_AUTHMODAL}> {updateAuthModal => ( <div> Welcome to City of Asheville Employee Check-in. Please&nbsp; <a href="#" onClick={(e) => { e.preventDefault(); updateAuthModal({ variables: { open: true, }, }); }} className="" >log in</a>. <p><span style={{ color: '#ef6601', fontStyle: 'italic' }}>Remember to use Chrome or Firefox. IE is not yet supported.</span></p> </div> )} </Mutation> ); } if (data.user.loggedIn && !data.user.email.endsWith('ashevillenc.gov')) { return (<div>Invalid user</div>); } return (<EmployeeHome {...props} />); }} </Query> ); export default Homepage;
src/js/screens/Text.js
grommet/next-sample
import React from 'react'; import { Box, Text } from 'grommet'; import doc from 'grommet/components/Text/doc'; import Doc from '../components/Doc'; const desc = doc(Text).toJSON(); export default () => ( <Doc name='Text' desc={desc}> <Box pad='large'> <Text size='xsmall'>Text XSmall</Text> <Text size='small'>Text Small</Text> <Text size='medium'>Text Medium</Text> <Text size='large'>Text Large</Text> <Text size='xlarge'>Text XLarge</Text> <Text size='xxlarge'>Text XXLarge</Text> <Text color='status-critical'>status-critical</Text> </Box> </Doc> );
packages/@lyra/imagetool/example/src/ImageToolDemo.js
VegaPublish/vega-studio
import PropTypes from 'prop-types' import React from 'react' import Preview from './Preview' import ImageSelector from './ImageSelector' import ImageTool from '../../src' import IMAGES from './data/testImages' const PREVIEW_ASPECT_RATIOS = [ ['None (default)', undefined], ['Auto', 'auto'], ['Landscape', 16 / 9], ['Square', 1], ['Wide', 4], ['Portrait', 9 / 16] ].map(([title, aspect]) => ({title, aspect})) export default class ImageToolDemo extends React.PureComponent { static propTypes = { src: PropTypes.string.isRequired } state = { value: { hotspot: { x: 0.5, y: 0.5, height: 0.9, width: 0.9 }, crop: { top: 0.0, bottom: 0.0, left: 0.0, right: 0.0 } } } handleHotspotChange = event => { const target = event.currentTarget const property = target.getAttribute('data-property') const {value} = this.state const newHotspot = Object.assign(value.hotspot, { [property]: Number(target.value) }) this.setState({value: Object.assign({}, value, {hotspot: newHotspot})}) } handleCropChange = event => { const target = event.currentTarget const property = target.getAttribute('data-property') const {value} = this.state const newCrop = Object.assign(value.crop, { [property]: Number(target.value) }) this.setState({value: Object.assign({}, value, {crop: newCrop})}) } handleChange = newValue => { this.setState({value: newValue}) } renderPreview = aspectRatio => { const {value} = this.state const {src} = this.props const previewStyle = aspectRatio.aspect === 'auto' ? {height: 150, width: 200, display: 'inline-block'} : {} return ( <div> <h3>{aspectRatio.title}</h3> <div style={{...previewStyle, outline: '1px solid #eee'}}> <Preview src={src} aspectRatio={aspectRatio.aspect} hotspot={value.hotspot} crop={value.crop} /> </div> </div> ) } render() { const value = this.state.value const {src} = this.props const HOTSPOT_WIDTH = 400 const thumbWidth = (HOTSPOT_WIDTH - IMAGES.length * 4) / IMAGES.length return ( <div style={{width: '100%', margin: 15, clear: 'both'}}> <div style={{float: 'left'}}> <div style={{height: 200, width: HOTSPOT_WIDTH}}> <ImageTool value={value} src={src} onChange={this.handleChange} /> </div> <div style={{width: HOTSPOT_WIDTH, outline: '1px dotted #aaa'}}> <ImageSelector thumbWidth={thumbWidth} images={IMAGES} /> </div> <h2>Hotspot</h2> <label> x: <this.range value={value.hotspot.x} onChange={this.handleHotspotChange} property="x" /> </label> <label> y: <this.range value={value.hotspot.y} onChange={this.handleHotspotChange} property="y" /> </label> <label> height: <this.range value={Math.abs(value.hotspot.height)} onChange={this.handleHotspotChange} property="height" /> </label> <label> width: <this.range value={Math.abs(value.hotspot.width)} onChange={this.handleHotspotChange} property="width" /> </label> <h2>Crop</h2> <label> left: <this.range value={value.crop.left} onChange={this.handleCropChange} property="left" /> </label> <label> right: <this.range value={value.crop.right} onChange={this.handleCropChange} property="right" /> </label> <label> top: <this.range value={value.crop.top} onChange={this.handleCropChange} property="top" /> </label> <label> bottom: <this.range value={value.crop.bottom} onChange={this.handleCropChange} property="bottom" /> </label> <h2>Value</h2> <pre>{JSON.stringify(value, null, 2)}</pre> </div> <div style={{padding: 5, margin: 5, float: 'left'}}> <ul className="previews"> {PREVIEW_ASPECT_RATIOS.map((aspectRatio, i) => { return <li key={i}>{this.renderPreview(aspectRatio)}</li> })} </ul> </div> </div> ) } range(props) { return ( <input value={props.value} type="range" min="0" max="1" step="0.001" onChange={props.onChange} data-property={props.property} /> ) } }
node_modules/enzyme/src/version.js
paul-brabet/tinkerlist
import React from 'react'; export const VERSION = React.version; const [major, minor] = VERSION.split('.'); export const REACT013 = VERSION.slice(0, 4) === '0.13'; export const REACT014 = VERSION.slice(0, 4) === '0.14'; export const REACT15 = major === '15'; export const REACT155 = REACT15 && minor >= 5;
src/index.js
flydev-labs/react-face-detector
import React from 'react'; import { render } from 'react-dom'; import './css/styles.css'; import './css/spinner.css'; import App from './components/App'; render(<App/>, document.querySelector('#main'));
app/components/TopBar.js
wbowling/deciderer
import React from 'react' import Reflux from 'reflux' import { History } from 'react-router' import { Navbar, Nav, NavBrand, Button } from 'react-bootstrap' import LoginStore from '../stores/LoginStore' import LoginActions from '../actions/LoginActions' import PollStore from '../stores/PollStore' import debug from '../constants/debug' const TopBar = React.createClass({ mixins: [ Reflux.listenTo(LoginStore, 'onLoginChange'), Reflux.listenTo(PollStore, 'onPollChange'), History ], getInitialState() { return { email: LoginStore.getEmail(), loggedIn: LoginStore.isLoggedIn(), admin: PollStore.isAdmin() } }, render() { let adminButton if (false && this.state.admin) { adminButton = <Button onClick={this.edit} eventKey={1}>Edit</Button> } else { adminButton = <span /> } return (<Navbar inverse toggleNavKey={0}> <NavBrand> {this.state.email ? this.state.email : 'Guest (login to create/vote)'} {PollStore.isAdmin() ? ' (Poll admin)' : ''} </NavBrand> <Nav right eventKey={0}> <form className="navbar-form navbar-left"> <Button bsStyle="success" onClick={this.createPoll} eventKey={1}>Create</Button> {adminButton} <Button onClick={this.toggleLogin} eventKey={1}>{this.state.loggedIn ? 'Logout' : 'Login'}</Button> </form> </Nav> </Navbar>) }, toggleLogin(e) { e.preventDefault() if (this.state.loggedIn) { LoginActions.logout() } else { LoginActions.login() } e.target.blur() }, createPoll(e) { e.preventDefault() this.history.pushState(null, '/') e.target.blur() }, onLoginChange(data) { debug.log('onLoginChange', data) this.setState({ email: data.email, loggedIn: data.loggedIn, admin: PollStore.isAdmin() }) }, onPollChange(data) { debug.log('onPollChange', data) this.setState({ admin: PollStore.isAdmin() }) } }) export default TopBar
assets/js/components/MkdirModal.js
basarevych/webfm
import React from 'react'; import PropTypes from 'prop-types'; import { Map } from 'immutable'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import { Form, FormGroup, Label, Col, Input } from 'reactstrap'; import RequiredFieldLabel from './RequiredFieldLabel'; import FormMessages from './FormMessages'; import FieldErrors from './FieldErrors'; class MkdirModal extends React.Component { static propTypes = { isOpen: PropTypes.bool.isRequired, isLocked: PropTypes.bool.isRequired, values: PropTypes.instanceOf(Map).isRequired, messages: PropTypes.instanceOf(Map).isRequired, errors: PropTypes.instanceOf(Map).isRequired, onToggle: PropTypes.func.isRequired, onInput: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { isOpen: props.isOpen, isLocked: props.isLocked, ignoreBlur: true, nextFocus: null, }; this.shareInput = React.createRef(); this.directoryInput = React.createRef(); this.nameInput = React.createRef(); this.handleInput = this.handleInput.bind(this); this.handleKeyPress = this.handleKeyPress.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } static getDerivedStateFromProps(nextProps, prevState) { let state = {}; if (nextProps.isOpen !== prevState.isOpen) state.isOpen = nextProps.isOpen; if (nextProps.isLocked !== prevState.isLocked) state.isLocked = nextProps.isLocked; if (state.isOpen === true) { state.nextFocus = 'name'; } else if (state.isLocked === false) { if (nextProps.errors.has('name')) state.nextFocus = 'name'; } return _.keys(state).length ? state : null; } handleInput(event) { if (this.props.isLocked) return; this.props.onInput({ [event.target.name]: event.target.value }); } handleKeyPress(event) { if (this.props.isLocked || event.charCode !== 13) // enter return; switch (event.target.name) { case 'share': if (this.directoryInput.current) setTimeout(() => this.directoryInput.current.focus(), 0); break; case 'directory': if (this.nameInput.current) setTimeout(() => this.nameInput.current.focus(), 0); break; case 'name': this.handleSubmit(); break; } } handleFocus() { if (this.props.isLocked) return; this.setState({ ignoreBlur: false }); } handleBlur(event) { if (this.props.isLocked || this.state.ignoreBlur) return; let submittedAt = Date.now(); let field = event.target.name; setTimeout( () => { if (this.props.isLocked || this.state.ignoreBlur) return; this.props.onSubmit(submittedAt, field); }, 250 ); } handleSubmit() { if (this.props.isLocked) return; this.setState({ ignoreBlur: true }); this.props.onSubmit(Date.now()); } componentDidUpdate() { if (this.state.nextFocus) { let field = this.state.nextFocus; this.setState({ nextFocus: null }, () => { switch (field) { case 'share': if (this.shareInput.current) setTimeout(() => this.shareInput.current.focus(), 0); break; case 'directory': if (this.directoryInput.current) setTimeout(() => this.directoryInput.current.focus(), 0); break; case 'name': if (this.nameInput.current) setTimeout(() => this.nameInput.current.focus(), 0); break; } }); } } render() { return ( <Modal isOpen={this.props.isOpen} toggle={this.props.onToggle} backdrop="static" fade centered > <ModalHeader toggle={this.props.onToggle}>{__('mkdir_title')}</ModalHeader> <ModalBody> <Form> <FormMessages messages={this.props.messages} /> <FormGroup row> <Label for="mkdirShare" sm={4} className="text-sm-right"> {__('share_label')} </Label> <Col sm={8}> <Input type="text" name="share" id="mkdirShare" disabled={true} invalid={this.props.errors.has('share')} value={this.props.values.get('share')} onKeyPress={this.handleKeyPress} onFocus={this.handleFocus} onBlur={this.handleBlur} innerRef={this.shareInput} /> <FieldErrors errors={this.props.errors.get('share')} /> </Col> </FormGroup> <FormGroup row> <Label for="mkdirDirectory" sm={4} className="text-sm-right"> {__('directory_label')} </Label> <Col sm={8}> <Input type="text" name="directory" id="mkdirDirectory" disabled={true} invalid={this.props.errors.has('directory')} value={this.props.values.get('directory')} onKeyPress={this.handleKeyPress} onFocus={this.handleFocus} onBlur={this.handleBlur} innerRef={this.directoryInput} /> <FieldErrors errors={this.props.errors.get('directory')} /> </Col> </FormGroup> <FormGroup row> <Label for="mkdirName" sm={4} className="text-sm-right"> {__('name_label')} <RequiredFieldLabel /> </Label> <Col sm={8}> <Input type="text" name="name" id="mkdirName" disabled={this.props.isLocked} invalid={this.props.errors.has('name')} value={this.props.values.get('name')} onChange={this.handleInput} onKeyPress={this.handleKeyPress} onFocus={this.handleFocus} onBlur={this.handleBlur} innerRef={this.nameInput} /> <FieldErrors errors={this.props.errors.get('name')} /> </Col> </FormGroup> </Form> </ModalBody> <ModalFooter> <Button color="secondary" disabled={this.props.isLocked} onClick={this.props.onToggle}> {__('cancel_button')} </Button> &nbsp; <Button color="primary" disabled={this.props.isLocked} onClick={this.handleSubmit}> {__('submit_button')} </Button> </ModalFooter> </Modal> ); } } export default MkdirModal;
components/card/CardText.js
jasonleibowitz/react-toolbox
import React from 'react'; import PropTypes from 'prop-types'; import { themr } from 'react-css-themr'; import classnames from 'classnames'; import { CARD } from '../identifiers.js'; const CardText = ({ children, className, theme, ...other }) => ( <div className={classnames(theme.cardText, className)} {...other}> {typeof children === 'string' ? <p>{children}</p> : children} </div> ); CardText.propTypes = { children: PropTypes.any, className: PropTypes.string, theme: PropTypes.shape({ cardText: PropTypes.string }) }; export default themr(CARD)(CardText); export { CardText };
src/Alert.js
jamon/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Alert = React.createClass({ mixins: [BootstrapMixin], propTypes: { onDismiss: React.PropTypes.func, dismissAfter: React.PropTypes.number }, getDefaultProps() { return { bsClass: 'alert', bsStyle: 'info' }; }, renderDismissButton() { return ( <button type="button" className="close" onClick={this.props.onDismiss} aria-hidden="true"> &times; </button> ); }, render() { let classes = this.getBsClassSet(); let isDismissable = !!this.props.onDismiss; classes['alert-dismissable'] = isDismissable; return ( <div {...this.props} className={classNames(this.props.className, classes)}> {isDismissable ? this.renderDismissButton() : null} {this.props.children} </div> ); }, componentDidMount() { if (this.props.dismissAfter && this.props.onDismiss) { this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter); } }, componentWillUnmount() { clearTimeout(this.dismissTimer); } }); export default Alert;
src/js/components/RoutedAnchor/RoutedAnchor.js
grommet/grommet
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Anchor } from '../Anchor'; class RoutedAnchor extends Component { static contextTypes = { router: PropTypes.shape({}).isRequired, }; static defaultProps = { method: 'push', }; render() { const { path, method, ...rest } = this.props; if (process.env.NODE_ENV !== 'production') { console.warn( `This component will be deprecated in the upcoming releases. Please refer to https://github.com/grommet/grommet/issues/2855 for more information.`, ); } return ( <Anchor {...rest} href={path} onClick={(event, ...args) => { const { onClick } = this.props; const { router } = this.context; if (event) { const modifierKey = event.ctrlKey || event.metaKey; // if the user right-clicked in the Anchor we should let it go if (modifierKey) { return; } } if (router) { event.preventDefault(); (router.history || router)[method](path); } if (onClick) { onClick(event, ...args); } }} /> ); } } export { RoutedAnchor };
app/javascript/mastodon/features/ui/util/react_router_helpers.js
glitch-soc/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { Switch, Route } from 'react-router-dom'; import ColumnLoading from '../components/column_loading'; import BundleColumnError from '../components/bundle_column_error'; import BundleContainer from '../containers/bundle_container'; // Small wrapper to pass multiColumn to the route components export class WrappedSwitch extends React.PureComponent { render () { const { multiColumn, children } = this.props; return ( <Switch> {React.Children.map(children, child => React.cloneElement(child, { multiColumn }))} </Switch> ); } } WrappedSwitch.propTypes = { multiColumn: PropTypes.bool, children: PropTypes.node, }; // Small Wrapper to extract the params from the route and pass // them to the rendered component, together with the content to // be rendered inside (the children) export class WrappedRoute extends React.Component { static propTypes = { component: PropTypes.func.isRequired, content: PropTypes.node, multiColumn: PropTypes.bool, componentParams: PropTypes.object, }; static defaultProps = { componentParams: {}, }; renderComponent = ({ match }) => { const { component, content, multiColumn, componentParams } = this.props; return ( <BundleContainer fetchComponent={component} loading={this.renderLoading} error={this.renderError}> {Component => <Component params={match.params} multiColumn={multiColumn} {...componentParams}>{content}</Component>} </BundleContainer> ); } renderLoading = () => { return <ColumnLoading />; } renderError = (props) => { return <BundleColumnError {...props} />; } render () { const { component: Component, content, ...rest } = this.props; return <Route {...rest} render={this.renderComponent} />; } }
js/components/signup/index.js
ChiragHindocha/stay_fit
import React, { Component } from 'react'; import { StatusBar, View, Image, TextInput, TouchableOpacity } from 'react-native'; import { connect } from 'react-redux'; import { Container, Header, Title, Content, Text, H3, Button, Icon, Footer, FooterTab, Left, Right, Body } from 'native-base'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; import { Actions } from 'react-native-router-flux'; const background = require("../../../img/fitness_bg.jpg"); const backIcon = require("../../../img/back.png"); const personIcon = require("../../../img/signup_person.png"); const lockIcon = require("../../../img/signup_lock.png"); const emailIcon = require("../../../img/signup_email.png"); class SignUp extends Component { static propTypes = { openDrawer: React.PropTypes.func, } render() { return ( <View style={styles.container}> <Image source={background} style={[styles.container, styles.bg]} resizeMode="cover" > <View style={styles.headerContainer}> <View style={styles.headerIconView}> <TouchableOpacity onPress={() => { Actions['home'](); }} style={styles.headerBackButtonView}> <Image source={backIcon} style={styles.backButtonIcon} resizeMode="contain" /> </TouchableOpacity> </View> <View style={styles.headerTitleView}> <Text style={styles.titleViewText}>Sign Up</Text> </View> </View> <View style={styles.inputsContainer}> <View style={styles.inputContainer}> <View style={styles.iconContainer}> <Image source={personIcon} style={styles.inputIcon} resizeMode="contain" /> </View> <TextInput style={[styles.input, styles.whiteFont]} placeholder="Name" placeholderTextColor="#FFF" underlineColorAndroid='transparent' /> </View> <View style={styles.inputContainer}> <View style={styles.iconContainer}> <Image source={emailIcon} style={styles.inputIcon} resizeMode="contain" /> </View> <TextInput style={[styles.input, styles.whiteFont]} placeholder="Email" placeholderTextColor="#FFF" keyboardType="email-address" /> </View> <View style={styles.inputContainer}> <View style={styles.iconContainer}> <Image source={lockIcon} style={styles.inputIcon} resizeMode="contain" /> </View> <TextInput secureTextEntry={true} style={[styles.input, styles.whiteFont]} placeholder="Password" placeholderTextColor="#FFF" /> </View> </View> <View style={styles.footerContainer}> <TouchableOpacity onPress={() => { Actions['basicTab'](); }}> <View style={styles.signup}> <Text style={styles.whiteFont}>Join</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={() => { Actions['home'](); }}> <View style={styles.signin}> <Text style={styles.greyFont}>Already have an account?<Text style={styles.whiteFont}> Sign In</Text></Text> </View> </TouchableOpacity> </View> </Image> </View> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(SignUp);
src/containers/App/index.js
nickjvm/grommet-color-contrast
import React from 'react'; import Main from 'containers/Main'; import SampleComponent from 'components/SampleComponent'; import 'grommet/scss/hpe/index.scss'; export default function App() { return ( <Main> <SampleComponent /> </Main> ); }
app/javascript/mastodon/features/explore/suggestions.js
koba-lab/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import AccountCard from 'mastodon/features/directory/components/account_card'; import LoadingIndicator from 'mastodon/components/loading_indicator'; import { connect } from 'react-redux'; import { fetchSuggestions } from 'mastodon/actions/suggestions'; const mapStateToProps = state => ({ suggestions: state.getIn(['suggestions', 'items']), isLoading: state.getIn(['suggestions', 'isLoading']), }); export default @connect(mapStateToProps) class Suggestions extends React.PureComponent { static propTypes = { isLoading: PropTypes.bool, suggestions: ImmutablePropTypes.list, dispatch: PropTypes.func.isRequired, }; componentDidMount () { const { dispatch } = this.props; dispatch(fetchSuggestions(true)); } render () { const { isLoading, suggestions } = this.props; return ( <div className='explore__suggestions'> {isLoading ? <LoadingIndicator /> : suggestions.map(suggestion => ( <AccountCard key={suggestion.get('account')} id={suggestion.get('account')} /> ))} </div> ); } }
src/svg-icons/av/add-to-queue.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvAddToQueue = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-7v2h-3v3h-2v-3H8v-2h3V7h2v3h3z"/> </SvgIcon> ); AvAddToQueue = pure(AvAddToQueue); AvAddToQueue.displayName = 'AvAddToQueue'; AvAddToQueue.muiName = 'SvgIcon'; export default AvAddToQueue;
actor-apps/app-web/src/app/components/common/Banner.react.js
liruqi/actor-platform
import React from 'react'; import BannerActionCreators from 'actions/BannerActionCreators'; class Banner extends React.Component { constructor(props) { super(props); if (window.localStorage.getItem('banner_jump') === null) { BannerActionCreators.show(); } } onClose = () => { BannerActionCreators.hide(); }; onJump = (os) => { BannerActionCreators.jump(os); this.onClose(); }; render() { return ( <section className="banner"> <p> Welcome to <b>Actor Network</b>! Check out our <a href="//actor.im/ios" onClick={this.onJump.bind(this, 'IOS')} target="_blank">iPhone</a> and <a href="//actor.im/android" onClick={this.onJump.bind(this, 'ANDROID')} target="_blank">Android</a> apps! </p> <a className="banner__hide" onClick={this.onClose}> <i className="material-icons">close</i> </a> </section> ); } } export default Banner;
src/components/routes/ImageAndTextTemplate.js
sievins/sarahs-footsteps
import React from 'react' import PropTypes from 'prop-types' import withClearDiv from 'components/with-clear-div' import grid from 'styles/grid.scss' import styles from './ImageAndTextTemplate.scss' ImageAndTextTemplate.propTypes = { img: PropTypes.shape({ src: PropTypes.string.isRequired, alt: PropTypes.string.isRequired, }).isRequired, Text: PropTypes.func.isRequired, } function ImageAndTextTemplate({ img, Text }) { return withClearDiv( <div> <img className={`${grid.col4} ${styles.img}`} src={img.src} alt={img.alt} /> <div className={grid.col8}> <Text /> </div> </div>, ) } export default ImageAndTextTemplate
src/Row.js
pandoraui/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import CustomPropTypes from './utils/CustomPropTypes'; const Row = React.createClass({ propTypes: { /** * You can use a custom element for this component */ componentClass: CustomPropTypes.elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { let ComponentClass = this.props.componentClass; return ( <ComponentClass {...this.props} className={classNames(this.props.className, 'row')}> {this.props.children} </ComponentClass> ); } }); export default Row;
src/components/navigation/Header/Header.js
cltk/cltk_frontend
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; // components import NavBar from './NavBar'; import LeftMenu from '../LeftMenu'; // actions import * as authActions from '../../../modules/auth/actions'; const Header = ({ toggleAuthModal, userId }) => ( <div> <LeftMenu /> <NavBar toggleAuthModal={toggleAuthModal} userId={userId} /> </div> ); Header.propTypes = { toggleAuthModal: PropTypes.func.isRequired, userId: PropTypes.string, }; Header.defaultProps = { userId: null }; const mapStateToProps = state => ({ userId: state.auth.userId, }); const mapDispatchToProps = dispatch => ({ toggleAuthModal: (e) => { e.preventDefault(); dispatch(authActions.toggleAuthModal()); }, }); export default connect( mapStateToProps, mapDispatchToProps )(Header);
src/svg-icons/communication/business.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationBusiness = (props) => ( <SvgIcon {...props}> <path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z"/> </SvgIcon> ); CommunicationBusiness = pure(CommunicationBusiness); CommunicationBusiness.displayName = 'CommunicationBusiness'; CommunicationBusiness.muiName = 'SvgIcon'; export default CommunicationBusiness;
admin/src/components/ItemsTableCell.js
wustxing/keystone
import React from 'react'; var ItemsTableCell = React.createClass({ displayName: 'ItemsTableCell', propTypes: { className: React.PropTypes.string, }, render () { let className = 'ItemList__col' + (this.props.className ? (' ' + this.props.className) : ''); return ( <td {...this.props} className={className} /> ); } }); module.exports = ItemsTableCell;
src/svg-icons/navigation/chevron-right.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationChevronRight = (props) => ( <SvgIcon {...props}> <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/> </SvgIcon> ); NavigationChevronRight = pure(NavigationChevronRight); NavigationChevronRight.displayName = 'NavigationChevronRight'; NavigationChevronRight.muiName = 'SvgIcon'; export default NavigationChevronRight;
src/common/components/OutlineButton.js
skallet/este
// @flow import type { ButtonProps } from './Button'; import React from 'react'; import Button from './Button'; const OutlineButton = (props: ButtonProps) => ( <Button // TODO: Recheck after Flow 0.38, propValues should not be required. gray={true} // eslint-disable-line react/jsx-boolean-value outline={true} // eslint-disable-line react/jsx-boolean-value textStyle={theme => ({ color: theme.colors.black })} {...props} /> ); export default OutlineButton;
information/blendle-frontend-react-source/app/modules/campaigns/NewsletterSignUp.js
BramscoChill/BlendleParser
import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Logo from 'components/Logo'; import Link from 'components/Link'; import { translate, translateElement } from 'instances/i18n'; import BackboneView from 'components/shared/BackboneView'; import SignUpForm from 'views/forms/signup'; import { isMobile } from 'instances/browser_environment'; import OpenMailButton from 'components/buttons/OpenMail'; import CSS from './NewsletterSignUpUS.scss'; export default class NewsletterSignUp extends React.Component { static propTypes = { analyticsEvent: PropTypes.string, onSignUp: PropTypes.func.isRequired, onShowLogin: PropTypes.func.isRequired, onFacebookConnect: PropTypes.func.isRequired, showUSVersion: PropTypes.bool, }; state = { signupSuccess: false, editEmail: false, }; componentWillMount() { this._form = new SignUpForm({ template: require('templates/modules/campaigns/newsletterSignUp'), facebookButtonClassName: 'inline', analyticsEvent: this.props.analyticsEvent, onFacebookConnected: this.props.onFacebookConnect, onSignUp: this.props.onSignUp, onShowLogin: this.props.onShowLogin, onSignupSuccess: this._onShowVerification.bind(this), autofocus: !isMobile(), }); } componentWillUnmount() { ReactDOM.unmountComponentAtNode(this._form.el); } _onShowForm(e) { e.preventDefault(); ReactDOM.unmountComponentAtNode(this._form.el); this.setState({ editEmail: true }); this._form.render(); } _onShowVerification(user, resent = false) { this.setState({ signupSuccess: true, editEmail: false, }); let resentMessage; if (resent) { resentMessage = ( <p className="resent"> <strong>{translate('campaigns.newsletter.mail_resent')}</strong> </p> ); } // the verification messages need to be rendered on the form el, // since the backbone form view still handles the resend logic. ReactDOM.render( <div className="v-newsletter-verification"> <h1>{translate('campaigns.newsletter.mail_sent')}</h1> <p>{translateElement('campaigns.newsletter.mailed_at', [user.get('email')], false)}</p> <OpenMailButton email={user.get('email')} className={CSS.openMail} /> {resentMessage} <span className="email-links"> <p className="resend"> <a href="#" onClick={this._onShowVerification.bind(this, user, true)}> {translate('campaigns.newsletter.mail_not_received')} </a> </p> <p className="change"> <a onClick={this._onShowForm.bind(this)} href="#"> {translate('campaigns.newsletter.mail_change')} </a> </p> </span> </div>, this._form.el, ); } _renderIntro() { if (this.state.editEmail) { return <h2 className="reenter">{translate('campaigns.newsletter.reenter_mail')}</h2>; } if (this.state.signupSuccess) { return null; } return ( <span> <h1>{translate('cta.newsletter.title')}</h1> {translateElement(<h2 />, 'campaigns.newsletter.subtitle', false)} <div className="illustration"> <img src="/img/illustrations/iphone-newsletter.png" alt="" /> </div> </span> ); } _renderUS() { let formTitle; if (!this.state.signupSuccess) { formTitle = <h3>{translate('campaigns.newsletter_us.formTitle')}</h3>; } return ( <div className={CSS.container}> <div className={CSS.intro}> <h1 className={CSS.title}>{translate('campaigns.newsletter_us.title')}</h1> {translateElement(<h2 className={CSS.subtitle} />, 'campaigns.newsletter_us.subtitle')} </div> <div className={CSS.formContainer}> {formTitle} <BackboneView className={CSS.form} view={this._form} /> <Link className={CSS.logo} href="/"> <Logo /> </Link> </div> <div className={CSS.legal}> <p> {translateElement('deeplink.footer.terms_conditions', false)}{' '} {translateElement('deeplink.footer.cookies', false)} </p> </div> <img height="1" width="1" style={{ display: 'none' }} src="https://www.facebook.com/tr?id=1588471818145525&ev=PageView&noscript=1" ariaHidden /> </div> ); } render() { if (this.props.showUSVersion) { return this._renderUS(); } return ( <section className="v-newsletter-signup"> <div className="body"> {this._renderIntro()} <BackboneView view={this._form} /> </div> <footer> <p> {translateElement('deeplink.footer.terms_conditions', false)}{' '} {translateElement('deeplink.footer.cookies', false)} </p> <Link className={CSS.logo} href="/"> <Logo /> </Link> </footer> </section> ); } } // WEBPACK FOOTER // // ./src/js/app/modules/campaigns/NewsletterSignUp.js
examples/profile-cards-react-with-styles/src/components/Profile.js
weaintplastic/react-sketchapp
/* eslint-disable react/prop-types */ import React from 'react'; import { Image, View, Text } from 'react-sketchapp'; import { css, withStyles } from '../withStyles'; const Profile = ({ user, styles }) => ( <View {...css(styles.container)}> <Image source={user.profile_image_url} {...css(styles.avatar)} /> <View {...css(styles.titleWrapper)}> <Text {...css(styles.title)}>{user.name}</Text> <Text {...css(styles.subtitle)}>{`@${user.screen_name}`}</Text> </View> <Text {...css(styles.body)}>{user.description}</Text> <Text {...css(styles.body)}>{user.location}</Text> <Text {...css(styles.body)}>{user.url}</Text> </View> ); export default withStyles(({ colors, fonts, spacing }) => ({ container: { backgroundColor: colors.Haus, padding: spacing, width: 260, marginRight: spacing, }, avatar: { height: 220, resizeMode: 'contain', marginBottom: spacing * 2, borderRadius: 10, }, titleWrapper: { marginBottom: spacing, }, title: { ...fonts['Title 2'] }, subtitle: { ...fonts['Title 3'] }, body: { ...fonts.Body }, }))(Profile);
src/svg-icons/content/remove-circle.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentRemoveCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11H7v-2h10v2z"/> </SvgIcon> ); ContentRemoveCircle = pure(ContentRemoveCircle); ContentRemoveCircle.displayName = 'ContentRemoveCircle'; ContentRemoveCircle.muiName = 'SvgIcon'; export default ContentRemoveCircle;
src/App.js
kalaksi/meadmate
import React from 'react'; import './index.css'; import ParameterForm from './Components/ParameterForm'; import EquationCanvas from './Components/EquationCanvas'; import { ferment, rate_my_mead } from './ferment'; export default class App extends React.Component { constructor(props) { super(props); this.state = { parameters: { sugar: "0", honey: "0", honeycontent: "83", water: "0", }, }; // Fill in the rest of the state ("result" and "equation") using the parameter fields. this.state = this.calculateFullState(this.state.parameters); this.handleChange = this.handleChange.bind(this); } render() { return ( <div id="content" className="container-fluid fill"> <div id="header" className="row page-header p-5"> <HeaderText/> </div> <div className="row"> <div id="parameters" className="col-xs-12 col-sm-5 col-md-4" onChange={this.handleChange}> <ParameterForm sugar={this.state.parameters.sugar} honey={this.state.parameters.honey} honeycontent={this.state.parameters.honeycontent} water={this.state.parameters.water} /> </div> <div id="equation" className="col-xs-12 col-sm-7 col-md-8"> <EquationCanvas water={this.state.equation.water} sucrose={this.state.equation.sucrose} ethanol={this.state.equation.ethanol} carbon_dioxide={this.state.equation.carbon_dioxide} /> </div> </div> <div id="result" className="row mt-4"> <ResultBox message={this.state.result.message} status={this.state.result.status} percentage={this.state.result.percentage}/> </div> <div id="references" className="row mt-4"> <References/> </div> </div> ); } handleChange(event) { let newParameters = { ...this.state.parameters }; // Invalid new values are replaced with zero newParameters[event.target.id] = parseInt(event.target.value) || 0; this.setState(this.calculateFullState(newParameters)); } calculateFullState = (parameters) => { let newState = { parameters: parameters, }; // Calculate the equation fields let all_sucrose = this.state.parameters.sugar + (this.state.parameters.honey * (this.state.parameters.honeycontent / 100) ); let result = ferment(all_sucrose, this.state.parameters.water); newState.equation = { water: result.consumed.water.toFixed(2), sucrose: result.consumed.sucrose.toFixed(2), ethanol: result.product.ethanol_l.toFixed(2), carbon_dioxide: result.product.carbon_dioxide.toFixed(2), }; // Rate the mead // Leaves out water consumed in the process. newState.result = rate_my_mead(parseFloat(result.product.ethanol_l), (parseFloat(newState.parameters.water) - result.consumed.water)); newState.result.percentage = newState.result.percentage.toFixed(1); return newState; } } class HeaderText extends React.Component { render() { return ( <h1 className="w-100 text-center">MeadMate</h1> ); } } class ResultBox extends React.Component { render() { const barStyle = { "width": this.props.percentage + "%" }; return ( <div className="col-xs-12 col-sm-12 col-md-12"> <div> {this.props.message} </div> <div className="progress" style={{height: "2.0em"}}> <div className={"progress-bar bg-"+this.props.status} role="progressbar" style={barStyle}> {this.props.percentage}% </div> </div> </div> ); } } class References extends React.Component { render() { return ( <div className="col-12"> <a className="badge badge-secondary" data-toggle="collapse" href="#reference-list" aria-expanded="false" aria-controls="reference-list"> References </a> <div id="reference-list" className="card card-body collapse p-3"> • http://www.chegg.com/homework-help/a-small-scale-approach-to-organic-laboratory-techniques-3rd-edition-chapter-16-solutions-9781111789411 <br /> • http://periodic.lanl.gov/index.shtml </div> </div> ); } }
src/components/Feed/Feed.js
bodguy/bodguy.github.io
// @flow strict import React from 'react'; import moment from 'moment'; import { Link } from 'gatsby'; import type { Edges } from '../../types'; import styles from './Feed.module.scss'; type Props = { edges: Edges }; const Feed = ({ edges }: Props) => ( <div className={styles['feed']}> {edges.map((edge) => ( <div className={styles['feed__item']} key={edge.node.fields.slug}> <div className={styles['feed__item-meta']}> <time className={styles['feed__item-meta-time']} dateTime={moment(edge.node.frontmatter.date).format('MMMM D, YYYY')}> {moment(edge.node.frontmatter.date).format('MMMM YYYY')} </time> <span className={styles['feed__item-meta-divider']} /> <span className={styles['feed__item-meta-category']}> <Link to={edge.node.fields.categorySlug} className={styles['feed__item-meta-category-link']}>{edge.node.frontmatter.category}</Link> </span> </div> <h2 className={styles['feed__item-title']}> <Link className={styles['feed__item-title-link']} to={edge.node.fields.slug}>{edge.node.frontmatter.title}</Link> </h2> <p className={styles['feed__item-description']}>{edge.node.frontmatter.description}</p> <Link className={styles['feed__item-readmore']} to={edge.node.fields.slug}>Read</Link> </div> ))} </div> ); export default Feed;
mxcube3/ui/components/Tasks/AddSample.js
amilan/mxcube3
import React from 'react'; import { reduxForm } from 'redux-form'; import { Modal } from 'react-bootstrap'; class AddSample extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); this.handleCancel = this.handleCancel.bind(this); } handleCancel() { this.props.hide(); } handleSubmit() { let prefix = this.props.values.sampleName ? this.props.values.sampleName : 'noname'; if (this.props.values.proteinAcronym && this.props.values.sampleName) { prefix += `-${this.props.values.proteinAcronym}`; } this.props.add({ ...this.props.values, type: 'Sample', defaultPrefix: prefix, location: 'Manual', sampleID: this.props.id.toString() }); this.props.hide(); } render() { const { fields: { sampleName, proteinAcronym } } = this.props; return ( <Modal show={this.props.show} onHide={this.handleCancel}> <Modal.Header closeButton> <Modal.Title>Add Sample Manually</Modal.Title> </Modal.Header> <Modal.Body> <form className="form-horizontal"> <div className="form-group"> <label className="col-sm-3 control-label">Sample Name:</label> <div className="col-sm-3"> <input type="text" className="form-control" {...sampleName} /> </div> <label className="col-sm-3 control-label">Protein Acronym:</label> <div className="col-sm-3"> <input type="text" className="form-control" {...proteinAcronym} /> </div> </div> </form> </Modal.Body> <Modal.Footer> <button className="btn btn-primary" type="button" onClick={this.handleSubmit} > Add Sample </button> </Modal.Footer> </Modal> ); } } // THIS IS THE IMPORTANT PART! AddSample = reduxForm({ // A unique name for this form form: 'addsample', // All the fields in your form fields: ['sampleName', 'proteinAcronym'] }, state => ({ // will pull state into form's initialValues initialValues: { ...state.taskForm.taskData.parameters } }))(AddSample); export default AddSample;
src/svg-icons/action/alarm-on.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAlarmOn = (props) => ( <SvgIcon {...props}> <path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-1.46-5.47L8.41 12.4l-1.06 1.06 3.18 3.18 6-6-1.06-1.06-4.93 4.95z"/> </SvgIcon> ); ActionAlarmOn = pure(ActionAlarmOn); ActionAlarmOn.displayName = 'ActionAlarmOn'; ActionAlarmOn.muiName = 'SvgIcon'; export default ActionAlarmOn;
app/javascript/mastodon/features/compose/components/search_results.js
palon7/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import AccountContainer from '../../../containers/account_container'; import StatusContainer from '../../../containers/status_container'; import Link from 'react-router-dom/Link'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class SearchResults extends ImmutablePureComponent { static propTypes = { results: ImmutablePropTypes.map.isRequired, }; render () { const { results } = this.props; let accounts, statuses, hashtags; let count = 0; if (results.get('accounts') && results.get('accounts').size > 0) { count += results.get('accounts').size; accounts = ( <div className='search-results__section'> {results.get('accounts').map(accountId => <AccountContainer key={accountId} id={accountId} />)} </div> ); } if (results.get('statuses') && results.get('statuses').size > 0) { count += results.get('statuses').size; statuses = ( <div className='search-results__section'> {results.get('statuses').map(statusId => <StatusContainer key={statusId} id={statusId} />)} </div> ); } if (results.get('hashtags') && results.get('hashtags').size > 0) { count += results.get('hashtags').size; hashtags = ( <div className='search-results__section'> {results.get('hashtags').map(hashtag => <Link key={hashtag} className='search-results__hashtag' to={`/timelines/tag/${hashtag}`}> #{hashtag} </Link> )} </div> ); } return ( <div className='search-results'> <div className='search-results__header'> <FormattedMessage id='search_results.total' defaultMessage='{count, number} {count, plural, one {result} other {results}}' values={{ count }} /> </div> {accounts} {statuses} {hashtags} </div> ); } }
packages/material-ui-icons/src/Iso.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Iso = 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>; Iso = pure(Iso); Iso.muiName = 'SvgIcon'; export default Iso;
Initial/src/client/app/components/ToDoApp.js
Louis0503/TestRact
'use strict' import React from 'react'; const TodoList = (props) => ( <ul> { props.items.map((item) => ( <li key={item.id}>{item.text}</li> )) } </ul> ); // 整個 App 的主要元件,這邊比較重要的是事件處理的部份 class ToDoApp extends React.Component { constructor(props) { super(props); this.onChange = this.onChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.state = { items :[], text : 'default', }; } onChange(e){ this.setState({text: e.target.value}); } handleSubmit(e){ e.preventDefault(); const nextItems = this.state.items.concat( [{text: this.state.text, id : Date.now()}]); const nextText = 'default'; this.setState({items : nextItems, text: nextText}); } render() { return ( <div> <h3>TodoList</h3> <TodoList items = {this.state.items}/> <form onSubmit = {this.handleSubmit}> <input onChange = {this.onChange} value = {this.state.text}/> <button>{'Add #' + (this.state.items.length +1)}</button> </form> </div> ); } } export default ToDoApp;
src/Parser/Paladin/Retribution/Modules/Talents/DivinePurpose.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import ITEMS from 'common/ITEMS'; import SpellIcon from 'common/SpellIcon'; import { formatNumber } from 'common/format'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; class DivinePurpose extends Analyzer { static dependencies = { combatants: Combatants, }; on_initialized() { const hasDivinePurpose = this.combatants.selected.hasTalent(SPELLS.DIVINE_PURPOSE_TALENT_RETRIBUTION.id); const hasSoulOfTheHighlord = this.combatants.selected.hasFinger(ITEMS.SOUL_OF_THE_HIGHLORD.id); this.active = hasDivinePurpose || hasSoulOfTheHighlord; } get divinePurposeProcs() { return this.combatants.selected.getBuffTriggerCount(SPELLS.DIVINE_PURPOSE_BUFF.id); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.DIVINE_PURPOSE_TALENT_RETRIBUTION.id} />} value={`${formatNumber(this.divinePurposeProcs)}`} label="Divine Purpose procs" /> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(1); } export default DivinePurpose;
app/containers/AdminRelaisCommandes/components/DetailCommandeProduit.js
Proxiweb/react-boilerplate
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import round from 'lodash/round'; import { TableRow, TableRowColumn } from 'material-ui/Table'; import { trouveTarification } from 'containers/CommandeEdit/components/components/AffichePrix'; import buildCommandeRow from 'components/DetailCommandeColumns'; import { supprimerCommandeContenu, diminuerCommandeContenu, modifierCommandeContenu, } from 'containers/Commande/actions'; import styles from './styles.css'; // eslint-disable-next-line class CommnandeParProduitFournisseur extends Component { static propTypes = { contenu: PropTypes.object.isRequired, readOnly: PropTypes.bool.isRequired, souligneQte: PropTypes.bool.isRequired, produit: PropTypes.object.isRequired, qteTotalOffre: PropTypes.number.isRequired, offre: PropTypes.object.isRequired, idx: PropTypes.number.isRequired, // diminuer: PropTypes.func.isRequired, supprimer: PropTypes.func.isRequired, modifierCommandeContenu: PropTypes.func.isRequired, }; handleDiminuer = () => { const { contenu, supprimer } = this.props; if (contenu.quantite === 1) { supprimer(contenu); } else { alert('Diminution non implémmentée'); // eslint-disable-line } }; handleChangeQte = () => { const { contenu, offre } = this.props; const poidsG = parseInt(offre.poids * (contenu.qteRegul + contenu.quantite) / 1000, 10); const nouveauPoids = parseInt(prompt('Poids réel (g) ?', poidsG), 10); // eslint-disable-line if (nouveauPoids && nouveauPoids !== poidsG) { const qteTotal = round(nouveauPoids * contenu.quantite / poidsG, 5); this.props.modifierCommandeContenu({ ...contenu, qteRegul: round(qteTotal - contenu.quantite, 5), quantiteAjustee: true, }); } }; handleResetQuantite = () => { this.props.modifierCommandeContenu({ ...this.props.contenu, qteRegul: 0, quantiteAjustee: false, }); }; handleClick = () => { const { dansPrepaPanier } = this.props.contenu; this.props.modifierCommandeContenu({ ...this.props.contenu, dansPrepaPanier: !dansPrepaPanier, }); }; render() { const { produit, contenu, offre, qteTotalOffre, idx, readOnly, souligneQte } = this.props; const tarif = trouveTarification(offre.tarifications, qteTotalOffre, 0); const tarifEnBaisse = offre.tarifications[0].prix > tarif.prix; const rows = buildCommandeRow({ contenu, idx, offre, tarifEnBaisse, colorTrendingDown: 'green', tarif, produit, handleChangeQte: !readOnly && offre.quantiteAjustable && !contenu.quantiteAjustee ? this.handleChangeQte : undefined, handleResetQuantite: !readOnly && contenu.quantiteAjustee ? this.handleResetQuantite : undefined, souligneQte, }); return ( <TableRow key={idx} onClick={this.handleClick} style={{ backgroundColor: contenu.dansPrepaPanier ? 'silver' : 'white', }} > {rows} {!readOnly && <TableRowColumn className={styles.lessSmallCol}> <button onClick={this.handleDiminuer} title="quantite - 1"> - 1 </button> </TableRowColumn>} </TableRow> ); } } const mapDispatchToProps = dispatch => bindActionCreators( { diminuer: diminuerCommandeContenu, supprimer: supprimerCommandeContenu, modifierCommandeContenu, }, dispatch ); export default connect(null, mapDispatchToProps)(CommnandeParProduitFournisseur);
client/js/view_controllers/LoginViewController.js
nebrius/schat
/* The MIT License (MIT) Copyright (c) 2014 Bryan Hughes <bryan@theoreticalideations.com> (http://theoreticalideations.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import React from 'react'; import { ViewController } from 'flvx'; import { LoginView } from 'views/LoginView'; export class LoginViewController extends ViewController { render(data) { React.renderComponent(new LoginView(data), document.getElementById('content')); } }
src/svg-icons/image/blur-off.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBlurOff = (props) => ( <SvgIcon {...props}> <path d="M14 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-.2 4.48l.2.02c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5-1.5.67-1.5 1.5l.02.2c.09.67.61 1.19 1.28 1.28zM14 3.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm-4 0c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm11 7c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM10 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm8 8c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-4 13.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM2.5 5.27l3.78 3.78L6 9c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1c0-.1-.03-.19-.06-.28l2.81 2.81c-.71.11-1.25.73-1.25 1.47 0 .83.67 1.5 1.5 1.5.74 0 1.36-.54 1.47-1.25l2.81 2.81c-.09-.03-.18-.06-.28-.06-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1c0-.1-.03-.19-.06-.28l3.78 3.78L20 20.23 3.77 4 2.5 5.27zM10 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm11-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 13c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zM3 9.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm7 11c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-3-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5z"/> </SvgIcon> ); ImageBlurOff = pure(ImageBlurOff); ImageBlurOff.displayName = 'ImageBlurOff'; ImageBlurOff.muiName = 'SvgIcon'; export default ImageBlurOff;
src/pages/activities/StarBeach.js
ayltai/fishing-club
// @flow 'use strict'; import React from 'react'; import muiThemeable from 'material-ui/styles/muiThemeable'; import { Card, CardMedia, CardTitle, CardText } from 'material-ui/Card'; import LazyLoad from 'react-lazy-load'; import ReactGA from 'react-ga'; import './StarBeach.css'; import StarBeachImage from '../../images/star-beach.jpg'; import StarfishImage from '../../images/starfish.jpg'; class StarBeach extends React.Component { componentDidMount() : void { window.scrollTo(0, 0); } render() : any { return ( <div> <Card className="starBeachItem"> <CardMedia> <img src={StarBeachImage} style={{ maxWidth : '100%' }} /> </CardMedia> <CardTitle title="Star beach (星星灘)" subtitle="A good place for selfies" /> <CardText> <p>It is a beach covered entirely by water and only appears when the tide is low. It was a place with no name, and people start to call it "Star beach" because the water there is so clear that many starfishes live in there.</p> <LazyLoad width={768} height={450} onContentVisible={() : void => ReactGA.event({ category : 'Star Beach', action : 'Display', label : 'Starfish' })}> <div style={{ textAlign : 'center' }}> <img src={StarfishImage} style={{ maxWidth : '100%' }} /> </div> </LazyLoad> <p>Sadly, due to heavy pollutions, we can no longer find that many starfishes there as shown in the above image. But still, we will find some, and you can even put it in your hands to feel when it crawls.</p> </CardText> </Card> <Card className="starBeachItem"> <CardTitle title="How and when to visit Star beach?" /> <CardText> <p>Star beach is covered by water when the tide is high, so we have to wait until the tide is low enough. For only once a day, the tide is at its lowest level. The time of a low tide is not fixed and is shifted about 1 hour each day. That's why we picked certain weekends when a low tide will appear in day time. On that day it will be around 3pm to 5pm, the beach will appear for about 1 hour.</p> <p>The raft owner will pay close attention to the tide and let us know when the time has come. From the raft, we will take a boat and travel to the beach in a few minutes. The beach will be surrounded by shallow water where the boat will not go too close to it, or it will be stranded. Therefore, we will leave the boat, jump into water, and walk to the beach. The water level there is about 2 to 3 feet (about as high as our hip).</p> </CardText> </Card> </div> ); } } export default muiThemeable()(StarBeach);
src/pageComponents/morph/morphResults.js
nai888/langua
import React from 'react' import classNames from 'classnames' import PropTypes from 'prop-types' import Results from '../../components/results' import sharedStyles from '../../components/results/sharedResults.module.sass' const MorphResults = ({ styles, outputFormat, results, showDiff, showChanges }) => { const resultsArr = results || [] const outputText = () => { // If there were errors, print them if (typeof resultsArr[0] === 'string') { return resultsArr.map((error, i) => ( <p className={classNames(styles.outText, sharedStyles.error)} key={i}> {error} </p> )) } // Format the results according to the selected option const format = result => { if (outputFormat === 'oo') { return result.output.trim() } else if (outputFormat === 'io') { return `${result.input.trim()} ${String.fromCharCode( 8594 )} ${result.output.trim()}` } else if (outputFormat === 'oi') { return `${result.output.trim()} ${String.fromCharCode( 8592 )} ${result.input.trim()}` } } // Assign the 'different' and 'changed' classes appropriately const classes = result => { if (showDiff && result.diff) { if (showChanges && result.input !== result.output) { return classNames(styles.outText, styles.different, styles.changed) } else { return classNames(styles.outText, styles.different) } } else { if (showChanges && result.input !== result.output) { return classNames(styles.outText, styles.changed) } else { return styles.outText } } } // Return the results text return resultsArr.length > 0 ? ( resultsArr.map((result, i) => ( <p className={classes(result)} key={i}> {format(result)} </p> )) ) : ( <p className={styles.outText} /> ) } const countStats = () => { const totalWords = resultsArr.length let unchangedWords = 0 let differentWords = 0 for (let i = 0; i < totalWords; i++) { if (resultsArr[i].input === resultsArr[i].output) { unchangedWords++ } if (resultsArr[i].diff) { differentWords++ } } const changedWords = totalWords - unchangedWords const sameWords = totalWords - differentWords return { total: totalWords, changed: changedWords, unchangedWords: unchangedWords, different: differentWords, same: sameWords } } const statsText = () => { const stats = countStats() return `${stats.changed} of ${stats.total} words changed (${stats.unchanged} unchanged); ${stats.different} of ${stats.total} words different from last time (${stats.same} the same)` } return ( <Results> <div className={styles.output}>{outputText()}</div> <div className={sharedStyles.stats}> <p className={sharedStyles.statsText}>{statsText()}</p> </div> </Results> ) } MorphResults.propTypes = { styles: PropTypes.object, outputFormat: PropTypes.string.isRequired, results: PropTypes.oneOfType([ PropTypes.arrayOf( PropTypes.shape({ input: PropTypes.string.isRequired, output: PropTypes.string.isRequired, diff: PropTypes.bool.isRequired }) ).isRequired, PropTypes.arrayOf(PropTypes.string.isRequired).isRequired ]), showDiff: PropTypes.bool.isRequired, showChanges: PropTypes.bool.isRequired } export default MorphResults
test/unit/testHelper.js
SupasitC/Pricetrolley
import jq from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import ReactTestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import createHistory from 'react-router/lib/browserHistory'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../../src/js/reducers'; // Global prerequisites to make it work in the command line global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; const $ = jq(window); // Set up chai-jquery chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = ReactTestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); // Produces HTML return $(ReactDOM.findDOMNode(componentInstance)); } function mockHistory(component) { component.childContextTypes = { history: React.PropTypes.object }; component.prototype.getChildContext = () => ({ history: createHistory() }); } // Helper for simulating events $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } ReactTestUtils.Simulate[eventName](this[0]); }; export { renderComponent, mockHistory, expect };
src/@ui/Icon/icons/Search.js
NewSpring/Apollos
import React from 'react'; import PropTypes from 'prop-types'; import { Svg } from '../../Svg'; import makeIcon from './makeIcon'; const Icon = makeIcon(({ size = 32, fill, ...otherProps } = {}) => ( <Svg width={size} height={size} viewBox="0 0 24 24" {...otherProps}> <Svg.Path d="M20.77 18.56l-3.42-3.42c.82-1.24 1.3-2.72 1.3-4.3 0-4.33-3.5-7.84-7.82-7.84S3 6.5 3 10.83c0 4.3 3.5 7.82 7.83 7.82 1.6 0 3.07-.48 4.3-1.3l3.43 3.42c.3.3.8.3 1.1 0l1.1-1.1c.32-.3.32-.8 0-1.1zm-16.2-7.73c0-3.46 2.8-6.26 6.26-6.26 3.45 0 6.26 2.8 6.26 6.26 0 3.45-2.83 6.26-6.28 6.26-3.46 0-6.26-2.83-6.26-6.28z" fill={fill} /> </Svg> )); Icon.propTypes = { size: PropTypes.number, fill: PropTypes.string, }; export default Icon;
writeExampleWebpack2/src/js/components/Todo.js
fengnovo/webpack-react
import React from 'react' const Todo = ({onclick,isCompleted,text}) =>{ //来自props的,参数要加花括号 return <li onClick={onclick} style={{textDecoration: isCompleted ? "line-through": "none"}}> <i className={ isCompleted ? "icon-star":"icon-star-empty"}></i> {text} </li> } export default Todo
app/components/Header/index.js
fascinating2000/productFrontend
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 messages from './messages'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <A href="/"> <h1>Welcome to Product Sites!</h1> </A> <NavBar> <HeaderLink to="/"> <FormattedMessage {...messages.home} /> </HeaderLink> <HeaderLink to="/create"> <FormattedMessage {...messages.features} /> </HeaderLink> </NavBar> </div> ); } } export default Header;
src/svg-icons/social/sentiment-very-satisfied.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialSentimentVerySatisfied = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.47 2 12s4.47 10 9.99 10S22 17.53 22 12 17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-10.06L14.06 11l1.06-1.06L16.18 11l1.06-1.06-2.12-2.12zm-4.12 0L9.94 11 11 9.94 8.88 7.82 6.76 9.94 7.82 11zM12 17.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/> </SvgIcon> ); SocialSentimentVerySatisfied = pure(SocialSentimentVerySatisfied); SocialSentimentVerySatisfied.displayName = 'SocialSentimentVerySatisfied'; SocialSentimentVerySatisfied.muiName = 'SvgIcon'; export default SocialSentimentVerySatisfied;
examples/src/components/Multiselect.js
pedroseac/react-select
import React from 'react'; import Select from 'react-select'; const FLAVOURS = [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla' }, { label: 'Strawberry', value: 'strawberry' }, { label: 'Caramel', value: 'caramel' }, { label: 'Cookies and Cream', value: 'cookiescream' }, { label: 'Peppermint', value: 'peppermint' }, ]; const WHY_WOULD_YOU = [ { label: 'Chocolate (are you crazy?)', value: 'chocolate', disabled: true }, ].concat(FLAVOURS.slice(1)); var MultiSelectField = React.createClass({ displayName: 'MultiSelectField', propTypes: { label: React.PropTypes.string, }, getInitialState () { return { disabled: false, crazy: false, options: FLAVOURS, value: [], }; }, handleSelectChange (value) { console.log('You\'ve selected:', value); this.setState({ value }); }, toggleDisabled (e) { this.setState({ disabled: e.target.checked }); }, toggleChocolate (e) { let crazy = e.target.checked; this.setState({ crazy: crazy, options: crazy ? WHY_WOULD_YOU : FLAVOURS, }); }, render () { return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select multi simpleValue disabled={this.state.disabled} value={this.state.value} placeholder="Select your favourite(s)" options={this.state.options} onChange={this.handleSelectChange} /> <div className="checkbox-list"> <label className="checkbox"> <input type="checkbox" className="checkbox-control" checked={this.state.disabled} onChange={this.toggleDisabled} /> <span className="checkbox-label">Disable the control</span> </label> <label className="checkbox"> <input type="checkbox" className="checkbox-control" checked={this.state.crazy} onChange={this.toggleChocolate} /> <span className="checkbox-label">I don't like Chocolate (disabled the option)</span> </label> </div> </div> ); } }); module.exports = MultiSelectField;
examples/fiber/debugger/src/App.js
sekiyaeiji/react
import React, { Component } from 'react'; import Draggable from 'react-draggable'; import ReactNoop from 'react-noop-renderer'; import ReactFiberInstrumentation from 'react-noop-renderer/lib/ReactFiberInstrumentation'; import Editor from './Editor'; import Fibers from './Fibers'; import describeFibers from './describeFibers'; function getFiberState(root, workInProgress) { if (!root) { return null; } return describeFibers(root.current, workInProgress); } const defaultCode = ` log('Render <div>Hello</div>'); ReactNoop.render(<div>Hello</div>); ReactNoop.flush(); log('Render <h1>Goodbye</h1>'); ReactNoop.render(<h1>Goodbye</h1>); ReactNoop.flush(); `; class App extends Component { constructor(props) { super(props); this.state = { code: localStorage.getItem('fiber-debugger-code') || defaultCode, isEditing: false, history: [], currentStep: 0, show: { alt: false, child: true, sibling: true, return: false, fx: false, progressedChild: false, progressedDel: false } }; } componentDidMount() { this.runCode(this.state.code); } runCode(code) { let currentStage; let currentRoot; ReactFiberInstrumentation.debugTool = null; ReactNoop.render(null); ReactNoop.flush(); ReactFiberInstrumentation.debugTool = { onMountContainer: (root) => { currentRoot = root; }, onUpdateContainer: (root) => { currentRoot = root; }, onBeginWork: (fiber) => { const fibers = getFiberState(currentRoot, fiber); const stage = currentStage; this.setState(({ history }) => ({ history: [ ...history, { action: 'BEGIN', fibers, stage } ] })); }, onCompleteWork: (fiber) => { const fibers = getFiberState(currentRoot, fiber); const stage = currentStage; this.setState(({ history }) => ({ history: [ ...history, { action: 'COMPLETE', fibers, stage } ] })); }, onCommitWork: (fiber) => { const fibers = getFiberState(currentRoot, fiber); const stage = currentStage; this.setState(({ history }) => ({ history: [ ...history, { action: 'COMMIT', fibers, stage } ] })); }, }; window.React = React; window.ReactNoop = ReactNoop; window.expect = () => ({ toBe() {}, toContain() {}, toEqual() {}, }); window.log = s => currentStage = s; // eslint-disable-next-line eval(window.Babel.transform(code, { presets: ['react', 'es2015'] }).code); } handleEdit = (e) => { e.preventDefault(); this.setState({ isEditing: true }); } handleCloseEdit = (nextCode) => { localStorage.setItem('fiber-debugger-code', nextCode); this.setState({ isEditing: false, history: [], currentStep: 0, code: nextCode }); this.runCode(nextCode); } render() { const { history, currentStep, isEditing, code } = this.state; if (isEditing) { return <Editor code={code} onClose={this.handleCloseEdit} />; } const { fibers, action, stage } = history[currentStep] || {}; let friendlyAction; if (fibers) { let wipFiber = fibers.descriptions[fibers.workInProgressID]; let friendlyFiber = wipFiber.type || wipFiber.tag + ' #' + wipFiber.id; friendlyAction = `After ${action} on ${friendlyFiber}`; } return ( <div style={{ height: '100%' }}> {fibers && <Draggable> <Fibers fibers={fibers} show={this.state.show} /> </Draggable> } <div style={{ width: '100%', textAlign: 'center', position: 'fixed', bottom: 0, padding: 10, zIndex: 1, backgroundColor: '#fafafa', border: '1px solid #ccc' }}> <input type="range" style={{ width: '25%' }} min={0} max={history.length - 1} value={currentStep} onChange={e => this.setState({ currentStep: Number(e.target.value) })} /> <p>Step {currentStep}: {friendlyAction} (<a style={{ color: 'gray' }} onClick={this.handleEdit} href='#'>Edit</a>)</p> {stage && <p>Stage: {stage}</p>} {Object.keys(this.state.show).map(key => <label style={{ marginRight: '10px' }} key={key}> <input type="checkbox" checked={this.state.show[key]} onChange={e => { this.setState(({ show }) => ({ show: {...show, [key]: !show[key]} })); }} /> {key} </label> )} </div> </div> ); } } export default App;
docs/src/app/components/pages/components/Tabs/ExampleControlled.js
barakmitz/material-ui
import React from 'react'; import {Tabs, Tab} from 'material-ui/Tabs'; const styles = { headline: { fontSize: 24, paddingTop: 16, marginBottom: 12, fontWeight: 400, }, }; export default class TabsExampleControlled extends React.Component { constructor(props) { super(props); this.state = { value: 'a', }; } handleChange = (value) => { this.setState({ value: value, }); }; render() { return ( <Tabs value={this.state.value} onChange={this.handleChange} > <Tab label="Tab A" value="a" > <div> <h2 style={styles.headline}>Controllable Tab A</h2> <p> Tabs are also controllable if you want to programmatically pass them their values. This allows for more functionality in Tabs such as not having any Tab selected or assigning them different values. </p> </div> </Tab> <Tab label="Tab B" value="b"> <div> <h2 style={styles.headline}>Controllable Tab B</h2> <p> This is another example of a controllable tab. Remember, if you use controllable Tabs, you need to give all of your tabs values or else you wont be able to select them. </p> </div> </Tab> </Tabs> ); } }
src/widgets/ContentBanner/index.js
mydearxym/mastani
/* * * ContentBanner * */ import React from 'react' import T from 'prop-types' import { contains, pluck, isNil, isEmpty } from 'ramda' import TimeAgo from 'timeago-react' import { buildLog } from '@/utils/logger' import DotDivider from '@/widgets/DotDivider' import { BannerContainer, BannerContentWrapper, PostBrief, Title, Desc, MarkTag, } from './styles' import ReactionNumbers from './ReactionNumbers' /* eslint-disable-next-line */ const log = buildLog('c:ContentBanner:index') // TODO: add a Loading effect const ContentBanner = ({ data, middleNode }) => { const isRefined = contains('refined', pluck('title', data.tags)) return ( <BannerContainer> {!isNil(data.id) && ( <BannerContentWrapper> <PostBrief> <Title>{data.title}</Title> <>{!isEmpty(middleNode) && <div>{middleNode}</div>}</> <Desc> {isRefined ? <MarkTag>精华</MarkTag> : <div />} <TimeAgo datetime={data.insertedAt} locale="zh_CN" /> <DotDivider /> 字数: {data.length} </Desc> </PostBrief> <ReactionNumbers data={data} /> </BannerContentWrapper> )} </BannerContainer> ) } ContentBanner.propTypes = { data: T.shape({ id: T.string, title: T.string, insertedAt: T.string, updatedAt: T.string, views: T.number, collectsCount: T.number, upvotesCount: T.number, viewerHasCollected: T.bool, viewerHasUpvoted: T.bool, length: T.bool, tags: T.object, }), middleNode: T.oneOfType([T.string, T.node]), } ContentBanner.defaultProps = { data: { id: '', title: '', views: 0, collectsCount: -1, upvotesCount: -1, viewerHasCollected: false, viewerHasUpvoted: false, }, middleNode: '', } export default React.memo(ContentBanner)
lib/MultiSelection/OptionsListWrapper.js
folio-org/stripes-components
import React from 'react'; import PropTypes from 'prop-types'; import Popper from '../Popper'; const OptionsListWrapper = React.forwardRef(({ useLegacy, children, controlRef, isOpen, renderToOverlay, modifiers, ...props }, ref) => { if (useLegacy) { return <div data-open={props.isOpen} {...props} hidden={!isOpen}>{children}</div>; } let portal; if (renderToOverlay) { portal = document.getElementById('OverlayContainer'); } return ( <Popper anchorRef={controlRef} overlayProps={{ ...props }} overlayRef={ref} isOpen={isOpen} portal={portal} placement="bottom-start" modifiers={modifiers} hideIfClosed > {children} </Popper> ); }); OptionsListWrapper.displayName = 'OptionsListWrapper'; OptionsListWrapper.propTypes = { children: PropTypes.node, controlRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), isOpen: PropTypes.bool, menuPropGetter: PropTypes.func, modifiers: PropTypes.object, renderToOverlay: PropTypes.bool, useLegacy: PropTypes.bool, }; export default OptionsListWrapper;
src/components/home.js
seanagibson/reserver-space
import React from 'react'; import {Link} from 'react-router'; import Navbar from './navbar'; import LoginContainer from '../containers/loginContainer'; const Home = ({children, userAuthenticated, submitLogout}) => { return ( <div> <Navbar userAuthenticated={userAuthenticated} submitLogout={submitLogout}/> <div className='jumbotron text-center'> <h1>Find Your Space</h1> <LoginContainer/> </div> </div> ) } export default Home;
plot/src/components/HomePage.js
tangr1/dd
import React from 'react'; const HomePage = () => { return ( <div> Hello world! </div> ); }; export default HomePage;
src/containers/ExampleForm/index.js
allyrippley/7ds
import React from 'react' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' import * as actions from '../../actions/heroActions' const Contact = (props) => { window.console.log('MainContactProps: ', props) return ( <div style={{width: '100%', paddingTop: 55}}> <div> <form name="myform" action="process.php" method="POST"> <input type="hidden" name="check_submit" value="1" /> Name: <input type="text" name="Name" /><br /> Password: <input type="password" name="Password" maxLength="10" /><br /> Select something from the list: <select name="Seasons"> <option value="Spring" selected="selected">Spring</option> <option value="Summer">Summer</option> <option value="Autumn">Autumn</option> <option value="Winter">Winter</option> </select><br /><br /> Choose one: <input type="radio" name="Country" value="USA" /> USA <input type="radio" name="Country" value="Canada" /> Canada <input type="radio" name="Country" value="Other" /> Other <br /> Choose the colors: <input type="checkbox" name="Colors[]" value="green" checked="checked" /> Green <input type="checkbox" name="Colors[]" value="yellow" /> Yellow <input type="checkbox" name="Colors[]" value="red" /> Red <input type="checkbox" name="Colors[]" value="gray" /> Gray <br /><br /> Comments:<br /> <textarea name="Comments" rows="10" cols="60">Enter your comments here</textarea><br /> <input type="submit" /> </form> </div> </div> ) } function mapStateToProps(state) { window.console.log('MainContactState: ', state) return { // fuelSavings: state.fuelSavings } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch) } } export default connect( mapStateToProps, mapDispatchToProps )(Contact)
blueocean-material-icons/src/js/components/svg-icons/image/movie-filter.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageMovieFilter = (props) => ( <SvgIcon {...props}> <path d="M18 4l2 3h-3l-2-3h-2l2 3h-3l-2-3H8l2 3H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4zm-6.75 11.25L10 18l-1.25-2.75L6 14l2.75-1.25L10 10l1.25 2.75L14 14l-2.75 1.25zm5.69-3.31L16 14l-.94-2.06L13 11l2.06-.94L16 8l.94 2.06L19 11l-2.06.94z"/> </SvgIcon> ); ImageMovieFilter.displayName = 'ImageMovieFilter'; ImageMovieFilter.muiName = 'SvgIcon'; export default ImageMovieFilter;
app/javascript/mastodon/features/ui/components/column_subheading.js
unarist/mastodon
import React from 'react'; import PropTypes from 'prop-types'; const ColumnSubheading = ({ text }) => { return ( <div className='column-subheading'> {text} </div> ); }; ColumnSubheading.propTypes = { text: PropTypes.string.isRequired, }; export default ColumnSubheading;
src/svg-icons/navigation/cancel.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationCancel = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/> </SvgIcon> ); NavigationCancel = pure(NavigationCancel); NavigationCancel.displayName = 'NavigationCancel'; NavigationCancel.muiName = 'SvgIcon'; export default NavigationCancel;
react-components/src/library/components/search/material-links.js
concord-consortium/rigse
import React from 'react' export class SMaterialLinks extends React.Component { render () { return ( <div> {this.props.links.map((link, idx) => link.type === 'dropdown' ? <SMaterialDropdownLink key={idx} link={link} /> : <SMaterialLink key={idx} link={link} /> )} </div> ) } } export class SGenericLink extends React.Component { constructor (props) { super(props) this.wrapOnClick = this.wrapOnClick.bind(this) } optionallyWrapConfirm (link) { if (link.ccConfirm) { const followLink = () => { window.location = link.url } link.onclick = function (event) { Portal.confirm({ message: link.ccConfirm, callback: followLink }) event.preventDefault() } } } wrapOnClick (str) { /* eslint no-eval: "off" */ return () => eval(str) } render () { const { link } = this.props this.optionallyWrapConfirm(link) if (link.className == null) { link.className = 'button' } if (typeof link.onclick === 'string') { link.onclick = this.wrapOnClick(link.onclick) } // React 16 shows a warning when using javascript:void(0) so replace it with the equivalent // Use #! instead of # so the page doesn't scroll to the top on click. This should // eventually be handled using preventDefault or by changing the anchor links to buttons. const url = link.url === 'javascript:void(0)' ? '#!' : link.url return ( <a href={url} className={link.className} target={link.target} onClick={link.onclick} data-cc-confirm={link.ccConfirm} dangerouslySetInnerHTML={{ __html: link.text }} /> ) } } export class SMaterialLink extends React.Component { render () { const { link } = this.props return ( <div key={link.key} style={{ float: 'right', marginRight: '5px' }}> <SGenericLink link={link} /> </div> ) } } export class SMaterialDropdownLink extends React.Component { constructor (props) { super(props) this.handleClick = this.handleClick.bind(this) } handleClick (event) { window.hideSharelinks() if (!event.target.nextSibling.visible()) { event.target.nextSibling.show() event.target.nextSibling.addClassName('visible') event.target.innerHTML = this.expandedText } } render () { const { link } = this.props this.expandedText = link.expandedText link.onclick = this.handleClick return ( <div key={link.key} style={{ float: 'right' }}> <SGenericLink link={link} /> <div className='Expand_Collapse Expand_Collapse_preview' style={{ display: 'none' }}> {link.options.map((item, idx) => ( <div key={idx} className='preview_link'> <SGenericLink link={item} /> </div> ))} </div> </div> ) } }
src/entre.js
jerryshew/react-uikits
require("babel-polyfill"); import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import RootComponent from './RootComponent'; import dot from './page/demo.less' if (module.hot) { module.hot.accept() } ReactDOM.render(<RootComponent/>, document.getElementById('root'))
src/components/ModuleLoading.js
saas-plat/saas-plat-native
import React from 'react'; import nprogress from 'nprogress'; import { View, Text, StatusBar, TouchableOpacity, Platform } from 'react-native'; import { autobind } from 'core-decorators'; import Spinner from './Spinner'; import Bundle from '../core/Bundle'; import { connectStyle } from '../core/Theme'; import { translate } from '../core/I18n'; import { connectStore } from '../core/Store'; // 模块加载等待 @translate('core.ModuleLoading') @connectStyle('core.ModuleLoading') @connectStore(['SystemStore']) @autobind export default class ModuleLoading extends React.Component { constructor(props) { super(props); this.state = { animating: true, code: 'ModuleLoading', taskId: 0 }; } componentWillMount() { this.prepare(this.props); } componentWillReceiveProps(nextProps) { if (nextProps.bundles != this.props.bundles) { this.prepare(nextProps); } } onPressFeed() { if (this.state.animating) { return; } this.prepare(this.props); } showBack() { this.props.history.replace('/404'); } finished(taskId) { this.setState({ animating: false, code: 'Success' }); if (this.props.onComplated) { this.props.onComplated(this.props.bundles); } if (Platform.OS === 'web') { nprogress.done(); } // try { // if (!this.props.history.replace(this.props.path)) { // this.setState({animating: false, code: 'ModuleRouteNotRegisterd'}); // this.showBack(); // } // } catch (err) { // console.warn(this.props.t('GotoFailed'), err); // if (this.state.taskId === taskId) { // this.setState({animating: false, code: 'ModuleRouteNotRegisterd'}); // this.showBack(); // } // } } loadBundle(taskId) { const bundles = this.props.bundles; return new Promise((resolve, reject) => { console.log(this.props.t('开始加载包...')); Bundle.load(bundles).then(( bundles) => { console.log(this.props.t('包加载完成')); resolve(bundles); }).catch((err) => { console.warn(this.props.t('包加载失败'), err); if (this.state.taskId === taskId) { this.setState({ animating: false, code: 'Failed', messageErr: err }); this.showBack(); } }); }); } handleInit(handlers, ns) { return new Promise(async(resolve, reject) => { await Promise.all(handlers); }); } prepare(props) { if (Platform.OS === 'web') { nprogress.start(); } const taskId = this.state.taskId + 1; this.setState({ animating: true, messageErr: null, code: 'Loading', taskId }); this.loadBundle(taskId).then(() => { // 如果模块配置了初始化方法,开始调用 支持promise if (this.props.initHandler && this.props.initHandler.length > 0) { this.handleInit(this.props.initHandler, this.props.module.name) .then(() => { this.finished(taskId); }); } else { this.finished(taskId); } }); } render() { let message; if (!this.state.messageErr) { switch (this.state.code) { case 'ModuleLoading': message = this.props.t('正在加载,请稍后...'); break; case 'Success': message = this.props.t('模块已加载完毕'); break; case 'ModuleRouteNotRegisterd': message = this.props.t('模块无法打开~'); break; case 'Failed': message = this.props.t('模块加载失败,稍后重试...'); break; case 'Loading': message = this.props.t('正在加载,请稍后...'); break; } } return ( <View style={this.props.style.container}> {(Platform.OS === 'android' || Platform.OS === 'ios') ? <StatusBar hidden={false} barStyle='default'/> : null} <Spinner visible={this.state.animating}/> <TouchableOpacity onPress={this.onPressFeed}> <View> <Text style={this.props.style.success}> {this.state.messageErr || message} </Text> </View> </TouchableOpacity> </View> ); } }
src/index.js
grantpalin/bc-elects
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
src/containers/BVsecret.js
pjkarlik/ReactUI
import React from 'react'; const Panel = () => { const content = ( <span> <h2>What is this?</h2> <p> This is a living example of my work, code, music, video and other digital art. My ongoing digital experiment for ui development, digital and generative art, interface research. </p> </span> ); return content; }; Panel.displayName = 'Panel'; export default Panel;
src/components/CamVideoDashboard/index.js
happyboy171/Feeding-Fish-View-
import React, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './style.css'; import history from '../../core/history'; import { Line, Circle } from 'rc-progress'; import ProgressBar from 'react-bootstrap'; import classNames from 'classnames'; import toDisplay from "./cut.mp4"; import {default as Video, Controls, Overlay} from 'react-html5video'; const colorMap = [ '#FE8C6A', '#3FC7FA', '#85D262',]; class CamVideoDashboard extends Component { constructor(props) { super(props); } render() { var props = this.props.props, ProgressColour=colorMap[parseInt(props.percentagefed * 0.03, 10)], color = {color:props.color, float:"right"} return ( <div key={props.id} className={s.panelColour}> <div className={classNames('row',s.xtitle)}> <div className="col-xs-8 col-sm-8"> <h4>Cage ID : {props.id}</h4> </div> <div className="col-xs-4 col-sm-4"><i className="fa fa-2x fa-dot-circle-o" style={color} aria-hidden="true"></i></div> </div> <div> <a href = '/live' > <Video autoPlay loop muted ref="video" className={s.main__video} > <source src={toDisplay} type="video/mp4" /> </Video> </a> </div> <div><Line percent={props.percentagefed} strokeWidth={2} strokeColor={ProgressColour}/></div> <div className='row'> <div className="col-xs-4">Last Feed:<br/><strong className={s.textSize}>{props.lastFeed}</strong></div> <div className="col-xs-4">Next Feed:<br/><strong className={s.textSize}>{props.nextFeed}</strong></div> <div className="col-xs-4">Feed (%):<br/><strong className={s.textSize}>{props.percentagefed}%</strong></div> </div> </div> ); } } export default withStyles(s)(CamVideoDashboard);
blueocean-material-icons/src/js/components/svg-icons/action/thumbs-up-down.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionThumbsUpDown = (props) => ( <SvgIcon {...props}> <path d="M12 6c0-.55-.45-1-1-1H5.82l.66-3.18.02-.23c0-.31-.13-.59-.33-.8L5.38 0 .44 4.94C.17 5.21 0 5.59 0 6v6.5c0 .83.67 1.5 1.5 1.5h6.75c.62 0 1.15-.38 1.38-.91l2.26-5.29c.07-.17.11-.36.11-.55V6zm10.5 4h-6.75c-.62 0-1.15.38-1.38.91l-2.26 5.29c-.07.17-.11.36-.11.55V18c0 .55.45 1 1 1h5.18l-.66 3.18-.02.24c0 .31.13.59.33.8l.79.78 4.94-4.94c.27-.27.44-.65.44-1.06v-6.5c0-.83-.67-1.5-1.5-1.5z"/> </SvgIcon> ); ActionThumbsUpDown.displayName = 'ActionThumbsUpDown'; ActionThumbsUpDown.muiName = 'SvgIcon'; export default ActionThumbsUpDown;
node_modules/react-router/es/StaticRouter.js
SuperUncleCat/ServerMonitoring
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import warning from 'warning'; import invariant from 'invariant'; import React from 'react'; import PropTypes from 'prop-types'; import { addLeadingSlash, createPath, parsePath } from 'history/PathUtils'; import Router from './Router'; var normalizeLocation = function normalizeLocation(object) { var _object$pathname = object.pathname, pathname = _object$pathname === undefined ? '/' : _object$pathname, _object$search = object.search, search = _object$search === undefined ? '' : _object$search, _object$hash = object.hash, hash = _object$hash === undefined ? '' : _object$hash; return { pathname: pathname, search: search === '?' ? '' : search, hash: hash === '#' ? '' : hash }; }; var addBasename = function addBasename(basename, location) { if (!basename) return location; return _extends({}, location, { pathname: addLeadingSlash(basename) + location.pathname }); }; var stripBasename = function stripBasename(basename, location) { if (!basename) return location; var base = addLeadingSlash(basename); if (location.pathname.indexOf(base) !== 0) return location; return _extends({}, location, { pathname: location.pathname.substr(base.length) }); }; var createLocation = function createLocation(location) { return typeof location === 'string' ? parsePath(location) : normalizeLocation(location); }; var createURL = function createURL(location) { return typeof location === 'string' ? location : createPath(location); }; var staticHandler = function staticHandler(methodName) { return function () { invariant(false, 'You cannot %s with <StaticRouter>', methodName); }; }; var noop = function noop() {}; /** * The public top-level API for a "static" <Router>, so-called because it * can't actually change the current location. Instead, it just records * location changes in a context object. Useful mainly in testing and * server-rendering scenarios. */ var StaticRouter = function (_React$Component) { _inherits(StaticRouter, _React$Component); function StaticRouter() { var _temp, _this, _ret; _classCallCheck(this, StaticRouter); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.createHref = function (path) { return addLeadingSlash(_this.props.basename + createURL(path)); }, _this.handlePush = function (location) { var _this$props = _this.props, basename = _this$props.basename, context = _this$props.context; context.action = 'PUSH'; context.location = addBasename(basename, createLocation(location)); context.url = createURL(context.location); }, _this.handleReplace = function (location) { var _this$props2 = _this.props, basename = _this$props2.basename, context = _this$props2.context; context.action = 'REPLACE'; context.location = addBasename(basename, createLocation(location)); context.url = createURL(context.location); }, _this.handleListen = function () { return noop; }, _this.handleBlock = function () { return noop; }, _temp), _possibleConstructorReturn(_this, _ret); } StaticRouter.prototype.getChildContext = function getChildContext() { return { router: { staticContext: this.props.context } }; }; StaticRouter.prototype.componentWillMount = function componentWillMount() { warning(!this.props.history, '<StaticRouter> ignores the history prop. To use a custom history, ' + 'use `import { Router }` instead of `import { StaticRouter as Router }`.'); }; StaticRouter.prototype.render = function render() { var _props = this.props, basename = _props.basename, context = _props.context, location = _props.location, props = _objectWithoutProperties(_props, ['basename', 'context', 'location']); var history = { createHref: this.createHref, action: 'POP', location: stripBasename(basename, createLocation(location)), push: this.handlePush, replace: this.handleReplace, go: staticHandler('go'), goBack: staticHandler('goBack'), goForward: staticHandler('goForward'), listen: this.handleListen, block: this.handleBlock }; return React.createElement(Router, _extends({}, props, { history: history })); }; return StaticRouter; }(React.Component); StaticRouter.propTypes = { basename: PropTypes.string, context: PropTypes.object.isRequired, location: PropTypes.oneOfType([PropTypes.string, PropTypes.object]) }; StaticRouter.defaultProps = { basename: '', location: '/' }; StaticRouter.childContextTypes = { router: PropTypes.object.isRequired }; export default StaticRouter;
src/js/App.js
vincentleung1/PersonalPage
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import '../css/App.css'; import Home from './Home'; import About from './About'; import Contact from './Contact'; import CV from './CV'; class App extends Component { constructor (props) { super(props); } goHome = function() { // this.refs.HOME.scrollIntoView({block:'center', behavior:'smooth'}); ReactDOM.render(<Home />, document.getElementById('App')); } goAbout = function() { // this.refs.ABOUT.scrollIntoView({block:'center', behavior:'smooth'}); ReactDOM.render(<About />, document.getElementById('App')); } goContact = function() { // this.refs.CONTACT.scrollIntoView({block:'center', behavior:'smooth'}); ReactDOM.render(<Contact />, document.getElementById('App')); } loadCV = function () { // this.refs.TOP.scrollIntoView({behavior:'smooth'}); ReactDOM.render(<CV />, document.getElementById('App')); } render() { return ( <div ref={"TOP"} className="App"> <title> Title </title> <div className="App-header"> <ul> <li> <a onClick={this.goHome.bind(this)}> Home </a> <a onClick={this.goAbout.bind(this)}> About </a> <a onClick={this.goContact.bind(this)}> Contact </a> <a onClick={this.loadCV.bind(this)}> CV </a> </li> </ul> </div> <div className="App-body" id="App"> <div className="component-div"> <div className="home-spaceholder"> </div> <Home /> </div> </div> </div> ); } } export default App;
examples/huge-apps/routes/Course/components/Dashboard.js
ustccjw/react-router
import React from 'react'; class Dashboard extends React.Component { render () { return ( <div> <h3>Course Dashboard</h3> </div> ); } } export default Dashboard;
src/layouts/CoreLayout/CoreLayout.js
prestonbernstein/react-redux-synthesizer
import React from 'react' import Header from '../../components/Header' import './CoreLayout.scss' import '../../styles/core.scss' export const CoreLayout = ({ children }) => ( <div className='container text-center'> <Header /> <div className='core-layout__viewport'> {children} </div> </div> ) CoreLayout.propTypes = { children : React.PropTypes.element.isRequired } export default CoreLayout
frontend/src/Artist/Editor/ArtistEditorFooter.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import MoveArtistModal from 'Artist/MoveArtist/MoveArtistModal'; import MetadataProfileSelectInputConnector from 'Components/Form/MetadataProfileSelectInputConnector'; import QualityProfileSelectInputConnector from 'Components/Form/QualityProfileSelectInputConnector'; import RootFolderSelectInputConnector from 'Components/Form/RootFolderSelectInputConnector'; import SelectInput from 'Components/Form/SelectInput'; import SpinnerButton from 'Components/Link/SpinnerButton'; import PageContentFooter from 'Components/Page/PageContentFooter'; import { kinds } from 'Helpers/Props'; import ArtistEditorFooterLabel from './ArtistEditorFooterLabel'; import DeleteArtistModal from './Delete/DeleteArtistModal'; import TagsModal from './Tags/TagsModal'; import styles from './ArtistEditorFooter.css'; const NO_CHANGE = 'noChange'; class ArtistEditorFooter extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { monitored: NO_CHANGE, qualityProfileId: NO_CHANGE, metadataProfileId: NO_CHANGE, rootFolderPath: NO_CHANGE, savingTags: false, isDeleteArtistModalOpen: false, isTagsModalOpen: false, isConfirmMoveModalOpen: false, destinationRootFolder: null }; } componentDidUpdate(prevProps) { const { isSaving, saveError } = this.props; if (prevProps.isSaving && !isSaving && !saveError) { this.setState({ monitored: NO_CHANGE, qualityProfileId: NO_CHANGE, metadataProfileId: NO_CHANGE, rootFolderPath: NO_CHANGE, savingTags: false }); } } // // Listeners onInputChange = ({ name, value }) => { this.setState({ [name]: value }); if (value === NO_CHANGE) { return; } switch (name) { case 'rootFolderPath': this.setState({ isConfirmMoveModalOpen: true, destinationRootFolder: value }); break; case 'monitored': this.props.onSaveSelected({ [name]: value === 'monitored' }); break; default: this.props.onSaveSelected({ [name]: value }); } } onApplyTagsPress = (tags, applyTags) => { this.setState({ savingTags: true, isTagsModalOpen: false }); this.props.onSaveSelected({ tags, applyTags }); } onDeleteSelectedPress = () => { this.setState({ isDeleteArtistModalOpen: true }); } onDeleteArtistModalClose = () => { this.setState({ isDeleteArtistModalOpen: false }); } onTagsPress = () => { this.setState({ isTagsModalOpen: true }); } onTagsModalClose = () => { this.setState({ isTagsModalOpen: false }); } onSaveRootFolderPress = () => { this.setState({ isConfirmMoveModalOpen: false, destinationRootFolder: null }); this.props.onSaveSelected({ rootFolderPath: this.state.destinationRootFolder }); } onMoveArtistPress = () => { this.setState({ isConfirmMoveModalOpen: false, destinationRootFolder: null }); this.props.onSaveSelected({ rootFolderPath: this.state.destinationRootFolder, moveFiles: true }); } // // Render render() { const { artistIds, selectedCount, isSaving, isDeleting, isOrganizingArtist, isRetaggingArtist, columns, onOrganizeArtistPress, onRetagArtistPress } = this.props; const { monitored, qualityProfileId, metadataProfileId, rootFolderPath, savingTags, isTagsModalOpen, isDeleteArtistModalOpen, isConfirmMoveModalOpen, destinationRootFolder } = this.state; const monitoredOptions = [ { key: NO_CHANGE, value: 'No Change', disabled: true }, { key: 'monitored', value: 'Monitored' }, { key: 'unmonitored', value: 'Unmonitored' } ]; return ( <PageContentFooter> <div className={styles.inputContainer}> <ArtistEditorFooterLabel label="Monitor Artist" isSaving={isSaving && monitored !== NO_CHANGE} /> <SelectInput name="monitored" value={monitored} values={monitoredOptions} isDisabled={!selectedCount} onChange={this.onInputChange} /> </div> { columns.map((column) => { const { name, isVisible } = column; if (!isVisible) { return null; } if (name === 'qualityProfileId') { return ( <div key={name} className={styles.inputContainer} > <ArtistEditorFooterLabel label="Quality Profile" isSaving={isSaving && qualityProfileId !== NO_CHANGE} /> <QualityProfileSelectInputConnector name="qualityProfileId" value={qualityProfileId} includeNoChange={true} isDisabled={!selectedCount} onChange={this.onInputChange} /> </div> ); } if (name === 'metadataProfileId') { return ( <div key={name} className={styles.inputContainer} > <ArtistEditorFooterLabel label="Metadata Profile" isSaving={isSaving && metadataProfileId !== NO_CHANGE} /> <MetadataProfileSelectInputConnector name="metadataProfileId" value={metadataProfileId} includeNoChange={true} isDisabled={!selectedCount} onChange={this.onInputChange} /> </div> ); } if (name === 'path') { return ( <div key={name} className={styles.inputContainer} > <ArtistEditorFooterLabel label="Root Folder" isSaving={isSaving && rootFolderPath !== NO_CHANGE} /> <RootFolderSelectInputConnector name="rootFolderPath" value={rootFolderPath} includeNoChange={true} isDisabled={!selectedCount} selectedValueOptions={{ includeFreeSpace: false }} onChange={this.onInputChange} /> </div> ); } return null; }) } <div className={styles.buttonContainer}> <div className={styles.buttonContainerContent}> <ArtistEditorFooterLabel label={`${selectedCount} Artist(s) Selected`} isSaving={false} /> <div className={styles.buttons}> <div> <SpinnerButton className={styles.organizeSelectedButton} kind={kinds.WARNING} isSpinning={isOrganizingArtist} isDisabled={!selectedCount || isOrganizingArtist || isRetaggingArtist} onPress={onOrganizeArtistPress} > Rename Files </SpinnerButton> <SpinnerButton className={styles.organizeSelectedButton} kind={kinds.WARNING} isSpinning={isRetaggingArtist} isDisabled={!selectedCount || isOrganizingArtist || isRetaggingArtist} onPress={onRetagArtistPress} > Write Metadata Tags </SpinnerButton> <SpinnerButton className={styles.tagsButton} isSpinning={isSaving && savingTags} isDisabled={!selectedCount || isOrganizingArtist || isRetaggingArtist} onPress={this.onTagsPress} > Set Lidarr Tags </SpinnerButton> </div> <SpinnerButton className={styles.deleteSelectedButton} kind={kinds.DANGER} isSpinning={isDeleting} isDisabled={!selectedCount || isDeleting} onPress={this.onDeleteSelectedPress} > Delete </SpinnerButton> </div> </div> </div> <TagsModal isOpen={isTagsModalOpen} artistIds={artistIds} onApplyTagsPress={this.onApplyTagsPress} onModalClose={this.onTagsModalClose} /> <DeleteArtistModal isOpen={isDeleteArtistModalOpen} artistIds={artistIds} onModalClose={this.onDeleteArtistModalClose} /> <MoveArtistModal destinationRootFolder={destinationRootFolder} isOpen={isConfirmMoveModalOpen} onSavePress={this.onSaveRootFolderPress} onMoveArtistPress={this.onMoveArtistPress} /> </PageContentFooter> ); } } ArtistEditorFooter.propTypes = { artistIds: PropTypes.arrayOf(PropTypes.number).isRequired, selectedCount: PropTypes.number.isRequired, isSaving: PropTypes.bool.isRequired, saveError: PropTypes.object, isDeleting: PropTypes.bool.isRequired, deleteError: PropTypes.object, isOrganizingArtist: PropTypes.bool.isRequired, isRetaggingArtist: PropTypes.bool.isRequired, showMetadataProfile: PropTypes.bool.isRequired, columns: PropTypes.arrayOf(PropTypes.object).isRequired, onSaveSelected: PropTypes.func.isRequired, onOrganizeArtistPress: PropTypes.func.isRequired, onRetagArtistPress: PropTypes.func.isRequired }; export default ArtistEditorFooter;
client/src/pages/SignUp.js
ccwukong/lfcommerce-react
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Form, FormGroup, Input, Modal, ModalHeader, ModalBody, Button, } from 'reactstrap'; import { injectIntl, FormattedMessage } from 'react-intl'; class SignUp extends Component { constructor(props) { super(props); this.state = { modal: false, }; } toggle = () => { this.setState({ modal: !this.state.modal, }); }; render() { const { formatMessage } = this.props.intl; return ( <Modal size="sm" isOpen={this.state.modal} toggle={this.toggle}> <ModalHeader toggle={this.toggle}> <FormattedMessage id="sys.register" /> </ModalHeader> <ModalBody> <Form horizontal> <FormGroup controlId="formHorizontalFirstName"> <Input type="text" placeholder={formatMessage({ id: 'sys.fName' })} /> </FormGroup> <FormGroup controlId="formHorizontalLastName"> <Input type="text" placeholder={formatMessage({ id: 'sys.lName' })} /> </FormGroup> <FormGroup controlId="formHorizontalEmail"> <Input type="email" placeholder={formatMessage({ id: 'sys.email' })} /> </FormGroup> <FormGroup controlId="formHorizontalPassword"> <Input type="password" placeholder={formatMessage({ id: 'sys.pwd' })} /> </FormGroup> <FormGroup> <Button color="primary" className="float-right" block> <FormattedMessage id="sys.register" /> </Button> </FormGroup> </Form> </ModalBody> </Modal> ); } } function mapStateToProps(state) { return {}; } export default connect( mapStateToProps, null )(injectIntl(SignUp));
app/main.js
kensworth/Filebrew
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App.js'; ReactDOM.render(<App />, document.getElementById('root'));
src/user/User.js
ryanbaer/busy
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Route } from 'react-router-dom'; import { Helmet } from 'react-helmet'; import getImage from '../helpers/getImage'; import { getIsAuthenticated, getAuthenticatedUser, getUser } from '../reducers'; import { openTransfer } from '../wallet/walletActions'; import { getAccountWithFollowingCount } from './usersActions'; import UserHero from './UserHero'; import LeftSidebar from '../app/Sidebar/LeftSidebar'; import RightSidebar from '../app/Sidebar/RightSidebar'; import Affix from '../components/Utils/Affix'; import ScrollToTopOnMount from '../components/Utils/ScrollToTopOnMount'; import UserProfile from './UserProfile'; import UserComments from './UserComments'; import UserFollowers from './UserFollowers'; import UserFollowing from './UserFollowing'; import UserReblogs from './UserReblogs'; import UserFeed from './UserFeed'; import UserWallet from './UserWallet'; export const needs = [getAccountWithFollowingCount]; @connect( (state, ownProps) => ({ authenticated: getIsAuthenticated(state), authenticatedUser: getAuthenticatedUser(state), user: getUser(state, ownProps.match.params.name), }), { getAccountWithFollowingCount, openTransfer, }, ) export default class User extends React.Component { static propTypes = { authenticated: PropTypes.bool.isRequired, authenticatedUser: PropTypes.shape().isRequired, match: PropTypes.shape().isRequired, user: PropTypes.shape().isRequired, getAccountWithFollowingCount: PropTypes.func, openTransfer: PropTypes.func, }; static defaultProps = { getAccountWithFollowingCount: () => {}, openTransfer: () => {}, }; static needs = needs; componentWillMount() { if (!this.props.user.name) { this.props.getAccountWithFollowingCount({ name: this.props.match.params.name }); } } componentDidUpdate(prevProps) { if (prevProps.match.params.name !== this.props.match.params.name) { this.props.getAccountWithFollowingCount({ name: this.props.match.params.name }); } } handleUserMenuSelect = (key) => { if (key === 'transfer') this.props.openTransfer(this.props.match.params.name); }; render() { const { authenticated, authenticatedUser, match } = this.props; const username = this.props.match.params.name; const { user } = this.props; const { profile = {} } = user.json_metadata || {}; const busyHost = global.postOrigin || 'https://busy.org'; const desc = profile.about || `Post by ${username}`; const image = getImage(`@${username}`); const canonicalUrl = `${busyHost}/@${username}`; const url = `${busyHost}/@${username}`; const displayedUsername = profile.name || username || ''; const hasCover = !!profile.cover_image; const title = `${displayedUsername} - Busy`; const isSameUser = authenticated && authenticatedUser.name === username; return ( <div className="main-panel"> <Helmet> <title>{title}</title> <link rel="canonical" href={canonicalUrl} /> <meta property="description" content={desc} /> <meta property="og:title" content={title} /> <meta property="og:type" content="article" /> <meta property="og:url" content={url} /> <meta property="og:image" content={image} /> <meta property="og:description" content={desc} /> <meta property="og:site_name" content="Busy" /> <meta property="twitter:card" content={image ? 'summary_large_image' : 'summary'} /> <meta property="twitter:site" content={'@steemit'} /> <meta property="twitter:title" content={title} /> <meta property="twitter:description" content={desc} /> <meta property="twitter:image" content={image || 'https://steemit.com/images/steemit-twshare.png'} /> </Helmet> <ScrollToTopOnMount /> {user && ( <UserHero authenticated={authenticated} user={user} username={displayedUsername} isSameUser={isSameUser} hasCover={hasCover} onFollowClick={this.handleFollowClick} onSelect={this.handleUserMenuSelect} /> )} <div className="shifted"> <div className="feed-layout container"> <Affix className="leftContainer" stickPosition={72}> <div className="left"> <LeftSidebar /> </div> </Affix> <Affix className="rightContainer" stickPosition={72}> <div className="right">{user && user.name && <RightSidebar key={user.name} />}</div> </Affix> <div className="center"> <Route exact path={match.path} component={UserProfile} /> <Route path={`${match.path}/comments`} component={UserComments} /> <Route path={`${match.path}/followers`} component={UserFollowers} /> <Route path={`${match.path}/followed`} component={UserFollowing} /> <Route path={`${match.path}/reblogs`} component={UserReblogs} /> <Route path={`${match.path}/feed`} component={UserFeed} /> <Route path={`${match.path}/transfers`} component={UserWallet} /> </div> </div> </div> </div> ); } }
fields/components/DateInput.js
giovanniRodighiero/cms
import moment from 'moment'; import DayPicker from 'react-day-picker'; import React from 'react'; import { findDOMNode } from 'react-dom'; import Popout from '../../admin/client/App/shared/Popout'; import { FormInput } from '../../admin/client/App/elemental'; let lastId = 0; module.exports = React.createClass({ displayName: 'DateInput', propTypes: { format: React.PropTypes.string, name: React.PropTypes.string, onChange: React.PropTypes.func.isRequired, path: React.PropTypes.string, value: React.PropTypes.string, }, getDefaultProps () { return { format: 'YYYY-MM-DD', }; }, getInitialState () { const id = ++lastId; let month = new Date(); const { format, value } = this.props; if (moment(value, format, true).isValid()) { month = moment(value, format).toDate(); } return { id: `_DateInput_${id}`, month: month, pickerIsOpen: false, inputValue: value, }; }, componentDidMount () { this.showCurrentMonth(); }, componentWillReceiveProps: function (newProps) { if (newProps.value === this.props.value) return; this.setState({ month: moment(newProps.value, this.props.format).toDate(), inputValue: newProps.value, }, this.showCurrentMonth); }, focus () { if (!this.refs.input) return; findDOMNode(this.refs.input).focus(); }, handleInputChange (e) { const { value } = e.target; this.setState({ inputValue: value }, this.showCurrentMonth); }, handleKeyPress (e) { if (e.key === 'Enter') { e.preventDefault(); // If the date is strictly equal to the format string, dispatch onChange if (moment(this.state.inputValue, this.props.format, true).isValid()) { this.props.onChange({ value: this.state.inputValue }); // If the date is not strictly equal, only change the tab that is displayed } else if (moment(this.state.inputValue, this.props.format).isValid()) { this.setState({ month: moment(this.state.inputValue, this.props.format).toDate(), }, this.showCurrentMonth); } } }, handleDaySelect (e, date, modifiers) { if (modifiers && modifiers.disabled) return; var value = moment(date).format(this.props.format); this.props.onChange({ value }); this.setState({ pickerIsOpen: false, month: date, inputValue: value, }); }, showPicker () { this.setState({ pickerIsOpen: true }, this.showCurrentMonth); }, showCurrentMonth () { if (!this.refs.picker) return; this.refs.picker.showMonth(this.state.month); }, handleFocus (e) { if (this.state.pickerIsOpen) return; this.showPicker(); }, handleCancel () { this.setState({ pickerIsOpen: false }); }, handleBlur (e) { let rt = e.relatedTarget || e.nativeEvent.explicitOriginalTarget; const popout = this.refs.popout.getPortalDOMNode(); while (rt) { if (rt === popout) return; rt = rt.parentNode; } this.setState({ pickerIsOpen: false, }); }, render () { const selectedDay = this.props.value; // react-day-picker adds a class to the selected day based on this const modifiers = { selected: (day) => moment(day).format(this.props.format) === selectedDay, }; return ( <div> <FormInput autoComplete="off" id={this.state.id} name={this.props.name} onBlur={this.handleBlur} onChange={this.handleInputChange} onFocus={this.handleFocus} onKeyPress={this.handleKeyPress} placeholder={this.props.format} ref="input" value={this.state.inputValue} /> <Popout isOpen={this.state.pickerIsOpen} onCancel={this.handleCancel} ref="popout" relativeToID={this.state.id} width={260} > <DayPicker modifiers={modifiers} onDayClick={this.handleDaySelect} ref="picker" tabIndex={-1} /> </Popout> </div> ); }, });
springboot/GReact/src/main/resources/static/app/components/layout/components/LayoutSwitcher.js
ezsimple/java
import React from 'react'; import {bindActionCreators} from 'redux' import {connect} from 'react-redux'; import classnames from 'classnames' import {config} from '../../../config/config'; import * as LayoutActions from '../LayoutActions' class LayoutSwitcher extends React.Component { constructor(props){ super(props); this.state = { isActivated : false } } onToggle = ()=> { this.setState({ isActivated: !this.state.isActivated }) }; render(){ return ( <div className={classnames('demo', { 'activate': this.state.isActivated })} > <span id="demo-setting" onClick={this.onToggle}> <i className="fa fa-cog txt-color-blueDark"/> </span> <form> <legend className="no-padding margin-bottom-10">Layout Options</legend> <section> <label><input type="checkbox" checked={this.props.fixedHeader} onChange={this.props.onFixedHeader} className="checkbox style-0"/><span>Fixed Header</span></label> <label><input type="checkbox" checked={this.props.fixedNavigation} onChange={this.props.onFixedNavigation} className="checkbox style-0"/><span>Fixed Navigation</span></label> <label><input type="checkbox" checked={this.props.fixedRibbon} onChange={this.props.onFixedRibbon} className="checkbox style-0"/><span>Fixed Ribbon</span></label> <label><input type="checkbox" checked={this.props.fixedPageFooter} onChange={this.props.onFixedPageFooter} className="checkbox style-0"/><span>Fixed Footer</span></label> <label><input type="checkbox" checked={this.props.insideContainer} onChange={this.props.onInsideContainer} className="checkbox style-0"/><span>Inside <b> .container</b></span></label> <label><input type="checkbox" checked={this.props.rtl} onChange={this.props.onRtl} className="checkbox style-0"/><span>RTL</span></label> <label><input type="checkbox" checked={this.props.menuOnTop} onChange={this.props.onMenuOnTop} className="checkbox style-0"/><span>Menu on <b>top</b></span></label> <label><input type="checkbox" checked={this.props.colorblindFriendly} onChange={this.props.onColorblindFriendly} className="checkbox style-0"/><span>For Colorblind <div className="font-xs text-right">(experimental) </div></span> </label><span id="smart-bgimages"/></section> <section><h6 className="margin-top-10 semi-bold margin-bottom-5">Clear Localstorage</h6><a onClick={this.props.factoryReset} className="btn btn-xs btn-block btn-primary" id="reset-smart-widget"><i className="fa fa-refresh"/> Factory Reset</a></section> <h6 className="margin-top-10 semi-bold margin-bottom-5">SmartAdmin Skins</h6> <section id="smart-styles"> { config.skins.map((skin) => { const check = this.props.smartSkin == skin.name ? <i className="fa fa-check fa-fw"/> : ''; const beta = skin.beta ? <sup>beta</sup> : ''; return <a onClick={this.props.onSmartSkin.bind(this, skin)} className={skin.class} style={skin.style} key={skin.name}>{check} {skin.label} {beta}</a> }) } </section> </form> </div> ) } } const mapStateToProps = (state, ownProps) => (state.layout); function mapDispatchToProps(dispatch) { return bindActionCreators(LayoutActions, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(LayoutSwitcher)
lib/ParallaxView.js
BigPun86/react-native-parallax-cached-image-view
'use strict'; import React, { Component } from 'react'; import ReactNative from 'react-native'; import Image from 'react-native-image-progress'; const { Dimensions, StyleSheet, View, ScrollView, Animated, ActivityIndicator } = ReactNative; const BlurView = require('react-native-blur').BlurView; const ScrollableMixin = require('react-native-scrollable-mixin'); const screen = Dimensions.get('window'); const ScrollViewPropTypes = ScrollView.propTypes; export default class ParallaxView extends Component { mixins: [ScrollableMixin] constructor(props) { super(props) const scrollY = new Animated.Value(0); this.state = { scrollY, onScroll: Animated.event( [{ nativeEvent: { contentOffset: { y: scrollY } } }] ) }; } /** * IMPORTANT: You must return the scroll responder of the underlying * scrollable component from getScrollResponder() when using ScrollableMixin. */ getScrollResponder() { return this._scrollView.getScrollResponder(); } setNativeProps(props) { this._scrollView.setNativeProps(props); } renderBackground() { var { windowHeight, backgroundSource, blur } = this.props; var { scrollY } = this.state; if (!windowHeight || !backgroundSource) { return null; } return ( <Animated.View style={[styles.background, { height: windowHeight + 15, // so children text component can overlap completeley transform: [{ translateY: scrollY.interpolate({ inputRange: [-windowHeight, 0, windowHeight], outputRange: [windowHeight / 2, 0, -windowHeight / 3] }) }, { scale: scrollY.interpolate({ inputRange: [-windowHeight, 0, windowHeight], outputRange: [2, 1, 1] }) }] }]} > <Image style={[styles.background, this.props.backgroundStyle, { height: windowHeight + 10 }]} source={{ ...backgroundSource, cache: 'force-cache' }}> <View style={{ flex: 1, backgroundColor: `rgba(0,0,0,${this.props.imageFilterOpacity})` }}> { !!blur && (BlurView || (BlurView = require('react-native-blur').BlurView)) && <BlurView blurType={blur} style={styles.blur} /> } </View> </Image> </Animated.View> ); } renderHeader() { var { windowHeight, backgroundSource } = this.props; var { scrollY } = this.state; if (!windowHeight || !backgroundSource) { return null; } return ( <Animated.View style={{ position: 'relative', height: windowHeight, opacity: scrollY.interpolate({ inputRange: [-windowHeight, 0, windowHeight / 1.2], outputRange: [1, 1, 0] }), }}> {this.props.header} </Animated.View> ); } render() { var { style } = this.props; var onScroll = this.props.onScroll ? e => { this.props.onScroll(e); this.state.onScroll(e); } : this.state.onScroll; return ( <View style={[styles.container, style]}> {this.renderBackground()} <ScrollView ref={component => { this._scrollView = component; }} {...this.props} style={styles.scrollView} onScroll={onScroll} scrollEventThrottle={16}> {this.renderHeader()} <View style={[styles.content, this.props.scrollableViewStyle]}> {this.props.children} </View> </ScrollView> </View> ); } } ParallaxView.propTypes = { ...ScrollViewPropTypes, windowHeight: React.PropTypes.number, backgroundStyle: React.PropTypes.object, backgroundSource: React.PropTypes.oneOfType([ React.PropTypes.shape({ uri: React.PropTypes.string, }), React.PropTypes.number, ]), header: React.PropTypes.node, blur: React.PropTypes.string, contentInset: React.PropTypes.object, imageFilterOpacity: React.PropTypes.number } ParallaxView.defaultProps = { windowHeight: 300, imageFilterOpacity: 0, contentInset: { top: screen.scale } } const styles = StyleSheet.create({ container: { flex: 1, borderColor: 'transparent', }, scrollView: { backgroundColor: 'transparent', }, background: { position: 'absolute', backgroundColor: 'white', width: screen.width }, blur: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundColor: 'transparent', }, content: { shadowColor: '#222', shadowOpacity: 0.3, shadowRadius: 2, backgroundColor: '#fff', flex: 1, flexDirection: 'column' } });
src/Parser/Rogue/Assassination/Modules/Legendaries/DuskwalkersFootpads.js
hasseboulen/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import Combatants from 'Parser/Core/Modules/Combatants'; import Analyzer from 'Parser/Core/Analyzer'; import SpellUsable from 'Parser/Core/Modules/SpellUsable'; import RESOURCE_TYPES from 'common/RESOURCE_TYPES'; import SpellLink from 'common/SpellLink'; /* * Equip: The remaining cooldown on Vendetta is reduced by 1 sec for every 65 Energy you expend. */ const VENDETTA_CDR_PER_ENERGY = 1 / 65; class DuskwalkersFootpads extends Analyzer { static dependencies = { combatants: Combatants, spellUsable: SpellUsable, }; totalReduction = 0; wastedReduction = 0; on_initialized() { this.active = this.combatants.selected.hasFeet(ITEMS.DUSKWALKERS_FOOTPADS.id); } on_byPlayer_spendresource(event) { if (event.resourceChangeType !== RESOURCE_TYPES.ENERGY.id || event.ability.guid === SPELLS.FEINT.id) { return; } const spent = event.resourceChange; const potentialReduction = spent * VENDETTA_CDR_PER_ENERGY; if (this.spellUsable.isOnCooldown(SPELLS.VENDETTA.id)) { const reduced = this.spellUsable.reduceCooldown(SPELLS.VENDETTA.id, potentialReduction * 1000) / 1000; this.totalReduction += reduced; this.wastedReduction += potentialReduction - reduced; } else { this.wastedReduction += potentialReduction; } } item() { return { item: ITEMS.DUSKWALKERS_FOOTPADS, result: ( <dfn data-tip={`You wasted ${this.wastedReduction.toFixed(1)} seconds of cooldown reduction.`}> Reduced <SpellLink id={SPELLS.VENDETTA.id} icon /> cooldown by {this.totalReduction.toFixed(1)} seconds. </dfn> ), }; } } export default DuskwalkersFootpads;
src/Interpolate.js
adampickeral/react-bootstrap
// https://www.npmjs.org/package/react-interpolate-component // TODO: Drop this in favor of es6 string interpolation import React from 'react'; import ValidComponentChildren from './utils/ValidComponentChildren'; const REGEXP = /\%\((.+?)\)s/; const Interpolate = React.createClass({ displayName: 'Interpolate', propTypes: { component: React.PropTypes.node, format: React.PropTypes.string, unsafe: React.PropTypes.bool }, getDefaultProps() { return { component: 'span', unsafe: false }; }, render() { let format = (ValidComponentChildren.hasValidComponent(this.props.children) || (typeof this.props.children === 'string')) ? this.props.children : this.props.format; let parent = this.props.component; let unsafe = this.props.unsafe === true; let props = {...this.props}; delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { let content = format.split(REGEXP).reduce(function(memo, match, index) { let html; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (React.isValidElement(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return React.createElement(parent, props); } else { let kids = format.split(REGEXP).reduce(function(memo, match, index) { let child; if (index % 2 === 0) { if (match.length === 0) { return memo; } child = match; } else { child = props[match]; delete props[match]; } memo.push(child); return memo; }, []); return React.createElement(parent, props, kids); } } }); export default Interpolate;
examples/with-react-router/src/index.js
suitejs/suite
import React from 'react'; import ReactDOM from 'react-dom'; import { HashRouter } from 'react-router-dom'; import App from './App'; import 'rsuite/es/styles/index.less'; ReactDOM.render( <HashRouter> <App /> </HashRouter>, document.getElementById('root') );
src/utils/children.js
chrismcv/material-ui
import React from 'react'; import createFragment from 'react-addons-create-fragment'; export default { create(fragments) { let newFragments = {}; let validChildrenCount = 0; let firstKey; //Only create non-empty key fragments for (let key in fragments) { const currentChild = fragments[key]; if (currentChild) { if (validChildrenCount === 0) firstKey = key; newFragments[key] = currentChild; validChildrenCount++; } } if (validChildrenCount === 0) return undefined; if (validChildrenCount === 1) return newFragments[firstKey]; return createFragment(newFragments); }, extend(children, extendedProps, extendedChildren) { return React.isValidElement(children) ? React.Children.map(children, (child) => { const newProps = typeof (extendedProps) === 'function' ? extendedProps(child) : extendedProps; const newChildren = typeof (extendedChildren) === 'function' ? extendedChildren(child) : extendedChildren ? extendedChildren : child.props.children; return React.cloneElement(child, newProps, newChildren); }) : children; }, };
app/components/Library.js
adjohnston/react-pattern-library
import React from 'react' import Nav from '../components/Nav' import childRoutes from '../utils/urls' const Library = ({children}) => { return ( <main className="rpl-container" role="main"> <Nav className="rpl-container__span rpl-container__span--auto" childRoutes={childRoutes} /> <div className="rpl-container__span"> {children} </div> </main> ) } export default Library
src/components/article/Youtube.js
garfieldduck/twreporter-react
'use strict' import BlockAlignmentWrapper from './BlockAlignmentWrapper' import React from 'react' // eslint-disable-next-line import YoutubePlayer from 'react-youtube' import cx from 'classnames' import commonStyles from './Common.scss' import styles from './Youtube.scss' // lodash import get from 'lodash/get' class Youtube extends React.Component { constructor(props) { super(props) } render() { const { content } = this.props let { description, youtubeId } = get(content, [ 0 ], {}) if (!youtubeId) { return null } return ( <div className={cx(styles['youtube-container'], 'hidden-print')}> <div className={styles['youtube-iframe-container']}> <YoutubePlayer videoId={youtubeId} /> </div> <div className={cx(commonStyles['desc-text-block'], 'text-justify')}>{description}</div> </div> ) } } Youtube.propTypes = { content: React.PropTypes.array.isRequired, device: React.PropTypes.string, styles: React.PropTypes.object } Youtube.defaultProps = { content: [], device: '', styles: {} } export const AlignedYoutube = BlockAlignmentWrapper(Youtube)
src/App.js
EKlevrai/courantderacines
import React, { Component } from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import io from 'socket.io-client'; import Menu from './menu/Menu'; import Chart from './components/chart/Chart'; import Home from './components/home/Home'; import Map from './components/map/Map'; const socket = io('http://80.240.136.144:2000'); global.logger = (d) => {socket.emit('action', d)} class App extends Component { componentDidMount(){ socket.emit('userAgent', navigator.userAgent); } render() { return ( <BrowserRouter> <div> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"></link> <Menu/> <Route path="/charts" component={Chart}/> <Route path="/maps" component={Map}/> <Route path="/" exact={true} component={Home}/> </div> </BrowserRouter> ); } } export default App;
src/components/Loader/Loader.js
shaohuawang2015/goldbeans-admin
import React from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' import styles from './Loader.less' const Loader = ({ spinning }) => { return (<div className={classNames(styles.loader, { [styles.hidden]: !spinning })}> <div className={styles.warpper}> <div className={styles.inner} /> <div className={styles.text} >LOADING</div> </div> </div>) } Loader.propTypes = { spinning: PropTypes.bool, } export default Loader
app/components/resources/randomResources.js
nypl-registry/browse
import React from 'react' // import Resource from '../../../models/resource.js' import RandomRecords from '../shared/randomRecords.js' const RandomResources = React.createClass({ render () { return <RandomRecords recordType='resource' records={this.props.resources} onFetch={this.props.onFetch} /> } }) export default RandomResources
src/components/active.js
casesandberg/reactcss
import React from 'react' export const active = (Component, Span = 'span') => { return class Active extends React.Component { state = { active: false } handleMouseDown = () => this.setState({ active: true }) handleMouseUp = () => this.setState({ active: false }) render = () => ( <Span onMouseDown={ this.handleMouseDown } onMouseUp={ this.handleMouseUp }> <Component { ...this.props } { ...this.state } /> </Span> ) } } export default active
src/components/Header/Header.js
przeor/ReactC
import React from 'react' import { IndexLink, Link } from 'react-router' import classes from './Header.scss' let loginObj = { user: '', password: '' } const usernameOnChange = (e) => { loginObj.user = e.target.value } const passwordOnChange = (e) => { loginObj.password = e.target.value } const prepareLoginJSX = (props) => (<div> <form onSubmit={props.handleLogin.bind(undefined, loginObj)}> <input type='input' placeholder='username' style={{width: 100}} name='username' onChange={usernameOnChange} /> <input type='input' placeholder='password' style={{width: 100}} name='password' onChange={passwordOnChange} /> <input type='submit' value={ 'Login Now' } /> </form> </div>) export const Header = (props) => { let loginFormJSX let loginMessageJSX = null if(props.session.isNotLoggedIn) { if(props.session.loginToken === 'invalid') { loginMessageJSX = <p>Invalid login details, please try with correct user and password</p> } loginFormJSX = prepareLoginJSX(props) } else { loginFormJSX = null } return ( <div> <h1>React Redux Starter Kit</h1> <div> <IndexLink to='/' activeClassName={classes.activeRoute}> Home </IndexLink> {' · '} <Link to='/counter' activeClassName={classes.activeRoute}> Counter </Link> {' · '} <Link to='/dashboard' activeClassName={classes.activeRoute}> Dashboard </Link> </div> {loginFormJSX} {loginMessageJSX} </div> ) } export default Header
App/Platform/RefreshableListView.android.js
taskrabbit/ReactNativeSampleApp
import React from 'react'; import { ListView, RefreshControl, } from 'react-native'; import isPromise from 'is-promise'; function delay(time) { return new Promise((resolve) => setTimeout(resolve, time)); } class RefreshableListView extends React.Component { static propTypes = { loadData: React.PropTypes.func.isRequired, minDisplayTime: React.PropTypes.number, minBetweenTime: React.PropTypes.number, androidRefreshable: React.PropTypes.bool, }; static defaultProps = { loadData: (() => {}), minDisplayTime: 300, minBetweenTime: 300, androidRefreshable: true, }; constructor(props) { super(props); this.state = {}; } handleRefresh = () => { if (this.willRefresh) return; this.willRefresh = true; var loadingDataPromise = new Promise((resolve) => { var loadDataReturnValue = this.props.loadData(resolve); if (isPromise(loadDataReturnValue)) { loadingDataPromise = loadDataReturnValue; } Promise.all([ loadingDataPromise, new Promise((resolve) => this.setState({isRefreshing: true}, resolve)), delay(this.props.minDisplayTime), ]) .then(() => delay(this.props.minBetweenTime)) .then(() => { this.willRefresh = false; this.setState({isRefreshing: false}); }); }); }; render() { const listViewProps = { dataSource: this.props.dataSource, renderRow: this.props.renderRow, renderFooter: this.props.renderFooter, style: [this.props.style, {flex: 1}], renderScrollComponent: this.props.renderScrollComponent, renderHeader: this.props.renderHeaderWrapper, }; const pullToRefreshProps = { style: [this.props.pullToRefreshStyle, {flex: 1}], refreshing: this.state.isRefreshing || false, onRefresh: this.handleRefresh, enabled: this.props.androidRefreshable, }; return ( <RefreshControl {...pullToRefreshProps}> <ListView {...listViewProps} /> </RefreshControl> ); } } export default RefreshableListView;
client/admin/viewLogs/ViewLogs.stories.js
subesokun/Rocket.Chat
import React from 'react'; import ViewLogs from './ViewLogs'; export default { title: 'admin/pages/ViewLogs', component: ViewLogs, decorators: [ (storyFn) => <div className='rc-old' style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}> {storyFn()} </div>, ], }; export const _default = () => <ViewLogs />;
app/javascript/mastodon/features/list_adder/index.js
tootcafe/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { injectIntl } from 'react-intl'; import { setupListAdder, resetListAdder } from '../../actions/lists'; import { createSelector } from 'reselect'; import List from './components/list'; import Account from './components/account'; import NewListForm from '../lists/components/new_list_form'; // hack const getOrderedLists = createSelector([state => state.get('lists')], lists => { if (!lists) { return lists; } return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title'))); }); const mapStateToProps = state => ({ listIds: getOrderedLists(state).map(list=>list.get('id')), }); const mapDispatchToProps = dispatch => ({ onInitialize: accountId => dispatch(setupListAdder(accountId)), onReset: () => dispatch(resetListAdder()), }); export default @connect(mapStateToProps, mapDispatchToProps) @injectIntl class ListAdder extends ImmutablePureComponent { static propTypes = { accountId: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, onInitialize: PropTypes.func.isRequired, onReset: PropTypes.func.isRequired, listIds: ImmutablePropTypes.list.isRequired, }; componentDidMount () { const { onInitialize, accountId } = this.props; onInitialize(accountId); } componentWillUnmount () { const { onReset } = this.props; onReset(); } render () { const { accountId, listIds } = this.props; return ( <div className='modal-root__modal list-adder'> <div className='list-adder__account'> <Account accountId={accountId} /> </div> <NewListForm /> <div className='list-adder__lists'> {listIds.map(ListId => <List key={ListId} listId={ListId} />)} </div> </div> ); } }
containers/Main.js
sayakbiswas/Git-Blogger
import React from 'react'; import { HashRouter, Switch, Route } from 'react-router-dom'; import Home from './Home'; import LandingScreenContainer from './LandingScreenContainer'; import DashboardContainer from './DashboardContainer'; import SetupScreenContainer from './SetupScreenContainer'; class Main extends React.Component { constructor(props) { super(props); } render() { return( <HashRouter> <Home> <Switch> <Route exact path="/" component={LandingScreenContainer} /> <Route path="/landing" component={LandingScreenContainer} /> <Route path="/dashboard" component={DashboardContainer} /> <Route path="/setupnew" component={SetupScreenContainer} /> </Switch> </Home> </HashRouter> ); } } module.exports = Main;
example/src/screens/text.js
cereigido/react-native-ez-layouts
import React, { Component } from 'react'; import { MonospacedText, Row, Separator, SmallText, Subtitle, Text, Title, View } from '../../../src'; class TextScreen extends Component { static navigationOptions = { title: 'Texts', } render() { return ( <View padding scroll> <MonospacedText>{`<Title>This is a title</Title>`}</MonospacedText> <Title>This is a title</Title> <Separator /> <MonospacedText>{`<Subtitle>This is a subtitle</Subtitle>`}</MonospacedText> <Subtitle>This is a subtitle</Subtitle> <Separator /> <MonospacedText>{`<Text>This is a regular text</Text>`}</MonospacedText> <Text>This is a regular text</Text> <Separator /> <MonospacedText>{`<SmallText>This is a small text</SmallText>`}</MonospacedText> <SmallText>This is a small text</SmallText> <Separator /> <MonospacedText>{`<MonospacedText>This is a monospaced text</MonospacedText>`}</MonospacedText> <MonospacedText>This is a monospaced text</MonospacedText> </View> ); } } export { TextScreen };
lib/components/MapPolygon.js
lelandrichardson/react-native-maps
import PropTypes from 'prop-types'; import React from 'react'; import { ColorPropType, ViewPropTypes, View } from 'react-native'; import decorateMapComponent, { USES_DEFAULT_IMPLEMENTATION, SUPPORTED, } from './decorateMapComponent'; import * as ProviderConstants from './ProviderConstants'; // if ViewPropTypes is not defined fall back to View.propType (to support RN < 0.44) const viewPropTypes = ViewPropTypes || View.propTypes; const propTypes = { ...viewPropTypes, /** * An array of coordinates to describe the polygon */ coordinates: PropTypes.arrayOf( PropTypes.shape({ /** * Latitude/Longitude coordinates */ latitude: PropTypes.number.isRequired, longitude: PropTypes.number.isRequired, }) ), /** * An array of array of coordinates to describe the polygon holes */ holes: PropTypes.arrayOf( PropTypes.arrayOf( PropTypes.shape({ /** * Latitude/Longitude coordinates */ latitude: PropTypes.number.isRequired, longitude: PropTypes.number.isRequired, }) ) ), /** * Callback that is called when the user presses on the polygon */ onPress: PropTypes.func, /** * Boolean to allow a polygon to be tappable and use the * onPress function */ tappable: PropTypes.bool, /** * The stroke width to use for the path. */ strokeWidth: PropTypes.number, /** * The stroke color to use for the path. */ strokeColor: ColorPropType, /** * The fill color to use for the path. */ fillColor: ColorPropType, /** * The order in which this tile overlay is drawn with respect to other overlays. An overlay * with a larger z-index is drawn over overlays with smaller z-indices. The order of overlays * with the same z-index is arbitrary. The default zIndex is 0. * * @platform android */ zIndex: PropTypes.number, /** * The line cap style to apply to the open ends of the path. * The default style is `round`. * * @platform ios */ lineCap: PropTypes.oneOf(['butt', 'round', 'square']), /** * The line join style to apply to corners of the path. * The default style is `round`. * * @platform ios */ lineJoin: PropTypes.oneOf(['miter', 'round', 'bevel']), /** * The limiting value that helps avoid spikes at junctions between connected line segments. * The miter limit helps you avoid spikes in paths that use the `miter` `lineJoin` style. If * the ratio of the miter length—that is, the diagonal length of the miter join—to the line * thickness exceeds the miter limit, the joint is converted to a bevel join. The default * miter limit is 10, which results in the conversion of miters whose angle at the joint * is less than 11 degrees. * * @platform ios */ miterLimit: PropTypes.number, /** * Boolean to indicate whether to draw each segment of the line as a geodesic as opposed to * straight lines on the Mercator projection. A geodesic is the shortest path between two * points on the Earth's surface. The geodesic curve is constructed assuming the Earth is * a sphere. * */ geodesic: PropTypes.bool, /** * The offset (in points) at which to start drawing the dash pattern. * * Use this property to start drawing a dashed line partway through a segment or gap. For * example, a phase value of 6 for the patter 5-2-3-2 would cause drawing to begin in the * middle of the first gap. * * The default value of this property is 0. * * @platform ios */ lineDashPhase: PropTypes.number, /** * An array of numbers specifying the dash pattern to use for the path. * * The array contains one or more numbers that indicate the lengths (measured in points) of the * line segments and gaps in the pattern. The values in the array alternate, starting with the * first line segment length, followed by the first gap length, followed by the second line * segment length, and so on. * * This property is set to `null` by default, which indicates no line dash pattern. * * @platform ios */ lineDashPattern: PropTypes.arrayOf(PropTypes.number), }; const defaultProps = { strokeColor: '#000', strokeWidth: 1, }; class MapPolygon extends React.Component { setNativeProps(props) { this.polygon.setNativeProps(props); } updateNativeProps() { return () => { const { fillColor, strokeColor, strokeWidth } = this.props; let polygonNativeProps = {}; if (fillColor) { polygonNativeProps.fillColor = fillColor; } if (strokeColor) { polygonNativeProps.strokeColor = strokeColor; } if (strokeWidth) { polygonNativeProps.strokeWidth = strokeWidth; } if (polygonNativeProps) { this.setNativeProps(polygonNativeProps); } }; } render() { const AIRMapPolygon = this.getAirComponent(); return ( <AIRMapPolygon {...this.props} ref={ref => { this.polygon = ref; }} onLayout={ this.context.provider === ProviderConstants.PROVIDER_GOOGLE ? this.updateNativeProps() : undefined } /> ); } } MapPolygon.propTypes = propTypes; MapPolygon.defaultProps = defaultProps; export default decorateMapComponent(MapPolygon, { componentType: 'Polygon', providers: { google: { ios: SUPPORTED, android: USES_DEFAULT_IMPLEMENTATION, }, }, });
src/svg-icons/action/tab.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTab = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h10v4h8v10z"/> </SvgIcon> ); ActionTab = pure(ActionTab); ActionTab.displayName = 'ActionTab'; ActionTab.muiName = 'SvgIcon'; export default ActionTab;
website/src/pages/components/Section.js
webdriverio/webdriverio
import React from 'react' import styles from './Section.module.css' export default function Section({ isDark, children }) { return ( <section className={[styles.section, ...(isDark ? [styles.darkSection, 'darkSection'] : [])].join(' ')}> <div className="container"> <div className="row"> {children} </div> </div> </section> ) }
src/views/components/task-item/task-item.js
connorbanderson/CoinREXX
import React, { Component } from 'react'; import classNames from 'classnames'; import PropTypes from 'prop-types'; import Button from '../button'; import Icon from '../icon'; import './task-item.css'; export class TaskItem extends Component { constructor() { super(...arguments); this.state = {editing: false}; this.edit = this.edit.bind(this); this.handleKeyUp = this.handleKeyUp.bind(this); this.remove = this.remove.bind(this); this.save = this.save.bind(this); this.stopEditing = this.stopEditing.bind(this); this.toggleStatus = this.toggleStatus.bind(this); } edit() { this.setState({editing: true}); } handleKeyUp(event) { if (event.keyCode === 13) { this.save(event); } else if (event.keyCode === 27) { this.stopEditing(); } } remove() { this.props.removeTask(this.props.task); } save(event) { if (this.state.editing) { const { task } = this.props; const title = event.target.value.trim(); if (title.length && title !== task.title) { this.props.updateTask(task, {title}); } this.stopEditing(); } } stopEditing() { this.setState({editing: false}); } toggleStatus() { const { task } = this.props; this.props.updateTask(task, {completed: !task.completed}); } renderTitle(task) { return ( <div className="task-item__title" tabIndex="0"> {task.title} </div> ); } renderTitleInput(task) { return ( <input autoComplete="off" autoFocus className="task-item__input" defaultValue={task.title} maxLength="64" onKeyUp={this.handleKeyUp} type="text" /> ); } render() { const { editing } = this.state; const { task } = this.props; let containerClasses = classNames('task-item', { 'task-item--completed': task.completed, 'task-item--editing': editing }); return ( <div className={containerClasses} tabIndex="0"> <div className="cell"> <Button className={classNames('btn--icon', 'task-item__button', {'active': task.completed, 'hide': editing})} onClick={this.toggleStatus}> <Icon name="done" /> </Button> </div> <div className="cell"> {editing ? this.renderTitleInput(task) : this.renderTitle(task)} </div> <div className="cell"> <Button className={classNames('btn--icon', 'task-item__button', {'hide': editing})} onClick={this.edit}> <Icon name="mode_edit" /> </Button> <Button className={classNames('btn--icon', 'task-item__button', {'hide': !editing})} onClick={this.stopEditing}> <Icon name="clear" /> </Button> <Button className={classNames('btn--icon', 'task-item__button', {'hide': editing})} onClick={this.remove}> <Icon name="delete" /> </Button> </div> </div> ); } } TaskItem.propTypes = { removeTask: PropTypes.func.isRequired, task: PropTypes.object.isRequired, updateTask: PropTypes.func.isRequired }; export default TaskItem;
app/components/shared/labelledFormComponent.js
buildkite/frontend
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import FormInputHelp from './FormInputHelp'; import FormInputErrors from './FormInputErrors'; import FormInputLabel from './FormInputLabel'; export default function labelledFormComponent(FormComponent) { return class LabelledFormComponent extends React.Component { static displayName = `Labelled(${FormComponent.displayName || FormComponent.name || FormComponent})`; static propTypes = { className: PropTypes.string, defaultValue: PropTypes.string, errors: PropTypes.array, help: PropTypes.node, label: PropTypes.string.isRequired, required: PropTypes.bool }; constructor(props) { super(props); if (this.constructor.proxyMethods && this.constructor.proxyMethods.length) { this.constructor.proxyMethods.forEach((method) => { this[method] = (...args) => this.input[method](...args); }); } } render() { const { className, errors, label, help, ...props } = this.props; const hasErrors = this.props.errors && this.props.errors.length > 0; return ( <div className="mb2"> <FormInputLabel label={label} errors={hasErrors} required={props.required} > <FormComponent {...props} className={classNames('input', { 'is-error': hasErrors }, className)} ref={(input) => this.input = input} /> </FormInputLabel> <FormInputErrors errors={errors} /> <FormInputHelp>{help}</FormInputHelp> </div> ); } set value(val) { return this.input ? this.input.value = val : null; } get value() { return this.input ? this.input.value : this.props.defaultValue; } focus() { this.input.focus(); this.input.selectionStart = this.input.selectionEnd = this.input.value.length; } }; }
packages/@vega/layout/src/components/ToolContainer.js
VegaPublish/vega-studio
import React from 'react' import PropTypes from 'prop-types' import tools from 'all:part:@lyra/base/tool' import {RouteScope} from 'part:@vega/core/router' function ToolContainer(props) { if (!tools.length) { return ( <div> No tools fulfill the role <code>`tool:@lyra/base/tool`</code> </div> ) } const {toolName} = props const activeTool = tools.find(tool => tool.name === toolName) if (!activeTool) { return ( <div> Ooops! Tool <code>{toolName}</code> is not among available tools{' '} <code>[{tools.map(tool => tool.name).join(', ')}]</code> </div> ) } const ActiveTool = activeTool.component return ( <RouteScope scope={toolName}> <ActiveTool {...props} /> </RouteScope> ) } ToolContainer.propTypes = { toolName: PropTypes.string.isRequired } export default ToolContainer
pages/doc/publish-your-data.js
sgmap/inspire
import React from 'react' import PropTypes from 'prop-types' import attachI18n from '../../components/hoc/attach-i18n' import Page from '../../components/page' import Meta from '../../components/meta' import Content from '../../components/content' import Container from '../../components/container' import Link from '../../components/link' const PublishYourDataPage = ({tReady}) => ( <Page ready={tReady}> {() => ( <React.Fragment> <Meta title='Publier sur data.gouv.fr' description='Documentation sur la publication de vos données sur data.gouv.fr' /> <Content> <Container> <h1>Publier sur data.gouv.fr</h1> <div> <h2>Sommaire</h2> <ul> <li><a href='#prerequisites'>Pré-requis applicables aux données</a></li> <li><a href='#step-by-step'>Utilisation pas à pas</a></li> <li><a href='#account'>Compte et organisation sur data.gouv.fr</a></li> <li><a href='#harvesting'>Référencement et moissonnage du flux CSW</a></li> <li><a href='#organizations'>Gestion de vos organisations</a></li> <li><a href='#add-catalogs'>Ajouter des catalogues source à l’organisation</a></li> <li><a href='#associate-producers'>Associer des producteurs au catalogue</a></li> <li><a href='#publish'>Publier sur data.gouv.fr</a></li> </ul> </div> <h3 id='prerequisites'>Pré-requis applicables aux données</h3> <p> Afin que vos données puissent être intégrées à data.gouv.fr via la passerelle, il faut qu’elles disposent de métadonnées et que celles-ci remplissent tous les critères suivants : </p> <ul> <li>avoir le mot-clé <b>données ouvertes</b> ;</li> <li>avoir une licence ouverte et indiquer qu’il n’y a aucune limitation au sens INSPIRE ;</li> <li>être présentes dans un catalogue librement accessible via CSW ;</li> <li>contenir au moins un lien de téléchargement opérationnel.</li> </ul> <p> Remarque : le premier critère n’est pas toujours requis. En effet, si les métadonnées pointent vers une licence reconnue comme ouverte, geo.data.gouv.fr passera outre ce critère. </p> <p>Les liens de téléchargement reconnus sont :</p> <ul> <li>lien vers un service WFS ;</li> <li>lien vers des fichiers de données vecteur aux formats GeoJSON, Shapefile, MapInfo MIF/MID, MapInfo TAB et GML ;</li> <li>lien vers des fichiers de données raster aux formats ECW, JPEG2000 et GeoTIFF.</li> </ul> <p>Les liens vers des fichiers PDF ne sont pas reconnus comme des liens vers des données.</p> <h3 id='step-by-step'>Utilisation pas à pas</h3> <p>Pour publier des métadonnées via geo.data.gouv.fr vous devez suivre les étapes suivantes :</p> <ul className='numbers'> <li>Vérifiez que vous disposez d’un compte sur data.gouv.fr et qu’il est associé à une organisation référencée ;</li> <li>Référencez votre flux CSW et vérifiez que le moissonnage est opérationnel ;</li> <li>Associez des producteurs référencés dans les métadonnées de votre flux CSW à votre organisation ;</li> <li>Publier les métadonnées pertinentes sur data.gouv.fr</li> </ul> <p>Ces étapes sont détaillées dans les chapitres suivants.</p> <h3 id='account'>Compte et organisation sur data.gouv.fr</h3> <p>Pour publier des données via geo.data.gouv.fr, vous devez disposer d’un compte compte individuel sur data.gouv.fr et de l’associer à une organisation.</p> <ul className='numbers'> <li> <p>Créer un compte sur data.gouv.fr</p> <p>Pour créer un compte ou se connecter : <a href='https://www.data.gouv.fr/login'>https://www.data.gouv.fr/login</a>.</p> <img src='/static/documentation/datagouv_authentification.png' alt='Se connecter ou créer un compte sur data.gouv.fr' /> </li> <li> <p>Créer / rejoindre une organisation sur data.gouv.fr</p> <p> Pour cela, il faut passer par l’administration de son profil : <a href='https://www.data.gouv.fr/fr/admin/organization/new/'>https://www.data.gouv.fr/fr/admin/organization/new/</a>. Si elle existe déjà, faites une demande pour la rejoindre. </p> <img src='/static/documentation/datagouv_create_org.png' alt='Créer son organisation sur data.gouv.fr' /> </li> </ul> <h3 id='harvesting'>Référencement et moissonnage du flux CSW</h3> <ul className='numbers'> <li> <p>Demander à ce que votre flux CSW soit référencé</p> <p>Pour référencer le flux CSW de votre catalogue, écrivez à contact@geo.data.gouv.fr en indiquant votre compte data.gouv.fr, votre / vos organisation(s) et bien sûr le(s) flux concerné(s).</p> </li> <li> <p>Lancer le moissonnage de son catalogue</p> <p>Une fois votre flux CSW référencé par l’équipe de data.gouv.fr, il faut lancer le moissonnage. Pour cela :</p> <ul> <li> <Link href='/catalogs'><a>se rendre sur liste des catalogues</a></Link> </li> <li>cliquez sur votre catalogue ;</li> <li> <p>puis dans la section <b>Moissonnage du catalogue</b> cliquez sur <b>Moissonner ce catalogue</b>.</p> <img src='/static/documentation/catalog_harvesting.png' alt='Moissonnage du catalogue' /> </li> </ul> </li> <li> <p>Vérifier le moissonnage</p> <p>Une fois la synchronisation terminée (actualiser la page au bout de quelques minutes selon le nombre de métadonnées à moissonner), il est possible d’effectuer une recherche.</p> <p>Plusieurs filtres facilitent la consultation des métadonnées moissonnées :</p> <ul> <li><b>Disponibilité = Oui</b> : limite l’affichage aux métadonnées dont les données sont accessibles (cf. <a href='#prerequisites'>prérequis</a>)</li> <li><b>Type de résultat = Jeu de données ou Jeu de données (non géographiques)</b> : en choisissant ’Jeu de données’, seules les métadonnées publiées à l’origine en ISO 19139 sont affichées ; en choisissant ’Jeu de données (non géographiques)’, seules les métadonnées publiées à l’origine en Dublin Core sont affichées</li> <li><b>Donnée ouverte = Oui</b> : limite l’affichage aux données ouvertes dont la licence est reconnue par data.gouv.fr. Exemples de licences non reconnues par data.gouv.fr : la licence engagée et la licence associée du Grand-Lyon</li> <li> <p><b>Publié sur data.gouv.fr = Oui</b> : identifie les métadonnées moissonnées par geo.data.gouv.fr et déjà publiées sur data.gouv.fr</p> <img src='/static/documentation/search_datasets.png' alt='Recherche jeux de données' /> <p>Si une donnée semble ne pas être disponible, revérifier les <a href='#prerequisites'>prérequis</a> puis <a href='contact@geo.data.gouv.fr'>contacter l’équipe data.gouv.fr</a>.</p> </li> </ul> </li> </ul> <h3 id='organizations'>Gestion de vos organisations</h3> <ul className='numbers'> <li> <p>Aller sur <Link href='/'><a>https://geo.data.gouv.fr/</a></Link> et cliquer sur <b>Publier des données</b></p> <img src='/static/documentation/home_page.png' alt='Page d’accueil de geo.data.gouv.fr' /> </li> <li> <p>Choisir l’organisation à configurer</p> <img src='/static/documentation/organizations.png' alt='Choisir parmi ses organisations' /> </li> </ul> <h3 id='add-catalogs'>Ajouter des catalogues source à l’organisation</h3> <ul className='numbers'> <li> <p>Accéder à la <a href='#account'>page de votre organisation</a></p> <ul> <li> <p>cliquer sur le bouton <b>Ajouter des catalogues</b> puis, dans la liste, ajouter le ou les catalogues correspondant aux flux que vous avez référencé précédemment.</p> <img src='/static/documentation/catalogs.png' alt='Choisir parmi les catalogues sources référencés' /> </li> </ul> </li> </ul> <h3 id='associate-producers'>Associer des producteurs au catalogue</h3> <p>Il s’agit de faire correspondre les contacts renseignés dans la métadonnée et le producteur identifié de la donnée. Par exemple, l’administrateur d’une IDG pourra indiquer à quels ayant-droits correspondent quelles données :</p> <img className='small' src='/static/documentation/associated_producers.png' alt='Aperçu des producteurs associés' /> <ul> <li> <p>Accéder à la <a href='#account'>page de votre organisation</a></p> <ul> <li>cliquez sur <b>Associer des producteurs</b></li> <li>ajouter les producteurs pour lesquels vous assumerez la publication des métadonnées.</li> </ul> <img src='/static/documentation/associate_producers.png' alt='Choisir parmi les producteurs à associer' /> <p>Lors de cette dernière étape, vous ne devez pas sélectionner des producteurs dont vous n’avez pas la responsabilité. En effet, une fois que vous aurez associé un producteur à votre organisation aucune autre organisation ne pourra l’associer à son propre compte. Vous ne devez donc pas associer à votre organisation des producteurs dont la politique de publication doit être assurer indépendamment de la vôtre.</p> <p>Typiquement, n’associez pas l’IGN, le BRGM, l’INSEE ou d’autres producteurs de données de ce type si vous ne faites pas partie de ces organismes. Par contre, il peut être très pertinent qu’un EPCI prenne en charge la publication des données pour le compte de ses communes.</p> </li> </ul> <h3 id='publish'>Publier sur data.gouv.fr</h3> <ul className='numbers'> <li> <p><a href='#account'>Accéder à la page de votre organisation</a></p> <img className='small' src='/static/documentation/datasets.png' alt='Jeux de données d’une organisation' /> <ul> <li>cliquez sur <b>Publier des données</b></li> </ul> <p>Le premier cadre au haut de la page dresse un état des lieux des données publiables au sens de data.gouv.fr: - les données déjà publiées et accessibles sur data.gouv.fr ; - les données en attente de publication : les données vérifiant les prérequis, issues de producteurs associés à votre organisme et qui n’ont pas encore été publiées (elles sont en attente d’une action de votre part).</p> <p>Les données qui ne vérifient pas les <a href='#prerequisites'>prérequis</a> et qui ne sont pas issues de producteurs associés à votre organisme n’apparaissent pas dans cette page.</p> <img src='/static/documentation/awaiting_publication.png' alt='Données en attente de publication' /> </li> <li> <p>Publier des données</p> <ul> <li>sélectionner les données que vous souhaitez publié en cochant la case ;</li> <li>ou sélectionner toutes les données en attente en cliquant sur le bouton <b>Tout sélectionner</b> ;</li> <li>une fois la sélection effectuée, cliquer sur <b>Publier les données sélectionnées</b>.</li> </ul> </li> </ul> </Container> </Content> <style jsx>{` h1 { font-size: 1.8rem; font-weight: 500; margin-bottom: 1em; } ul.numbers { list-style-type: decimal; } img { margin: 1em 0; box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.3); max-width: 700px; } img.small { width: 400px; } @media (max-width: 767px) { img, img.small { width: 100%; } a { display: block; } } `}</style> </React.Fragment> )} </Page> ) PublishYourDataPage.propTypes = { tReady: PropTypes.bool.isRequired } export default attachI18n()(PublishYourDataPage)
src/pages/projects/main.js
bhuvanmalik007/bhuvanmalik
import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import Box from 'grommet/components/Box' import Anchor from 'grommet/components/Anchor' import Menu from 'grommet/components/Menu' import GunmetalHeading from '../../components/gunmetalheading' import texture from '../../static/texture.png' import FilterIcon from 'grommet/components/icons/base/Filter' import Card from 'grommet/components/Card' import Columns from 'grommet/components/Columns' import Image from 'grommet/components/Image' import Paragraph from 'grommet/components/Paragraph' import Heading from 'grommet/components/Heading' import { Label as SLabel } from 'semantic-ui-react' import SocialGithubIcon from 'grommet/components/icons/base/SocialGithub' import Animate from 'grommet/components/Animate' const ClickableImage = styled(Image)` cursor: pointer; border: 5px; ` const Projects = ({ filteredArray, filterProjects, allProjects, currentFilter }) => ( <div> <Box direction='row' full='horizontal' texture={texture} justify='start' appCentered pad={{ horizontal:'large', vertical:'medium' }}> <GunmetalHeading size='large' align='center' strong>PROJECTS</GunmetalHeading> </Box> <Box direction='row' full='horizontal' justify='center' pad={{ horizontal:'large', vertical:'large' }}> <Menu responsive size='large' label='Filter' icon={<FilterIcon />} inline direction='row'> <Anchor onClick={allProjects} className={currentFilter === 'all' ? 'active' : ''}> All </Anchor> <Anchor onClick={() => filterProjects('React')} className={currentFilter === 'React' ? 'active' : ''}> React/Redux </Anchor> <Anchor onClick={() => filterProjects('Angular')} className={currentFilter === 'Angular' ? 'active' : ''}> Angular JS </Anchor> <Anchor onClick={() => filterProjects('Node')} className={currentFilter === 'Node' ? 'active' : ''}> Node </Anchor> <Anchor onClick={() => filterProjects('Elixir')} className={currentFilter === 'Elixir' ? 'active' : ''}> Elixir </Anchor> <Anchor onClick={() => filterProjects('Electron')} className={currentFilter === 'Electron' ? 'active' : ''}> Electron </Anchor> <Anchor onClick={() => filterProjects('Cpp')} className={currentFilter === 'Cpp' ? 'active' : ''}> C++ </Anchor> </Menu> </Box> <Box direction='column' align='center' justify='center' pad='large' colorIndex='light-2'> <Animate enter={{ 'animation': 'slide-up', 'duration': 1000, 'delay': 100 }}> <Columns size='xxsmall' justify='between' maxCount={3} masonry> {filteredArray.map((project, index) => <Box key={index} pad='none' margin='medium'> <Card colorIndex='light-1' contentPad='small'> {project.img && <ClickableImage src={project.img} onClick={_ => window.open(project.link, '_blank')} />} <Heading margin='small'>{project.name} { project.github && <Anchor target='_blank' icon={<SocialGithubIcon size='medium' />} href={project.github} /> } </Heading> <div>{project.tech.map((tech, index) => <SLabel key={index} color={tech.color}>{tech.name}</SLabel>)} </div> <Paragraph margin='small'>{project.description}</Paragraph> </Card> </Box> )} </Columns> </Animate> </Box> </div> ) Projects.propTypes = { filteredArray: PropTypes.array, filterProjects: PropTypes.func, allProjects: PropTypes.func, currentFilter: PropTypes.string } export default Projects