path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/components/Home/Home.spec.js
lucaslencinas/react-node-template
import React from 'react'; import { shallow } from 'enzyme'; import Home from './Home'; describe('Home', () => { let games; let home; let selectedGame; let onSelectGame; let onDeleteGame; let onEditGame; let onCreateGame; let onEnterCreateMode; let onLeaveCreateMode; let onEnterEditMode; let onLeaveEditMode; beforeEach(() => { onDeleteGame = sandbox.spy(); onSelectGame = sandbox.spy(); onEditGame = sandbox.spy(); onCreateGame = sandbox.spy(); onEnterCreateMode = sandbox.spy(); onLeaveCreateMode = sandbox.spy(); onEnterEditMode = sandbox.spy(); onLeaveEditMode = sandbox.spy(); games = [ { name: 'someGame', slug: 'somegame', description: 'some description', link: 'someGame.html', types: ['singlePlayer', 'multiPlayer'], teamSizes: [1, 2, 4] }, { name: 'otherGame', slug: 'othergame', description: 'other description', link: 'otherGame.html', types: ['multiPlayer'], teamSizes: [1, 2, 4] } ]; selectedGame = games[1]; }); context('when the user is not editing or creating a game', () => { beforeEach(() => { home = shallow( <Home games={games} selectedGame={selectedGame} onDeleteGame={onDeleteGame} onSelectGame={onSelectGame} onEditGame={onEditGame} onCreateGame={onCreateGame} onEnterCreateMode={onEnterCreateMode} onLeaveCreateMode={onLeaveCreateMode} onEnterEditMode={onEnterEditMode} onLeaveEditMode={onLeaveEditMode} isCreating={false} isEditing={false} /> ); }); it('renders the title', () => { home.find('h1').text().should.eql('React Node Template'); }); it('renders the GamesList component with the correct params', () => { const gamesList = home.find('GamesList'); gamesList.prop('games').should.eql(games); gamesList.prop('onSelectGame').should.eql(onSelectGame); gamesList.prop('selectedGame').should.eql(selectedGame); gamesList.prop('onDeleteGame').should.eql(onDeleteGame); gamesList.prop('onOpenCreateGameForm').should.eql(onEnterCreateMode); gamesList.prop('isFormOpen').should.eql(false); }); it('renders the GameDescription component with the correct params', () => { const gameDescription = home.find('GameDescription'); gameDescription.prop('game').should.eql(selectedGame); gameDescription.prop('onOpenEditGameForm').should.eql(onEnterEditMode); }); it('does not render the GameForm', () => { home.find('GamesForm').exists().should.eql(false); }); }); context('when the user is editing a game', () => { beforeEach(() => { home = shallow( <Home games={games} onDeleteGame={onDeleteGame} selectedGame={selectedGame} onSelectGame={onSelectGame} onEditGame={onEditGame} onCreateGame={onCreateGame} onEnterCreateMode={onEnterCreateMode} onLeaveCreateMode={onLeaveCreateMode} onEnterEditMode={onEnterEditMode} onLeaveEditMode={onLeaveEditMode} isEditing /> ); }); it('renders the GamesList component with isFormOpen prop in true', () => { const gamesList = home.find('GamesList'); gamesList.prop('isFormOpen').should.eql(true); }); it('does not render the GameDescription component', () => { home.find('GamesDescription').exists().should.eql(false); }); it('does not render the GameForm with the correct params', () => { const gameForm = home.find('GameForm'); gameForm.prop('game').should.eql(selectedGame); gameForm.prop('actionName').should.eql('Edit'); gameForm.prop('onSubmit').should.eql(onEditGame); gameForm.prop('onCancel').should.eql(onLeaveEditMode); }); }); context('when the user is creating a game', () => { beforeEach(() => { home = shallow( <Home games={games} onDeleteGame={onDeleteGame} onSelectGame={onSelectGame} onEditGame={onEditGame} onCreateGame={onCreateGame} onEnterCreateMode={onEnterCreateMode} onLeaveCreateMode={onLeaveCreateMode} onEnterEditMode={onEnterEditMode} onLeaveEditMode={onLeaveEditMode} isCreating /> ); }); it('renders the GamesList component with isFormOpen prop in true', () => { const gamesList = home.find('GamesList'); gamesList.prop('isFormOpen').should.eql(true); }); it('does not render the GameDescription component', () => { home.find('GamesDescription').exists().should.eql(false); }); it('renders the GameForm with the correct params', () => { const gameForm = home.find('GameForm'); gameForm.prop('actionName').should.eql('Create'); gameForm.prop('onSubmit').should.eql(onCreateGame); gameForm.prop('onCancel').should.eql(onLeaveCreateMode); }); }); });
app/javascript/src/client/sessions/destroy.js
rringler/billtalk
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { destroySession } from './actions'; class SessionDestroy extends Component { componentWillMount() { this.props.destroySession(); this.props.history.push('/'); } render() { return <div></div>; } } export default connect(null, { destroySession })(SessionDestroy);
node_modules/react-bootstrap/es/NavbarBrand.js
C0deSamurai/muzjiks
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 { prefix } from './utils/bootstrapUtils'; var contextTypes = { $bs_navbar: React.PropTypes.shape({ bsClass: React.PropTypes.string }) }; var NavbarBrand = function (_React$Component) { _inherits(NavbarBrand, _React$Component); function NavbarBrand() { _classCallCheck(this, NavbarBrand); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } NavbarBrand.prototype.render = function render() { var _props = this.props, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['className', 'children']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var bsClassName = prefix(navbarProps, 'brand'); if (React.isValidElement(children)) { return React.cloneElement(children, { className: classNames(children.props.className, className, bsClassName) }); } return React.createElement( 'span', _extends({}, props, { className: classNames(className, bsClassName) }), children ); }; return NavbarBrand; }(React.Component); NavbarBrand.contextTypes = contextTypes; export default NavbarBrand;
demo/src/mockups/calculator/interfaces/calculator-interface.js
tuantle/hypertoxin
'use strict'; // eslint-disable-line import { Hf } from 'hyperflow'; import { Ht } from 'hypertoxin'; import React from 'react'; import ReactNative from 'react-native'; // eslint-disable-line import EVENT from '../events/calculator-event'; const KEYPADLABELS = [ [ `C`, `7`, `4`, `1`, `0` ], [ `±`, `8`, `5`, `2` ], [ `Pi`, `9`, `6`, `3`, `.` ], [ `÷`, `×`, `-`, `+`, `=` ] ]; const { BodyScreen, HeaderScreen, RowLayout, ColumnLayout, FlatButton, IconImage, HeadlineText, SubtitleText, CaptionText } = Ht; const CalculatorInterface = Hf.Interface.augment({ composites: [ Hf.React.ComponentComposite ], setup (done) { done(); }, render () { const component = this; const { navigation, screenProps } = component.props; const { Theme, shade } = screenProps.component.state; const { displayResult, displayComputes } = component.state; return ([ <HeaderScreen key = 'header-screen' shade = { shade } label = 'CALCULATOR APP' > <FlatButton room = 'content-left' overlay = 'transparent' corner = 'circular' onPress = {() => { component.outgoing(EVENT.ON.RESET).emit(); navigation.navigate(`mockupAppsHome`); }} > <IconImage room = 'content-middle' size = 'large' source = 'go-back' /> </FlatButton> </HeaderScreen>, <BodyScreen key = 'body-screen' shade = { shade } contentTopRoomAlignment = 'stretch' coverImageSource = { shade === `light` ? require(`../../../../assets/images/light-background-with-logo.png`) : require(`../../../../assets/images/dark-background-with-logo.png`) } > <ColumnLayout room = 'content-top' overlay = 'transparent-outline' roomAlignment = 'end' color = 'accent' corner = 'circular' margin = {{ top: 150, horizontal: 20, right: 10 }} > <HeadlineText room = 'content-right' size = 'large' indentation = { -10 } color = { Theme.color.palette.white }>{ displayResult }</HeadlineText> </ColumnLayout> <RowLayout room = 'content-middle' roomAlignment = 'stretch' margin = {{ horizontal: 20 }} > <RowLayout room = 'content-top' overlay = 'transparent' roomAlignment = 'end' margin = {{ bottom: 30 }} > <SubtitleText room = 'content-middle' size = 'small' color = { Theme.color.palette.grey }>{ `${displayComputes}` }</SubtitleText> <CaptionText room = 'content-middle' > Version: 0.6 </CaptionText> </RowLayout> <ColumnLayout room = 'content-middle' overlay = 'transparent' roomAlignment = 'start' margin = {{ horizontal: 40, bottom: 30 }} > { KEYPADLABELS.map((cellLabels, col) => { return ( <RowLayout key = { col } room = 'content-middle' overlay = 'transparent' roomAlignment = 'center' margin = {{ horizontal: 10 }} > { cellLabels.map((cellLabel, row) => { return ( <FlatButton room = 'content-middle' key = { cellLabel } label = { cellLabel } size = 'large' corner = 'round' overlay = 'opaque' color = {(() => { if (row === 0 && col < 3) { return `secondary`; } else if (col === 3) { return `accent`; } return `primary`; })()} onPress = {() => { if (cellLabel === `C`) { component.outgoing(EVENT.ON.RESET).emit(); } else if (cellLabel === `÷` || cellLabel === `×` || cellLabel === `+` || cellLabel === `-`) { component.outgoing(EVENT.ON.OPERATION).emit(() => cellLabel); } else if (Hf.isNumeric(cellLabel) || cellLabel === `.` || cellLabel === `Pi` || cellLabel === `±`) { component.outgoing(EVENT.ON.OPERAND).emit(() => cellLabel); } else if (cellLabel === `=`) { component.outgoing(EVENT.ON.COMPUTE).emit(); } }} /> ); }) } </RowLayout> ); }) } </ColumnLayout> </RowLayout> </BodyScreen> ]); } }); export default CalculatorInterface;
src/SvgIcon/SvgIcon.spec.js
ngbrown/material-ui
/* eslint-env mocha */ import React from 'react'; import sinon from 'sinon'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import SvgIcon from './SvgIcon'; import getMuiTheme from '../styles/getMuiTheme'; describe('<SvgIcon />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node) => shallow(node, {context: {muiTheme}}); const path = <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />; it('renders children by default', () => { const wrapper = shallowWithContext( <SvgIcon>{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); }); it('renders children and color', () => { const wrapper = shallowWithContext( <SvgIcon color="red">{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); assert.equal(wrapper.node.props.style.fill, 'red', 'should have color set to red'); }); it('renders children and hoverColor when mouseEnter', () => { const onMouseEnter = sinon.spy(); const wrapper = shallowWithContext( <SvgIcon className="material-icons" color="red" hoverColor="green" onMouseEnter={onMouseEnter} > {path} </SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); assert.equal(wrapper.node.props.style.fill, 'red', 'should have color set to red'); wrapper.simulate('mouseEnter'); assert.equal(wrapper.node.props.style.fill, 'green', 'should have color set to green after hover'); assert.equal(onMouseEnter.calledOnce, true, 'should have called onMouseEnter callback function'); }); it('renders children and call onMouseEnter callback', () => { const onMouseEnter = sinon.spy(); const wrapper = shallowWithContext( <SvgIcon onMouseEnter={onMouseEnter} hoverColor="green">{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseEnter'); assert.equal(onMouseEnter.calledOnce, true, 'should have called onMouseEnter callback function'); }); it('renders children and call onMouseEnter callback even when hoverColor is not set', () => { const onMouseEnter = sinon.spy(); const wrapper = shallowWithContext( <SvgIcon onMouseEnter={onMouseEnter}>{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseEnter'); assert.equal(onMouseEnter.calledOnce, true, 'should have called onMouseEnter callback function'); }); it('renders children and call onMouseLeave callback', () => { const onMouseLeave = sinon.spy(); const wrapper = shallowWithContext( <SvgIcon onMouseLeave={onMouseLeave} hoverColor="green">{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseLeave'); assert.equal(onMouseLeave.calledOnce, true, 'should have called onMouseLeave callback function'); }); it('renders children and call onMouseLeave callback even when hoverColor is not set', () => { const onMouseLeave = sinon.spy(); const wrapper = shallowWithContext( <SvgIcon onMouseLeave={onMouseLeave}>{path}</SvgIcon> ); assert.ok(wrapper.contains(path), 'should contain the children'); wrapper.simulate('mouseLeave'); assert.equal(onMouseLeave.calledOnce, true, 'should have called onMouseLeave callback function'); }); it('renders children and overwrite styles', () => { const style = { backgroundColor: 'red', }; const wrapper = shallowWithContext( <SvgIcon style={style}>{path}</SvgIcon> ); assert.equal(wrapper.get(0).props.style.backgroundColor, style.backgroundColor, 'should have backgroundColor to red'); }); });
modules/dqt/jsx/react.notice.js
aces/Loris
import React from 'react'; const NoticeMessage = (props) => { let alert; // Display load alert if alert is present if (props.alertLoaded) { alert = ( <div className='alert alert-success' role='alert'> <button type='button' className='close' aria-label='Close' onClick={props.dismissAlert}> <span aria-hidden='true'>&times;</span> </button> <strong>Success</strong> Query Loaded. </div> ); } // Display save alert if alert is present if (props.alertSaved) { alert = ( <div className='alert alert-success' role='alert'> <button type='button' className='close' aria-label='Close' onClick={props.dismissAlert}> <span aria-hidden='true'>&times;</span> </button> <strong>Success</strong> Query Saved. </div> ); } // Display Conflict Query alert if (props.alertConflict.show) { alert = ( <div className='alert alert-warning' role='alert'> <button type='button' className='close' aria-label='Close' onClick={props.dismissAlert}> <span aria-hidden='true'>&times;</span> </button> <button type='button' className='close' aria-label='Close' onClick={props.dismissAlert}> <span aria-hidden='true'>Override</span> </button> <strong>Error</strong> Query with the same name already exists. <a href='#' className='alert-link' onClick={props.overrideQuery}>Click here to override</a> </div> ); } return ( <> {alert} </> ); }; export default NoticeMessage;
src/components/common/svg-icons/image/monochrome-photos.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageMonochromePhotos = (props) => ( <SvgIcon {...props}> <path d="M20 5h-3.2L15 3H9L7.2 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 14h-8v-1c-2.8 0-5-2.2-5-5s2.2-5 5-5V7h8v12zm-3-6c0-2.8-2.2-5-5-5v1.8c1.8 0 3.2 1.4 3.2 3.2s-1.4 3.2-3.2 3.2V18c2.8 0 5-2.2 5-5zm-8.2 0c0 1.8 1.4 3.2 3.2 3.2V9.8c-1.8 0-3.2 1.4-3.2 3.2z"/> </SvgIcon> ); ImageMonochromePhotos = pure(ImageMonochromePhotos); ImageMonochromePhotos.displayName = 'ImageMonochromePhotos'; ImageMonochromePhotos.muiName = 'SvgIcon'; export default ImageMonochromePhotos;
src/demo/App.js
sergiocruz/react-logbook
import React, { Component } from 'react'; import { Link } from 'react-router'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <h1>React Logbook</h1> <div className="App-intro"> <ul className="App-menu"> <li>Demos:</li> <li> <Link to="/inline" activeClassName="active">inline</Link> </li> <li> <Link to="/ajax" activeClassName="active">ajax</Link> </li> <li> <Link to="/firebase" activeClassName="active">firebase</Link> </li> </ul> </div> </div> <div className="container"> {this.props.children} </div> </div> ); } } export default App;
packages/material-ui-icons/src/DialerSip.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let DialerSip = props => <SvgIcon {...props}> <path d="M17 3h-1v5h1V3zm-2 2h-2V4h2V3h-3v3h2v1h-2v1h3V5zm3-2v5h1V6h2V3h-3zm2 2h-1V4h1v1zm0 10.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.01.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.27-.26.35-.65.24-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1z" /> </SvgIcon>; DialerSip = pure(DialerSip); DialerSip.muiName = 'SvgIcon'; export default DialerSip;
client/src/components/setup-workflow/inprogress_lists.js
safv12/trello-metrics
'use strict'; import React from 'react'; import { DropTarget } from 'react-dnd'; import InprogressListsItem from './inprogress_list_item'; const listTarget = { drop(props, monitor) { const list = monitor.getItem(); props.onMoveList({ list: list.list, destination: 'inprogressLists' }); } }; function collect(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver() }; } const InprogressLists = (props) => { const listItems = props.lists.map((list) => { return ( <InprogressListsItem key={list.id} list={list}/> ); }); const { isOver, canDrop, connectDropTarget } = props; return connectDropTarget( <ul className="col-md-12 list-group column-small"> <li className="column-title">In progress lists</li> { listItems } </ul> ); } export default DropTarget('list', listTarget, collect)(InprogressLists);
src/index.js
sblesson/resume
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
test/server/ModalSpec.js
westonplatter/react-bootstrap
import React from 'react'; import {assert} from 'chai'; import Modal from '../../src/Modal.js'; describe('Modal', () => { it('Should be rendered on the server side', () => { let noOp = () => {}; assert.doesNotThrow(function renderOnServerSide() { return React.renderToString( <Modal onHide={noOp}> <strong>Message</strong> </Modal> ); }); }); });
src/components/Navbar/Navbar.js
bryanlelliott/bryan_site_react
/* * 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. */ import './Navbar.less'; import React from 'react'; // eslint-disable-line no-unused-vars class Navbar { render() { return ( <div className="navbar-top" role="navigation"> <a className="navbar-brand row" href="/"> <span><b>BRYAN</b>SITE</span> </a> </div> ); } } export default Navbar;
indico/web/client/js/jquery/widgets/jinja/duration_widget.js
indico/indico
// This file is part of Indico. // Copyright (C) 2002 - 2022 CERN // // Indico is free software; you can redistribute it and/or // modify it under the terms of the MIT License; see the // LICENSE file for more details. import React from 'react'; import ReactDOM from 'react-dom'; import {WTFDurationField} from 'indico/react/components'; window.setupDurationWidget = function setupDurationWidget({fieldId, required, disabled}) { // Make sure the results dropdown is displayed above the dialog. const field = $(`#${fieldId}`); field.closest('.ui-dialog-content').css('overflow', 'inherit'); field.closest('.exclusivePopup').css('overflow', 'inherit'); ReactDOM.render( <WTFDurationField timeId={`${fieldId}-timestorage`} required={required} disabled={disabled} />, document.getElementById(fieldId) ); };
js/components/sideBar/index.js
amandamfielding/Coffee-Shop-Mobile
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Image, View } from 'react-native'; import { Content, Text, List, ListItem, ProgressBar } from 'native-base'; import { firebaseApp } from "../auth/authentication"; import { Font } from 'exponent'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import { actions } from 'react-native-navigation-redux-helpers'; import { setIndex } from '../../actions/list'; import { closeDrawer } from '../../actions/drawer'; import navigateTo from '../../actions/sideBarNav'; import myTheme from '../../themes/base-theme'; import Exponent from 'exponent'; import styles from './styles'; const { reset, pushRoute, } = actions; class SideBar extends Component { static propTypes = { // setIndex: React.PropTypes.func, navigateTo: React.PropTypes.func, } constructor(props) { super(props); this.state = { fontLoaded: false, progress: 30 }; } navigateTo(route) { this.props.navigateTo(route, 'home'); } goToNews() { this.props.pushRoute({ key: 'news', index: 1 }, this.props.navigation.key); this.props.closeDrawer(); } goToLocations() { this.props.pushRoute({ key: 'locations', index: 1 }, this.props.navigation.key); this.props.closeDrawer(); } signOut() { firebaseApp.auth().signOut() .then(() => { this.props.reset(this.props.navigation.key) }, (error) => { console.log(error) }) this.props.closeDrawer(); } async componentDidMount() { await Font.loadAsync({ 'veneer': require('../../../assets/fonts/veneer.ttf'), }); this.setState({ fontLoaded: true }); } render() { if (!this.state.fontLoaded) {return null;} const news = this.state.fontLoaded ? "What's new?" : null; const locations = this.state.fontLoaded ? "Find A Store" : null; const signout = this.state.fontLoaded ? "Sign Out" : null; let pic; let name = ""; if (firebaseApp.auth().currentUser != null && this.props.user.picture != null) { pic = this.props.user.picture.data.url name = firebaseApp.auth().currentUser.displayName } let profilePic = (pic != null) ? (<Image style={styles.profilePic} source={{uri: this.props.user.picture.data.url}}/>) : (<Image style={styles.profilePic} source={require('../../../images/profilePicDefault.png')}/>) return ( <Content style={styles.sidebar} > <View style={styles.profile}> {profilePic} <Text style={{color:"white", alignSelf: "center", fontFamily: "veneer", fontSize: 24, paddingTop: 12 }}>{name}</Text> </View> <List style={styles.list}> <ListItem style={styles.listItem} button onPress={this.goToNews.bind(this)} > <Text style={styles.itemText} >{news}</Text> </ListItem> <ListItem style={styles.listItem} button onPress={this.goToLocations.bind(this)} > <Text style={styles.itemText}>{locations}</Text> </ListItem> <ListItem style={styles.listItem} button onPress={() => this.signOut()} > <Text style={styles.itemText}>{signout}</Text> </ListItem> </List> </Content> ); } } function bindAction(dispatch) { return { setIndex: index => dispatch(setIndex(index)), navigateTo: (route, homeRoute) => dispatch(navigateTo(route, homeRoute)), reset: key => dispatch(reset([{ key: 'logIn' }], key, 0)), closeDrawer: () => dispatch(closeDrawer()), pushRoute: (route, key) => dispatch(pushRoute(route, key)) }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, user: state.user.user }); export default connect(mapStateToProps, bindAction)(SideBar);
examples/dynamic-segments/app.js
fiture/react-router
import React from 'react'; import { Router, Route, Link, Redirect } from 'react-router'; var App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/user/123">Bob</Link></li> <li><Link to="/user/abc">Sally</Link></li> </ul> {this.props.children} </div> ); } }); var User = React.createClass({ render() { var { userID } = this.props.params; return ( <div className="User"> <h1>User id: {userID}</h1> <ul> <li><Link to={`/user/${userID}/tasks/foo`}>foo task</Link></li> <li><Link to={`/user/${userID}/tasks/bar`}>bar task</Link></li> </ul> {this.props.children} </div> ); } }); var Task = React.createClass({ render() { var { userID, taskID } = this.props.params; return ( <div className="Task"> <h2>User ID: {userID}</h2> <h3>Task ID: {taskID}</h3> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="user/:userID" component={User}> <Route path="tasks/:taskID" component={Task} /> <Redirect from="todos/:taskID" to="/user/:userID/tasks/:taskID" /> </Route> </Route> </Router> ), document.getElementById('example'));
src/components/Nav.js
jeremyburr/psyburr
import React from 'react' import Radium from 'radium' import NavLink from '../containers/NavLink.js' const rowStyle = { textAlign: 'center', '@media (min-width: 320px)' : { marginTop: '30px' }, '@media (min-width: 375px)' : { marginTop: '40px' }, '@media (min-width: 414px)' : { marginTop: '50px' }, '@media (min-width: 768px)' : { marginTop: '75px' }, } const middleLink = { display: 'inline', '@media (min-width: 320px)' : { //border: 'solid 1px red', width: '80px', paddingLeft: '25px', paddingRight: '25px', }, '@media (min-width: 375px)' : { width: '81px', paddingLeft: '30px', paddingRight: '31px', }, '@media (min-width: 414px)' : { width: '80px', paddingLeft: '35px', paddingRight: '35px', }, '@media (min-width: 768px)' : { width: '80px', paddingLeft: '115px', paddingRight: '115px', } } let Nav = () => ( <div style={rowStyle}> <NavLink target='1'> About </NavLink> <NavLink target='2'> <div style={middleLink}> Endeavors </div> </NavLink> <NavLink target='3'> Contact </NavLink> </div> ) Nav = Radium(Nav) export default Nav
docs/app/Examples/elements/Header/Content/HeaderExampleSubheaderProp.js
aabustamante/Semantic-UI-React
import React from 'react' import { Header } from 'semantic-ui-react' const HeaderExampleSubheaderProp = () => ( <Header as='h2' content='Account Settings' subheader='Manage your account settings and set email preferences' /> ) export default HeaderExampleSubheaderProp
js/src/components/Scene/SceneControls.js
scottdonaldson/voxcel
import React from 'react'; import CONFIG from '../../config'; import swal from 'sweetalert'; class SceneControls extends React.Component { constructor() { super(); } takeSnapshot() { let canvas = $(this.props.controlManager.canvas); canvas.addClass('faded'); $.ajax({ url: CONFIG.imgurEndpoint, type: 'POST', headers: { Authorization: 'Client-ID ' + CONFIG.imgurId, Accept: 'application/json' }, data: { image: canvas[0].toDataURL().split(',')[1], type: 'base64' }, success(result) { let id = result.data.id; console.log('success', CONFIG.imgurPrefix + '/' + id); }, error(err) { console.log('error uploading', err); } }); setTimeout(() => { canvas.removeClass('faded'); }, 350); } changeColor() { this.props.controlManager.changeColor(this.refs.colorPicker.value); } render() { return this.props.isAdmin ? ( <div id="scene-controls"> <input type="color" id="color-picker" ref="colorPicker" onChange={this.changeColor.bind(this)} /> <img src="/img/icons/camera.svg" onClick={this.takeSnapshot.bind(this)} /> </div> ) : null; } } export default SceneControls;
app/app.js
projectcashmere/admin
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import FontFaceObserver from 'fontfaceobserver'; import 'react-select/dist/react-select.css'; import 'sanitize.css/sanitize.css'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS and Global Styles import './global-styles'; // Import root routes import createRoutes from './routes'; // Observe loading of Open Sans (to remove open sans, remove the <link> tag in // the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); // When Open Sans is loaded, add a font-family using Open Sans to the body openSansObserver.load().then( () => { document.body.classList.add('fontLoaded'); }, () => { document.body.classList.remove('fontLoaded'); } ); // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = messages => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { new Promise(resolve => { resolve(import('intl')); }) .then(() => Promise.all([import('intl/locale-data/jsonp/en.js')])) .then(() => render(translationMessages)) .catch(err => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
node_modules/react-bootstrap/es/MediaListItem.js
mohammed52/something.pk
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 { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var MediaListItem = function (_React$Component) { _inherits(MediaListItem, _React$Component); function MediaListItem() { _classCallCheck(this, MediaListItem); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaListItem.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('li', _extends({}, elementProps, { className: classNames(className, classes) })); }; return MediaListItem; }(React.Component); export default bsClass('media', MediaListItem);
docs/app/Examples/views/Card/index.js
aabustamante/Semantic-UI-React
import React from 'react' import Content from './Content' import Types from './Types' import Variations from './Variations' const CardExamples = () => ( <div> <Types /> <Content /> <Variations /> </div> ) export default CardExamples
packages/xo-web/src/xo-app/settings/cloud-configs/index.js
vatesfr/xo-web
import _ from 'intl' import ActionButton from 'action-button' import decorate from 'apply-decorators' import defined from '@xen-orchestra/defined' import React from 'react' import SortedTable from 'sorted-table' import { addSubscriptions } from 'utils' import { AvailableTemplateVars, DEFAULT_CLOUD_CONFIG_TEMPLATE } from 'cloud-config' import { Container, Col } from 'grid' import { find } from 'lodash' import { generateId } from 'reaclette-utils' import { injectState, provideState } from 'reaclette' import { Text } from 'editable' import { Textarea as DebounceTextarea } from 'debounce-input-decorator' import { createCloudConfig, deleteCloudConfigs, editCloudConfig, subscribeCloudConfigs } from 'xo' // =================================================================== const COLUMNS = [ { itemRenderer: _ => _.id.slice(4, 8), name: _('formId'), sortCriteria: _ => _.id.slice(4, 8), }, { itemRenderer: ({ id, name }) => <Text value={name} onChange={name => editCloudConfig(id, { name })} />, sortCriteria: 'name', name: _('formName'), default: true, }, ] const ACTIONS = [ { handler: deleteCloudConfigs, icon: 'delete', individualLabel: _('deleteCloudConfig'), label: _('deleteSelectedCloudConfigs'), level: 'danger', }, ] const INDIVIDUAL_ACTIONS = [ { handler: (cloudConfig, { populateForm }) => populateForm(cloudConfig), icon: 'edit', label: _('editCloudConfig'), level: 'primary', }, ] const initialParams = { cloudConfigToEditId: undefined, name: '', template: undefined, } export default decorate([ addSubscriptions({ cloudConfigs: subscribeCloudConfigs, }), provideState({ initialState: () => initialParams, effects: { setInputValue: (_, { target: { name, value } }) => state => ({ ...state, [name]: value, }), reset: () => state => ({ ...state, ...initialParams, }), createCloudConfig: ({ reset }) => async ({ name, template = DEFAULT_CLOUD_CONFIG_TEMPLATE }) => { await createCloudConfig({ name, template }) reset() }, editCloudConfig: ({ reset }) => async ({ name, template, cloudConfigToEditId }, { cloudConfigs }) => { const oldCloudConfig = find(cloudConfigs, { id: cloudConfigToEditId }) if (oldCloudConfig.name !== name || oldCloudConfig.template !== template) { await editCloudConfig(cloudConfigToEditId, { name, template }) } reset() }, populateForm: (_, { id, name, template }) => state => ({ ...state, name, cloudConfigToEditId: id, template, }), }, computed: { formId: generateId, inputNameId: generateId, inputTemplateId: generateId, isInvalid: ({ name, template }) => name.trim() === '' || (template !== undefined && template.trim() === ''), }, }), injectState, ({ state, effects, cloudConfigs }) => ( <Container> <Col mediumSize={6}> <form id={state.formId}> <div className='form-group'> <label htmlFor={state.inputNameId}> <strong>{_('formName')}</strong>{' '} </label> <input className='form-control' id={state.inputNameId} name='name' onChange={effects.setInputValue} type='text' value={state.name} /> </div>{' '} <div className='form-group'> <label htmlFor={state.inputTemplateId}> <strong>{_('settingsCloudConfigTemplate')}</strong>{' '} </label>{' '} <AvailableTemplateVars /> <DebounceTextarea className='form-control' id={state.inputTemplateId} name='template' onChange={effects.setInputValue} rows={12} value={defined(state.template, DEFAULT_CLOUD_CONFIG_TEMPLATE)} /> </div>{' '} {state.cloudConfigToEditId !== undefined ? ( <ActionButton btnStyle='primary' disabled={state.isInvalid} form={state.formId} handler={effects.editCloudConfig} icon='edit' > {_('formEdit')} </ActionButton> ) : ( <ActionButton btnStyle='success' disabled={state.isInvalid} form={state.formId} handler={effects.createCloudConfig} icon='add' > {_('formCreate')} </ActionButton> )} <ActionButton className='pull-right' handler={effects.reset} icon='cancel'> {_('formCancel')} </ActionButton> </form> </Col> <Col mediumSize={6}> <SortedTable actions={ACTIONS} collection={cloudConfigs} columns={COLUMNS} data-populateForm={effects.populateForm} individualActions={INDIVIDUAL_ACTIONS} stateUrlParam='s' /> </Col> </Container> ), ])
src/index.js
chasm/tic-tac-routes
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { Router, Route } from 'react-router' import { createHistory } from 'history' import { syncReduxAndRouter } from 'redux-simple-router' import store from './store' import HomeView from './views/home' import GamesView from './views/games' const history = createHistory() syncReduxAndRouter(history, store) const render = () => { ReactDOM.render( <Provider store={store}> <Router history={history}> <Route path="/" component={HomeView}> <Route path="/games/:id" component={GamesView}/> </Route> </Router> </Provider>, document.getElementById('app') ) } store.subscribe(render) render()
src/stories/mobile/cityInfo.js
Cirych/WeatherApp
import React from 'react'; import { storiesOf, addDecorator, action, linkTo } from '@kadira/storybook'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import MobileTearSheet from './MobileTearSheet'; import weatherData from '../api/data'; import forecastData from '../api/forecast'; import CityInfo from '../../components/CityInfo'; const MobileDecorator = story => ( <MuiThemeProvider> <MobileTearSheet customColor="lightblue"> {story()} </MobileTearSheet> </MuiThemeProvider> ); const cityInfoData = { ...weatherData[0], forecast: forecastData.list }; storiesOf('Mobile.CityInfo', module) .addDecorator(MobileDecorator) .add('Info', () => ( <CityInfo city={cityInfoData} /> ))
src/components/callout/index.js
adrienlozano/stephaniewebsite
import React from 'react'; import Section from '~/components/section'; import styled from 'styled-components'; import Typography from '~/components/typography'; import PageSection from "~/components/page-section"; import CalloutButton from './button'; import withSettings from "~/enhancers/with-settings"; const CalloutSection = ({className, heading, subHeading}) => { return (<PageSection className={className} bg="dark" py={128} > <Typography component="h1" color="#FFF" f={[4, 6]}>{heading}</Typography> <Typography component="h2" color="#FFF" f={[2, 4]}>{subHeading}</Typography> <CalloutButton color="white" href="contact">Contact Us</CalloutButton> </PageSection>) }; const withCalloutSettings = withSettings( settings => ({ ...settings.map(x => x.landing).map(x => x.callout).getOrElse({}) }) ); export default withCalloutSettings(styled(CalloutSection)` text-align:center; `);
test/components/WorldMap-test.js
davrodpin/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import {test} from 'tape'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import WorldMap from '../../src/js/components/WorldMap'; import CSSClassnames from '../../src/js/utils/CSSClassnames'; const CLASS_ROOT = CSSClassnames.WORLD_MAP; test('loads a WorldMap', (t) => { t.plan(1); const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(WorldMap, { series: [{continent: 'Australia'}] })); const worldMapElement = shallowRenderer.getRenderOutput(); if (worldMapElement.props.className.indexOf(CLASS_ROOT) > -1) { t.pass('WorldMap has class'); } else { t.fail('WorldMap does not have class'); } });
packages/react-events/src/Drag.js
STRML/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { ReactResponderEvent, ReactResponderContext, } from 'shared/ReactTypes'; import React from 'react'; const targetEventTypes = ['pointerdown']; const rootEventTypes = [ 'pointerup', 'pointercancel', {name: 'pointermove', passive: false}, ]; type DragState = { dragTarget: null | Element | Document, isPointerDown: boolean, isDragging: boolean, startX: number, startY: number, x: number, y: number, }; // In the case we don't have PointerEvents (Safari), we listen to touch events // too if (typeof window !== 'undefined' && window.PointerEvent === undefined) { targetEventTypes.push('touchstart', 'mousedown'); rootEventTypes.push('mouseup', 'mousemove', 'touchend', 'touchcancel', { name: 'touchmove', passive: false, }); } type EventData = { diffX: number, diffY: number, }; type DragEventType = 'dragstart' | 'dragend' | 'dragchange' | 'dragmove'; type DragEvent = {| target: Element | Document, type: DragEventType, timeStamp: number, diffX?: number, diffY?: number, |}; function createDragEvent( context: ReactResponderContext, type: DragEventType, target: Element | Document, eventData?: EventData, ): DragEvent { return { target, type, timeStamp: context.getTimeStamp(), ...eventData, }; } function dispatchDragEvent( context: ReactResponderContext, name: DragEventType, listener: DragEvent => void, state: DragState, discrete: boolean, eventData?: EventData, ): void { const target = ((state.dragTarget: any): Element | Document); const syntheticEvent = createDragEvent(context, name, target, eventData); context.dispatchEvent(syntheticEvent, listener, {discrete}); } const DragResponder = { targetEventTypes, createInitialState(): DragState { return { dragTarget: null, isPointerDown: false, isDragging: false, startX: 0, startY: 0, x: 0, y: 0, }; }, stopLocalPropagation: true, onEvent( event: ReactResponderEvent, context: ReactResponderContext, props: Object, state: DragState, ): void { const {target, type, nativeEvent} = event; switch (type) { case 'touchstart': case 'mousedown': case 'pointerdown': { if (!state.isDragging) { if (props.onShouldClaimOwnership) { context.releaseOwnership(); } const obj = type === 'touchstart' ? (nativeEvent: any).changedTouches[0] : nativeEvent; const x = (state.startX = (obj: any).screenX); const y = (state.startY = (obj: any).screenY); state.x = x; state.y = y; state.dragTarget = target; state.isPointerDown = true; if (props.onDragStart) { dispatchDragEvent( context, 'dragstart', props.onDragStart, state, true, ); } context.addRootEventTypes(rootEventTypes); } break; } } }, onRootEvent( event: ReactResponderEvent, context: ReactResponderContext, props: Object, state: DragState, ): void { const {type, nativeEvent} = event; switch (type) { case 'touchmove': case 'mousemove': case 'pointermove': { if (event.passive) { return; } if (state.isPointerDown) { const obj = type === 'touchmove' ? (nativeEvent: any).changedTouches[0] : nativeEvent; const x = (obj: any).screenX; const y = (obj: any).screenY; state.x = x; state.y = y; if (!state.isDragging && x !== state.startX && y !== state.startY) { let shouldEnableDragging = true; if ( props.onShouldClaimOwnership && props.onShouldClaimOwnership() ) { shouldEnableDragging = context.requestGlobalOwnership(); } if (shouldEnableDragging) { state.isDragging = true; if (props.onDragChange) { const dragChangeEventListener = () => { props.onDragChange(true); }; dispatchDragEvent( context, 'dragchange', dragChangeEventListener, state, true, ); } } else { state.dragTarget = null; state.isPointerDown = false; context.removeRootEventTypes(rootEventTypes); } } else { if (props.onDragMove) { const eventData = { diffX: x - state.startX, diffY: y - state.startY, }; dispatchDragEvent( context, 'dragmove', props.onDragMove, state, false, eventData, ); } (nativeEvent: any).preventDefault(); } } break; } case 'pointercancel': case 'touchcancel': case 'touchend': case 'mouseup': case 'pointerup': { if (state.isDragging) { if (props.onShouldClaimOwnership) { context.releaseOwnership(); } if (props.onDragEnd) { dispatchDragEvent(context, 'dragend', props.onDragEnd, state, true); } if (props.onDragChange) { const dragChangeEventListener = () => { props.onDragChange(false); }; dispatchDragEvent( context, 'dragchange', dragChangeEventListener, state, true, ); } state.isDragging = false; } if (state.isPointerDown) { state.dragTarget = null; state.isPointerDown = false; context.removeRootEventTypes(rootEventTypes); } break; } } }, }; export default React.unstable_createEventComponent(DragResponder, 'Drag');
src/components/Html.js
Maryanushka/masterskaya
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import serialize from 'serialize-javascript'; import config from '../config'; /* eslint-disable react/no-danger */ class Html extends React.Component { static propTypes = { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, styles: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string.isRequired, cssText: PropTypes.string.isRequired, }).isRequired), scripts: PropTypes.arrayOf(PropTypes.string.isRequired), app: PropTypes.object, // eslint-disable-line children: PropTypes.string.isRequired, }; static defaultProps = { styles: [], scripts: [], }; render() { const { title, description, styles, scripts, app, children } = this.props; return ( <html className="no-js" lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <title>{title}</title> <meta name="description" content={description} /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="apple-touch-icon" href="apple-touch-icon.png" /> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css" /> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css" /> {styles.map(style => ( <style key={style.id} id={style.id} dangerouslySetInnerHTML={{ __html: style.cssText }} /> ))} </head> <body> <div id="app" dangerouslySetInnerHTML={{ __html: children }} /> <script dangerouslySetInnerHTML={{ __html: `window.App=${serialize(app)}` }} /> {scripts.map(script => <script key={script} src={script} />)} <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </body> </html> ); } } export default Html;
demo/containers/FormV1/Fields.js
vbait/vb-react-form
import React from 'react'; import PropTypes from 'prop-types'; import { Button, FormGroup, ControlLabel, FormControl, HelpBlock, Alert } from 'react-bootstrap'; import { VBForm, connectForm } from '../../../src/Forms'; const Actions = ({ form }) => { const isValid = form.isValid(); return ( <Button type="submit" bsStyle="success" disabled={!isValid}> {isValid ? 'Submit' : 'Not Valid'} </Button> ) }; Actions.propTypes = { form: PropTypes.object.isRequired, }; const FormActions = connectForm(Actions); class FormFieldWrapper extends React.Component { state = { invalid: false, }; onFieldChange = (model) => { this.setState(() => ({ invalid: model.touched && !model.isValid(), errors: model.errors(), })); }; render() { const { id, label } = this.props; const { invalid, errors } = this.state; return ( <FormGroup controlId={id} validationState={invalid ? 'error' : null}> {label && <ControlLabel>{label}</ControlLabel>} <VBForm.Field {...this.props} onFieldChange={this.onFieldChange} /> {invalid && ( <HelpBlock> {errors.map(error => ( <div key={error}>{error}</div> ))} </HelpBlock> )} </FormGroup> ) } } const PasswordField = ({ model, ...props }) => { const invalid = model.touched && !model.isValid(); const errors = model.errors(); return ( <FormGroup controlId={props.id} validationState={invalid ? 'error' : null}> {props.label && <ControlLabel>{props.label}</ControlLabel>} <InputField {...props} /> {invalid && ( <HelpBlock> {errors.map(error => ( <div key={error}>{error}</div> ))} </HelpBlock> )} </FormGroup> ); }; const RBField = ({ model, ...props }) => { const invalid = model.touched && !model.isValid(); const errors = model.errors(); return ( <FormGroup controlId={props.id} validationState={invalid ? 'error' : null}> {props.label && <ControlLabel>{props.label}</ControlLabel>} <InputField {...props} /> {invalid && ( <HelpBlock> {errors.map(error => ( <div key={error}>{error}</div> ))} </HelpBlock> )} </FormGroup> ); }; class InputField extends React.PureComponent { onChange = (event) => { event.preventDefault(); this.props.onChange(event.target.value); }; render() { const { value, ...other } = this.props; return ( <FormControl value={value || ''} {...other} onChange={this.onChange} /> ) } } const ErrorComponent = ({ form, field }) => { let errors = []; let invalid = false; if (field) { errors = field.errors(); invalid = field.touched && !field.isValid(); } else { errors = form.errors().form; invalid = form.isTouched() && errors.length; } return ( <div> {invalid ? ( <Alert bsStyle="danger"> {errors.map(error => ( <div key={error}>{error}</div> ))} </Alert> ) : null} </div> ) }; export { FormActions, FormFieldWrapper, PasswordField, InputField, ErrorComponent, RBField, };
src/svg-icons/av/forward-10.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvForward10 = (props) => ( <SvgIcon {...props}> <path d="M4 13c0 4.4 3.6 8 8 8s8-3.6 8-8h-2c0 3.3-2.7 6-6 6s-6-2.7-6-6 2.7-6 6-6v4l5-5-5-5v4c-4.4 0-8 3.6-8 8zm6.8 3H10v-3.3L9 13v-.7l1.8-.6h.1V16zm4.3-1.8c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.8-.8v-.5s-.1-.2-.1-.3-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z"/> </SvgIcon> ); AvForward10 = pure(AvForward10); AvForward10.displayName = 'AvForward10'; AvForward10.muiName = 'SvgIcon'; export default AvForward10;
examples/todomvc/test/components/Footer.spec.js
paulkogel/redux
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import Footer from '../../components/Footer' import { SHOW_ALL, SHOW_ACTIVE } from '../../constants/TodoFilters' function setup(propOverrides) { const props = Object.assign({ completedCount: 0, activeCount: 0, filter: SHOW_ALL, onClearCompleted: expect.createSpy(), onShow: expect.createSpy() }, propOverrides) const renderer = TestUtils.createRenderer() renderer.render(<Footer {...props} />) const output = renderer.getRenderOutput() return { props: props, output: output } } function getTextContent(elem) { const children = Array.isArray(elem.props.children) ? elem.props.children : [ elem.props.children ] return children.reduce(function concatText(out, child) { // Children are either elements or text strings return out + (child.props ? getTextContent(child) : child) }, '') } describe('components', () => { describe('Footer', () => { it('should render container', () => { const { output } = setup() expect(output.type).toBe('footer') expect(output.props.className).toBe('footer') }) it('should display active count when 0', () => { const { output } = setup({ activeCount: 0 }) const [ count ] = output.props.children expect(getTextContent(count)).toBe('No items left') }) it('should display active count when above 0', () => { const { output } = setup({ activeCount: 1 }) const [ count ] = output.props.children expect(getTextContent(count)).toBe('1 item left') }) it('should render filters', () => { const { output } = setup() const [ , filters ] = output.props.children expect(filters.type).toBe('ul') expect(filters.props.className).toBe('filters') expect(filters.props.children.length).toBe(3) filters.props.children.forEach(function checkFilter(filter, i) { expect(filter.type).toBe('li') const a = filter.props.children expect(a.props.className).toBe(i === 0 ? 'selected' : '') expect(a.props.children).toBe({ 0: 'All', 1: 'Active', 2: 'Completed' }[i]) }) }) it('should call onShow when a filter is clicked', () => { const { output, props } = setup() const [ , filters ] = output.props.children const filterLink = filters.props.children[1].props.children filterLink.props.onClick({}) expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE) }) it('shouldnt show clear button when no completed todos', () => { const { output } = setup({ completedCount: 0 }) const [ , , clear ] = output.props.children expect(clear).toBe(undefined) }) it('should render clear button when completed todos', () => { const { output } = setup({ completedCount: 1 }) const [ , , clear ] = output.props.children expect(clear.type).toBe('button') expect(clear.props.children).toBe('Clear completed') }) it('should call onClearCompleted on clear button click', () => { const { output, props } = setup({ completedCount: 1 }) const [ , , clear ] = output.props.children clear.props.onClick({}) expect(props.onClearCompleted).toHaveBeenCalled() }) }) })
node_modules/react-router/es6/withRouter.js
TheeSweeney/ComplexReactReduxMiddlewareReview
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; }; import invariant from 'invariant'; import React from 'react'; import hoistStatics from 'hoist-non-react-statics'; import { routerShape } from './PropTypes'; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function withRouter(WrappedComponent, options) { var withRef = options && options.withRef; var WithRouter = React.createClass({ displayName: 'WithRouter', contextTypes: { router: routerShape }, propTypes: { router: routerShape }, getWrappedInstance: function getWrappedInstance() { !withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0; return this.wrappedInstance; }, render: function render() { var _this = this; var router = this.props.router || this.context.router; var props = _extends({}, this.props, { router: router }); if (withRef) { props.ref = function (c) { _this.wrappedInstance = c; }; } return React.createElement(WrappedComponent, props); } }); WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')'; WithRouter.WrappedComponent = WrappedComponent; return hoistStatics(WithRouter, WrappedComponent); }
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-forms-v3-slider.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import Environment from '../environment/environment.js'; import {BaseMixin, ElementaryMixin, ContentMixin, Tools} from './../common/common.js'; import {Glyphicon} from './../bricks/bricks.js'; import Slid from './../bricks/slider.js'; import InputMixin from './mixins/input-mixin.js'; import Number from './number.js'; import TextInput from './internal/text-input.js'; import './slider.less'; export const Slider = React.createClass({ mixins: [ BaseMixin, ElementaryMixin, ContentMixin, InputMixin ], statics: { tagName: 'UU5.Forms.Slider', classNames: { main: 'uu5-forms-slider', inputGroup: 'uu5-forms-slider-input-group', slider: 'uu5-forms-slider-slider', number: 'uu5-forms-slider-number' }, defaults: { nanMessage: 'Please insert a number', } }, propTypes: { colorSchema: React.PropTypes.oneOf(Environment.colorSchema), // TODO //position: React.PropTypes.oneOf(['horizontal', 'vertical']), min: React.PropTypes.number, max: React.PropTypes.number, step: React.PropTypes.number, value: React.PropTypes.number, onChange: React.PropTypes.func, onChanged: React.PropTypes.func }, // Setting defaults getDefaultProps() { return { colorSchema: 'default', //position: 'horizontal', min: 0, max: 10, step: 1, value: null, onChanged: null }; }, componentWillMount(){ let value = typeof this.props.value === 'number' ? this.props.value : this.props.min; if (this.props.onValidate && typeof this.props.onValidate === 'function') { this._validateOnChange({value: value, event: null, component: this}) } else { this.setInitial(null, value) } return this; }, componentWillReceiveProps(nextProps) { if (this.props.controlled) { let value = typeof this.props.value === 'number' ? nextProps.value : nextProps.min; this.setFeedback(nextProps.feedback, nextProps.message, nextProps.value) } return this; }, // Interface // Overriding Functions setValue_(value, setStateCallback) { if (typeof this.props.onValidate === 'function') { this._validateOnChange({value:value}) } else { this.props.required ? this.setSuccess(null, value, setStateCallback) : this.setInitial(null, value, setStateCallback); } return this; }, // Component Specific Helpers // _onChange(e) { // if (!this.isDisabled()) { // var value = !this.getValue(); // var newState = this._validateValue(value); // // if (newState) { // this.setState(newState); // } else { // if (this.props.onChange) { // this.props.onChange({ value: value, input: this, event: e }); // } else { // this.setState({ value: value }); // } // } // } // return this; // }, _validateOnChange(opt){ let result = typeof this.props.onValidate === 'function' ? this.props.onValidate(opt) : null; if (result) { if (typeof result === 'object') { if (result.feedback) { this.setFeedback(result.feedback, result.message, result.value); } else { this.setState({value: opt.value}); } } else { this.showError('validateError', null, {context: {event: e, func: this.props.onValidate, result: result}}); } } return this; }, _getMainAttrs() { return this.getInputMainAttrs(); }, _getInputGroupAttrs() { return { className: this.getClassName().inputGroup }; }, _getSliderProps() { let value = this.props.min; if (this.state.value) { value = typeof this.state.value === 'number' ? this.state.value : parseInt(this.state.value); } return { name: this.getName(), className: this.getClassName().slider, colorSchema: this.props.colorSchema, //position: 'horizontal', min: this.props.min, max: this.props.max, step: this.props.step, value: value, content: this.getContent(), onChange: this._onChange, onChanged: this.props.onChanged, disabled: this.isDisabled() || this.isReadOnly() }; }, _getNumberProps() { let value = this.state.value || 0; value = value > this.props.max ? this.props.max : (value < this.props.min) ? this.props.min : value; return { className: this.getClassName().number, min: this.props.min, max: this.props.max, value: value.toString(), onChange: (event)=> { this._onChange({component: this, value: event.target.value, event: event}) }, onBlur: (opt) => { if (this.state.value < this.props.min) { opt.component.setValue(this.props.min); } else if (this.state.value > this.props.max) { opt.component.setValue(this.props.max); } }, disabled: this.isDisabled(), onChangeFeedback: this._onChangeNumberFeedback }; }, _getOnChanged(value, e) { let onChanged; if (typeof this.props.onChanged === 'function') { onChanged = () => { this.props.onChanged({value: value, component: this, event: e}); }; } return onChanged; }, _onChange(opt) { if (!this.isDisabled()) { if (typeof this.props.onChange == 'function') { opt.component = this; this.props.onChange(opt); } else if (typeof this.props.onValidate === 'function') { this._validateOnChange(opt) } else { let result = this._checkNumberResultChange(opt); if (result.feedback && result.feedback === 'warning') { this.setFeedback(result.feedback, result.message, result.value); } else { this.setInitial(null, opt.value, this._getOnChanged(opt.value, opt.event)); } } } return this; }, _checkNumberResultChange(opt){ if (opt.value) { opt.value = opt.value.toString(); let isComma = opt.value.indexOf(',') > 0; opt.value = opt.value.trim().replace(new RegExp(this.props.thousandSeparator, 'g'), ''); opt.value = opt.value.replace(',', '.'); let isNan = isNaN(opt.value); if (isNan && opt.value != '-') { opt.value = this.state.value; opt.feedback = 'warning'; opt.message = this.getDefault().nanMessage; } isComma && (opt.value = opt.value.replace('.', ',')); } return opt; }, _onChangeNumberFeedback(opt) { this.setValue(opt.value ? +opt.value : null, opt.callback); //this.setFeedback(opt.feedback, opt.message, opt.value ? +opt.value : null, opt.callback); return this; }, _getFeedbackIcon(){ let icon = this.props.required ? this.props.successGlyphicon : null; switch (this.getFeedback()) { case 'success': icon = this.props.successGlyphicon; break; case 'warning': icon = this.props.warningGlyphicon; break; case 'error': icon = this.props.errorGlyphicon; break; } return icon; }, // Render render() { let inputId = this.getId() + '-input'; return ( <div {...this._getInputAttrs()}> {this.getLabel(inputId)} {this.getInputWrapper([ <Slid {...this._getSliderProps()}> {this.props.children && React.Children.toArray(this.props.children)} </Slid>, <TextInput {...this._getNumberProps()} id={inputId} name={this.props.name || inputId} //value={this.state.value.toString()} placeholder={this.props.placeholder} type='text' //onChange={this.onChange} //onBlur={this.onBlur} //onFocus={this.onFocus} mainAttrs={this.props.inputAttrs} disabled={this.isDisabled() || this.isLoading()} readonly={this.isReadOnly()} glyphicon={this._getFeedbackIcon()} loading={this.isLoading()} />])} </div> ); } }); export default Slider;
frontend/src/components/eois/details/overview/projectDetails.js
unicef/un-partner-portal
import React from 'react'; import PropTypes from 'prop-types'; import Typography from 'material-ui/Typography'; import Grid from 'material-ui/Grid'; import Button from 'material-ui/Button'; import { browserHistory as history } from 'react-router'; import SectorForm from '../../../forms/fields/projectFields/sectorField/sectorFieldArray'; import GridColumn from '../../../common/grid/gridColumn'; import GridRow from '../../../common/grid/gridRow'; import HeaderList from '../../../common/list/headerList'; import TextField from '../../../forms/textFieldForm'; import ProjectPartners from '../../../forms/fields/projectFields/partnersField/ProjectPartners'; import PaddedContent from '../../../common/paddedContent'; import PartnersForm from '../../../forms/fields/projectFields/partnersField/partnersFieldArray'; import { Attachments, TitleField, FocalPoint, OtherInfo, Background, Goal, StartDate, EndDate, DeadlineDate, ClarificationRequestDeadlineDate, NotifyDate, } from '../../../forms/fields/projectFields/commonFields'; import LocationFieldReadOnlyArray from '../../../forms/fields/projectFields/locationField/locationFieldReadOnlyArray'; import SpreadContent from '../../../common/spreadContent'; import { PROJECT_TYPES, ROLES } from '../../../../helpers/constants'; import OrganizationTypes from '../../../forms/fields/projectFields/organizationType'; import Agencies from '../../../forms/fields/projectFields/agencies'; const messages = { title: 'Project Details', labels: { id: 'CFEI ID:', dsrId: 'DSR ID:', issued: 'Issued by', goal: 'Expected Results', agency: 'Agency', partner: 'Organization\'s Legal Name', type: 'Type of Organization', viewProfile: 'view partner\'s profile', }, }; const Fields = ({ type, role, partnerId, displayGoal, formName }) => { if (type === PROJECT_TYPES.UNSOLICITED) { return (<PaddedContent> <GridColumn > {role === ROLES.AGENCY && <GridRow columns={2} > <ProjectPartners fieldName="partner_name" label={messages.labels.partner} readOnly /> <OrganizationTypes fieldName="display_type" label={messages.labels.type} readOnly /> </GridRow>} <TitleField readOnly /> {role === ROLES.PARTNER && <Agencies fieldName="agency" readOnly />} <LocationFieldReadOnlyArray formName={formName} /> <SectorForm readOnly /> {role === ROLES.AGENCY && <Grid container justify="flex-end"> <Grid item> <Button onClick={() => history.push(`/partner/${partnerId}/details`)} color="accent" > {messages.labels.viewProfile} </Button> </Grid> </Grid>} </GridColumn> </PaddedContent>); } return (<PaddedContent> <GridColumn > <TitleField readOnly /> {role === ROLES.AGENCY ? <FocalPoint readOnly /> : null} <LocationFieldReadOnlyArray formName={formName} /> <SectorForm readOnly /> <Agencies fieldName="agency" label={messages.labels.issued} readOnly /> <Background readOnly /> {displayGoal && <Goal readOnly />} <OtherInfo readOnly /> {type === PROJECT_TYPES.OPEN && <GridRow columns={3} > <ClarificationRequestDeadlineDate readOnly /> <DeadlineDate readOnly /> <NotifyDate readOnly /> </GridRow>} <GridRow columns={2} > <StartDate readOnly /> <EndDate readOnly /> </GridRow> {type === PROJECT_TYPES.OPEN && <Attachments readOnly />} {type === PROJECT_TYPES.DIRECT && <PartnersForm hidePartner readOnly />} </GridColumn> </PaddedContent>); }; Fields.propTypes = { type: PropTypes.string, role: PropTypes.string, partner: PropTypes.string, formName: PropTypes.string, partnerId: PropTypes.number, displayGoal: PropTypes.bool, }; const title = type => () => ( <SpreadContent> <Typography type="headline" >{messages.title}</Typography> {type !== PROJECT_TYPES.UNSOLICITED && <TextField fieldName="displayID" label={(type === PROJECT_TYPES.OPEN || type === PROJECT_TYPES.PINNED) ? messages.labels.id : messages.labels.dsrId} readOnly />} </SpreadContent> ); const ProjectDetails = ({ type, role, partner, partnerId, displayGoal, formName }) => ( <HeaderList header={title(type)} > <Fields formName={formName} type={type} role={role} partner={partner} partnerId={partnerId} displayGoal={displayGoal} /> </HeaderList> ); ProjectDetails.propTypes = { type: PropTypes.string, role: PropTypes.string, partner: PropTypes.string, partnerId: PropTypes.number, displayGoal: PropTypes.bool, }; export default ProjectDetails;
web/src/components/preview.js
ajmalafif/ajmalafif.com
import React from 'react' import tw, { css } from 'twin.macro' export const Preview = React.forwardRef(function Preview(props, ref) { return ( <div {...props} tw="block relative bg-gradient-to-t" css={{ height: 'max(40rem, 30vmin)', marginTop: '-40rem', '--tw-gradient-from': 'var(--bg-primary)', '--tw-gradient-stops': 'var(--tw-gradient-from), var(--tw-gradient-to, rgba(255, 255, 255, 0))', gridColumn: '1 / 4' }} > {ref} </div> ) })
test/index.js
zhbhun/react-window-kit
/** * Created by zhbhun on 2015/9/17. */ import React from 'react'; import {Window, Modal, Confirm, Tip} from './bootstrap'; import assign from 'object-assign'; // modal demo class ModalDemo extends React.Component { constructor(props) { super(props); this.state = { show: false } } render() { return ( <div> <button onClick={this.openWindow.bind(this)}>open modal</button> <Modal visible={this.state.show} size='lg' header='Title' onHide={this.closeWindow.bind(this)} onCancel={this.closeWindow.bind(this)} onConfirm={this.closeWindow.bind(this)} > <h3>Hello Modal!</h3> </Modal> </div> ) } openWindow() { this.setState({ show: true }) } closeWindow() { this.setState({ show: false }) } } React.render(<ModalDemo/>, document.getElementById('modal-demo')); // --- // confirm demo class ConfirmDemo extends React.Component { constructor(props) { super(props); this.state = { show: false } } render() { return ( <div> <button onClick={this.openWindow.bind(this)}>open confirm</button> <Confirm visible={this.state.show} title='Are you sure!' onCancel={this.closeWindow.bind(this)} onOk={this.closeWindow.bind(this)} > Hello Modal! Hello Modal! Hello Modal! Hello Modal! Hello Modal! </Confirm> </div> ) } openWindow() { this.setState({ show: true }) } closeWindow() { this.setState({ show: false }) } } React.render(<ConfirmDemo/>, document.getElementById('confirm-demo')); // --- // tip demo class ConfirmTip extends React.Component { constructor(props) { super(props); this.state = { show: false } } render() { return ( <div> <button onClick={this.openWindow.bind(this)}>open tip</button> <Tip visible={this.state.show} type='info' title='Are you sure!' onOk={this.closeWindow.bind(this)} > Hello Modal! Hello Modal! Hello Modal! Hello Modal! Hello Modal! </Tip> </div> ) } openWindow() { this.setState({ show: true }) } closeWindow() { this.setState({ show: false }) } } React.render(<ConfirmTip/>, document.getElementById('tip-demo'));
service-worker-prototype/src/index.js
ericapisani/service-worker-prototype
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
public/containers/CourseList/UserPaymentBlock.js
ninjiangstar/hackSChedule
import React, { Component } from 'react'; import classnames from 'classnames'; import api from '../../utils/api-interface'; import StripeCheckout from 'react-stripe-checkout'; class UserPaymentBlock extends Component { constructor(props) { super(props); this.state = { errorMessage: '', paymentInProgress: false, paid: false }; if (window.location.hostname == 'hackschedule.com') { this.stripeKey = 'pk_live_qmovCOmw8NHmyjlH9PPu3Jgp'; } else { this.stripeKey = 'pk_test_VJUKGjbH9Amo8DwJhqDeCAtM'; } this.socket = io(); this.onToken = this.onToken.bind(this); this.close = this.close.bind(this); this.userChangedPaid = this.userChangedPaid.bind(this); } componentWillMount() { this.socket.on('receive:userChangedPaid', this.userChangedPaid); } componentWillUnmount() { this.socket.off('receive:userChangedPaid', this.userChangedPaid); } userChangedPaid({ email: userChangedEmail, paid }) { const { email } = this.props; if (email == userChangedEmail && paid) this.setState({ paid }); } renderPayment() { const { email } = this.props; const { errorMessage, paymentInProgress } = this.state; return <div className='start upgrade'> <h3 className='red'>Upgrade Features for $2 🙏</h3> <div> <p>Hosting and maintaining this service is expensive! I need your help to offset the costs of building and running this app. For $2, you get to unlock the ability to <b>see more than 25 options, pin class sections, and block out unavailabilities</b>!</p> </div> <div> <StripeCheckout token={this.onToken} stripeKey={this.stripeKey} name="HackSChedule Upgrade" description="by Andrew Jiang" amount={200} currency="USD" allowRememberMe={false} email={email}> <button className="red">Pay With Card</button> </StripeCheckout> <button className="blue" onClick={() => { window.open('https://venmo.com/?txn=pay&audience=friends&recipients=ninjiangstar&amount=2&note=hackschedule_id:' + email.split('@')[0]) }}>Venmo</button> </div> {(() => { if (errorMessage.length > 0) return <div className='alert'>{errorMessage}</div>; })()} </div>; } renderThankYou() { return <div className='start upgrade'> <p><b>Thank you and good luck!</b></p> <button onClick={this.close}>Activate Upgrades Now</button> </div>; } render() { const { paid } = this.state; const { paid: isUserPaid } = this.props; if (isUserPaid) return null; else if(!paid) return this.renderPayment(); else return this.renderThankYou(); } onToken(token) { let { email, pin } = this.props; this.setState({ paymentInProgress: true, errorMessage: '' }); api.post(api.user.pay(email), { pin, token }) .then(response => { if (response.paid) { this.setState({ paid: true }); } else { this.setState({ paymentInProgress: false, paid: false, errorMessage: 'Unable to process payment: ' + response.error }); } }); } close() { this.props.close({ action: 'PAYMENT', paid: this.state.paid }); } } export default UserPaymentBlock;
auth/src/components/common/CardSection.js
DaveWJ/LearningReact
/** * Created by david on 2/22/17. */ import React from 'react'; import { View } from 'react-native'; const CardSection = (props) => { return ( <View style={styles.containerStyle}> {props.children} </View> ); }; const styles = { containerStyle: { borderBottomWidth: 1, padding: 5, backgroundColor: '#fff', justifyContent: 'flex-start', flexDirection: 'row', borderColor: '#ddd', position: 'relative' } }; export { CardSection };
src/components/Icons/Mute/index.js
jmikrut/keen-2017
import React from 'react'; import './Mute.css'; export default (props) => { if (props.color) { this.color = props.color; } else { this.color = '#4df7ca'; } return ( <svg className="mute" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <polyline stroke={this.color} points="8.47 14.91 11.07 17.74 11.07 11.08"/> <path stroke={this.color} d="M11.07,6.48V2.26L5.6,7.71H3.17A1.26,1.26,0,0,0,2,8.92v2.43a1.19,1.19,0,0,0,1.13,1.22H5"/> <path stroke={this.color} d="M13.45,9.93a1.91,1.91,0,0,1-1.92,1.91h-.46"/> <line stroke={this.color} x1="2.56" y1="17.74" x2="18.05" y2="2.26"/> </svg> ); }
app/containers/CreateBundle.js
kaunio/gloso
// @flow import React, { Component } from 'react'; import { withRouter } from 'react-router' import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import LanguagePair from '../components/LanguagePair'; import * as glosorActions from '../actions/glosorActions'; class HomePage extends Component { createFn(lang1, lang2) { this.props.setLangs(lang1, lang2); this.props.router.push("/addGlosor"); } render() { return ( <LanguagePair createFn={(a,b) => this.createFn(a,b)} /> ); } } function mapStateToProps(state) { return { }; } function mapDispatchToProps(dispatch) { return bindActionCreators(glosorActions, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(withRouter(HomePage));
src/components/Feedback/Feedback.js
hang-up/react-whatever
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback extends Component { 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;
examples/huge-apps/routes/Grades/components/Grades.js
ArmendGashi/react-router
import React from 'react'; class Grades extends React.Component { render () { return ( <div> <h2>Grades</h2> </div> ); } } export default Grades;
app/containers/App.js
pavelkomiagin/npmr
// @flow import React, { Component } from 'react'; export default class App extends Component { props: { children: HTMLElement }; render() { return ( <div> {this.props.children} </div> ); } }
src/Register.js
RobertMcCoy/CodeCollaborator
import React, { Component } from 'react'; import './Register.css'; import './main.css'; import { Redirect } from 'react-router'; import axios from 'axios'; import validator from 'validator'; class Register extends Component { constructor(props) { super(props); this.state = { errors: {}, user: { email: '', firstname: '', lastname: '', username: '', password: '', confirmPassword: '' }, registered: false } this.verifyInput = this.verifyInput.bind(this); this.handleForm = this.handleForm.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(event) { event.preventDefault(); for (var property in this.state.user) { this.verifyInput(property, this.state.user[property]); } for (var error in this.state.errors) { if (this.state.errors[error].length > 0) { return false; } } axios.post('/auth/signup', { 'username': this.state.user.username, 'email': this.state.user.email, 'password': this.state.user.password, 'firstname': this.state.user.firstname, 'lastname': this.state.user.lastname }).then((response) => { if (response.status === 200) { localStorage.setItem('jwtToken', response.data.token); } this.setState({ registered: true }) }).catch((response) => { localStorage.setItem('jwtToken', ''); this.setState({ errors: { registrationError: response.data } }) }); } verifyInput(field, value) { var currentErrors = this.state.errors; if (field === "email") { if (!validator.isEmail(value)) { currentErrors.emailError = "Email must be a valid address!"; this.setState({ errors: currentErrors }); } else { currentErrors.emailError = ""; this.setState({ errors: currentErrors }); } } if (field === "username") { if (!value) { currentErrors.userNameError = "Username must be present!"; this.setState({ errors: currentErrors }); } } if (field === "firstname") { if (!value) { currentErrors.firstNameError = "First Name must be filled in!"; this.setState({ errors: currentErrors }); } } if (field === "lastname") { if (!value) { currentErrors.lastNameError = "Last Name must be filled in!"; this.setState({ errors: currentErrors }); } } if (field === "password") { if (!value) { currentErrors.passwordError = "Password must be filled in!"; this.setState({ errors: currentErrors }); } } if (field === "password" || field === "confirmPassword") { if (this.state.user.password !== this.state.user.confirmPassword || this.state.user.password === '' || this.state.user.confirmPassword === '') { currentErrors.passwordMismatch = "Passwords must match!"; this.setState({ errors: currentErrors }); } else { currentErrors.passwordMismatch = ""; this.setState({ errors: currentErrors }); } } } handleForm(event) { const field = event.target.name; const user = this.state.user; user[field] = event.target.value; this.verifyInput(field, event.target.value); this.setState({ user }); } render() { if (this.state.registered) { return ( <Redirect to='/profile' /> ) } else { return ( <div className="container"> <form id="signup" name="signup" onSubmit={this.handleSubmit} > <h2>Sign-up for CodeCollaborator</h2> {this.state.errors.unfilledFields && <p className="code-collab-error">*{this.state.errors.unfilledFields}</p>} <div className="form-group"> <label htmlFor="email">Email*:</label> <input type="email" className="form-control" name="email" onChange={this.handleForm} value={this.state.user.email} /> {this.state.errors.emailError && <p className="code-collab-error">*{this.state.errors.emailError}</p>} </div> <div className="form-group"> <label htmlFor="firstname">First Name*:</label> <input type="text" className="form-control" name="firstname" onChange={this.handleForm} value={this.state.user.firstname} /> {this.state.errors.firstNameError && <p className="code-collab-error">*{this.state.errors.firstNameError}</p>} </div> <div className="form-group"> <label htmlFor="lastname">Last Name*:</label> <input type="text" className="form-control" name="lastname" onChange={this.handleForm} value={this.state.user.lastname} /> {this.state.errors.lastNameError && <p className="code-collab-error">*{this.state.errors.lastNameError}</p>} </div> <div className="form-group"> <label htmlFor="username">Username*:</label> <input type="text" className="form-control" name="username" onChange={this.handleForm} value={this.state.user.username} /> {this.state.errors.userNameError && <p className="code-collab-error">*{this.state.errors.userNameError}</p>} </div> <div className="form-group"> <label htmlFor="password">Password*:</label> <input type="password" className="form-control" name="password" onChange={this.handleForm} value={this.state.user.password} /> {this.state.errors.passwordError && <p className="code-collab-error">*{this.state.errors.passwordError}</p>} </div> <div className="form-group"> <label htmlFor="confirmPassword">Confirm Password*:</label> <input type="password" className="form-control" name="confirmPassword" onChange={this.handleForm} value={this.state.user.confirmPassword} /> {this.state.errors.passwordMismatch && <p className="code-collab-error">*{this.state.errors.passwordMismatch}</p>} </div> {this.state.errors.registrationError && <p className="code-collab-error">*{this.state.errors.registrationError}</p>} <input type="submit" value="Register" className="btn btn-info" /> </form> </div> ); } } } export default Register;
src/svg-icons/av/loop.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvLoop = (props) => ( <SvgIcon {...props}> <path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/> </SvgIcon> ); AvLoop = pure(AvLoop); AvLoop.displayName = 'AvLoop'; export default AvLoop;
app/javascript/mastodon/features/ui/components/modal_loading.js
danhunsaker/mastodon
import React from 'react'; import LoadingIndicator from '../../../components/loading_indicator'; // Keep the markup in sync with <BundleModalError /> // (make sure they have the same dimensions) const ModalLoading = () => ( <div className='modal-root__modal error-modal'> <div className='error-modal__body'> <LoadingIndicator /> </div> <div className='error-modal__footer'> <div> <button className='error-modal__nav onboarding-modal__skip' /> </div> </div> </div> ); export default ModalLoading;
client/src/components/ApartmentList/components/Apartment.js
uramen/apartments
import React, { Component } from 'react'; import FontAwesome from 'react-fontawesome' import Tooltip from 'rc-tooltip'; import { Link } from 'react-router'; import 'rc-tooltip/assets/bootstrap.css'; import _ from 'lodash'; export default class Apartment extends Component { constructor(props) { super(props); this.state = { visibleType: false, visibleWifi: false, } } handleTypeHover = () => { this.setState({ visibleType: !this.state.visibleType, }); } handleWifiHover = () => { this.setState({ visibleWifi: !this.state.visibleWifi, }); } render() { return ( <div className="col-md-6 apartment"> <div className="flex-wrapp"> <div className="apartment-image"> <img src={this.props.images[0]} alt=""/> </div> <div className="apartment-info"> <h4>{_.truncate(this.props.title, {'length': 24, 'separator': ' '})}</h4> <div className="rooms-with-price"> <span className="rooms">{`${this.props.rooms}к`}</span> <span className="price">{`${this.props.price} грн`}</span> </div> <div className="comfort"> <Tooltip visible={this.state.visibleType} animation="zoom" trigger={[]} overlayStyle={{ zIndex: 1000 }} overlay={<span>{this.props.type}</span>} > <div className="comfort-yellow" onClick={this.handleTypeHover.bind(this)}> { this.props.type === 'Flat' ? <FontAwesome name="building" style={{paddingLeft: 2, paddingRight: 2}} /> : <FontAwesome name="home" /> } </div> </Tooltip> <Tooltip visible={this.state.visibleWifi} animation="zoom" trigger={[]} overlayStyle={{ zIndex: 1000 }} overlay={<span>wifi</span>} > <div className="comfort-blue" onClick={this.handleWifiHover.bind(this)}> <FontAwesome name="wifi" /> </div> </Tooltip> </div> <div className="phone">{this.props.number}</div> <Link to={`/apartments/${this.props.id}`} className="detail-btn">Детально</Link> </div> </div> <p className="apartment-description">{_.truncate(this.props.description, {'length': 150, 'separator': ' '})}</p> </div> ); } }
client/modules/Post/__tests__/components/PostList.spec.js
caleb272/PollIt
import React from 'react'; import test from 'ava'; import { shallow } from 'enzyme'; import PostList from '../../components/PostList'; const posts = [ { name: 'Prashant', title: 'Hello Mern', slug: 'hello-mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'" }, { name: 'Mayank', title: 'Hi Mern', slug: 'hi-mern', cuid: 'f34gb2bh24b24b3', content: "All dogs bark 'mern!'" }, ]; test('renders the list', t => { const wrapper = shallow( <PostList posts={posts} handleShowPost={() => {}} handleDeletePost={() => {}} /> ); t.is(wrapper.find('PostListItem').length, 2); });
packages/cockpit/ui/src/components/Converter.js
iurimatias/embark-framework
import PropTypes from "prop-types"; import React from 'react'; import { Card, CardBody, CardHeader, Col, FormGroup, Input, Row, Label } from 'reactstrap'; import CopyButton from './CopyButton'; import { calculateUnits } from '../services/unitConverter'; class Converter extends React.Component { constructor(props) { super(props); this.state = { etherConversions: []}; } componentDidMount() { this.setState({etherConversions: calculateUnits(this.props.baseEther, 'Ether')}); } handleOnChange(event, key) { const value = event.target.value; let newUnits; if (value.slice(-1) === '.') { // `calculateUnits()` turns `1.` to `1` which makes it impossible // for users to get beyond the first dot when typing decimal values. // That's why we bypass recalculation all together when the last character // is a dot and only update the form control in question. newUnits = this.state.etherConversions.map(unit => { if (unit.key === key) { unit.value = value; } return unit; }); this.setState({etherConversions: newUnits}); } else { newUnits = calculateUnits(value, key); this.setState({etherConversions: newUnits}); } const newBaseEther = newUnits.find(unit => unit.key === 'ether'); this.props.updateBaseEther(newBaseEther.value); } render() { return( <Row className="justify-content-md-center"> <Col xs="12" sm="9" lg="9"> <Card> <CardHeader> <strong>Ether Converter</strong> </CardHeader> <CardBody> { this.state.etherConversions.map(unit => ( <FormGroup key={unit.key}> <Label htmlFor={unit.name}>{unit.name}</Label> <div className="position-relative"> <Input id={unit.name} placeholder={unit.name} value={unit.value} onChange={e => this.handleOnChange(e, unit.key)} /> <CopyButton text={unit.value} title="Copy value to clipboard" size={2}/> </div> </FormGroup> )) } </CardBody> </Card> </Col> </Row> ); } } Converter.propTypes = { baseEther: PropTypes.string, updateBaseEther: PropTypes.func }; export default Converter;
CompositeUi/src/views/component/SectionHeader.js
kreta-io/kreta
/* * This file is part of the Kreta package. * * (c) Beñat Espiña <benatespina@gmail.com> * (c) Gorka Laucirica <gorka.lauzirika@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import './../../scss/components/_section-header.scss'; import React from 'react'; const SectionHeader = props => <div className="section-header"> <h3 className="section-header__title"> {props.title} </h3> <div className="section-header__actions"> {props.actions} </div> </div>; export default SectionHeader;
docs/src/app/components/pages/components/AppBar/Page.js
igorbt/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import appBarReadmeText from './README'; import AppBarExampleIcon from './ExampleIcon'; import appBarExampleIconCode from '!raw!./ExampleIcon'; import AppBarExampleIconButton from './ExampleIconButton'; import appBarExampleIconButtonCode from '!raw!./ExampleIconButton'; import AppBarExampleComposition from './ExampleComposition'; import appBarExampleIconComposition from '!raw!./ExampleComposition'; import appBarCode from '!raw!material-ui/AppBar/AppBar'; const AppBarPage = () => ( <div> <Title render={(previousTitle) => `App Bar - ${previousTitle}`} /> <MarkdownElement text={appBarReadmeText} /> <CodeExample code={appBarExampleIconCode} title="Simple example" > <AppBarExampleIcon /> </CodeExample> <CodeExample code={appBarExampleIconButtonCode} title="Buttons example" > <AppBarExampleIconButton /> </CodeExample> <CodeExample code={appBarExampleIconComposition} title="Composition example" > <AppBarExampleComposition /> </CodeExample> <PropTypeDescription code={appBarCode} /> </div> ); export default AppBarPage;
src/layouts/CoreLayout.js
terakilobyte/rumbl_front
import React from 'react'; import 'styles/core.scss'; export default class CoreLayout extends React.Component { static propTypes = { children : React.PropTypes.element } render () { return ( <div className='page-container'> <div className='view-container'> {this.props.children} </div> </div> ); } }
src/views/pages/admin-dashboard/admin-dashboard.js
Metaburn/doocrate
import React, { Component } from 'react'; import { OrderedMap } from 'immutable'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Redirect } from 'react-router'; import { firebaseDb } from 'src/firebase'; import { CSVLink } from 'react-csv'; import './admin-dashboard.css'; import Button from '../../components/button/button'; import { notificationActions } from '../../../notification'; import { Textbox } from 'react-inputs-validation'; import Textarea from 'react-textarea-autosize'; export class AdminDashboard extends Component { constructor() { super(...arguments); this.state = { users: OrderedMap(), query: [], isButtonsUnlocked: false, usersWhoDidntBuy: [], usersToAllowToRegisterCount: 0, successEmails: [], CSVLink: undefined, }; this.setAllUsersToHaveCreateTaskAssignPermissions = this.setAllUsersToHaveCreateTaskAssignPermissions.bind( this, ); this.unlockDashboard = this.unlockDashboard.bind(this); this.handleUsersWhoDidntBuy = this.handleUsersWhoDidntBuy.bind(this); this.handleChange = this.handleChange.bind(this); this.setUsersToDidntBuy = this.setUsersToDidntBuy.bind(this); this.setUsersAllowCreateTasks = this.setUsersAllowCreateTasks.bind(this); //this.migrateIsDone = this.migrateIsDone.bind(this); } static propTypes = { auth: PropTypes.object.isRequired, }; componentWillMount() { // We are ordering the users by creation date to use it in 3. Allowing more users to get tickets firebaseDb .collection('users') .orderBy('created', 'asc') .get() .then(querySnapshot => { const users = {}; querySnapshot.forEach(function(doc) { users[doc.id] = doc.data(); }); this.setState({ users: OrderedMap(users) }); }); } onCSVLink() { this.setState({ CSVLink: ( <span> <CSVLink className={'button-as-link'} data={this.generateUsersCSV()}> הורדת דוח משתמשים </CSVLink> </span> ), }); } componentWillReceiveProps(nextProps) {} componentDidUpdate(prevProps, prevState) { if (prevState.users !== this.state.users) { //this.setState({query}); } } isAdmin() { return this.props.auth.role === 'admin'; } generateUsersCSV = () => { const { users } = this.state; const result = [ [ 'Id', 'Created', 'Email', 'Name', 'Default Project', 'Language', 'Photo Url', 'Bio', 'Updated', ], ]; users.forEach(user => { let row = [ user.id, user.created, user.email, user.name, user.defaultProject, user.language, user.photoURL, user.bio, user.updated, ]; result.push(row); }); return result; }; render() { if (!this.isAdmin()) { return <Redirect to="/" />; } return ( <div className="admin-dashboard"> <h3>זהירות אם אתה לא יודע מה לעשות בעמוד זה עדיף שתשאל לפני</h3> <br /> <br /> <span> מספר משתמשים במערכת סך הכל {this.state.users.size}</span> <br /> {this.state.CSVLink ? ( this.state.CSVLink ) : ( <button className={'button-as-link'} onClick={this.onCSVLink.bind(this)} > הכן הורדה של רשימת המשתמשים </button> )} <br /> <Button onClick={this.unlockDashboard}> אפשר את כל הכפתורים הבאים - מנגנון אזהרה </Button> <hr /> <br /> <h1>1.פתיחת אפשרות למשתמשים ליצור ולקחת משימות</h1> <Button disabled={!this.state.isButtonsUnlocked} onClick={this.setAllUsersToHaveCreateTaskAssignPermissions} > הפוך את כל המשתמשים של המערכת לבעלי הרשאה ליצור משימות ולקחת משימות </Button> <hr /> <br /> <br /> <h1>2.קביעת משתמשים שלא קנו כרטיס</h1> {this.renderUsersWhoDidntBuy( 'usersWhoDidntBuy', 'משתמשים שלא קנו כרטיס מחולקים בפסיק לדוגמא galbra@test.com,john@gmail.com', this.state.isButtonsUnlocked, 1, )} <span> סך משתמשים שיושפעו: {this.state.usersWhoDidntBuy.length}</span> <br /> <Button disabled={!this.state.isButtonsUnlocked} onClick={this.setUsersToDidntBuy} > הדלק את הדגל עבור את המשתמשים הללו ל-DidntBuy </Button> <hr /> <br /> <br /> <h1>3.פתיחת אפשרות לייצר משימות למשתמשים האחרונים שנרשמו</h1> {this.renderInput( 'usersToAllowToRegisterCount', 'מספר משתמשים לפתוח עבורם הרשמה. נגיד 100', this.state.isButtonsUnlocked, 2, false, )} <br /> <Button disabled={!this.state.isButtonsUnlocked} onClick={this.setUsersAllowCreateTasks} > פתח את האפשרות לפתוח משימה ולקחת משימה לאנשים הללו </Button> {this.state.successEmails && this.state.successEmails.length > 0 ? ( <div> <span>אימיילים שנפתחה עבורם האפשרות להרשם:</span> <br /> <span>{this.state.successEmails.join(',')}</span> </div> ) : ( '' )} <br /> {/*<h1>4.מיגרציה להוסיף לכל המשימות את ה isDone פלאג</h1>*/} {/*<Button disabled={!this.state.isButtonsUnlocked} onClick={this.migrateIsDone}>בצע מיגרציה</Button>*/} </div> ); } renderUsersWhoDidntBuy(fieldName, placeholder, isEditable, tabIndex) { const classNames = isEditable ? ' editable' : ''; return ( <Textarea className={`changing-input${classNames}`} name={fieldName} tabIndex={tabIndex} value={this.state[fieldName]} placeholder={placeholder} ref={e => (this[fieldName + 'Input'] = e)} onChange={this.handleUsersWhoDidntBuy} onBlur={this.handleUsersWhoDidntBuy} // here to trigger validation callback on Blur onKeyUp={() => {}} // here to trigger validation callback on Key up disabled={!isEditable} /> ); } renderInput(fieldName, placeholder, isEditable, tabIndex, isAutoFocus) { const classNames = isEditable ? ' editable' : ''; return ( <Textbox className={`changing-input${classNames}`} type="text" tabIndex={tabIndex} name={fieldName} value={this.state[fieldName]} placeholder={placeholder} ref={e => (this[fieldName + 'Input'] = e)} onChange={this.handleChange} onKeyUp={() => {}} // here to trigger validation callback on Key up disabled={!isEditable} autofocus={isAutoFocus} /> ); } handleUsersWhoDidntBuy(o) { let fieldName = o.target.name; // Remove empty spaces let parsedString = o.target.value.replace(/\s/g, ''); // Break it into an array if (o.target.value) { this.setState({ [fieldName]: parsedString.split(','), }); } else { this.setState({ [fieldName]: null, }); } } handleChange(n, e) { let fieldName = e.target.name; this.setState({ [fieldName]: e.target.value, }); } // Find that user in a sluggish way findUserByEmail(userEmail) { let result = this.state.users.findEntry((user, userid) => { return user.email === userEmail; }); // Return null if empty if (!result) { return result; } // Otherwise return the key return result[0]; } /* Goes over the list of given users and allow them to create task and assign themselves */ setUsersAllowCreateTasks() { const usersCollection = firebaseDb.collection('users'); let dontHaveTicketCounter = 0; let haveTicketCounter = 0; let usersThatShouldHaveTicket = {}; this.state.users.forEach((user, userid) => { if (dontHaveTicketCounter >= this.state.usersToAllowToRegisterCount) { return; } if (!user.canCreateTask) { console.log('Dont have ticket counter - ' + dontHaveTicketCounter++); // Give him a ticket and email him and output his name console.log('Ticket for ' + user.email); usersThatShouldHaveTicket[userid] = user; } else { console.log('Have counter - ' + haveTicketCounter++); console.log('Already have ticket for ' + user.email); } }); let successCounter = 0; let successEmails = []; OrderedMap(usersThatShouldHaveTicket).forEach((user, userid) => { console.log('About to ticket ' + user.email); successEmails.push(user.email); const userDoc = usersCollection.doc(userid); userDoc .update({ canCreateTask: true, canAssignTask: true, }) .then(res => { console.log('Success ' + successCounter++ + ' ' + user.email); }) .catch(err => { console.error(err); console.log('With the following user:'); console.error(userid); console.error(user); }); }); console.log('Success emails: ' + successEmails); this.setState({ successEmails }); this.props.showSuccess( 'People who didnt have ticket and now have ' + dontHaveTicketCounter + ' People\r\n' + 'People who have ticket ' + haveTicketCounter, ); } /* Goes over the list of given users and set the didntBuy flag to true */ setUsersToDidntBuy() { const usersCollection = firebaseDb.collection('users'); let counter = 1; this.state.usersWhoDidntBuy.forEach(userWhoDidntBuyEmail => { let targetUserId = this.findUserByEmail(userWhoDidntBuyEmail); if (!targetUserId) { console.log('Cant find a user by that email: ' + userWhoDidntBuyEmail); this.props.showError( 'Cant find a user by the email ' + userWhoDidntBuyEmail + '. Check console for more info', ); } else { const userDoc = usersCollection.doc(targetUserId); userDoc .update({ didntBuy: true, }) .then(res => { console.log(counter++); }) .catch(err => { console.error(err); }); } }); this.props.showSuccess( 'Updating ' + this.state.usersWhoDidntBuy.length + ' Users... - all have flag of didntBuy. Check console and wait for it to reach ' + this.state.usersWhoDidntBuy.length, ); } /* Goes over all the users and give them permission to create task and assign tasks */ setAllUsersToHaveCreateTaskAssignPermissions() { const usersCollection = firebaseDb.collection('users'); let counter = 1; this.state.users.forEach((user, userid) => { const userDoc = usersCollection.doc(userid); userDoc .update({ canCreateTask: true, canAssignTask: true, }) .then(res => { console.log(counter++); }) .catch(err => { console.error(err); }); }); this.props.showSuccess( 'Updating ' + this.state.users.size + ' Users... - all have permission to create tasks and assign tasks. Check console and wait for it to reach ' + this.state.users.size, ); } /** * Adds a flag isDone to all the existing tasks * Done once. Stored here for future migrations till we have a proper migration system */ // migrateIsDone() { // firebaseDb.collection('projects').get().then((projectSnapshot) => { // let projectCounter = 0; // projectSnapshot.forEach((project) => { // projectCounter++; // const projectData = project.data(); // const projectTasksCollection = firebaseDb.collection('projects').doc(projectData.url).collection('tasks'); // projectTasksCollection.get().then((tasksSnapshot) => { // let counter = 1; // tasksSnapshot.forEach((task) => { // const taskId = task.id; // projectTasksCollection.doc(taskId).update({ // isDone: false // }).then(res => { // counter++; // console.log("User " + projectCounter + ": Counter " + counter); // }).catch(err => { // console.error(err); // }); // }) // }); // debugger; // // }) // // }); // // } unlockDashboard() { this.setState({ isButtonsUnlocked: !this.state.isButtonsUnlocked }); } } //===================================== // CONNECT //------------------------------------- const mapStateToProps = state => { return { tasks: state.tasks.list, auth: state.auth, }; }; const mapDispatchToProps = Object.assign({}, notificationActions); export default connect(mapStateToProps, mapDispatchToProps)(AdminDashboard);
website/src/pages/index.js
wix/react-native-navigation
import React from 'react'; import { Redirect } from '@docusaurus/router'; function Home() { return <Redirect to="/react-native-navigation/docs/before-you-start/" />; } export default Home;
test/specs/views/Card/CardGroup-test.js
aabustamante/Semantic-UI-React
import faker from 'faker' import React from 'react' import { SUI } from 'src/lib' import CardGroup from 'src/views/Card/CardGroup' import * as common from 'test/specs/commonTests' describe('CardGroup', () => { common.isConformant(CardGroup) common.hasUIClassName(CardGroup) common.rendersChildren(CardGroup) common.implementsWidthProp(CardGroup, SUI.WIDTHS, { propKey: 'itemsPerRow', canEqual: false }) common.propKeyOnlyToClassName(CardGroup, 'doubling') common.propKeyOnlyToClassName(CardGroup, 'stackable') describe('renders children', () => { const firstText = faker.hacker.phrase() const secondText = faker.hacker.phrase() it('with `items` prop', () => { const items = [ { header: firstText }, { header: secondText }, ] const wrapper = mount(<CardGroup items={items} />).find('Card') wrapper.first().find('CardHeader').should.contain.text(firstText) wrapper.last().find('CardHeader').should.contain.text(secondText) }) }) })
components/slider/__tests__/index.spec.js
jasonleibowitz/react-toolbox
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import sinon from 'sinon'; import expect from 'expect'; import { ProgressBar } from '../../progress_bar/ProgressBar.js'; import Input, { Input as RawInput } from '../../input/Input.js'; import Slider, { Slider as RawSlider } from '../Slider.js'; import utils from '../../utils/testing'; import theme from '../theme.scss'; describe('Slider', function () { let slider, progress, input, onChange; describe('#positionToValue', function () { before(function () { const tree = TestUtils.renderIntoDocument(<Slider min={-500} max={500} />); slider = TestUtils.findRenderedComponentWithType(tree, RawSlider); slider.setState({ sliderStart: 500, sliderLength: 100 }); }); it('returns min when position is less than origin', function () { expect(slider.positionToValue({x: 400})).toEqual(-500); }); it('returns max when position is more and origin plus length', function () { expect(slider.positionToValue({x: 900})).toEqual(500); }); it('returns the proper position when the position is inside slider', function () { expect(slider.positionToValue({x: 520})).toEqual(-300); }); }); describe('#trimValue', function () { before(function () { const tree = TestUtils.renderIntoDocument(<Slider min={0} max={100} step={0.1} />); slider = TestUtils.findRenderedComponentWithType(tree, RawSlider); }); it('rounds to the proper number', function () { expect(slider.trimValue(57.16)).toEqual(57.2); expect(slider.trimValue(57.12)).toEqual(57.10); }); it('returns min if number is less than min', function () { expect(slider.trimValue(-57.16)).toEqual(0); }); it('returns max if number is more than max', function () { expect(slider.trimValue(257.16)).toEqual(100); }); }); describe('#valueForInput', function () { before(function () { const tree = TestUtils.renderIntoDocument(<Slider min={0} max={100} step={0.01} />); slider = TestUtils.findRenderedComponentWithType(tree, RawSlider); }); it('returns a fixed number when an integer is given', function () { expect(slider.valueForInput(4)).toEqual('4.00'); }); it('returns a fixed number when a float is given', function () { expect(slider.valueForInput(4.06)).toEqual('4.06'); }); }); describe('#knobOffset', function () { it('returns the corresponding offset for a given value and slider length/start', function () { const tree = TestUtils.renderIntoDocument(<Slider min={-500} max={500} value={-250} />); slider = TestUtils.findRenderedComponentWithType(tree, RawSlider); slider.setState({ sliderStart: 500, sliderLength: 100 }); expect(slider.knobOffset()).toEqual(25); }); }); describe('#render', function () { it('contains a linear progress bar with proper properties', function () { const tree = TestUtils.renderIntoDocument(<Slider min={100} max={1000} value={140} />); slider = TestUtils.findRenderedComponentWithType(tree, RawSlider); progress = TestUtils.findRenderedComponentWithType(slider, ProgressBar); expect(progress.props.mode).toEqual('determinate'); expect(progress.props.type).toEqual('linear'); expect(progress.props.value).toEqual(140); expect(progress.props.min).toEqual(100); expect(progress.props.max).toEqual(1000); }); it('contains an input component if its editable', function () { const tree = TestUtils.renderIntoDocument(<Slider editable value={130} />); slider = TestUtils.findRenderedComponentWithType(tree, RawSlider); input = TestUtils.findRenderedComponentWithType(slider, Input); expect(parseInt(input.props.value)).toEqual(slider.props.value); }); it('contains the proper number of snaps when snapped', function () { slider = utils.shallowRenderComponent(RawSlider, {editable: true, pinned: true, theme}); expect(slider.props.className).toContain(theme.ring); expect(slider.props.className).toContain(theme.pinned); slider = utils.shallowRenderComponent(RawSlider, {editable: true, value: 50, theme}); expect(slider.props.className).toNotContain(theme.ring); }); }); describe('#events', function () { beforeEach(function () { onChange = sinon.spy(); const tree = TestUtils.renderIntoDocument(<Slider min={-500} max={500} onChange={onChange} />); slider = TestUtils.findRenderedComponentWithType(tree, RawSlider); slider.setState({ sliderStart: 0, sliderLength: 1000 }); slider.handleResize = (event, callback) => { callback(); }; }); it('sets pressed state when knob is clicked', function () { TestUtils.Simulate.mouseDown(slider.refs.knob); expect(slider.state.pressed).toEqual(true); }); it('sets pressed state when knob is touched', function () { TestUtils.Simulate.touchStart(slider.refs.knob, {touches: [{pageX: 200}]}); expect(slider.state.pressed).toEqual(true); }); it('sets a proper value when the slider is clicked', function () { TestUtils.Simulate.mouseDown(slider.refs.slider, { pageX: 200 }); expect(onChange.called).toEqual(true); expect(onChange.getCall(0).args[0]).toEqual(-300); }); it('sets a proper value when the slider is touched', function () { TestUtils.Simulate.touchStart(slider.refs.slider, {touches: [{pageX: 200, pageY: 0}]}); expect(onChange.called).toEqual(true); expect(onChange.getCall(0).args[0]).toEqual(-300); }); it('changes input value when slider changes', function () { const tree = TestUtils.renderIntoDocument(<Slider editable onChange={onChange} />); slider = TestUtils.findRenderedComponentWithType(tree, RawSlider); slider.setState({sliderStart: 0, sliderLength: 1000}); slider.handleResize = (event, callback) => { callback(); }; input = TestUtils.findRenderedComponentWithType(slider, Input); TestUtils.Simulate.mouseDown(slider.refs.slider, { pageX: 900 }); expect(onChange.called).toEqual(true); expect(onChange.getCall(0).args[0]).toEqual(90); }); it('changes its value when input is blurred', function () { const tree = TestUtils.renderIntoDocument(<Slider editable value={50} onChange={onChange} />); slider = TestUtils.findRenderedComponentWithType(tree, RawSlider); input = TestUtils.findRenderedComponentWithType(slider, RawInput); TestUtils.Simulate.change(input.refs.input, {target: {value: '80'}}); TestUtils.Simulate.blur(input.refs.input); expect(onChange.called).toEqual(true); expect(onChange.getCall(0).args[0]).toEqual(80); }); it('calls onChange callback when the value is changed', function () { const onChangeSpy = sinon.spy(); const tree = TestUtils.renderIntoDocument(<Slider onChange={onChangeSpy} />); slider = TestUtils.findRenderedComponentWithType(tree, RawSlider); slider.setState({sliderStart: 0, sliderLength: 1000}); TestUtils.Simulate.mouseDown(slider.refs.slider, { pageX: 900 }); expect(onChangeSpy.called).toEqual(true); }); }); });
app/src/client/components/app/Notifications.js
dvdschwrtz/DockDev
import React from 'react'; import {Link} from 'react-router'; // import { remote } from 'electron'; const Notifications = ({ DOToken, updateToken }) => ( <div className="full-page"> <div className="notification-content"> <div className="list-group"> <a href="#" className="list-group-item active"> <h4 className="list-group-item-heading">List group item heading</h4> <p className="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p> </a> <a href="#" className="list-group-item"> <h4 className="list-group-item-heading">List group item heading</h4> <p className="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p> </a> <a href="#" className="list-group-item"> <h4 className="list-group-item-heading">List group item heading</h4> <p className="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p> </a> </div> </div> </div> ); Notifications.propTypes = { updateToken: React.PropTypes.func, DOToken: React.PropTypes.string, }; export default Notifications;
src/components/search/AccountFilter.js
whphhg/vcash-ui
import React from 'react' import { translate } from 'react-i18next' import { inject, observer } from 'mobx-react' /** Ant Design */ import Select from 'antd/lib/select' @translate(['common']) @inject('send', 'wallet') @observer class AccountFilter extends React.Component { constructor(props) { super(props) this.t = props.t this.send = props.send this.wallet = props.wallet } render() { return ( <Select onChange={acc => this.send.setSpendFrom(acc)} optionFilterProp="children" size="small" style={{ width: '140px' }} value={this.send.spend.fromAccount} > <Select.Option disabled={ this.send.recipients.size > 1 && this.send.spend.utxo.length === 0 } value="*ANY*" > {this.t('any')} </Select.Option> <Select.Option value="*DEFAULT*">{this.t('default')}</Select.Option> {this.wallet.accNames.map(acc => ( <Select.Option key={acc} value={acc}> {acc} </Select.Option> ))} </Select> ) } } export default AccountFilter
src/step-23/ReOrganize.js
gufsky/react-native-workshop
import React, { Component } from 'react' import Highlight from 'react-syntax-highlight' import Note from '../Note' import structurePng from './Structure.png' const HomeScreen = `import React from 'react' import { connect } from 'react-redux' import { searchBars } from './../store/actions/actions' import { AppRegistry, StyleSheet, Text, TextInput, View, Image, TouchableOpacity } from 'react-native' import * as colors from './../styles/colors' class HomeScreen extends React.Component { static navigationOptions () { return { title: 'Welcome' } } constructor (props) { super(props) this.clickHandler = this.clickHandler.bind(this) navigator.geolocation.getCurrentPosition(data => this.state.location = data, error => console.log('GEO ERROR', error)) this.state = { searchString: '', location: null } console.log('CURRENT POSITION: ', this.state.location) } clickHandler () { const { navigation, doSearch } = this.props const { searchString, location } = this.state doSearch(searchString, location.coords.latitude, location.coords.longitude).then(() => navigation.navigate('Map', { searchString: this.state.searchString })) } render () { console.log('search props', this.state) return ( <View style={styles.container}> <View style={styles.row}> <Image source={require('./../assets/images/Beer.png')} style={styles.mainIcon} /> <Image source={require('./../assets/images/Wine.png')} style={styles.mainIcon} /> <Image source={require('./../assets/images/Martini.png')} style={styles.mainIcon} /> </View> <Text style={styles.welcome}>Begin Your Adventure</Text> <View style={{ flexDirection: 'row' }}> <View style={styles.searchWrap}> <TextInput style={styles.search} underlineColorAndroid='transparent' placeholder='Search for beer, wine, or cocktail' placeholderTextColor='#f7f7f7' onChangeText={text => this.setState({ searchString: text })} value={this.state.searchString} /> </View> <TouchableOpacity onPress={this.clickHandler} style={{ flex: 1, alignItems: 'center', padding: 5 }} > <Image source={require('./../assets/images/Search.png')} style={{ height: 30, width: 30, marginTop: -5 }} /> </TouchableOpacity> </View> </View> ) } } const STANDARD_VERT_SPACING = 25 const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: colors.PRIMARY_PURPLE, padding: 20 }, row: { flexDirection: 'row', marginBottom: 15 }, mainIcon: { height: 80, width: 80 }, searchWrap: { height: 30, flex: 5, backgroundColor: '#986FBF', borderWidth: 0.5, borderColor: colors.WHITE, borderRadius: 2, marginBottom: STANDARD_VERT_SPACING, padding: 5, paddingLeft: 10 }, search: { flex: 1, // needed for IOS text to center vertically fontSize: 14, color: colors.WHITE }, welcome: { color: colors.WHITE, fontSize: 20, textAlign: 'center', margin: 10, marginBottom: STANDARD_VERT_SPACING }, instructions: { textAlign: 'center', color: colors.WHITE, marginBottom: 5 } }) export default connect(null, dispatch => { return { doSearch: (text, lat, long) => dispatch(searchBars(text, lat, long)) } })(HomeScreen)` const indexJs = `import React from 'react' import { AppRegistry } from 'react-native' import { StackNavigator } from 'react-navigation' import { fetchInitialState } from './store/actions/actions'; import MapScreen from './components/Map' import HomeScreen from './components/HomeScreen' const Routes = StackNavigator({ Home: { screen: HomeScreen }, Map: { screen: MapScreen } }, { headerMode: 'none' }) export default class App extends React.Component { render () { return ( <Routes /> ) } } AppRegistry.registerComponent('barfinder', () => App) ` const packageJSON = `{ "name": "barfinder", "version": "0.0.1", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "test": "jest", "lint": "standard --fix" }, "dependencies": { "lodash": "^4.17.4", "react": "16.0.0-alpha.12", "react-native": "0.48.3", "react-native-configs": "^1.1.0", "react-native-maps": "^0.16.4", "react-navigation": "^1.0.0-beta.11", "react-redux": "^5.0.6", "redux": "^3.7.2", "redux-thunk": "^2.2.0" }, "devDependencies": { "babel-jest": "21.0.2", "babel-preset-react-native": "4.0.0", "jest": "21.1.0", "react-test-renderer": "16.0.0-alpha.12", "standard-react-native": "^1.0.1" }, "jest": { "preset": "react-native" } } ` class SearchUiView extends Component { render() { return ( <div className="general"> <h1>16. Let's Start by Reorganizing!</h1> <p>In the next few steps we will be cleaning up some code from the last workshop, adding the components we need for our search screen, and the interactions and supporting routes for the map screen, and detail screen.</p> <h2>Project Structure</h2> <p>Setup your project with the following files and folders:</p> <p><b>2 key folders added </b></p> <ul> <li>/config</li> <li>/store</li> </ul> <img src={structurePng} style={{height: '60rem'}} /> <p>Update package.json to include the redux and config dependencies</p> <Highlight lang='json' value={packageJSON} /> <p>npm install</p> <h2>Move HomeScreen to its own component</h2> <p>Let's start by making our entry files a bit more readable</p> <ul className="setup__steps"> <li> <p>Create a component file called HomeScreen.js and add migrate the code from entry to our new component.</p> <Highlight lang='javascript' value={HomeScreen} /> </li> <li> <p>Now update index.ios.js and index.android.ios</p> <Highlight lang='javascript' value={indexJs} /> </li> </ul> <p>We are now ready to implement our redux store!</p> </div> ) } } export default SearchUiView
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ObjectSpread.js
TondaHack/create-react-app
/** * 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, { Component } from 'react'; import PropTypes from 'prop-types'; function load(baseUser) { return [ { id: 1, name: '1', ...baseUser }, { id: 2, name: '2', ...baseUser }, { id: 3, name: '3', ...baseUser }, { id: 4, name: '4', ...baseUser }, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load({ age: 42 }); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-object-spread"> {this.state.users.map(user => ( <div key={user.id}>{user.name}: {user.age}</div> ))} </div> ); } }
examples/sidebar/app.js
rkaneriya/react-router
import React from 'react' import { createHistory, useBasename } from 'history' import { Router, Route, Link } from 'react-router' import data from './data' require('./app.css') const history = useBasename(createHistory)({ basename: '/sidebar' }) class Category extends React.Component { render() { const category = data.lookupCategory(this.props.params.category) return ( <div> <h1>{category.name}</h1> {this.props.children || ( <p>{category.description}</p> )} </div> ) } } class CategorySidebar extends React.Component { render() { const category = data.lookupCategory(this.props.params.category) return ( <div> <Link to="/">◀︎ Back</Link> <h2>{category.name} Items</h2> <ul> {category.items.map((item, index) => ( <li key={index}> <Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link> </li> ))} </ul> </div> ) } } class Item extends React.Component { render() { const { category, item } = this.props.params const menuItem = data.lookupItem(category, item) return ( <div> <h1>{menuItem.name}</h1> <p>${menuItem.price}</p> </div> ) } } class Index extends React.Component { render() { return ( <div> <h1>Sidebar</h1> <p> Routes can have multiple components, so that all portions of your UI can participate in the routing. </p> </div> ) } } class IndexSidebar extends React.Component { render() { return ( <div> <h2>Categories</h2> <ul> {data.getAll().map((category, index) => ( <li key={index}> <Link to={`/category/${category.name}`}>{category.name}</Link> </li> ))} </ul> </div> ) } } class App extends React.Component { render() { const { children } = this.props return ( <div> <div className="Sidebar"> {children ? children.sidebar : <IndexSidebar />} </div> <div className="Content"> {children ? children.content : <Index />} </div> </div> ) } } React.render(( <Router history={history}> <Route path="/" component={App}> <Route path="category/:category" components={{ content: Category, sidebar: CategorySidebar }}> <Route path=":item" component={Item} /> </Route> </Route> </Router> ), document.getElementById('example'))
examples/basic/index.js
hhhonzik/react-createjs
import React from 'react'; import { render } from 'react-dom'; import { App } from './App'; render(<App />, document.getElementById('main'));
app/components/ItemInput.js
dxu/electric-trumpet
import React from 'react' // renders a single list, handles the list of lists const ItemInput = React.createClass({ onKeyAddContent: function(evt) { if (evt.keyCode === 13 && !evt.shiftKey) { evt.preventDefault() this.props.dispatchAddItem({ // NOTE: ASSUMING CLIENT ONLY, no xss sanitization content: this._inputContentEl.innerHTML, archive_id: this.props.activeArchive.get('_id') }) this._inputContentEl.innerHTML = '' } }, onKeyAddTitle: function(evt) { if (evt.keyCode === 13) { evt.preventDefault() this.props.dispatchAddItem({ // NOTE: ASSUMING CLIENT ONLY, no xss sanitization title: this._inputTitleEl.value, archive_id: this.props.activeArchive.get('_id') }) this._inputTitleEl.value = '' } }, render: function() { const { activeArchive, displayArchive=false, contentPlaceholderText="" , titlePlaceholderText="" } = this.props return ( <div className="items-input" ref={ el => this._wrapperEl = el }> { displayArchive ? <p>Adding to { activeArchive.get('name') }</p> : null } <input className="items-input-title" contentEditable="true" placeholder={titlePlaceholderText} onKeyDown={ this.onKeyAddTitle } ref={ el => this._inputTitleEl = el } /> <div className="items-input-content" contentEditable="true" data-placeholder={contentPlaceholderText} onKeyDown={ this.onKeyAddTitle } ref={ el => this._inputContentEl = el }> </div> </div> ) } }) export default ItemInput
src/client.js
sandfox/webdebs-links
import React from 'react'; import Router from 'react-router'; import routes from './routes'; import fetchData from './utils/fetch-data'; let first = true; const rehydrate = () => { const data = window.DATA; delete window.DATA; return data; }; const render = (Root, state, data) => { React.render(<Root data={data} state={state} />, document.getElementById('app')); }; Router.run(routes, Router.HistoryLocation, (Root, state) => { if (first) { first = false; render(Root, state, rehydrate()); } else { fetchData(state).then((data) => { render(Root, state, data); }); } });
src/app.js
vk92kokil/My-react-boilerplate
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ /* eslint-disable */ import 'babel/polyfill'; import React from 'react'; import Router from 'react-router'; var Redirect = Router.Redirect; import FastClick from 'fastclick'; import App from './components/App'; import HomePage from './components/HomePage'; import NotFoundHandler from './components/NotFoundPage'; /* react tap event plugin !important for material ui*/ import injectTapEventPlugin from "react-tap-event-plugin"; injectTapEventPlugin(); var Route = Router.Route; var RouteHandler = Router.RouteHandler; var DefaultRoute = Router.DefaultRoute; var NotFoundRoute = Router.NotFoundRoute; var routes = ( <Route handler={App} path="/"> {/*<DefaultRoute name="home" handler={CrmApp} />*/} <Route path='/crm' handler={HomePage}/> <Redirect from='/' to='/crm'/> <NotFoundRoute handler={NotFoundHandler}/> </Route> ); function run () { Router.run(routes, Router.HistoryLocation , function(Handler,state) { React.render(<Handler/>, document.getElementById('app')); }); }; Promise.all([ new Promise((resolve) => { if (window.addEventListener) { window.addEventListener('DOMContentLoaded', resolve); } else { window.attachEvent('onload', resolve); } }).then(() => FastClick.attach(document.body)) ]).then(run);
src/browser/createRoutes.js
jks8787/react-redux-yay
import App from './app/App.react'; import Auth from './auth/Page.react'; import Firebase from './firebase/Page.react'; import Home from './home/Page.react'; import Me from './me/Page.react'; import NotFound from './notfound/Page.react'; import Profile from './me/Profile.react'; import React from 'react'; import Settings from './me/Settings.react'; import Todos from './todos/Page.react'; import { IndexRoute, Route } from 'react-router'; export default function createRoutes(getState) { const requireAuth = (nextState, replace) => { const loggedInUser = getState().users.viewer; if (!loggedInUser) { replace({ pathname: '/login', state: { nextPathname: nextState.location.pathname } }); } }; return ( <Route component={App} path="/"> <IndexRoute component={Home} /> <Route component={Auth} path="login" /> <Route component={Firebase} path="firebase" /> <Route component={Me} onEnter={requireAuth} path="me"> <Route component={Profile} path="profile" /> <Route component={Settings} path="settings" /> </Route> <Route component={Todos} path="todos" /> <Route component={NotFound} path="*" /> </Route> ); }
visualizations/mapWidgets/source/scripts/MapWidgetComponent.js
EITIorg/eiti
import React, { Component } from 'react'; import { renderToString } from 'react-dom/server'; import { Map, Marker, Popup, TileLayer, GeoJson } from 'react-leaflet'; import { countryGeoJson } from './data/countries.js'; //import { countryInfo } from './data/implementing_country.js'; import { helpers } from './helpers.js' ; import { translations } from './data/translations.js' ; import _ from 'underscore'; // Legend information import { indicator_list } from './data/indicator_list.js'; import { status } from './data/status.js'; import { status2 } from './data/status2.js'; import { online_oil_registry } from './data/online_oil_registry.js'; import { online_mining_registry } from './data/online_mining_registry.js'; import { online_contracts } from './data/online_contracts.js'; import { oil_volume } from './data/oil_volume.js'; import { gas_volume } from './data/gas_volume.js'; import { coal_volume } from './data/coal_volume.js'; import { gold_volume} from './data/gold_volume.js'; import { copper_volume } from './data/copper_volume.js'; import { revenue } from './data/revenue.js'; import { share_revenues } from './data/share_revenues.js'; import geostats from 'geostats'; export default class MapWidgetComponent extends Component { constructor() { super(); this.state = { initialized: false, indicator_id: 'status', valuetypes: 'fixed', baseMap: undefined, data: {}, latlng: { lat: 18.897489183755892, lng: 15.76171875 }, hasLocation: false, }; } componentWillMount() { jQuery.get(helpers.getEndPoint() + '?fields=id', function(result) { var calls = []; var results = []; for (var i = 0; i < result.count / helpers.getPageSize(); i++) { calls.push( jQuery.get(helpers.getEndPointPage(i + 1), function(result) { results.push(result.data); }) ); } jQuery.when.apply(null, calls).done(function() { var consolidated = []; results.forEach(function(r) { consolidated = consolidated.concat(r); }); var baseMap = ::this.decorate(consolidated, this.state.indicator_id, this.state.valuetypes); this.setState({ baseMap: baseMap, data: consolidated }); }.bind(this)); }.bind(this)); } decorate(data, indicator_id, valuetypes) { var countryGeoJsonProcessed = { "type" : "FeatureCollection", "metadata" : [], "features" : [] }; // Get Legend information var metadata = ::this.getValues(indicator_id); countryGeoJson.features.forEach(function(country) { var datapoint = _.find(data, function(v){ return v.iso3 === country.id;}); if(datapoint) { var indicator_value = 0; var indicator_unit = ''; switch(indicator_id) { case "status": indicator_value = datapoint.status ? datapoint.status.tid || 0: 0; break; case "online_oil_registry": if(datapoint.licenses) { var years = Object.keys(datapoint.licenses); var last = _.last(years); var yearData = datapoint.licenses[last]; indicator_value = yearData['Public registry of licences, oil'] !== undefined; } break; case "online_mining_registry": if(datapoint.licenses) { var years = Object.keys(datapoint.licenses); var last = _.last(years); var yearData = datapoint.licenses[last]; indicator_value = yearData['Public registry of licences, mining'] !== undefined; } break; case "online_contracts": if(datapoint.contracts) { var years = Object.keys(datapoint.contracts); var last = _.last(years); var yearData = datapoint.contracts[last]; indicator_value = yearData['Publicly available registry of contracts'] !== undefined; } break; case "oil_volume": if(datapoint.reports && Object.keys(datapoint.reports).length > 0) { var years = Object.keys(datapoint.reports); var last = _.last(years); var yearData = datapoint.reports[last]; var indicator = yearData.find(function(v){ return (v.commodity === "Oil, volume" && v.unit && v.unit.toLowerCase() === 'sm3')}); indicator_value = indicator ? indicator.value : 0; indicator_unit = indicator ? indicator.unit : 0; } break; case "gas_volume": if(datapoint.reports && Object.keys(datapoint.reports).length > 0) { var years = Object.keys(datapoint.reports); var last = _.last(years); var yearData = datapoint.reports[last]; var indicator = yearData.find(function(v){ return (v.commodity === "Gas, volume" && v.unit && v.unit.toLowerCase() === 'sm3')}); indicator_value = indicator ? indicator.value : 0; indicator_unit = indicator ? indicator.unit : 0; } break; case "coal_volume": if(datapoint.reports && Object.keys(datapoint.reports).length > 0) { var years = Object.keys(datapoint.reports); var last = _.last(years); var yearData = datapoint.reports[last]; var indicator = yearData.find(function(v){return (v.commodity === "Coal, volume" && v.unit && (v.unit.toLowerCase() === 'tonne' || v.unit.toLowerCase() === 'tonnes' || v.unit.toLowerCase() === 'tons'))}); indicator_value = indicator ? indicator.value : 0; indicator_unit = indicator ? indicator.unit : 0; } break; case "gold_volume": if(datapoint.reports && Object.keys(datapoint.reports).length > 0) { var years = Object.keys(datapoint.reports); var last = _.last(years); var yearData = datapoint.reports[last]; var indicator = yearData.find(function(v){ return (v.commodity === "Gold, volume" && v.unit && (v.unit.toLowerCase() === 'tonne' || v.unit.toLowerCase() === 'tonnes' || v.unit.toLowerCase() === 'tons'))}); indicator_value = indicator ? indicator.value : 0; indicator_unit = indicator ? indicator.unit : 0; } break; case "copper_volume": if(datapoint.reports && Object.keys(datapoint.reports).length > 0) { var years = Object.keys(datapoint.reports); var last = _.last(years); var yearData = datapoint.reports[last]; var indicator = yearData.find(function(v){ return (v.commodity === "Copper, volume" && v.unit && (v.unit.toLowerCase() === 'tonne' || v.unit.toLowerCase() === 'tonnes' || v.unit.toLowerCase() === 'tons'))}); indicator_value = indicator ? indicator.value : 0; indicator_unit = indicator ? indicator.unit : 0; } break; case "revenue": if(datapoint.revenues) { var years = Object.keys(datapoint.revenues); var last = _.last(years); var yearData = datapoint.revenues[last]; var indicator = yearData.government; indicator_value = indicator; indicator_unit = 'USD'; } break; case "share_revenues": if(datapoint.revenues && datapoint.reports) { var years = Object.keys(datapoint.revenues); var last = _.last(years); var yearData = datapoint.revenues[last]; var generalYearData = datapoint.reports[last]; var indicator_government = yearData.government; var indicator_allsectors = generalYearData ? generalYearData.find(function(v){ return (v.commodity === "Government revenue - all sectors")}) : undefined; if(indicator_government && indicator_allsectors && indicator_allsectors.value !== 0 && indicator_government !== 0 && indicator_allsectors.unit === 'USD') { indicator_value = indicator_government*100/indicator_allsectors.value; } else { indicator_value = 'n/a'; } indicator_unit = ''; } break; } var indicator_type = valuetypes; country['indicator_type'] = valuetypes; country['indicator_value'] = indicator_value; country['indicator_unit'] = indicator_unit; } countryGeoJsonProcessed.features.push(country); }.bind(this)); if(valuetypes === 'range') { // Update metadata with ranges metadata = this.updateMetadata(countryGeoJsonProcessed, metadata); } // Assign color with the new metadata countryGeoJsonProcessed.features.forEach(function(feature) { var indicator_color; indicator_color = ::this.getColor(feature.indicator_type, feature.indicator_value, metadata, indicator_id); feature['indicator_color'] = indicator_color; }.bind(this)); return countryGeoJsonProcessed; } updateMetadata(data, metadata) { //var values = _.map(_.pluck(data.features, 'indicator_value'),function(v){ return v?v*1:0;}); var part = _.pluck(data.features, 'indicator_unit'); var unit = _.find(part, function(v) { return v !== undefined && v !== "" && v !== 0;}); //var classifier = new geostats(values); //var ranges = classifier.getEqInterval(metadata.length); for(var i=0; i< metadata.length;i++) { metadata[i].unit = unit; //metadata[i].range.start = ranges[i]; //metadata[i].range.end = ranges[i+1]; //metadata[i].title = helpers.formatNumber(ranges[i]) + ' - ' + helpers.formatNumber(ranges[i+1]); } return metadata; } addLayer(e) { //Deactivate anything selected jQuery('.map-option-wrapper').find("LI").removeClass('active') //Activate current selected jQuery(e.target).parents("LI").addClass('active'); //Activate itself jQuery(e.target).addClass('active') if(this.removeLayer) this.removeLayer(); const map = this.refs['map'].leafletElement; var indicator_id = e.target.dataset ? e.target.dataset.indicatorid : e.target.getAttribute("data-indicatorid"); var valuetypes = e.target.dataset ? e.target.dataset.valuetypes : e.target.getAttribute("data-valuetypes"); var countryDataProcessed = ::this.decorate(this.state.data, indicator_id, valuetypes); const hoverDecider = this.props.infobox ? function(feature, layer){this.onEachFeaturePage(feature, layer)}.bind(this) : function(feature, layer){this.onEachFeatureStatus(feature, layer)}.bind(this); ::this.updateLegend(e, indicator_id); if (this.props.buttons) { ::this.updateCountriesList(e, countryDataProcessed); } this.refs['geoJsonLayer'].leafletElement = L.geoJson(countryDataProcessed, {style:helpers.style, onEachFeature:hoverDecider}).addTo(map); } getValues(indicator_id) { var values; switch(indicator_id) { case "status": values = status; if(this.props.selector) { values = status2; } break; case "online_oil_registry": values = online_oil_registry; break; case "online_mining_registry": values = online_mining_registry; break; case "online_contracts": values = online_contracts; break; case "oil_volume": values = oil_volume; break; case "gas_volume": values = gas_volume; break; case "coal_volume": values = coal_volume; break; case "gold_volume": values = gold_volume; break; case "copper_volume": values = copper_volume; break; case "revenue": values = revenue; break; case "share_revenues": values = share_revenues; break; } return values; } removeLayer() { const map = this.refs['map'].leafletElement; const geoJsonLayer = this.refs['geoJsonLayer'].leafletElement; map.removeLayer(geoJsonLayer); } legend(indicator_id) { // For simple status/overview map. if (indicator_id == 'status' && !this.props.buttons) { var legend = document.createElement("DIV"); var h2El_2 = document.createElement("H2"); h2El_2.innerText = helpers.t('EITI members'); var indicatorHeader = '<a href="/countries">Click here to view the full interactive map</a>'; var mergedHTML = ""; var headerText = '<div class="legend_header" >' + helpers.t(indicatorHeader) + "</div>"; mergedHTML += headerText; var divLegendBody = document.createElement("DIV"); divLegendBody.className = "inner"; divLegendBody.innerHTML = mergedHTML; legend.appendChild(h2El_2); legend.appendChild(divLegendBody); return legend; } var legend = document.createElement("DIV"); var indicatorMetadata; indicatorMetadata = ::this.getValues(indicator_id || this.state.indicator_id); var indicatorData = ::this.getIndicatorData(indicator_id || this.state.indicator_id) var indicatorDescription = indicatorData["description"]; var indicatorHeader = indicatorData["header"]; var indicatorFooter = indicatorData["footer"]; var unit = _.find(_.pluck(indicatorMetadata, 'unit'), function(v) {return v !== undefined}); var h2El_2 = document.createElement("H2"); h2El_2.innerText = helpers.t(indicatorDescription) + " " + (unit ? "("+unit+ ")" : ""); var mergedHTML = ""; var headerText = '<div class="legend_header" >' + helpers.t(indicatorHeader) + "</div>"; mergedHTML += headerText; var noDataIncluded = false; indicatorMetadata.forEach(function(v) { noDataIncluded = (v.color === "#dddddd" && noDataIncluded === false) ? noDataIncluded = true : false; if(v.use_style) { mergedHTML += '<i class="' + v.title.toLowerCase().replace(/<[^>]*>/g, "").replace(/\/| /g,"_") + '"></i> <div class="legend_title">'+helpers.t(v.title)+ '<br/></div>'; } else { mergedHTML += '<i style="background:' + v.color + '"></i> <div class="legend_title">'+helpers.t(v.title)+ '<br/></div>'; } if(v.subtitle != "") { mergedHTML += (helpers.t(v.subtitle) || '') + '<br>'; } }); var footerText = '<div class="legend_footer" >' + helpers.t(indicatorFooter) + "</div>"; mergedHTML += footerText; var sourceText = '<a class="legend_source" href="/data">' + helpers.t('Source: EITI summary data') + "</a>"; var divLegendBody = document.createElement("DIV"); divLegendBody.className = "inner"; divLegendBody.innerHTML = mergedHTML + sourceText; legend.appendChild(h2El_2); legend.appendChild(divLegendBody); return legend; } updateLegend(e, indicator_id) { var legend = this.legend(indicator_id); var legend_wrapper = jQuery(e.target).closest('.eiti-map-wrapper').find('.top.legend'); legend_wrapper.html(legend.innerHTML); } getIndicatorData(indicator_id){ var current_indicator = _.find(indicator_list, function(v){ return (v.name == indicator_id)}); return current_indicator; } onEachFeaturePage(feature, layer) { layer.on({ mouseover: function(e){ helpers.showHint(e) }, mouseout: helpers.resetTooltip, click: function(e){ helpers.showInfobox(e, this.state.data) }.bind(this) }); } onEachFeatureStatus(feature, layer) { var data = this.state.data; layer.on({ mouseover: function(e){ helpers.showTooltipStatus(e, data) }, mouseout: helpers.resetTooltip, click: function(e){ helpers.zoomToFeature(e, data) } }); } getColor(indicator_type, indicator_value, metadata, indicator_id) { if(indicator_type == 'fixed') { var i_val = indicator_value; // Limit overview to 2 colors together with status.js changes. if (indicator_id == 'status' && !this.props.buttons) { i_val = 0; if (this.isNumeric(indicator_value) && jQuery.inArray(indicator_value, ['5329', '75', '74', '5327', '8212', '8213']) > -1) { i_val = 1; } } var completeType = _.find(metadata, function(v){ return (v.id == i_val)}); return completeType ? completeType.color: '#dddddd'; } else { if (metadata === undefined) return; if(this.isNumeric(indicator_value)) { var value = Number(indicator_value); var completeType = _.find(metadata, function(v){ return value > v.range.start && (!v.range.end || value <= v.range.end);}); return completeType !== undefined ? completeType.color : '#dddddd'; } else { return '#dddddd'; } } } isNumeric( obj ) { return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; } getCountriesList(countryDataProcessed) { var selector; if(this.props.selector) { var listed_countries = []; if (countryDataProcessed) { for (var i = 0; i < countryDataProcessed.features.length; i++) { if (countryDataProcessed.features[i].indicator_value) { if (countryDataProcessed.features[i].indicator_value != 0 && countryDataProcessed.features[i].indicator_value != 'n/a') { listed_countries[countryDataProcessed.features[i].id] = []; listed_countries[countryDataProcessed.features[i].id]['value'] = countryDataProcessed.features[i].indicator_value; listed_countries[countryDataProcessed.features[i].id]['color'] = countryDataProcessed.features[i].indicator_color; } } } } var items = []; var cols = []; var countries = _.sortBy(this.state.data, 'label'); var sortedCountries = countries.filter(function(k,v){ return (k.status.name !== "Other")}); if (countryDataProcessed) { sortedCountries = countries.filter(function(k,v){ return (listed_countries[k.iso3] !== undefined)}); } var cutout = Math.ceil(sortedCountries.length/4); for (var i = 0; i < sortedCountries.length;i++) { var itemStyle = sortedCountries[i].status ? "member-status " + sortedCountries[i].status.name.toLowerCase().replace(/\/| /g,"_") : "member-status other"; var inlineStyles = {}; if (countryDataProcessed) { inlineStyles = { background: listed_countries[sortedCountries[i].iso3]['color'] } } else if (sortedCountries[i].status.name === "Other") { continue; } var countryPageURL = "/implementing_country/" + sortedCountries[i].id; var years = Object.keys(sortedCountries[i].metadata); var last = _.last(years); var yearData = sortedCountries[i].metadata[last]; // If there's an attached report to the implementing country, use that one. If not, look for it in the metadata var reportURL = sortedCountries[i].annual_report_file; var reportClass = ""; if(reportURL === undefined || reportURL === null) { var reportObj = yearData && yearData.web_report_links && yearData.web_report_links.length > 0 ? _.first(yearData.web_report_links) : undefined; reportURL = reportObj ? reportObj.url : ""; reportClass = reportObj ? "" : "empty"; } var country_name = helpers.t(sortedCountries[i].label); items.push( <li> <span style={inlineStyles} className={itemStyle}></span> <a href={countryPageURL}>{country_name}</a> </li> ); if((i+1)%cutout === 0 || i+1 === sortedCountries.length) { cols.push( <div className="country-col"> <ul className="country-list"> {items} </ul> </div> ); items = []; } } //Divide in columns by 4 selector = ( <div className="country-list-wrapper clearfix"> {cols} </div> ); return selector; } } updateCountriesList(e, countryDataProcessed) { if (jQuery(e.target).data('indicatorid') == 'status') { var selector = this.getCountriesList(); } else { var selector = this.getCountriesList(countryDataProcessed); } var list_wrapper = jQuery(e.target).closest('.eiti-map-wrapper').find('.country-list-wrapper'); list_wrapper.replaceWith(renderToString(selector)); } filterToggleOpen(e) { jQuery(e.target).closest('li').toggleClass('open'); } render() { //if(!this.state || !this.state.baseMap) return; const hoverDecider = this.props.infobox ? function(feature, layer){this.onEachFeaturePage(feature, layer)}.bind(this) : function(feature, layer){this.onEachFeatureStatus(feature, layer)}.bind(this); var geoJsonLayer; if(this.state.baseMap === undefined) { geoJsonLayer == null; } else { geoJsonLayer = <GeoJson data={this.state.baseMap} ref='geoJsonLayer' onEachFeature={hoverDecider} style={helpers.style}></GeoJson>; } var buttons; if(this.props.buttons) { buttons = (<div className="map-option-wrapper"> <h2>{helpers.t('Apply filter')}</h2> <ul className="map-option-widget"> <li data-indicatorid="status" data-valuetypes="fixed" onClick={::this.addLayer} className="simple active"> {helpers.t('Implementation status')} </li> <li className="open"> <span onClick={::this.filterToggleOpen}>{helpers.t('Tax & Legal Framework')}</span> <ul className="map-option-items"> <li data-indicatorid="online_oil_registry" data-valuetypes="fixed" onClick={::this.addLayer}>{helpers.t('Online oil registry')}</li> <li data-indicatorid="online_mining_registry" data-valuetypes="fixed" onClick={::this.addLayer}>{helpers.t('Online mining registry')}</li> <li data-indicatorid="online_contracts" data-valuetypes="fixed" onClick={::this.addLayer}>{helpers.t('Online registry of contracts')}</li> </ul> </li> <li className="open"> <span onClick={::this.filterToggleOpen}>{helpers.t('Production')}</span> <ul className="map-option-items"> <li data-indicatorid="oil_volume" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Oil, volume')}</li> <li data-indicatorid="gas_volume" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Gas, volume')}</li> <li data-indicatorid="coal_volume" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Coal, tons')}</li> <li data-indicatorid="gold_volume" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Gold, tons')}</li> <li data-indicatorid="copper_volume" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Copper, tons')}</li> </ul> </li> <li className="open"> <span onClick={::this.filterToggleOpen}>{helpers.t('Revenues')}</span> <ul className="map-option-items"> <li data-indicatorid="revenue" data-valuetypes="range" onClick={::this.addLayer}>{helpers.t('Government extractives revenue')}</li> <li data-indicatorid="share_revenues" data-valuetypes="percentage" onClick={::this.addLayer}>{helpers.t('Share of revenues')}</li> </ul> </li> </ul> </div>); } /* var reportLink = (<svg id="country-report-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160"> <rect x="4.8" y="4" className="st0" width="115" height="151.6"/> <rect x="4.8" y="4" className="st0" width="20.9" height="151.6"/> <rect x="44" y="30.1" className="st0" width="57.5" height="31.4"/> <line className="st0" x1="54.5" y1="40.6" x2="91.1" y2="40.6"/> <line className="st0" x1="54.5" y1="51" x2="91.1" y2="51"/> </svg>);*/ var selector = this.getCountriesList(); var screenWidth = (window.innerWidth > 0) ? window.innerWidth : screen.width; var zoom = 3; if(this.props.buttons) { zoom = 2; } var min_zoom = 2; if(screenWidth <= 400) { zoom = 1; min_zoom = 1; } // If there's a selector, add the responsive classes. var containerClass = 'map-container'; var elementClass = 'map'; if(selector) { containerClass = 'map-container media-resizable-element'; elementClass = 'resizable-map'; } var legend = this.legend(this.state.indicator_id); var map_output = ( <Map className={elementClass} center={this.state.latlng} length={4} ref='map' zoom={zoom} maxZoom={8} minZoom={min_zoom} height={500} scrollWheelZoom={false} maxBounds={[[-84, -180], [90, 180]]} maxBoundsViscosity={0.8} > <TileLayer url='' onLeafletLoad={function(e) { if(!this.state.initialized) { this.setState({initialized:true}); } }.bind(this)} /> {geoJsonLayer} </Map> ); if (buttons) { return ( <div className={containerClass}> <div className="map-data"> <div className="legend top" dangerouslySetInnerHTML={{__html: legend.innerHTML}}></div> <div className="map-wrap"> {map_output} </div> </div> {buttons} {selector} </div> ); } else { return ( <div className={containerClass}> <div className="legend top" dangerouslySetInnerHTML={{__html: legend.innerHTML}}></div> <div className="map-wrap"> {map_output} </div> {selector} </div> ); } } }
frontend/app/components/Phrasebook/edit.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' import Immutable from 'immutable' import ProviderHelpers from 'common/ProviderHelpers' import StateLoading from 'components/Loading' import StateErrorBoundary from 'components/ErrorBoundary' import StateSuccessEdit from './states/successEdit' import StateSuccessDelete from './states/successDelete' import StateEdit from './states/create' import AuthenticationFilter from 'components/AuthenticationFilter' import PromiseWrapper from 'components/PromiseWrapper' // REDUX import { connect } from 'react-redux' // REDUX: actions/dispatch/func import { createCategory, deleteCategory, fetchCategory, fetchCategories, updateCategory } from 'reducers/fvCategory' import { fetchDialect, fetchDialect2 } from 'reducers/fvDialect' import { pushWindowPath } from 'reducers/windowPath' import selectn from 'selectn' import { getFormData, handleSubmit } from 'common/FormHelpers' // Models import { Document } from 'nuxeo' import { STATE_LOADING, STATE_DEFAULT, STATE_ERROR, STATE_SUCCESS, STATE_SUCCESS_DELETE, STATE_ERROR_BOUNDARY, DEFAULT_PAGE, DEFAULT_PAGE_SIZE, DEFAULT_LANGUAGE, DEFAULT_SORT_COL, DEFAULT_SORT_TYPE, } from 'common/Constants' import './Phrasebook.css' const { array, element, func, number, object, string } = PropTypes export class PhrasebookEdit extends React.Component { static propTypes = { className: string, copy: object, groupName: string, breadcrumb: element, DEFAULT_PAGE: number, DEFAULT_PAGE_SIZE: number, DEFAULT_LANGUAGE: string, DEFAULT_SORT_COL: string, DEFAULT_SORT_TYPE: string, onDocumentCreated: func, validator: object, createUrl: string, // REDUX: reducers/state computeCategory: object.isRequired, computeCategories: object.isRequired, computeCreateCategory: object, computeDialect: object.isRequired, computeDialect2: object.isRequired, routeParams: object.isRequired, splitWindowPath: array.isRequired, // REDUX: actions/dispatch/func createCategory: func.isRequired, deleteCategory: func.isRequired, fetchCategory: func.isRequired, fetchCategories: func.isRequired, fetchDialect: func.isRequired, fetchDialect2: func.isRequired, pushWindowPath: func.isRequired, updateCategory: func.isRequired, } static defaultProps = { className: 'FormPhrasebook', groupName: '', breadcrumb: null, DEFAULT_PAGE, DEFAULT_PAGE_SIZE, DEFAULT_LANGUAGE, DEFAULT_SORT_COL, DEFAULT_SORT_TYPE, } _commonInitialState = { errors: [], formData: {}, isBusy: false, is403: false, } state = { componentState: STATE_LOADING, ...this._commonInitialState, } // NOTE: Using callback refs since on old React // https://reactjs.org/docs/refs-and-the-dom.html#callback-refs form = null setFormRef = (_element) => { this.form = _element } async componentDidMount() { const copy = this.props.copy ? this.props.copy : await import(/* webpackChunkName: "PhrasebookCopy" */ './copy').then((_copy) => { return _copy.default }) const validator = this.props.validator ? this.props.validator : await import(/* webpackChunkName: "PhrasebookValidator" */ './validator').then((_validator) => { return _validator.default }) await this._getData({ copy, validator }) } render() { let content = null switch (this.state.componentState) { case STATE_DEFAULT: { content = this._stateGetEdit() break } case STATE_ERROR: { content = this._stateGetError() break } case STATE_SUCCESS: { content = this._stateGetSuccess() break } case STATE_SUCCESS_DELETE: { content = this._stateGetSuccessDelete() break } case STATE_ERROR_BOUNDARY: { // STATE_ERROR_BOUNDARY === server or authentication issue content = this._stateGetErrorBoundary() break } default: // STATE_LOADING === loading content = this._stateGetLoading() } return content } _getData = async (addToState = {}) => { // Do any loading here... const { routeParams } = this.props const { itemId } = routeParams await this.props.fetchDialect(`/${this.props.routeParams.dialect_path}`) await this.props.fetchCategory(itemId) const item = await this._getItem() if (item.isError) { this.setState({ componentState: STATE_DEFAULT, // Note: Intentional == comparison is403: item.message == '403', errorMessage: item.message, ...addToState, }) } else { this.setState({ errorMessage: undefined, componentState: STATE_DEFAULT, valueName: item.name, valueDescription: item.description, isTrashed: item.isTrashed, item: item.data, ...this._commonInitialState, ...addToState, }) } } _stateGetLoading = () => { const { className } = this.props return <StateLoading className={className} isEdit copy={this.state.copy} /> } _stateGetErrorBoundary = () => { // Make `errorBoundary.explanation` === `errorBoundary.explanationEdit` const _copy = Object.assign({}, this.state.copy) _copy.errorBoundary.explanation = this.state.copy.errorBoundary.explanationEdit return <StateErrorBoundary errorMessage={this.state.errorMessage} copy={this.state.copy} /> } _stateGetEdit = () => { const { className, breadcrumb, groupName } = this.props const { errors, isBusy, isTrashed, valueDescription, valueName } = this.state return ( <AuthenticationFilter.Container is403={this.state.is403} notAuthenticatedComponent={<StateErrorBoundary copy={this.state.copy} errorMessage={this.state.errorMessage} />} > <PromiseWrapper computeEntities={Immutable.fromJS([ { id: `/${this.props.routeParams.dialect_path}`, entity: this.props.fetchDialect, }, ])} > <StateEdit copy={this.state.copy} className={className} groupName={groupName} breadcrumb={breadcrumb} errors={errors} isBusy={isBusy} isTrashed={isTrashed} isEdit deleteItem={() => { this.props.deleteCategory(this.state.item.id) this.setState({ componentState: STATE_SUCCESS_DELETE, }) }} onRequestSaveForm={() => { this._onRequestSaveForm() }} setFormRef={this.setFormRef} valueName={valueName} valueDescription={valueDescription} /> </PromiseWrapper> </AuthenticationFilter.Container> ) } _stateGetError = () => { // default state handles errors, just call it... return this._stateGetEdit() } _stateGetSuccess = () => { const { className } = this.props const { formData, itemUid } = this.state return ( <StateSuccessEdit className={className} copy={this.state.copy} itemUid={itemUid} formData={formData} handleClick={() => { this._getData() }} /> ) } _stateGetSuccessDelete = () => { const { createUrl, className, routeParams } = this.props const { formData } = this.state const { siteTheme, dialect_path } = routeParams const _createUrl = createUrl || `/${siteTheme}${dialect_path}/create/phrasebook` return ( <StateSuccessDelete createUrl={_createUrl} className={className} copy={this.state.copy} formData={formData} /> ) } async _handleCreateItemSubmit(formData) { const { item } = this.state const newDocument = new Document(item.response, { repository: item.response._repository, nuxeo: item.response._nuxeo, }) // Set new value property on document newDocument.set({ 'dc:description': formData['dc:description'], 'dc:title': formData['dc:title'], }) // Save document const _updateCategory = await this.props.updateCategory(newDocument, null, null) if (_updateCategory.success) { this.setState({ errors: [], formData, itemUid: _updateCategory.pathOrId, componentState: STATE_SUCCESS, }) } else { this.setState({ componentState: STATE_ERROR_BOUNDARY, errorMessage: _updateCategory.message, }) } } _onRequestSaveForm = async () => { const formData = getFormData({ formReference: this.form, }) const valid = () => { this.setState( { isBusy: true, }, () => { this._handleCreateItemSubmit(formData) } ) } const invalid = (response) => { this.setState({ errors: response.errors, componentState: STATE_ERROR, }) } handleSubmit({ validator: this.state.validator, formData, valid, invalid, }) } _getItem = async () => { const { computeCategory, routeParams } = this.props const { itemId } = routeParams // Extract data from immutable: const _computeCategory = await ProviderHelpers.getEntry(computeCategory, itemId) if (_computeCategory.success) { // Extract data from object: const name = selectn(['response', 'properties', 'dc:title'], _computeCategory) const description = selectn(['response', 'properties', 'dc:description'], _computeCategory) const isTrashed = selectn(['response', 'isTrashed'], _computeCategory) // Respond... return { isError: _computeCategory.isError, name, description, isTrashed, data: _computeCategory, } } return { isError: _computeCategory.isError, message: _computeCategory.message } } } // REDUX: reducers/state const mapStateToProps = (state /*, ownProps*/) => { const { fvCategory, fvDialect, navigation, windowPath } = state const { computeCategory, computeCategories, computeCreateCategory } = fvCategory const { computeDialect, computeDialect2 } = fvDialect const { splitWindowPath } = windowPath const { route } = navigation return { computeCategory, computeCategories, computeCreateCategory, computeDialect, computeDialect2, routeParams: route.routeParams, splitWindowPath, } } // REDUX: actions/dispatch/func const mapDispatchToProps = { createCategory, deleteCategory, fetchCategory, fetchCategories, fetchDialect, fetchDialect2, pushWindowPath, updateCategory, } export default connect(mapStateToProps, mapDispatchToProps)(PhrasebookEdit)
client/Pets.js
lizraeli/react-personal-boilerplate
import React from 'react' import { Card, CardImage, Text, Heading, Section } from 'rebass' import { Grid, Row, Col } from 'react-flexbox-grid'; const Pets = () => ( <Section> <Row center="xs"> <Col xs={12} sm={3}> <Card> <CardImage width={256} src={require('./photos/fred.jpeg')} /> <Heading level={3}> Fred </Heading> <Text> First puppy </Text> </Card> </Col> <Col xs={12} sm={3}> <Card> <CardImage width={256} src={require('./photos/george.jpeg')} /> <Heading level={3}> George </Heading> <Text> Second puppy </Text> </Card> </Col> </Row> </Section> ) export default Pets
src/components/topic/UpdateForStorySearchWarning.js
mitmedialab/MediaCloud-Web-Tools
import React from 'react'; import { FormattedMessage, FormattedHTMLMessage } from 'react-intl'; import { WarningNotice } from '../common/Notice'; const localMessages = { title: { id: 'errors.storySwitchover.title', defaultMessage: 'Update for Story-Level Searches' }, intro: { id: 'errors.storySwitchover.intro', defaultMessage: '<b>Your topic query needs to be checked because we have switched to story-level searches.</b>' }, details: { id: 'errors.storySwitchover.details', defaultMessage: 'When you last ran your topic we searched at the sentence level. Since then we have switched over to do everything at the story level, because that is what most people tell us they want. This also helps us save space and make things faster (<a target="_new" href="https://mediacloud.org/news/2018/4/12/switching-to-story-based-searching-on-may-12th">learn more about this change</a>). If your seed query relied on finding multiple words in the same sentence you need to update it.' }, }; const UpdateForStorySearchWarning = () => ( <div className="story-switchover"> <WarningNotice> <p className="title"><FormattedMessage {...localMessages.title} /></p> <p><FormattedHTMLMessage {...localMessages.intro} /></p> <p><FormattedHTMLMessage {...localMessages.details} /></p> </WarningNotice> </div> ); export default UpdateForStorySearchWarning;
resources/js/react/search/SearchResultListItem.js
chekun/spore
import React from 'react'; var Avatar = require('../Avatar'); //<SearchResultListItem item=[] /> class SearchResultListItem extends React.Component { render() { var item = this.props.item; if (item["title"]) { item.type = 3; } else if (item["intro"]) { item.type = 2; } else { item.type = 1; } switch (item.type) { case 1: return ( <a href="javascript:void(0);" className="list-group-item"> <Avatar width="30" height="30" icon={item.icon} alt={item.name} /> <span>用户</span>: {item.name} </a> ); break; case 2: var link = "http://baoz.cn/" + item.id; return ( <a href={link} target="_blank" className="list-group-item"> <Avatar width="30" height="30" icon={item.icon} alt={item.name} /> <span>群组</span>: {item.name} </a> ); break; case 3: var link = "http://baoz.cn/" + item.id; return ( <a href={link} target="_blank" className="list-group-item"> <span>帖子</span>: {item.title} </a> ); } } } export default SearchResultListItem
create-react-app/src/router.js
wumouren/react-demo
// import React, { Component } from 'react'; import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import App from './components/app/App'; import Home from './components/home/Home'; // 两种写法都可以 // export default class Routers extends Component { // render() { // return ( // <Router> // <Switch> // <Route exact path='/' component={App}/> // </Switch> // </Router> // ); // } // } const Routers = () => { return ( <Router> <Switch> <Route exact path='/' component={App}/> <Route exact path='/home' component={Home}/> </Switch> </Router> ); } export default Routers;
src/componentOrElement.js
react-bootstrap/prop-types-extra
import React from 'react'; import createChainableTypeChecker from './utils/createChainableTypeChecker'; function validate(props, propName, componentName, location, propFullName) { const propValue = props[propName]; const propType = typeof propValue; if (React.isValidElement(propValue)) { return new Error( `Invalid ${location} \`${propFullName}\` of type ReactElement ` + `supplied to \`${componentName}\`, expected a ReactComponent or a ` + 'DOMElement. You can usually obtain a ReactComponent or DOMElement ' + 'from a ReactElement by attaching a ref to it.', ); } if ( (propType !== 'object' || typeof propValue.render !== 'function') && propValue.nodeType !== 1 ) { return new Error( `Invalid ${location} \`${propFullName}\` of value \`${propValue}\` ` + `supplied to \`${componentName}\`, expected a ReactComponent or a ` + 'DOMElement.', ); } return null; } export default createChainableTypeChecker(validate);
demo/containers/badges-icons.js
nbonamy/react-native-app-components
import React, { Component } from 'react'; import { StyleSheet, ScrollView, View, Text } from 'react-native'; import { theme, Badge, Icon } from 'react-native-app-components'; export default class BadgesIcons extends Component { constructor(props) { super(props); } render() { return ( <ScrollView style={{paddingBottom: 32, paddingLeft: 16, paddingRight: 16}}> <View style={{flexDirection: 'column'}}> <Text style={styles.title}>BADGES</Text> <View style={{flexDirection: 'row', flexWrap: 'wrap'}}> <Badge primary style={styles.badge}>0</Badge> <Badge info style={styles.badge}>1</Badge> <Badge success style={styles.badge}>2</Badge> <Badge warning style={styles.badge}>3</Badge> <Badge danger style={styles.badge}>4</Badge> </View> </View> <View style={{flexDirection: 'column'}}> <Text style={styles.title}>ICONS</Text> <View style={{flexDirection: 'row', flexWrap: 'wrap'}}> <Icon name="add-circle" color={theme.colors.primary} size={32} style={styles.icon} /> <Icon name="md-alert" color={theme.colors.danger} size={32} style={styles.icon} /> <Icon font="entypo" name="archive" color={theme.colors.success} size={32} style={styles.icon} /> </View> </View> </ScrollView> ); } } const styles = StyleSheet.create({ title: { fontSize: 18, marginTop: 32, marginBottom: 16, color: theme.colors.dark, }, badge: { margin: 8, }, icon: { margin: 8, }, });
app/javascript/mastodon/containers/admin_component.js
Kirishima21/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { IntlProvider, addLocaleData } from 'react-intl'; import { getLocale } from '../locales'; const { localeData, messages } = getLocale(); addLocaleData(localeData); export default class AdminComponent extends React.PureComponent { static propTypes = { locale: PropTypes.string.isRequired, children: PropTypes.node.isRequired, }; render () { const { locale, children } = this.props; return ( <IntlProvider locale={locale} messages={messages}> {children} </IntlProvider> ); } }
4.2.0/src/routes.js
erikras/redux-form-docs
import React from 'react' import { Router, Route, hashHistory } from 'react-router' import markdownPage from 'components/markdownPage' import App from 'pages/App' import Home from 'pages/Home' import Simple from 'pages/examples/Simple' import ComplexValues from 'pages/examples/ComplexValues' import File from 'pages/examples/File' import Wizard from 'pages/examples/Wizard' import Deep from 'pages/examples/Deep' import SynchronousValidation from 'pages/examples/SynchronousValidation' import SubmitFromParent from 'pages/examples/SubmitFromParent' import SubmitValidation from 'pages/examples/SubmitValidation' import AsynchronousBlurValidation from 'pages/examples/AsynchronousBlurValidation' import AlternateMountPoint from 'pages/examples/AlternateMountPoint' import Multirecord from 'pages/examples/Multirecord' import Normalizing from 'pages/examples/Normalizing' import Dynamic from 'pages/examples/Dynamic' import InitializingFromState from 'pages/examples/InitializingFromState' import Examples from 'pages/examples/Examples.md' import Faq from 'pages/faq/Faq.md' import FaqEnterToSubmit from 'pages/faq/EnterToSubmit.md' import FaqSubmitFunction from 'pages/faq/SubmitFunction.md' import FaqHandleVsOn from 'pages/faq/HandleVsOn.md' import FaqHowToClear from 'pages/faq/HowToClear.md' import FaqReactNative from 'pages/faq/ReactNative.md' import FaqImmutableJs from 'pages/faq/ImmutableJs.md' import FaqCustomComponent from 'pages/faq/CustomComponent.md' import FaqWebsockets from 'pages/faq/WebsocketSubmit.md' import GettingStarted from 'pages/GettingStarted.md' import Api from 'pages/api/Api.md' import ApiReduxForm from 'pages/api/ReduxForm.md' import ApiReducer from 'pages/api/Reducer.md' import ApiReducerNormalize from 'pages/api/ReducerNormalize.md' import ApiReducerPlugin from 'pages/api/ReducerPlugin.md' import ApiProps from 'pages/api/Props.md' import ApiActionCreators from 'pages/api/ActionCreators.md' import ApiGetValues from 'pages/api/GetValues.md' const routes = ( <Router history={hashHistory}> <Route component={App}> <Route path="/" component={Home}/> <Route path="/api" component={markdownPage(Api)}/> <Route path="/api/action-creators" component={markdownPage(ApiActionCreators)}/> <Route path="/api/get-values" component={markdownPage(ApiGetValues)}/> <Route path="/api/props" component={markdownPage(ApiProps)}/> <Route path="/api/reduxForm" component={markdownPage(ApiReduxForm)}/> <Route path="/api/reducer" component={markdownPage(ApiReducer)}/> <Route path="/api/reducer/normalize" component={markdownPage(ApiReducerNormalize)}/> <Route path="/api/reducer/plugin" component={markdownPage(ApiReducerPlugin)}/> <Route path="/getting-started" component={markdownPage(GettingStarted)}/> <Route path="/examples" component={markdownPage(Examples)}/> <Route path="/examples/asynchronous-blur-validation" component={AsynchronousBlurValidation}/> <Route path="/examples/alternate-mount-point" component={AlternateMountPoint}/> <Route path="/examples/deep" component={Deep}/> <Route path="/examples/initializing-from-state" component={InitializingFromState}/> <Route path="/examples/dynamic" component={Dynamic}/> <Route path="/examples/multirecord" component={Multirecord}/> <Route path="/examples/normalizing" component={Normalizing}/> <Route path="/examples/simple" component={Simple}/> <Route path="/examples/complex" component={ComplexValues}/> <Route path="/examples/file" component={File}/> <Route path="/examples/wizard" component={Wizard}/> <Route path="/examples/submit-validation" component={SubmitValidation}/> <Route path="/examples/synchronous-validation" component={SynchronousValidation}/> <Route path="/examples/submit-from-parent" component={SubmitFromParent}/> <Route path="/faq" component={markdownPage(Faq)}/> <Route path="/faq/submit-function" component={markdownPage(FaqSubmitFunction)}/> <Route path="/faq/handle-vs-on" component={markdownPage(FaqHandleVsOn)}/> <Route path="/faq/how-to-clear" component={markdownPage(FaqHowToClear)}/> <Route path="/faq/enter-to-submit" component={markdownPage(FaqEnterToSubmit)}/> <Route path="/faq/immutable-js" component={markdownPage(FaqImmutableJs)}/> <Route path="/faq/react-native" component={markdownPage(FaqReactNative)}/> <Route path="/faq/custom-component" component={markdownPage(FaqCustomComponent)}/> <Route path="/faq/websockets" component={markdownPage(FaqWebsockets)}/> <Route path="*" component={Home}/> </Route> </Router> ) export default routes
packages/react/src/components/Portal/__tests__/Portal-test.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import { render, screen } from '@testing-library/react'; import React from 'react'; import { Portal } from '../'; describe('Portal', () => { it('should render its children in the document', () => { render( <Portal> <span data-testid="test" /> </Portal> ); expect(screen.getByTestId('test')).toBeInTheDocument(); }); it('should support rendering in a custom container', () => { const container = document.createElement('div'); document.body.appendChild(container); function TestComponent() { const ref = React.useRef(null); if (ref.current === null) { ref.current = container; } return ( <Portal container={ref}> <span data-testid="test" /> </Portal> ); } render(<TestComponent />); expect(container).toContainElement(screen.getByTestId('test')); document.body.removeChild(container); }); });
src/containers/ProductHotItem/ProductHotItem.js
kingpowerclick/kpc-web-backend
import React, { Component } from 'react'; import classNames from 'classnames'; import { FilterPage, Breadcrumb } from 'components'; import { DropdownButton, MenuItem, Modal } from 'react-bootstrap'; export default class ProductHotItem extends Component { state = { displayCompleteModal: false, displayLineProductModal: false } handleOpenAddProductExcModal = () => { this.setState({ displayCompleteModal: true }); } handleCloseModal = () => { this.setState({ displayCompleteModal: false }); } handleOpenLineProductModal = () => { this.setState({ displayLineProductModal: true }); } handleCloseLineProductModal = () => { this.setState({ displayLineProductModal: false }); } handleOpenModal = (styles) => { const { displayCompleteModal } = this.state; return ( <Modal show={ displayCompleteModal } dialogClassName={ styles['addproduct-modal'] } > <Modal.Header> <Modal.Title className={ styles['modal-title'] }><strong>Add product for Exclusive launch at King Power</strong> <button className={ classNames(styles['btn-ghost'], styles['close-modal'])} onClick={ this.handleCloseModal }> <i className="fa fa-times"></i> </button> </Modal.Title> </Modal.Header> <Modal.Body> <div className={ styles['addproduct-box'] }> <div className={ styles['modal-body'] }> <div className={ styles['select-file']}> <span>Select file to Import</span> </div> <div className="input-group"> <input type="text" className="form-control" placeholder="Chose file"/> <span className="input-group-btn"> <button className="btn btn-default" type="button">Browse</button> </span> </div> <div className={ styles['download-file'] }> <a href="Download Sample File">Download Sample File</a> </div> <button className={ classNames(styles['btn-blue'], 'btn', 'btn-default') }> Check Data & Upload Now</button> </div> </div> </Modal.Body> <Modal.Footer></Modal.Footer> </Modal> ); } handleOpenModalLineProduct = (styles) => { const { displayLineProductModal } = this.state; return ( <Modal show={ displayLineProductModal } dialogClassName={ styles['addproduct-line-modal'] } > <Modal.Header> <Modal.Title className={ styles['modal-title'] }><strong>Add product for Exclusive launch at King Power</strong> <button className={ classNames(styles['btn-ghost'], styles['close-modal'])} onClick={ this.handleCloseLineProductModal }> <i className="fa fa-times"></i> </button> </Modal.Title> </Modal.Header> <Modal.Body> <div className={ styles['addproduct-line-box'] }> <div className={ styles['modal-body'] }> <div className="row"> <div className={ styles['modal-body-left'] }> <div className={ styles['title-box']}> <span>Product name or SKU</span> </div> <div className={ styles['search-product'] }> <input type="text" className="form-control" placeholder="Search orders"/> </div> <div className={ styles['product-table']}> <table className="table table-striped"> <thead> <tr className={ styles['title-table']}> <th className={ styles['product-checkbox'] }><input type="checkbox"/></th> <th className={ styles['product-id'] }>Product</th> <th className={ styles['product-thumbnail'] }>SKU</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox"/></td> <td>MONTBLANC Legend Special Edition EDT 100 มล.</td> <td>74396</td> </tr> <tr> <td><input type="checkbox"/></td> <td>COACH New York EDP 50 มล.</td> <td>74396</td> </tr> <tr> <td><input type="checkbox"/></td> <td>Barracuda กระเป๋าเดินทางอัจฉริยะ สี Pure Gold</td> <td>74396</td> </tr> <tr> <td><input type="checkbox"/></td> <td>KIEHL'S 75ML Powerful-Strength Line-Reducing Concentrate</td> <td>74396</td> </tr> </tbody> </table> </div> </div> <div className={ styles['modal-body-center'] }> <div className={ styles['title-box']}> <i className="fa fa-chevron-right "></i> </div> </div> <div className={ styles['modal-body-right'] }> <div className={ styles['title-box']}> <span>Selected product</span> </div> <div className={ styles['selected-product-box']}> <div className={ styles['selected-product-inner']}> <div className={ styles['selected-product']}> <span className={ classNames(styles['label-product'], 'label')}>MONTBLANC Legend Special <button className={ classNames(styles['btn-ghost'], styles['delete-selected-product'])}> <i className="fa fa-times"></i> </button> </span> </div> <div className={ styles['selected-product']}> <span className={ classNames(styles['label-product'], 'label')}>KIEHL'S 75ML Powerful-Stresssss… <button className={ classNames(styles['btn-ghost'], styles['delete-selected-product'])}> <i className="fa fa-times"></i> </button> </span> </div> </div> </div> </div> </div> </div> </div> </Modal.Body> <Modal.Footer> <div className={ styles['btn-group']}> <button type="button" className={classNames( styles['btn-white'], 'btn', 'btn-default') }>Cancel</button> <button type="button" className={classNames( styles['btn-blue'], 'btn', 'btn-default') }>Add to order now</button> </div> </Modal.Footer> </Modal> ); } render() { const styles = require('./productHotItem.scss'); return ( <div className="container-fluid"> { this.handleOpenModal(styles) } { this.handleOpenModalLineProduct(styles) } <div className="row"> <div className={ classNames(styles['product-hotitem-view']) }> <header className={ styles['page-header']}> <div className={ styles['page-title']}> <h1 className={ styles.header }><strong>Hot Item</strong></h1> </div> <div className={ styles['page-filter']}> <ul className={ styles['list-filter']}> <li className={ classNames( styles.filter, styles['add-product'])}> <div className="dropdown"> <DropdownButton title="Add Exclusive Products" className={ classNames(styles['btn-blue'], 'btn', 'btn-default', 'dropdown-toggle')}> <MenuItem eventKey="1" onClick={ this.handleOpenLineProductModal }>Add by Line Product</MenuItem> <MenuItem eventKey="2" onClick={ this.handleOpenAddProductExcModal }>Add by Excel</MenuItem> <MenuItem eventKey="3">Add by Line Parent Product</MenuItem> <MenuItem eventKey="4">Add GWP by Excel</MenuItem> </DropdownButton> </div> </li> </ul> </div> <Breadcrumb breadcrumb={ "Product > Hot Item" }/> </header> <section className={ styles['wrapper-content']}> <div className={ styles.content}> <div className={ classNames(styles['filter-product'])}> <div className={ classNames(styles['wrapper-filter'])}> <div className={ styles['filter-left']}> <div className={ styles['filter-action']}> <div className="btn-group"> <button type="button" className={ classNames(styles['btn-action'], 'btn', 'btn-default')}>Action</button> <button type="button" className={ classNames(styles['btn-action-select'], 'btn', 'btn-default', 'dropdown-toggle')} aria-expanded="false"> <span className="caret"></span> </button> </div> </div> <div className={ styles['filter-id']}> <div className="input-group"> <div className="input-group-btn"> <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action <span className="caret"></span></button> <ul className="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" className="divider"></li> <li><a href="#">Separated link</a></li> </ul> </div> <input type="text" className={ classNames(styles['input-productid'], 'form-control') } aria-label="..."/> </div> </div> </div> <div className={ classNames(styles['filter-right']) }> <FilterPage/> </div> </div> </div> <div className={ styles['table-detail'] }> <div className={ styles['tab-content'] }> <table className="table table-striped"> <thead> <tr className={ styles['title-table']}> <th className={ styles['product-checkbox'] }><input type="checkbox"/></th> <th className={ styles['product-id'] }>ID</th> <th className={ styles['product-thumbnail'] }>Thumbnail</th> <th className={ styles['product-name'] }>Name</th> <th className={ styles['product-type'] }>Type</th> <th className={ styles['product-attribute'] }>Arttribute Set</th> <th className={ styles['product-sku'] }>SKU</th> <th className={ styles['product-price'] }>Price</th> <th className={ styles['product-qty'] }>Qty</th> <th className={ styles['product-status'] }>Status</th> <th className={ styles['product-batch'] }>Batch</th> <th className={ styles['product-action'] }>Action</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox"/></td> <td>503576</td> <td><img src="http://via.placeholder.com/50x50"/></td> <td>EMPORIO ARMANI CLASSIC WATCH</td> <td>-</td> <td>default</td> <td>8169513</td> <td>11,800.00 THB</td> <td>172</td> <td>Enable</td> <td>batch 110</td> <td> <div className="btn-group"> <button type="button" className={ classNames(styles['btn-action'], 'btn', 'btn-default')}>Action</button> <button type="button" className={ classNames(styles['btn-action-select'], 'btn', 'btn-default', 'dropdown-toggle')} aria-expanded="false"> <span className="caret"></span> </button> </div> </td> </tr> <tr> <td><input type="checkbox"/></td> <td>503576</td> <td><img src="http://via.placeholder.com/50x50"/></td> <td>EMPORIO ARMANI CLASSIC WATCH</td> <td>Child Product </td> <td>default</td> <td>8169513</td> <td>11,800.00 THB</td> <td>172</td> <td>Enable</td> <td>batch 110</td> <td> <div className="btn-group"> <button type="button" className={ classNames(styles['btn-action'], 'btn', 'btn-default')}>Action</button> <button type="button" className={ classNames(styles['btn-action-select'], 'btn', 'btn-default', 'dropdown-toggle')} aria-expanded="false"> <span className="caret"></span> </button> </div> </td> </tr> <tr> <td><input type="checkbox"/></td> <td>503576</td> <td><img src="http://via.placeholder.com/50x50"/></td> <td>EMPORIO ARMANI CLASSIC WATCH</td> <td>-</td> <td>default</td> <td>8169513</td> <td>11,800.00 THB</td> <td>172</td> <td>Enable</td> <td>batch 110</td> <td> <div className="btn-group"> <button type="button" className={ classNames(styles['btn-action'], 'btn', 'btn-default')}>Action</button> <button type="button" className={ classNames(styles['btn-action-select'], 'btn', 'btn-default', 'dropdown-toggle')} aria-expanded="false"> <span className="caret"></span> </button> </div> </td> </tr> </tbody> </table> </div> <div className="row"> <div className={ classNames(styles['filter-bottom'])}> <FilterPage/> </div> </div> </div> </div> </section> </div> </div> </div> ); } }
packages/docs/pages/plugin/emoji/index.js
nikgraf/draft-js-plugin-editor
/* eslint-disable no-template-curly-in-string */ import React, { Component } from 'react'; // eslint-disable-next-line import/no-unresolved import gettingStarted from '!!raw-loader!../../../components/Examples/emoji/gettingStarted'; // eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-duplicates import simpleExampleCode from '!!raw-loader!../../../components/Examples/emoji/SimpleEmojiEditor'; // eslint-disable-next-line import/no-unresolved import simpleEditorStylesCode from '!!raw-loader!../../../components/Examples/emoji/SimpleEmojiEditor/editorStyles.module.css'; // eslint-disable-next-line import/no-unresolved import webpackConfig from '!!raw-loader!../../../components/Examples/emoji/webpackConfig'; // eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-duplicates import customExampleCode from '!!raw-loader!../../../components/Examples/emoji/CustomEmojiEditor'; import styles from './styles.module.css'; import Container from '../../../components/Container/Container'; import Heading from '../../../components/Heading/Heading'; import Code from '../../../components/Code/Code'; // eslint-disable-next-line import/no-duplicates import SimpleEmojiEditor from '../../../components/Examples/emoji/SimpleEmojiEditor'; // eslint-disable-next-line import/no-duplicates import CustomEmojiEditor from '../../../components/Examples/emoji/CustomEmojiEditor'; import AlternateContainer from '../../../components/AlternateContainer/AlternateContainer'; import ExternalLink from '../../../components/Link/Link'; import InlineCode from '../../../components/InlineCode/InlineCode'; import PluginPageFrame from '../../../components/PluginPageFrame/PluginPageFrame'; const toneSelectStyles = `.emojiSelectPopoverToneSelect { position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: 2; }`; const priorityListCode = `priorityList: { ':see_no_evil:': ["1f648"], ':raised_hands:': ["1f64c"], ':100:': ["1f4af"], }`; const selectGroupsCode = `selectGroups: [{ title: 'Society', icon: '👥', categories: ['people', 'food', 'travel'], }, { title: 'Objects & symbols', icon: '❤️', categories: ['objects', 'symbols'], }]`; export default class App extends Component { render() { return ( <PluginPageFrame> <Container> <Heading level={2}>Emoji</Heading> <p> Consistent Emoji display across all platforms, independent of the host system. </p> <Heading level={3}>Attribution to EmojiOne</Heading> <p> The beautiful Emoji art used in this plugin is provided by the{' '} <ExternalLink href="http://emojione.com/">Emoji One</ExternalLink>{' '} project. Personal or non-commercial use of the emojis do not require attribution. For the rights to use our emojis still for free in commercial projects proper attribution in form of a link is required. More here:{' '} <ExternalLink href="http://emojione.com/licensing"> http://emojione.com/licensing </ExternalLink> . </p> <Heading level={3}>Implementation</Heading> <p> Emoji unicode characters are wrapped in a span, hidden, and displayed instead through a background image. This creates consistency across all platforms while maintaining natural copy/pasting functionality. </p> <p> If useNativeArt parameter is used, emoji unicode characters are displayed. This enables displaying platform specific art for emojis. </p> <Heading level={3}>Usage</Heading> <p> To use simply type <code>:</code> which will show an autocomplete with matching emojis. </p> <Heading level={3}>Supported Environment</Heading> <ul className={styles.list}> <li className={styles.listEntry}>Desktop: Yes</li> <li className={styles.listEntry}>Mobile: Yes</li> <li className={styles.listEntry}>Screen-reader: Yes</li> </ul> </Container> <AlternateContainer> <Heading level={2}>Getting Started</Heading> <Code code="npm install @draft-js-plugins/editor" /> <Code code="npm install @draft-js-plugins/emoji" /> <Code code={gettingStarted} name="gettingStarted.js" /> <Heading level={3}>Importing the default styles</Heading> <p> The plugin ships with a default styling available at this location in the installed package: &nbsp; <InlineCode code={'node_modules/@draft-js-plugins/emoji/lib/plugin.css'} /> </p> <Heading level={4}>Webpack Usage</Heading> <ul className={styles.list}> <li className={styles.listEntry}> 1. Install Webpack loaders: &nbsp; <InlineCode code={'npm i style-loader css-loader --save-dev'} /> </li> <li className={styles.listEntry}> 2. Add the below section to Webpack config (if your config already has a loaders array, simply add the below loader object to your existing list. <Code code={webpackConfig} className={styles.guideCodeBlock} /> </li> <li className={styles.listEntry}> 3. Add the below import line to your component to tell Webpack to inject the style to your component. <Code code={"import '@draft-js-plugins/emoji/lib/plugin.css';"} className={styles.guideCodeBlock} /> </li> <li className={styles.listEntry}>4. Restart Webpack.</li> </ul> <Heading level={4}>Browserify Usage</Heading> <p> Please help, by submiting a Pull Request to the{' '} <ExternalLink href="https://github.com/draft-js-plugins/draft-js-plugins/blob/master/docs/client/components/pages/Emoji/index.js"> documentation </ExternalLink> . </p> </AlternateContainer> <Container> <Heading level={2}>Configuration Parameters</Heading> <div className={styles.param}> <span className={styles.paramName}>theme</span> <span>Object of CSS classes with the following keys.</span> <div className={styles.subParams}> <div className={styles.subParam}> <span className={styles.subParamName}>emoji:</span> CSS class for the emoji wrapper. </div> <div className={styles.subParam}> <span className={styles.subParamName}>emojiSuggestions:</span> CSS class for suggestions component. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSuggestionsEntry: </span> CSS class for an entry in the suggestions component. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSuggestionsEntryFocused: </span> CSS class for the focused entry in the suggestions component. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSuggestionsEntryText: </span> CSS class for an entry’s text in the suggestions component. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSuggestionsEntryIcon: </span> CSS class for an entry’s emoji image in the suggestions component. </div> {/* EmojiSelect styles */} <div className={styles.subParam}> <span className={styles.subParamName}>emojiSelect:</span> CSS class for emoji select component. </div> <div className={styles.subParam}> <span className={styles.subParamName}>emojiSelectButton:</span> CSS class for button to open emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectButtonPressed: </span> CSS class for pressed state of button to open emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}>emojiSelectPopover:</span> CSS class for emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverClosed: </span> CSS class for closed state of the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverTitle: </span> CSS class for a title of active group in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverGroups: </span> CSS class for the emoji groups wrapper in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverGroup: </span> CSS class for a group of emojis in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverGroupTitle: </span> CSS class for a title of emoji group in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverGroupList: </span> CSS class for a group emoji list in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverGroupItem: </span> CSS class for a group emoji list item in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverToneSelect: </span> CSS class for tone select in the emoji select popup. <div> <em> Important. The tone select must overlap the emoji select popup so that disable controls of the popup. By default </em> <Code code={toneSelectStyles} /> </div> </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverToneSelectList: </span> CSS class for a tone select emoji list in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverToneSelectItem: </span> CSS class for a tone select emoji list item in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverEntry: </span> CSS class for an emoji entry in the emoji select popup (including tone select). </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverEntryFocused: </span> CSS class for the focused emoji entry in the emoji select popup (including tone select). </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverEntryIcon: </span> CSS class for an emoji entry’s image in the emoji select popup (including tone select). </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverNav: </span> CSS class for a group navigation in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverNavItem: </span> CSS class for a group navigation item in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverNavEntry: </span> CSS class for an entry of the group navigation in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverNavEntryActive: </span> CSS class for active state of the group navigation entry in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverScrollbarOuter: </span> CSS class for the outer scrollbar box in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverScrollbar: </span> CSS class for scrollbar in the emoji select popup. </div> <div className={styles.subParam}> <span className={styles.subParamName}> emojiSelectPopoverScrollbarThumb: </span> CSS class for scrollbar thumb in the emoji select popup. </div> </div> </div> <div className={styles.paramBig}> <span className={styles.paramName}>positionSuggestions</span> <span> The function can be used to manipulate the position of the popover containing the suggestions. It receives one object as arguments containing the visible rectangle surrounding the decorated search string including the colon. In addition the object contains prevProps, prevState, state & props. An object should be returned which can contain all sorts of styles. The defined properties will be applied as inline-styles. </span> </div> <div className={styles.paramBig}> <span className={styles.paramName}>priorityList</span> <div> These entries will be show first in the EmojiSuggestions dropdown after typing `:`. Must be an object which must contain Emoji entries used by EmojiOne e.g. <Code code={priorityListCode} /> </div> </div> <div className={styles.paramBig}> <span className={styles.paramName}>selectGroups</span> <div> Emoji select groups specification. Must be an array of objects, which declare each group: title, icon (can be a string or React element), array of emoji categories from EmojiOne e.g. <Code code={selectGroupsCode} /> </div> </div> <div className={styles.paramBig}> <span className={styles.paramName}>selectButtonContent</span> <span> Content of button which opens emoji select popup. (Default content is ☺) </span> </div> <div className={styles.paramBig}> <span className={styles.paramName}>toneSelectOpenDelay</span> <span> Time delay before opening tone select. (Default value is 500&nbsp;ms) </span> </div> <div className={styles.paramBig}> <span className={styles.paramName}>useNativeArt</span> <span> If set to <InlineCode code={'true'} />, uses host system art for emojis instead of EmojiOne art. Default value is{' '} <InlineCode code={'false'} />. </span> </div> <div className={styles.paramBig}> <span className={styles.paramName}>emojiImage</span> <span> If provided the passed component is used to render the preview image for the suggestions. If this parameter is set the{' '} <InlineCode code={'useNativeArt'} /> is ignored. You can use this component to implement your own emoji library. It receives the following props: emoji, unicode and theme </span> </div> <div className={styles.paramBig}> <span className={styles.paramName}>emojiInlineText</span> <span> If provided the passed component is used to render the emojis in the text. If this parameter is set the{' '} <InlineCode code={'useNativeArt'} /> is ignored. You can use this component to implement your own emoji library. It receives the following props: decoratedText, className, children and theme </span> </div> <div className={styles.paramBig}> <span className={styles.paramName}>disableInlineEmojis</span> <span> Disables the suggestion popover for emojis in the editor. </span> </div> <Heading level={3}>EmojiSuggestions</Heading> <div> The EmojiSuggestions component is part of the plugin and should placed somewhere in the JSX after the Editor. It takes the following props: <div className={styles.paramBig}> <span className={styles.paramName}>onSearchChange</span> <span> A callback which is triggered whenever the search term changes. The first argument is an object which constains the search term in the property value. </span> </div> <div className={styles.paramBig}> <span className={styles.paramName}>onOpen</span> <span> A callback which is triggered whenever the suggestions popover opens. </span> </div> <div className={styles.paramBig}> <span className={styles.paramName}>onClose</span> <span> A callback which is triggered whenever the suggestions popover closes. </span> </div> </div> <Heading level={3}>EmojiSelect</Heading> <div> The EmojiSelect is another component of the plugin. It takes the following props: <div className={styles.paramBig}> <span className={styles.paramName}>onOpen</span> <span> A callback which is triggered whenever the emoji popover opens. </span> </div> <div className={styles.paramBig}> <span className={styles.paramName}>onClose</span> <span> A callback which is triggered whenever the emoji popover closes. </span> </div> <div className={styles.paramBig}> <span className={styles.paramName}>closeOnEmojiSelect</span> <span> If set to true the popup is closed after an emoji is selected, otherwise it will stay open. </span> </div> </div> </Container> <Container> <Heading level={2}>Simple Emoji Example</Heading> <SimpleEmojiEditor /> <Code code={simpleExampleCode} name="SimpleEmojiEditor.js" /> <Code code={simpleEditorStylesCode} name="editorStyles.js" /> </Container> <Container> <Heading level={2}>Custom Emoji Example with native emojis</Heading> <CustomEmojiEditor /> <Code code={customExampleCode} name="SimpleEmojiEditor.js" /> </Container> </PluginPageFrame> ); } }
src/index.js
justinkahrs/portfolio
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import '../node_modules/bootstrap/dist/css/bootstrap.css'; import '../node_modules/bootstrap/dist/css/bootstrap-theme.css'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root'), );
client/src/components/calculateButton.js
BukhariH/finimizeChallenge
import React, { Component } from 'react'; import 'bootstrap/dist/css/bootstrap.css'; import '../App.css'; import PropTypes from 'prop-types'; class CalculateButton extends Component { render() { return ( <button id="calc-btn" name="calc-btn" className="btn btn-success" onClick={this.props.calcFunc}>Figure this all out! 🤓</button> ); } } CalculateButton.propTypes = { calcFunc: PropTypes.func }; export default CalculateButton;
src/components/WebResults/TotalResults.js
nicolas-adamini/littleblue
import React from 'react'; export default function TotalResults(props) { const number = props.number; function format(num) { let n = num.toString(), p = n.indexOf('.'); return n.replace(/\d(?=(?:\d{3})+(?:\.|$))/g, function ($0, i) { return p < 0 || i < p ? ($0 + ',') : $0; }); } return ( <p className="number-of-results"> <small>About {format(number)} results.</small> </p> ); }
app/scripts/Mobilization/__tests__/components/MobilizationListHeader.spec.js
igr-santos/hub-client
import React from 'react' import { expect } from 'chai' import { shallow } from 'enzyme' import MobilizationsHeader from '../../components/MobilizationsHeader' describe('app/scripts/Mobilization/components/MobilizationsHeader', () => { const context = { router: {} } let wrapper const props = { location: { pathname: '' }, mobilization: { id: 1 } } beforeEach(() => { wrapper = shallow(<MobilizationsHeader {...props} />, { context }) }) describe('#render', () => { it('should render add new mobilization button', () => { expect(wrapper.find('Link').length).to.equal(1) }) describe('tabs', () => { it('should render one <Tabs> parent component', () => { expect(wrapper.find('Tabs')).to.have.length(1) }) it('should render 2 <Tab> children component', () => { expect(wrapper.find('Tab')).to.have.length(2) }) }) }) })
springboot/GReact/src/main/resources/static/app/components/forms/wizards/Wizard.js
ezsimple/java
import React from 'react' export default class Wizard extends React.Component { componentDidMount() { let self = this; let element = $(this.refs.wizard); var stepsCount = $('[data-smart-wizard-tab]').length; var currentStep = 1; var validSteps = []; var $form = element.closest('form'); var $prev = $('[data-smart-wizard-prev]', element); var $next = $('[data-smart-wizard-next]', element); function setStep(step) { currentStep = step; $('[data-smart-wizard-pane=' + step + ']', element).addClass('active').siblings('[data-smart-wizard-pane]').removeClass('active'); $('[data-smart-wizard-tab=' + step + ']', element).addClass('active').siblings('[data-smart-wizard-tab]').removeClass('active'); $prev.toggleClass('disabled', step == 1) } element.on('click', '[data-smart-wizard-tab]', function (e) { setStep(parseInt($(this).data('smartWizardTab'))); e.preventDefault(); }); $next.on('click', function (e) { if ($form.data('validator')) { if (!$form.valid()) { validSteps = _.without(validSteps, currentStep); $form.data('validator').focusInvalid(); return false; } else { validSteps = _.without(validSteps, currentStep); validSteps.push(currentStep); element.find('[data-smart-wizard-tab=' + currentStep + ']') .addClass('complete') .find('.step') .html('<i class="fa fa-check"></i>'); } } if (currentStep < stepsCount) { setStep(currentStep + 1); } else { if (validSteps.length < stepsCount) { var steps = _.range(1, stepsCount + 1) _(steps).forEach(function (num) { if (validSteps.indexOf(num) == -1) { setStep(num); return false; } }) } else { var data = {}; _.each($form.serializeArray(), function (field) { data[field.name] = field.value }); if (_.isFunction(self.props.onComplete)) { self.props.onComplete(data) } } } e.preventDefault(); }); $prev.on('click', function (e) { if (!$prev.hasClass('disabled') && currentStep > 0) { setStep(currentStep - 1); } e.preventDefault(); }); setStep(currentStep); } render() { let {children, onComplete, ...props} = this.props; return ( <div {...props} ref="wizard"> {children} </div> ) } }
src/client/app/boot.js
jsilvestre/tasky
import Application from './components/application'; import logger from 'debug'; import React from 'react'; import { Provider } from 'react-redux'; import startRouter from './router'; import { configureStore } from './store.js'; import en from './locales/en'; import fr from './locales/fr'; const debug = logger('app:boot'); export default function boot(data) { debug('Prepare application to boot.'); debug('Get localization strings based on given locale.'); const locale = data.locale; const localesLoader = {en, fr}; let phrases = localesLoader[locale]; if (!phrases) { debug(`Localized strings could not be found for locale ${locale},` + `using EN locale instead.`); phrases = localesLoader.en; } // Initialize polyglot object with phrases. const Polyglot = require('node-polyglot'); const polyglot = new Polyglot({ allowMissing: process.env.NODE_ENV === 'production', locale: locale, }); polyglot.extend(phrases); const store = configureStore(data); const history = startRouter(store); const application = ( <Provider store={store}> <Application router={history} t={polyglot.t.bind(polyglot)}/> </Provider> ); debug('Application configured.'); return application; }
src/components/ChallengeList.js
quintel/etmobile
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Challenge from './Challenge'; const sortChallenges = (left, right) => ( left.name.toLowerCase() < right.name.toLowerCase() ? 0 : 1 ); class ChallengeList extends React.Component { constructor() { super(); this.state = { challenges: null }; } componentWillMount() { const queries = { orderByChild: 'expires' }; if (this.props.active) { queries.startAt = new Date().getTime(); } else { queries.endAt = new Date().getTime(); } this.props.base.fetch('challenges', { context: this, asArray: true, queries }).then(data => this.setState({ challenges: data.sort(sortChallenges) }) ); } render() { if (!this.state.challenges) { return ( <div className="challenge loading"> <FormattedMessage id="challenges.loadingChallenges" />&hellip; </div> ); } return ( <div> {this.state.challenges.map(({ key, name, expires, mode }) => ( <Challenge key={key} base={this.props.base} expires={new Date(expires)} id={key} modeName={mode} name={name} /> ))} </div> ); } } ChallengeList.contextTypes = { router: PropTypes.shape({}) }; ChallengeList.propTypes = { active: PropTypes.bool, base: PropTypes.shape({ fetch: PropTypes.func.isRequired }).isRequired }; ChallengeList.defaultProps = { active: false }; export default ChallengeList;
app/javascript/mastodon/components/attachment_list.js
pixiv/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; const filename = url => url.split('/').pop().split('#')[0].split('?')[0]; export default class AttachmentList extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.list.isRequired, compact: PropTypes.bool, }; render () { const { media, compact } = this.props; if (compact) { return ( <div className='attachment-list compact'> <ul className='attachment-list__list'> {media.map(attachment => { const displayUrl = attachment.get('remote_url') || attachment.get('url'); return ( <li key={attachment.get('id')}> <a href={displayUrl} target='_blank' rel='noopener'><i className='fa fa-link' /> {filename(displayUrl)}</a> </li> ); })} </ul> </div> ); } return ( <div className='attachment-list'> <div className='attachment-list__icon'> <i className='fa fa-link' /> </div> <ul className='attachment-list__list'> {media.map(attachment => { const displayUrl = attachment.get('remote_url') || attachment.get('url'); return ( <li key={attachment.get('id')}> <a href={displayUrl} target='_blank' rel='noopener'>{filename(displayUrl)}</a> </li> ); })} </ul> </div> ); } }
src/components/Header/Header.js
langpavel/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import { defineMessages, FormattedMessage } from 'react-intl'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.css'; import Link from '../Link'; import Navigation from '../Navigation'; import LanguageSwitcher from '../LanguageSwitcher'; import logoUrl from './logo-small.png'; import logoUrl2x from './logo-small@2x.png'; const messages = defineMessages({ brand: { id: 'header.brand', defaultMessage: 'Your Company Brand', description: 'Brand name displayed in header', }, bannerTitle: { id: 'header.banner.title', defaultMessage: 'React', description: 'Title in page header', }, bannerDesc: { id: 'header.banner.desc', defaultMessage: 'Complex web apps made easy', description: 'Description in header', }, }); class Header extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <Navigation /> <Link className={s.brand} to="/"> <img src={logoUrl} srcSet={`${logoUrl2x} 2x`} width="38" height="38" alt="React" /> <span className={s.brandTxt}> <FormattedMessage {...messages.brand} /> </span> </Link> <LanguageSwitcher /> <div className={s.banner}> <h1 className={s.bannerTitle}> <FormattedMessage {...messages.bannerTitle} /> </h1> <FormattedMessage tagName="p" {...messages.bannerDesc} /> </div> </div> </div> ); } } export default withStyles(s)(Header);
source/PhoneInputBrowser.js
halt-hammerzeit/react-phone-number-input
import React from 'react' import PropTypes from 'prop-types' import PhoneInput_ from './PhoneInput' import InputSmart from './InputSmart' import InputBasic from './InputBasic' export function createInput(defaultMetadata) { function PhoneInput({ smartCaret, ...rest }, ref) { return ( <PhoneInput_ {...rest} ref={ref} Component={smartCaret ? InputSmart : InputBasic} /> ) } PhoneInput = React.forwardRef(PhoneInput) PhoneInput.propTypes = { /** * HTML `<input/>` `type` attribute. */ type: PropTypes.string, /** * HTML `<input/>` `autocomplete` attribute. */ autoComplete: PropTypes.string, /** * By default, the caret position is being "intelligently" managed * while a user inputs a phone number. * This "smart" caret behavior can be turned off * by passing `smartCaret={false}` property. * This is just an "escape hatch" for any possible caret position issues. */ // Is `true` by default. smartCaret: PropTypes.bool.isRequired, /** * `libphonenumber-js` metadata. */ metadata: PropTypes.object.isRequired } PhoneInput.defaultProps = { /** * HTML `<input/>` `type="tel"`. */ type: 'tel', /** * Remember (and autofill) the value as a phone number. */ autoComplete: 'tel', /** * Set to `false` to use "basic" caret instead of the "smart" one. */ smartCaret: true, /** * `libphonenumber-js` metadata. */ metadata: defaultMetadata } return PhoneInput } export default createInput()
src/js/components/widget/Overview.js
kukua/dashboard
import _ from 'underscore' import React from 'react' import ControlsWidget from './Controls' import DevicePickerWidget from './DevicePicker' import AlertOverviewWidget from './AlertOverview' import FilterGraphWidget from './FilterGraph' import DownloadWidget from './Download' import NotFoundWidget from './NotFound' const availableWidgets = { 'controls': ControlsWidget, 'device-picker': DevicePickerWidget, 'alert-overview': AlertOverviewWidget, 'filter-graph': FilterGraphWidget, 'download': DownloadWidget, } class WidgetOverview extends React.Component { constructor () { super() this.state = { shared: {}, } } onSetShared (key, value) { var shared = this.state.shared shared[key] = value this.setState({ shared }) } render () { var rows = [[]] var columnCount = (row) => _.chain(row) .map((column) => column[0]) .reduce((memo, num) => memo + num, 0) .value() this.props.widgets.forEach((widget, i) => { var row = rows[rows.length - 1] widget.columns = Math.min(4, widget.columns || 4) if (columnCount(row) + widget.columns > 4) { // New row rows.push([]) row = rows[rows.length - 1] } var Widget = availableWidgets[widget.type] || NotFoundWidget var widthClass = 'col-md-' + Math.max(1, Math.min(12, widget.columns * 3)) var Container = ( <div key={i} class={widthClass}> <Widget {...widget} shared={this.state.shared} onSetShared={(key, value) => this.onSetShared(key, value)} /> </div> ) row.push([widget.columns, Container]) }) return ( <div> {rows.map((columns, i) => <div key={i} class="row">{columns.map((column) => column[1])}</div>)} </div> ) } } WidgetOverview.propTypes = { widgets: React.PropTypes.array.isRequired, } export default WidgetOverview
client/src/javascript/components/icons/FeedIcon.js
stephdewit/flood
import React from 'react'; import BaseIcon from './BaseIcon'; export default class FeedIcon extends BaseIcon { render() { return ( <svg className={`icon icon--feed ${this.props.className}`} viewBox={this.getViewBox()}> <path d="M18.47,47.88A6.49,6.49,0,1,0,12,54.38,6.5,6.5,0,0,0,18.47,47.88Zm18,3.51a30.41,30.41,0,0,0-8.85-19.12A30.33,30.33,0,0,0,8.48,23.41H8.31A2.07,2.07,0,0,0,6.85,24a2.06,2.06,0,0,0-.71,1.59v4.57a2.14,2.14,0,0,0,2,2.13A21.64,21.64,0,0,1,27.57,51.77a2.14,2.14,0,0,0,2.13,2h4.56A2.06,2.06,0,0,0,35.85,53,2.19,2.19,0,0,0,36.42,51.4Zm17.3,0.07a47.68,47.68,0,0,0-14-31.37,47.55,47.55,0,0,0-31.33-14H8.31a2.1,2.1,0,0,0-1.49.61,2.07,2.07,0,0,0-.68,1.56v4.84a2.15,2.15,0,0,0,2,2.13A38.72,38.72,0,0,1,44.57,51.7a2.15,2.15,0,0,0,2.16,2h4.83A2.19,2.19,0,0,0,53.73,51.46Z" /> </svg> ); } }
client/pages/examples/threejs/sph/sph.js
fdesjardins/webgl
import React from 'react' import * as THREE from 'three' import { MarchingCubes } from 'three/examples/jsm/objects/MarchingCubes' import tinygradient from 'tinygradient' import { createAxes, addControls, createParticle, addAxesLabels, } from '../graphing/utils' // import { buildCells, buildCellNeighbors, assignToCell } from './2d-cell-list' import { buildCells, buildCellNeighbors, assignToCell } from './3d-cell-list' const WHITE = 0xffffff const BLACK = 0x000000 const setupOrthoCamera = ({ domain, margin }) => { const width = domain[1] - domain[0] const camera = new THREE.OrthographicCamera( -width / 2 - margin[0], width / 2 + margin[1], width / 2 + margin[2], -width / 2 - margin[3], 0.01, 1000 ) camera.updateProjectionMatrix() camera.position.z = 50 return camera } const setupPerspectiveCamera = ({ width, height }) => { const camera = new THREE.PerspectiveCamera(35, width / height, 0.1, 1000) camera.position.x = 0 camera.position.y = 0 camera.position.z = 50 return camera } const templatePoint = null const createParticles = ({ n, size, center }) => { const point = templatePoint || createParticle({ size, color: 0x0000ff, transparent: true, opacity: 0.65, }) const particles = [] for (let i = 0; i < n; i += 1) { const p = point.clone() p.position.set( center + (Math.random() - 0.5) * 0.1, center + (Math.random() - 0.5) * 0.1, center + (Math.random() - 0.5) * 0.1 ) p.lastPosition = p.position.clone() particles.push(p) } return { particles, } } // const lines = connections.map(([m, n]) => // createConnectingLine(points[m], points[n]) // ) // const lines = [] // lines.map(l => scene.add(l)) const createBoundingCube = () => { const cubeGeom = new THREE.BoxBufferGeometry(10, 10, 10) const cubeMat = new THREE.MeshLambertMaterial({ color: 0xeeeeee, opacity: 0.25, transparent: true, side: THREE.BackSide, }) const cube = new THREE.Mesh(cubeGeom, cubeMat) return cube } const mousePos = (event) => { const bounds = event.target.getBoundingClientRect() const xy = { x: event.clientX - bounds.left, y: event.clientY - bounds.top, } const x = (xy.x / event.target.clientWidth) * 2 - 1 const y = -((xy.y / event.target.clientHeight) * 2 - 1) return [x, y] } const calcF_spring = (particle, obj2, k, restLength) => { const d = particle.position.clone().sub(obj2.position) const l = d.length() const F_spring = d.normalize().multiplyScalar(-1 * k * (l - restLength)) particle.f.add(F_spring) } const F_gravity = new THREE.Vector3(0, -9.81, 0) const F_pressure = new THREE.Vector3(0, 0, 0) const F_viscosity = new THREE.Vector3(0, 0, 0) const F = new THREE.Vector3(0, 0, 0) const tempPressure = new THREE.Vector3(0, 0, 0) const tempV = new THREE.Vector3(0, 0, 0) const visc = (r, h) => 45 / (Math.PI * h ** 6) const poly6f = (r, h) => { if (r > 0 && r < h) { return (315 / (64 * h ** 9 * Math.PI)) * (h ** 2 - r ** 2) ** 3 } return 0 } const spikyf = (r, h) => 15 / (h ** 6 * Math.PI) / (h - r) ** 3 const poly6fg = (r, h) => -1 * r * (945 / (32 * h ** 9 * Math.PI)) * (h ** 2 - r ** 2) ** 2 const sqNorm = (v) => { return v.x ** 2 + v.y ** 2 + v.z ** 2 } const norm = (v) => { return Math.sqrt(sqNorm(v)) } const calcDensityPressure = ( particles, neighbors, { h, gasConstant, restDensity, mass } ) => { particles.map((pi, i) => { pi.density = 0 neighbors[i].map((j) => { const pj = particles[j] const dist = pj.position.distanceTo(pi.position) if (dist < h) { pi.density += mass * poly6f(dist, h) } }) pi.pressure = gasConstant * (pi.density - restDensity) }) } const calcForces = (particles, neighbors, { h, viscosity, mass }) => { particles.map((pi, i) => { F_pressure.set(0, 0, 0) F_viscosity.set(0, 0, 0) F.set(0, 0, 0) if (!neighbors || neighbors.length === 0) { return } neighbors[i].map((j) => { const pj = particles[j] const r = pj.position.distanceTo(pi.position) if (r < h) { tempPressure .copy(pj.position) .sub(pi.position) .normalize() .multiplyScalar((-1 * (pi.pressure + pj.pressure)) / 2) F_pressure.add(tempPressure) tempV .copy(pj.v) .sub(pi.v) .multiplyScalar( ((viscosity * mass) / pj.density) * visc(r, h) * (h - r) ) F_viscosity.add(tempV) } }) F.add(F_gravity) F.add(F_pressure) F.add(F_viscosity) pi.f.add(F) }) } // gravity (m/s) const G = -9.81 const config = { scene: { domain: [-20, 20], gridSize: 1, // l,r,t,b margin: [4, 4, 4, 4], surfaceResolution: 26, }, sim: { numParticles: 700, numToAdd: 8, particleSize: 1, }, sph: { h: 4, gasConstant: 100, mass: 5, restDensity: 1, viscosity: 30, }, } const width = config.scene.domain[1] - config.scene.domain[0] const center = (config.scene.domain[1] + config.scene.domain[0]) / 2 const init = ({ state }) => { const canvas = document.getElementById('sph') let scene = new THREE.Scene() scene.background = new THREE.Color(WHITE) let renderer = new THREE.WebGLRenderer({ canvas, antialias: true }) renderer.setSize(canvas.clientWidth, canvas.clientWidth) const ambientLight = new THREE.AmbientLight(0x707070) scene.add(ambientLight) const pointLight = new THREE.PointLight(WHITE) pointLight.position.set(20, 20, -20) scene.add(pointLight) const { domain, gridSize, margin } = config.scene const camera = setupOrthoCamera({ domain, margin }) // const camera = setupPerspectiveCamera({ // width: canvas.width, // height: canvas.height // }) const controls = addControls({ camera, renderer }) controls.target.set(center, center, 0) controls.update() const grid = new THREE.GridHelper( domain[1] - domain[0], (domain[1] - domain[0]) / gridSize, 0x000000, 0xf2f2f2 ) grid.rotation.x = Math.PI / 2 grid.position.set(center, center, 0) const axes = createAxes({ size: (domain[1] - domain[0]) / 2, fontSize: 0 }) axes.position.set(center, center, 0) scene.add(axes) addAxesLabels({ scene, domain, gridSize }) // let lastMousePos = { x: 0.5, y: 0.5 } // let label // canvas.onmousemove = event => { // const [x, y] = mousePos(event) // lastMousePos = { // x, // y // } // } // canvas.onmouseleave = () => { // lastMousePos = { x: 0.5, y: 0.5 } // if (label) { // scene.remove(label) // label = null // } // } // const raycaster = new THREE.Raycaster() const arrowHelper = new THREE.ArrowHelper( new THREE.Vector3(1, 0, 0).normalize(), new THREE.Vector3(0, 0, 0), width / 4, BLACK ) scene.add(arrowHelper) const { numParticles, numToAdd, particleSize } = config.sim const particles = [] const connectionsMap = [] let n = 0 const particlesSceneNode = new THREE.Group() const particleEmitters = [ new THREE.Vector3(15, 18, 15), new THREE.Vector3(-15, 18, 15), new THREE.Vector3(15, 18, -15), new THREE.Vector3(-15, 18, -15), ] const interval = setInterval(() => { const { particles: newParticles } = createParticles({ n: numToAdd, size: particleSize, center, }) newParticles.map((p, i) => { p.position.add(particleEmitters[i % 4]) p.lastPosition = p.position.clone() p.v = new THREE.Vector3(0, 0, 0) p.f = new THREE.Vector3(0, 0, 0) p.lastf = new THREE.Vector3(0, 0, 0) const len = particles.length connectionsMap[len] = [] connectionsMap.map((_, j) => { connectionsMap[j].push(len) connectionsMap[len].push(j) }) particles.push(p) particlesSceneNode.add(p) }) n += numToAdd if (n >= numParticles) { clearInterval(interval) } }, 100) const tempPos = new THREE.Vector3() const F_g = new THREE.Vector3(0, G, 0) const xAxis = new THREE.Vector3(1, 0, 0) const zAxis = new THREE.Vector3(0, 0, 1) let thenSecs = 0 const cellmin = domain[0] const cellmax = domain[1] const cellw = 2.5 const stride = (domain[1] - domain[0]) / cellw const cells = buildCells({ cellmin, cellmax, cellw }) const cellNeighbors = buildCellNeighbors(cells, { cellmin, cellmax, cellw, stride, }) const cubesMaterial = new THREE.MeshPhongMaterial({ color: 0xcccccc, opacity: 0.85, transparent: true, refractionRatio: 0.5, vertexColors: THREE.VertexColors, shininess: 60, }) let cubesInstance = new MarchingCubes(24, cubesMaterial, true, true) cubesInstance.position.set(0, 0, 0) cubesInstance.scale.set(40, 40, 40) const carribean = [ '#cbdcf2', '#91e1e9', '#00c0e3', '#0096cc', '#006fb6', '#044185', ] const lava = ['#fff1a1', '#d9a848', '#c93200', '#841800', '#3d0a03'] const acid = ['#b0bf1a', '#3b8e22', '#1e4d2b', '#0d2b0f'] const gradient = tinygradient(lava) const lookUpTable = {} const gradientMax = config.sph.restDensity * 2 const gradientMin = config.sph.restDensity / 2 for (let i = gradientMin; i <= gradientMax; i += 0.1) { lookUpTable[i.toFixed(1).toString()] = new THREE.Color( gradient.rgbAt(i / gradientMax).toHexString() ) } const maxColor = new THREE.Color( lookUpTable[Object.keys(lookUpTable).length - 1] ) const animate = (now) => { if (!renderer) { return } controls.update() requestAnimationFrame(animate) const nowSecs = now * 0.001 let deltaSecs = nowSecs - thenSecs thenSecs = nowSecs if (!deltaSecs) { deltaSecs = 0 } const dt = state.get('timestep') F_gravity.copy(F_g) .applyAxisAngle(zAxis, 0.5 * Math.sin(nowSecs / 2)) .applyAxisAngle(xAxis, 0.5 * Math.cos(nowSecs / 3)) arrowHelper.setDirection(F_gravity.clone().normalize()) // Rebuild neighbors list const particleCellIndices = particles.map((p) => { return assignToCell(cells, cellw, p.position) }) const neighbors = particleCellIndices.map((cellIndex) => { const neighboringCells = cellNeighbors[cellIndex] const nb = [] particleCellIndices.map((b, j) => { if (neighboringCells.includes(b) || cellIndex === b) { nb.push(j) } }) return nb }) particles.map((p, i) => { p.lookAt(camera.position) // Velocity Verlet Method // tempV.copy(p.v).multiplyScalar(dt) // tempPos.copy(p.position).add(tempV) // tempV // .copy(p.f) // .divideScalar(2) // .multiplyScalar(dt ** 2) // tempPos.add(tempV) // p.position.copy(tempPos) // p.lastf.copy(p.f) p.f.set(0, 0, 0) }) // Calculate forces calcDensityPressure(particles, neighbors, config.sph) // // const mousePosVec = new THREE.Vector2(lastMousePos.x, lastMousePos.y) // raycaster.setFromCamera(mousePosVec, camera) // const intersects = raycaster.intersectObjects(particles) // if (intersects.length > 0) { // intersects[0].object.pressure += 500 // } calcForces(particles, neighbors, config.sph) const particleRadius = particleSize / 2 particles.map((p, i) => { // Euler Method // const newPos = p.position.clone().add(p.v.clone().multiplyScalar(dt)) // const newVel = p.v.clone().add(p.f.clone().multiplyScalar(dt)) // p.lastPosition.copy(p.position) // p.position.copy(newPos) // p.v.copy(newVel) // Verlet Method tempPos .copy(p.position) .multiplyScalar(2) .sub(p.lastPosition) .add(p.f.clone().multiplyScalar(dt ** 2)) p.lastPosition.copy(p.position) p.position.copy(tempPos) p.v .copy(tempPos) .sub(p.lastPosition) .divideScalar(2 * dt) // Velocity Verlet // tempV // .copy(p.f) // .add(p.lastf) // .divideScalar(2) // .multiplyScalar(dt) // p.v.add(tempV) // Handle Boundary Conditions const damping = -0.8 if (p.position.x + particleRadius > domain[1]) { p.v.x = damping * p.v.x p.position.x = domain[1] - particleRadius } else if (p.position.x - particleRadius < -1 * domain[1]) { p.v.x = damping * p.v.x p.position.x = domain[0] + particleRadius } if (p.position.y + particleRadius > domain[1]) { p.v.y = damping * p.v.y p.position.y = domain[1] - particleRadius } else if (p.position.y - particleRadius < -1 * domain[1]) { p.v.y = damping * p.v.y p.position.y = domain[0] + particleRadius } if (p.position.z + particleRadius > domain[1]) { p.v.z = damping * p.v.z p.position.z = domain[1] - particleRadius } else if (p.position.z - particleRadius < -1 * domain[1]) { p.v.z = damping * p.v.z p.position.z = domain[0] + particleRadius } }) cubesInstance.reset() // Update color of particles and fluid particles.map((p) => { const color = lookUpTable[p.density.toFixed(1)] || maxColor p.material.color.set(color) cubesInstance.addBall( (p.position.x + 40) / 80, (p.position.y + 40) / 80, (p.position.z + 40) / 80, 0.025, 7, new THREE.Color(color) ) }) // if (label) { // label.lookAt(camera.position) // } // if (intersects.length === 0 && label) { // scene.remove(label) // label = null // } else if (intersects.length > 0) { // const target = intersects[0] // const { position, v, density, pressure } = target.object // if (label) { // scene.remove(label) // label = null // } // label = createLabel({ // text: `Pos: (${position.x.toFixed(2)}, ${position.y.toFixed( // 2 // )})\nVel: (${v.x.toFixed(2)})\nDen: (${density.toFixed( // 2 // )})\nPrs: (${pressure.toFixed(2)})`, // color: BLACK, // size: gridSize / 2 // }) // label.position.set( // target.object.position.x, // target.object.position.y, // target.object.position.z // ) // const labelToCam = label.position.clone().sub(camera.position) // labelToCam.normalize() // label.position.sub(labelToCam.multiplyScalar(10)) // scene.add(label) // label.lookAt(camera.position) // } if (state.get('showGrid')) { scene.add(grid) } else { scene.remove(grid) } if (state.get('showSurface')) { scene.add(cubesInstance) } else { scene.remove(cubesInstance) } if (state.get('showParticles')) { scene.add(particlesSceneNode) } else { scene.remove(particlesSceneNode) } config.sph.viscosity = state.get('viscosity') const surfaceResolution = state.get('surfaceResolution') if (config.scene.surfaceResolution !== surfaceResolution) { scene.remove(cubesInstance) cubesInstance = new MarchingCubes( surfaceResolution, cubesMaterial, true, true ) cubesInstance.position.set(0, 0, 0) cubesInstance.scale.set(40, 40, 40) config.scene.surfaceResolution = surfaceResolution } renderer.render(scene, camera) } animate() return () => { renderer.dispose() scene = null renderer = null } } const SPH = ({ state, labels }) => { React.useEffect(() => { if (document.getElementById('sph')) { return init({ state }) } }) return <canvas id="sph" /> } export { init } export default SPH
packages/react-jsx-highcharts/src/components/FunnelSeries/FunnelSeries.js
AlexMayants/react-jsx-highcharts
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Series from '../Series'; class FunnelSeries extends Component { static propTypes = { id: PropTypes.string.isRequired }; render () { return ( <Series {...this.props} type="funnel" /> ); } } export default FunnelSeries;
packages/material-ui-icons/src/SettingsInputAntenna.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SettingsInputAntenna = props => <SvgIcon {...props}> <path d="M12 5c-3.87 0-7 3.13-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.87-3.13-7-7-7zm1 9.29c.88-.39 1.5-1.26 1.5-2.29 0-1.38-1.12-2.5-2.5-2.5S9.5 10.62 9.5 12c0 1.02.62 1.9 1.5 2.29v3.3L7.59 21 9 22.41l3-3 3 3L16.41 21 13 17.59v-3.3zM12 1C5.93 1 1 5.93 1 12h2c0-4.97 4.03-9 9-9s9 4.03 9 9h2c0-6.07-4.93-11-11-11z" /> </SvgIcon>; SettingsInputAntenna = pure(SettingsInputAntenna); SettingsInputAntenna.muiName = 'SvgIcon'; export default SettingsInputAntenna;
src/app/User.js
halhenke/life-letters
import React from 'react'; import classnames from 'classnames'; import styles from './User.css'; import {GeneSequence, SequenceKey} from './Genetics.js'; import {Card, CardHeader, Avatar, CardMedia, CardTitle} from 'material-ui'; import {Paper} from 'material-ui'; import Colors from 'material-ui/src/styles/colors'; import {RaisedButton} from 'material-ui'; import fb from 'flexboxgrid/dist/flexboxgrid.css'; export const UserList = React.createClass({ propTypes: { user: React.PropTypes.object.required, click: React.PropTypes.func.required, order: React.PropTypes.number.required, }, choose(e) { e.preventDefault(); this.props.click(this.props.order); }, render() { const bgStyle = { backgroundImage: `url(${this.props.user.avatar})`, }; const initialAvatar = ( <Avatar backgroundColor={(this.props.user.gender === 'female') ? Colors.red400 : Colors.blue400} > {this.props.user.firstName[0]}{this.props.user.lastName[0]} </Avatar> ); return ( <section className={styles.user} onClick={this.choose}> <Card> <CardHeader avatar={initialAvatar} title={`${this.props.user.firstName} ${this.props.user.lastName}`} /> <CardMedia> <div className={styles.imgCont}> <div className={styles.imgBG} style={bgStyle}> { // <img src={this.props.avatar}/> } </div> </div> </CardMedia> </Card> </section> ); }, }); export const UserDetail = React.createClass({ propTypes: { user: React.PropTypes.object.required, reference: React.PropTypes.array.required, geneRegions: React.PropTypes.array.required, clicked: React.PropTypes.func.required, }, back(e) { e.preventDefault(); this.props.clicked(); }, render() { const fullName = `${this.props.user.firstName} ${this.props.user.lastName}`; const avatarClasses = classnames([ fb[`col-xs-6`], ]); return ( <div> <RaisedButton label="Back to Users" secondary={true} onClick={this.back} /> <Paper> <Card> <div className={fb[`row`]}> <div className={fb[`col-xs-6`]}> <SequenceKey /> </div> <div className={avatarClasses}> <CardMedia overlay={<CardTitle title={fullName} />} > <img src={this.props.user.avatar}/> </CardMedia> </div> </div> </Card> <div> <GeneSequence refSequence={this.props.reference} userSequence={this.props.user.sequence} geneRegions={this.props.geneRegions} /> </div> </Paper> </div> ); }, });
node_modules/babel-preset-react-hmre/test/Test.js
ajames72/MovieDBReact
import React from 'react' export default class Test extends React.Component { render() { return ( <div>Winning?</div> ) } }
docs/examples/Checkbox/Example1.js
romagny13/react-form-validation
import React from 'react'; import { Checkbox } from 'romagny13-react-form-validation'; const Example1 = () => { let values = ['a','c']; return ( <div> <h4>Direct check</h4> <Checkbox checked name="g1" /> <h4>Grouped by name (all checked are checked)</h4> <Checkbox checked name="g2" /> <Checkbox checked name="g2" /> <h4>Checked by value (if values contains control value)</h4> <Checkbox name="g3" value="a" checked={values.indexOf("a") !== -1}/> <Checkbox name="g3" value="b" checked={values.indexOf("b") !== -1}/> <Checkbox name="g3" value="c" checked={values.indexOf("c") !== -1}/> </div> ); }; export default Example1;
server/sonar-web/src/main/js/apps/system/section.js
joansmith/sonarqube
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import ItemValue from './item-value'; export default React.createClass({ render() { let items = this.props.items.map(item => { return <tr key={item.name}> <td className="thin"> <div style={{ width: '25vw', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.name}</div> </td> <td style={{ wordBreak: 'break-all' }}><ItemValue name={item.name} value={item.value}/></td> </tr>; }); return <div className="big-spacer-bottom"> <h3 className="spacer-bottom">{this.props.section}</h3> <table className="data zebra" id={this.props.section}> <tbody>{items}</tbody> </table> </div>; } });