path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
techCurriculum/ui/solutions/6.1/src/components/Title.js
jennybkim/engineeringessentials
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ import React from 'react'; function Title() { return ( <div> <h1>Cards</h1> <h2>Share your ideas</h2> </div> ); } export default Title;
folktale-react/src/index.js
Muzietto/react-playground
import React from 'react'; import ReactDOM from 'react-dom'; import Maybe from 'folktale/maybe'; import compose from 'folktale/core/lambda/compose'; ReactDOM.render(<App />, document.getElementById('root')); function App() { const inc = x => x + 1; const double = x => x * 2; const theMaybe = Maybe.Just(1).map(compose(double, inc)); const n = 5; const result = n |> double |> double |> (x => { console.log(x); return x + 1; }) |> double; return <div> {`theMaybe=${theMaybe}`} <hr /> {`result=${result}`} </div>; }
components/Tools/AvailableHours.js
juhojo/WLO
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Card, CardActions, CardHeader, CardText } from 'material-ui/Card'; import Slider from 'material-ui/Slider'; export default class AvailableHours extends Component { constructor(props) { super(props); this.state = { expanded: false, }; } handleExpandChange(expanded) { this.setState({expanded: expanded}); }; sliderChange(e, value) { const { updateHours } = this.props; updateHours(value); } render() { const { hours } = this.props; const { expanded } = this.state; const headerText = expanded ? "Available hours" : `Available hours (${hours * 400} hours)`; return ( <Card expanded={expanded} onExpandChange={this.handleExpandChange.bind(this)}> <CardHeader title={headerText} actAsExpander={true} showExpandableButton={true} /> <CardText expandable={true}> Choose the amount of hours you have available for courses. <Slider name="hours" onChange={this.sliderChange.bind(this)} step={0.10} value={hours} /> <p style={{ textAlign: 'center' }}>{hours * 400} hours</p> </CardText> </Card> ); } } AvailableHours.propTypes = { hours: React.PropTypes.number, updateHours: React.PropTypes.func, }
src/smif/app/test/components/Simulation/Stepper.js
tomalrussell/smif
import React from 'react' import sinon from 'sinon' import {expect} from 'chai' import {mount} from 'enzyme' import {describe, it} from 'mocha' import Stepper from 'components/Simulation/Stepper' describe('<Stepper />', () => { it('step unstarted', () => { let wrapper = mount(<Stepper status='unstarted'/>) expect(wrapper.find('[id="step_ready"]').at(0).html()).to.include('rc-steps-item-process') expect(wrapper.find('[id="step_queuing"]').at(0).html()).to.include('rc-steps-item-wait') expect(wrapper.find('[id="step_running"]').at(0).html()).to.include('rc-steps-item-wait') expect(wrapper.find('[id="step_completed"]').at(0).html()).to.include('rc-steps-item-wait') }) it('step queing', () => { let wrapper = mount(<Stepper status='queing'/>) expect(wrapper.find('[id="step_ready"]').at(0).html()).to.include('rc-steps-item-finish') expect(wrapper.find('[id="step_queuing"]').at(0).html()).to.include('rc-steps-item-process') expect(wrapper.find('[id="step_running"]').at(0).html()).to.include('rc-steps-item-wait') expect(wrapper.find('[id="step_completed"]').at(0).html()).to.include('rc-steps-item-wait') }) it('step running', () => { let wrapper = mount(<Stepper status='running'/>) expect(wrapper.find('[id="step_ready"]').at(0).html()).to.include('rc-steps-item-finish') expect(wrapper.find('[id="step_queuing"]').at(0).html()).to.include('rc-steps-item-finish') expect(wrapper.find('[id="step_running"]').at(0).html()).to.include('rc-steps-item-process') expect(wrapper.find('[id="step_completed"]').at(0).html()).to.include('rc-steps-item-wait') }) it('step stopped', () => { let wrapper = mount(<Stepper status='stopped'/>) expect(wrapper.find('[id="step_ready"]').at(0).html()).to.include('rc-steps-item-finish') expect(wrapper.find('[id="step_queuing"]').at(0).html()).to.include('rc-steps-item-finish') expect(wrapper.find('[id="step_running"]').at(0).html()).to.include('rc-steps-item-error') expect(wrapper.find('[id="step_completed"]').at(0).html()).to.include('rc-steps-item-wait') }) it('step done', () => { let wrapper = mount(<Stepper status='done'/>) expect(wrapper.find('[id="step_ready"]').at(0).html()).to.include('rc-steps-item-finish') expect(wrapper.find('[id="step_queuing"]').at(0).html()).to.include('rc-steps-item-finish') expect(wrapper.find('[id="step_running"]').at(0).html()).to.include('rc-steps-item-finish') expect(wrapper.find('[id="step_completed"]').at(0).html()).to.include('rc-steps-item-process') }) it('step failed', () => { let wrapper = mount(<Stepper status='failed'/>) expect(wrapper.find('[id="step_ready"]').at(0).html()).to.include('rc-steps-item-finish') expect(wrapper.find('[id="step_queuing"]').at(0).html()).to.include('rc-steps-item-finish') expect(wrapper.find('[id="step_running"]').at(0).html()).to.include('rc-steps-item-error') expect(wrapper.find('[id="step_completed"]').at(0).html()).to.include('rc-steps-item-wait') }) })
techCurriculum/ui/solutions/3.3/src/components/Message.js
jennybkim/engineeringessentials
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ import React from 'react'; function Message(props) { return ( <div className='message-text'> <p>{props.text}</p> </div> ); } export default Message;
src/components/Columns.js
kdesterik/koendirkvanesterik.com
import React from 'react'; export default class Columns extends React.Component { render() { let columns = ''; switch( this.props.width ){ case 'full': columns = ( <div className="col-lg-12 col-md-12 col-sm-12 col-xs-12" dangerouslySetInnerHTML={{ __html: this.props.text }} /> ); break; case 'half': default: columns = ( <div className="col-lg-offset-3 col-lg-6 col-md-offset-3 col-md-6 col-sm-offset-2 col-sm-8 col-xs-12" dangerouslySetInnerHTML={{ __html: this.props.text }}/> ); break; } return ( <div className='columns'> <div className="container"> <div className="row"> { columns } </div> </div> </div> ); } }
test/ButtonSpec.js
adampickeral/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Button from '../src/Button'; describe('Button', function () { it('Should output a button', function () { let instance = ReactTestUtils.renderIntoDocument( <Button> Title </Button> ); assert.equal(React.findDOMNode(instance).nodeName, 'BUTTON'); }); it('Should have type=button by default', function () { let instance = ReactTestUtils.renderIntoDocument( <Button> Title </Button> ); assert.equal(React.findDOMNode(instance).getAttribute('type'), 'button'); }); it('Should show the type if passed one', function () { let instance = ReactTestUtils.renderIntoDocument( <Button type='submit'> Title </Button> ); assert.equal(React.findDOMNode(instance).getAttribute('type'), 'submit'); }); it('Should output an anchor if called with a href', function () { let href = '/url'; let instance = ReactTestUtils.renderIntoDocument( <Button href={href}> Title </Button> ); assert.equal(React.findDOMNode(instance).nodeName, 'A'); assert.equal(React.findDOMNode(instance).getAttribute('href'), href); }); it('Should output an anchor if called with a target', function () { let target = '_blank'; let instance = ReactTestUtils.renderIntoDocument( <Button target={target}> Title </Button> ); assert.equal(React.findDOMNode(instance).nodeName, 'A'); assert.equal(React.findDOMNode(instance).getAttribute('target'), target); }); it('Should call onClick callback', function (done) { let doneOp = function () { done(); }; let instance = ReactTestUtils.renderIntoDocument( <Button onClick={doneOp}> Title </Button> ); ReactTestUtils.Simulate.click(React.findDOMNode(instance)); }); it('Should be disabled', function () { let instance = ReactTestUtils.renderIntoDocument( <Button disabled> Title </Button> ); assert.ok(React.findDOMNode(instance).disabled); }); it('Should be disabled link', function () { let instance = ReactTestUtils.renderIntoDocument( <Button disabled href='#'> Title </Button> ); assert.ok(React.findDOMNode(instance).className.match(/\bdisabled\b/)); }); it('Should have block class', function () { let instance = ReactTestUtils.renderIntoDocument( <Button block> Title </Button> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-block\b/)); }); it('Should apply bsStyle class', function () { let instance = ReactTestUtils.renderIntoDocument( <Button bsStyle='danger'> Title </Button> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-danger\b/)); }); it('Should honour additional classes passed in, adding not overriding', function () { let instance = ReactTestUtils.renderIntoDocument( <Button className="bob" bsStyle="danger"> Title </Button> ); assert.ok(React.findDOMNode(instance).className.match(/\bbob\b/)); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-danger\b/)); }); it('Should default to bsStyle="default"', function () { let instance = ReactTestUtils.renderIntoDocument( <Button bsStyle='default'> Title </Button> ); assert.equal(instance.props.bsStyle, 'default'); }); it('Should be active', function () { let instance = ReactTestUtils.renderIntoDocument( <Button active> Title </Button> ); assert.ok(React.findDOMNode(instance).className.match(/\bactive\b/)); }); it('Should render an anchor in a list item when in a nav', function () { let instance = ReactTestUtils.renderIntoDocument( <Button navItem active> Title </Button> ); let li = React.findDOMNode(instance); let anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'); assert.equal(li.nodeName, 'LI'); assert.ok(li.className.match(/\bactive\b/)); assert.ok(anchor.props.href, '#'); }); it('Should render an anchor when in a navDropdown', function () { let instance = ReactTestUtils.renderIntoDocument( <Button navDropdown> Title </Button> ); let anchor = React.findDOMNode(instance); assert.equal(anchor.nodeName, 'A'); assert.ok(anchor.getAttribute('href'), '#'); }); });
app/javascript/spec/network-routers-interfaces-form/network-routers-interfaces-form.spec.js
ManageIQ/manageiq-ui-classic
import React from 'react'; import toJson from 'enzyme-to-json'; import fetchMock from 'fetch-mock'; import { shallow } from 'enzyme'; import InterfacesForm from '../../components/network-routers-interfaces-form'; import '../helpers/miqAjaxButton'; require('../helpers/set_fixtures_helper.js'); require('../helpers/old_js_file_require_helper.js'); require('../helpers/miqSparkle.js'); require('../helpers/miqAjaxButton.js'); jest.mock('../../helpers/miq-redirect-back', () => jest.fn()); describe('Network Router Interfaces Form Component', () => { let submitSpyMiqSparkleOn; let submitSpyMiqSparkleOff; let spyMiqAjaxButton; const networkRouter = { admin_state_up: true, cloud_network_id: 50, cloud_tenant: { name: 'admin' }, ext_management_system: { id: '8', name: 'Openstack Network Manager' }, extra_attributes: { distributed: false, routes: [], high_availability: false, external_gateway_info: { enable_snat: true, external_fixed_ips: [{ subnet_id: '1ca5cc3e-ffe1-44cf-94df-98a798489d06', ip_address: '10.9.60.151' }], network_id: '6b3d0c3b-8b68-4c26-a493-5be44d160241', }, }, }; const initialInterface = { resources: { href: 'http://localhost:3000/api/cloud_subnets/50', id: '50', name: 'ext-sub', }, }; const interfaces = { 'pat-subnwt': 148, 'ext-sub': 50 }; const removeinterfaces = { 'admin-project-subnet': 57 }; const routerId = '3'; beforeEach(() => { submitSpyMiqSparkleOn = jest.spyOn(window, 'miqSparkleOn'); submitSpyMiqSparkleOff = jest.spyOn(window, 'miqSparkleOff'); spyMiqAjaxButton = jest.spyOn(window, 'miqAjaxButton'); }); afterEach(() => { fetchMock.reset(); fetchMock.restore(); submitSpyMiqSparkleOn.mockRestore(); submitSpyMiqSparkleOff.mockRestore(); spyMiqAjaxButton.mockRestore(); }); it('should render add interface form', (done) => { const wrapper = shallow(<InterfacesForm interfaces={interfaces} add routerId={routerId} />); fetchMock.getOnce( // eslint-disable-next-line max-len `/api/network_routers/3?attributes=name,admin_state_up,cloud_network_id,cloud_tenant.name,ext_management_system.id,ext_management_system.name,extra_attributes`, networkRouter ); fetchMock.getOnce( '/api/cloud_subnets?expand=resources&attributes=name&filter[]=ems_ref=1ca5cc3e-ffe1-44cf-94df-98a798489d06', initialInterface, ); setImmediate(() => { wrapper.update(); expect(toJson(wrapper)).toMatchSnapshot(); done(); }); }); it('should render remove interface form', (done) => { const wrapper = shallow(<InterfacesForm interfaces={interfaces} add={false} routerId={routerId} />); fetchMock.getOnce( // eslint-disable-next-line max-len `/api/network_routers/3?attributes=name,admin_state_up,cloud_network_id,cloud_tenant.name,ext_management_system.id,ext_management_system.name,extra_attributes`, networkRouter ); fetchMock.getOnce( '/api/cloud_subnets?expand=resources&attributes=name&filter[]=ems_ref=1ca5cc3e-ffe1-44cf-94df-98a798489d06', initialInterface, ); setImmediate(() => { wrapper.update(); expect(toJson(wrapper)).toMatchSnapshot(); done(); }); }); it('should add interface', (done) => { const wrapper = shallow(<InterfacesForm interfaces={interfaces} add={false} routerId={routerId} />); const addInterface = { admin_state_up: true, cloud_network_id: 50, cloud_subnet_id: 50, cloud_tenant: { name: 'admin' }, ext_management_system: { id: '8', name: 'Openstack Network Manager' }, extra_attributes: { distributed: false, routes: [], high_availability: false, external_gateway_info: { enable_snat: true, external_fixed_ips: [{ subnet_id: '1ca5cc3e-ffe1-44cf-94df-98a798489d06', ip_address: '10.9.60.151' }], network_id: '6b3d0c3b-8b68-4c26-a493-5be44d160241', }, }, }; miqAjaxButton( '/network_router/add_interface/3?button=add', addInterface, { complete: false } ); expect(spyMiqAjaxButton).toHaveBeenCalledWith( '/network_router/add_interface/3?button=add', addInterface, { complete: false } ); setImmediate(() => { wrapper.update(); expect(toJson(wrapper)).toMatchSnapshot(); done(); }); }); it('should remove interface', (done) => { const wrapper = shallow(<InterfacesForm interfaces={interfaces} removeinterfaces={removeinterfaces} routerId={routerId} />); const removeInterface = { admin_state_up: true, cloud_network_id: 50, cloud_subnet_id: 50, cloud_tenant: { name: 'admin' }, ext_management_system: { id: '8', name: 'Openstack Network Manager' }, extra_attributes: { distributed: false, routes: [], high_availability: false, external_gateway_info: { enable_snat: true, external_fixed_ips: [{ subnet_id: '1ca5cc3e-ffe1-44cf-94df-98a798489d06', ip_address: '10.9.60.151' }], network_id: '6b3d0c3b-8b68-4c26-a493-5be44d160241', }, }, }; miqAjaxButton( '/network_router/add_interface/3?button=add', removeInterface, { complete: false } ); expect(spyMiqAjaxButton).toHaveBeenCalledWith( '/network_router/add_interface/3?button=add', removeInterface, { complete: false } ); setImmediate(() => { wrapper.update(); expect(toJson(wrapper)).toMatchSnapshot(); done(); }); }); });
src/Main/ReportHistory.js
hasseboulen/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { getReportHistory } from 'selectors/reportHistory'; import { makePlainUrl } from 'Main/makeAnalyzerUrl'; import { title as AboutArticleTitle } from 'Main/News/Articles/2017-01-31-About'; import makeNewsUrl from 'Main/News/makeUrl'; class ReportHistory extends React.PureComponent { static propTypes = { reportHistory: PropTypes.arrayOf(PropTypes.shape({ code: PropTypes.string.isRequired, fightId: PropTypes.number.isRequired, fightName: PropTypes.string.isRequired, playerId: PropTypes.number.isRequired, playerName: PropTypes.string.isRequired, playerClass: PropTypes.string.isRequired, end: PropTypes.number.isRequired, })).isRequired, }; render() { const { reportHistory } = this.props; const now = (+new Date()) / 1000; return ( <ul className="list selection"> {[...reportHistory].reverse().map(report => ( <li key={report.code} className="selectable"> <Link to={makePlainUrl(report.code, report.fightId, report.fightName, report.playerId, report.playerName)} style={{ color: '#fff', textDecoration: 'none' }}> <div> <div className={`playerName ${report.playerClass}`}>{report.playerName}</div> <div className="flex wrapable"> <div>{report.fightName}</div> <div className="flex-sub">{Math.floor(Math.max(0, now - report.end) / 86400)}d old report</div> </div> </div> </Link> </li> ))} {reportHistory.length === 0 && ( <li style={{ padding: '10px 22px' }}> You haven't viewed a report yet. Not sure where to start? <Link to={makeNewsUrl(AboutArticleTitle)}>About WoWAnalyzer.</Link> </li> )} </ul> ); } } const mapStateToProps = state => ({ reportHistory: getReportHistory(state), }); export default connect(mapStateToProps, null)(ReportHistory);
client/index.js
forkful/forkful
import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import { syncHistoryWithStore, routerMiddleware } from 'react-router-redux'; import App from './components/App'; import MainRecipe from './components/MainRecipe'; import Profile from './components/Profile'; import Dashboard from './components/Dashboard'; import Discover from './components/Discover'; import SearchResults from './components/SearchResults'; import ImageUpload from './components/ImageUpload.js'; import CreateRecipe from './components/CreateRecipe'; import Landing from './components/Landing'; import rootReducer from './reducers'; const middleware = routerMiddleware(browserHistory); // createStore accepts a single reducer or a collection of reducers const store = createStore(rootReducer, applyMiddleware(middleware)); const history = syncHistoryWithStore(browserHistory, store); const render = function () { ReactDOM.render( <Provider store={store}> <div> <Router history={history}> <Route path="/" component={App}> <IndexRoute component={Landing} /> <Route path="/dashboard" component={Dashboard} /> <Route path="/landing" component={Landing} /> <Route path="/discover" component={Discover} /> <Route path="/profile/:user_id" component={Profile} /> <Route path="/recipe/:id" component={MainRecipe} /> <Route path="/create" component={CreateRecipe} /> <Route path="/search" component={SearchResults} /> <Route path="/*" component={Dashboard} /> </Route> </Router> </div> </Provider>, document.getElementById('app') ); }; render(); store.subscribe(render);
docs/app/Examples/elements/Loader/Variations/LoaderExampleInline.js
shengnian/shengnian-ui-react
import React from 'react' import { Loader } from 'shengnian-ui-react' const LoaderExampleInline = () => ( <Loader active inline /> ) export default LoaderExampleInline
client/src/components/streamsList/listOfStreams.js
AuggieH/GigRTC
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { getActivePerformances } from '../../actions'; import { Link } from 'react-router'; import List from 'material-ui/lib/lists/list'; import ListItem from 'material-ui/lib/lists/list-item'; import Divider from 'material-ui/lib/divider'; import Avatar from 'material-ui/lib/avatar'; import Colors from 'material-ui/lib/styles/colors'; import PlayCircleOutline from 'material-ui/lib/svg-icons/av/play-circle-outline'; export class StreamsUL extends Component { componentWillMount(){ this.props.getActivePerformances() } render () { if (this.props.presentActiveStreams && this.props.presentActiveStreams.length) { return( <div> <ul className="sidebar-ul-landing"> {this.renderEvents()} </ul> </div> ) } else { return ( <div> <span>Stream Yourself!</span> </div> ) } } renderEvents () { return this.props.presentActiveStreams.map((performance)=> { return ( <li className="sidebar-li" key={performance.room} style={{"margin-top": "1em"}}> <Link to={`/router/activeStream/${performance.room}`} style={{"color": "white"}}> {performance.title} by {performance.room} </Link> </li> ) }) } } function mapStateToProps(state){ return { presentActiveStreams : state.data.activeStreams } } const mapDispatchToProps = { getActivePerformances }; export default connect(mapStateToProps,mapDispatchToProps)(StreamsUL)
example/__tests__/index.android.js
moschan/react-native-flip-card
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
test/expect_spec.js
yormi/test-them-all
/* global describe, it */ import { renderIntoDocument } from 'react-addons-test-utils' import React from 'react' import { expect } from '~/src/index' describe('batch expect', () => { class List extends React.Component { render () { return ( <ul> <li>foo</li> <li>bar</li> </ul> ) } } it('can accept an expectation as JSX', () => { const renderedComponent = renderIntoDocument(<List />) expect(renderedComponent, 'to contain', <li>foo</li>) }) it('can accept an array of JSX expectations', () => { const renderedComponent = renderIntoDocument(<List />) expect(renderedComponent, 'to contain', [ <li>foo</li>, <li>bar</li> ]) }) })
src/components/TouchableWithoutFeedback.js
lelandrichardson/react-native-mock
/** * https://github.com/facebook/react-native/blob/master/Libraries/Components/Touchable/TouchableWithoutFeedback.js */ import React from 'react'; import EdgeInsetsPropType from '../propTypes/EdgeInsetsPropType'; import View from './View'; const TouchableWithoutFeedback = React.createClass({ propTypes: { accessible: React.PropTypes.bool, accessibilityComponentType: React.PropTypes.oneOf(View.AccessibilityComponentType), accessibilityTraits: React.PropTypes.oneOfType([ React.PropTypes.oneOf(View.AccessibilityTraits), React.PropTypes.arrayOf(React.PropTypes.oneOf(View.AccessibilityTraits)), ]), /** * If true, disable all interactions for this component. */ disabled: React.PropTypes.bool, /** * Called when the touch is released, but not if cancelled (e.g. by a scroll * that steals the responder lock). */ onPress: React.PropTypes.func, onPressIn: React.PropTypes.func, onPressOut: React.PropTypes.func, /** * Invoked on mount and layout changes with * * `{nativeEvent: {layout: {x, y, width, height}}}` */ onLayout: React.PropTypes.func, onLongPress: React.PropTypes.func, /** * Delay in ms, from the start of the touch, before onPressIn is called. */ delayPressIn: React.PropTypes.number, /** * Delay in ms, from the release of the touch, before onPressOut is called. */ delayPressOut: React.PropTypes.number, /** * Delay in ms, from onPressIn, before onLongPress is called. */ delayLongPress: React.PropTypes.number, /** * When the scroll view is disabled, this defines how far your touch may * move off of the button, before deactivating the button. Once deactivated, * try moving it back and you'll see that the button is once again * reactivated! Move it back and forth several times while the scroll view * is disabled. Ensure you pass in a constant to reduce memory allocations. */ pressRetentionOffset: EdgeInsetsPropType, /** * This defines how far your touch can start away from the button. This is * added to `pressRetentionOffset` when moving off of the button. * ** NOTE ** * The touch area never extends past the parent view bounds and the Z-index * of sibling views always takes precedence if a touch hits two overlapping * views. */ hitSlop: EdgeInsetsPropType, }, render() { return null; }, }); module.exports = TouchableWithoutFeedback;
app/components/Home.js
pyreta/songrider
// @flow import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Home.css'; export default class Home extends Component { render() { return ( <div> <div className={styles.container}> <h2>Homerr</h2> <Link to="/counter">to Counter</Link> </div> </div> ); } }
src/index.js
RedZulu/ReduxArt
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
admin/src/components/AltText.js
ligson/keystone
import React from 'react'; import blacklist from 'blacklist'; import vkey from 'vkey'; var AltText = React.createClass({ getDefaultProps () { return { component: 'span', modifier: '<alt>', normal: '', modified: '' }; }, getInitialState () { return { modified: false }; }, componentDidMount () { document.body.addEventListener('keydown', this.handleKeyDown, false); document.body.addEventListener('keyup', this.handleKeyUp, false); }, componentWillUnmount () { document.body.removeEventListener('keydown', this.handleKeyDown); document.body.removeEventListener('keyup', this.handleKeyUp); }, handleKeyDown (e) { if (vkey[e.keyCode] !== this.props.modifier) return; this.setState({ modified: true }); }, handleKeyUp (e) { if (vkey[e.keyCode] !== this.props.modifier) return; this.setState({ modified: false }); }, render () { var props = blacklist(this.props, 'component', 'modifier', 'normal', 'modified'); return React.createElement(this.props.component, props, this.state.modified ? this.props.modified : this.props.normal); } }); module.exports = AltText;
src/timelines/components/card/TootAge.js
algernon/mad-tooter
// @flow /* The Mad Tooter -- A Mastodon client * Copyright (C) 2017 Gergely Nagy * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import moment from 'moment'; import { withStyles } from 'material-ui/styles'; const styles = theme => ({ tootAge: { textDecoration: 'none', color: theme.palette.text.secondary, 'a&:hover': { textDecoration: 'underline', }, } }); class TootAge extends React.Component { constructor(props) { super(props); this.state = {time: props.time, age: moment(props.time).fromNow()}; } componentDidMount() { this.timerID = setInterval( () => this.tick(), 10000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({age: moment(this.props.time).fromNow()}); } render() { if (this.props.href !== null) { return ( <a href={this.props.href} className={this.props.classes.tootAge} target="_blank">{this.state.age}</a> ); } else { return ( <span className={this.props.classes.tootAge}>{this.state.age}</span> ); } } } export default withStyles(styles)(TootAge);
src/components/MenuBar.js
Journey316/resume
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class MenuBar extends React.Component { constructor(props){ super(props); this.state = { selected : props.selected || 0 }; this.callHistory = this.callHistory.bind(this); } renderOverlay() { console.log('overlay', this.props.menu); return ( <div onClick={this.props.onPressOverlay} className={this.props.menu === true ? "overlay" : "hide-overlay"}> </div> ); } renderMenu() { let className = "menu-btn"; if (this.props.menu === true) { className += " active"; } return ( <div> <a onClick={this.props.onPressMenu} className={className}> <span></span> </a> </div> ); } callHistory(el, i) { this.setState({ selected: i }); } renderFull() { return this.props.data.map((el, i) => { let selected = ''; if(this.state.selected == i) { selected = 'active'; } return ( <li key={i} className={selected}> <Link to={el.link} onClick={() => this.callHistory(el, i)}> {el.title} </Link> </li> ) }); } renderNav() { let className = "menu"; if (this.props.menu && this.props.menu === true) { className += " active"; } return ( <div className={className}> {this.renderMenu()} <ul className="menu-list"> <span className="menu-container"> {this.renderFull()} </span> </ul> </div> ); } render() { return ( <div className="test-overlay"> {this.renderNav()} {this.renderOverlay()} </div> ); } } export default MenuBar;
server/sonar-web/src/main/js/apps/permission-templates/permission-template.js
vamsirajendra/sonarqube
import _ from 'underscore'; import Backbone from 'backbone'; import React from 'react'; import Defaults from './permission-template-defaults'; import SetDefaults from './permission-template-set-defaults'; import UsersView from './users-view'; import GroupsView from './groups-view'; import UpdateView from './update-view'; import DeleteView from './delete-view'; export default React.createClass({ propTypes: { permissionTemplate: React.PropTypes.object.isRequired, topQualifiers: React.PropTypes.array.isRequired, refresh: React.PropTypes.func.isRequired }, showGroups(permission, e) { e.preventDefault(); new GroupsView({ permission: permission, permissionTemplate: this.props.permissionTemplate, refresh: this.props.refresh }).render(); }, showUsers(permission, e) { e.preventDefault(); new UsersView({ permission: permission, permissionTemplate: this.props.permissionTemplate, refresh: this.props.refresh }).render(); }, onUpdate(e) { e.preventDefault(); new UpdateView({ model: new Backbone.Model(this.props.permissionTemplate), refresh: this.props.refresh }).render(); }, onDelete(e) { e.preventDefault(); new DeleteView({ model: new Backbone.Model(this.props.permissionTemplate), refresh: this.props.refresh }).render(); }, renderAssociation() { let projectKeyPattern = this.props.permissionTemplate.projectKeyPattern; if (!projectKeyPattern) { return null; } return <div className="spacer-bottom">Project Key Pattern: <code>{projectKeyPattern}</code></div>; }, renderDeleteButton() { if (_.size(this.props.permissionTemplate.defaultFor) > 0) { return null; } return <button onClick={this.onDelete} className="button-red">Delete</button>; }, render() { let permissions = this.props.permissionTemplate.permissions.map(p => { return ( <td key={p.key}> <table> <tbody> <tr> <td className="spacer-right">Users</td> <td className="spacer-left bordered-left">{p.usersCount}</td> <td className="spacer-left"> <a onClick={this.showUsers.bind(this, p)} className="icon-bullet-list" title="Update Users" data-toggle="tooltip" href="#"></a> </td> </tr> <tr> <td className="spacer-right">Groups</td> <td className="spacer-left bordered-left">{p.groupsCount}</td> <td className="spacer-left"> <a onClick={this.showGroups.bind(this, p)} className="icon-bullet-list" title="Update Users" data-toggle="tooltip" href="#"></a> </td> </tr> </tbody> </table> </td> ); }); return ( <tr> <td> <strong>{this.props.permissionTemplate.name}</strong> <p className="note little-spacer-top">{this.props.permissionTemplate.description}</p> </td> {permissions} <td className="thin text-right"> {this.renderAssociation()} <Defaults permissionTemplate={this.props.permissionTemplate} topQualifiers={this.props.topQualifiers}/> <div className="nowrap"> <SetDefaults permissionTemplate={this.props.permissionTemplate} topQualifiers={this.props.topQualifiers} refresh={this.props.refresh}/> <div className="button-group"> <button onClick={this.onUpdate}>Update</button> {this.renderDeleteButton()} </div> </div> </td> </tr> ); } });
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/DefaultPropsInferred.js
MichaelDeBoey/flow
// @flow import React from 'react'; class MyComponent extends React.Component { static defaultProps = {}; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { static defaultProps = {}; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
jenkins-design-language/src/js/components/material-ui/svg-icons/device/screen-rotation.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const DeviceScreenRotation = (props) => ( <SvgIcon {...props}> <path d="M16.48 2.52c3.27 1.55 5.61 4.72 5.97 8.48h1.5C23.44 4.84 18.29 0 12 0l-.66.03 3.81 3.81 1.33-1.32zm-6.25-.77c-.59-.59-1.54-.59-2.12 0L1.75 8.11c-.59.59-.59 1.54 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12L10.23 1.75zm4.6 19.44L2.81 9.17l6.36-6.36 12.02 12.02-6.36 6.36zm-7.31.29C4.25 19.94 1.91 16.76 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32z"/> </SvgIcon> ); DeviceScreenRotation.displayName = 'DeviceScreenRotation'; DeviceScreenRotation.muiName = 'SvgIcon'; export default DeviceScreenRotation;
src/index.js
JimFung/interval
import React from 'react' import ReactDOM from 'react-dom' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import { Router, Route, browserHistory, IndexRoute } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import promiseMiddleware from 'redux-promise-middleware'; import thunkMiddleware from 'redux-thunk'; import rootReducers from './reducers/index.js' import App from './components/App' import Home from './components/Home' // Add the reducer to your store on the `routing` key const store = createStore(rootReducers, {}, applyMiddleware(thunkMiddleware, promiseMiddleware() )); // Create an enhanced history that syncs navigation events with the store const history = syncHistoryWithStore(browserHistory, store) const Routes = ( <Provider store={store}> <Router history={history}> <Route path="/" component={App}> <IndexRoute component={Home}></IndexRoute> </Route> </Router> </Provider> ) ReactDOM.render( Routes, document.getElementById('root') );
src/svg-icons/action/shop.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionShop = (props) => ( <SvgIcon {...props}> <path d="M16 6V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H2v13c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6h-6zm-6-2h4v2h-4V4zM9 18V9l7.5 4L9 18z"/> </SvgIcon> ); ActionShop = pure(ActionShop); ActionShop.displayName = 'ActionShop'; ActionShop.muiName = 'SvgIcon'; export default ActionShop;
entry_types/scrolled/package/spec/frontend/VideoPlayerControls-spec.js
codevise/pageflow
import {VideoPlayerControls} from 'frontend/VideoPlayerControls'; import {useFile} from 'entryState'; import React from 'react'; import '@testing-library/jest-dom/extend-expect' import {useFakeTranslations} from 'pageflow/testHelpers'; import {renderInEntry} from 'support'; import {getInitialPlayerState, getPlayerActions} from 'support/fakePlayerState'; describe('VideoPlayerControls', () => { useFakeTranslations({ 'pageflow_scrolled.public.video_qualities.labels.fullhd': '1080p', 'pageflow_scrolled.public.video_qualities.annotations.fullhd': 'HD' }); it('renders quality selection menu', () => { const {getByRole} = renderInEntry( () => <VideoPlayerControls videoFile={useFile({collectionName: 'videoFiles', permaId: 10})} playerState={getInitialPlayerState()} playerActions={getPlayerActions()} />, { seed: { videoFiles: [{ permaId: 10, variants: ['fullhd'] }] } } ); expect(getByRole('menuitemradio', {name: '1080p HD'})).not.toBeNull(); }); it('renders text tracks menu', () => { const {getByRole} = renderInEntry( () => <VideoPlayerControls videoFile={useFile({collectionName: 'videoFiles', permaId: 10})} playerState={getInitialPlayerState()} playerActions={getPlayerActions()} />, { seed: { videoFiles: [{ id: 100, permaId: 10, variants: ['fullhd'] }], textTrackFiles: [{ parentFileId: 100, parentFileModelType: 'Pageflow::VideoFile', configuration: { label: 'English (CC)' } }] } } ); expect(getByRole('menuitemradio', {name: 'English (CC)'})).not.toBeNull(); }); it('handles missing file', () => { expect(() => renderInEntry(<VideoPlayerControls playerState={getInitialPlayerState()} playerActions={getPlayerActions()} />) ).not.toThrow(); }); });
system/src/layouts/containers/HeaderDropdownContainer/index.js
axmatthew/react
/* eslint react/prefer-stateless-function: 0 */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import { List, Map } from 'immutable'; import enquiryModule from '../../../modules/enquiries'; import HeaderDropdown from '../../components/HeaderDropdown'; class HeaderDropdownContainer extends Component { static propTypes = { user: React.PropTypes.instanceOf(Map), enquiries: React.PropTypes.instanceOf(List).isRequired }; render() { const { user, enquiries } = this.props; return React.createElement(HeaderDropdown, { newEnquiries: user ? enquiries.filter(enquiry => ( enquiry.get('status') === 'New' && enquiry.get('sales') === user.get('username') )) : List() }); } } function mapStateToProps(state) { return { user: state.users.getIn(['data', 'user']), enquiries: state[enquiryModule.entityUrl].getIn(['listView', 'data', 'entities']) }; } export default connect(mapStateToProps)(HeaderDropdownContainer);
examples/real-world/containers/Root.js
xiamidaxia/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { Router, Route } from 'react-router'; import configureStore from '../store/configureStore'; import App from './App'; import UserPage from './UserPage'; import RepoPage from './RepoPage'; const store = configureStore(); export default class Root extends Component { render() { return ( <div> <Provider store={store}> {() => <Router history={this.props.history}> <Route path='/' component={App}> <Route path='/:login/:name' component={RepoPage} /> <Route path='/:login' component={UserPage} /> </Route> </Router> } </Provider> </div> ); } }
src/components/layout/Aside.js
dhruv-kumar-jha/productivity-frontend
'use strict'; import React from 'react'; const AsideLayout = (props) => { return ( <aside className="default"> { props.children } </aside> ); } export default AsideLayout;
src/components/ShowHeader.js
kiyoshitaro/Instagram-
import React from 'react'; class ShowHeader extends React.Component { constructor(props) { super(props); this.state = { value: 1 }; } render() { return ( <div> {/*<div className="section section-cards section-gold">*/} {/*<header className="codrops-header">*/} {/*<div className="row">*/} {/*<div className="col-md-4">*/} {/*<div className="section-description">*/} {/*<h3 className="title">Beautiful Cards</h3>*/} {/*<h6 className="category">One Card for Every Problem</h6>*/} {/*<h5 className="description">We have gone above and beyond with options for you to organise your information. From cards designed for blog posts, to product cards or user profiles, you will have many options to choose from. All the cards follow the Paper Kit style principles and have a design that stands out. </h5>*/} {/*</div>*/} {/*</div>*/} {/*</div>*/} {/*</header>*/} {/*<section className="section-intro ">*/} {/*<div className="isolayer isolayer--deco1 isolayer--shadow " style={{"transform-style": "preserve-3d", transform: "translateX(33vw) translateY(-340px) rotateX(45deg) rotateZ(45deg)"}}>*/} {/*<ul className="grid grid--loaded" style={{position: "relative", width: "1200px", height: "1110px"}}>*/} {/*<li className="grid__item first-card" style={{position: "absolute", left: "0px", top: "0px", "z-index":" 1"}}>*/} {/*<a className="grid__link" href="index.html#cards" style={{"z-index": "1"}}>*/} {/*<img className="grid__img layer" src="assets/img/presentation-page/try/purple-card.png" alt="01" style={{transform: "matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)" }}/>*/} {/*</a>*/} {/*</li>*/} {/*<li className="grid__item second-card" style={{position: "absolute", left: "400px", top: "0px", "z-index": "1"}}>*/} {/*<a className="grid__link" href="index.html#cards" style="z-index: 1;">*/} {/*<img className="grid__img layer" src="assets/img/presentation-page/try/twitter-card.jpg" alt="02" style={{transform: "matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)"}} />*/} {/*</a>*/} {/*</li>*/} {/*<li className="grid__item third-card" style={{position: "absolute", left: "800px", top: "0px"}}>*/} {/*<a className="grid__link" href="index.html#cards">*/} {/*<img className="grid__img layer" src="assets/img/presentation-page/try/facebook-card.jpg" alt="03" />*/} {/*</a>*/} {/*</li>*/} {/*<li className="grid__item fourth-card" style={{position: "absolute", left: "0px" ,top: "300px"}}>*/} {/*<a className="grid__link" href="index.html#cards">*/} {/*<img className="grid__img layer" src="assets/img/presentation-page/try/pricing-card.jpg" alt="04" />*/} {/*</a>*/} {/*</li>*/} {/*<li className="grid__item fifth-card" style={{position: "absolute", left: "800px", top: "300px"}}>*/} {/*<a className="grid__link" href="index.html#cards">*/} {/*<img className="grid__img layer" src="assets/img/presentation-page/try/blog-card.jpg" alt="05" />*/} {/*</a>*/} {/*</li>*/} {/*<li className="grid__item sixth-card" style={{position: "absolute", left: "400px", top:" 510px" }}>*/} {/*<a className="grid__link" href="index.html#cards">*/} {/*<img className="grid__img layer" src="assets/img/presentation-page/try/capture.jpg" alt="06" />*/} {/*</a>*/} {/*</li>*/} {/*<li className="grid__item seventh-card" style={{position: "absolute", left: "0px", top: "600px"}}>*/} {/*<a className="grid__link" href="index.html#cards">*/} {/*<img className="grid__img layer" src="assets/img/presentation-page/try/team-card.jpg" alt="07" />*/} {/*</a>*/} {/*</li>*/} {/*<li className="grid__item eight-card" style={{position: "absolute", left: "800px", top: "600px"}}>*/} {/*<a className="grid__link" href="index.html#cards">*/} {/*<img className="grid__img layer" src="assets/img/presentation-page/try/testimonal-card.jpg" alt="07" />*/} {/*</a>*/} {/*</li>*/} {/*<li className="grid__item ninth-card" style={{position: "absolute", left: "400px", top: "810px"}}>*/} {/*<a className="grid__link" href="index.html#cards">*/} {/*<img className="grid__img layer" src="assets/img/presentation-page/try/pricing-card-icon.jpg" alt="07" />*/} {/*</a>*/} {/*</li>*/} {/*</ul>*/} {/*</div>*/} {/*</section>*/} {/*</div>*/} <div className="page-header" data-parallax="true" style={{"background-image": "url(../Girl.jpg)"}}> <div className="filter"></div> <div className="content-center"> <div className="container"> <div className="motto"> <div> <center><h1 className="title" style={{color: "mediumseagreen", "font-family": "TlwgTypewriter", "font-size": "80px"}}> Instagram</h1></center> <br/> <h3 className="description" style={{color: "mediumseagreen"}}>Start designing your landing page here.</h3> <br/> <br/><br/> <div> <center> <button type="button" className="btn btn-outline-success btn-round" onClick={() => { this.setState({value: this.state.value + 1}); this.props.getPost(this.state.value); this.props.isAddHeader(); }} style={{width: "400px", value: "Readmore..."}}>Go with me ... </button> </center> </div> </div> </div> </div> </div> </div> </div> ); } } export default ShowHeader;
lib/codemod/src/transforms/__testfixtures__/storiesof-to-csf/export-destructuring.input.js
kadirahq/react-storybook
/* eslint-disable import/no-extraneous-dependencies */ import React from 'react'; import { storiesOf } from '@storybook/react'; import ComponentRow from './ComponentRow'; import * as SpecRowStories from './SpecRow.stories'; export const { actions } = SpecRowStories; storiesOf('ComponentRow', module).add('pending', () => ( <ComponentRow snapshots={snapshots.pending} buildNumber={2} {...actions} /> ));
tests/routes/Home/components/HomeView.spec.js
fxghqc/walk
import React from 'react' import { HomeView } from 'routes/Home/components/HomeView' import { render } from 'enzyme' describe('(View) Home', () => { let _component beforeEach(() => { _component = render(<HomeView />) }) it('Renders a welcome message', () => { const welcome = _component.find('h4') expect(welcome).to.exist expect(welcome.text()).to.match(/Welcome!/) }) it('Renders an awesome duck image', () => { const duck = _component.find('img') expect(duck).to.exist expect(duck.attr('alt')).to.match(/This is a duck, because Redux!/) }) })
nlyyAPP/component/图片管理模块/模块上传/MLMoKuaiNewUpdateList.js
a497500306/nlyy_APP
/** * Created by Rolle on 2017/5/25. */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, ListView, TouchableOpacity, Platform } from 'react-native'; var MLNavigatorBar = require('../../MLNavigatorBar/MLNavigatorBar'); var MLTableCell = require('../../MLTableCell/MLTableCell'); var ImagePicker = require('react-native-image-picker'); import ImagePicker1 from 'react-native-image-crop-picker'; import ActionSheet from 'react-native-actionsheet'; var settings = require("../../../settings"); var buttons = ['取消', '拍照', '相册中选择']; if (Platform.OS !== 'ios'){ buttons = ['取消', '相册中选择']; } const CANCEL_INDEX = 0; const DESTRUCTIVE_INDEX = 4; var friendId = 0; var seveRowData = {}; var options = { title: 'Select Avatar', customButtons: [ {name: 'fb', title: 'Choose Photo from Facebook'}, ], storageOptions: { skipBackup: true, path: 'images', }, mediaType:'photo', quality:0.4 }; var MLMoKuaiNewUpdateList = React.createClass({ show() { this.ActionSheet.show(); }, _handlePress(index) { }, getInitialState() { //ListView设置 var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); return { tableData:[], //ListView设置 dataSource: ds.cloneWithRows([]), avatarSource:null } }, render() { // console.log('更新属性' + this.props.initialProps.weChatUser + "123") return ( <View style={styles.container}> <MLNavigatorBar title={'按模块上传'} isBack={true} newTitle={"plus-circle"} backFunc={() => { this.props.navigator.pop() }} newFunc={()=>{ this.show(this) }} leftTitle={'首页'} leftFunc={()=>{ this.props.navigator.popToRoute(this.props.navigator.getCurrentRoutes()[1]) }}/> <ListView dataSource={this.state.dataSource}//数据源 renderRow={this.renderRow} /> <ActionSheet ref={(o) => this.ActionSheet = o} title="选择您的操作?" options={buttons} cancelButtonIndex={CANCEL_INDEX} destructiveButtonIndex={DESTRUCTIVE_INDEX} onPress={(sss)=>{ this._handlePress(this) if (sss == 1){//点击修改备注 console.log('点击相机'); if (Platform.OS != 'ios'){ console.log('点击安卓相册'); ImagePicker1.openPicker({ cropping: false, multiple: false }).then(image => { console.log('图片地址'); console.log(image.path); let formData = new FormData(); let file = {uri: image.path, type: 'multipart/form-data', name: 'image.png'}; formData.append("images",file); fetch(settings.fwqUrl + "/app/imageUpdata",{ method:'POST', headers:{ 'Content-Type':'multipart/form-data', }, body:formData, }) .then((response) => response.json()) .then((responseJson) => { console.log('成功??'); console.log(responseJson); }) .catch((error) => { console.log('错误??'); console.log(error); }); }) }else { options.quality = 0.5; //启动相机: ImagePicker.launchCamera(options, (response) => { if (response.didCancel) { console.log('User cancelled image picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { let source = {uri: response.uri}; console.log('Response = ', source); // You can also display the image using data: // let source = { uri: 'data:image/jpeg;base64,' + response.data }; this.setState({ avatarSource: source }); } }); ImagePicker.showImagePicker(options, (response) => { }); } }else if (sss == 2){//点击查看资料 console.log('点击相册'); // Open Image Library: ImagePicker.launchImageLibrary(options, (response) => { if (response.didCancel) { console.log('User cancelled image picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { let source = { uri: response.uri }; console.log('相册 = ', source); // You can also display the image using data: // let source = { uri: 'data:image/jpeg;base64,' + response.data }; this.setState({ avatarSource: source }); let formData = new FormData(); let file = {uri: source.uri, type: 'multipart/form-data', name: 'image.png'}; formData.append("images",file); fetch(settings.fwqUrl + "/app/imageUpdata",{ method:'POST', headers:{ 'Content-Type':'multipart/form-data', }, body:formData, }) .then((response) => response.json()) .then((responseJson) => { console.log('成功??'); console.log(responseJson); }) .catch((error) => { console.log('错误??'); console.log(error); }); } }); } }} /> </View> ); }, //返回具体的cell renderRow(rowData, sectionID, rowID){ return ( <TouchableOpacity onPress={()=> { }}> <MLTableCell title={'图片' + rowID}/> </TouchableOpacity> ) } }) const styles = StyleSheet.create({ container: { flex: 1, // justifyContent: 'center', // alignItems: 'center', backgroundColor: 'rgba(233,234,239,1.0)', }, }); // 输出组件类 module.exports = MLMoKuaiNewUpdateList;
examples/src/components/CustomOption.js
pdrko/react-select
import React from 'react'; import Gravatar from 'react-gravatar'; var Option = React.createClass({ propTypes: { addLabelText: React.PropTypes.string, className: React.PropTypes.string, mouseDown: React.PropTypes.func, mouseEnter: React.PropTypes.func, mouseLeave: React.PropTypes.func, option: React.PropTypes.object.isRequired, renderFunc: React.PropTypes.func }, render () { var obj = this.props.option; var size = 15; var gravatarStyle = { borderRadius: 3, display: 'inline-block', marginRight: 10, position: 'relative', top: -2, verticalAlign: 'middle', }; return ( <div className={this.props.className} onMouseEnter={this.props.mouseEnter} onMouseLeave={this.props.mouseLeave} onMouseDown={this.props.mouseDown} onClick={this.props.mouseDown}> <Gravatar email={obj.email} size={size} style={gravatarStyle} /> {obj.value} </div> ); } }); module.exports = Option;
fields/types/location/LocationColumn.js
riyadhalnur/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTableValue'; const SUB_FIELDS = ['street1', 'suburb', 'state', 'postcode', 'country']; var LocationColumn = React.createClass({ displayName: 'LocationColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { let value = this.props.data.fields[this.props.col.path]; if (!value || !Object.keys(value).length) return null; let output = []; SUB_FIELDS.map((i) => { if (value[i]) { output.push(value[i]); } }); return ( <ItemsTableValue field={this.props.col.type} title={output.join(', ')}> {output.join(', ')} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); } }); module.exports = LocationColumn;
public/components/Login.js
supportivesantas/project-ipsum
import React from 'react'; import actions from '../actions/ipsumActions.js'; import { connect } from 'react-redux'; import maps from '../mappingFunctions.js'; import NavigationBarLogin from './NavigationBarLogin.js'; import { Grid, Panel, Col, Row, Jumbotron } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; import { Link } from 'react-router'; import Footer from './Footer.js'; var Login = () => { return ( <div className="outerContainer" > <Grid fluid className="mainContainer" > <Row><Col> <NavigationBarLogin /> </Col></Row> <Row><Col md={12}> <Jumbotron className="loginJumbo"> <Row> <Col xs={12} sm={8}> <h1> The easiest way to manage all your deployments</h1> <Link to={'/about'}>Take the tour</Link> </Col> </Row> </Jumbotron> </Col></Row> <Row><Col md={12}> <div className='layout-middle'> <div className='layout-middle-img-cover' style={{backgroundImage: 'url(assets/img/using-phone.jpg)'}}></div> <div className='layout-middle-text'> <h1> <small> Control</small> </h1> <h3> The freedom to let go </h3> <p>Manage all your deployment servers in one place. Heroku, Digital Ocean, AWS, and Azure supported</p> </div> </div> </Col></Row> <Row><Col md={12}> <div className='layout-middle flip'> <div className='layout-middle-img-cover' style={{backgroundImage: 'url(assets/img/servers.jpg)'}}></div> <div className='layout-middle-text'> <h1> <small> Trust</small> </h1> <h3> A robust service at your disposal </h3> <p>Add our proprietary middleware to your applications, and watch the data flow!</p> </div> </div> </Col></Row> <Row><Col md={12}> <div className='layout-middle'> <div className='layout-middle-img-cover' style={{backgroundImage: 'url(assets/img/woman.jpg)'}}> </div> <div className='layout-middle-text'> <h1> <small>Insight</small> </h1> <h3> Data you can depend on </h3> <p>Get real time data on all your servers, applications, and even individual API endpoints!</p> </div> </div> </Col></Row> </Grid> <Footer /> </div> ) } Login = connect(state => ({ state: state }))(Login); export default Login;
src/js/components/success/Success.component.js
katie-day/we_do
import React from 'react'; import Header from '../common/header/Header.component'; import { getWindowHeight } from '../../utils'; const Success = () => { const windowHeight = getWindowHeight(); const guest = {}; const style = { minHeight: windowHeight - 50, }; return ( <div> <Header guest={guest} /> <div className="welcome u-text-center t-plum" style={style}> <div className="welcome__background" /> <div className="gutters welcome__table-cell"> <h4 className="u-current-text-color"> Thanks for your rsvp </h4> </div> </div> </div> ); }; export default Success;
app/javascript/mastodon/features/home_timeline/index.js
robotstart/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../ui/components/column'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnSettingsContainer from './containers/column_settings_container'; import { Link } from 'react-router'; const messages = defineMessages({ title: { id: 'column.home', defaultMessage: 'Home' } }); const mapStateToProps = state => ({ hasUnread: state.getIn(['timelines', 'home', 'unread']) > 0, hasFollows: state.getIn(['accounts_counters', state.getIn(['meta', 'me']), 'following_count']) > 0 }); class HomeTimeline extends React.PureComponent { render () { const { intl, hasUnread, hasFollows } = this.props; let emptyMessage; if (hasFollows) { emptyMessage = <FormattedMessage id='empty_column.home.inactivity' defaultMessage="Your home feed is empty. If you have been inactive for a while, it will be regenerated for you soon." /> } else { emptyMessage = <FormattedMessage id='empty_column.home' defaultMessage="You aren't following anyone yet. Visit {public} or use search to get started and meet other users." values={{ public: <Link to='/timelines/public'><FormattedMessage id='empty_column.home.public_timeline' defaultMessage='the public timeline' /></Link> }} />; } return ( <Column icon='home' active={hasUnread} heading={intl.formatMessage(messages.title)}> <ColumnSettingsContainer /> <StatusListContainer {...this.props} scrollKey='home_timeline' type='home' emptyMessage={emptyMessage} /> </Column> ); } } HomeTimeline.propTypes = { intl: PropTypes.object.isRequired, hasUnread: PropTypes.bool, hasFollows: PropTypes.bool }; export default connect(mapStateToProps)(injectIntl(HomeTimeline));
App/containers/DayThreeScreen/MeScreen.js
carney520/30-days-of-react-native
// @flow import React from 'react' import {Text} from 'react-native' import TabbarIcon from './components/TabbarIcon' export default class MeScreen extends React.Component { static navigationOptions = { tabBar: { label: 'Me', icon: ({tintColor}) => <TabbarIcon name="user" color={tintColor} /> } } render () { return (<Text>MeScreen</Text>) } }
node_modules/react-bootstrap/es/Form.js
caughtclean/but-thats-wrong-blog
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { horizontal: React.PropTypes.bool, inline: React.PropTypes.bool, componentClass: elementType }; var defaultProps = { horizontal: false, inline: false, componentClass: 'form' }; var Form = function (_React$Component) { _inherits(Form, _React$Component); function Form() { _classCallCheck(this, Form); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Form.prototype.render = function render() { var _props = this.props, horizontal = _props.horizontal, inline = _props.inline, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['horizontal', 'inline', 'componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = []; if (horizontal) { classes.push(prefix(bsProps, 'horizontal')); } if (inline) { classes.push(prefix(bsProps, 'inline')); } return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Form; }(React.Component); Form.propTypes = propTypes; Form.defaultProps = defaultProps; export default bsClass('form', Form);
example/js/main.js
shirou/goagen_js
import React from 'react'; import * as api from "./api_request.js"; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import {createStore, combineReducers} from 'redux'; import {reducer as reduxFormReducer} from 'redux-form'; import { Values } from 'redux-form-website-template'; const dest = document.getElementById('content'); const reducer = combineReducers({ form: reduxFormReducer // mounted under "form" }); const store = (createStore)(reducer); const showResults = (values) => { api.UserCreate(values).then((result) =>{ if (result.status !== 200){ throw new Error('invalid paramater'); } alert("OK!") }).catch((error) => { alert(error.message) }); }; const FieldLevelValidationForm = require('./components/FieldLevelValidationForm').default; ReactDOM.render( <Provider store={store}> <div> <h2>Form</h2> <FieldLevelValidationForm onSubmit={showResults} /> <Values form="fieldLevelValidation" /> </div> </Provider>, dest );
src/app/components/Layout.js
Dynamit/healthcare-microsite
/** * Master layout * @description Layout wrapper. Used only in prerender. Client-side app renders on `document.body` */ import React from 'react'; class Layout extends React.Component { constructor(props) { super(props); // improved async Typekit loading https://goo.gl/t1jDL8 let kitId = 'omf4gip'; this.loadFonts = `!function(e){var t=3e3;window.sessionStorage&&"false"===sessionStorage.getItem("useTypekit")&&(t=0);var s,a={kitId:'${kitId}',scriptTimeout:t},i=e.documentElement,o=setTimeout(function(){i.className=i.className.replace(/\bwf-loading\b/g,"")+"wf-inactive",window.sessionStorage&&sessionStorage.setItem("useTypekit","false")},a.scriptTimeout),n=e.createElement("script"),c=!1,r=e.getElementsByTagName("script")[0];i.className+="wf-loading",n.src="//use.typekit.net/"+a.kitId+".js",n.async=!0,n.onload=n.onreadystatechange=function(){if(s=this.readyState,!(c||s&&"complete"!=s&&"loaded"!=s)){c=!0,clearTimeout(o);try{Typekit.load(a)}catch(e){}}},r.parentNode.insertBefore(n,r)}(document);`; this.GA = ` (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-23605672-3', 'auto'); `; } /** * Convert a string returned by react-helmet to React DOM * @param {String} str react-helmet `meta` or `link` value from `rewind()` * @return {Array} Array of React components */ _helmetToComponent(str) { // stop if str is empty if (!str.length) { return; } // an array of React components let Components = []; // react-helmet returns a line-break delimited list of tags // split so we can deal with each individually str.split(/\n/).forEach((node, i) => { // extrapolate node type let nodeType = str.match(/[a-z]+/)[0]; // container for props let props = { key: i }; // match attr="value" pattern // store props node.match(/([a-z\-]+=".*?")/g).forEach((attr) => { let matches = attr.match(/([a-z\-]+)="(.*?)"/); props[matches[1]] = matches[2]; }); // create and save the component Components.push(React.createElement(nodeType, props)); }); // return the array of components return Components; } render() { let meta = this._helmetToComponent(this.props.head.meta); let link = this._helmetToComponent(this.props.head.link); return ( <html lang="en"> <head> <title>{this.props.head.title}</title> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {meta} <link rel="icon" type="image/x-icon" href="/favicon.ico" /> <link rel="stylesheet" href="/assets/styles/main.css" /> {link} <script src="http://use.typekit.net/omf4gip.js"></script> <script dangerouslySetInnerHTML={{__html: this.loadFonts}}></script> <script dangerouslySetInnerHTML={{__html: this.GA }}></script> </head> <body dangerouslySetInnerHTML={{ __html: this.props.markup }} /> <script src="/assets/scripts/main.js" async></script> </html> ); } }; export default Layout;
src/components/ResourceGroup/index.js
DeveloperLaPoste/protagonist-react
import PropTypes from 'prop-types'; import React from 'react'; import { ResourceGroupTitle, Description, Resources } from '../'; export default function ResourceGroup({ resourceGroup }) { const resources = resourceGroup.resources ? ( <div className="ResourceGroup-content"> <Resources resources={resourceGroup.resources} /> </div> ) : <div className="ResourceGroup-noContent" />; return ( <div className="ResourceGroup-main"> <ResourceGroupTitle title={resourceGroup.name} /> <Description description={resourceGroup.description} /> {resources} </div> ); } ResourceGroup.propTypes = { resourceGroup: PropTypes.shape({ name: PropTypes.string, description: PropTypes.string, resources: PropTypes.array, }), }; ResourceGroup.defaultProps = { resourceGroup: {}, };
examples/todomvc/index.js
chrisege/redux
import React from 'react'; import App from './containers/App'; import 'todomvc-app-css/index.css'; React.render( <App />, document.getElementById('root') );
src/index.js
shonmacray/Showcase
import React from 'react'; import ReactDOM from 'react-dom'; import Mainlayout from './Showcase/index'; import registerServiceWorker from './registerServiceWorker'; import './index.css'; import './abc.css'; ReactDOM.render(<Mainlayout />, document.getElementById('root')); registerServiceWorker();
packages/es-components/src/components/controls/buttons/OutlineButton.js
jrios/es-components
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { useTheme } from '../../util/useTheme'; const StyledButton = styled.button` background-color: ${props => props.variant.bgColor}; border: 2px solid ${props => props.variant.borderColor}; border-radius: ${props => props.buttonSize.borderRadius}; box-sizing: border-box; color: ${props => props.variant.textColor}; cursor: pointer; display: block; font-family: inherit; font-size: ${props => props.buttonSize.fontSize}; font-weight: ${props => props.buttonSize.fontWeight || 'normal'}; line-height: ${props => props.buttonSize.lineHeight || props.theme.sizes.baseLineHeight}; min-width: 100px; outline: none; padding-bottom: ${props => props.buttonSize.paddingBottom}; padding-left: ${props => props.buttonSize.paddingSides}; padding-right: ${props => props.buttonSize.paddingSides}; padding-top: ${props => props.buttonSize.paddingTop}; text-align: center; text-decoration: none; text-transform: ${props => props.buttonSize.textTransform ? props.buttonSize.textTransform : 'none'}; transition: background-color 150ms linear, color 150ms linear; white-space: nowrap; width: 100%; @media (min-width: ${props => props.theme.screenSize.tablet}) { display: ${props => (props.block ? 'block' : 'inline-block')}; width: ${props => (props.block ? '100%' : 'auto')}; } &:focus, &:focus-within { box-shadow: 0 0 3px 3px ${props => props.theme.colors.inputFocus}; } &:hover { background-color: ${props => props.variant.hoverBgColor}; color: ${props => props.variant.hoverTextColor}; } &:active { background-color: ${props => props.variant.activeBgColor}; color: ${props => props.variant.activeTextColor}; } &[disabled] { cursor: not-allowed; opacity: 0.65; > * { pointer-events: none; } } &[disabled]:hover { color: ${props => props.variant.textColor}; background-color: ${props => props.variant.bgColor}; } `; const OutlineButton = React.forwardRef(function OutlineButton(props, ref) { const { children, styleType, size, block, ...other } = props; const theme = useTheme(); const buttonSize = theme.buttonStyles.outlineButton.size[size]; const variant = theme.buttonStyles.outlineButton.variant[styleType]; return ( <StyledButton ref={ref} block={block} buttonSize={buttonSize} variant={variant} type="button" {...other} > {children} </StyledButton> ); }); OutlineButton.propTypes = { children: PropTypes.node.isRequired, /** Select the color style of the button, types come from theme buttonStyles.outlineButton */ styleType: PropTypes.string, size: PropTypes.oneOf(['lg', 'default', 'sm', 'xs']), /** Make the button's width the size of it's parent container */ block: PropTypes.bool }; OutlineButton.defaultProps = { styleType: 'default', block: false, size: 'default' }; export default OutlineButton;
_deprecated/src/components/Home.js
paigekehoe/paigekehoe.github.io
import React from 'react'; import Interactive from 'react-interactive'; import { Link } from 'react-router-dom'; import { Code } from '../styles/style'; import s from '../styles/home.style'; export default function Home() { const repoReadmeLink = text => ( <Interactive as="a" {...s.link} href="https://github.com/paigekehoe/paigekehoe.github.io#readme" >{text}</Interactive> ); return ( <div> <p style={s.p}> Welcome to my little site - a work in progress. Come back soon! </p> </div> ); }
src/components/UsernameForm/TimeMessage/index.js
jenkoian/hacktoberfest-checker
import React from 'react'; import getTimeMessage from './getTimeMessage'; const TimeMessage = () => ( <p className="text-center light-mode:text-hack-dark-title pb-2"> {getTimeMessage()} </p> ); export default TimeMessage;
client/scripts/components/config/disclosure-requirements/disclosure-requirements/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; import Panel from '../../panel'; import ConfigActions from '../../../../actions/config-actions'; import CheckBox from '../../check-box'; import ActiveProjectType from '../active-project-type'; import InactiveProjectType from '../inactive-project-type'; import {BlueButton} from '../../../blue-button'; import ConfiguringPanel from '../configuring-panel'; import ConfigPage from '../../config-page'; export default class DisclosureRequirements extends React.Component { constructor() { super(); this.toggleSelectingProjectTypes = this.toggleSelectingProjectTypes.bind(this); } toggleSelectingProjectTypes() { ConfigActions.toggle('applicationState.selectingProjectTypes'); } render() { const {configState} = this.context; let projectTypesPanel; if ( configState.config && configState.config.projectTypes && !configState.applicationState.configuringProjectType ) { const projectsRequiringDisclosure = configState.config.projectTypes.filter(projectType => { return projectType.reqDisclosure === 1; }); if (configState.applicationState.selectingProjectTypes) { const projectTypes = configState.config.projectTypes.map((projectType, index) => { return ( <span key={projectType.typeCd} className={styles.checkbox}> <CheckBox path={`config.projectTypes[${index}].reqDisclosure`} checked={projectType.reqDisclosure === 1} label={projectType.description} /> </span> ); }); let doneButton; if (projectsRequiringDisclosure.length > 0) { doneButton = ( <BlueButton onClick={this.toggleSelectingProjectTypes}>DONE</BlueButton> ); } projectTypesPanel = ( <div> <div className={styles.title}> Choose from the project types below <br /> which require the completion of a COI disclosure </div> <Panel> {projectTypes} <div style={{textAlign: 'center'}}> {doneButton} </div> </Panel> </div> ); } else { const activeProjectTypes = projectsRequiringDisclosure.map(projectType => { return ( <ActiveProjectType {...projectType} key={projectType.typeCd} configure={ConfigActions.configureProjectType} /> ); }); const inactiveProjectTypes = configState.config.projectTypes.filter(projectType => { return Number(projectType.reqDisclosure) === 0; }) .map(projectType => { return ( <InactiveProjectType {...projectType} key={projectType.typeCd} /> ); }); projectTypesPanel = ( <div> <div className={styles.title}> The project types below require the completion of a COI disclosure.<br /> <a className={styles.link} onClick={this.toggleSelectingProjectTypes}>Click here to edit these project types</a> </div> <div> <div style={{marginBottom: '50px'}}> <div className={styles.activeHeader}> ACTIVE </div> {activeProjectTypes} </div> <div> <div className={styles.activeHeader} style={{marginBottom: '15px'}}> NOT ACTIVE </div> {inactiveProjectTypes} </div> </div> </div> ); } } let configuringPanel; if (configState.applicationState.configuringProjectType) { configuringPanel = ( <ConfiguringPanel projectType={configState.applicationState.configuringProjectType} roles={configState.config.projectRoles} statuses={configState.config.projectStatuses} /> ); } return ( <ConfigPage title='Disclosure Requirements' routeName='disclosure-requirements' dirty={configState.dirty} className={this.props.className} > {projectTypesPanel} {configuringPanel} </ConfigPage> ); } } DisclosureRequirements.contextTypes = { configState: React.PropTypes.object };
week02-rest-basics/client/src/App.js
kajayr/isit322-leosinani-2017
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import 'whatwg-fetch'; class App extends Component { constructor() { super(); this.state = { file: 'Get Nine Result will be placed here.', foo: 'waiting for express server' }; } bar = () => { // this.setState({foo: 'Clicked the express succesfully'}); //this.setState({file: 'The results have been placed'}); const that = this; fetch('/api/foo') .then(function(response) { return response.json(); }).then(function(json) { console.log('parsed json', json); that.setState(foo => (json)); }).catch(function(ex) { console.log('parsing failed', ex); }); }; render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> state.foo: {this.state.foo} </p> <p className="App-intro"> state.file: {this.state.file} </p> <button onClick={this.bar}> Click me </button> </div> ); } } export default App;
test/specs/collections/Message/MessageList-test.js
aabustamante/Semantic-UI-React
import React from 'react' import MessageList from 'src/collections/Message/MessageList' import * as common from 'test/specs/commonTests' describe('MessageList', () => { common.isConformant(MessageList) common.implementsCreateMethod(MessageList) common.rendersChildren(MessageList) it('renders an ul tag', () => { shallow(<MessageList />) .should.have.tagName('ul') }) it('has className list', () => { shallow(<MessageList />) .should.have.className('list') }) describe('items', () => { it('creates MessageItem children', () => { const items = ['foo', 'bar', 'baz'] const wrapper = shallow(<MessageList items={items} />) wrapper.should.have.exactly(3).descendants('MessageItem') wrapper .childAt(0) .shallow() .should.have.text(items[0]) wrapper .childAt(1) .shallow() .should.have.text(items[1]) wrapper .childAt(2) .shallow() .should.have.text(items[2]) }) }) })
src/svg-icons/device/devices.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceDevices = (props) => ( <SvgIcon {...props}> <path d="M4 6h18V4H4c-1.1 0-2 .9-2 2v11H0v3h14v-3H4V6zm19 2h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z"/> </SvgIcon> ); DeviceDevices = pure(DeviceDevices); DeviceDevices.displayName = 'DeviceDevices'; DeviceDevices.muiName = 'SvgIcon'; export default DeviceDevices;
blueprints/view/files/__root__/views/__name__View/__name__View.js
availabs/kauffman-atlas
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
src/components/NotFoundPage/NotFoundPage.js
phoenixbox/vesty-fe
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; //require('./NotFoundPage.less'); import React from 'react'; export default React.createClass({ render() { return ( <div> <h1>Page Not Found</h1> <p>Sorry, but the page you were trying to view does not exist.</p> </div> ); } });
client/node_modules/react-router/es6/IndexLink.js
Discounty/Discounty
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _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 React, { Component } from 'react'; import Link from './Link'; /** * An <IndexLink> is used to link to an <IndexRoute>. */ var IndexLink = (function (_Component) { _inherits(IndexLink, _Component); function IndexLink() { _classCallCheck(this, IndexLink); _Component.apply(this, arguments); } IndexLink.prototype.render = function render() { return React.createElement(Link, _extends({}, this.props, { onlyActiveOnIndex: true })); }; return IndexLink; })(Component); export default IndexLink;
app/javascript/mastodon/features/compose/components/compose_form.js
esetomo/mastodon
import React from 'react'; import CharacterCounter from './character_counter'; import Button from '../../../components/button'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ReplyIndicatorContainer from '../containers/reply_indicator_container'; import AutosuggestTextarea from '../../../components/autosuggest_textarea'; import UploadButtonContainer from '../containers/upload_button_container'; import { defineMessages, injectIntl } from 'react-intl'; import Collapsable from '../../../components/collapsable'; import SpoilerButtonContainer from '../containers/spoiler_button_container'; import PrivacyDropdownContainer from '../containers/privacy_dropdown_container'; import SensitiveButtonContainer from '../containers/sensitive_button_container'; import EmojiPickerDropdown from '../containers/emoji_picker_dropdown_container'; import UploadFormContainer from '../containers/upload_form_container'; import WarningContainer from '../containers/warning_container'; import { isMobile } from '../../../is_mobile'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { length } from 'stringz'; import { countableText } from '../util/counter'; const messages = defineMessages({ placeholder: { id: 'compose_form.placeholder', defaultMessage: 'What is on your mind?' }, spoiler_placeholder: { id: 'compose_form.spoiler_placeholder', defaultMessage: 'Write your warning here' }, publish: { id: 'compose_form.publish', defaultMessage: 'Toot' }, publishLoud: { id: 'compose_form.publish_loud', defaultMessage: '{publish}!' }, }); @injectIntl export default class ComposeForm extends ImmutablePureComponent { static propTypes = { intl: PropTypes.object.isRequired, text: PropTypes.string.isRequired, suggestion_token: PropTypes.string, suggestions: ImmutablePropTypes.list, spoiler: PropTypes.bool, privacy: PropTypes.string, spoiler_text: PropTypes.string, focusDate: PropTypes.instanceOf(Date), preselectDate: PropTypes.instanceOf(Date), is_submitting: PropTypes.bool, is_uploading: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClearSuggestions: PropTypes.func.isRequired, onFetchSuggestions: PropTypes.func.isRequired, onSuggestionSelected: PropTypes.func.isRequired, onChangeSpoilerText: PropTypes.func.isRequired, onPaste: PropTypes.func.isRequired, onPickEmoji: PropTypes.func.isRequired, showSearch: PropTypes.bool, }; static defaultProps = { showSearch: false, }; handleChange = (e) => { this.props.onChange(e.target.value); } handleKeyDown = (e) => { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { this.handleSubmit(); } } handleSubmit = () => { if (this.props.text !== this.autosuggestTextarea.textarea.value) { // Something changed the text inside the textarea (e.g. browser extensions like Grammarly) // Update the state to match the current text this.props.onChange(this.autosuggestTextarea.textarea.value); } this.props.onSubmit(); } onSuggestionsClearRequested = () => { this.props.onClearSuggestions(); } onSuggestionsFetchRequested = (token) => { this.props.onFetchSuggestions(token); } onSuggestionSelected = (tokenStart, token, value) => { this._restoreCaret = null; this.props.onSuggestionSelected(tokenStart, token, value); } handleChangeSpoilerText = (e) => { this.props.onChangeSpoilerText(e.target.value); } componentWillReceiveProps (nextProps) { // If this is the update where we've finished uploading, // save the last caret position so we can restore it below! if (!nextProps.is_uploading && this.props.is_uploading) { this._restoreCaret = this.autosuggestTextarea.textarea.selectionStart; } } componentDidUpdate (prevProps) { // This statement does several things: // - If we're beginning a reply, and, // - Replying to zero or one users, places the cursor at the end of the textbox. // - Replying to more than one user, selects any usernames past the first; // this provides a convenient shortcut to drop everyone else from the conversation. // - If we've just finished uploading an image, and have a saved caret position, // restores the cursor to that position after the text changes! if (this.props.focusDate !== prevProps.focusDate || (prevProps.is_uploading && !this.props.is_uploading && typeof this._restoreCaret === 'number')) { let selectionEnd, selectionStart; if (this.props.preselectDate !== prevProps.preselectDate) { selectionEnd = this.props.text.length; selectionStart = this.props.text.search(/\s/) + 1; } else if (typeof this._restoreCaret === 'number') { selectionStart = this._restoreCaret; selectionEnd = this._restoreCaret; } else { selectionEnd = this.props.text.length; selectionStart = selectionEnd; } this.autosuggestTextarea.textarea.setSelectionRange(selectionStart, selectionEnd); this.autosuggestTextarea.textarea.focus(); } else if(prevProps.is_submitting && !this.props.is_submitting) { this.autosuggestTextarea.textarea.focus(); } } setAutosuggestTextarea = (c) => { this.autosuggestTextarea = c; } handleEmojiPick = (data) => { const position = this.autosuggestTextarea.textarea.selectionStart; const emojiChar = data.native; this._restoreCaret = position + emojiChar.length + 1; this.props.onPickEmoji(position, data); } render () { const { intl, onPaste, showSearch } = this.props; const disabled = this.props.is_submitting; const text = [this.props.spoiler_text, countableText(this.props.text)].join(''); let publishText = ''; if (this.props.privacy === 'private' || this.props.privacy === 'direct') { publishText = <span className='compose-form__publish-private'><i className='fa fa-lock' /> {intl.formatMessage(messages.publish)}</span>; } else { publishText = this.props.privacy !== 'unlisted' ? intl.formatMessage(messages.publishLoud, { publish: intl.formatMessage(messages.publish) }) : intl.formatMessage(messages.publish); } return ( <div className='compose-form'> <Collapsable isVisible={this.props.spoiler} fullHeight={50}> <div className='spoiler-input'> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.spoiler_placeholder)}</span> <input placeholder={intl.formatMessage(messages.spoiler_placeholder)} value={this.props.spoiler_text} onChange={this.handleChangeSpoilerText} onKeyDown={this.handleKeyDown} type='text' className='spoiler-input__input' id='cw-spoiler-input' /> </label> </div> </Collapsable> <WarningContainer /> <ReplyIndicatorContainer /> <div className='compose-form__autosuggest-wrapper'> <AutosuggestTextarea ref={this.setAutosuggestTextarea} placeholder={intl.formatMessage(messages.placeholder)} disabled={disabled} value={this.props.text} onChange={this.handleChange} suggestions={this.props.suggestions} onKeyDown={this.handleKeyDown} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} onPaste={onPaste} autoFocus={!showSearch && !isMobile(window.innerWidth)} /> <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} /> </div> <div className='compose-form__modifiers'> <UploadFormContainer /> </div> <div className='compose-form__buttons-wrapper'> <div className='compose-form__buttons'> <UploadButtonContainer /> <PrivacyDropdownContainer /> <SensitiveButtonContainer /> <SpoilerButtonContainer /> </div> <div className='compose-form__publish'> <div className='character-counter__wrapper'><CharacterCounter max={500} text={text} /></div> <div className='compose-form__publish-button-wrapper'><Button text={publishText} onClick={this.handleSubmit} disabled={disabled || this.props.is_uploading || length(text) > 500 || (text.length !== 0 && text.trim().length === 0)} block /></div> </div> </div> </div> ); } }
components/Entry.js
nikhilsaraf/react-native-todo-app
/** * @flow */ import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import PropTypes from 'prop-types'; import { Icon } from 'react-native-elements'; import Box from './Box'; class Entry extends React.Component { render() { return ( <Box style={styles.box} numberOfLines={this.props.numberOfLines} > <Text style={styles.text} numberOfLines={this.props.numberOfLines} ellipsizeMode='tail' > {this.props.text} </Text> <Icon style={styles.icon} name={this.props.icon1} raised={true} color='#000' size={20} underlayColor='transparent' onPress={this.props.onPressIcon1} /> <Icon style={styles.icon} name={this.props.icon2} raised={true} color='#000' size={20} underlayColor='transparent' onPress={this.props.onPressIcon2} /> </Box> ); } } Entry.propTypes = { text: PropTypes.string.isRequired, numberOfLines: PropTypes.number.isRequired, icon1: PropTypes.string.isRequired, icon2: PropTypes.string.isRequired, onPressIcon1: PropTypes.func.isRequired, onPressIcon2: PropTypes.func.isRequired }; const styles = StyleSheet.create({ box: { flexDirection: 'row', alignItems: 'center', }, text: { flex: 10, paddingTop: 6, paddingBottom: 2, paddingLeft: 6, paddingRight: 2, color: '#000', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontFamily: 'Helvetica', }, icon: { flex: 1, paddingTop: 4, paddingRight: 2, }, }); export default Entry;
src/components/Login/Login.js
nambawan/g-old
/* eslint-disable react/destructuring-assignment */ import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { defineMessages, FormattedMessage } from 'react-intl'; import { login } from '../../actions/session'; import { getAccountUpdates } from '../../reducers'; import Link from '../Link'; import Button from '../Button'; import Box from '../Box'; import FormField from '../FormField'; import { createValidator, passwordValidation, emailValidation, } from '../../core/validation'; const messages = defineMessages({ email: { id: 'label.email', defaultMessage: 'Email', description: 'Heading of email section', }, password: { id: 'label.password', defaultMessage: 'Password', description: 'Heading of password section', }, resetPassword: { id: 'login.resetPassword', defaultMessage: 'Forgot your password?', description: 'Help for password', }, empty: { id: 'form.error-empty', defaultMessage: "You can't leave this empty", description: 'Help for empty fields', }, invalidEmail: { id: 'form.error-invalidEmail', defaultMessage: 'Your email address seems to be invalid', description: 'Help for email', }, error: { id: 'login.error', defaultMessage: 'Login attempt failed', description: 'Failed login', }, login: { id: 'label.login', defaultMessage: 'Log In', description: 'Label login', }, }); class Login extends React.Component { static propTypes = { status: PropTypes.shape({ login: PropTypes.shape({ error: PropTypes.bool, success: PropTypes.bool, pending: PropTypes.bool, }), }).isRequired, login: PropTypes.func.isRequired, }; constructor(props) { super(props); this.onSubmit = this.onSubmit.bind(this); this.handleLogin = this.handleLogin.bind(this); this.onEmailChange = this.onEmailChange.bind(this); this.onPasswordChange = this.onPasswordChange.bind(this); this.state = { email: '', password: '', errors: { email: {}, password: {} }, }; const testValues = { password: { fn: 'password' }, email: { fn: 'email' }, }; this.Validator = createValidator( testValues, { password: passwordValidation, email: emailValidation, }, this, obj => obj.state, ); } componentWillReceiveProps(nextProps) { if ( nextProps.status && nextProps.status.login && nextProps.status.login.error ) { this.setState({ password: '' }); } } onEmailChange(e) { this.setState({ email: e.target.value }); } onPasswordChange(e) { this.setState({ password: e.target.value }); } onSubmit(e) { /* prevent the default form-submit action */ e.preventDefault(); this.handleLogin(); /* apparently this is needed with some browsers to prevent the submit action */ return false; } handleLogin() { const validated = this.Validator(['password', 'email']); this.setState(prevState => ({ errors: { ...prevState.errors, ...validated.errors }, })); if (!validated.failed) { this.props.login({ email: this.state.email.trim(), password: this.state.password.trim(), }); } } render() { const { status } = this.props; const { errors, password, email } = this.state; /* if (status.login && status.login.success) { // / history.push('/private'); } */ const emailError = errors.email.errorName ? ( <FormattedMessage {...messages[errors.email.errorName]} /> ) : null; const passwordError = errors.password.errorName ? ( <FormattedMessage {...messages[errors.password.errorName]} /> ) : null; const loginError = status.login && status.login.error ? ( <div style={{ backgroundColor: 'rgba(255, 50, 77,0.3)' }}> <FormattedMessage {...messages.error} /> </div> ) : null; return ( <Box column pad> <form onSubmit={this.onSubmit}> {/* invisible submit button */} <input type="submit" style={{ display: 'none' }} /> <fieldset> <FormField label={<FormattedMessage {...messages.email} />} error={emailError} > <input name="email" type="text" value={email} onChange={this.onEmailChange} /> </FormField> <FormField label={<FormattedMessage {...messages.password} />} error={passwordError} > <input name="password" type="password" value={password} onChange={this.onPasswordChange} /> </FormField> {loginError} </fieldset> </form> <Button fill primary label={<FormattedMessage {...messages.login} />} onClick={this.handleLogin} disabled={status.login && status.login.pending} /> {/* eslint-disable */} <Link to="/account/password/reset"> {/* eslint-enable */} <FormattedMessage {...messages.resetPassword} /> </Link> </Box> ); } } const mapStateToProps = state => { const initialId = '0000'; return { status: getAccountUpdates(state, initialId), }; }; const mapDispatch = { login, }; export default connect( mapStateToProps, mapDispatch, )(Login);
src/components/Seo.js
rhostem/blog
import React from 'react' import PropTypes from 'prop-types' import Helmet from 'react-helmet' import { StaticQuery, graphql } from 'gatsby' import { concat, not, isEmpty, filter, includes, isNil, compose } from 'ramda' import { PROFILE_IMAGE } from 'src/constants' export const DEFAULT_KEYWORDS = ['웹 개발', 'Front-end', '프론트엔드'] function SEO({ title, description, keywords = [], meta = [], lang }) { return ( <StaticQuery query={detailsQuery} render={data => { const metaDescription = description || data.site.siteMetadata.description const siteTitle = data.site.siteMetadata.title let metaTags = [ { name: `description`, content: metaDescription }, { property: `og:url`, content: 'https://blog.rhostem.com' }, { property: `og:type`, content: 'website' }, { property: `og:title`, content: title }, { property: `og:description`, content: metaDescription }, { property: `og:image`, content: PROFILE_IMAGE }, { name: `twitter:card`, content: `summary_large_image` }, { name: `twitter:creator`, content: data.site.siteMetadata.author }, { name: `twitter:title`, content: title }, { name: `twitter:description`, content: metaDescription }, { name: `twitter:image`, content: PROFILE_IMAGE }, ] // 키워드 추가 if (keywords && !isEmpty(keywords)) { metaTags.push({ name: `keywords`, content: keywords.concat(DEFAULT_KEYWORDS).join(`, `), }) } else { metaTags.push({ name: 'keywords', content: DEFAULT_KEYWORDS.join(', '), }) } // SEO 컴포넌트에 직접 전달받은 메타 태그는 중복을 제거하고 추가한다. if (meta.length > 0) { const metaNamesToAdd = meta .map(m => m.name) .filter( compose( not, isNil ) ) metaTags = concat( // metaTags에서 SEO 컴포넌트에 직접 전달된 filter(currentMeta => not(includes(currentMeta.name, metaNamesToAdd)) )(metaTags), meta ) } return ( <Helmet htmlAttributes={{ lang: 'ko', }} title={title || siteTitle} titleTemplate={title ? `%s | ${siteTitle}` : ''} meta={metaTags} /> ) }} /> ) } SEO.defaultProps = { lang: `ko`, meta: [], keywords: [], } SEO.propTypes = { description: PropTypes.string, lang: PropTypes.string, meta: PropTypes.array, keywords: PropTypes.arrayOf(PropTypes.string), title: PropTypes.string, } export default SEO const detailsQuery = graphql` query DefaultSEOQuery { site { siteMetadata { title description author } } } `
fields/components/DateInput.js
lastjune/keystone
import moment from 'moment'; import DayPicker from 'react-day-picker'; import React from 'react'; import Popout from '../../admin/src/components/Popout'; import { FormInput } from 'elemental'; function isSameDay(d1, d2) { d1.setHours(0, 0, 0, 0); d2.setHours(0, 0, 0, 0); return d1.getTime() === d2.getTime(); } module.exports = React.createClass({ displayName: 'DateInput', // set default properties getDefaultProps () { return { format: 'YYYY-MM-DD' }; }, getInitialState () { return { selectedDay: new Date(), id: Math.round(Math.random() * 100000), pickerIsOpen: false }; }, // componentWillReceiveProps: function(newProps) { // console.log(moment(newProps.value).format("ddd MMMM DD YYYY hh:mm:ss a Z")); // if (newProps.value === this.state.selectedDay) return; // this.setState({ // selectedDay: moment(newProps.value).format("ddd MMMM DD YYYY hh:mm:ss a Z") // }); // }, handleChange (e, day) { this.setState({ selectedDay: day }, () => { setTimeout(() => { this.setState({ pickerIsOpen: false }); }, 200); }); }, handleFocus (e) { this.setState({ pickerIsOpen: true }); }, handleBlur (e) { }, render () { let { selectedDay } = this.state; let modifiers = { 'selected': (day) => isSameDay(selectedDay, day) }; return ( <div> <FormInput autoComplete="off" id={this.state.id} name={this.props.name} onBlur={this.handleBlur} onFocus={this.handleFocus} onChange={this.handleChange} placeholder={this.props.format} value={moment(selectedDay).format(this.props.format)} /> <Popout isOpen={this.state.pickerIsOpen} onCancel={() => this.setState({ pickerIsOpen: false })} relativeToID={this.state.id} width={260}> <DayPicker modifiers={ modifiers } onDayClick={ this.handleChange } style={{ marginBottom: 9 }} tabIndex={-1} /> </Popout> </div> ); // return <FormInput name={this.props.name} value={this.state.value} placeholder={this.props.format} onChange={this.handleChange} onBlur={this.handleBlur} autoComplete="off" />; } });
q-a11y-training-demo/src/components/person/achievements/Achievements.js
AlmeroSteyn/Q-A11y-Training
import React from 'react'; const Achievements = () => <div>Achievements page</div>; export default Achievements;
node_modules/react-error-overlay/lib/index.js
lujinming1/hejicaoye
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React from 'react'; import ReactDOM from 'react-dom'; import CompileErrorContainer from './containers/CompileErrorContainer'; import RuntimeErrorContainer from './containers/RuntimeErrorContainer'; import { listenToRuntimeErrors } from './listenToRuntimeErrors'; import { iframeStyle, overlayStyle } from './styles'; import { applyStyles } from './utils/dom/css'; var iframe = null; var isLoadingIframe = false; var renderedElement = null; var currentBuildError = null; var currentRuntimeErrorRecords = []; var currentRuntimeErrorOptions = null; var stopListeningToRuntimeErrors = null; export function reportBuildError(error) { currentBuildError = error; update(); } export function dismissBuildError() { currentBuildError = null; update(); } export function startReportingRuntimeErrors(options) { if (stopListeningToRuntimeErrors !== null) { throw new Error('Already listening'); } currentRuntimeErrorOptions = options; listenToRuntimeErrors(function (errorRecord) { try { if (typeof options.onError === 'function') { options.onError.call(null); } } finally { handleRuntimeError(errorRecord); } }, options.filename); } function handleRuntimeError(errorRecord) { if (currentRuntimeErrorRecords.some(function (_ref) { var error = _ref.error; return error === errorRecord.error; })) { // Deduplicate identical errors. // This fixes https://github.com/facebookincubator/create-react-app/issues/3011. return; } currentRuntimeErrorRecords = currentRuntimeErrorRecords.concat([errorRecord]); update(); } function dismissRuntimeErrors() { currentRuntimeErrorRecords = []; update(); } export function stopReportingRuntimeErrors() { if (stopListeningToRuntimeErrors === null) { throw new Error('Not currently listening'); } currentRuntimeErrorOptions = null; try { stopListeningToRuntimeErrors(); } finally { stopListeningToRuntimeErrors = null; } } function update() { renderedElement = render(); // Loading iframe can be either sync or async depending on the browser. if (isLoadingIframe) { // Iframe is loading. // First render will happen soon--don't need to do anything. return; } if (iframe) { // Iframe has already loaded. // Just update it. updateIframeContent(); return; } // We need to schedule the first render. isLoadingIframe = true; var loadingIframe = window.document.createElement('iframe'); applyStyles(loadingIframe, iframeStyle); loadingIframe.onload = function () { var iframeDocument = loadingIframe.contentDocument; if (iframeDocument != null && iframeDocument.body != null) { iframeDocument.body.style.margin = '0'; // Keep popup within body boundaries for iOS Safari iframeDocument.body.style['max-width'] = '100vw'; var iframeRoot = iframeDocument.createElement('div'); applyStyles(iframeRoot, overlayStyle); iframeDocument.body.appendChild(iframeRoot); // Ready! Now we can update the UI. iframe = loadingIframe; isLoadingIframe = false; updateIframeContent(); } }; var appDocument = window.document; appDocument.body.appendChild(loadingIframe); } function render() { if (currentBuildError) { return React.createElement(CompileErrorContainer, { error: currentBuildError }); } if (currentRuntimeErrorRecords.length > 0) { if (!currentRuntimeErrorOptions) { throw new Error('Expected options to be injected.'); } return React.createElement(RuntimeErrorContainer, { errorRecords: currentRuntimeErrorRecords, close: dismissRuntimeErrors, launchEditorEndpoint: currentRuntimeErrorOptions.launchEditorEndpoint }); } return null; } function updateIframeContent() { if (iframe === null) { throw new Error('Iframe has not been created yet.'); } var iframeBody = iframe.contentDocument.body; if (!iframeBody) { throw new Error('Expected iframe to have a body.'); } var iframeRoot = iframeBody.firstChild; if (renderedElement === null) { // Destroy iframe and force it to be recreated on next error window.document.body.removeChild(iframe); ReactDOM.unmountComponentAtNode(iframeRoot); iframe = null; return; } // Update the overlay ReactDOM.render(renderedElement, iframeRoot); }
src/ThreadView.js
drop-table-ryhmatyo/tekislauta-front
import React, { Component } from 'react'; import Helmet from 'react-helmet'; import Post, { OriginalPost } from './Post'; import SubmitForm from './SubmitForm'; import Endpoints from './Endpoints'; var self; class ThreadView extends Component { constructor(props) { super(props); this.state = { title: "Loading..." }; } componentDidMount() { this.fetchPosts(); } render() { self = this; let posts = []; if (this.state && this.state.posts && this.state.posts.length >= 0) { posts.push(<OriginalPost data={this.state.posts[0]} key={this.state.posts[0].id} board={this.props.params.board} onReplyClicked={d => this.handleReplyClick(d)} />); for (let i = 1; i < this.state.posts.length; i++) { const t = this.state.posts[i]; posts.push(<Post data={t} key={t.id} board={this.props.abbreviation} onReplyClicked={d => this.handleReplyClick(d)} />); } } return ( <div className='Thread'> <Helmet title={this.state.title}/> <div className='SubmitFormBox'> <SubmitForm title="Submit new reply" submit={this.submitResponse.bind(this)} callback={inst => self.submitForm = inst} /> </div> <div> {posts} </div> <p> {posts.length === 1 ? 'No replies' : ''} </p> </div> ); } handleReplyClick(postId) { self.submitForm.setMessageBoxVal('>> ' + postId); } fetchPosts() { Endpoints.Replies(this.props.params.board, this.props.params.thread).getData() .then(data => { const opMsg = data[0].message; const truncatedMsg = opMsg.length > 32 ? opMsg.substr(0, 32-3) + "..." : opMsg; this.setState({ posts: data, title: `/${this.props.params.board}/ - ${truncatedMsg}` }); }) .catch(err => console.error("ThreadView::fetchPots", "Error while getting posts!", err)); } submitResponse(formData) { Endpoints.Replies(this.props.params.board, this.props.params.thread).postData(formData) .then(data => { console.log("ThreadView::submitResponse", "Submitted new post!", data); window.location.reload(); }) .catch(err => { console.log("ThreadView::submitResponse", "Error while submitting new post!", err); }); } } export default ThreadView;
src/components/common/svg-icons/hardware/tablet-android.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareTabletAndroid = (props) => ( <SvgIcon {...props}> <path d="M18 0H6C4.34 0 3 1.34 3 3v18c0 1.66 1.34 3 3 3h12c1.66 0 3-1.34 3-3V3c0-1.66-1.34-3-3-3zm-4 22h-4v-1h4v1zm5.25-3H4.75V3h14.5v16z"/> </SvgIcon> ); HardwareTabletAndroid = pure(HardwareTabletAndroid); HardwareTabletAndroid.displayName = 'HardwareTabletAndroid'; HardwareTabletAndroid.muiName = 'SvgIcon'; export default HardwareTabletAndroid;
src/components/Contentful/News/presenter.js
ndlib/usurper
// Presenter component for a Page content type from Contentful import React from 'react' import PropTypes from 'prop-types' import 'static/css/global.css' import LibMarkdown from 'components/LibMarkdown' import Related from '../Related' import Image from 'components/Image' import Link from 'components/Interactive/Link' import Librarians from 'components/Librarians' import PageTitle from 'components/Layout/PageTitle' import SearchProgramaticSet from 'components/SearchProgramaticSet' import { formatDate } from 'shared/DateLibs.js' import ShareLinks from 'components/Interactive/ShareLinks' import OpenGraph from 'components/OpenGraph' import Canonical from 'components/Canonical' const PagePresenter = ({ entry }) => ( <article className='container-fluid content-area news-article' itemScope itemType='http://schema.org/NewsArticle' itemProp='mainEntity' > {entry.fields.shortDescription && (<meta name='description' content={entry.fields.shortDescription} />)} <PageTitle title={entry.fields.title} itemProp='headline' classes='col-md-8 col-sm-8'> <div className='tagline news col-md-12'> {entry.fields.author && <div className='author'>{'By ' + entry.fields.author}</div>} {entry.fields.publishedDate && ( <div className={'published' + (entry.fields.author ? ' separator' : '')}> {formatDate(entry.fields.publishedDate)} </div> )} <ShareLinks className='separator' title={entry.fields.title} /> </div> </PageTitle> {entry.fields.canonicalUrl && ( <Canonical url={entry.fields.canonicalUrl} /> )} <OpenGraph title={entry.fields.title} description={entry.fields.shortDescription} image={entry.fields.image} /> <SearchProgramaticSet open={false} /> <div className='row'> <main className='col-md-8 col-sm-8 article'> <Image cfImage={entry.fields.image} className='news cover' itemProp='image' width={747} /> <LibMarkdown itemProp='articleBody'>{entry.fields.content}</LibMarkdown> <LibMarkdown className='contactNews'>{entry.fields.contactUsPubInfo}</LibMarkdown> <Related className='p-resources' title='Resources' showImages={false}> {entry.fields.relatedResources} </Related> <Link to='/news' className='newsEventsLink' arrow>View All News</Link> </main> <aside className='col-md-4 col-sm-4 right news'> <Librarians netids={entry.fields.contactPeople} /> <Related className='p-pages' title='Related Pages' showImages={false}>{entry.fields.relatedPages}</Related> </aside> </div> </article> ) PagePresenter.propTypes = { entry: PropTypes.object.isRequired, } export default PagePresenter
src/svg-icons/action/settings-input-svideo.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsInputSvideo = (props) => ( <SvgIcon {...props}> <path d="M8 11.5c0-.83-.67-1.5-1.5-1.5S5 10.67 5 11.5 5.67 13 6.5 13 8 12.33 8 11.5zm7-5c0-.83-.67-1.5-1.5-1.5h-3C9.67 5 9 5.67 9 6.5S9.67 8 10.5 8h3c.83 0 1.5-.67 1.5-1.5zM8.5 15c-.83 0-1.5.67-1.5 1.5S7.67 18 8.5 18s1.5-.67 1.5-1.5S9.33 15 8.5 15zM12 1C5.93 1 1 5.93 1 12s4.93 11 11 11 11-4.93 11-11S18.07 1 12 1zm0 20c-4.96 0-9-4.04-9-9s4.04-9 9-9 9 4.04 9 9-4.04 9-9 9zm5.5-11c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm-2 5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5z"/> </SvgIcon> ); ActionSettingsInputSvideo = pure(ActionSettingsInputSvideo); ActionSettingsInputSvideo.displayName = 'ActionSettingsInputSvideo'; ActionSettingsInputSvideo.muiName = 'SvgIcon'; export default ActionSettingsInputSvideo;
upgrade-guides/v0.12-v0.13/es5/src/components/Layout.js
lore/lore
/** * This component is intended to reflect the high level structure of your application, * and render any components that are common across all views, such as the header or * top-level navigation. All other components should be rendered by route handlers. **/ import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import logo from '../../assets/images/logo.png'; export default createReactClass({ displayName: 'Layout', render() { return ( <div> <div className="header"> <div className="container"> <div className="title"> <img className="logo" src={logo} /> <h1> Welcome to Lore! </h1> <h3> You're looking at <code>src/components/Layout.js</code> </h3> </div> </div> </div> <div className="main"> <div className="container"> <ul> <li> <div> <h3>Getting Started</h3> <p>Edit this file and the page will automatically reload to display changes.</p> </div> </li> <li> <div> <h3>New to Lore?</h3> <p>Learn how to use it by following the <a target="_blank" href="http://www.lorejs.org/quickstart/">quickstart</a>.</p> </div> </li> </ul> </div> </div> </div> ); } });
node_modules/rc-time-picker/es/TimePicker.js
prodigalyijun/demo-by-antd
import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Trigger from 'rc-trigger'; import Panel from './Panel'; import placements from './placements'; import moment from 'moment'; function noop() {} function refFn(field, component) { this[field] = component; } var Picker = function (_Component) { _inherits(Picker, _Component); function Picker(props) { _classCallCheck(this, Picker); var _this = _possibleConstructorReturn(this, (Picker.__proto__ || Object.getPrototypeOf(Picker)).call(this, props)); _initialiseProps.call(_this); _this.saveInputRef = refFn.bind(_this, 'picker'); _this.savePanelRef = refFn.bind(_this, 'panelInstance'); var defaultOpen = props.defaultOpen, defaultValue = props.defaultValue, _props$open = props.open, open = _props$open === undefined ? defaultOpen : _props$open, _props$value = props.value, value = _props$value === undefined ? defaultValue : _props$value; _this.state = { open: open, value: value }; return _this; } _createClass(Picker, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var value = nextProps.value, open = nextProps.open; if ('value' in nextProps) { this.setState({ value: value }); } if (open !== undefined) { this.setState({ open: open }); } } }, { key: 'setValue', value: function setValue(value) { if (!('value' in this.props)) { this.setState({ value: value }); } this.props.onChange(value); } }, { key: 'getFormat', value: function getFormat() { var _props = this.props, format = _props.format, showHour = _props.showHour, showMinute = _props.showMinute, showSecond = _props.showSecond, use12Hours = _props.use12Hours; if (format) { return format; } if (use12Hours) { var fmtString = [showHour ? 'h' : '', showMinute ? 'mm' : '', showSecond ? 'ss' : ''].filter(function (item) { return !!item; }).join(':'); return fmtString.concat(' a'); } return [showHour ? 'HH' : '', showMinute ? 'mm' : '', showSecond ? 'ss' : ''].filter(function (item) { return !!item; }).join(':'); } }, { key: 'getPanelElement', value: function getPanelElement() { var _props2 = this.props, prefixCls = _props2.prefixCls, placeholder = _props2.placeholder, disabledHours = _props2.disabledHours, disabledMinutes = _props2.disabledMinutes, disabledSeconds = _props2.disabledSeconds, hideDisabledOptions = _props2.hideDisabledOptions, allowEmpty = _props2.allowEmpty, showHour = _props2.showHour, showMinute = _props2.showMinute, showSecond = _props2.showSecond, defaultOpenValue = _props2.defaultOpenValue, clearText = _props2.clearText, addon = _props2.addon, use12Hours = _props2.use12Hours; return React.createElement(Panel, { clearText: clearText, prefixCls: prefixCls + '-panel', ref: this.savePanelRef, value: this.state.value, onChange: this.onPanelChange, onClear: this.onPanelClear, defaultOpenValue: defaultOpenValue, showHour: showHour, showMinute: showMinute, showSecond: showSecond, onEsc: this.onEsc, allowEmpty: allowEmpty, format: this.getFormat(), placeholder: placeholder, disabledHours: disabledHours, disabledMinutes: disabledMinutes, disabledSeconds: disabledSeconds, hideDisabledOptions: hideDisabledOptions, use12Hours: use12Hours, addon: addon }); } }, { key: 'getPopupClassName', value: function getPopupClassName() { var _props3 = this.props, showHour = _props3.showHour, showMinute = _props3.showMinute, showSecond = _props3.showSecond, use12Hours = _props3.use12Hours, prefixCls = _props3.prefixCls; var popupClassName = this.props.popupClassName; // Keep it for old compatibility if ((!showHour || !showMinute || !showSecond) && !use12Hours) { popupClassName += ' ' + prefixCls + '-panel-narrow'; } var selectColumnCount = 0; if (showHour) { selectColumnCount += 1; } if (showMinute) { selectColumnCount += 1; } if (showSecond) { selectColumnCount += 1; } if (use12Hours) { selectColumnCount += 1; } popupClassName += ' ' + prefixCls + '-panel-column-' + selectColumnCount; return popupClassName; } }, { key: 'setOpen', value: function setOpen(open) { var _props4 = this.props, onOpen = _props4.onOpen, onClose = _props4.onClose; if (this.state.open !== open) { if (!('open' in this.props)) { this.setState({ open: open }); } if (open) { onOpen({ open: open }); } else { onClose({ open: open }); } } } }, { key: 'focus', value: function focus() { this.picker.focus(); } }, { key: 'render', value: function render() { var _props5 = this.props, prefixCls = _props5.prefixCls, placeholder = _props5.placeholder, placement = _props5.placement, align = _props5.align, disabled = _props5.disabled, transitionName = _props5.transitionName, style = _props5.style, className = _props5.className, getPopupContainer = _props5.getPopupContainer, name = _props5.name, autoComplete = _props5.autoComplete; var _state = this.state, open = _state.open, value = _state.value; var popupClassName = this.getPopupClassName(); return React.createElement( Trigger, { prefixCls: prefixCls + '-panel', popupClassName: popupClassName, popup: this.getPanelElement(), popupAlign: align, builtinPlacements: placements, popupPlacement: placement, action: disabled ? [] : ['click'], destroyPopupOnHide: true, getPopupContainer: getPopupContainer, popupTransitionName: transitionName, popupVisible: open, onPopupVisibleChange: this.onVisibleChange }, React.createElement( 'span', { className: prefixCls + ' ' + className, style: style }, React.createElement('input', { className: prefixCls + '-input', ref: this.saveInputRef, type: 'text', placeholder: placeholder, name: name, readOnly: true, onKeyDown: this.onKeyDown, disabled: disabled, value: value && value.format(this.getFormat()) || '', autoComplete: autoComplete }), React.createElement('span', { className: prefixCls + '-icon' }) ) ); } }]); return Picker; }(Component); Picker.propTypes = { prefixCls: PropTypes.string, clearText: PropTypes.string, value: PropTypes.object, defaultOpenValue: PropTypes.object, disabled: PropTypes.bool, allowEmpty: PropTypes.bool, defaultValue: PropTypes.object, open: PropTypes.bool, defaultOpen: PropTypes.bool, align: PropTypes.object, placement: PropTypes.any, transitionName: PropTypes.string, getPopupContainer: PropTypes.func, placeholder: PropTypes.string, format: PropTypes.string, showHour: PropTypes.bool, showMinute: PropTypes.bool, showSecond: PropTypes.bool, style: PropTypes.object, className: PropTypes.string, popupClassName: PropTypes.string, disabledHours: PropTypes.func, disabledMinutes: PropTypes.func, disabledSeconds: PropTypes.func, hideDisabledOptions: PropTypes.bool, onChange: PropTypes.func, onOpen: PropTypes.func, onClose: PropTypes.func, addon: PropTypes.func, name: PropTypes.string, autoComplete: PropTypes.string, use12Hours: PropTypes.bool }; Picker.defaultProps = { clearText: 'clear', prefixCls: 'rc-time-picker', defaultOpen: false, style: {}, className: '', popupClassName: '', align: {}, defaultOpenValue: moment(), allowEmpty: true, showHour: true, showMinute: true, showSecond: true, disabledHours: noop, disabledMinutes: noop, disabledSeconds: noop, hideDisabledOptions: false, placement: 'bottomLeft', onChange: noop, onOpen: noop, onClose: noop, addon: noop, use12Hours: false }; var _initialiseProps = function _initialiseProps() { var _this2 = this; this.onPanelChange = function (value) { _this2.setValue(value); }; this.onPanelClear = function () { _this2.setValue(null); _this2.setOpen(false); }; this.onVisibleChange = function (open) { _this2.setOpen(open); }; this.onEsc = function () { _this2.setOpen(false); _this2.focus(); }; this.onKeyDown = function (e) { if (e.keyCode === 40) { _this2.setOpen(true); } }; }; export default Picker;
src/containers/Location/index.js
TUIHackfridays/tuise-poc
import React from 'react' const Location = () => <div> The location page </div> const styles = { } export default Location
src/components/topic/words/InfluentialWordsContainer.js
mitmedialab/MediaCloud-Web-Tools
import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; import { injectIntl, FormattedMessage } from 'react-intl'; import { Grid, Row, Col } from 'react-flexbox-grid/lib'; import Word2VecTimespanPlayerContainer from './Word2VecTimespanPlayerContainer'; import WordCloudComparisonContainer from './WordCloudComparisonContainer'; import FociWordComparison from './FociWordComparison'; import TopicPageTitle from '../TopicPageTitle'; const localMessages = { title: { id: 'topic.influentialWords.title', defaultMessage: 'Influential Words' }, intro: { id: 'topic.influentialWords.intro', defaultMessage: 'This screen lets you compare the words most used within this Timespan to the words used with this Subtopic. The words on the left are the most used in this Timespan. Those on the right are the most used within this Subtopic (if one is set, otherwise they are the most used in the whole snapshot).' }, }; const InfluentialWordsContainer = props => ( <Grid> <TopicPageTitle value={localMessages.title} /> <Row> <Col lg={12} md={12} sm={12}> <h1><FormattedMessage {...localMessages.title} /></h1> <p><FormattedMessage {...localMessages.intro} /></p> </Col> </Row> <FociWordComparison filters={props.filters} topicId={props.topicId} /> <WordCloudComparisonContainer /> <Word2VecTimespanPlayerContainer /> </Grid> ); InfluentialWordsContainer.propTypes = { // from compositional chain intl: PropTypes.object.isRequired, // from state topicId: PropTypes.number.isRequired, filters: PropTypes.object.isRequired, }; const mapStateToProps = state => ({ filters: state.topics.selected.filters, topicId: state.topics.selected.id, }); export default connect(mapStateToProps)( injectIntl( InfluentialWordsContainer ) );
src/js/containers/GalleryContainer.js
sdeleon28/react-fullscreen-gallery
import React from 'react'; import Gallery from '../components/Gallery'; const pt = React.PropTypes; class GalleryContainer extends React.Component { constructor() { super(); this.onImageSelected = this.onImageSelected.bind(this); this.state = { selectedImageIndex: 0, }; } onImageSelected(selectedImageIndex) { this.setState({ selectedImageIndex }); } render() { const images = this.props.images.map((image, index) => ({ ...image, index, selected: index === this.state.selectedImageIndex, })); const selectedImage = images.filter(image => image.selected)[0]; const { imageUrl, title } = selectedImage; return ( <Gallery imageUrl={imageUrl} title={title} images={images} onImageSelected={this.onImageSelected} /> ); } } GalleryContainer.propTypes = { images: pt.arrayOf(pt.shape({ imageUrl: pt.string.isRequired, thumbnailUrl: pt.string.isRequired, title: pt.string, alt: pt.string, })), }; export default GalleryContainer;
information/blendle-frontend-react-source/app/modules/timeline/components/FollowChannels.js
BramscoChill/BlendleParser
import React from 'react'; import PropTypes from 'prop-types'; import { translate, translateElement, getIso639_1 as getLang } from 'instances/i18n'; import classNames from 'classnames'; import Link from 'components/Link'; import ChannelName from 'components/ChannelName'; import Auth from 'controllers/auth'; import ChannelsStore from 'stores/ChannelsStore'; import ChannelActions from 'actions/ChannelActions'; import { STATUS_OK } from 'app-constants'; export default class TimelineNavigation extends React.Component { static propTypes = { onClose: PropTypes.func.isRequired, onChange: PropTypes.func, }; constructor() { super(); this.state = { channels: ChannelsStore.getState().channels, }; } componentWillMount() { ChannelsStore.listen(this._onStoreChange); } componentWillUnmount() { ChannelsStore.unlisten(this._onStoreChange); } _onStoreChange = (storeState) => { this.setState({ channels: storeState.channels }); }; _onChannelClick(channel, ev) { ChannelActions.followChannel(Auth.getId(), channel.id, !channel.get('following')); ev.stopPropagation(); ev.preventDefault(); if (this.props.onChange) { this.props.onChange(); } } _onContainerClick(ev) { ev.stopPropagation(); } _renderChannel(channel) { const className = classNames({ 'v-channel': true, 'v-channel-name': true, channel: true, [`channel-${channel.id}`]: true, 'l-following': channel.get('following'), }); return ( <li> <ChannelName onClick={this._onChannelClick.bind(this, channel)} className={className} channel={channel} /> </li> ); } _renderRequestChannel() { let url = 'https://blendle.typeform.com/to/duv5p9'; if (getLang() === 'nl') { url = 'https://blendle.typeform.com/to/Ar9GBY'; } return ( <li> <Link href={url} className="v-channel channel suggest-channel" target="_blank"> {translate('channels.suggest')} </Link> </li> ); } render() { if (this.state.channels.status !== STATUS_OK) { return null; } return ( <div className="channel-overlay" onClick={this.props.onClose}> <div className="v-channels" onClick={this._onContainerClick}> <a className="v-close-button" onClick={this.props.onClose} /> <h1>{translateElement('timeline.channel.title', [Auth.getUser().getFirstName()])}</h1> <ul> {this.state.channels.data.map(this._renderChannel.bind(this))} {this._renderRequestChannel()} </ul> </div> </div> ); } } // WEBPACK FOOTER // // ./src/js/app/modules/timeline/components/FollowChannels.js
motion-test/src/motionCustom.js
wandarkaf/React-Bible
import React, { Component } from 'react'; import {Motion, spring, presets} from 'react-motion'; class MotionCustom extends Component { render(){ return ( <Motion defaultStyle={{ y: 500, z: 4 }} style={{ y: spring(100, presets.wobbly), z: spring(1, presets.wobbly), }}> {obj => { let style= { transform: `translate(100px, ${obj.y}px) scale(${obj.z})`, border: '1px solid red', width: '100px', height: '100px', backgroundColor: '#b00b00', } return <div style={style} className="block"></div> }} </Motion> ) } } export default MotionCustom;
packages/icons/src/md/maps/LocalDrink.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdLocalDrink(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M6 4h36l-4.03 36.47A3.994 3.994 0 0 1 34 44H14c-2.05 0-3.74-1.54-3.97-3.53L6 4zm18 34c3.31 0 6-2.69 6-6 0-4-6-10.8-6-10.8S18 28 18 32c0 3.31 2.69 6 6 6zm12.65-22l.89-8H10.47l.88 8h25.3z" /> </IconBase> ); } export default MdLocalDrink;
components/BottomNavigation.js
BDE-ESIEE/mobile
'use strict'; import React from 'react'; import ScrollableTabView from 'react-native-scrollable-tab-view'; import {DefaultRenderer} from 'react-native-router-flux'; import TabBar from './TabBar'; class BottomNavigation extends React.Component { render () { const props = this.props; return ( <ScrollableTabView tabBarPosition='bottom' locked={true} renderTabBar={() => <TabBar />} > { props.navigationState.children.map(el => { return ( <DefaultRenderer navigationState={el} onNavigate={props.onNavigate} key={el.key} {...el} tabLabel={el.title} /> ); }) } </ScrollableTabView> ); } } module.exports = BottomNavigation;
src/components/RayGunComponent.js
pacmessica/worms-copy
import React from 'react'; class RayGunComponent extends React.Component { constructor() { super(); } gunStyle() { return { position: "fixed", width: "5px", height: "5px", backgroundColor: "black", left: this.props.x + 5 + "px", top: this.props.y + "px" }; } render() { console.log(this.props.x) return ( <div style={this.gunStyle()}> </div> ); } } export default RayGunComponent;
examples/src/app.js
mrcodemonkey/react-autosuggest
require('./app.less'); import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Badges from './Badges/Badges'; import Examples from './Examples'; import Footer from './Footer/Footer'; import ForkMeOnGitHub from './ForkMeOnGitHub/ForkMeOnGitHub'; import TrackLinks from './TrackLinks/TrackLinks'; class App extends Component { render() { return ( <TrackLinks> <h1>react-autosuggest</h1> <Badges /> <Examples /> <Footer /> <ForkMeOnGitHub user="moroshko" repo="react-autosuggest" /> </TrackLinks> ); } } ReactDOM.render(<App />, document.getElementById('app'));
lib/ui/src/modules/ui/components/layout/index.js
bigassdragon/storybook
import PropTypes from 'prop-types'; import React from 'react'; import USplit from './usplit'; import Dimensions from './dimensions'; import SplitPane from 'react-split-pane'; const rootStyle = { height: '100vh', backgroundColor: '#F7F7F7', }; const leftPanelStyle = leftPanelOnTop => ({ width: '100%', display: 'flex', flexDirection: leftPanelOnTop ? 'column' : 'row', alignItems: 'stretch', paddingRight: leftPanelOnTop ? 10 : 0, }); const downPanelStyle = downPanelInRight => ({ display: 'flex', flexDirection: downPanelInRight ? 'row' : 'column', alignItems: 'stretch', width: '100%', height: '100%', padding: downPanelInRight ? '5px 10px 10px 0' : '0px 10px 10px 0', boxSizing: 'border-box', }); const resizerCursor = isVert => (isVert ? 'col-resize' : 'row-resize'); const storiesResizerStyle = (showLeftPanel, leftPanelOnTop) => ({ cursor: showLeftPanel ? resizerCursor(!leftPanelOnTop) : undefined, height: leftPanelOnTop ? 10 : 'auto', width: leftPanelOnTop ? '100%' : 10, zIndex: 1, }); const addonResizerStyle = (showDownPanel, downPanelInRight) => ({ cursor: showDownPanel ? resizerCursor(downPanelInRight) : undefined, height: downPanelInRight ? '100%' : 10, width: downPanelInRight ? 10 : '100%', zIndex: 1, }); const contentPanelStyle = (downPanelInRight, leftPanelOnTop) => ({ position: 'absolute', boxSizing: 'border-box', width: '100%', height: '100%', padding: downPanelInRight ? '10px 2px 10px 0' : '10px 10px 2px 0', paddingTop: leftPanelOnTop ? 0 : 10, }); const normalPreviewStyle = { width: '100%', height: '100%', backgroundColor: '#FFF', border: '1px solid #ECECEC', borderRadius: 4, }; const fullScreenPreviewStyle = { position: 'fixed', left: '0px', right: '0px', top: '0px', zIndex: 1, backgroundColor: '#FFF', height: '100%', width: '100%', border: 0, margin: 0, padding: 0, overflow: 'hidden', }; const onDragStart = function() { document.body.classList.add('dragging'); }; const onDragEnd = function() { document.body.classList.remove('dragging'); }; const defaultSizes = { addonPanel: { down: 200, right: 400, }, storiesPanel: { left: 250, top: 400, }, }; const saveSizes = sizes => { try { localStorage.setItem('panelSizes', JSON.stringify(sizes)); return true; } catch (e) { return false; } }; const getSavedSizes = sizes => { try { const panelSizes = localStorage.getItem('panelSizes'); if (panelSizes) { return JSON.parse(panelSizes); } saveSizes(sizes); return sizes; } catch (e) { saveSizes(sizes); return sizes; } }; class Layout extends React.Component { constructor(props) { super(props); this.layerSizes = getSavedSizes(defaultSizes); this.state = { previewPanelDimensions: { height: 0, width: 0, }, }; this.onResize = this.onResize.bind(this); } componentDidMount() { window.addEventListener('resize', this.onResize); } componentWillUnmount() { window.removeEventListener('resize', this.onResize); } onResize(pane, mode) { return size => { this.layerSizes[pane][mode] = size; saveSizes(this.layerSizes); const { clientWidth, clientHeight } = this.previewPanelRef; this.setState({ previewPanelDimensions: { width: clientWidth, height: clientHeight, }, }); }; } render() { const { goFullScreen, showLeftPanel, showDownPanel, downPanelInRight, downPanel, leftPanel, preview, } = this.props; const { previewPanelDimensions } = this.state; const leftPanelOnTop = false; let previewStyle = normalPreviewStyle; if (goFullScreen) { previewStyle = fullScreenPreviewStyle; } const sizes = getSavedSizes(this.layerSizes); const leftPanelDefaultSize = !leftPanelOnTop ? sizes.storiesPanel.left : sizes.storiesPanel.top; const downPanelDefaultSize = !downPanelInRight ? sizes.addonPanel.down : sizes.addonPanel.right; const addonSplit = downPanelInRight ? 'vertical' : 'horizontal'; const storiesSplit = leftPanelOnTop ? 'horizontal' : 'vertical'; return ( <div style={rootStyle}> <SplitPane split={storiesSplit} allowResize={showLeftPanel} minSize={150} maxSize={-400} size={showLeftPanel ? leftPanelDefaultSize : 1} defaultSize={leftPanelDefaultSize} resizerStyle={storiesResizerStyle(showLeftPanel, leftPanelOnTop)} onDragStarted={onDragStart} onDragFinished={onDragEnd} onChange={this.onResize('storiesPanel', leftPanelOnTop ? 'top' : 'left')} > {showLeftPanel ? <div style={leftPanelStyle(leftPanelOnTop)}> <div style={{ flexGrow: 1, height: '100%' }}> {leftPanel()} </div> <USplit shift={5} split={storiesSplit} /> </div> : <div />} <SplitPane split={addonSplit} allowResize={showDownPanel} primary="second" minSize={downPanelInRight ? 200 : 100} maxSize={-200} size={showDownPanel ? downPanelDefaultSize : 1} defaultSize={downPanelDefaultSize} resizerStyle={addonResizerStyle(showDownPanel, downPanelInRight)} onDragStarted={onDragStart} onDragFinished={onDragEnd} onChange={this.onResize('addonPanel', downPanelInRight ? 'right' : 'down')} > <div style={contentPanelStyle(downPanelInRight, leftPanelOnTop)}> <div style={previewStyle} ref={ref => { this.previewPanelRef = ref; }} > {preview()} </div> <Dimensions {...previewPanelDimensions} /> </div> {showDownPanel ? <div style={downPanelStyle(downPanelInRight)}> <USplit shift={-5} split={addonSplit} /> {downPanel()} </div> : <div />} </SplitPane> </SplitPane> </div> ); } } Layout.propTypes = { showLeftPanel: PropTypes.bool.isRequired, showDownPanel: PropTypes.bool.isRequired, goFullScreen: PropTypes.bool.isRequired, leftPanel: PropTypes.func.isRequired, preview: PropTypes.func.isRequired, downPanel: PropTypes.func.isRequired, downPanelInRight: PropTypes.bool.isRequired, }; export default Layout;
src/components/Github/Feed/DetailPush.js
jseminck/react-native-github-feed
import React from 'react'; import { Text, View, Image, ScrollView, ListView } from 'react-native'; import moment from 'moment'; export default class DetailComment extends React.Component { static propTypes = { eventDetail: React.PropTypes.object.isRequired } constructor(props) { super(props); const dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); this.state = { dataSource: dataSource.cloneWithRows(this.props.eventDetail.payload.commits) }; } render() { return ( <ScrollView> <View style={styles.container}> <Image source={{uri : this.props.eventDetail.actor.avatar_url}} style={styles.image} /> <Text style={styles.name}> {moment(this.props.eventDetail.created_at).fromNow()} </Text> <Text> {this.props.eventDetail.actor.login} pushed to </Text> <Text> {this.props.eventDetail.payload.ref.replace('refs/heads/', '')} </Text> <Text> at {this.props.eventDetail.repo.name} </Text> {this.renderCommits()} </View> </ScrollView> ); } renderCommits() { return ( <View style={styles.container}> <Text style={styles.name}> {this.props.eventDetail.payload.commits.length} commit(s) </Text> <ListView enableEmptySections={true} dataSource={this.state.dataSource} renderRow={this.renderRow} /> </View> ); } renderRow(rowData) { return ( <View style={styles.issueContainer}> <Text style={styles.issueTitle}> {rowData.sha.substring(1, 6)} - {rowData.message} </Text> </View> ); } } const styles = { container: { justifyContent: 'flex-start', alignItems: 'center', flex: 1 }, image: { borderRadius: 100, height: 200, width: 200 }, name: { marginTop: 20, fontSize: 24 }, issueContainer: { marginTop: 20, marginBottom: 20, marginLeft: 10, marginRight: 10, padding: 20, backgroundColor: '#45698F', justifyContent: 'flex-start', alignItems: 'center' }, issueTitle: { color: 'white', fontWeight: 'bold' }, issueBody: { color: 'white', marginTop: 5 } };
src/containers/Asians/TabControls/PreliminaryRounds/CreateRooms/8_VenuePreview/index.js
westoncolemanl/tabbr-web
import React from 'react' import withStyles from 'material-ui/styles/withStyles' import Typography from 'material-ui/Typography' import VenueTable from './VenueTable' import Navigation from './Navigation' const styles = theme => ({ root: { [theme.breakpoints.down('sm')]: { paddingLeft: theme.spacing.unit, paddingRight: theme.spacing.unit }, [theme.breakpoints.between('sm', 'lg')]: { paddingLeft: theme.spacing.unit * 4, paddingRight: theme.spacing.unit * 4 }, [theme.breakpoints.up('lg')]: { paddingLeft: theme.spacing.unit * 8, paddingRight: theme.spacing.unit * 8 } } }) export default withStyles(styles)(({ round, roomsDraft, onChange, onBack, onNext, classes, minimumRelevantAdjudicatorPoint }) => <div className={classes.root} > <Typography variant={'display4'} > {'Adjust venues'} </Typography> <Typography variant={'display1'} gutterBottom > {'Drag and drop venues to move them around'} </Typography> <VenueTable round={round} roomsDraft={roomsDraft} onChange={onChange} minimumRelevantAdjudicatorPoint={minimumRelevantAdjudicatorPoint} /> <Navigation onBack={onBack} onNext={onNext} /> </div> )
app/index.js
Onra/inspiringquote
import React from 'react'; import ReactDOM from 'react-dom'; import Home from './components/Home'; import './styles/stylesheet.scss'; document.addEventListener('DOMContentLoaded', () => { ReactDOM.render(<Home />, document.getElementById('root')); });
src/scenes/home/landing/landing.js
sethbergman/operationcode_frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactModal from 'react-modal'; import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import { faTimes } from '@fortawesome/fontawesome-free-solid'; import Hero from './hero/hero'; import Membership from './membership/membership'; import MoreInformation from './moreInformation/moreInformation'; import SuccessStories from './successStories/successStories'; import Partners from './partners/partners'; import Donate from '../../../shared/components/donate/donate'; import Join from '../../../shared/components/join/join'; import EmailSignup from './emailSignup/emailSignup'; import styles from './landing.css'; class Landing extends Component { state = { showModal: false }; componentDidMount() { // Uncomment in order to render landing screen pop-up when desired // this.toggleModal(); } toggleModal = () => { this.setState({ showModal: !this.state.showModal }); }; render() { return ( <div className={styles.landing}> {/* Modal only rendered when this.toggleModal() is uncommented in componentDidMount() */} <ReactModal isOpen={this.state.showModal} onRequestClose={this.toggleModal} contentLabel="None" className={styles.landingModal} > <FontAwesomeIcon icon={faTimes} size="4x" className={styles.landingModal_CloseButton} onClick={this.toggleModal} /> <div className={styles.landingModal_Content}> <h3>Pop-up Title</h3> <p>Content</p> </div> </ReactModal> <Hero /> <Membership /> <MoreInformation /> <SuccessStories /> <Partners /> <Donate /> <Join /> <EmailSignup sendNotification={this.props.sendNotification} /> </div> ); } } Landing.propTypes = { sendNotification: PropTypes.func.isRequired }; export default Landing;
src/web/forms/__tests__/DynamicForm-test.js
asha-nepal/AshaFusionCross
/** * Copyright 2017 Yuichiro Tsuchiya * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-env jest */ jest.unmock('react-redux'); jest.unmock('immutable'); jest.unmock('react-dnd'); jest.unmock('react-dnd-html5-backend'); jest.unmock('../DynamicForm'); import React from 'react'; import { shallow } from 'enzyme'; import Immutable from 'immutable'; import { Form } from 'react-redux-form'; import { DynamicFormComponent } from '../DynamicForm'; describe('<DynamicFormComponent />', () => { it('shows submit button if onSubmit prop provided', () => { const onSubmit = jest.fn(); const wrapper = shallow( <DynamicFormComponent style={Immutable.List()} onSubmit={onSubmit} /> ); const submitButtons = wrapper.find('button[type="submit"]'); expect(submitButtons.length).toBe(1); const submitButton = submitButtons.at(0); expect(submitButton.parents(Form).length).toBe(1); }); it('hides submit button if onSubmit not provided', () => { const wrapper = shallow( <DynamicFormComponent style={Immutable.List()} /> ); expect(wrapper.find('button[type="submit"]').length).toBe(0); }); it('shows remove button if onRemove prop provided', () => { const onRemove = jest.fn(); const ev = { preventDefault: jest.fn() }; const wrapper = shallow( <DynamicFormComponent style={Immutable.List()} onRemove={onRemove} /> ); const removeButton = wrapper.find('a').last(); removeButton.simulate('click', ev); expect(onRemove).toBeCalled(); }); it('hides remove button if onRemove not provided', () => { const wrapper = shallow( <DynamicFormComponent style={Immutable.List()} /> ); expect(wrapper.find('a').length).toBe(0); }); });
src/svg-icons/file/cloud-upload.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCloudUpload = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/> </SvgIcon> ); FileCloudUpload = pure(FileCloudUpload); FileCloudUpload.displayName = 'FileCloudUpload'; FileCloudUpload.muiName = 'SvgIcon'; export default FileCloudUpload;
src/components/RecurrencePicker/RecurrencePicker.js
F-Ruxton/taskata
import React, { Component } from 'react'; // import moment from 'moment'; // import 'moment-recur'; // import { find, chunk, map, remove, isEmpty } from 'lodash'; import { find, chunk, map } from 'lodash'; import './RecurrencePicker.css'; import SimpleSelectWrapper from '../SimpleSelectWrapper/SimpleSelectWrapper'; import SingleDatePickerWrapper from '../SingleDatePickerWrapper/SingleDatePickerWrapper'; const RecurrenceTypeSelect = ({ name, value, handleChange, optionsType, placeholder }) => { const options = { shortLabelOptions: [ { value: 'day', label: 'Daily' }, { value: 'week', label: 'Weekly' }, { value: 'month', label: 'Monthly' }, ], longLabelOptions: [ // { value: 'none', label: 'None' }, { value: 'day', label: 'Every Day' }, { value: 'week', label: 'Every Week' }, { value: 'month', label: 'Every Month' }, { value: 'weekdays', label: 'Weekdays' }, { value: 'weekends', label: 'Weekends' }, { value: 'custom', label: 'Custom...' } ] }; return ( <SimpleSelectWrapper value={value} name={name} handleChange={handleChange} options={options[optionsType]} placeholder={placeholder || 'Every...'} clearable={false} /> ); } const PickerTable = ({name, options, values, numRows, handleUpdate}) => { let toCells = (value, key) => ( <td key={key} onClick={e => handleUpdate({ name, value })} style={{padding: 3, border: '1px solid #bfbfbf'}} className={!!find(values, v => v===value) ? 'picked' : '' } > { value } </td> ); let cells = map(options, toCells); let rows = chunk(cells, Math.ceil(cells.length / numRows)); return ( <div style={{ margin: 5 }}> <table style={{borderCollapse: 'collapse'}}> <tbody> {map(rows, (row, key) => <tr key={key}>{row}</tr>)} </tbody> </table> </div> ); } class CustomRecurrencePicker extends Component { render() { let dayOptions = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]; let weekOptions = ['0','1','2','3']; let monthDayOptions = [] for(let i=1 ; i<32; i++){ monthDayOptions.push(i.toString()) }; let monthOptions = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; let { customRecurrenceType, values, handleUpdate, handleUpdateValue } = this.props; let { recurrenceInterval, days, weeks, monthDays, months } = values; let recurrencePickerElement; switch(customRecurrenceType){ case 'day': recurrencePickerElement = ( <div style={{textAlign: 'left'}}> Every <input type="number" style={{marginLeft: 3, width: 34, height:20, fontSize: 16}} value={recurrenceInterval} min='1' name='recurrenceInterval' onChange={handleUpdateValue} /> day(s) </div> ); break; case 'week': recurrencePickerElement = ( <div> <div style={{ display: 'flex', alignItems: 'center', marginBottom: -4, paddingLeft: 3}}> <div> Weeks of each month: </div> <PickerTable handleUpdate={handleUpdateValue} name='weeks' values={weeks} options={weekOptions} numRows={1} /> </div> <PickerTable handleUpdate={handleUpdateValue} name='days' values={days} options={dayOptions} numRows={1} /> </div> ); break; case 'month': recurrencePickerElement = ( <div style={{display: 'flex'}}> <div> <PickerTable handleUpdate={handleUpdateValue} name='monthDays' values={monthDays} options={monthDayOptions} numRows={5} /> </div> <div> <PickerTable handleUpdate={handleUpdateValue} name='months' values={months} options={monthOptions} numRows={3} /> </div> </div> ); break; default: } return ( <div style={{marginBottom: -6}}> <div style={{display: 'flex'}}> <span style={{width: 100}}> <RecurrenceTypeSelect name='customRecurrenceType' value={customRecurrenceType} handleChange={handleUpdate} optionsType='shortLabelOptions' placeholder='Frequency...' /> </span> </div> <div style={{textAlign: 'left'}}> {recurrencePickerElement} </div> </div> ); } } class RecurrencePicker extends Component { render() { const { recurrence, recurrenceData, updateRecurrenceData, updateRecurrenceDataValue } = this.props; const { recurrenceType, customRecurrenceType, values } = recurrenceData; return ( <div style={{ padding: '15px 10px 8px 10px' }}> <div style={{display: 'flex'}}> <div style={{width: 125, marginRight: 5}}> <RecurrenceTypeSelect name='recurrenceType' value={recurrenceType} handleChange={updateRecurrenceData} optionsType='longLabelOptions' /> </div> <div> <SingleDatePickerWrapper monthFormat="MMM YY" isDayHighlighted={day => recurrence && recurrence.matches && recurrence.matches(day)} daySize={20} readOnly placeholder='Preview' hideKeyboardShortcutsPanel keepOpenOnDateSelect /> </div> </div> { recurrenceType === 'custom' ? <div style={{marginTop: 10}}> <CustomRecurrencePicker values={values} handleUpdate={updateRecurrenceData} handleUpdateValue={updateRecurrenceDataValue} customRecurrenceType={customRecurrenceType} /> </div> : <div style={{display: 'none'}}/> } </div> ); } } export default RecurrencePicker;
src/components/Last/Last.stories.js
joshwcomeau/react-collection-helpers
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import Last from '../Last'; import Sort from '../Sort'; storiesOf('Last', module) .add('default (1 item)', () => ( <Last collection={['Apple', 'Banana', 'Carrot']}> {item => <div>{item}</div>} </Last> )) .add('last 3 of 4 items', () => ( <Last collection={['Apple', 'Banana', 'Carrot', 'Dragonfruit']} num={3}> {item => <div>{item}</div>} </Last> )) .add('composed with Sort', () => { const collection = [ { id: 'a', name: 'Apple', price: 5 }, { id: 'b', name: 'Banana', price: 10.25 }, { id: 'c', name: 'Carrot', price: 4.50 }, { id: 'd', name: 'Dragonfruit', price: 7.50 }, { id: 'e', name: 'Eggplant', price: 12.75 }, ]; return ( <Sort collection={collection} comparator="price"> <Last num={2}> {item => <div>{item.name} - {item.price}</div>} </Last> </Sort> ); });
src/components/projectManageIndex/projectManageIndex.js
wengyian/project-manager-system
/** * Created by 51212 on 2017/4/10. */ import React, { Component } from 'react'; import {BrowserRouter as Router, Route, browserHistory, Switch} from 'react-router-dom'; import Header from '../Header/Header'; //import ProjectManage from '../projectManage/projectManage'; //import TextTable from '../textTable/textTable'; import { Icon, Tabs } from 'antd'; import ProjectManageFirstView from '../projectManageFirstView/projectManageFirstView'; import ProjectInfo from '../projectInfo/projectInfo'; require('./projectManageIndex.scss'); const TabPane = Tabs.TabPane; const TabExtraContent = <div className="project-tabExtraContent"><span className="search"><Icon type="search" />查询</span><span className="add"><Icon type="plus" />新增</span></div>; class ProjectManageIndex extends Component{ constructor(props){ super(props); } render(){ return ( <div> <Header {...this.props}></Header> <Tabs type="card" className="project-tabs" tabBarExtraContent={TabExtraContent}> <TabPane tab="项目管理" key="project-manage"> <Router> <div> <Route exact path="/projectManageIndex" component={ProjectManageFirstView}></Route> <Route path="/projectManageIndex/projectInfo" component={ProjectInfo}></Route> </div> </Router> </TabPane> <TabPane tab="员工管理" key="employee-manage">2</TabPane> <TabPane tab="设置" key="settings">3</TabPane> </Tabs> </div> ) } } export default ProjectManageIndex;
src/parser/warrior/fury/modules/spells/Recklessness.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import SPELLS from 'common/SPELLS'; import RESOURCE_TYPES from 'game/RESOURCE_TYPES'; import { SELECTED_PLAYER } from 'parser/core/EventFilter'; import StatisticBox from 'interface/others/StatisticBox'; import { formatPercentage, formatThousands } from 'common/format'; import SpellIcon from 'common/SpellIcon'; class Recklessness extends Analyzer { reckRageGen = 0; totalRageGen = 0; reckDamage = 0; constructor(...args) { super(...args); this.addEventListener(Events.energize.by(SELECTED_PLAYER).to(SELECTED_PLAYER), this.onPlayerEnergize); this.addEventListener(Events.damage.by(SELECTED_PLAYER), this.onPlayerDamage); } onPlayerEnergize(event) { const resource = event.classResources && event.classResources.find(classResources => classResources.type === RESOURCE_TYPES.RAGE.id); if (!resource) return; if (this.selectedCombatant.hasBuff(SPELLS.RECKLESSNESS.id)) { this.reckRageGen += event.resourceChange / 2; } this.totalRageGen += event.resourceChange; } onPlayerDamage(event) { if (this.selectedCombatant.hasBuff(SPELLS.RECKLESSNESS.id)) { this.reckDamage += event.amount; } } get ratioReckRageGen() { return this.reckRageGen / this.totalRageGen; } get reckDPS() { return this.owner.getPercentageOfTotalDamageDone(this.reckDamage); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.RECKLESSNESS.id} />} label="Recklessness" value={`${this.reckRageGen} extra rage generated`} tooltip={<><strong>{formatPercentage(this.ratioReckRageGen)}%</strong> of your rage and <strong>{formatPercentage(this.reckDPS)}% ({formatThousands(this.reckDamage)}) </strong> of your damage was generated during Recklessness.</>} /> ); } } export default Recklessness;
src/js/components/settings/Global.js
barumel/ultritium-radio-player
import React from 'react'; import { Panel } from 'react-bootstrap'; import { SettingsPanel } from './panel/Panel'; import { SettingsPanelHeader } from './panel/Header'; import { SettingsFormGlobal } from './form/Global'; export class GlobalSettings extends SettingsPanel { constructor() { super(); this.state = { collapsed: true, locked: true, title: 'Global Settings' }; } render() { const header = (<SettingsPanelHeader title={this.state.title} locked={this.state.locked} lock={this.lock.bind(this)} toggle={this.toggle.bind(this)}> </SettingsPanelHeader> ); return( <Panel header={header} collapsible={true} expanded={!this.state.collapsed}> <SettingsFormGlobal locked={this.state.locked}></SettingsFormGlobal> </Panel> ); } }
docs/app/Examples/elements/List/Variations/ListExampleCelled.js
mohammed88/Semantic-UI-React
import React from 'react' import { Image, List } from 'semantic-ui-react' const ListExampleCelled = () => ( <List celled> <List.Item> <Image avatar src='http://semantic-ui.com/images/avatar/small/helen.jpg' /> <List.Content> <List.Header>Snickerdoodle</List.Header> An excellent companion </List.Content> </List.Item> <List.Item> <Image avatar src='http://semantic-ui.com/images/avatar/small/daniel.jpg' /> <List.Content> <List.Header>Poodle</List.Header> A poodle, its pretty basic </List.Content> </List.Item> <List.Item> <Image avatar src='http://semantic-ui.com/images/avatar/small/daniel.jpg' /> <List.Content> <List.Header>Paulo</List.Header> He's also a dog </List.Content> </List.Item> </List> ) export default ListExampleCelled
packages/icons/src/md/av/LibraryAdd.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdLibraryAdd(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M8 12H4v28c0 2.21 1.79 4 4 4h28v-4H8V12zm32-8c2.21 0 4 1.79 4 4v24c0 2.21-1.79 4-4 4H16c-2.21 0-4-1.79-4-4V8c0-2.21 1.79-4 4-4h24zm-2 18v-4h-8v-8h-4v8h-8v4h8v8h4v-8h8z" /> </IconBase> ); } export default MdLibraryAdd;
src/Container.js
thebritican/react-router-relay
import React from 'react'; import StaticContainer from 'react-static-container'; import getParamsForRoute from './getParamsForRoute'; import RootComponent from './RootComponent'; import RouteAggregator from './RouteAggregator'; export default class Container extends React.Component { static displayName = 'ReactRouterRelay.Container'; static propTypes = { Component: React.PropTypes.func.isRequired, }; static contextTypes = { routeAggregator: React.PropTypes.instanceOf(RouteAggregator), }; render() { const {routeAggregator} = this.context; if (!routeAggregator) { return <RootComponent {...this.props} />; } const {Component, ...routerProps} = this.props; const {route} = routerProps; const {queries} = route; if (!queries) { return <Component {...routerProps} />; } const params = getParamsForRoute(routerProps); const {fragmentPointers, failure} = routeAggregator.getData(route, queries, params); let shouldUpdate = true; let element; // This is largely copied from RelayRootContainer#render. if (failure) { const {renderFailure} = route; if (renderFailure) { const [error, retry] = failure; element = renderFailure(error, retry); } else { element = null; } } else if (fragmentPointers) { const data = {...routerProps, ...params, ...fragmentPointers}; const {renderFetched} = route; if (renderFetched) { element = renderFetched(data); } else { element = <Component {...data} />; } } else { const {renderLoading} = route; if (renderLoading) { element = renderLoading(); } else { element = undefined; } if (element === undefined) { element = null; shouldUpdate = false; } } return ( <StaticContainer shouldUpdate={shouldUpdate}> {element} </StaticContainer> ); } }
frontend/src/common/InputEmail.js
Ormabe/tuesday
import React from 'react'; import TextField from 'material-ui/TextField'; import { green800, grey800, orange800 } from 'material-ui/styles/colors'; const InputEmail = ({ name, label, value, onChange, errorText }) => { const { floatingLabelFocusStyle, floatingLabelStyle, underlineStyle, errorStyle } = styles; return( <TextField name={name} type="email" value={value} onChange={onChange} errorText={errorText} errorStyle={errorStyle} floatingLabelText={label} underlineStyle={underlineStyle} floatingLabelStyle={floatingLabelStyle} floatingLabelFocusStyle={floatingLabelFocusStyle} /> ); }; const styles = { underlineStyle: { borderColor: grey800, }, floatingLabelStyle: { color: grey800, }, floatingLabelFocusStyle: { color: green800, }, errorStyle: { color: orange800 } }; export { InputEmail };
app/javascript/mastodon/main.js
riku6460/chikuwagoddon
import * as registerPushNotifications from './actions/push_notifications'; import { default as Mastodon, store } from './containers/mastodon'; import React from 'react'; import ReactDOM from 'react-dom'; import ready from './ready'; const perf = require('./performance'); function main() { perf.start('main()'); if (window.history && history.replaceState) { const { pathname, search, hash } = window.location; const path = pathname + search + hash; if (!(/^\/web[$/]/).test(path)) { history.replaceState(null, document.title, `/web${path}`); } } ready(() => { const mountNode = document.getElementById('mastodon'); const props = JSON.parse(mountNode.getAttribute('data-props')); ReactDOM.render(<Mastodon {...props} />, mountNode); if (process.env.NODE_ENV === 'production') { // avoid offline in dev mode because it's harder to debug require('offline-plugin/runtime').install(); store.dispatch(registerPushNotifications.register()); } perf.stop('main()'); }); } export default main;
docs/pages/api-docs/breadcrumbs.js
lgollut/material-ui
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'api/breadcrumbs'; const requireRaw = require.context('!raw-loader!./', false, /\/breadcrumbs\.md$/); export default function Page({ docs }) { return <MarkdownDocs docs={docs} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
resources/assets/js/components/admin/LateralMenu.js
jrm2k6/i-heart-reading
import React, { Component } from 'react'; import { browserHistory } from 'react-router'; export default class LateralMenu extends Component { constructor(props) { super(props); this.state = { activeTab: null, randomBackgroundColor: this.getRandomColor() }; } getRandomColor() { return `rgb(${this.getRandomInt(1, 256)}, ${this.getRandomInt(1, 256)}, ${this.getRandomInt(1, 256)})`; } getClassnameItem(name) { let className = 'menu-item'; if (this.state.activeTab === name) { className += ' active'; } return className; } handleClickMenu(tabName) { switch (tabName) { case 'home': browserHistory.push('/admin'); break; case 'dashboard': window.location.replace('/app'); break; case 'logout': window.location.replace('/logout'); break; default: browserHistory.push('/admin'); break; } this.setState({ activeTab: tabName }); } getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } render() { const { user } = this.props; let name = null; let role = null; let firstLetter = null; if (user) { name = user.name; role = user.role.charAt(0).toUpperCase() + user.role.slice(1); firstLetter = user.name.charAt(0); } return ( <div className='ihr-lateral-menu'> <div className='logo-container'> <img src='/images/logos/i-heart-reading-logo.png' /> </div> <div className='profile-container'> <div className='profile-avatar'> <div className='profile' style={{ backgroundColor: this.state.randomBackgroundColor }}> {firstLetter} </div> </div> <div className='profile-short-description'> <span className='profile-name'>{name}</span> <span className='profile-title'>{role}</span> </div> </div> <div className='menu-container' > <div className={this.getClassnameItem('home')} onClick={() => { this.handleClickMenu('home');}} > <i className='material-icons'>home</i><span>Home</span> </div> <div className={this.getClassnameItem('dashboard')} onClick={() => { this.handleClickMenu('dashboard');}} > <i className='material-icons'>dashboard</i><span>Dashboard</span> </div> <div className={this.getClassnameItem('logout')} onClick={() => { this.handleClickMenu('logout');}} > <i className='material-icons'>exit_to_app</i><span>Log Out</span> </div> <div className='separator-container'> <hr className='separator' /> </div> </div> </div> ); } }
src/components/Calendar/Calendar.js
nambawan/g-old
import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/withStyles'; import { defineMessages } from 'react-intl'; import InfiniteCalendar, { withRange, Calendar as CalendarWithRange, } from 'react-infinite-calendar'; import s from './Calendar.css'; /* eslint-disable */ const messages = defineMessages({ blank: { id: 'calendar.blank', defaultMessage: 'No date set', description: 'Blank calendar', }, todayShort: { id: 'calendar.today.short', defaultMessage: 'Today', description: 'Today', }, todayLong: { id: 'calendar.today.long', defaultMessage: 'Today', description: 'Today', }, }); const months = { 'de-DE': 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split( '_', ), 'it-IT': 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split( '_', ), }; const monthsShort = { 'de-DE': 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), 'it-IT': 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'), }; const weekdaysShort = { 'de-DE:': 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), 'it-IT': 'dom_lun_mar_mer_gio_ven_sab'.split('_'), }; const weekdays = { 'de-DE': 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), 'it-IT': 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'), }; const format = { 'de-DE': 'dddd,MM.YYYY', 'it-IT': 'D MMMM YYYY', }; class Calendar extends React.Component { static propTypes = { lang: PropTypes.string.isRequired, intl: PropTypes.shape({ 'calendar.blank': PropTypes.string, }).isRequired, }; static locales = { 'de-DE': require('date-fns/locale/de'), 'it-IT': require('date-fns/locale/it'), }; render() { throw Error('Not finished'); const today = new Date(); const lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7); const { lang, intl } = this.props; const localizedWeekdays = weekdaysShort[this.props.lang]; return ( <InfiniteCalendar Component={withRange(CalendarWithRange)} theme={{ selectionColor: 'rgb(146, 118, 255)', textColor: { default: '#333', active: '#FFF', }, weekdayColor: 'rgb(146, 118, 255)', headerColor: 'rgb(127, 95, 251)', floatingNav: { background: 'rgba(81, 67, 138, 0.96)', color: '#FFF', chevron: '#FFA726', }, }} onSelect={function(date) { console.log(`You selected: ${JSON.stringify(date)}`); }} width={380} height={400} selected={new Date()} locale={{ locale: Calendar.locales[this.props.lang], headerFormat: 'dddd, D MMM', weekdays: localizedWeekdays, blank: 'Nothing selected', todayLabel: { long: 'Today', short: 'Today', }, }} /> ); } } /* eslint-enable */ export default withStyles(s)(Calendar);
src/components/Feedback/Feedback.js
vbauerster/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import styles from './Feedback.less'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
test/MenuItemSpec.js
victorzhang17/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import MenuItem from '../src/MenuItem'; import { shouldWarn } from './helpers'; describe('MenuItem', () => { it('renders divider', () => { const instance = ReactTestUtils.renderIntoDocument(<MenuItem divider />); const node = React.findDOMNode(instance); node.className.should.match(/\bdivider\b/); node.getAttribute('role').should.equal('separator'); }); it('renders divider not children', () => { const instance = ReactTestUtils.renderIntoDocument( <MenuItem divider> Some child </MenuItem> ); const node = React.findDOMNode(instance); node.className.should.match(/\bdivider\b/); node.innerHTML.should.not.match(/Some child/); shouldWarn('Children will not be rendered for dividers'); }); it('renders header', () => { const instance = ReactTestUtils.renderIntoDocument(<MenuItem header>Header Text</MenuItem>); const node = React.findDOMNode(instance); node.className.should.match(/\bdropdown-header\b/); node.getAttribute('role').should.equal('heading'); node.innerHTML.should.match(/Header Text/); }); it('renders menu item link', (done) => { const instance = ReactTestUtils.renderIntoDocument( <MenuItem onKeyDown={() => done()} href='/herpa-derpa'> Item </MenuItem> ); const node = React.findDOMNode(instance); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A').getDOMNode(); node.getAttribute('role').should.equal('presentation'); anchor.getAttribute('role').should.equal('menuitem'); anchor.getAttribute('tabIndex').should.equal('-1'); anchor.getAttribute('href').should.equal('/herpa-derpa'); anchor.innerHTML.should.match(/Item/); ReactTestUtils.Simulate.keyDown(anchor, { keyCode: 1 }); }); it('click handling with onSelect prop', () => { const handleSelect = (event, eventKey) => { eventKey.should.equal('1'); }; const instance = ReactTestUtils.renderIntoDocument( <MenuItem onSelect={handleSelect} eventKey='1'>Item</MenuItem> ); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); ReactTestUtils.Simulate.click(anchor); }); it('click handling with onSelect prop (no eventKey)', () => { const handleSelect = (event, eventKey) => { expect(eventKey).to.be.undefined; }; const instance = ReactTestUtils.renderIntoDocument( <MenuItem onSelect={handleSelect}>Item</MenuItem> ); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); ReactTestUtils.Simulate.click(anchor); }); it('does not fire onSelect when divider is clicked', () => { const handleSelect = () => { throw new Error('Should not invoke onSelect with divider flag applied'); }; const instance = ReactTestUtils.renderIntoDocument( <MenuItem onSelect={handleSelect} divider /> ); ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A').length.should.equal(0); const li = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'li'); ReactTestUtils.Simulate.click(li); }); it('does not fire onSelect when header is clicked', () => { const handleSelect = () => { throw new Error('Should not invoke onSelect with divider flag applied'); }; const instance = ReactTestUtils.renderIntoDocument( <MenuItem onSelect={handleSelect} header>Header content</MenuItem> ); ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A').length.should.equal(0); const li = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'li'); ReactTestUtils.Simulate.click(li); }); it('disabled link', () => { const handleSelect = () => { throw new Error('Should not invoke onSelect event'); }; const instance = ReactTestUtils.renderIntoDocument( <MenuItem onSelect={handleSelect} disabled>Text</MenuItem> ); const node = React.findDOMNode(instance); const anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'A'); node.className.should.match(/\bdisabled\b/); ReactTestUtils.Simulate.click(anchor); }); it('should pass through props', () => { let instance = ReactTestUtils.renderIntoDocument( <MenuItem className="test-class" href="#hi-mom!" title="hi mom!" > Title </MenuItem> ); let node = React.findDOMNode(instance); assert(node.className.match(/\btest-class\b/)); assert.equal(node.getAttribute('href'), null); assert.equal(node.getAttribute('title'), null); let anchorNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a')); assert.notOk(anchorNode.className.match(/\btest-class\b/)); assert.equal(anchorNode.getAttribute('href'), '#hi-mom!'); assert.equal(anchorNode.getAttribute('title'), 'hi mom!'); }); it('Should set target attribute on anchor', () => { let instance = ReactTestUtils.renderIntoDocument( <MenuItem target="_blank"> Title </MenuItem> ); let anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'); assert.equal(React.findDOMNode(anchor).getAttribute('target'), '_blank'); }); it('should output an li', () => { let instance = ReactTestUtils.renderIntoDocument( <MenuItem> Title </MenuItem> ); assert.equal(React.findDOMNode(instance).nodeName, 'LI'); assert.equal(React.findDOMNode(instance).getAttribute('role'), 'presentation'); }); });
src/view/UIElement/iconfont/index.js
fishmankkk/mircowater2.0
import React from 'react' import { Iconfont } from 'components' import { Table, Row, Col, Icon } from 'antd' import styles from './index.less' import './emoji' const colorfulIcons = ['boluo', 'baixiangguo', 'chengzi', 'boluomei', 'caomei', 'dayouzi', 'chelizi', 'fanqie', 'hamigua', 'ganlan', 'juzi', 'heimei', 'huolongguo', 'hongmei', 'lizi', 'lanmei', 'mangguo', 'mihoutao', 'longyan', 'mugua', 'lizi1', 'ningmeng'] const flatIcons = ['home', 'user', 'timelimit', 'shopcart', 'message', 'remind', 'service', 'shop', 'sweep', 'express', 'payment', 'search', 'feedback', 'pencil', 'setting', 'refund', 'delete', 'star', 'heart', 'share', 'location', 'console'] const localSVGIcons = ['vomiting', 'smirking', 'surprised', 'unamused', 'zombie', 'tired', 'tongue', 'wink'] const localRequireSVGIcons = [ require('../../../svg/cute/congratulations.svg'), require('../../../svg/cute/cry.svg'), require('../../../svg/cute/kiss.svg'), require('../../../svg/cute/leisurely.svg'), require('../../../svg/cute/notice.svg'), require('../../../svg/cute/proud.svg'), require('../../../svg/cute/shy.svg'), require('../../../svg/cute/sweat.svg'), require('../../../svg/cute/think.svg'), ] const IcoPage = () => (<div className="content-inner"> <Icon type="star-oo" /> <h2 style={{ margin: '16px 0' }}>Colorful Icon</h2> <ul className={styles.list}> {colorfulIcons.map(item => (<li key={item}> <Iconfont className={styles.icon} colorful type={item} /> <span className={styles.name}>{item}</span> </li>))} </ul> <h2 style={{ margin: '16px 0' }}>Flat Icon</h2> <ul className={styles.list}> {flatIcons.map(item => (<li key={item}> <Iconfont className={styles.icon} type={item} /> <span className={styles.name}>{item}</span> </li>))} </ul> <h2 style={{ margin: '16px 0' }}>Local SVG</h2> <ul className={styles.list}> {localSVGIcons.map(item => (<li key={item}> <Iconfont className={styles.icon} colorful type={item} /> <span className={styles.name}>{item}</span> </li>))} </ul> <h2 style={{ margin: '16px 0' }}>Local Require SVG</h2> <ul className={styles.list}> {localRequireSVGIcons.map(item => (<li key={item.default.id}> <Iconfont className={styles.icon} colorful type={item.default.id} /> <span className={styles.name}>{item.default.id}</span> </li>))} </ul> <h2 style={{ margin: '16px 0' }}>API</h2> <Row> <Col lg={18} md={24}> <Table rowKey={(record, key) => key} pagination={false} bordered scroll={{ x: 800 }} columns={[ { title: 'Property', dataIndex: 'props', }, { title: 'Description', dataIndex: 'desciption', }, { title: 'Type', dataIndex: 'type', }, { title: 'Default', dataIndex: 'default', }, ]} dataSource={[ { props: 'type', desciption: 'icon type', type: 'String', default: '-', }, { props: 'colorful', desciption: "to set the SVG has 'symbol element'", type: 'Bool', default: 'false', }]} /> </Col> </Row> <h2 style={{ margin: '16px 0' }}>Thanks</h2> <div style={{ margin: '16px 0', lineHeight: 2 }}> <p> <a href="http://www.iconfont.cn/user/detail?uid=116813">何阿酥</a> colorful fruit icon <a href="http://www.iconfont.cn/collections/detail?cid=4014" target="_blank" rel="noopener noreferrer"> http://www.iconfont.cn/collections/detail?cid=4014</a> </p> <p> <a href="http://www.iconfont.cn/user/detail?uid=496384">ColinXu</a> colorful &apos;tsundere&apos; emoji icon <a href="http://www.iconfont.cn/collections/detail?cid=4116" target="_blank" rel="noopener noreferrer"> http://www.iconfont.cn/collections/detail?cid=4116</a> </p> <p> <a href="http://www.iconfont.cn/user/detail?uid=116813">咕噜小莫莫</a> colorful &apos;face cute&apos; emoji icon <a href="http://www.iconfont.cn/collections/detail?cid=4268" target="_blank" rel="noopener noreferrer"> http://www.iconfont.cn/collections/detail?cid=4268</a> </p> </div> </div>) export default IcoPage