path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
packages/material-ui/src/List/ListItemSecondaryAction.js
cherniavskii/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; export const styles = { root: { position: 'absolute', right: 4, top: '50%', transform: 'translateY(-50%)', }, }; function ListItemSecondaryAction(props) { const { children, classes, className, ...other } = props; return ( <div className={classNames(classes.root, className)} {...other}> {children} </div> ); } ListItemSecondaryAction.propTypes = { /** * The content of the component, normally an `IconButton` or selection control. */ children: PropTypes.node, /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, }; ListItemSecondaryAction.muiName = 'ListItemSecondaryAction'; export default withStyles(styles, { name: 'MuiListItemSecondaryAction' })(ListItemSecondaryAction);
src/Parser/Hunter/BeastMastery/Modules/Traits/Thunderslash.js
enragednuke/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; import SpellIcon from "common/SpellIcon"; import SpellLink from 'common/SpellLink'; import ItemDamageDone from 'Main/ItemDamageDone'; class Thunderslash extends Analyzer { static dependencies = { combatants: Combatants, }; damage = 0; on_initialized() { this.active = this.combatants.selected.traitsBySpellId[SPELLS.THUNDERSLASH_TRAIT.id]; } on_byPlayerPet_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.THUNDERSLASH_DAMAGE.id) { return; } this.damage += event.amount + (event.absorbed || 0); } subStatistic() { return ( <div className="flex"> <div className="flex-main"> <SpellLink id={SPELLS.THUNDERSLASH_TRAIT.id}> <SpellIcon id={SPELLS.THUNDERSLASH_TRAIT.id} noLink /> Thunderslash </SpellLink> </div> <div className="flex-sub text-right"> <ItemDamageDone amount={this.damage} /> </div> </div> ); } } export default Thunderslash;
examples/todomvc/containers/TodoApp.js
TallerWebSolutions/redux-devtools-gentest-plugin
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { Connector } from 'react-redux'; import Header from '../components/Header'; import MainSection from '../components/MainSection'; import * as TodoActions from '../actions/TodoActions'; export default class TodoApp extends Component { render() { return ( <Connector select={state => ({ todos: state.todos })}> {this.renderChild} </Connector> ); } renderChild({ todos, dispatch }) { const actions = bindActionCreators(TodoActions, dispatch); return ( <div> <Header addTodo={actions.addTodo} /> <MainSection todos={todos} actions={actions} /> </div> ); } }
src/svg-icons/maps/map.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsMap = (props) => ( <SvgIcon {...props}> <path d="M20.5 3l-.16.03L15 5.1 9 3 3.36 4.9c-.21.07-.36.25-.36.48V20.5c0 .28.22.5.5.5l.16-.03L9 18.9l6 2.1 5.64-1.9c.21-.07.36-.25.36-.48V3.5c0-.28-.22-.5-.5-.5zM15 19l-6-2.11V5l6 2.11V19z"/> </SvgIcon> ); MapsMap = pure(MapsMap); MapsMap.displayName = 'MapsMap'; MapsMap.muiName = 'SvgIcon'; export default MapsMap;
src/time-travel/TimeTravelList.js
wuxinwei240/React-Bacon-Timetravel-Example
import React, { Component } from 'react'; import h from 'react-hyperscript'; import Bacon from 'baconjs'; export default class TimeTravelList extends Component { componentWillMount() { var state$ = Bacon.combineTemplate({ actions: this.props.timetravel.actions$, states: this.props.timetravel.states$, index: this.props.timetravel.index$ }); this.unsubscribe = state$.onValue((state) => { this.setState(state); }); } componentWillUnmount() { this.unsubscribe(); } onClick(i) { this.props.timetravel.timelineAction$.push({type: 'goto', payload: {index: i}}); } renderItem(item, i) { return h('li', { key: i, onClick: this.onClick.bind(this, i) }, [ `Action ${item.type} ${JSON.stringify(item.payload)} => Store ${JSON.stringify(this.state.states[i])} ${i == this.state.index ? '<' : ''}` ]); } render() { return h('ol', [ this.state.actions.map(this.renderItem.bind(this)) ]); } };
src/svg-icons/device/battery-charging-80.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryCharging80 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h4.93L13 7v2h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9h-4v3.5z"/> </SvgIcon> ); DeviceBatteryCharging80 = pure(DeviceBatteryCharging80); DeviceBatteryCharging80.displayName = 'DeviceBatteryCharging80'; DeviceBatteryCharging80.muiName = 'SvgIcon'; export default DeviceBatteryCharging80;
src/SafeAnchor.js
bbc/react-bootstrap
import React from 'react'; import createChainedFunction from './utils/createChainedFunction'; /** * Note: This is intended as a stop-gap for accessibility concerns that the * Bootstrap CSS does not address as they have styled anchors and not buttons * in many cases. */ export default class SafeAnchor extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(event) { if (this.props.href === undefined) { event.preventDefault(); } } render() { return ( <a role={this.props.href ? undefined : 'button'} {...this.props} onClick={createChainedFunction(this.props.onClick, this.handleClick)} href={this.props.href || ''}/> ); } } SafeAnchor.propTypes = { href: React.PropTypes.string, onClick: React.PropTypes.func };
src/components/Forms/InputComponent.js
dziksu/songs-manager
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactHtmlParser from 'react-html-parser'; class InputRenderComponent extends Component { constructor(props) { super(props); this.input = this.input.bind(this); } input() { const { input: { name, value, onChange, onBlur }, type = 'text', readOnly = false, className = 'form-control', placeholder = '', tabindex } = this.props; return (<input name={name} value={value} type={type} placeholder={placeholder} className={`${className}`} onChange={onChange} onBlur={onBlur} readOnly={readOnly} tabIndex={tabindex} />); } render() { return ( <div className="input-form" style={{width: "100%"}}> {this.input()} </div> ); } } export default InputRenderComponent;
src/front/app/common/components/buttons/BackButton.js
travel-and-help/start-kit
import React from 'react'; import IconButton from './IconButton'; import { hashHistory } from 'react-router'; const BackButton = ({ lightness }) => ( <IconButton iconName={'back'} iconSize={24} iconClassName={`icon_${lightness}`} clickHandler={hashHistory.goBack} /> ); BackButton.propTypes = { lightness: React.PropTypes.string }; export default BackButton;
src/components/Camera.js
neontribe/spool
import React, { Component } from 'react'; import captureVideoFrame from 'capture-video-frame'; import _ from 'lodash'; import Grid from './Grid'; import Button from './Button'; import CountdownClock from './CountdownClock'; import PageOverlay from './PageOverlay'; import TouchIcon from './TouchIcon'; import styles from './css/Camera.module.css'; import headings from '../css/Headings.module.css'; const mediaConstraints = { audio: false, video: true }; class Camera extends Component { constructor (props) { super(props); this.state = { connecting: true, streaming: false, stream: null, streamURL: null, image: null, thumbnail: null, text: '', devices: [], activeDevice: null, showDescriptionField: false }; this.startMediaStream = this.startMediaStream.bind(this); this.stopMediaStream = this.stopMediaStream.bind(this); this.onMediaSuccess = this.onMediaSuccess.bind(this); this.onMediaFailure = this.onMediaFailure.bind(this); this.startCountdown = _.debounce(this.startCountdown.bind(this), 500, { leading: true, trailing: false }); this.shutter = this.shutter.bind(this); this.save = this.save.bind(this); this.getVideoDevices = this.getVideoDevices.bind(this); this.switchVideoDevices = _.debounce(this.switchVideoDevices.bind(this), 500, { leading: true, trailing: false }); this.showDescripton = this.showDescripton.bind(this); this.hideDescripton = this.hideDescripton.bind(this); this.onTextChange = this.onTextChange.bind(this); } componentWillMount () { this.startMediaStream(); } componentWillUnmount () { this.stopMediaStream(); } startMediaStream () { // First get a hold of getUserMedia, if present const getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; if (!getUserMedia) { this.setState({ mediaFailure: { name: 'getUserMediaUnsupported' } }); return; } this.getVideoDevices().then((devices) => { var activeDevice = this.state.activeDevice || devices[0].deviceId; mediaConstraints.video = { optional: [{ sourceId: activeDevice }] }; this.setState({ activeDevice: activeDevice, devices: devices }); getUserMedia.call(navigator, mediaConstraints, this.onMediaSuccess, this.onMediaFailure); }); } getVideoDevices () { return navigator.mediaDevices.enumerateDevices().then((devices) => { return _.filter(devices, { kind: 'videoinput' }); }); } switchVideoDevices () { var currentIndex = _.findIndex(this.state.devices, { deviceId: this.state.activeDevice }); var nextIndex = (currentIndex + 1) % this.state.devices.length; var newDevice = this.state.devices[nextIndex].deviceId || this.state.activeDevice; this.setState({ activeDevice: newDevice }, () => { this.stopMediaStream(); this.startMediaStream(); }); } onMediaSuccess (stream) { this.setState({ connecting: false, streaming: true, streamURL: URL.createObjectURL(stream), stream: stream }); } onMediaFailure (error) { this.props.onFailure(error); } stopMediaStream () { this.state.stream.getTracks().map((track) => track.stop()); } startCountdown () { this.setState({ image: null, thumbnail: null, countdown: true }); } shutter () { const image = captureVideoFrame(this._viewfinder, 'png'); this.setState({ countdown: false, image: image, thumbnail: image }); } save () { // Pass the blobs up this.props.save({ text: this.state.text, image: this.state.image.blob, imageThumbnail: this.state.thumbnail.blob }); } showDescripton () { this.setState({ showDescriptionField: true }); } hideDescripton () { this.setState({ showDescriptionField: false }); } onTextChange (event) { this.setState({ text: event.target.value }); } render () { return ( <div className={styles.wrapper}> {this.state.showDescriptionField && ( <div className={styles.description}> <h2 className={headings.large}>Add a description</h2> <div className={styles.content}> <textarea maxLength={this.props.maxTextLength} className={styles.textarea} value={this.state.text} onChange={this.onTextChange} ></textarea> <p className={styles.charCounter}> {this.state.text.length} of {this.props.maxTextLength} letters used </p> </div> <div className={styles.descriptionControls}> <Button onClick={this.hideDescripton}><TouchIcon />Save</Button> </div> </div> )} <Grid enforceConsistentSize={true}> <div className={styles.outputWrapper}> {this.state.connecting && <PageOverlay title='Connecting.' />} {this.state.streaming && ( <video className={styles.video} ref={(ref) => { this._viewfinder = ref; }} src={this.state.streamURL} muted={true} autoPlay={true} /> )} {this.state.thumbnail && ( <div> <img className={styles.thumbnail} src={this.state.thumbnail.dataUri} alt='Your most recent take' /> {this.state.text && ( <div className={styles.text}>{this.state.text}</div> )} </div> )} {this.state.countdown && ( <CountdownClock seconds={this.props.countdownSeconds} onComplete={this.shutter} /> )} </div> <div className={styles.btnStack}> {((this.state.devices.length > 1) && !this.state.countdown) && ( <Button onClick={this.switchVideoDevices} >Switch Cameras</Button> )} {(!this.state.countdown && !this.state.image) && ( <Button onClick={this.startCountdown} ><TouchIcon />Take Picture</Button> )} {this.state.image && [ <Button key={0} onClick={this.startCountdown} >Try Again</Button>, <Button key={1} onClick={this.showDescripton} >Add Description</Button>, <Button key={2} onClick={this.save} ><TouchIcon />Save</Button> ]} </div> </Grid> </div> ); } } Camera.propTypes = { save: React.PropTypes.func.isRequired, onFailure: React.PropTypes.func.isRequired, countdownSeconds: React.PropTypes.number }; Camera.defaultProps = { countdownSeconds: 3, maxTextLength: 1000 }; /** * Expose a test for media capabilities for use by other components */ Camera.mediaCheck = function () { return new Promise(function (resolve, reject) { function mediaOK (stream) { stream.getTracks().map((track) => track.stop()); resolve(); } function mediaFail (error) { reject(error); } // First get a hold of getUserMedia, if present const getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); if (!getUserMedia) { reject({ name: 'getUserMediaUnsupported' }); } else { getUserMedia.call(navigator, mediaConstraints, mediaOK, mediaFail);// First get a hold of getUserMedia, if present } }); }; export default Camera;
src/js/components/cardView.js
jesseokeya/bigechs
import React from 'react'; import './css/styles.css' class CardView extends React.Component { constructor(props) { super(props); this.state = { info: props.info }; } render() { return ( <div className="col-md-6 col-lg-3"> <div className="card" style={{ height: '31rem' }}> <img className="card-img-top img-fluid" src={this.state.info.img}/> <div className="card-block"> <h3 className="card-title">{this.state.info.title}</h3> { this.state.info.text.map((result, index)=>{ return ( <p className="card-text" key={index}> {result} </p> ); }) } </div> </div> </div> ); } } export default CardView;
src/components/app.js
ronaldofs/starterkit-electron-react-es6
import React from 'react'; import ReactDOM from 'react-dom'; import Main from './main/Main.js'; const remote = window.require('remote'); let container = document.createElement('div'); document.body.appendChild(container); ReactDOM.render(<Main />, container);
src/components/SettingsManager/Links.js
welovekpop/uwave-web-welovekpop.club
import React from 'react'; import PropTypes from 'prop-types'; import withProps from 'recompose/withProps'; import { translate } from 'react-i18next'; import Button from '@material-ui/core/Button'; import LicenseIcon from '@material-ui/icons/Copyright'; import GithubIcon from './GithubIcon'; const enhance = translate(); const Link = withProps({ className: 'SettingsPanel-link', target: '_blank', })(Button); const Links = ({ t }) => ( <div> <h2 className="SettingsPanel-header">{t('settings.links.title')}</h2> <Link href="http://u-wave.net"> <GithubIcon className="SettingsPanel-linkIcon" /> {t('settings.links.website')} </Link> <Link href="https://github.com/u-wave/web"> <GithubIcon className="SettingsPanel-linkIcon" /> {t('settings.links.source')} </Link> <Link href="https://github.com/u-wave/web/tree/master/LICENSE"> <LicenseIcon className="SettingsPanel-linkIcon" /> {t('settings.links.license')} </Link> </div> ); Links.propTypes = { t: PropTypes.func.isRequired, }; export default enhance(Links);
docs/app/Examples/modules/Embed/States/index.js
shengnian/shengnian-ui-react
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const EmbedStatesExamples = () => ( <ExampleSection title='States'> <ComponentExample title='Active' description='An embed can be active.' examplePath='modules/Embed/States/EmbedExampleActive' /> </ExampleSection> ) export default EmbedStatesExamples
src/pages/graph/Findbridges/Findbridges.js
hyy1115/react-redux-webpack2
import React from 'react' class Findbridges extends React.Component { render() { return ( <div>Findbridges</div> ) } } export default Findbridges
src/routes.js
Alex-Just/gymlog
import React from 'react'; import { Route, IndexRoute, Redirect } from 'react-router'; import App from './components/App'; // import CounterApp from './containers/CounterApp'; import GymlogApp from './containers/GymlogApp'; export default ( <Route path="/" component={App}> <IndexRoute component={GymlogApp}/> <Redirect from="*" to="/"/> </Route> );
src/shared/components/form/form.js
sethbergman/operationcode_frontend
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import styles from './form.css'; const Form = ({ className, children }) => { const classes = classNames({ [`${styles.form}`]: true, [`${className}`]: className }); return ( <form className={classes}> {children} </form> ); }; Form.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.element ]).isRequired, className: PropTypes.string }; Form.defaultProps = { className: null }; export default Form;
src/containers/PhotoPage.js
nickeblewis/walkapp
/** * Component that lists all Posts */ import React from 'react' import { graphql } from 'react-apollo' import gql from 'graphql-tag' // import { Link } from 'react-router' import { withRouter } from 'react-router' import { CloudinaryContext, Transformation, Image } from 'cloudinary-react' class PhotoPage extends React.Component { static propTypes = { data: React.PropTypes.shape({ loading: React.PropTypes.bool, error: React.PropTypes.object, Photo: React.PropTypes.object, }).isRequired, router: React.PropTypes.object.isRequired, params: React.PropTypes.object.isRequired } render () { // const outputUrl = "http://placehold.it/400x400"; // var myText = this.props.params.id; // console.log(this.props.data.Photo) // let outputUrl = ''; // if(this.props.data.Photo.publicId === null) { // outputUrl = this.props.data.Photo.imageUrl; // } else { // outputUrl = 'http://res.cloudinary.com/dqpknoetx/image/upload/c_scale,w_1200/v1489441520/' + this.props.data.Photo.publicId; // } if (this.props.data.loading) { return (<div>Loading</div>) } if (this.props.data.error) { console.log(this.props.data.error) return (<div>An unexpected error occurred</div>) } // const Photo = this.props.data.Photo return ( <article className="avenir"> <div className="pa4 ph7-l mw9-l center"> <CloudinaryContext cloudName="dqpknoetx"> <Image publicId={this.props.data.Photo.publicId}> <Transformation width="800" crop="scale" /> </Image> </CloudinaryContext> <h4 className="f1 ttu tracked-tight mt0">{this.props.data.Photo.name} </h4> <p className="f4 mid-gray lh-copy"> {this.props.data.Photo.description} {/* {this.props.data.Photo.publicId} */} </p> </div> </article> ) } } const PhotoQuery = gql` query PhotoQuery($id: ID!) { Photo(id: $id) { id publicId name description } } ` const PhotoPageWithQuery = graphql(PhotoQuery,{ options: (ownProps) => ({ variables: { id: ownProps.params.id } }) })(withRouter(PhotoPage)) // Nilan suggests.... // const PhotoQuery = gqlquery PhotoQuery($id: ID!) { Photo(id: $id) { id file { url } } } // const PhotoComponentWithData = graphql(PhotoQuery, { // options: (ownProps) => ({ // variables: { // id: ownProps.params.id // } // }) // } // )(withRouter(Photo)) export default PhotoPageWithQuery
src/TabPane.js
herojobs/react-bootstrap
import React from 'react'; import deprecationWarning from './utils/deprecationWarning'; import Tab from './Tab'; const TabPane = React.createClass({ componentWillMount() { deprecationWarning( 'TabPane', 'Tab', 'https://github.com/react-bootstrap/react-bootstrap/pull/1091' ); }, render() { return ( <Tab {...this.props} /> ); } }); export default TabPane;
jenkins-design-language/src/js/components/material-ui/svg-icons/av/web.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const AvWeb = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 14H4v-4h11v4zm0-5H4V9h11v4zm5 5h-4V9h4v9z"/> </SvgIcon> ); AvWeb.displayName = 'AvWeb'; AvWeb.muiName = 'SvgIcon'; export default AvWeb;
manoseimas/compatibility_test/client/app/ResultsView/Sidebar.js
ManoSeimas/manoseimas.lt
import React from 'react' import { connect } from 'react-redux' import { subscribe } from 'subscribe-ui-event' import { FacebookShare, ManoBalsas } from '../../components' import styles from '../../styles/views/results.css' class Sidebar extends React.Component { static propTypes = { fractions: React.PropTypes.array } constructor (props) { super(props) this.state = { sticky: false } this.subscribers this.scrollHandler = this.scrollHandler.bind(this) } componentDidMount () { this.subscribers = [ subscribe('scroll', this.scrollHandler, {enableScrollInfo:true}) ] } componentWillUnmount () { let subscribers = this.subscribers || [] for (let subscriber of subscribers) { subscriber.unsubscribe() } } scrollHandler (event, payload) { if (payload.scroll.top > 100 && !this.state.sticky) { this.setState({sticky: true}) } if (payload.scroll.top < 101 && this.state.sticky) { this.setState({sticky: false}) } } trackFBShare (response) { if (response) window.ga('send', 'event', { eventCategory: 'Facebook Share', eventAction: 'click', eventLabel: 'Post successfully shared' }) } render () { let sticky_style = {} if (this.state.sticky) { sticky_style = { position: 'fixed', top: '10px' } } if (this.props.fractions.length !== 0) return ( <div className={styles.side}> <div style={sticky_style}> <FacebookShare responseHandler={this.trackFBShare} fractions={this.props.fractions} /> <ManoBalsas /> </div> </div> ) return null } } const mapStateToProps = (state) => ({ fractions: state.results.fractions }) export default connect((mapStateToProps), {})(Sidebar)
packages/core/src/icons/components/Pause.js
iCHEF/gypcrete
import React from 'react'; export default function SvgPause(props) { return ( <svg width="1em" height="1em" viewBox="0 0 1000 1000" xmlns="http://www.w3.org/2000/svg" {...props} > <path fillRule="evenodd" clipRule="evenodd" d="M187.6 500c.2-172.5 140-312.3 312.5-312.5 172.5.2 312.2 140 312.5 312.5-.2 172.5-140 312.3-312.5 312.5-172.6-.2-312.4-140-312.5-312.5zm70.2 0C258 633.7 366.3 742 500 742.2 633.7 742 742 633.7 742.2 500 742 366.3 633.7 258 500 257.9 366.3 258 258 366.4 257.9 500h-.1zm273.4 125V375H625v250h-93.8zM375 625V375h93.7v250H375z" /> </svg> ); }
src/components/jog.js
DarklyLabs/LaserWeb4
/** * Jog module. * @module */ // React import React from 'react' import { connect } from 'react-redux'; import keydown, { Keys } from 'react-keydown'; import { PanelGroup, Panel, ProgressBar} from 'react-bootstrap'; import { setSettingsAttrs } from '../actions/settings'; import { setWorkspaceAttrs } from '../actions/workspace'; import CommandHistory from './command-history'; import { Input, TextField, NumberField, ToggleField, SelectField } from './forms'; import { runCommand, runJob, pauseJob, resumeJob, abortJob, clearAlarm, setZero, gotoZero, checkSize, laserTest, jog, jogTo, feedOverride, spindleOverride, resetMachine } from './com.js'; import { MacrosBar } from './macros'; import '../styles/index.css' import Icon from './font-awesome' import Toggle from 'react-toggle'; import { Label } from 'react-bootstrap' var ovStep = 1; var ovLoop; var playing = false; var paused = false; $('body').on('keydown', function (ev) { if (ev.keyCode === 17) { //CTRL key down > set override stepping to 10 ovStep = 10; } }); $('body').on('keyup', function (ev) { if (ev.keyCode === 17) { //CTRL key released-> reset override stepping to 1 ovStep = 1; } }); let liveJoggingState = { hasHomed: false, active: false, disabled: true } /** * Jog component. * * @extends module:react~React~Component * @param {Object} props Component properties. */ class Jog extends React.Component { constructor(props) { super(props); let { jogStepsize, jogFeedXY, jogFeedZ, machineZEnabled, machineAEnabled } = this.props.settings; this.state = { jogStepsize: jogStepsize, jogFeedXY: jogFeedXY, jogFeedZ: jogFeedZ, liveJogging: liveJoggingState, isPlaying: playing, isPaused: paused, machineZEnabled: machineZEnabled, machineAEnabled: machineAEnabled, }; } componentWillUnmount() { liveJoggingState = this.state.liveJogging; } @keydown('alt+right') jogRight(event) { event.preventDefault(); this.jog('X', '+') } @keydown('alt+left') jogLeft(event) { event.preventDefault(); this.jog('X', '-') } @keydown('alt+up') jogUp(event) { event.preventDefault(); this.jog('Y', '+') } @keydown('alt+down') jogDown(event) { event.preventDefault(); this.jog('Y', '-') } @keydown('ctrl+alt+up') jogZUp(event) { event.preventDefault(); this.jog('Z', '+') } @keydown('ctrl+alt+down') jogZDown(event) { event.preventDefault(); this.jog('Z', '-') } @keydown('ctrl+alt+right') jogAplus(event) { event.preventDefault(); this.jog('A', '+') } @keydown('ctrl+alt+left') jogAminus(event) { event.preventDefault(); this.jog('A', '-') } @keydown('ctrl+x') keylogger( event ) { event.preventDefault(); resetMachine(); } homeAll() { console.log('homeAll'); let cmd = this.props.settings.gcodeHoming; if (!this.state.isPlaying) this.setState({ liveJogging: { ... this.state.liveJogging, hasHomed: true, disabled: false } }) runCommand(cmd); } runCommand(e) { console.log('runCommand ' + e); runCommand(e); } runJob() { if (!playing) { let cmd = this.props.gcode; //alert(cmd); console.log('runJob(' + cmd.length + ')'); playing = true; this.setState({ isPlaying: true, liveJogging: { ... this.state.liveJogging, disabled: true, hasHomed: false } }) runJob(cmd); } else { if (!paused) { console.log('pauseJob'); paused = true; this.setState({ isPaused: true }) pauseJob(); } else { console.log('resumeJob'); paused = false; this.setState({ isPaused: false }) resumeJob(); } } } pauseJob() { console.log('pauseJob'); let cmd = this.props.settings.gcodeToolOff; pauseJob(); } resumeJob() { console.log('resumeJob'); let cmd = this.props.settings.gcodeToolOn; resumeJob(); } abortJob() { if ($('#machineStatus').html() == 'Alarm') { console.log('clearAlarm'); clearAlarm(2); } else if ($('#machineStatus').html() == 'Idle' && !paused) { console.log('abort ignored, because state is idle'); } else { console.log('abortJob'); paused = false; playing = false; this.setState({ isPaused: false, isPlaying: false }) abortJob(); } } setZero(axis) { console.log('setZero(' + axis + ')'); setZero(axis); } gotoZero(axis) { console.log('gotoZero(' + axis + ')'); gotoZero(axis); } checkSize() { console.log('checkSize'); let feedrate = $('#jogfeedxy').val() * 60; let gcode = this.props.gcode; let xArray = gcode.split(/x/i); let xMin = 0; let xMax = 0; for (let i = 0; i < xArray.length; i++) { if (parseFloat(xArray[i]) < xMin) { xMin = parseFloat(xArray[i]); } if (parseFloat(xArray[i]) > xMax) { xMax = parseFloat(xArray[i]); } } let yArray = gcode.split(/y/i); let yMin = 0; let yMax = 0; for (let i = 0; i < yArray.length; i++) { if (parseFloat(yArray[i]) < yMin) { yMin = parseFloat(yArray[i]); } if (parseFloat(yArray[i]) > yMax) { yMax = parseFloat(yArray[i]); } } let power = this.props.settings.gcodeCheckSizePower / 100 * this.props.settings.gcodeSMaxValue; let moves = ` G90\n G0 X` + xMin + ` Y` + yMin + ` F` + feedrate + `\n G1 F` + feedrate + ` S` + power + `\n G1 X` + xMax + ` Y` + yMin + `\n G1 X` + xMax + ` Y` + yMax + `\n G1 X` + xMin + ` Y` + yMax + `\n G1 X` + xMin + ` Y` + yMin + `\n G90\n`; runCommand(moves); } laserTest() { console.log('laserTest'); let power = this.props.settings.gcodeToolTestPower; let duration = this.props.settings.gcodeToolTestDuration; let maxS = this.props.settings.gcodeSMaxValue; console.log('laserTest(' + power + ',' + duration + ',' + maxS + ')'); laserTest(power, duration, maxS); } jog(axis, dir) { let dist = this.props.settings.jogStepsize; let units = this.props.settings.toolFeedUnits; let feed, mult = 1, mode = 1; let x, y, z, a; if (dir === '+') { dir = ''; } if (units == 'mm/s') mult = 60; switch (axis) { case 'X': x = dir + dist; feed = jQuery('#jogfeedxy').val() * mult; break; case 'Y': y = dir + dist; feed = jQuery('#jogfeedxy').val() * mult; break; case 'Z': z = dir + dist; feed = jQuery('#jogfeedz').val() * mult; break; case 'A': a = dir + dist; feed = jQuery('#jogfeedxy').val() * mult; break; } CommandHistory.log('jog(' + axis + ',' + dir + dist + ',' + feed + ')'); jog(axis, dir + dist, feed); //CommandHistory.log('jogTo(' + x + ',' + y + ',' + z + ',' + mode + ',' + feed + ')'); //jogTo(x, y, z, mode, feed); } changeJogFeedXY(e) { console.log('changeJogFeedXY'); let that = this; that.setState({ jogFeedXY: e }); let { dispatch } = this.props; dispatch(setSettingsAttrs({ jogFeedXY: e })); } changeJogFeedZ(e) { console.log('changeJogFeedZ'); let that = this; that.setState({ jogFeedZ: e }); let { dispatch } = this.props; dispatch(setSettingsAttrs({ jogFeedZ: e })); } changeStepsize(stepsize) { let that = this; that.setState({ jogStepsize: stepsize }); let { dispatch } = this.props; dispatch(setSettingsAttrs({ jogStepsize: stepsize })); console.log('Jog will use ' + stepsize + ' mm per click'); CommandHistory.write('Jog will use ' + stepsize + ' mm per click', CommandHistory.WARN); //$('.stepsizeval').empty(); //$('.stepsizeval').html(stepsize + 'mm'); } resetF() { console.log('resetFeedOverride'); feedOverride(0); } increaseF() { console.log('increaseFeedOverride ' + ovStep); feedOverride(ovStep); } decreaseF() { console.log('decreaseFeedOverride ' + ovStep); feedOverride(-ovStep); } resetS() { console.log('resetSpindeOverride'); spindleOverride(0); } increaseS() { console.log('increaseSpindleOverride ' + ovStep); spindleOverride(ovStep); } decreaseS() { console.log('decreaseSpindleOverride ' + ovStep); spindleOverride(-ovStep); } /** * Render the component. * @return {String} */ render() { let { settings, dispatch } = this.props; const machineZEnabled = this.state.machineZEnabled; const machineAEnabled = this.state.machineAEnabled; return ( <div style={{ paddingTop: 6 }} > <span className="badge badge-default badge-notify" title="Items in Queue" id="machineStatus" style={{ marginRight: 5 }}>Not Connected</span> <span className="badge badge-default badge-notify" title="Items in Queue" id="queueCnt" style={{ marginRight: 5 }}>Queued: 0</span> <div id="mPosition" className="well well-sm" style={{ marginBottom: 7}}> <div id="rX" className="drolabel">X:</div> <div className="btn-group dropdown" style={{ marginLeft: -3 }}> <button id="" type="button" className="btn btn-sm btn-default" style={{ padding: 2, top: -3, backgroundColor: '#ffdbdb' }} data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span className="fa-stack fa-1x"> <i className="fa fa-caret-down fa-stack-1x"></i> </span> </button> <ul className="dropdown-menu"> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-hand-o-down" aria-hidden="true"></i><b>Probe Stock</b><br />NB: Manually jog to ensure other<br />axes are clear first</li> <li id="XProbeMin"><a href="#"><i className="fa fa-fw fa-arrow-right" aria-hidden="true"></i>Probe X Min</a></li> <li id="XProbeMax"><a href="#"><i className="fa fa-fw fa-arrow-left" aria-hidden="true"></i>Probe X Max</a></li> <li role="separator" className="divider"></li> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-crop" aria-hidden="true"></i><b>Work Coordinates</b></li> <li id="homeX"><a href="#"><i className="fa fa-fw fa-home" aria-hidden="true"></i>Home X Axis</a></li> <li id="zeroX"><a href="#" onClick={(e) => { this.setZero('x') }}><i className="fa fa-fw fa-crosshairs" aria-hidden="true"></i>Set X Axis Zero</a></li> <li role="separator" className="divider"></li> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-arrows" aria-hidden="true"></i><b>Move</b></li> <li id="gotoXZero"><a href="#" onClick={(e) => { this.gotoZero('x') }}><i className="fa fa-fw fa-play" aria-hidden="true"></i>G0 to X0</a></li> </ul> </div> <div id="mX" className="droPos" style={{ marginRight: 0, backgroundColor: '#ffdbdb' }}>0.00</div><div className="droUnit" style={{ backgroundColor: '#ffdbdb' }}> mm</div> <br /> <div id="rY" className="drolabel">Y:</div> <div className="btn-group dropdown" style={{ marginLeft: -3 }}> <button id="" type="button" className="btn btn-sm btn-default" style={{ padding: 2, top: -3, backgroundColor: '#dbffdf' }} data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span className="fa-stack fa-1x"> <i className="fa fa-caret-down fa-stack-1x"></i> </span> </button> <ul className="dropdown-menu"> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-hand-o-down" aria-hidden="true"></i><b>Probe Stock</b><br />NB: Manually jog to ensure other<br />axes are clear first</li> <li id="YProbeMin"><a href="#"><i className="fa fa-fw fa-arrow-up" aria-hidden="true"></i>Probe Y Min</a></li> <li id="YProbeMax"><a href="#"><i className="fa fa-fw fa-arrow-down" aria-hidden="true"></i>Probe Y Max</a></li> <li role="separator" className="divider"></li> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-crop" aria-hidden="true"></i><b>Work Coordinates</b></li> <li id="homeY"><a href="#"><i className="fa fa-fw fa-home" aria-hidden="true"></i>Home Y Axis</a></li> <li id="zeroY"><a href="#" onClick={(e) => { this.setZero('y') }}><i className="fa fa-fw fa-crosshairs" aria-hidden="true"></i>Set Y Axis Zero</a></li> <li role="separator" className="divider"></li> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-arrows" aria-hidden="true"></i><b>Move</b></li> <li id="gotoYZero"><a href="#" onClick={(e) => { this.gotoZero('y') }}><i className="fa fa-fw fa-play" aria-hidden="true"></i>G0 to Y0</a></li> </ul> </div> <div id="mY" className="droPos" style={{ marginRight: 0, backgroundColor: '#dbffdf' }}>0.00</div><div className="droUnit" style={{ backgroundColor: '#dbffdf' }}> mm</div> <br /> {machineZEnabled && ( <div> <div id="rZ" className="drolabel">Z:</div> <div className="btn-group dropdown" style={{ marginLeft: -3 }}> <button id="" type="button" className="btn btn-sm btn-default" style={{ padding: 2, top: -3, backgroundColor: '#dbe8ff' }} data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span className="fa-stack fa-1x"> <i className="fa fa-caret-down fa-stack-1x"></i> </span> </button> <ul className="dropdown-menu"> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-hand-o-down" aria-hidden="true"></i><b>Probe Stock</b><br />NB: Manually jog to ensure other<br />axes are clear first</li> <li id="ZProbeMin"><a href="#" ><i className="fa fa-fw fa-arrow-down" aria-hidden="true"></i>Probe Z Min</a></li> <li role="separator" className="divider"></li> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-crop" aria-hidden="true"></i><b>Work Coordinates</b></li> <li id="homeZ"><a href="#"><i className="fa fa-fw fa-home" aria-hidden="true"></i>Home Z Axis</a></li> <li id="zeroZ"><a href="#" onClick={(e) => { this.setZero('z') }}><i className="fa fa-fw fa-crosshairs" aria-hidden="true"></i>Set Z Axis Zero</a></li> <li role="separator" className="divider"></li> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-arrows" aria-hidden="true"></i><b>Move</b></li> <li id="gotoZZero"><a href="#" onClick={(e) => { this.gotoZero('z') }}><i className="fa fa-fw fa-play" aria-hidden="true"></i>G0 to Z0</a></li> </ul> </div> <div id="mZ" className="droPos" style={{ marginRight: 0, backgroundColor: '#dbe8ff' }}>0.00</div><div className="droUnit" style={{ backgroundColor: '#dbe8ff' }}> mm</div> <br /> </div> )} {machineAEnabled && ( <div> <div id="rA" className="drolabel">A:</div> <div className="btn-group dropdown" style={{ marginLeft: -3 }}> <button id="" type="button" className="btn btn-sm btn-default" style={{ padding: 2, top: -3, backgroundColor: '#fffbcf' }} data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span className="fa-stack fa-1x"> <i className="fa fa-caret-down fa-stack-1x"></i> </span> </button> <ul className="dropdown-menu"> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-hand-o-down" aria-hidden="true"></i><b>Probe Stock</b><br />NB: Manually jog to ensure other<br />axes are clear first</li> <li id="AProbeMin"><a href="#"><i className="fa fa-fw fa-arrow-up" aria-hidden="true"></i>Probe A Min</a></li> <li id="AProbeMax"><a href="#"><i className="fa fa-fw fa-arrow-down" aria-hidden="true"></i>Probe A Max</a></li> <li role="separator" className="divider"></li> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-crop" aria-hidden="true"></i><b>Work Coordinates</b></li> <li id="homeA"><a href="#"><i className="fa fa-fw fa-home" aria-hidden="true"></i>Home A Axis</a></li> <li id="zeroA"><a href="#" onClick={(e) => { this.setZero('y') }}><i className="fa fa-fw fa-crosshairs" aria-hidden="true"></i>Set A Axis Zero</a></li> <li role="separator" className="divider"></li> <li role="presentation" className="dropdown-header"><i className="fa fa-fw fa-arrows" aria-hidden="true"></i><b>Move</b></li> <li id="gotoAZero"><a href="#" onClick={(e) => { this.gotoZero('a') }}><i className="fa fa-fw fa-play" aria-hidden="true"></i>G0 to A0</a></li> </ul> </div> <div id="mA" className="droPos" style={{ marginRight: 0, backgroundColor: '#fffbcf' }}>0.00</div><div className="droUnit" style={{ backgroundColor: '#fffbcf' }}> mm</div> <br /> </div> )} <div id="overrides"> <div className="drolabel">F:</div> <div id="oF" className="droOR">100<span className="drounitlabel"> %</span></div> <div className="btn-group btn-override"> <button id="rF" type="button" onClick={(e) => { this.resetF(e) }} className="btn btn-sm btn-default" style={{ padding: 2, top: -3 }} data-toggle="tooltip" data-placement="bottom" title="Click to Reset F-Override to 100%"> <span className="fa-stack fa-1x"> <i className="fa fa-retweet fa-stack-1x"></i> </span> </button> <button id="iF" type="button" onClick={(e) => { this.increaseF(e) }} className="btn btn-sm btn-default" style={{ padding: 2, top: -3 }} data-toggle="tooltip" data-placement="bottom" title="Click to Increase by 1% or Ctrl+Click to increase by 10%"> <span className="fa-stack fa-1x"> <i className="fa fa-arrow-up fa-stack-1x"></i> </span> </button> <button id="dF" type="button" onClick={(e) => { this.decreaseF(e) }} className="btn btn-sm btn-default" style={{ padding: 2, top: -3 }} data-toggle="tooltip" data-placement="bottom" title="Click to Decrease by 1% or Ctrl+Click to decrease by 10%"> <span className="fa-stack fa-1x"> <i className="fa fa-arrow-down fa-stack-1x"></i> </span> </button> </div> <br /> <div className="drolabel">S:</div> <div id="oS" className="droOR">100<span className="drounitlabel"> %</span></div> <div className="btn-group btn-override"> <button id="rS" type="button" onClick={(e) => { this.resetS(e) }} className="btn btn-sm btn-default" style={{ padding: 2, top: -3 }} data-toggle="tooltip" data-placement="bottom" title="Click to Reset S-Override to 100%"> <span className="fa-stack fa-1x"> <i className="fa fa-retweet fa-stack-1x"></i> </span> </button> <button id="iS" type="button" onClick={(e) => { this.increaseS(e) }} className="btn btn-sm btn-default" style={{ padding: 2, top: -3 }} data-toggle="tooltip" data-placement="bottom" title="Click to Increase by 1% or Ctrl+Click to increase by 10%"> <span className="fa-stack fa-1x"> <i className="fa fa-arrow-up fa-stack-1x"></i> </span> </button> <button id="dS" type="button" onClick={(e) => { this.decreaseS(e) }} className="btn btn-sm btn-default" style={{ padding: 2, top: -3 }} data-toggle="tooltip" data-placement="bottom" title="Click to Decrease by 1% or Ctrl+Click to decrease by 10%"> <span className="fa-stack fa-1x"> <i className="fa fa-arrow-down fa-stack-1x"></i> </span> </button> </div> </div> </div> <div className="well well-sm" style={{ marginBottom: 7}}> <div id="controlmachine" className="btn-group" role="group" aria-label="controljob"> <div className="btn-group btn-group-justified"> <div className="btn-group"> <button type='button' id="homeAll" className="btn btn-ctl btn-default" onClick={(e) => { this.homeAll(e) }}> <span className="fa-stack fa-1x"> <i className="fa fa-home fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">home</strong> <strong className="fa-stack-1x icon-bot-text">all</strong> </span> </button> </div> <div className="btn-group"> <button type='button' id="playBtn" className="btn btn-ctl btn-default" onClick={(e) => { this.runJob(e) }}> <span className="fa-stack fa-1x"> <i id="playicon" className="fa fa-play fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">run</strong> <strong className="fa-stack-1x icon-bot-text">job</strong> </span> </button> </div> <div className="btn-group" style={{ display: 'none' }}> <button type='button' id="uploadBtn" className="btn btn-ctl btn-default" onClick={(e) => { this.uploadSD(e) }}> <span className="fa-stack fa-1x"> <i className="fa fa-hdd-o fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">upload</strong> <strong className="fa-stack-1x icon-bot-text">to SD</strong> </span> </button> </div> <div className="btn-group"> <button type='button' id="stopBtn" className="btn btn-ctl btn-default" onClick={(e) => { this.abortJob(e) }}> <span className="fa-stack fa-1x"> <i id="stopIcon" className="fa fa-stop fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">abort</strong> <strong className="fa-stack-1x icon-bot-text">job</strong> </span> </button> </div> <div className="btn-group"> <button type='button' id="zeroAll" className="btn btn-ctl btn-default" onClick={(e) => { this.setZero('all') }}> <span className="fa-stack fa-1x"> <i className="fa fa-crosshairs fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">set</strong> <strong className="fa-stack-1x icon-bot-text">zero</strong> </span> </button> </div> <div className="btn-group"> <button type='button' id="bounding" className="btn btn-ctl btn-default" onClick={(e) => { this.checkSize(e) }}> <span className="fa-stack fa-1x"> <i className="fa fa-square-o fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">check</strong> <strong className="fa-stack-1x icon-bot-text">size</strong> </span> </button> </div> </div> </div> </div> <div className="well well-sm" style={{ marginBottom: 7}}> <table className='centerTable' style={{ width: 99 + '%' }}> <tbody> <tr> <td> <button id="lT" type="button" data-title="Laser Test" className="btn btn-ctl btn-default" onClick={(e) => { this.laserTest(e) }}> <span className="fa-stack fa-1x"> <i className="fa fa-fire fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">Laser</strong> <strong className="fa-stack-1x icon-bot-text">Test</strong> </span> </button> </td> <td> <button style={{ backgroundColor: '#dbffdf' }} id="yP" type="button" data-title="Jog Y+" className="btn btn-ctl btn-default" onClick={(e) => { this.jog('Y', '+') }}> <span className="fa-stack fa-1x"> <i className="fa fa-arrow-up fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">Y+</strong> <strong className="fa-stack-1x stepsizeval icon-bot-text">{this.state.jogStepsize}mm</strong> </span> </button> </td> <td> <button id="motorsOff" type="button" data-title="Motors Off" className="btn btn-ctl btn-default" style={{ display: 'none' }} onClick={(e) => { this.motorsOff(e) }}> <span className="fa-stack fa-1x"> <i className="fa fa-power-off fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">Motors</strong> <strong className="fa-stack-1x icon-bot-text">Off</strong> </span> </button> </td> <td></td> {machineAEnabled && ( <td> <button style={{ backgroundColor: '#fffbcf' }} id="aP" type="button" data-title="Jog A+" className="btn btn-ctl btn-default" onClick={(e) => { this.jog('A', '+') }}> <span className="fa-stack fa-1x"><i className="fa fa-arrow-up fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">A+</strong> <strong className="fa-stack-1x stepsizeval icon-bot-text">{this.state.jogStepsize}mm</strong> </span> </button> </td> )} {machineZEnabled && ( <td> <button style={{ backgroundColor: '#dbe8ff' }} id="zP" type="button" data-title="Jog Z+" className="btn btn-ctl btn-default" onClick={(e) => { this.jog('Z', '+') }}> <span className="fa-stack fa-1x"><i className="fa fa-arrow-up fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">Z+</strong> <strong className="fa-stack-1x stepsizeval icon-bot-text">{this.state.jogStepsize}mm</strong> </span> </button> </td> )} {!machineZEnabled && ( <td></td> )} </tr> <tr> <td> <button style={{ backgroundColor: '#ffdbdb' }} id="xM" type="button" data-title="Jog X-" className="btn btn-ctl btn-default" onClick={(e) => { this.jog('X', '-') }}> <span className="fa-stack fa-1x"> <i className="fa fa-arrow-left fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">X-</strong> <strong className="fa-stack-1x stepsizeval icon-bot-text">{this.state.jogStepsize}mm</strong> </span> </button> </td> <td> <button style={{ backgroundColor: '#dbffdf' }} id="yM" type="button" data-title="Jog Y-" className="btn btn-ctl btn-default" onClick={(e) => { this.jog('Y', '-') }}> <span className="fa-stack fa-1x"> <i className="fa fa-arrow-down fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">Y-</strong> <strong className="fa-stack-1x stepsizeval icon-bot-text">{this.state.jogStepsize}mm</strong> </span> </button> </td> <td> <button style={{ backgroundColor: '#ffdbdb' }} id="xP" type="button" data-title="Jog X+" className="btn btn-ctl btn-default" onClick={(e) => { this.jog('X', '+') }}> <span className="fa-stack fa-1x"> <i className="fa fa-arrow-right fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">X+</strong> <strong className="fa-stack-1x stepsizeval icon-bot-text">{this.state.jogStepsize}mm</strong> </span> </button> </td> <td> <div style={{ width: '8px' }}></div> </td> {machineAEnabled && ( <td> <button style={{ backgroundColor: '#fffbcf' }} id="aM" type="button" data-title="Jog A-" className="btn btn-ctl btn-default" onClick={(e) => { this.jog('A', '-') }}> <span className="fa-stack fa-1x"> <i className="fa fa-arrow-down fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">A-</strong> <strong className="fa-stack-1x stepsizeval icon-bot-text">{this.state.jogStepsize}mm</strong> </span> </button> </td> )} {machineZEnabled && ( <td> <button style={{ backgroundColor: '#dbe8ff' }} id="zM" type="button" data-title="Jog Z-" className="btn btn-ctl btn-default" onClick={(e) => { this.jog('Z', '-') }}> <span className="fa-stack fa-1x"> <i className="fa fa-arrow-down fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">Z-</strong> <strong className="fa-stack-1x stepsizeval icon-bot-text">{this.state.jogStepsize}mm</strong> </span> </button> </td> )} {!machineZEnabled && ( <td></td> )} </tr> <tr> <td colSpan="5"> <form id="stepsize" > <div data-toggle="buttons"> <label style={{ backgroundColor: '#F5F5F5' }} className="btn btn-jog btn-default" onClick={(e) => { this.changeStepsize(0.1) }} > <input type="radio" name="stp" defaultValue="0.1" /> <span className="fa-stack fa-1x"> <i className="fa fa-arrows-h fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">jog by</strong> <strong className="fa-stack-1x icon-bot-text">0.1mm</strong> </span> </label> <label style={{ backgroundColor: '#F0F0F0' }} className="btn btn-jog btn-default" onClick={(e) => { this.changeStepsize(1) }} > <input type="radio" name="stp" defaultValue="1" /> <span className="fa-stack fa-1x"> <i className="fa fa-arrows-h fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">jog by</strong> <strong className="fa-stack-1x icon-bot-text">1mm</strong> </span> </label> <label style={{ backgroundColor: '#E8E8E8' }} className="btn btn-jog btn-default" onClick={(e) => { this.changeStepsize(10) }} > <input type="radio" name="stp" defaultValue="10" /> <span className="fa-stack fa-1x"> <i className="fa fa-arrows-h fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">jog by</strong> <strong className="fa-stack-1x icon-bot-text">10mm</strong> </span> </label> <label style={{ backgroundColor: '#E0E0E0' }} className="btn btn-jog btn-default" onClick={(e) => { this.changeStepsize(100) }} > <input type="radio" name="stp" defaultValue="100" /> <span className="fa-stack fa-1x"> <i className="fa fa-arrows-h fa-stack-1x"></i> <strong className="fa-stack-1x icon-top-text">jog by</strong> <strong className="fa-stack-1x icon-bot-text">100mm</strong> </span> </label> </div> </form> </td> </tr> <tr> <td colSpan="5"> <div className="input-group"> <span className="input-group-addon">X/Y Jog</span> <Input id="jogfeedxy" type="number" className="form-control numpad input-sm text-right" value={this.state.jogFeedXY} onChangeValue={(e) => { this.changeJogFeedXY(e) }} /> <span className="input-group-addon"><small>{settings.toolFeedUnits}</small></span> </div> </td> </tr> <tr> <td colSpan="5"> <div className="input-group"> <span className="input-group-addon">Z Jog </span> <Input id="jogfeedz" type="number" className="form-control numpad input-sm text-right" value={this.state.jogFeedZ} onChangeValue={(e) => { this.changeJogFeedZ(e) }} /> <span className="input-group-addon"><small>{settings.toolFeedUnits}</small></span> </div> </td> </tr> <tr> <td colSpan="5"> <LiveJogging {... this.state.liveJogging} onChange={(v) => this.setState({ liveJogging: { ...this.state.liveJogging, active: v } })} /> </td> </tr> </tbody> </table> </div> <div className="well well-sm" style={{ marginBottom: 7}} id="macrosBar"><MacrosBar /></div> </div> ) } } Jog = connect( state => ({ settings: state.settings, jogStepsize: state.jogStepsize, gcode: state.gcode.content }) )(Jog); // Exports export default Jog export function runStatus(status) { if (status === 'running') { playing = true; paused = false; $('#playicon').removeClass('fa-play'); $('#playicon').addClass('fa-pause'); } else if (status === 'paused') { paused = true; $('#playicon').removeClass('fa-pause'); $('#playicon').addClass('fa-play'); } else if (status === 'resumed') { paused = false; $('#playicon').removeClass('fa-play'); $('#playicon').addClass('fa-pause'); } else if (status === 'stopped') { playing = false; paused = false; $('#playicon').removeClass('fa-pause'); $('#playicon').addClass('fa-play'); } else if (status === 'finished') { playing = false; paused = false; $('#playicon').removeClass('fa-pause'); $('#playicon').addClass('fa-play'); } else if (status === 'alarm') { //socket.emit('clearAlarm', 2); } }; export class LiveJogging extends React.Component { static isEnabled() { return liveJoggingState.active && !liveJoggingState.disabled; } componentWillReceiveProps(nextProps) { liveJoggingState = { active: nextProps.active, hasHomed: nextProps.hasHomed, disabled: nextProps.disabled }; } render() { const toggleLiveJogging = (checked) => { liveJoggingState.active = checked if (this.props.onChange) this.props.onChange(checked); } return <div className="toggleField"> <Toggle disabled={!this.props.hasHomed || this.props.disabled} id="toggle_liveJogging" checked={this.props.active} onChange={e => toggleLiveJogging(e.target.checked)} /><label htmlFor="toggle_liveJogging" title="Live jogging allows to travel pressing (ALT or META)+Click in the workspace. Prior homing mandatory. Use carefully."> Live Jogging {this.props.hasHomed ? '': <Label bsStyle="danger" title="Home all first!"><Icon name="home"/>Disabled</Label>}</label> </div> } }
client/src/components/header/index.js
OpenChemistry/materialsdatabank
import React, { Component } from 'react'; import { withStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Button from '@material-ui/core/Button'; import Hidden from '@material-ui/core/Hidden'; import IconButton from '@material-ui/core/IconButton'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import LinearProgress from '@material-ui/core/LinearProgress'; import MenuIcon from '@material-ui/icons/Menu'; import SearchBar from 'material-ui-search-bar' import { connect } from 'react-redux' import _ from 'lodash' import { push } from 'connected-react-router' import './index.css' import logo from './mdb_logo.svg'; import { searchDatasetsByText } from '../../redux/ducks/datasets' import Menu from './menu' import Login from './login' import selectors from '../../redux/selectors'; const searchBarStyle = { width: '100%', maxWidth: '30rem' }; const divStyle = { width: '100%', display: 'flex', justifyContent: 'flex-end' } const loginMenuStyle = { alignSelf: 'center', marginLeft: '1rem' // marginTop: '18px' } class RightElement extends Component { constructor(props) { super(props) this.state = { searchText: null } } componentWillMount = () => { this.props.dispatch(searchDatasetsByText()); } onChange = (searchText) => { this.setState({ searchText }) } onRequestSearch = () => { this.props.dispatch(push('/results')) if (_.isString(this.state.searchText) && !_.isEmpty(this.state.searchText)) { const text = this.state.searchText.toLowerCase(); this.props.dispatch(searchDatasetsByText(text.split(/\s/))) } else { this.props.dispatch(searchDatasetsByText()); } } render = () => { return ( <div style={divStyle}> <Hidden mdDown> <SearchBar placeholder={'Search by MDB ID, name of the structure, atomic species'} onChange={this.onChange} onRequestSearch={this.onRequestSearch} style={searchBarStyle} className={'mdb-searchbar'} /> </Hidden> <div style={loginMenuStyle}> {!this.props.isAuthenticated ? <Login/> : <Menu/>} </div> </div>); } } function mapStateToProps(state) { const isAuthenticated = selectors.girder.isAuthenticated(state); return { isAuthenticated, } } RightElement = connect(mapStateToProps)(RightElement) const appBarStyles = theme => ({ appBar: { zIndex: theme.zIndex.drawer + 1, }, navIconHide: { [theme.breakpoints.up('md')]: { display: 'none', }, }, }); class Header extends Component { render = () => { const progressStyle = {} if (!this.props.progress) { progressStyle['display'] = 'none'; } const {classes, onToggleMenu} = this.props; return ( <div> <AppBar color="default" position="static" className={classes.appBar}> <Toolbar> <IconButton color="inherit" aria-label="Open drawer" onClick={onToggleMenu} className={classes.navIconHide} > <MenuIcon /> </IconButton> <Button color="inherit" aria-label="Logo" style={{marginRight: 9, paddingTop: 5, paddingBottom: 5}}> <img className='mdb-logo' src={logo} alt="logo" /> </Button> <Hidden smDown> <Typography variant="title" color="inherit" style={{flexGrow: 0}}> Materials Data Bank <Typography variant="caption" color="textSecondary"> 3D atomic views of real materials </Typography> </Typography> </Hidden> <div style={{flexGrow: 1}}> <RightElement/> </div> </Toolbar> </AppBar> <LinearProgress style={progressStyle} variant="indeterminate" /> </div> ); } } function mapStateToPropsHeader(state) { const progress = selectors.app.progress(state); return { progress, } } Header = withStyles(appBarStyles)(Header); export default connect(mapStateToPropsHeader)(Header)
react/src/routes.js
aaronbini/mile-tracker
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/App'; import HomePage from './components/home/HomePage'; import AboutPage from './components/about/AboutPage'; import CoursesPage from './components/course/CoursesPage'; import ManageCoursePage from './components/course/ManageCoursePage'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage} /> <Route path="courses" component={CoursesPage} /> <Route path="course" component={ManageCoursePage} /> <Route path="course/:id" component={ManageCoursePage} /> <Route path="about" component={AboutPage} /> </Route> );
SSBW/Tareas/Tarea9/restaurantes2/node_modules/react-bootstrap/es/Radio.js
jmanday/Master
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import warning from 'warning'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { inline: PropTypes.bool, disabled: PropTypes.bool, /** * Only valid if `inline` is not set. */ validationState: PropTypes.oneOf(['success', 'warning', 'error', null]), /** * Attaches a ref to the `<input>` element. Only functions can be used here. * * ```js * <Radio inputRef={ref => { this.input = ref; }} /> * ``` */ inputRef: PropTypes.func }; var defaultProps = { inline: false, disabled: false }; var Radio = function (_React$Component) { _inherits(Radio, _React$Component); function Radio() { _classCallCheck(this, Radio); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Radio.prototype.render = function render() { var _props = this.props, inline = _props.inline, disabled = _props.disabled, validationState = _props.validationState, inputRef = _props.inputRef, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var input = React.createElement('input', _extends({}, elementProps, { ref: inputRef, type: 'radio', disabled: disabled })); if (inline) { var _classes2; var _classes = (_classes2 = {}, _classes2[prefix(bsProps, 'inline')] = true, _classes2.disabled = disabled, _classes2); // Use a warning here instead of in propTypes to get better-looking // generated documentation. process.env.NODE_ENV !== 'production' ? warning(!validationState, '`validationState` is ignored on `<Radio inline>`. To display ' + 'validation state on an inline radio, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : void 0; return React.createElement( 'label', { className: classNames(className, _classes), style: style }, input, children ); } var classes = _extends({}, getClassSet(bsProps), { disabled: disabled }); if (validationState) { classes['has-' + validationState] = true; } return React.createElement( 'div', { className: classNames(className, classes), style: style }, React.createElement( 'label', null, input, children ) ); }; return Radio; }(React.Component); Radio.propTypes = propTypes; Radio.defaultProps = defaultProps; export default bsClass('radio', Radio);
src/shared/js/components/D3Axis.js
datalocale/dataviz-finances-gironde
import React from 'react'; export default function D3Axis({ tickData, className, onSelectedAxisItem }){ return React.createElement('g', {className: ['d3-axis', className].filter(x => x).join(' ')}, tickData.map(({id, transform, line: {x1, y1, x2, y2}, text: {x, y, dx, dy, anchor='middle', t}, className: tickClass }, i) => { return React.createElement('g', { key: i, className: ['tick', tickClass, onSelectedAxisItem ? 'actionable' : undefined].filter(x=>x).join(' '), transform, onClick(){ onSelectedAxisItem(id) }}, React.createElement('line', {x1, y1, x2, y2}), React.createElement('text', {x, y, dx, dy, textAnchor: anchor}, t) ) }) ) }
src/components/icons/CallMadeIcon.js
InsideSalesOfficial/insidesales-components
import React from 'react'; const CallMadeIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24"> {props.title && <title>{props.title}</title>} <path d="M0 0h24v24H0z" fill="none"/> <path d="M9 5v2h6.59L4 18.59 5.41 20 17 8.41V15h2V5z"/> </svg> ); export default CallMadeIcon;
src/components/form/FormField.js
shrimpliu/shradmin
import React from 'react'; import PropTypes from 'prop-types'; const FormField = () => ( <span></span> ); const formItemLayout = { labelCol: { lg: { span: 3 }, xs: { span: 24 }, sm: { span: 4 }, }, wrapperCol: { lg: { span: 6 }, xs: { span: 24 }, sm: { span: 12 }, }, }; FormField.propTypes = { source: PropTypes.string.isRequired, input: PropTypes.element.isRequired, options: PropTypes.object, layoutSpan: PropTypes.object, format: PropTypes.func, parse: PropTypes.func, }; FormField.defaultProps = { options: {}, layoutSpan: formItemLayout, format: value => value, parse: value => value, }; export default FormField;
src/js/rectangle.js
garygao12580/react_photo_wall
import React from 'react' import '../css/rectangle.less' class Rectangle extends React.Component { constructor(props) { super(props); } render() { let {item, offsetX, onLabelClick} = this.props; let className = item.active ? "active-rectangle" : "normal-rectangle"; let stepLeft = item.Index * 250 + offsetX; // let contentLeft = item.Index * 450; return ( <div className={"rectangle " + className} style={{left: stepLeft}} onClick={() => onLabelClick && onLabelClick(item.Index)}> {item.DateString} {/*<div className={"rectangle-content "}>*/} {/*<img src=""/>*/} {/*</div>*/} </div> ); } } export default Rectangle
docs/src/sections/ResponsiveEmbedSection.js
Lucifier129/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function ResponsiveEmbedSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="responsive-embed">Responsive embed</Anchor> <small>ResponsiveEmbed</small> </h2> <p>Allow browsers to determine video or slideshow dimensions based on the width of their containing block by creating an intrinsic ratio that will properly scale on any device.</p> <p>You don't need to include <code>frameborder="0"</code> in your <code>iframe</code>s.</p> <p className="bg-warning">Either <b>16by9</b> or <b>4by3</b> aspect ratio via <code>a16by9</code> or <code>a4by3</code> attribute must be set.</p> <ReactPlayground codeText={Samples.ResponsiveEmbed} /> <h3><Anchor id="responsive-embed-props">Props</Anchor></h3> <PropTable component="ResponsiveEmbed"/> </div> ); }
src/js/LoadingPage.js
ludonow/ludo-beta-react
import React from 'react'; import { browserHistory } from 'react-router'; import RefreshIndicator from 'material-ui/RefreshIndicator'; import axios from './axios-config'; // override material ui style const style = { container: { alignItems: 'center', display: 'flex', height: 'calc(100vh - 100px)', justifyContent: 'center' }, refresh: { backgroundColor: 'none', boxShadow: 'none', display: 'inline-block', position: 'relative' } }; const RefreshIndicatorExampleLoading = () => ( <div style={style.container}> <RefreshIndicator left={0} loadingColor="#FF9800" size={100} status="loading" style={style.refresh} top={0} /> </div> ); export default class LoadingPage extends React.Component { constructor(props) { super(props); } componentDidMount() { const { ludo_id } = this.props.params; const { temp_ludo_id } = this.props.params; const joinLudoPutbody = this.props.location.state; if (temp_ludo_id) { /* TODO ask pochun to create temp ludo */ // axios.put(`/apis/ludo/temp/${temp_ludo_id}`, joinLudoPutbody) // .then(response => { // if (response.data.status === '200') { // /* TODO: Figure out how to use same url redirect to other component */ // browserHistory.push(`/ludo/${ludo_id}`); // } else if (response.data.status === '400' && response.data.message === 'Your Fuel is out.') { // window.alert('你的燃料用完囉!'); // browserHistory.push(`/ludo/${ludo_id}`); // } else { // window.alert('加入Ludo發生錯誤,請重試一次;若問題還是發生,請聯絡開發團隊'); // console.error('OpenedBystanderForm join else response from server: ', response); // console.error('OpenedBystanderForm join else message from server: ', response.data.message); // } // }) // .catch(error => { // window.alert('加入Ludo發生錯誤,請重試一次;若問題還是發生,請聯絡開發團隊'); // console.error('OpenedBystanderForm join put error', error); // }); } if (ludo_id) { axios.put(`/apis/ludo/${ludo_id}`, joinLudoPutbody) .then(response => { if (response.data.status === '200') { /* TODO: Figure out how to use same url redirect to other component */ browserHistory.push(`/ludo/${ludo_id}`); } else if (response.data.status === '400' && response.data.message === 'Your Fuel is out.') { window.alert('你的燃料用完囉!'); browserHistory.push(`/ludo/${ludo_id}`); } else { if (window.confirm('加入Ludo卡片時伺服器未回傳正確資訊,請點擊「確定」回報此問題給開發團隊')) { window.open("https://www.facebook.com/messages/t/ludonow"); } } }) .catch(error => { if (window.confirm('加入Ludo卡片時發生錯誤,請點擊「確定」回報此問題給開發團隊')) { window.open("https://www.facebook.com/messages/t/ludonow"); } }); } else { // browserHistory.push('/cardList'); } } render () { return ( <RefreshIndicatorExampleLoading /> ); } };
es/utils/react-if.js
cvdlab/react-planner
import React from 'react'; import PropTypes from 'prop-types'; /** * @return {null} */ export default function If(_ref) { var condition = _ref.condition, style = _ref.style, children = _ref.children; return condition ? Array.isArray(children) ? React.createElement( 'div', { style: style }, children ) : children : null; } If.propTypes = { condition: PropTypes.bool.isRequired, style: PropTypes.object };
app/javascript/mastodon/features/ui/components/column_subheading.js
tootcafe/mastodon
import React from 'react'; import PropTypes from 'prop-types'; const ColumnSubheading = ({ text }) => { return ( <div className='column-subheading'> {text} </div> ); }; ColumnSubheading.propTypes = { text: PropTypes.string.isRequired, }; export default ColumnSubheading;
src/Parser/DemonHunter/Havoc/Modules/Spells/Momentum.js
hasseboulen/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage, formatDuration } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; class Momentum extends Analyzer { static dependencies = { combatants: Combatants, }; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.MOMENTUM_TALENT.id); } statistic() { const momentumUptime = this.combatants.selected.getBuffUptime(SPELLS.MOMENTUM_TALENT.id); const momentumUptimePercentage = momentumUptime / this.owner.fightDuration; return ( <StatisticBox icon={<SpellIcon id={SPELLS.MOMENTUM_TALENT.id} />} value={`${formatPercentage(momentumUptimePercentage)}%`} label="Momentum Uptime" tooltip={`The Momentum buff total uptime was ${formatDuration(momentumUptime / 1000)}.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(3); } export default Momentum;
docs/app/Examples/collections/Message/Variations/MessageExampleNegative.js
shengnian/shengnian-ui-react
import React from 'react' import { Message } from 'shengnian-ui-react' const MessageExampleNegative = () => ( <Message negative> <Message.Header>We're sorry we can't apply that discount</Message.Header> <p>That offer has expired</p> </Message> ) export default MessageExampleNegative
examples/cra-kitchen-sink/src/stories/force-rerender.stories.js
storybooks/storybook
import React from 'react'; import { forceReRender } from '@storybook/react'; import { Button } from '@storybook/react/demo'; let count = 0; const increment = () => { count += 1; forceReRender(); }; export default { title: 'Force ReRender', }; export const DefaultView = () => ( <Button type="button" onClick={increment}> Click me to increment: {count} </Button> );
src/components/input/autocomplete-text/consult.js
KleeGroup/focus-components
import React from 'react'; function AutocompleteTextConsult({ label, name, type, value }) { return ( <div label={label} name={name} type={type}> {value} </div> ); } export default AutocompleteTextConsult;
src/js/components/postList.js
blaketarter/react-lobsters
import React from 'react'; import Post from './post'; export default class PostList extends React.Component { render() { const postNodes = this.props.posts.map(function(post) { post = post.toJS(); return ( <Post { ...post } key={post.shortId} /> ); }); return ( <ul className="post-list"> { postNodes } </ul> ); } };
app/components/Transcribe/UserForm.js
taggun/app-benchmark
/* eslint-disable react/no-array-index-key */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import styles from './Transcribe.css'; const internals = {}; internals.renderData = item => { if (!item || !item.confidenceLevel) { return ''; } if (moment(item.data, moment.ISO_8601, true).isValid()) { return `${moment .utc(item.data) .format('LL')} [${item.confidenceLevel.toFixed(2)}]`; } return `${item.data} [${item.confidenceLevel.toFixed(2)}]`; }; export default class UserForm extends Component { constructor(props) { super(props); this.state = { totalAmount: '', taxAmount: '', date: '', merchantName: '' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.setField = this.setField.bind(this); } componentWillReceiveProps(newProps) { if (this.props.md5 === newProps.md5) { this.setState({ totalAmount: '', taxAmount: '', date: '', merchantName: '' }); } } componentDidUpdate() { this.setField('totalAmount'); this.setField('taxAmount'); this.setField('date'); this.setField('merchantName'); Materialize.updateTextFields(); } setField(fieldName) { if ( !this.state[fieldName] && (this.props.userResult[fieldName] || this.props.ocrResult[fieldName].data) ) { const stateChanged = {}; const result = this.props.userResult[fieldName] || this.props.ocrResult[fieldName].data; if (moment(result, moment.ISO_8601, true).isValid()) { stateChanged[fieldName] = `${moment.utc(result).format('YYYY-MM-DD')}`; } else { stateChanged[fieldName] = result; } this.setState(stateChanged); } } handleChange(event) { const stateChanged = {}; stateChanged[event.target.id] = event.target.value; this.setState(stateChanged); } handleSubmit(event) { this.props.saveRequest(this.state, this.props.ocrResult); event.preventDefault(); } render() { return ( <div> <form onSubmit={this.handleSubmit}> <div> <div className="row valign-wrapper"> <div className="input-field browser-default col s6"> <input id="totalAmount" type="text" value={this.state.totalAmount} onChange={this.handleChange} /> <label htmlFor="totalAmount"> Total </label> </div> <div className="col s6"> {internals.renderData(this.props.ocrResult.totalAmount)} </div> </div> <div className="valign-wrapper"> <div className="input-field browser-default col s6"> <input id="taxAmount" type="text" value={this.state.taxAmount} onChange={this.handleChange} /> <label htmlFor="taxAmount"> Tax </label> </div> <div className="col s6"> {internals.renderData(this.props.ocrResult.taxAmount)} </div> </div> <div className="valign-wrapper"> <div className="input-field browser-default col s6"> <input id="date" type="date" value={this.state.date} onChange={this.handleChange} /> </div> <div className="col s6"> {internals.renderData(this.props.ocrResult.date)} </div> </div> <div className="valign-wrapper"> <div className="input-field browser-default col s6"> <input id="merchantName" type="text" value={this.state.merchantName} onChange={this.handleChange} /> <label htmlFor="merchantName"> Merchant name </label> </div> <div className="col s6"> {internals.renderData(this.props.ocrResult.merchantName)} </div> </div> <div className="row"> <div className="col s2"> <input type="submit" disabled={this.props.userResult.isLoading} value="Save" className="btn" /> </div> </div> { this.props.userForm.error ? <span className="red-text">{ this.props.userForm.error }</span> : '' } </div> <div className={styles.numbers}> <div className="col s12"> <h6>Amounts</h6> {this.props.ocrResult.amounts.map((amount, i) => ( <span key={`amounts-${i}`} className="col s2"> {amount.data} </span> ))} </div> <div className="col s12"> <h6>Line Amounts</h6> {this.props.ocrResult.lineAmounts.map((amount, i) => ( <span key={`lineAmounts-${i}`} className="col s2"> {amount.data} </span> ))} </div> <div className="col s12"> <h6>Numbers</h6> {this.props.ocrResult.numbers.map((number, i) => ( <span key={`numbers-${i}`} className="col s4"> {number.data} </span> ))} </div> </div> </form> </div> ); } } UserForm.propTypes = { id: PropTypes.string, md5: PropTypes.string, saveRequest: PropTypes.func, transcribe: PropTypes.shape({ apikey: PropTypes.string, md5: PropTypes.string, contentType: PropTypes.string, file: PropTypes.any }), ocrResult: PropTypes.shape({ totalAmount: PropTypes.object, taxAmount: PropTypes.object, date: PropTypes.object, merchantName: PropTypes.object, amounts: PropTypes.array, lineAmounts: PropTypes.array, numbers: PropTypes.array }), userResult: PropTypes.shape({ totalAmount: PropTypes.number, taxAmount: PropTypes.number, date: PropTypes.ISO_8601, merchantName: PropTypes.string, error: PropTypes.string, isLoading: PropTypes.bool }), userForm: PropTypes.shape({ error: PropTypes.string, isLoading: PropTypes.bool }) }; UserForm.defaultProps = { id: undefined, md5: undefined, saveRequest: undefined, transcribe: {}, ocrResult: { totalAmount: {}, taxAmount: {}, date: {}, merchantName: {}, amounts: [], lineAmounts: [], numbers: [] }, userResult: { totalAmount: undefined, taxAmount: undefined, date: undefined, merchantName: undefined }, userForm: { error: undefined, isLoading: undefined } };
src/scenes/home/scholarshipApplication/success/success.js
miaket/operationcode_frontend
import React from 'react'; import { Link } from 'react-router-dom'; import Section from 'shared/components/section/section'; import FormButton from 'shared/components/form/formButton/formButton'; import styles from './success.css'; const Success = () => ( <Section title="Success!" theme="white"> <span className={styles.successText}>We have recieved your application.</span> <Link to="/scholarships"> <FormButton text="Return to scholarships" /> </Link> </Section> ); export default Success;
src/shared/element-react/dist/npm/es6/src/slider/Slider.js
thundernet8/Elune-WWW
import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import { Component, PropTypes } from '../../libs'; import InputNumber from '../input-number'; import SliderButton from './Button'; var Slider = function (_Component) { _inherits(Slider, _Component); function Slider(props) { _classCallCheck(this, Slider); var _this = _possibleConstructorReturn(this, _Component.call(this, props)); _this.state = { firstValue: 0, secondValue: 0, oldValue: 0, precision: 0, inputValue: 0, dragging: false }; return _this; } Slider.prototype.getChildContext = function getChildContext() { return { component: this }; }; Slider.prototype.componentWillMount = function componentWillMount() { var _props = this.props, range = _props.range, value = _props.value, min = _props.min, max = _props.max, step = _props.step; var _state = this.state, firstValue = _state.firstValue, secondValue = _state.secondValue, oldValue = _state.oldValue, inputValue = _state.inputValue, precision = _state.precision; if (range) { if (Array.isArray(value)) { firstValue = Math.max(min, value[0]); secondValue = Math.min(max, value[1]); } else { firstValue = min; secondValue = max; } oldValue = [firstValue, secondValue]; } else { if (typeof value !== 'number' || isNaN(value)) { firstValue = min; } else { firstValue = Math.min(max, Math.max(min, value)); } oldValue = firstValue; } var precisions = [min, max, step].map(function (item) { var decimal = ('' + item).split('.')[1]; return decimal ? decimal.length : 0; }); precision = Math.max.apply(null, precisions); inputValue = inputValue || firstValue; this.setState({ firstValue: firstValue, secondValue: secondValue, oldValue: oldValue, inputValue: inputValue, precision: precision }); }; Slider.prototype.componentWillUpdate = function componentWillUpdate(props, state) { if (props.min != this.props.min || props.max != this.props.max) { this.setValues(); } if (props.value != this.props.value) { var _oldValue = this.state.oldValue; if (this.state.dragging || Array.isArray(this.props.value) && Array.isArray(props.value) && Array.isArray(_oldValue) && this.props.value.every(function (item, index) { return item === _oldValue[index]; })) { return; } this.setValues(); } }; Slider.prototype.valueChanged = function valueChanged() { var range = this.props.range; var _state2 = this.state, firstValue = _state2.firstValue, oldValue = _state2.oldValue; if (range && Array.isArray(oldValue)) { return ![this.minValue(), this.maxValue()].every(function (item, index) { return item === oldValue[index]; }); } else { return firstValue !== oldValue; } }; Slider.prototype.setValues = function setValues() { var _props2 = this.props, range = _props2.range, value = _props2.value, min = _props2.min, max = _props2.max; var _state3 = this.state, firstValue = _state3.firstValue, secondValue = _state3.secondValue, oldValue = _state3.oldValue, inputValue = _state3.inputValue; if (range && Array.isArray(value)) { if (value[1] < min) { inputValue = [min, min]; } else if (value[0] > max) { inputValue = [max, max]; } else if (value[0] < min) { inputValue = [min, value[1]]; } else if (value[1] > max) { inputValue = [value[0], max]; } else { firstValue = value[0]; secondValue = value[1]; if (this.valueChanged()) { this.onValueChanged([this.minValue(), this.maxValue()]); oldValue = value.slice(); } } } else if (!range && typeof value === 'number' && !isNaN(value)) { if (value < min) { inputValue = min; } else if (value > max) { inputValue = max; } else { inputValue = firstValue; if (this.valueChanged()) { this.onValueChanged(firstValue); oldValue = firstValue; } } } this.forceUpdate(); }; Slider.prototype.setPosition = function setPosition(percent) { var _props3 = this.props, range = _props3.range, min = _props3.min, max = _props3.max; var _state4 = this.state, firstValue = _state4.firstValue, secondValue = _state4.secondValue; var targetValue = min + percent * (max - min) / 100; if (!range) { this.refs.button1.setPosition(percent);return; } var button = void 0; if (Math.abs(this.minValue() - targetValue) < Math.abs(this.maxValue() - targetValue)) { button = firstValue < secondValue ? 'button1' : 'button2'; } else { button = firstValue > secondValue ? 'button1' : 'button2'; } this.refs[button].setPosition(percent); }; Slider.prototype.onSliderClick = function onSliderClick(event) { if (this.props.disabled || this.state.dragging) return; if (this.props.vertical) { var sliderOffsetBottom = this.refs.slider.getBoundingClientRect().bottom; this.setPosition((sliderOffsetBottom - event.clientY) / this.sliderSize() * 100); } else { var sliderOffsetLeft = this.refs.slider.getBoundingClientRect().left; this.setPosition((event.clientX - sliderOffsetLeft) / this.sliderSize() * 100); } this.setValues(); }; /* Watched Methods */ Slider.prototype.onValueChanged = function onValueChanged(val) { if (this.props.onChange) { this.props.onChange(val); } }; Slider.prototype.onInputValueChanged = function onInputValueChanged(e) { var _this2 = this; this.setState({ inputValue: e || 0, firstValue: e || 0 }, function () { _this2.setValues(); }); }; Slider.prototype.onFirstValueChange = function onFirstValueChange(e) { if (this.state.firstValue != e) { this.state.firstValue = e; this.forceUpdate(); this.setValues(); } }; Slider.prototype.onSecondValueChange = function onSecondValueChange(e) { if (this.state.secondValue != e) { this.state.secondValue = e; this.forceUpdate(); this.setValues(); } }; /* Computed Methods */ Slider.prototype.sliderSize = function sliderSize() { return parseInt(this.props.vertical ? this.refs.slider.offsetHeight : this.refs.slider.offsetWidth, 10); }; Slider.prototype.stops = function stops() { var _this3 = this; var _props4 = this.props, range = _props4.range, min = _props4.min, max = _props4.max, step = _props4.step; var firstValue = this.state.firstValue; var stopCount = (max - min) / step; var stepWidth = 100 * step / (max - min); var result = []; for (var i = 1; i < stopCount; i++) { result.push(i * stepWidth); } if (range) { return result.filter(function (step) { return step < 100 * (_this3.minValue() - min) / (max - min) || step > 100 * (_this3.maxValue() - min) / (max - min); }); } else { return result.filter(function (step) { return step > 100 * (firstValue - min) / (max - min); }); } }; Slider.prototype.minValue = function minValue() { return Math.min(this.state.firstValue, this.state.secondValue); }; Slider.prototype.maxValue = function maxValue() { return Math.max(this.state.firstValue, this.state.secondValue); }; Slider.prototype.runwayStyle = function runwayStyle() { return this.props.vertical ? { height: this.props.height } : {}; }; Slider.prototype.barStyle = function barStyle() { return this.props.vertical ? { height: this.barSize(), bottom: this.barStart() } : { width: this.barSize(), left: this.barStart() }; }; Slider.prototype.barSize = function barSize() { return this.props.range ? 100 * (this.maxValue() - this.minValue()) / (this.props.max - this.props.min) + '%' : 100 * (this.state.firstValue - this.props.min) / (this.props.max - this.props.min) + '%'; }; Slider.prototype.barStart = function barStart() { return this.props.range ? 100 * (this.minValue() - this.props.min) / (this.props.max - this.props.min) + '%' : '0%'; }; Slider.prototype.render = function render() { var _props5 = this.props, vertical = _props5.vertical, showInput = _props5.showInput, showStops = _props5.showStops, showInputControls = _props5.showInputControls, range = _props5.range, step = _props5.step, disabled = _props5.disabled, min = _props5.min, max = _props5.max; var _state5 = this.state, inputValue = _state5.inputValue, firstValue = _state5.firstValue, secondValue = _state5.secondValue; return React.createElement( 'div', { className: this.className('el-slider', { 'is-vertical': vertical, 'el-slider--with-input': showInput }) }, showInput && !range && React.createElement(InputNumber, { ref: 'input', className: 'el-slider__input', defaultValue: inputValue, value: firstValue, step: step, disabled: disabled, controls: showInputControls, min: min, max: max, size: 'small', onChange: this.onInputValueChanged.bind(this) }), React.createElement( 'div', { ref: 'slider', style: this.runwayStyle(), className: this.classNames('el-slider__runway', { 'show-input': showInput, 'disabled': disabled }), onClick: this.onSliderClick.bind(this) }, React.createElement('div', { className: 'el-slider__bar', style: this.barStyle() }), React.createElement(SliderButton, { ref: 'button1', vertical: vertical, value: firstValue, onChange: this.onFirstValueChange.bind(this) }), range && React.createElement(SliderButton, { ref: 'button2', vertical: vertical, value: secondValue, onChange: this.onSecondValueChange.bind(this) }), showStops && this.stops().map(function (item, index) { return React.createElement('div', { key: index, className: 'el-slider__stop', style: vertical ? { 'bottom': item + '%' } : { 'left': item + '%' } }); }) ) ); }; return Slider; }(Component); export default Slider; Slider.childContextTypes = { component: PropTypes.any }; Slider.propTypes = { min: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), max: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), step: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), value: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]), showInput: PropTypes.bool, showInputControls: PropTypes.bool, showTooltip: PropTypes.bool, showStops: PropTypes.bool, disabled: PropTypes.bool, range: PropTypes.bool, vertical: PropTypes.bool, height: PropTypes.string, formatTooltip: PropTypes.func, onChange: PropTypes.func }; Slider.defaultProps = { showTooltip: true, showInputControls: true, min: 0, max: 100, step: 1, value: 0 };
app/components/WhyStart.js
gidich/votrient-kiosk
import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './WhyStart.css'; export default class WhyStart extends Component { render() { return ( <div className={styles.container}> <Link to="/" className={styles.home}></Link> <Link to="/ThankYou" className={styles.powerAhead}><div /></Link> <Link to="/ProductInfo" className={styles.productInformation}></Link> <Link to="/" className={styles.logo}></Link> <Link to="/WhyStart/References" className={styles.references}></Link> <Link to="/WhyStart/Diagram" className={styles.diagram}></Link> </div> ); } }
frontend/src/components/common/grid/customGridColumn.js
unicef/un-partner-portal
import React from 'react'; import PropTypes from 'prop-types'; import Grid from 'material-ui/Grid'; import { withStyles } from 'material-ui/styles'; /** Custom grid column based on flexbox * - used instead of materia-ui one to avoid strange spacing * issues when multiple grid columns being nested in each other * currently supports only one spacing - 12px * */ const styleSheet = theme => ({ grid: { display: 'flex', flexDirection: 'column', margin: -(theme.spacing.unit * 1.5), }, gridItem: { padding: theme.spacing.unit * 1.5, }, }); function CustomGridColumn(props) { const { classes, children, spacing, ...other } = props; return ( <div className={classes.grid} > {React.Children.map(children, child => (child ? <div className={classes.gridItem} > {child} </div> : null))} </div> ); } CustomGridColumn.propTypes = { classes: PropTypes.object, children: PropTypes.node, }; export default withStyles(styleSheet, { name: 'CustomGridColumn' })(CustomGridColumn);
src/templates/categories-list-template.js
bapti/blog
// @flow strict import React from 'react'; import { Link } from 'gatsby'; import kebabCase from 'lodash/kebabCase'; import Sidebar from '../components/Sidebar'; import Layout from '../components/Layout'; import Page from '../components/Page'; import { useSiteMetadata, useCategoriesList } from '../hooks'; const CategoriesListTemplate = () => { const { title, subtitle } = useSiteMetadata(); const categories = useCategoriesList(); return ( <Layout title={`Categories - ${title}`} description={subtitle}> <Sidebar /> <Page title="Categories"> <ul> {categories.map((category) => ( <li key={category.fieldValue}> <Link to={`/category/${kebabCase(category.fieldValue)}/`}> {category.fieldValue} ({category.totalCount}) </Link> </li> ))} </ul> </Page> </Layout> ); }; export default CategoriesListTemplate;
geonode/monitoring/frontend/monitoring/src/components/atoms/hr/index.js
francbartoli/geonode
/* ######################################################################### # # Copyright (C) 2019 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### */ import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles'; class HR extends React.Component { static propTypes = { children: PropTypes.node, style: PropTypes.object, } render() { return ( <hr style={styles.hr} /> ); } } export default HR;
app/redux/router.js
andreipreda/coconut
import React from 'react'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import { Wrap, Header } from './../wrap'; const NotFound = () => <div>Route not found</div>; export const AppRouter = () => <Router history={browserHistory}> <Route path="/" component={Wrap}> <IndexRoute component={Header} /> <Route path="*" component={NotFound} /> </Route> </Router>;
src/index.js
madi031/ReactRouterBlog
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import { createStore, applyMiddleware } from 'redux'; import promise from 'redux-promise'; import PostsIndex from './components/posts_index'; import PostsNew from './components/posts_new'; import PostsShow from './components/posts_show'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(promise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <div> <Switch> <Route path='/posts/new' component={PostsNew} /> <Route path='/posts/:id' component={PostsShow} /> <Route path='/' component={PostsIndex} /> </Switch> </div> </BrowserRouter> </Provider> , document.querySelector('.container'));
src/ServiceList.js
CanopyTax/sofe-inspector
import React from 'react'; import formStyles from './Form.style.css'; import buttonStyles from './Button.style.css'; export default function ServiceList({services, updateService, deleteService, renameService}) { return (services && services.length) ? <div style={{height: '240px', overflow: 'auto', marginBottom: '16px'}}> <table className={formStyles.table}> <thead> <tr className='row'> <th style={{width: '20%'}} className='col-xs-2'>Service Name</th> <th style={{width: '80%'}} className='col-xs-10'>SRC</th> </tr> </thead> <tbody> {services.map((service, index) => { return <tr style={{verticalAlign: 'top'}} className='row' key={service.id}> <td style={{padding: 8}} className='col-xs-2'> <input defaultValue={service.name} className={formStyles.formControl} onChange={(e) => renameService(e, service.src, service.name, index)} /> </td> <td style={{padding: 8}} className='col-xs-9'> <div style={{width: 'calc(100% - 40px)', display: 'inline-block'}}> <input onChange={(e) => updateService(service.name, index, e)} defaultValue={service.src} className={formStyles.formControl} /> </div> <div style={{width: 40, verticalAlign: 'top', display: 'inline-block', position: 'relative', top: -3}}> <span onClick={(e) => deleteService(service.name, e)} className={buttonStyles.closeButton}>x</span> </div> </td> </tr> })} </tbody> </table> </div>: getBlankMessage(); } function getBlankMessage() { return <p style={{padding: 15, background: 'rgba(52, 152, 219, .5)', textAlign: 'center'}}>You do not have any overriden sofe services</p> }
src/containers/Home/FormActions.js
oPauloChaves/controle-frotas
import React from 'react' import Row from 'react-bootstrap/lib/Row' import Col from 'react-bootstrap/lib/Col' import Button from 'react-bootstrap/lib/Button' import Glyphicon from 'react-bootstrap/lib/Glyphicon' import FormGroup from 'react-bootstrap/lib/FormGroup' import InputGroup from 'react-bootstrap/lib/InputGroup' import FormControl from 'react-bootstrap/lib/FormControl' const FormActions = ({ search, handleSearch, handleSearchInputChange }) => ( <Row className="AppFormAction"> <Col xs={5} sm={3} md={2}> <Button href="#/carros/novo" bsStyle="success" block className="AppBtnNew" >Novo Carro</Button> </Col> <Col xs={7} smOffset={5} sm={4} mdOffset={7} md={3}> <FormGroup> <InputGroup> <FormControl type="text" placeholder="Pesquisar" value={search} onChange={handleSearchInputChange} onKeyUp={handleSearch} /> <InputGroup.Button> <Button onClick={handleSearch}><Glyphicon glyph="search" /></Button> </InputGroup.Button> </InputGroup> </FormGroup> </Col> </Row> ) export default FormActions
src/svg-icons/social/sentiment-neutral.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialSentimentNeutral = (props) => ( <SvgIcon {...props}> <path d="M9 14h6v1.5H9z"/><circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/> </SvgIcon> ); SocialSentimentNeutral = pure(SocialSentimentNeutral); SocialSentimentNeutral.displayName = 'SocialSentimentNeutral'; SocialSentimentNeutral.muiName = 'SvgIcon'; export default SocialSentimentNeutral;
src/index.js
surongaukeys/gallery-by-react
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/svg-icons/navigation/arrow-drop-down-circle.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowDropDownCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 12l-4-4h8l-4 4z"/> </SvgIcon> ); NavigationArrowDropDownCircle = pure(NavigationArrowDropDownCircle); NavigationArrowDropDownCircle.displayName = 'NavigationArrowDropDownCircle'; export default NavigationArrowDropDownCircle;
docs/pages/home.js
n7best/react-weui
import React from 'react'; import FontAwesome from 'react-fontawesome'; import './home.less'; //import { Button } from 'react-weui'; const Home = () => ( <div className="App__preview background--canvas flex-center"> <div className="App__preview--none"> <FontAwesome name="weixin" size="4x" /> <p>Hello, React-WeUI</p> </div> </div> ); export default Home;
src/index.js
ianwcarlson/react-components
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
react-router-nb/react-router/examples/pinterest/app.js
zhangfaliang/learnReact
import React from 'react' import { render } from 'react-dom' import { browserHistory, Router, Route, IndexRoute, Link } from 'react-router' import withExampleBasename from '../withExampleBasename' const PICTURES = [ { id: 0, src: 'http://placekitten.com/601/601' }, { id: 1, src: 'http://placekitten.com/610/610' }, { id: 2, src: 'http://placekitten.com/620/620' } ] const Modal = React.createClass({ styles: { position: 'fixed', top: '20%', right: '20%', bottom: '20%', left: '20%', padding: 20, boxShadow: '0px 0px 150px 130px rgba(0, 0, 0, 0.5)', overflow: 'auto', background: '#fff' }, render() { return ( <div style={this.styles}> <p><Link to={this.props.returnTo}>Back</Link></p> {this.props.children} </div> ) } }) const App = React.createClass({ componentWillReceiveProps(nextProps) { // if we changed routes... if (( nextProps.location.key !== this.props.location.key && nextProps.location.state && nextProps.location.state.modal )) { // save the old children (just like animation) this.previousChildren = this.props.children } }, render() { let { location } = this.props let isModal = ( location.state && location.state.modal && this.previousChildren ) return ( <div> <h1>Pinterest Style Routes</h1> <div> {isModal ? this.previousChildren : this.props.children } {isModal && ( <Modal isOpen={true} returnTo={location.state.returnTo}> {this.props.children} </Modal> )} </div> </div> ) } }) const Index = React.createClass({ render() { return ( <div> <p> The url `/pictures/:id` can be rendered anywhere in the app as a modal. Simply put `modal: true` in the location descriptor of the `to` prop. </p> <p> Click on an item and see its rendered as a modal, then copy/paste the url into a different browser window (with a different session, like Chrome -> Firefox), and see that the image does not render inside the overlay. One URL, two session dependent screens :D </p> <div> {PICTURES.map(picture => ( <Link key={picture.id} to={{ pathname: `/pictures/${picture.id}`, state: { modal: true, returnTo: this.props.location.pathname } }} > <img style={{ margin: 10 }} src={picture.src} height="100" /> </Link> ))} </div> <p><Link to="/some/123/deep/456/route">Go to some deep route</Link></p> </div> ) } }) const Deep = React.createClass({ render() { return ( <div> <p>You can link from anywhere really deep too</p> <p>Params stick around: {this.props.params.one} {this.props.params.two}</p> <p> <Link to={{ pathname: '/pictures/0', state: { modal: true, returnTo: this.props.location.pathname } }}> Link to picture with Modal </Link><br/> <Link to="/pictures/0"> Without modal </Link> </p> </div> ) } }) const Picture = React.createClass({ render() { return ( <div> <img src={PICTURES[this.props.params.id].src} style={{ height: '80%' }} /> </div> ) } }) render(( <Router history={withExampleBasename(browserHistory, __dirname)}> <Route path="/" component={App}> <IndexRoute component={Index}/> <Route path="/pictures/:id" component={Picture}/> <Route path="/some/:one/deep/:two/route" component={Deep}/> </Route> </Router> ), document.getElementById('example'))
00-todo-lab4/src/TodoList.js
iproduct/course-node-express-react
import React from 'react'; const TodoList = ({todos, ...rest}) => { return ( <ul className="list-group"> { todos.map(todo => (<li>{todo.text} - {todo.status}</li>)) } </ul> ); } export default TodoList;
server/sonar-web/src/main/js/apps/overview/main/timeline.js
vamsirajendra/sonarqube
import d3 from 'd3'; import React from 'react'; import { LineChart } from '../../../components/charts/line-chart'; const HEIGHT = 80; export class Timeline extends React.Component { filterSnapshots () { return this.props.history.filter(s => { let matchBefore = !this.props.before || s.date <= this.props.before; let matchAfter = !this.props.after || s.date >= this.props.after; return matchBefore && matchAfter; }); } render () { let snapshots = this.filterSnapshots(); if (snapshots.length < 2) { return null; } let data = snapshots.map((snapshot, index) => { return { x: index, y: snapshot.value }; }); let domain = [0, d3.max(this.props.history, d => d.value)]; return <LineChart data={data} domain={domain} interpolate="basis" displayBackdrop={true} displayPoints={false} displayVerticalGrid={false} height={HEIGHT} padding={[0, 0, 0, 0]}/>; } } Timeline.propTypes = { history: React.PropTypes.arrayOf(React.PropTypes.object).isRequired, before: React.PropTypes.object, after: React.PropTypes.object };
V2-Node/esquenta.v2/UI/src/views/Base/Tables/Tables.js
leandrocristovao/esquenta
import React, { Component } from 'react'; import { Badge, Card, CardBody, CardHeader, Col, Pagination, PaginationItem, PaginationLink, Row, Table } from 'reactstrap'; class Tables extends Component { render() { return ( <div className="animated fadeIn"> <Row> <Col xs="12" lg="6"> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Simple Table </CardHeader> <CardBody> <Table responsive> <thead> <tr> <th>Username</th> <th>Date registered</th> <th>Role</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Samppa Nori</td> <td>2012/01/01</td> <td>Member</td> <td> <Badge color="success">Active</Badge> </td> </tr> <tr> <td>Estavan Lykos</td> <td>2012/02/01</td> <td>Staff</td> <td> <Badge color="danger">Banned</Badge> </td> </tr> <tr> <td>Chetan Mohamed</td> <td>2012/02/01</td> <td>Admin</td> <td> <Badge color="secondary">Inactive</Badge> </td> </tr> <tr> <td>Derick Maximinus</td> <td>2012/03/01</td> <td>Member</td> <td> <Badge color="warning">Pending</Badge> </td> </tr> <tr> <td>Friderik Dávid</td> <td>2012/01/21</td> <td>Staff</td> <td> <Badge color="success">Active</Badge> </td> </tr> </tbody> </Table> <Pagination> <PaginationItem> <PaginationLink previous tag="button"></PaginationLink> </PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem> <PaginationLink tag="button">2</PaginationLink> </PaginationItem> <PaginationItem> <PaginationLink tag="button">3</PaginationLink> </PaginationItem> <PaginationItem> <PaginationLink tag="button">4</PaginationLink> </PaginationItem> <PaginationItem> <PaginationLink next tag="button"></PaginationLink> </PaginationItem> </Pagination> </CardBody> </Card> </Col> <Col xs="12" lg="6"> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Striped Table </CardHeader> <CardBody> <Table responsive striped> <thead> <tr> <th>Username</th> <th>Date registered</th> <th>Role</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Yiorgos Avraamu</td> <td>2012/01/01</td> <td>Member</td> <td> <Badge color="success">Active</Badge> </td> </tr> <tr> <td>Avram Tarasios</td> <td>2012/02/01</td> <td>Staff</td> <td> <Badge color="danger">Banned</Badge> </td> </tr> <tr> <td>Quintin Ed</td> <td>2012/02/01</td> <td>Admin</td> <td> <Badge color="secondary">Inactive</Badge> </td> </tr> <tr> <td>Enéas Kwadwo</td> <td>2012/03/01</td> <td>Member</td> <td> <Badge color="warning">Pending</Badge> </td> </tr> <tr> <td>Agapetus Tadeáš</td> <td>2012/01/21</td> <td>Staff</td> <td> <Badge color="success">Active</Badge> </td> </tr> </tbody> </Table> <Pagination> <PaginationItem disabled><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem><PaginationLink tag="button">2</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem> <PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem> </Pagination> </CardBody> </Card> </Col> </Row> <Row> <Col xs="12" lg="6"> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Condensed Table </CardHeader> <CardBody> <Table responsive size="sm"> <thead> <tr> <th>Username</th> <th>Date registered</th> <th>Role</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Carwyn Fachtna</td> <td>2012/01/01</td> <td>Member</td> <td> <Badge color="success">Active</Badge> </td> </tr> <tr> <td>Nehemiah Tatius</td> <td>2012/02/01</td> <td>Staff</td> <td> <Badge color="danger">Banned</Badge> </td> </tr> <tr> <td>Ebbe Gemariah</td> <td>2012/02/01</td> <td>Admin</td> <td> <Badge color="secondary">Inactive</Badge> </td> </tr> <tr> <td>Eustorgios Amulius</td> <td>2012/03/01</td> <td>Member</td> <td> <Badge color="warning">Pending</Badge> </td> </tr> <tr> <td>Leopold Gáspár</td> <td>2012/01/21</td> <td>Staff</td> <td> <Badge color="success">Active</Badge> </td> </tr> </tbody> </Table> <Pagination> <PaginationItem><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem><PaginationLink tag="button">2</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem> <PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem> </Pagination> </CardBody> </Card> </Col> <Col xs="12" lg="6"> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Bordered Table </CardHeader> <CardBody> <Table responsive bordered> <thead> <tr> <th>Username</th> <th>Date registered</th> <th>Role</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Pompeius René</td> <td>2012/01/01</td> <td>Member</td> <td> <Badge color="success">Active</Badge> </td> </tr> <tr> <td>Paĉjo Jadon</td> <td>2012/02/01</td> <td>Staff</td> <td> <Badge color="danger">Banned</Badge> </td> </tr> <tr> <td>Micheal Mercurius</td> <td>2012/02/01</td> <td>Admin</td> <td> <Badge color="secondary">Inactive</Badge> </td> </tr> <tr> <td>Ganesha Dubhghall</td> <td>2012/03/01</td> <td>Member</td> <td> <Badge color="warning">Pending</Badge> </td> </tr> <tr> <td>Hiroto Šimun</td> <td>2012/01/21</td> <td>Staff</td> <td> <Badge color="success">Active</Badge> </td> </tr> </tbody> </Table> <Pagination> <PaginationItem><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem className="page-item"><PaginationLink tag="button">2</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem> <PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem> </Pagination> </CardBody> </Card> </Col> </Row> <Row> <Col> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Combined All Table </CardHeader> <CardBody> <Table hover bordered striped responsive size="sm"> <thead> <tr> <th>Username</th> <th>Date registered</th> <th>Role</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Vishnu Serghei</td> <td>2012/01/01</td> <td>Member</td> <td> <Badge color="success">Active</Badge> </td> </tr> <tr> <td>Zbyněk Phoibos</td> <td>2012/02/01</td> <td>Staff</td> <td> <Badge color="danger">Banned</Badge> </td> </tr> <tr> <td>Einar Randall</td> <td>2012/02/01</td> <td>Admin</td> <td> <Badge color="secondary">Inactive</Badge> </td> </tr> <tr> <td>Félix Troels</td> <td>2012/03/01</td> <td>Member</td> <td> <Badge color="warning">Pending</Badge> </td> </tr> <tr> <td>Aulus Agmundr</td> <td>2012/01/21</td> <td>Staff</td> <td> <Badge color="success">Active</Badge> </td> </tr> </tbody> </Table> <nav> <Pagination> <PaginationItem><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem><PaginationLink tag="button">2</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem> <PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem> </Pagination> </nav> </CardBody> </Card> </Col> </Row> </div> ); } } export default Tables;
pages/404.js
ivygong/irc
import React, { Component } from 'react'; import Helmet from 'react-helmet'; import { config } from 'config'; import { Link } from 'react-router'; import { prefixLink } from 'gatsby-helpers'; export default class NotFound extends Component { render () { return ( <div className="page page--not-found"> <Helmet title={config.siteTitle} /> <h1> The page you were looking for cannot be found. </h1> </div> ); } }
src/components/logout_button.js
Helabs/handup-web
import React from 'react'; import { connect } from 'react-redux'; import { graphql, compose } from 'react-apollo'; import gql from 'graphql-tag'; import { SetCurrentUserId, SetCurrentUserToken } from '../actions'; function LogoutButton({ currentUserId, getUserQuery, SetCurrentUserId, SetCurrentUserToken }) { if (!currentUserId) { return null; } return ( <div> {renderUserAvatar()} <button className="btn btn-default faded" onClick={onClick}> <i className="fa fa-sign-out" /> </button> </div> ); function onClick() { SetCurrentUserId(null); SetCurrentUserToken(null); } function renderUserAvatar() { if (getUserQuery.loading) { return; } return <img className="circle m-r-s" src={getUserQuery.getUser.avatarImageUrl} style={{ width: '35px' }} />; } } const getUserQueryOptions = ({ currentUserId }) => ({ variables: { id: currentUserId } }); const getUserQuery = gql` query getUser($id: ID!) { getUser(id: $id) { id name avatarImageUrl } } `; const LogoutButtonWithData = compose( graphql(getUserQuery, { name: 'getUserQuery', options: getUserQueryOptions, skip: ({ currentUserId }) => !currentUserId }) )(LogoutButton); function mapStateToProps({ currentUser }) { return { currentUserId: currentUser.id }; } export default connect(mapStateToProps, { SetCurrentUserId, SetCurrentUserToken })(LogoutButtonWithData);
packages/mcs-lite-ui/src/TabItem/TabItem.example.js
MCS-Lite/mcs-lite
import React from 'react'; import PropTypes from 'prop-types'; import { storiesOf } from '@storybook/react'; import { withInfo } from '@storybook/addon-info'; import { action } from '@storybook/addon-actions'; import TabItem from '.'; class StatefulTabItems extends React.Component { static propTypes = { items: PropTypes.arrayOf(PropTypes.number).isRequired, }; state = { value: '' }; onChange = (e, value) => this.setState({ value }); render() { const { items } = this.props; const { onChange } = this; const { value } = this.state; return ( <div> {items.map(i => ( <TabItem key={i} value={i} onClick={onChange} active={i === value}> {`Tab ${i}`} </TabItem> ))} </div> ); } } storiesOf('TabItem', module) .add( 'API', withInfo({ text: '', inline: true, })(() => ( <div> <TabItem value="key" onClick={action('onClick')}> TabItem </TabItem> <TabItem value="key" active onClick={action('onClick')}> Active TabItem </TabItem> </div> )), ) .add( 'With color props', withInfo({ text: '', inline: true, })(() => ( <div> <TabItem value={1} color="warning"> TabItem 1 </TabItem> <TabItem value={2} color="warning" active> TabItem 2 </TabItem> </div> )), ) .add( 'With state', withInfo({ text: 'This is a react controlled component.', inline: true, propTables: [TabItem], })(() => <StatefulTabItems items={[1, 2, 3]} />), );
actor-apps/app-web/src/app/components/sidebar/RecentSection.react.js
TimurTarasenko/actor-platform
import _ from 'lodash'; import React from 'react'; import { Styles, RaisedButton } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import DialogActionCreators from 'actions/DialogActionCreators'; import DialogStore from 'stores/DialogStore'; import CreateGroupActionCreators from 'actions/CreateGroupActionCreators'; import RecentSectionItem from './RecentSectionItem.react'; import CreateGroupModal from 'components/modals/CreateGroup.react'; import CreateGroupStore from 'stores/CreateGroupStore'; const ThemeManager = new Styles.ThemeManager(); const LoadDialogsScrollBottom = 100; const getStateFromStore = () => { return { isCreateGroupModalOpen: CreateGroupStore.isModalOpen(), dialogs: DialogStore.getAll() }; }; class RecentSection extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } componentWillMount() { DialogStore.addChangeListener(this.onChange); DialogStore.addSelectListener(this.onChange); CreateGroupStore.addChangeListener(this.onChange); ThemeManager.setTheme(ActorTheme); } componentWillUnmount() { DialogStore.removeChangeListener(this.onChange); DialogStore.removeSelectListener(this.onChange); CreateGroupStore.removeChangeListener(this.onChange); } constructor() { super(); this.onChange = this.onChange.bind(this); this.onScroll = this.onScroll.bind(this); this.openCreateGroup = this.openCreateGroup.bind(this); this.state = getStateFromStore(); } onChange() { this.setState(getStateFromStore()); } openCreateGroup() { CreateGroupActionCreators.openModal(); } onScroll(event) { if (event.target.scrollHeight - event.target.scrollTop - event.target.clientHeight <= LoadDialogsScrollBottom) { DialogActionCreators.onDialogsEnd(); } } render() { let dialogs = _.map(this.state.dialogs, (dialog, index) => { return ( <RecentSectionItem dialog={dialog} key={index}/> ); }, this); let createGroupModal; if (this.state.isCreateGroupModalOpen) { createGroupModal = <CreateGroupModal/>; } return ( <section className="sidebar__recent"> <ul className="sidebar__list sidebar__list--recent" onScroll={this.onScroll}> {dialogs} </ul> <footer> <RaisedButton label="Create group" onClick={this.openCreateGroup} style={{width: '100%'}}/> {createGroupModal} </footer> </section> ); } } export default RecentSection;
codes/chapter03/webpack2/demo13/app/components/Welcome.js
atlantis1024/react-step-by-step
/** * Created by Zhang Peng on 2017/6/8. */ import React from 'react'; class Clock extends React.Component { constructor(props) { super(props); this.state = { date: new Date().toLocaleDateString() }; this.click = this.click.bind(this); } click() { // 动态引入import() import('moment') .then(moment => moment().format("MMMM Do YYYY, h:mm:ss a")) .then(str => this.setState({date:str})) .catch(err => console.log("Failed to load moment", err)); } render() { return ( <div> <h2>It is {this.state.date}.</h2> <p onClick={this.click}>Click here to changing the time.</p> </div> ); } } class Welcome extends React.PureComponent { render() { return ( <div> <h1>Hello, {this.props.name}</h1> <Clock /> </div> ); } } export default Welcome;
src/routes/ConnectedDevices/components/ConnectedDevicesSpeeds.js
liuyaoao/omnyiq-sc1-server-render
import React from 'react'; import {getSpeedsChartData} from './ConnectedDevicesChartData'; import TimeSelectionTab from '../../../components/TimeSelectionTab'; var ConnectedDevicesSpeeds = React.createClass({ getInitialState:function(){ return{ } }, componentDidMount:function(){ let _this = this; let deviceListUrl = APPCONFING.deviceListUrl; let deviceInfo = localStorage.getItem('deviceInfo'); deviceInfo = JSON.parse(deviceInfo); if(this.props.isAllDevices){ $.ajax({ type: "GET", url: deviceListUrl+'/GetBandwidthServlet', success: function(data){ data = JSON.parse(data); let allBandwidthList = data.AllBandwidthList || []; for(let obj of allBandwidthList){ obj.total_bandwidth = +(+obj.total_bandwidth || 0).toFixed(2); obj.used = +(obj.used || 0).toFixed(2); } _this._renderSpeedsChart(allBandwidthList); } }); } }, _onClickChartCall:function(e){ var data = zingchart.exec(e.id, 'getseriesvalues', {}); // console.log("ConnectedDevicesSpeeds_e:",e); // console.log("ConnectedDevicesSpeeds_ChartData:",data); var availableNum = data[0][e.nodeindex] ? (data[0][e.nodeindex]-data[1][e.nodeindex])/data[0][e.nodeindex] : 0; this._setSpeedsNum_SpeedsGrade(data[1][e.nodeindex], availableNum*100); }, _renderSpeedsChart:function(bandwidthList){ let _this = this; if(!bandwidthList || bandwidthList.length <= 0){ $('.connectedDevicesSpeedsContainer .noDataContainer').removeClass('hide'); $('.devicesSpeedsBottom').addClass('hide'); this._setSpeedsNum_SpeedsGrade(0, 0); return; } $('.connectedDevicesSpeedsContainer .noDataContainer').addClass('hide'); $('.devicesSpeedsBottom').removeClass('hide'); let lastObj = bandwidthList[bandwidthList.length-1]; this._setSpeedsNum_SpeedsGrade(lastObj.used||0, (+lastObj.available||0)*100); let timeLabelList=[], totalList=[] , usedList=[]; var i=0; for(let obj of bandwidthList){ if(i%3 == 0){ let hour = (new Date(obj.savetime)).getHours(); timeLabelList.push((hour<10?"0":"")+hour+':00'); }else{ timeLabelList.push(''); } totalList.push(obj.total_bandwidth||0); usedList.push(obj.used||0); i++; } var chartData = getSpeedsChartData(timeLabelList,totalList,usedList); zingchart.render({id : 'ConnectDevicesSpeedsChart',data : chartData,height: "300",width: "100%"}); zingchart.node_click = function(e){ if(e.id == 'ConnectDevicesSpeedsChart'){ _this._onClickChartCall(e); } } }, componentDidUpdate:function(){ if(!this.props.isAllDevices){ this._renderSpeedsChart(this.props.bandwidthList); } }, _setSpeedsNum_SpeedsGrade:function(speedsNum, speedsGrade){ $('.devicesSpeedsTop .speedsNum').text((+speedsNum).toFixed(2)); $('.devicesSpeedsTop .speedsGrade').text((+speedsGrade).toFixed(1)); }, componentWillUnmount:function(){ zingchart.exec('ConnectDevicesSpeedsChart', 'destroy');//不销毁的话会导致第二次加载这个路由页面的时候会报错。 }, render:function(){ return( <div className='connectedDevicesSpeedsContainer' style={{height:this.props.screenHeight-245}}> {!this.props.isAllDevices?<div onClick={this.props.onClickCloseSingleSpeeds} className='closeSingleSpeedsBtn glyphicon glyphicon-remove'></div>:''} <div className='devicesSpeedsTop'> {this.props.deviceName? <span>{this.props.deviceName} Devices</span>:<span>All Wi-Fi Devices</span>} <p className='speedsTitle'><span className='speedsNum'></span> Mbps</p> <p className='speedsState'><span className='speedsGrade'></span>% available</p> </div> <div className='noDataContainer hide' style={{height:this.props.screenHeight-325}}><p>No Speeds Data!!</p></div> <div className='devicesSpeedsBottom'> <div id={'ConnectDevicesSpeedsChart'} style={{height:'100%',width:'98%',margin:'0 auto'}}></div> </div> <TimeSelectionTab/> </div> ); } }); module.exports = ConnectedDevicesSpeeds;
js/cards/MarkDownCard/MarkDownCard.js
Learnone/ShanghaiTechAPP
import React, { Component } from 'react'; import { View } from 'react-native'; import { Container, Content, CardItem, Text } from 'native-base'; import Markdown from 'react-native-simple-markdown'; import { connect } from 'react-redux'; import { FlipCard } from '../../cards'; import styles from './styles'; const markDownStyle = { heading1: { fontSize: 22, flexWrap: 'wrap', wrapText: 'wrap', }, strong: { fontSize: 18, }, paragraph: { fontSize: 14, }, view: { borderWidth: 1, flex: 1, }, }; @connect(null, null) export default class MarkDownCard extends Component { static propTypes = { cardMeta: React.PropTypes.object.isRequired, }; render() { return ( <FlipCard cardMeta={this.props.cardMeta} > <View style={styles.container}> <Markdown styles={markDownStyle}> #Who is the best dev in town??????????????? {'\n\n'} Probably **the one** reading this lines 😏… </Markdown> </View> </FlipCard> ); } }
packages/ui/src/components/uploadAttendance.js
she-smashes/thehub
/** * @author Thenmozhi Subramaniam * @name EventDetails * @desc renders event details component */ import React, { Component } from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import {Link} from 'react-router-dom'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import SelectField from 'material-ui/SelectField'; import TextField from 'material-ui/TextField'; import { INVALID_USER, EVENT_FAILURE } from "../constants/actions"; class UploadAttendance extends Component { constructor(props) { super(props); this.state = { eventData: {}, attendanceData: {}, attendanceDataWithUserId: {}, errors: {}, errorData: {}, fieldsDisabled: false, attendanceMessage: "" } } componentDidMount = () => { this.getEventData(); }; getEventData = () => { this.props.getEventDetails(this.props.match.params.id, this.props.userInfo).then((response, error) => { this.props.updateEventDetails(this.props.userInfo, JSON.parse(response.data)); let eventData = JSON.parse(response.data); let attendanceSubmitted = false; eventData.participants.map((participant, participantIndex) => { let userNames = ""; if (eventData.enrollments !== undefined) { eventData.enrollments.map((enrollment, enrollmentIndex) => { if(enrollment.attendanceFlag === 'submit') { attendanceSubmitted = true; } let participantIdStr = participant.id + ''; if (enrollment.enrollmentType !== undefined && enrollment.enrollmentType === participantIdStr) { userNames = enrollment.users.username + ", " + userNames; } }); } userNames = userNames.substring(0, userNames.length - 2); let attendanceData = this.state.attendanceData; attendanceData[participant.id] = userNames; this.setState({ attendanceData }); if(attendanceSubmitted) { this.setState({ fieldsDisabled: true }); this.setState({ attendanceMessage: "Attendance submitted for the event" }); } }); }, (error) => { console.log(error); }); }; showAttendancePerRole = (participants) => { if (participants !== undefined) { return participants.map((participant, participantIndex) => { console.log(this.state.attendanceData[participant.id]); let usName = "userNames_" + participant.id; return (<TableRow key={participantIndex}> <TableRowColumn key={1} > {participant.participantType} </TableRowColumn> <TableRowColumn key={2}> <div className="field-line"> <TextField floatingLabelText="Participant Names" multiLine={true} rows={2} className="align-left participant-input" name={usName} multiline="true" value={this.state.attendanceData[participant.id]} onChange={this.changeAttendanceData} errorText={this.state.errorData[participant.id]} disabled = {this.state.fieldsDisabled}/> </div> </TableRowColumn> </TableRow>); }); } }; /** * Change the user object. * * @param {object} event - the JavaScript event object */ changeAttendanceData = (event) => { let field = event.target.name; let fieldArr = field.split("_"); field = fieldArr[1]; const attendanceData = this.state.attendanceData; attendanceData[field] = event.target.value; this.setState({ attendanceData }); }; /** * verify the users. */ verifyUsers = (attendanceFlag) => { const attendanceDataWithUserId = {}; const errors = {}; const errorData = {}; this.setState({ attendanceDataWithUserId, errors, errorData }); let userArr = []; if (this.state.attendanceData !== undefined && this.state.attendanceData !== '') { console.log(this.state.attendanceData); Object.keys(this.state.attendanceData).map((event, index) => { userArr = userArr.concat(this.state.attendanceData[event].split(',')); }); let errorMap = {}; if (userArr.length > 0) { this.props.verifyUsers(userArr, this.props.userInfo, 'save') .then((response, error) => { let users = JSON.parse(response.data); Object.keys(this.state.attendanceData).map((participantId, index) => { this.state.attendanceData[participantId].split(',').map((username, usernameIndex) => { let foundUserName = false; let userId = ""; users.map((userEvent, userIndex) => { if (userEvent.username === username) { foundUserName = true; userId = userEvent.id; } }); if (foundUserName) { const attendanceDataWithUserId = this.state.attendanceDataWithUserId; let userIds = attendanceDataWithUserId[participantId]; if (userIds === undefined) { userIds = []; } userIds.push(userId); attendanceDataWithUserId[participantId] = userIds; this.setState({ attendanceDataWithUserId }); } else { const errors = this.state.errors; let errorUserNames = errors[participantId]; if (errorUserNames === undefined) { errorUserNames = []; } errorUserNames.push(username); errors[participantId] = errorUserNames; this.setState({ errors }); } }); }); if (this.handleValidation()) { this.props.saveAttendanceData(this.props.match.params.id, this.props.userInfo, this.state.attendanceDataWithUserId, attendanceFlag).then((response, error) => { if(attendanceFlag === 'submit') { this.setState({ fieldsDisabled: true }); this.setState({ attendanceMessage: "Attendance submitted for the event" }); if (this.props.userInfo.allowedActionList.indexOf('task_count')) { let notificationCount = 0; if (this.props.userInfo.notificationCount !== undefined && this.props.userInfo.notificationCount !== null && this.props.userInfo.notificationCount !== '') { notificationCount = this.props.userInfo.notificationCount; } this.props.userInfo.notificationCount = parseInt(notificationCount) + 1; let userString = JSON.stringify(this.props.userInfo) this.props.updateUserInfo(JSON.parse(userString)); } } }, (error) => { console.log(error); }); } }, (error) => { alert('Error' + error); }); } } }; handleValidation = () => { let fields = this.state.errors; let errorData = {}; let formIsValid = true; Object.keys(this.state.errors).map((participantId, index) => { let userNameString = ""; this.state.errors[participantId].map((userName, index) => { userNameString = userName + ", " + userNameString; }); if (userNameString !== '') { userNameString = userNameString.substring(0, userNameString.length - 2) + " "; formIsValid = false; errorData[participantId] = "UserName " + userNameString + "invalid."; } }); this.setState({ errorData: errorData }); return formIsValid; } saveAttendanceData = () => { this.verifyUsers('save'); } submitAttendanceData = () => { this.verifyUsers('submit'); } showAttendanceButtons = (participants) => { if (participants !== undefined) { return (<TableRow> <TableRowColumn key={1} > <div className="button-line margin35"> <RaisedButton type="submit" label="Save" primary onClick={() => { this.saveAttendanceData() }} disabled = {this.state.fieldsDisabled}/> </div> </TableRowColumn> <TableRowColumn key={2}> <div className="button-line margin35"> <RaisedButton type="submit" label="Save & Submit" primary onClick={() => { this.submitAttendanceData() }} disabled = {this.state.fieldsDisabled}/> </div> </TableRowColumn> </TableRow>); } }; renderAttendanceForm = (eventData) => { return ( <div> <br></br> { (this.state.attendanceMessage !== '' && this.state.attendanceMessage !== undefined && this.state.attendanceMessage !== null) ? <div class="alert alert-success" role="alert" style={{"width": "100%"}}> <p style={{"margin-left": "201px"}}>{this.state.attendanceMessage}</p> </div>: <div></div> } <Table style={{ "width": '100%' }}> <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow className="table-header"> <TableHeaderColumn tooltip="Role" >Role</TableHeaderColumn> <TableHeaderColumn tooltip="User Name" >User Name</TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false}> {this.showAttendancePerRole(eventData.participants)} {this.showAttendanceButtons(eventData.participants)} </TableBody> </Table> </div> ); }; /** * @name render * @desc render the event details in the page * @return event details */ render() { return ( <div className="widget well hub-widget"> <div className="widget-header">Upload Attendance</div> <div class="event-details"> { (this.props.eventData !== '' && this.props.eventData !== undefined && this.props.eventData !== null) ? <Link to={`/eventDetails/${this.props.eventData.id}`} style={{"color":"#337ab7"}}>Back ></Link> : <div></div> } { (this.props.eventData !== '' && this.props.eventData !== undefined && this.props.eventData !== null) ? this.renderAttendanceForm(this.props.eventData) : <div></div> } </div> </div> ); } } export default UploadAttendance;
react/src/browser/app/components/View.js
janprasil/mi-vmm-product-quality-rating
/* @flow */ import React from 'react'; import { Base } from 'rebass'; const View = (props: Object) => ( <Base {...props} is="div" /> ); export default View;
client/src/components/FocusedCrawling.js
ViDA-NYU/domain_discovery_tool_react
import React, { Component } from 'react'; import { Col, Row} from 'react-bootstrap'; // From https://github.com/oliviertassinari/react-swipeable-views import Terms from './Terms'; import ScaleBar from './ScaleBar'; import { InputGroup, FormControl , DropdownButton} from 'react-bootstrap'; import RaisedButton from 'material-ui/RaisedButton'; import IconMenu from 'material-ui/IconMenu'; import IconButton from 'material-ui/IconButton'; import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card'; import Checkbox from 'material-ui/Checkbox'; import Divider from 'material-ui/Divider'; import MenuItem from 'material-ui/MenuItem'; import Avatar from 'material-ui/Avatar'; import {List, ListItem} from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; import CommunicationChatBubble from 'material-ui/svg-icons/communication/chat-bubble'; import Save from 'material-ui/svg-icons/content/save'; import Cancel from 'material-ui/svg-icons/action/highlight-off'; import Export from 'material-ui/svg-icons/file/file-download'; import Monitoring from './Monitoring.js'; import Dialog from 'material-ui/Dialog'; import {scaleLinear} from 'd3-scale'; import {range} from 'd3-array'; import CircularProgress from 'material-ui/CircularProgress'; import FlatButton from 'material-ui/FlatButton'; import { Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import $ from 'jquery'; const styles = { card: { borderStyle: 'solid', borderColor: '#C09ED7', background: 'white', borderRadius: '0px 0px 0px 0px', borderWidth: '0px 0px 0px 0px' }, avatar:{ margin:'-4px 8px 0px 0px', }, cardHeader:{ background: "white", //'#DCCCE7', padding:'10px 1px 10px 6px', borderRadius: '0px 0px 0px 0px', }, cardMedia:{ background: "white", padding:'2px 4px 2px 4px', borderRadius: '0px 0px 0px 0px', height: "382px", }, }; class CircularProgressSimple extends React.Component{ render(){ return( <div style={{borderColor:"green", marginLeft:"50%"}}> <CircularProgress size={30} thickness={7} /> </div> );} } class FocusedCrawling extends Component { constructor(props) { super(props); this.state = { slideIndex: 0, pages:{}, currentTags:undefined, selectedPosTags: ["Relevant"], selectedNegTags: ["Irrelevant"], session:{}, loadTerms:false, disableStopCrawlerSignal:true, disableAcheInterfaceSignal:true, disabledCreateModel:false, //false disabledStartCrawler:false, //false messageCrawler:"", open:false, openDialog:false, anchorEl:undefined, termsList: [], accuracyOnlineLearning:0, loadingModel:false, createModelMessage:"", openMessageModelResult:false, openDialogStatusCrawler:false, messageErrorCrawler:'', }; this.handleCloseDialogStatusCrawler = this.handleCloseDialogStatusCrawler.bind(this); } /** * Set * @method componentWillMount * @param */ componentWillMount(){ var update_disabledStartCrawler = (this.props.updateCrawlerData)?true:false; this.setState({session:this.props.session, disabledStartCrawler:update_disabledStartCrawler,}); this.forceUpdate(); var temp_session = this.props.session; this.getAvailableTags(this.props.session); this.getModelTags(this.props.domainId); } componentWillReceiveProps = (newProps, nextState) => { } setSelectedPosTags(selectedPosTags){ } loadingTerms(session, selectedPosTags){ var temp_session = session; temp_session['newPageRetrievalCriteria'] = "one"; temp_session['pageRetrievalCriteria'] = "Tags"; temp_session['selected_tags']=this.state.selectedPosTags.join(','); this.setState({session: temp_session, selectedPosTags: selectedPosTags, loadTerms:true}); this.forceUpdate(); } updateTerms(terms){ this.setState({termsList: terms}); } getAvailableTags(session){ $.post( '/getAvailableTags', {'session': JSON.stringify(session), 'event': 'Tags'}, function(tagsDomain) { this.setState({currentTags: tagsDomain['tags']}); //, session:this.props.session, tagString: JSON.stringify(this.props.session['selected_tags'])}); this.forceUpdate(); }.bind(this) ); } getModelTags(domainId){ $.post( '/getModelTags', {'domainId': domainId}, function(tags){ var session = this.props.session; session['model']['positive'] = []; session['model']['negative'] = []; if(Object.keys(tags).length > 0){ session['model']['positive'] = tags['positive'].slice(); session['model']['negative'] = tags['negative'].slice(); //setting session info for generating terms. session['newPageRetrievalCriteria'] = "one"; session['pageRetrievalCriteria'] = "Tags"; session['selected_tags']=(tags['positive'].slice()).join(','); this.updateClassifierCrawler(session); this.setState({session: session, selectedPosTags: tags['positive'].slice(), selectedNegTags: tags['negative'].slice(), loadTerms:true}); this.forceUpdate(); } else {if(!(session['model']['positive'].length>0)){ this.setState({loadTerms:false,}); this.forceUpdate(); }} }.bind(this) ); } saveInitialModel() { var session = this.props.session; session['model']['positive'] = this.state.selectedPosTags.slice(); session['model']['negative'] = this.state.selectedNegTags.slice(); //this.setState({session: session, selectedPosTags: this.state.selectedPosTags.slice(),}); if(session['model']['positive'].length>0 ){ this.loadingTerms(session, this.state.selectedPosTags); this.updateClassifierCrawler(session); $.post( '/saveModelTags', {'session': JSON.stringify(session)}, function(update){ //this.forceUpdate(); }.bind(this) ); } } handleSaveTags() { var session = this.props.session; session['model']['positive'] = this.state.selectedPosTags.slice(); session['model']['negative'] = this.state.selectedNegTags.slice(); //this.setState({session: session, selectedPosTags: this.state.selectedPosTags.slice(),}); if(session['model']['positive'].length>0 ){ this.loadingTerms(session, this.state.selectedPosTags); } else{ this.setState({openDialog:true, loadTerms:false}); } this.updateClassifierCrawler(session); $.post( '/saveModelTags', {'session': JSON.stringify(session)}, function(update){ //this.forceUpdate(); }.bind(this) ); } handleCancelTags(){ this.setState({selectedPosTags: this.state.session['model']['positive'].slice(), selectedNegTags: this.state.session['model']['negative'].slice()}) this.forceUpdate(); } addPosTags(tag){ var tags = this.state.selectedPosTags; if(tags.includes(tag)){ var index = tags.indexOf(tag); tags.splice(index, 1); } else{ tags.push(tag); } this.setState({selectedPosTags: tags}) this.forceUpdate(); } addNegTags(tag){ var tags = this.state.selectedNegTags; if(tags.includes(tag)){ var index = tags.indexOf(tag); tags.splice(index, 1); } else{ tags.push(tag); } this.setState({selectedNegTags: tags}) this.forceUpdate(); } startFocusedCrawler =()=>{ this.saveInitialModel(); this.startCrawler("focused"); this.forceUpdate(); } startCrawler(type){ var session = JSON.parse(JSON.stringify(this.state.session)); var message = "Running"; this.setState({disableAcheInterfaceSignal:false, disableStopCrawlerSignal:false, disabledStartCrawler:true, messageCrawler:message}); this.forceUpdate(); var terms = []; var pos_terms = []; terms = pos_terms = this.state.termsList.map((term)=>{ if(term['tags'].indexOf('Positive') !== -1) return term['word']; }).filter((term)=>{return term !== undefined}); if(pos_terms.length === 0){ terms = this.state.termsList.map((term)=>{ return term['word'] }); } $.post( '/startCrawler', {'session': JSON.stringify(session),'type': type, 'terms': this.state.termsList.join('|')}, function(message) { var disableStopCrawlerFlag = false; var disableAcheInterfaceFlag = false; var disabledStartCrawlerFlag = true; var crawlerIsNotRunningFlag = false; var messageErrorCrawlerTemp = ''; if(message.toLowerCase() === "no regex domain model available" || message.toLowerCase()=== "no page classifier or regex domain model available" || message.toLowerCase()==="no domain model available" || message.toLowerCase()=== "failed to connect to server. server may not be running" || message.toLowerCase()=== "failed to run crawler"){ disableStopCrawlerFlag = true; disableAcheInterfaceFlag =true; disabledStartCrawlerFlag = false; crawlerIsNotRunningFlag = true; messageErrorCrawlerTemp = message; } this.setState({ disableAcheInterfaceSignal: disableAcheInterfaceFlag, disableStopCrawlerSignal:disableStopCrawlerFlag, disabledStartCrawler:disabledStartCrawlerFlag, messageCrawler:message, openDialogStatusCrawler:crawlerIsNotRunningFlag, messageErrorCrawler:messageErrorCrawlerTemp}); this.forceUpdate(); }.bind(this) ); } stopFocusedCrawler(event) { this.stopCrawler("focused"); } stopCrawler(type){ var session = this.props.session; var message = "Terminating"; this.setState({disableAcheInterfaceSignal:true, disableStopCrawlerSignal:true, disabledStartCrawler:true, messageCrawler:message,}); this.forceUpdate(); $.post( '/stopCrawler', {'session': JSON.stringify(session), 'type' : type }, function(message) { this.setState({disableAcheInterfaceSignal:true, disableStopCrawlerSignal:true, disabledStartCrawler: false, messageCrawler:"",}); this.forceUpdate(); }.bind(this) ).fail((error) => { this.setState({disabledStartCrawler: false}); }); } handleRequestClosePopOver(){ this.setState({open:false}); } handleExport(event){ this.setState({open:true,anchorEl:event.currentTarget}) } handleOpenMenu = () => { this.setState({ openMenu: true, }); } handlecloseDialog(){ this.setState({openDialog:false}); this.forceUpdate(); } //Handling open/close 'status crawler' Dialog handleCloseDialogStatusCrawler = () => { this.setState({openDialogStatusCrawler: false, }); }; handleOnRequestChange = (value) => { this.setState({ openMenu: value, }); } //////////////////// ///Create a model//// //////////////////// getCreatedModel(session){ this.setState({loadingModel:true, disabledCreateModel:true, createModelMessage:"",}) $.post( '/createModel', {'session': JSON.stringify(session)}, function(model_file) { var url = model_file; var message = (url.indexOf("_model.zip")==-1)?"Model was not created.":"Model created successfully."; this.setState({modelDownloadURL: model_file, loadingModel:false, disabledCreateModel:false, createModelMessage:message, openMessageModelResult:true}) this.forceUpdate(); }.bind(this) ); } exportModel(){ this.getCreatedModel(this.state.session); } downloadExportedModel = (event) => { if((this.state.modelDownloadURL || "").indexOf("_model.zip") !== -1) window.open(this.state.modelDownloadURL, 'download') } handleCloseModelResult = () => { this.setState({openMessageModelResult: false}); }; //////////////////// ////////////////////// ///////////////////// updateClassifierCrawler(sessionTemp){ $.post( '/updateClassifierCrawler', {'session': JSON.stringify(sessionTemp)}, function(accuracy) { this.setState({accuracyOnlineLearning:accuracy,}); this.forceUpdate(); }.bind(this) ); } /////////////////////// ////////////////////// render() { var total_selectedPosTags=0; var total_selectedNegTags=0; var ratioPosNeg =0; var ratioAccuracy=0; var checkedTagsPosNeg = (this.state.currentTags!==undefined) ? <Row style={{height:330, overflowY: "scroll", }}> <Col xs={6} md={6} style={{marginTop:'2px'}}> Positive {Object.keys(this.state.currentTags).map((tag, index)=>{ var labelTags= tag+" (" +this.state.currentTags[tag]+")"; var checkedTag=false; var tags = this.state.selectedPosTags; if(tags.includes(tag)){ checkedTag=true; total_selectedPosTags=total_selectedPosTags +this.state.currentTags[tag]; } return <Checkbox label={labelTags} checked={checkedTag} onClick={this.addPosTags.bind(this,tag)} /> })} </Col> <Col xs={6} md={6} style={{marginTop:'2px'}}> Negative {Object.keys(this.state.currentTags).map((tag, index)=>{ var labelTags= tag+" (" +this.state.currentTags[tag]+")"; var checkedTag=false; var tags = this.state.selectedNegTags; if(tags.includes(tag)){ checkedTag=true; total_selectedNegTags=total_selectedNegTags+this.state.currentTags[tag]; } return <Checkbox label={labelTags} checked={checkedTag} onClick={this.addNegTags.bind(this,tag)} /> })} </Col> </Row>:<div />; ratioPosNeg = (total_selectedPosTags>total_selectedNegTags)?total_selectedNegTags/total_selectedPosTags:total_selectedPosTags/total_selectedNegTags; ratioAccuracy = ratioPosNeg*this.state.accuracyOnlineLearning; var barScale = scaleLinear().range([0, 240]); barScale.domain([0, 100]); var aux_ratioAccuracy = barScale(ratioAccuracy); var DialogBox= <RaisedButton disabled={false} onTouchTap={this.handlecloseDialog.bind(this)} style={{ height:20, marginTop: 15, marginRight:10, minWidth:118, width:118}} labelStyle={{textTransform: "capitalize"}} buttonStyle={{height:19}} label="Close" labelPosition="before" containerElement="label" />; var renderTerms = (this.state.loadTerms)?<Terms statedCard={true} sizeAvatar={20} showExpandableButton={false} actAsExpander={false} BackgroundColorTerm={"white"} renderAvatar={false} session={this.state.session} focusedCrawlDomains={this.state.loadTerms} fromCrawling={true} updateTerms={this.updateTerms.bind(this)}/> :<div></div>; var openMessage = (this.props.slideIndex && this.state.openDialog)?true:false; var loadingModel_signal = (this.state.disabledCreateModel)?<CircularProgressSimple style={{marginTop:"5px", marginLeft:"-30px"}} size={20} thickness={4} />:<div />; const actionsModelResult = [ <FlatButton label="Close" primary={true} onTouchTap={this.handleCloseModelResult.bind(this)} />, ]; const actionsStatusCrawler = [ <FlatButton label="Close" primary={true} onTouchTap={this.handleCloseDialogStatusCrawler.bind(this)}/>, ]; return ( <div> <Row> <Col xs={11} md={11} style={{margin:'10px'}}> <Card id={"Settings"} initiallyExpanded={true} style={{paddingBottom:0,}} containerStyle={{paddingBottom:0,}} > <CardHeader title="Model Settings" actAsExpander={false} showExpandableButton={false} style={{fontWeight:'bold', padding:'10px 1px 10px 6px', borderRadius: '0px 0px 0px 0px',}} /> <CardText expandable={true} style={{padding:'1px 16px 0px 16px',}}> <Row> <Col xs={7} md={7} style={{margin:0, padding:0,}}> <Card id={"Tags"} initiallyExpanded={true} style={styles.card}> <CardHeader title="Select postive and negative examples." actAsExpander={false} showExpandableButton={false} style={styles.cardHeader} /> <CardText expandable={true} style={styles.cardMedia}> <Divider/> <Row style={{margin:"5px 5px 10px 20px"}} title="Model Settings"> {checkedTagsPosNeg} </Row> <Row style={{margin:"-8px 5px 10px 20px"}}> <RaisedButton disabled={false} label="Save" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} icon={<Save />} //buttonStyle={{height:19}} style={{height:35, marginTop: 8, marginBottom:"-8px", marginRight:10}} disabled={false} onTouchTap={this.handleSaveTags.bind(this)} /> <RaisedButton disabled={false} label="Cancel" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} icon={<Cancel />} //buttonStyle={{height:19}} style={{height:35, marginTop: 8, marginBottom:"-8px"}} disabled={false} onTouchTap={this.handleCancelTags.bind(this)} /> </Row> <Dialog title="Select positive tags to extract terms." open={openMessage}> {DialogBox}</Dialog> </CardText> </Card> </Col> <Col xs={5} md={5} style={{margin:0, padding:0,}}> {renderTerms} </Col> </Row> </CardText> </Card> </Col> </Row> <Row> <Col xs={5} md={5} style={{margin:'10px'}}> <Card id={"Crawling"} initiallyExpanded={true} > <CardHeader title="CRAWLING" actAsExpander={false} showExpandableButton={false} style={{fontWeight:'bold',}} /> <CardText expandable={true} style={{height:212}}> <Row> <Col xs={5} md={5} style={{marginLeft:'0px'}}> <RaisedButton label="Start Crawler" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} //icon={<Search />} disable={this.state.disabledStartCrawler} style={ this.state.disabledStartCrawler ? {pointerEvents: 'none', opacity: 0.5, height:35, marginTop: 0, margin: 12} : {pointerEvents: 'auto', opacity: 1.0, height:35, marginTop: 0, margin: 12} } onClick={this.startFocusedCrawler} /> </Col> { this.state.disabledStartCrawler ? <Col xs={7} md={7} style={{marginLeft:'-70px'}}> <RaisedButton label="Crawler Monitor" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} style={{height:35, marginTop: 0, margin: 12}} href={this.props.crawlerServers['focused']+"/monitoring"} target="_blank" /> <RaisedButton label="Stop Crawler" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} style={{height:35, marginTop: 0, margin: 12}} onClick={this.stopFocusedCrawler.bind(this)} /> </Col> : null } </Row> </CardText> </Card> </Col> <Col xs={6} md={6} style={{margin:'10px', marginLeft:"-10px",}}> <Card id={"Model"} initiallyExpanded={true} > <CardHeader title="Model" actAsExpander={false} showExpandableButton={false} style={{fontWeight:'bold'}} /> <CardText expandable={true} style={{marginTop:"-12px", paddingTop:0, marginBottom:18,}}> <p><span style={{marginRight:10,}}>Total Positive: </span>{total_selectedPosTags} </p> <p><span style={{marginRight:10,}}>Total Negative: </span>{total_selectedNegTags} </p> <p><span>Domain Model (Accuracy): </span> {this.state.accuracyOnlineLearning} %</p> <Divider /> <div style={{marginLeft:10, marginTop:0, marginBottom:"-25px"}}> <ScaleBar ratioAccuracy={aux_ratioAccuracy}/> </div> <div style={{marginTop:"-20px", }}> <RaisedButton disabled={this.state.disabledCreateModel} label="Export" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} icon={<Export />} style={{height:35, marginTop: 0, margin: 12}} onClick={this.exportModel.bind(this)} /> <div style={{marginTop:"-40px", marginLeft:"-180px"}}> {loadingModel_signal} </div> <Dialog actions={actionsModelResult} modal={false} open={this.state.openMessageModelResult} onRequestClose={this.handleCloseModelResult.bind(this)} > {this.state.createModelMessage} <RaisedButton label="Download" style={{margin: 5}} labelStyle={{textTransform: "capitalize"}} onClick={this.downloadExportedModel} /> </Dialog> <Dialog title="Status Focused Crawler" actions={actionsStatusCrawler} modal={true} open={this.state.openDialogStatusCrawler} onRequestClose={this.handleCloseDialogStatusCrawler.bind(this)}> {this.state.messageErrorCrawler} </Dialog> </div> </CardText> </Card> </Col> </Row> </div> ); } } FocusedCrawling.defaultProps = { backgroundColor:"#9A7BB0", }; export default FocusedCrawling;
components/Deadline/components/List/List.js
yabeow/sinhvienuit
import React from 'react'; import PropTypes from 'prop-types'; import { FlatList, RefreshControl } from 'react-native'; import { View } from 'native-base'; import Deadline from './Item'; import EmptyList from '../../../EmptyList'; import { ANDROID_PULL_TO_REFRESH_COLOR } from '../../../../config/config'; const sortDeadlines = deadlines => // Sắp xếp theo thứ tự thời gian còn lại tăng dần. deadlines.sort((a, b) => { let timeA = a.getTime(); let timeB = b.getTime(); if (a.getStatus() !== 0) { timeA += 999999999999999; } if (b.getStatus() !== 0) { timeB += 999999999999999; } if (timeA < timeB) return -1; if (timeA > timeB) return 1; return 0; }); class List extends React.Component { constructor(props) { super(props); const { deadlines } = this.props; this.state = { deadlines: sortDeadlines(deadlines), }; } componentWillReceiveProps(nextProps) { const { deadlines } = nextProps; if (deadlines !== this.props.deadlines) { this.setState({ deadlines: sortDeadlines(deadlines) }); } } render() { if ( typeof this.props.onRefresh !== 'undefined' && typeof this.props.refreshing !== 'undefined' ) { return ( <FlatList ListEmptyComponent={<EmptyList />} data={this.state.deadlines} horizontal={false} keyExtractor={course => course.getId()} renderItem={({ item }) => <Deadline deadline={item} />} refreshControl={ <RefreshControl refreshing={this.props.refreshing} onRefresh={() => this.props.onRefresh()} colors={ANDROID_PULL_TO_REFRESH_COLOR} /> } /> ); } return ( <View> {this.state.deadlines.map(item => <Deadline deadline={item} key={item.getId()} />)} </View> ); } } List.defaultProps = { refreshing: false, onRefresh: () => {}, }; List.propTypes = { deadlines: PropTypes.array.isRequired, refreshing: PropTypes.bool, onRefresh: PropTypes.func, }; export default List;
js/BaseComponents/ThemedMaterialIcon.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. */ // @flow 'use strict'; import React from 'react'; import Icon from 'react-native-vector-icons/MaterialIcons'; import { withTheme, } from '../App/Components/HOC/withTheme'; import { prepareRootPropsIcon, } from './prepareRootProps'; const ThemedMaterialIcon = (props: Object): Object => { return ( <Icon {...prepareRootPropsIcon(props)} allowFontScaling={false}/> ); }; export default (withTheme(ThemedMaterialIcon): Object);
src/components/Main.js
Amous-th/gallery-by-react
require('normalize.css/normalize.css'); require('styles/App.scss'); import React from 'react'; import {findDOMNode} from 'react-dom'; //获取图片相关的数据 var imageDatas = require('../data/imageDatas.json'); //利用自执行函数,将图片信息转成图片URL路径信息 imageDatas = (function getImageURL(imageDataArr) { for(var i = 0,j=imageDataArr.length;i<j;i++){ var singleImageData = imageDataArr[i]; singleImageData.imageURL = require('../images/'+singleImageData.fileName) imageDataArr[i] = singleImageData; } return imageDataArr; })(imageDatas); /* * 获取区间内的一个随机值 */ function getRangeRandom(low, high) { return Math.ceil(Math.random() * (high - low) + low); } /* * 获取 0~30° 之间的一个任意正负值 */ function get30DegRandom() { return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30)); } var ImgFigure = React.createClass({ /* * imgFigure 的点击处理函数 */ handleClick: function (e) { if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.stopPropagation(); e.preventDefault(); }, render:function () { var styleObj = {}; // 如果props属性中指定了这张图片的位置,则使用 if (this.props.arrange.pos) { styleObj = this.props.arrange.pos; } // 如果图片的旋转角度有值并且不为0, 添加旋转角度 if (this.props.arrange.rotate) { (['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function (value) { styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)'; }.bind(this)); } // 如果是居中的图片, z-index设为11 if (this.props.arrange.isCenter) { styleObj.zIndex = 11; } var imgFigureClassName = 'img-figure'; imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : ''; return ( <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}> <img src={this.props.data.imageURL} alt={this.props.data.title} /> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick}> <p> {this.props.data.desc} </p> </div> </figcaption> </figure> ); } }); // 控制组件 var ControllerUnit = React.createClass({ handleClick: function (e) { // 如果点击的是当前正在选中态的按钮,则翻转图片,否则将对应的图片居中 if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.preventDefault(); e.stopPropagation(); }, render: function () { var controlelrUnitClassName = 'controller-unit'; // 如果对应的是居中的图片,显示控制按钮的居中态 if (this.props.arrange.isCenter) { controlelrUnitClassName += ' is-center'; // 如果同时对应的是翻转图片, 显示控制按钮的翻转态 if (this.props.arrange.isInverse) { controlelrUnitClassName += ' is-inverse'; } } return ( <span className={controlelrUnitClassName} onClick={this.handleClick}></span> ); } }); var GalleryByReactApp = React.createClass ({ Constant: { centerPos: { left: 0, right: 0 }, hPosRange: { // 水平方向的取值范围 leftSecX: [0, 0], rightSecX: [0, 0], y: [0, 0] }, vPosRange: { // 垂直方向的取值范围 x: [0, 0], topY: [0, 0] } }, /* * 翻转图片 * @param index 传入当前被执行inverse操作的图片对应的图片信息数组的index值 * @returns {Function} 这是一个闭包函数, 其内return一个真正待被执行的函数 */ inverse: function (index) { return function () { var imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr: imgsArrangeArr }); }.bind(this); }, /* * 重新布局所有图片 * @param centerIndex 指定居中排布哪个图片 */ rearrange: function (centerIndex) { var imgsArrangeArr = this.state.imgsArrangeArr, Constant = this.Constant, centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecX, hPosRangeY = hPosRange.y, vPosRangeTopY = vPosRange.topY, vPosRangeX = vPosRange.x, imgsArrangeTopArr = [], topImgNum = Math.floor(Math.random() * 2), // 取一个或者不取 topImgSpliceIndex = 0, imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1); // 首先居中 centerIndex 的图片, 居中的 centerIndex 的图片不需要旋转 imgsArrangeCenterArr[0] = { pos: centerPos, rotate: 0, isCenter: true }; // 取出要布局上侧的图片的状态信息 topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum)); imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum); // 布局位于上侧的图片 imgsArrangeTopArr.forEach(function (value, index) { imgsArrangeTopArr[index] = { pos: { top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]), left: getRangeRandom(vPosRangeX[0], vPosRangeX[1]) }, rotate: get30DegRandom(), isCenter: false }; }); // 布局左右两侧的图片 for (var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) { var hPosRangeLORX = null; // 前半部分布局左边, 右半部分布局右边 if (i < k) { hPosRangeLORX = hPosRangeLeftSecX; } else { hPosRangeLORX = hPosRangeRightSecX; } imgsArrangeArr[i] = { pos: { top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate: get30DegRandom(), isCenter: false }; } if (imgsArrangeTopArr && imgsArrangeTopArr[0]) { imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]); this.setState({ imgsArrangeArr: imgsArrangeArr }); }, /* * 利用arrange函数, 居中对应index的图片 * @param index, 需要被居中的图片对应的图片信息数组的index值 * @returns {Function} */ center: function (index) { return function () { this.rearrange(index); }.bind(this); }, getInitialState: function () { return { imgsArrangeArr: [ /*{ pos: { left: '0', top: '0' }, rotate: 0, // 旋转角度 isInverse: false, // 图片正反面 isCenter: false, // 图片是否居中 }*/ ] }; }, //组建加载后,为每张图片计算其位置的范围 componentDidMount: function () { //首先拿到舞台的大小 var stageDOM = findDOMNode(this.refs.stage), stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW/2), halfStageH = Math.ceil(stageH/2); //拿到一个imgFilgure的大小 var imgFigureDom = findDOMNode(this.refs.imgFigure0), imgW = imgFigureDom.scrollWidth, imgH = imgFigureDom.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); // 计算中心图片的位置点 this.Constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH }; // 计算左侧,右侧区域图片排布位置的取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[1] = stageH - halfImgH; // 计算上侧区域图片排布位置的取值范围 this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.Constant.vPosRange.x[0] = halfStageW - imgW; this.Constant.vPosRange.x[1] = halfStageW; this.rearrange(0); }, render() { var controllerUnits = [], imgFigures=[]; imageDatas.forEach(function (value,index) { if (!this.state.imgsArrangeArr[index]) { this.state.imgsArrangeArr[index] = { pos: { left: 0, top: 0 }, rotate: 0, isInverse: false //isCenter: false }; } imgFigures.push( <ImgFigure data={value} key={index} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)} />); controllerUnits.push( <ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)} /> ); }.bind(this)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} <nav className="controller-nav"> {controllerUnits} </nav> </section> </section> ); } }) GalleryByReactApp.defaultProps = { }; export default GalleryByReactApp;
src/frontend/src/components/DonorDetailPage.js
open-austin/influence-texas
import React from 'react' import { useParams } from 'react-router-dom' import { useQuery } from '@apollo/react-hooks' import { gql } from 'apollo-boost' import Typography from '@material-ui/core/Typography' import PaginatedList, { ShortLoadingListBody } from './PaginatedList' import { formatMoney, getDebugQuery } from 'utils' import CustomLink from 'components/CustomLink' import { BlankLoadingLine } from 'styles' import { RoundSquare } from 'styles' import { useTheme } from '@material-ui/core' const GET_DONOR = gql` query Donor($id: Int!) { donor(pk: $id) { fullName totalContributions city state employer occupation donations { cycleTotal candidateName office party legId } } ${getDebugQuery()} } ` function DonorDetailPage() { const { palette } = useTheme() const { id } = useParams() const { data, loading, error } = useQuery(GET_DONOR, { variables: { id }, }) document.title = `${data ? data.donor.fullName : ''} - Influence Texas` if (error) { return 'server error' } const fullDonorData = data ? data.donor : {} return ( <div className="detail-page"> <CustomLink to="/donors"> ← All Donors</CustomLink> <section style={{ margin: '1rem' }}> <h1> {loading ? <BlankLoadingLine width="40%" /> : fullDonorData.fullName} </h1> <div> {loading ? ( <BlankLoadingLine width="20%" /> ) : ( `Total Contributions: ${formatMoney( fullDonorData.totalContributions, )}` )} </div> {fullDonorData.occupation}{' '} {fullDonorData.occupation && fullDonorData.employer && 'at'}{' '} {fullDonorData.employer} <div> {fullDonorData.city}, {fullDonorData.state} </div> </section> <PaginatedList url="legislators/legislator" pk="legId" data={ loading ? null : { edges: fullDonorData.donations, totalCount: fullDonorData.donations.length, } } columns={[ { render: (rowData) => ( <div style={{ display: 'flex' }}> <RoundSquare style={{ marginTop: 10, width: 20, height: 20, background: rowData.legId ? palette.primary.main : '#bbb', }} /> <div style={{ margin: '0 1em' }}> <Typography>{rowData.candidateName}</Typography> <Typography variant="subtitle2"> {rowData.office} {rowData.party ? `(${rowData.party})` : ''} </Typography> </div> </div> ), }, { render: (rowData) => ( <div style={{ textAlign: 'right' }}> {formatMoney(rowData.cycleTotal)} </div> ), }, ]} showHover={(rowData) => !!rowData.legId} loading={loading} loadingListBody={ShortLoadingListBody} rowsPerPage={500} /> </div> ) } export default DonorDetailPage
packages/core/__deprecated__/Project/Project.js
romelperez/arwes
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import AnimationComponent from '../Animation'; import FrameComponent from '../Frame'; import WordsComponent from '../Words'; import HeadingComponent from '../Heading'; // TODO: // - Add a 'featured' prop to highligh item. export default function Project (props) { const { theme, classes, sounds, Animation, Frame, Words, Heading, animation, animate, show, node, header, headerSize, icon, className, children, ...etc } = props; const cls = cx(classes.root, className); return ( <Animation animate={animate} show={show} timeout={theme.animTime} {...animation} > {anim => React.createElement( node, { className: cx(cls, classes[anim.status]), ...etc }, <Frame animate={animate} show={show} timeout={theme.animTime} layer='primary' level={0} corners={4} hover noBackground onClick={() => sounds.click && sounds.click.play()} > {frameAnim => ( <div> <header className={classes.header}> <Heading node='h1'> <Words animate={animate} show={frameAnim.entered}> {header} </Words> </Heading> <div className={classes.icon}>{icon}</div> </header> <div className={classes.separator} /> <div className={classes.children}> {typeof children === 'function' ? children(frameAnim) : children} </div> </div> )} </Frame> ) } </Animation> ); } Project.propTypes = { Animation: PropTypes.any.isRequired, Frame: PropTypes.any.isRequired, Words: PropTypes.any.isRequired, Heading: PropTypes.any.isRequired, theme: PropTypes.any.isRequired, classes: PropTypes.any.isRequired, animate: PropTypes.bool, show: PropTypes.bool, animation: PropTypes.object, /** * It uses the `click` player. */ sounds: PropTypes.object, /** * The HTML tag element to use. */ node: PropTypes.string, /** * The HTML header used for the title. */ header: PropTypes.string.isRequired, /** * The actual font size to use for the HTML header. */ headerSize: PropTypes.oneOf(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']), /** * The icon to decorate the project. */ icon: PropTypes.any, /** * If function, receives the animation status object. */ children: PropTypes.any, className: PropTypes.any }; Project.defaultProps = { Animation: AnimationComponent, Frame: FrameComponent, Words: WordsComponent, Heading: HeadingComponent, show: true, sounds: {}, node: 'article', headerSize: 'h2', icon: <i className='mdi mdi-package' /> };
docs/app/Examples/modules/Dropdown/Content/DropdownExampleLabel.js
clemensw/stardust
import React from 'react' import { Dropdown } from 'semantic-ui-react' const DropdownExampleLabel = () => ( <Dropdown text='Filter' floating labeled button className='icon'> {/* <i class="filter icon"></i> */} <Dropdown.Menu> <Dropdown.Header icon='tags' content='Filter by tag' /> <Dropdown.Divider /> <Dropdown.Item label={{ color: 'red', empty: true, circular: true }} text='Important' /> <Dropdown.Item label={{ color: 'blue', empty: true, circular: true }} text='Announcement' /> <Dropdown.Item label={{ color: 'black', empty: true, circular: true }} text='Discussion' /> </Dropdown.Menu> </Dropdown> ) export default DropdownExampleLabel
components/Form/Select/Select.story.js
NGMarmaduke/bloom
import React from 'react'; import { storiesOf, action } from '@storybook/react'; import { withKnobs, boolean } from '@storybook/addon-knobs'; import Select from './Select'; import Option from './Option'; import icons from '../../Icon/icons'; const stories = storiesOf('FormComponents', module); stories.addDecorator(withKnobs); stories.add('Select', () => ( <Select name="icon" onChange={ action('onChange') } onFocus={ action('onFocus') } onBlur={ action('onBlur') } error={ boolean('Errored', false) ? 'Something went wrong' : '' } multiple={ boolean('Multiple', false) } > { Object .keys(icons) .map(option => ( <Option key={ option } value={ option }>{ option }</Option> )) } </Select> )) .add('Select w/high priority', () => ( <Select name="icon" onChange={ action('onChange') } onFocus={ action('onFocus') } onBlur={ action('onBlur') } error={ boolean('Errored', false) ? 'Something went wrong' : '' } multiple={ boolean('Multiple', false) } priority="high" > { Object .keys(icons) .map(option => ( <Option key={ option } value={ option }>{ option }</Option> )) } </Select> ));
node_modules/redbox-react/examples/react-hot-loader-example/index.js
hnikupet/dddhackaton
import React from 'react' import App from './components/App' const root = document.getElementById('root') React.render(<App />, root)
src/components/Layout/SearchDrawer/AdvancedSearch/DateField/presenter.js
ndlib/usurper
import React from 'react' import PropTypes from 'prop-types' const DateField = (props) => { // Create list of days const days = [(<option id={`${props.id}Day_00`} key={`${props.id}Day_00`}>Day</option>)] for (let i = 1; i <= 31; i++) { const id = `${props.id}${props.formatID(i, 'Day')}` days.push(<option id={id} key={id}>{i}</option>) } // Create list of months const months = [(<option id={`${props.id}Month_00`} key={`${props.id}Month_00`}>Month</option>)] for (let i = 1; i <= 12; i++) { const id = `${props.id}${props.formatID(i, 'Month')}` months.push(<option id={id} key={id}>{i}</option>) } return ( <div> <label>{props.label}: </label> <div className='dateFieldSelector'> <span className='selector'> <select id={`${props.id}Day`} onChange={props.onChange}>{days}</select> </span> <span className='selector'> <select id={`${props.id}Month`} onChange={props.onChange}>{months}</select> </span> <input type='text' id={`${props.id}Year5`} placeholder='year' onBlur={props.onChange} onKeyDown={props.onKeyDown} autoComplete='off' data-lpignore /> </div> </div> ) } DateField.propTypes = { id: PropTypes.string.isRequired, onChange: PropTypes.func, onKeyDown: PropTypes.func, label: PropTypes.string.isRequired, formatID: PropTypes.func.isRequired, } export default DateField
docs/src/pages/components/tables/CustomPaginationActionsTable.js
lgollut/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import { makeStyles, useTheme } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableFooter from '@material-ui/core/TableFooter'; import TablePagination from '@material-ui/core/TablePagination'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import IconButton from '@material-ui/core/IconButton'; import FirstPageIcon from '@material-ui/icons/FirstPage'; import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft'; import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight'; import LastPageIcon from '@material-ui/icons/LastPage'; const useStyles1 = makeStyles((theme) => ({ root: { flexShrink: 0, marginLeft: theme.spacing(2.5), }, })); function TablePaginationActions(props) { const classes = useStyles1(); const theme = useTheme(); const { count, page, rowsPerPage, onChangePage } = props; const handleFirstPageButtonClick = (event) => { onChangePage(event, 0); }; const handleBackButtonClick = (event) => { onChangePage(event, page - 1); }; const handleNextButtonClick = (event) => { onChangePage(event, page + 1); }; const handleLastPageButtonClick = (event) => { onChangePage(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1)); }; return ( <div className={classes.root}> <IconButton onClick={handleFirstPageButtonClick} disabled={page === 0} aria-label="first page" > {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />} </IconButton> <IconButton onClick={handleBackButtonClick} disabled={page === 0} aria-label="previous page"> {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />} </IconButton> <IconButton onClick={handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="next page" > {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />} </IconButton> <IconButton onClick={handleLastPageButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="last page" > {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />} </IconButton> </div> ); } TablePaginationActions.propTypes = { count: PropTypes.number.isRequired, onChangePage: PropTypes.func.isRequired, page: PropTypes.number.isRequired, rowsPerPage: PropTypes.number.isRequired, }; function createData(name, calories, fat) { return { name, calories, fat }; } const rows = [ createData('Cupcake', 305, 3.7), createData('Donut', 452, 25.0), createData('Eclair', 262, 16.0), createData('Frozen yoghurt', 159, 6.0), createData('Gingerbread', 356, 16.0), createData('Honeycomb', 408, 3.2), createData('Ice cream sandwich', 237, 9.0), createData('Jelly Bean', 375, 0.0), createData('KitKat', 518, 26.0), createData('Lollipop', 392, 0.2), createData('Marshmallow', 318, 0), createData('Nougat', 360, 19.0), createData('Oreo', 437, 18.0), ].sort((a, b) => (a.calories < b.calories ? -1 : 1)); const useStyles2 = makeStyles({ table: { minWidth: 500, }, }); export default function CustomPaginationActionsTable() { const classes = useStyles2(); const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(5); const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage); const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; return ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="custom pagination table"> <TableBody> {(rowsPerPage > 0 ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : rows ).map((row) => ( <TableRow key={row.name}> <TableCell component="th" scope="row"> {row.name} </TableCell> <TableCell style={{ width: 160 }} align="right"> {row.calories} </TableCell> <TableCell style={{ width: 160 }} align="right"> {row.fat} </TableCell> </TableRow> ))} {emptyRows > 0 && ( <TableRow style={{ height: 53 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} </TableBody> <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]} colSpan={3} count={rows.length} rowsPerPage={rowsPerPage} page={page} SelectProps={{ inputProps: { 'aria-label': 'rows per page' }, native: true, }} onChangePage={handleChangePage} onChangeRowsPerPage={handleChangeRowsPerPage} ActionsComponent={TablePaginationActions} /> </TableRow> </TableFooter> </Table> </TableContainer> ); }
app/assets/scripts/components/map-options.js
orma/openroads-vn-analytics
import React from 'react'; import { getContext } from 'recompose'; import T, { translate } from './t'; const MapOptions = ({ layer, language, handleLayerChange, handleShowNoVpromms }) => ( <div className='panel options-panel'> <div className='panel__body'> <form className='form'> <div className='form__group'> <label className='form__label'><T>Visualized variable</T></label> <select className='form__control' onChange={ e => handleLayerChange(e) }> <option value='iri_mean'>{translate(language, 'IRI')}</option> <option value='or_section_delivery_vehicle'>{translate(language, 'CVTS')}</option> </select> </div> {layer === 'iri_mean' && ( <div className='form__group'> <label className='form__label'>{translate(language, 'Options')}</label> <label className='form__option form__option--switch option fos-io' htmlFor='show-no-vpromms' > <input type='checkbox' defaultChecked={true} name='show-no-vpromms' id='show-no-vpromms' value='show-no-vpromms' onChange={ e => handleShowNoVpromms(e) } /> <span className='form__option__ui'></span> <span className='form__option__text'><T>Road without VPRoMMS ID</T> <b>----</b></span> </label> </div> ) } </form> </div> </div> ); MapOptions.propTypes = { layer: React.PropTypes.string, handleLayerChange: React.PropTypes.func, handleShowNoVpromms: React.PropTypes.func, language: React.PropTypes.string }; export default getContext({ language: React.PropTypes.string })(MapOptions);
docs/app/Examples/elements/Icon/IconSet/IconExampleAccessibility.js
ben174/Semantic-UI-React
import React from 'react' import { Grid, Icon } from 'semantic-ui-react' const IconExampleAccessibility = () => ( <Grid columns='5' doubling> <Grid.Column> <Icon name='wheelchair' /> <p>wheelchair</p> </Grid.Column> <Grid.Column> <Icon name='asl interpreting' /> <p>asl interpreting</p> </Grid.Column> <Grid.Column> <Icon name='assistive listening systems' /> <p>assistive listening systems</p> </Grid.Column> <Grid.Column> <Icon name='audio description' /> <p>audio description</p> </Grid.Column> <Grid.Column> <Icon name='blind' /> <p>blind</p> </Grid.Column> <Grid.Column> <Icon name='braille' /> <p>braille</p> </Grid.Column> <Grid.Column> <Icon name='deafness' /> <p>deafness</p> </Grid.Column> <Grid.Column> <Icon name='low vision' /> <p>low vision</p> </Grid.Column> <Grid.Column> <Icon name='sign language' /> <p>sign language</p> </Grid.Column> <Grid.Column> <Icon name='universal access' /> <p>universal access</p> </Grid.Column> <Grid.Column> <Icon name='volume control phone' /> <p>volume control phone</p> </Grid.Column> </Grid> ) export default IconExampleAccessibility
src/svg-icons/hardware/phone-iphone.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwarePhoneIphone = (props) => ( <SvgIcon {...props}> <path d="M15.5 1h-8C6.12 1 5 2.12 5 3.5v17C5 21.88 6.12 23 7.5 23h8c1.38 0 2.5-1.12 2.5-2.5v-17C18 2.12 16.88 1 15.5 1zm-4 21c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5-4H7V4h9v14z"/> </SvgIcon> ); HardwarePhoneIphone = pure(HardwarePhoneIphone); HardwarePhoneIphone.displayName = 'HardwarePhoneIphone'; HardwarePhoneIphone.muiName = 'SvgIcon'; export default HardwarePhoneIphone;
ui/src/main/js/components/UpdateStateMachine.js
rdelval/aurora
import React from 'react'; import StateMachine from 'components/StateMachine'; import { addClass } from 'utils/Common'; import { UPDATE_STATUS } from 'utils/Thrift'; import { getClassForUpdateStatus } from 'utils/Update'; export default function UpdateStateMachine({ update }) { const events = update.updateEvents; const states = events.map((e, i) => ({ className: addClass( getClassForUpdateStatus(e.status), (i === events.length - 1) ? ' active' : ''), state: UPDATE_STATUS[e.status], message: e.message, timestamp: e.timestampMs })); const className = getClassForUpdateStatus(events[events.length - 1].status); return <StateMachine className={addClass('update-state-machine', className)} states={states} />; }
app/javascript/mastodon/features/account_gallery/components/media_item.js
im-in-space/mastodon
import Blurhash from 'mastodon/components/blurhash'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; import { autoPlayGif, displayMedia, useBlurhash } from 'mastodon/initial_state'; import { isIOS } from 'mastodon/is_mobile'; import PropTypes from 'prop-types'; import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class MediaItem extends ImmutablePureComponent { static propTypes = { attachment: ImmutablePropTypes.map.isRequired, displayWidth: PropTypes.number.isRequired, onOpenMedia: PropTypes.func.isRequired, }; state = { visible: displayMedia !== 'hide_all' && !this.props.attachment.getIn(['status', 'sensitive']) || displayMedia === 'show_all', loaded: false, }; handleImageLoad = () => { this.setState({ loaded: true }); } handleMouseEnter = e => { if (this.hoverToPlay()) { e.target.play(); } } handleMouseLeave = e => { if (this.hoverToPlay()) { e.target.pause(); e.target.currentTime = 0; } } hoverToPlay () { return !autoPlayGif && ['gifv', 'video'].indexOf(this.props.attachment.get('type')) !== -1; } handleClick = e => { if (e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); if (this.state.visible) { this.props.onOpenMedia(this.props.attachment); } else { this.setState({ visible: true }); } } } render () { const { attachment, displayWidth } = this.props; const { visible, loaded } = this.state; const width = `${Math.floor((displayWidth - 4) / 3) - 4}px`; const height = width; const status = attachment.get('status'); const title = status.get('spoiler_text') || attachment.get('description'); let thumbnail, label, icon, content; if (!visible) { icon = ( <span className='account-gallery__item__icons'> <Icon id='eye-slash' /> </span> ); } else { if (['audio', 'video'].includes(attachment.get('type'))) { content = ( <img src={attachment.get('preview_url') || attachment.getIn(['account', 'avatar_static'])} alt={attachment.get('description')} onLoad={this.handleImageLoad} /> ); if (attachment.get('type') === 'audio') { label = <Icon id='music' />; } else { label = <Icon id='play' />; } } else if (attachment.get('type') === 'image') { const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0; const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0; const x = ((focusX / 2) + .5) * 100; const y = ((focusY / -2) + .5) * 100; content = ( <img src={attachment.get('preview_url')} alt={attachment.get('description')} style={{ objectPosition: `${x}% ${y}%` }} onLoad={this.handleImageLoad} /> ); } else if (attachment.get('type') === 'gifv') { content = ( <video className='media-gallery__item-gifv-thumbnail' aria-label={attachment.get('description')} role='application' src={attachment.get('url')} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} autoPlay={!isIOS() && autoPlayGif} loop muted /> ); label = 'GIF'; } thumbnail = ( <div className='media-gallery__gifv'> {content} {label && <span className='media-gallery__gifv__label'>{label}</span>} </div> ); } return ( <div className='account-gallery__item' style={{ width, height }}> <a className='media-gallery__item-thumbnail' href={status.get('url')} onClick={this.handleClick} title={title} target='_blank' rel='noopener noreferrer'> <Blurhash hash={attachment.get('blurhash')} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && loaded })} dummy={!useBlurhash} /> {visible ? thumbnail : icon} </a> </div> ); } }
src/components/foundation/original/FoundationOriginal.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './FoundationOriginal.svg' /** FoundationOriginal */ function FoundationOriginal({ width, height, className }) { return ( <SVGDeviconInline className={'FoundationOriginal' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } FoundationOriginal.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default FoundationOriginal
src/components/Home/index.js
chavisclark/chavisclark.github.io
import React from 'react'; import Button from '../Button'; import { Link } from 'react-router'; import Helmet from 'react-helmet'; import styles from './styles.css'; function Home() { return ( <article className={styles.padding}> <Helmet title="Chavis Clark | Digital Nomad & Fullstack Web Developer" meta={[ { name: 'description', content: 'Chavis Clark is a self-taught Web Application Developer who works remotely and passionately. View Chavis Clark\'s comprehensive work history and GitHub projects here.' }, ]} /> <div className={`${styles.centered} ${styles.intro}`}> <h3>I develop performance-oriented websites and web applications.</h3> When I'm not practicing Spanish or mentoring less-experienced developers, I'm exploring new places, cultures, and music! </div> </article> ); } export default Home;
examples/src/components/CustomRenderField.js
mcanthony/react-select
import React from 'react'; import Select from 'react-select'; function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } var CustomRenderField = React.createClass({ displayName: 'CustomRenderField', propTypes: { delimiter: React.PropTypes.string, label: React.PropTypes.string, multi: React.PropTypes.bool, }, renderOption (option) { return <span style={{ color: option.hex }}>{option.label} ({option.hex})</span>; }, renderValue (option) { return <strong style={{ color: option.hex }}>{option.label}</strong>; }, render () { var ops = [ { label: 'Red', value: 'red', hex: '#EC6230' }, { label: 'Green', value: 'green', hex: '#4ED84E' }, { label: 'Blue', value: 'blue', hex: '#6D97E2' } ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select delimiter={this.props.delimiter} multi={this.props.multi} allowCreate={true} placeholder="Select your favourite" options={ops} optionRenderer={this.renderOption} valueRenderer={this.renderValue} onChange={logChange} /> </div> ); } }); module.exports = CustomRenderField;
src/results/ResultsList.react.js
codeforamerica/citybook
import React, { Component } from 'react'; import Alert from 'react-bootstrap/lib/Alert'; import LoadingSpinner from '../LoadingSpinner.react.js'; import Result from './Result.react.js'; import '../../styles/loading-spinner.scss'; export default class ResultsList extends Component { constructor(){ super(); } render() { let list; let errors; if(this.props.erros){ console.error(error); } if(this.props.loaded){ let resultsList = this.props.results; resultsList.sort(function(a, b){ if(a['Organization Name'] < b['Organization Name']) return - 1; if(a['Organization Name'] > b['Organization Name']) return 1; return 0; }); list = resultsList.map(function(result, i){ let resultName = result['Organization Name'] return ( <Result key={i} result={result} /> ) }) } else { list = <LoadingSpinner /> } return( <ul className='results-list row'> {list} </ul> ) } }
src/navigation/auth.js
banovotz/WatchBug2
/** * Auth Scenes * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React from 'react'; import { Scene, ActionConst } from 'react-native-router-flux'; // Consts and Libs import { AppConfig } from '@constants/'; // Scenes import Authenticate from '@containers/auth/AuthenticateView'; import LoginForm from '@containers/auth/Forms/LoginContainer'; import SignUpForm from '@containers/auth/Forms/SignUpContainer'; import ResetPasswordForm from '@containers/auth/Forms/ResetPasswordContainer'; import UpdateProfileForm from '@containers/auth/Forms/UpdateProfileContainer'; /* Routes ==================================================================== */ const scenes = ( <Scene key={'authenticate'}> <Scene hideNavBar key={'authLanding'} component={Authenticate} type={ActionConst.RESET} analyticsDesc={'Authentication'} /> <Scene {...AppConfig.navbarProps} key={'login'} title={'Login'} clone component={LoginForm} analyticsDesc={'Login'} /> <Scene {...AppConfig.navbarProps} key={'signUp'} title={'Sign Up'} clone component={SignUpForm} analyticsDesc={'Sign Up'} /> <Scene {...AppConfig.navbarProps} key={'passwordReset'} title={'Password Reset'} clone component={ResetPasswordForm} analyticsDesc={'Password Reset'} /> <Scene {...AppConfig.navbarProps} key={'updateProfile'} title={'Update Profile'} clone component={UpdateProfileForm} analyticsDesc={'Update Profile'} /> </Scene> ); export default scenes;
src/server/index.js
vesparny/widget
'use strict'; const env = process.env.NODE_ENV || 'development'; import http from 'http'; import path from 'path'; import cors from 'cors'; import React from 'react'; import Router from 'react-router'; import FluxComponent from 'flummox/component'; import Flux from '../shared/Flux'; import routes from '../shared/routes'; import address from 'network-address'; import api from './api'; import logger from './logger'; import { CustomError } from './errors'; import app from './app'; const webpackConfigDev = require('../../webpack.config.development'); let js = `http://${webpackConfigDev._address}:${webpackConfigDev._hotPort}/build/bundle.js`; if (app.get('env') === 'development') { // run webpack dev server require('../../dev-tools'); } if (app.get('env') === 'production') { const webpackBuildStats = require('../../public/build/webpackBuildStats'); js = `/build/bundle-${webpackBuildStats.hash}.min.js`; // jscs:disable } // register apis app.use('/api', api); // react-router will take care of the rest app.use((req, res) => { const flux = new Flux(); let appString; Router.run(routes, req.path, function (Handler, state) { let isNotFound = state.routes.some(route => route.name === 'not-found'); res.status(isNotFound ? 404 : 200); try { appString = React.renderToString( <FluxComponent flux={flux}> <Handler {...state} /> </FluxComponent>); }catch (err) { throw new CustomError({ message: err.message }); } res.render('index', { js: js, appString: appString }); }); }); app.use((err, req, res, next) => {/* eslint no-unused-vars:0 */ logger.error({ err: err.stack }); res.status(err.statusCode); res.send({ error: err.message || 'Unexpected error' }); }); app.listen(app.get('port'), () => { logger.info(`Demo app is listening on ${address()}:${app.get('port')} env=${env}`); // jscs:disable });
packages/material-ui-icons/src/Laptop.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M20 18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z" /></g> , 'Laptop');
blueocean-material-icons/src/js/components/svg-icons/image/filter-9.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageFilter9 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM15 5h-2c-1.1 0-2 .89-2 2v2c0 1.11.9 2 2 2h2v2h-4v2h4c1.1 0 2-.89 2-2V7c0-1.11-.9-2-2-2zm0 4h-2V7h2v2z"/> </SvgIcon> ); ImageFilter9.displayName = 'ImageFilter9'; ImageFilter9.muiName = 'SvgIcon'; export default ImageFilter9;
docs/src/pages/layout/hidden/BreakpointOnly.js
cherniavskii/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import compose from 'recompose/compose'; import { withStyles } from 'material-ui/styles'; import Paper from 'material-ui/Paper'; import Hidden from 'material-ui/Hidden'; import withWidth from 'material-ui/utils/withWidth'; import Typography from 'material-ui/Typography'; const styles = theme => ({ root: { flexGrow: 1, }, container: { display: 'flex', }, paper: { padding: theme.spacing.unit * 2, textAlign: 'center', color: theme.palette.text.secondary, flex: '1 0 auto', margin: theme.spacing.unit, }, }); function BreakpointOnly(props) { const { classes } = props; return ( <div className={classes.root}> <Typography variant="subheading">Current width: {props.width}</Typography> <div className={classes.container}> <Hidden only="lg"> <Paper className={classes.paper}>Hidden on lg</Paper> </Hidden> <Hidden only="sm"> <Paper className={classes.paper}>Hidden on sm</Paper> </Hidden> <Hidden only={['sm', 'lg']}> <Paper className={classes.paper}>Hidden on sm and lg</Paper> </Hidden> </div> </div> ); } BreakpointOnly.propTypes = { classes: PropTypes.object.isRequired, width: PropTypes.string.isRequired, }; export default compose(withStyles(styles), withWidth())(BreakpointOnly);
server/sonar-web/src/main/js/components/shared/checkbox.js
abbeyj/sonarqube
import React from 'react'; export default React.createClass({ propTypes: { onCheck: React.PropTypes.func.isRequired, initiallyChecked: React.PropTypes.bool, thirdState: React.PropTypes.bool }, getInitialState() { return { checked: this.props.initiallyChecked || false }; }, componentWillReceiveProps(nextProps) { if (nextProps.initiallyChecked != null) { this.setState({ checked: nextProps.initiallyChecked }); } }, toggle(e) { e.preventDefault(); this.props.onCheck(!this.state.checked); this.setState({ checked: !this.state.checked }); }, render() { let classNames = ['icon-checkbox']; if (this.state.checked) { classNames.push('icon-checkbox-checked'); } if (this.props.thirdState) { classNames.push('icon-checkbox-single'); } let className = classNames.join(' '); return <a onClick={this.toggle} className={className} href="#"/>; } });
frontend/app/components/Form/FormRelatedPictures.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' // import Text from 'components/Form/Common/Text' // NOTE: importing the non-wrapped provide() version import FormRelatedPicture from 'components/Form/FormRelatedPicture' import { getIndexOfElementById, removeItem, moveItemDown, moveItemUp } from 'components/Form/FormInteractions' import ProviderHelpers from 'common/ProviderHelpers' // REDUX import { connect } from 'react-redux' // REDUX: actions/dispatch/func import { createContributor, fetchContributors } from 'reducers/fvContributor' import { fetchDialect } from 'reducers/fvDialect' import { fetchResources } from 'reducers/fvResources' import selectn from 'selectn' const { string, array, object, func, number } = PropTypes let SelectMediaComponent = null export class FormRelatedPictures extends React.Component { static propTypes = { name: string.isRequired, className: string, textInfo: string, items: array, idDescribedbyItemBrowse: string, idDescribedByItemMove: string, textDescribedbyItemBrowse: string, textDescribedByItemMove: string, textLegendItems: string, textBtnAddItem: string, textLegendItem: string, textBtnRemoveItem: string, textBtnMoveItemUp: string, textBtnMoveItemDown: string, textBtnCreateItem: string, textBtnSelectExistingItems: string, textLabelItemSearch: string, DEFAULT_PAGE: number, DEFAULT_PAGE_SIZE: number, DEFAULT_LANGUAGE: string, DEFAULT_SORT_COL: string, DEFAULT_SORT_TYPE: string, // REDUX: reducers/state computeContributor: object.isRequired, computeContributors: object.isRequired, computeCreateContributor: object, computeDialect: object.isRequired, computeDialect2: object.isRequired, splitWindowPath: array.isRequired, // REDUX: actions/dispatch/func createContributor: func.isRequired, fetchContributors: func.isRequired, fetchDialect: func.isRequired, fetchResources: func.isRequired, } static defaultProps = { className: 'FormRelatedPictures', idDescribedbyItemBrowse: 'describedbyRelatedPictureBrowse', idDescribedByItemMove: 'describedByRelatedPictureMove', name: 'FormRelatedPictures', textDescribedbyItemBrowse: 'Select a picture from previously created pictures', textDescribedByItemMove: `If you are adding multiple Related Pictures, you can change the position of the picture with the 'Move Related Picture left' and 'Move Related Picture right' buttons`, textLegendItems: 'Related Pictures', textBtnAddItem: 'Add Related Picture', textLegendItem: 'Related Picture', textBtnRemoveItem: 'Remove Related Picture', textBtnMoveItemUp: 'Move Related Picture left', textBtnMoveItemDown: 'Move Related Picture right', textBtnCreateItem: 'Create new picture', textBtnSelectExistingItems: 'Select from existing pictures', textLabelItemSearch: 'Search existing pictures', DEFAULT_PAGE: 1, DEFAULT_PAGE_SIZE: 100, DEFAULT_LANGUAGE: 'english', DEFAULT_SORT_COL: 'dc:title', DEFAULT_SORT_TYPE: 'asc', } state = { items: [], loading: true, pictures: [], } // Fetch data on initial render async componentDidMount() { const { computeDialect, splitWindowPath } = this.props // USING this.DIALECT_PATH instead of setting state // this.setState({ dialectPath: dialectPath }) this.DIALECT_PATH = ProviderHelpers.getDialectPathFromURLArray(splitWindowPath) this.CONTRIBUTOR_PATH = `${this.DIALECT_PATH}/Contributors` // Get data for computeDialect if (!computeDialect.success) { await this.props.fetchDialect('/' + this.DIALECT_PATH) } const { DEFAULT_PAGE, DEFAULT_PAGE_SIZE, DEFAULT_SORT_TYPE, DEFAULT_SORT_COL } = this.props let currentAppliedFilter = '' // eslint-disable-line // if (filter.has('currentAppliedFilter')) { // currentAppliedFilter = Object.values(filter.get('currentAppliedFilter').toJS()).join('') // } // Get contrinbutors await this.props.fetchContributors( this.CONTRIBUTOR_PATH, `${currentAppliedFilter}&currentPageIndex=${DEFAULT_PAGE - 1}&pageSize=${DEFAULT_PAGE_SIZE}&sortOrder=${DEFAULT_SORT_TYPE}&sortBy=${DEFAULT_SORT_COL}` ) // Get existing pictures // TODO: hardcoded current page and page size! await this.props.fetchResources( '/FV/Workspaces/', `AND ecm:primaryType LIKE 'FVPicture' AND ecm:isCheckedInVersion = 0 AND ecm:isTrashed = 0 AND ecm:currentLifeCycleState != 'Disabled' AND (ecm:path STARTSWITH '${ this.DIALECT_PATH }/Resources/')&currentPageIndex=${0}&pageSize=${1000}` ) const _SelectMediaComponent = await import('components/SelectMediaComponent') SelectMediaComponent = _SelectMediaComponent.default this.setState({ loading: false }) } render() { const { className, idDescribedbyItemBrowse, idDescribedByItemMove, textDescribedbyItemBrowse, textDescribedByItemMove, textLegendItems, textBtnAddItem, } = this.props const items = this.state.items return ( <fieldset className={className}> <legend>{textLegendItems}</legend> <button type="button" disabled={this.state.loading} onClick={() => { this.handleClickAddItem() }} > {textBtnAddItem} </button> {items} {this._generateHiddenInput()} {/* SCREEN READER DESCRIPTIONS --------------- */} <span id={idDescribedbyItemBrowse} className="visually-hidden"> {textDescribedbyItemBrowse} </span> <span id={idDescribedByItemMove} className="visually-hidden"> {textDescribedByItemMove} </span> </fieldset> ) } _generateHiddenInput = () => { const { items } = this.state const selectedItems = items.map((element) => { return element.props.id }) return <input type="hidden" name="fv:related_pictures" value={JSON.stringify(selectedItems)} /> } handleClickAddItem = () => { const _props = { name: this.props.name, className: this.props.className, idDescribedbyItemBrowse: this.props.idDescribedbyItemBrowse, idDescribedByItemMove: this.props.idDescribedByItemMove, textLegendItem: this.props.textLegendItem, textBtnRemoveItem: this.props.textBtnRemoveItem, textBtnMoveItemUp: this.props.textBtnMoveItemUp, textBtnMoveItemDown: this.props.textBtnMoveItemDown, textBtnCreateItem: this.props.textBtnCreateItem, textBtnSelectExistingItems: this.props.textBtnSelectExistingItems, textLabelItemSearch: this.props.textLabelItemSearch, handleClickSelectItem: this.handleClickSelectItem, handleClickRemoveItem: this.handleClickRemoveItem, handleClickMoveItemUp: this.handleClickMoveItemUp, handleClickMoveItemDown: this.handleClickMoveItemDown, handleItemSelected: this.handleItemSelected, computeDialectFromParent: this.props.computeDialect, DIALECT_PATH: this.DIALECT_PATH, } const items = this.state.items const id = `${_props.className}_${items.length}_${Date.now()}` items.push(<FormRelatedPicture key={id} id={id} {..._props} selectMediaComponent={SelectMediaComponent} />) this.setState({ items, }) } handleItemSelected = (selected, callback) => { const uid = selectn('uid', selected) let { items } = this.state const arg = { id: uid, items } if (getIndexOfElementById(arg) !== -1) { items = removeItem(arg) } const _props = { name: this.props.name, className: this.props.className, idDescribedbyItemBrowse: this.props.idDescribedbyItemBrowse, idDescribedByItemMove: this.props.idDescribedByItemMove, textLegendItem: this.props.textLegendItem, textBtnRemoveItem: this.props.textBtnRemoveItem, textBtnMoveItemUp: this.props.textBtnMoveItemUp, textBtnMoveItemDown: this.props.textBtnMoveItemDown, textBtnCreateItem: this.props.textBtnCreateItem, textBtnSelectExistingItems: this.props.textBtnSelectExistingItems, textLabelItemSearch: this.props.textLabelItemSearch, handleClickSelectItem: this.handleClickSelectItem, handleClickRemoveItem: this.handleClickRemoveItem, handleClickMoveItemUp: this.handleClickMoveItemUp, handleClickMoveItemDown: this.handleClickMoveItemDown, handleItemSelected: this.handleItemSelected, computeDialectFromParent: this.props.computeDialect, DIALECT_PATH: this.DIALECT_PATH, } this.setState( { items: [ ...items, <FormRelatedPicture componentState={3} key={uid} id={uid} {..._props} selectMediaComponent={SelectMediaComponent} />, ], }, () => { if (callback) { callback() } } ) } handleClickRemoveItem = (id) => { this.setState({ items: removeItem({ id, items: this.state.items }), }) } handleClickMoveItemDown = (id) => { this.setState({ items: moveItemDown({ id, items: this.state.items }), }) } handleClickMoveItemUp = (id) => { this.setState({ items: moveItemUp({ id, items: this.state.items }), }) } } // REDUX: reducers/state const mapStateToProps = (state /*, ownProps*/) => { const { fvContributor, fvDialect, windowPath } = state const { computeContributor, computeContributors, computeCreateContributor } = fvContributor const { computeDialect, computeDialect2 } = fvDialect const { splitWindowPath } = windowPath return { computeContributor, computeContributors, computeCreateContributor, computeDialect, computeDialect2, splitWindowPath, } } // REDUX: actions/dispatch/func const mapDispatchToProps = { createContributor, fetchContributors, fetchDialect, fetchResources, } export default connect(mapStateToProps, mapDispatchToProps)(FormRelatedPictures)
app/component/AddFriend.js
icalF/piye-kabare
'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, StyleSheet, Text, TextInput, TouchableHighlight, View } from 'react-native'; import styles from '../style/FormStyles'; export default class AddFriend extends Component { constructor(props) { super(props); this.state = { uname: '', isLoading: false, message: '' }; this.socket = this.props.socket; this.socket.on('add_friend_resp', this.addResp.bind(this)); } onUsernameChanged(ev) { this.setState({ uname: ev.nativeEvent.text }); } clearForm() { this.setState({ uname: '' }); } addResp(resp) { switch (resp) { case 300: this.clearForm(); this.setState({message: 'User had become friend', isLoading: false}); break; case 400: this.clearForm(); this.setState({message: 'Username not found', isLoading: false}); break; case 500: this.clearForm(); this.setState({message: 'Service error\nPlease try again', isLoading: false}); break; case 200: this.setState({message: 'Request has been sent', isLoading: false}); setTimeout(() => { this.setState({message: ''}); }, 500); this.props.onAdd(); break; } } onFind() { this.socket.emit('add_friend', { uname: this.props.uname, fname: this.state.uname }); this.setState({ isLoading: true }); } render() { var loading = this.state.isLoading ? <ActivityIndicator style={styles.loading} size='large'/> : <View/> return ( <View style={styles.container}> <TextInput style={styles.textInput} value={this.state.uname} onChange={this.onUsernameChanged.bind(this)} underlineColorAndroid={'transparent'} placeholder='Username'/> <TouchableHighlight style={styles.button} onPress={this.onFind.bind(this)} underlayColor='#1219FF'> <Text style={styles.buttonText}>Find</Text> </TouchableHighlight> {loading} <Text style={styles.description}>{this.state.message}</Text> </View> ); } };
src/components/form/index.js
WHCIBoys/nitpik-web
import React from 'react'; function Form({ children, handleSubmit }) { return ( <form onSubmit={(e) => { e.preventDefault(); if (document.activeElement) { document.activeElement.blur(); } handleSubmit(); }}> { children } </form> ); } Form.propTypes = { children: React.PropTypes.node, handleSubmit: React.PropTypes.func, }; export default Form;
src/lib/components/SecondExample.js
thepixelninja/react-component-test
import React from 'react'; import './SecondExample.scss'; const SecondExample = () => ( <div className="SecondExample"> <p className="SecondExample-text"> Based on Facebook's {'\u00A0'} <a className="SecondExample-link" target="_blank" rel="noopener noreferrer" href="https://github.com/facebookincubator/create-react-app" > Create react app </a> </p> <a className="SecondExample-github-link" target="_blank" rel="noopener noreferrer" href="https://github.com/Rubbby/create-react-library" > Documentation </a> </div> ); export default SecondExample;
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SvgInclusion.js
iamdoron/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 from 'react'; import logo from './assets/logo.svg'; export default () => <img id="feature-svg-inclusion" src={logo} alt="logo" />;
src/index.js
straku/react-workshop
import injectTapEventPlugin from 'react-tap-event-plugin' injectTapEventPlugin() import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import MuiTheme from './components/MuiTheme/MuiTheme' import App from './components/App/App' import store from './store' import './styles/fonts.css' import './styles/main.css' ReactDOM.render( <MuiTheme> <Provider store={store}> <App /> </Provider> </MuiTheme>, document.getElementById('root') )