path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
packages/examples-counter/src/containers/CounterApp.js
kastigar/borex
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Counter from '../components/Counter'; import * as CounterActions from '../actions/CounterActions'; class CounterApp extends Component { render() { const { counter, dispatch } = this.props; return ( <Counter counter={counter} {...bindActionCreators(CounterActions, dispatch)} /> ); } } function select(state) { return { counter: state.counter }; } export default connect(select)(CounterApp);
src/components/shell/index.js
datea/datea-webapp-react
import React from 'react'; import {inject} from 'mobx-react'; import {RouterView} from 'mobx-state-router'; import Main from '../main'; import HeadMeta from '../head-meta'; import DateoFormModal from '../dateo-form-modal'; import {MarkerDefs} from '../marker'; import ViewMap from './viewMap'; const Shell = ({store}) => <Main> <HeadMeta /> <RouterView routerStore={store.router} viewMap={ViewMap} /> <DateoFormModal /> <svg height="0" width="0" style={{padding:0, margin: 0, position: 'absolute'}}> <MarkerDefs /> </svg> </Main> export default inject('store')(Shell);
app/js/public_keys/connected_public_key_list.js
yock/forte-gui
import React from 'react'; import { connect } from 'react-redux'; import PublicKeyList from './public_key_list'; const deletePublicKey = (id) => { return { type: 'DELETE_PUBLIC_KEY', publicKeyId: id } } const mapStateToProps = (state) => { return { publicKeys: state.publicKeys } } const mapDispatchToProps = (dispatch) => { return { onDeleteClick(id) { return dispatch(deletePublicKey(id)); } } } const ConnectedPublicKeyList = connect( mapStateToProps, mapDispatchToProps )(PublicKeyList); export default ConnectedPublicKeyList;
src/Pagination.js
PeterDaveHello/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import PaginationButton from './PaginationButton'; import CustomPropTypes from './utils/CustomPropTypes'; import SafeAnchor from './SafeAnchor'; const Pagination = React.createClass({ mixins: [BootstrapMixin], propTypes: { activePage: React.PropTypes.number, items: React.PropTypes.number, maxButtons: React.PropTypes.number, ellipsis: React.PropTypes.bool, first: React.PropTypes.bool, last: React.PropTypes.bool, prev: React.PropTypes.bool, next: React.PropTypes.bool, onSelect: React.PropTypes.func, /** * You can use a custom element for the buttons */ buttonComponentClass: CustomPropTypes.elementType }, getDefaultProps() { return { activePage: 1, items: 1, maxButtons: 0, first: false, last: false, prev: false, next: false, ellipsis: true, buttonComponentClass: SafeAnchor, bsClass: 'pagination' }; }, renderPageButtons() { let pageButtons = []; let startPage, endPage, hasHiddenPagesAfter; let { maxButtons, activePage, items, onSelect, ellipsis, buttonComponentClass } = this.props; if(maxButtons){ let hiddenPagesBefore = activePage - parseInt(maxButtons / 2); startPage = hiddenPagesBefore > 1 ? hiddenPagesBefore : 1; hasHiddenPagesAfter = startPage + maxButtons <= items; if(!hasHiddenPagesAfter){ endPage = items; startPage = items - maxButtons + 1; if(startPage < 1){ startPage = 1; } } else { endPage = startPage + maxButtons - 1; } } else { startPage = 1; endPage = items; } for(let pagenumber = startPage; pagenumber <= endPage; pagenumber++){ pageButtons.push( <PaginationButton key={pagenumber} eventKey={pagenumber} active={pagenumber === activePage} onSelect={onSelect} buttonComponentClass={buttonComponentClass}> {pagenumber} </PaginationButton> ); } if(maxButtons && hasHiddenPagesAfter && ellipsis){ pageButtons.push( <PaginationButton key='ellipsis' disabled buttonComponentClass={buttonComponentClass}> <span aria-label='More'>...</span> </PaginationButton> ); } return pageButtons; }, renderPrev() { if(!this.props.prev){ return null; } return ( <PaginationButton key='prev' eventKey={this.props.activePage - 1} disabled={this.props.activePage === 1} onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='Previous'>&lsaquo;</span> </PaginationButton> ); }, renderNext() { if(!this.props.next){ return null; } return ( <PaginationButton key='next' eventKey={this.props.activePage + 1} disabled={this.props.activePage >= this.props.items} onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='Next'>&rsaquo;</span> </PaginationButton> ); }, renderFirst() { if(!this.props.first){ return null; } return ( <PaginationButton key='first' eventKey={1} disabled={this.props.activePage === 1 } onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='First'>&laquo;</span> </PaginationButton> ); }, renderLast() { if(!this.props.last){ return null; } return ( <PaginationButton key='last' eventKey={this.props.items} disabled={this.props.activePage >= this.props.items} onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='Last'>&raquo;</span> </PaginationButton> ); }, render() { return ( <ul {...this.props} className={classNames(this.props.className, this.getBsClassSet())}> {this.renderFirst()} {this.renderPrev()} {this.renderPageButtons()} {this.renderNext()} {this.renderLast()} </ul> ); } }); export default Pagination;
examples/demo3.js
seolheehwang/seolhee
import React from 'react'; import ReactDOM from 'react-dom'; import Gallery from '../src/Gallery'; class Demo3 extends React.Component { constructor(props){ super(props); this.state = { images: this.props.images }; } render () { return ( <div style={{ display: "block", minHeight: "1px", width: "100%", border: "1px solid #ddd", overflow: "auto"}}> <Gallery images={this.state.images} enableLightbox={false} enableImageSelection={false}/> </div> ); } } Demo3.propTypes = { images: React.PropTypes.arrayOf( React.PropTypes.shape({ src: React.PropTypes.string.isRequired, thumbnail: React.PropTypes.string.isRequired, srcset: React.PropTypes.array, caption: React.PropTypes.string, thumbnailWidth: React.PropTypes.number.isRequired, thumbnailHeight: React.PropTypes.number.isRequired }) ).isRequired }; Demo3.defaultProps = { images: shuffleArray([ { src: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_b.jpg", thumbnail: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_n.jpg", thumbnailWidth: 320, thumbnailHeight: 174, caption: "After Rain (Jeshu John - designerspics.com)" }, { src: "https://c6.staticflickr.com/9/8890/28897154101_a8f55be225_b.jpg", thumbnail: "https://c6.staticflickr.com/9/8890/28897154101_a8f55be225_n.jpg", thumbnailWidth: 320, thumbnailHeight: 183, caption: "37H (gratispgraphy.com)" }, { src: "https://c7.staticflickr.com/9/8106/28941228886_86d1450016_b.jpg", thumbnail: "https://c7.staticflickr.com/9/8106/28941228886_86d1450016_n.jpg", thumbnailWidth: 271, thumbnailHeight: 320, caption: "Orange Macro (Tom Eversley - isorepublic.com)" }, { src: "https://c6.staticflickr.com/9/8342/28897193381_800db6419e_b.jpg", thumbnail: "https://c6.staticflickr.com/9/8342/28897193381_800db6419e_n.jpg", thumbnailWidth: 320, thumbnailHeight: 213, caption: "201H (gratisography.com)" }, { src: "https://c8.staticflickr.com/9/8104/28973555735_ae7c208970_b.jpg", thumbnail: "https://c8.staticflickr.com/9/8104/28973555735_ae7c208970_n.jpg", thumbnailWidth: 320, thumbnailHeight: 213, caption: "Flower Interior Macro (Tom Eversley - isorepublic.com)" }, { src: "https://c1.staticflickr.com/9/8707/28868704912_cba5c6600e_b.jpg", thumbnail: "https://c1.staticflickr.com/9/8707/28868704912_cba5c6600e_n.jpg", thumbnailWidth: 320, thumbnailHeight: 213, caption: "Man on BMX (Tom Eversley - isorepublic.com)" }, { src: "https://c4.staticflickr.com/9/8578/28357117603_97a8233cf5_b.jpg", thumbnail: "https://c4.staticflickr.com/9/8578/28357117603_97a8233cf5_n.jpg", thumbnailWidth: 320, thumbnailHeight: 213, caption: "Ropeman - Thailand (Tom Eversley - isorepublic.com)" }, { src: "https://c1.staticflickr.com/9/8056/28354485944_148d6a5fc1_b.jpg", thumbnail: "https://c1.staticflickr.com/9/8056/28354485944_148d6a5fc1_n.jpg", thumbnailWidth: 257, thumbnailHeight: 320, caption: "A photo by 贝莉儿 NG. (unsplash.com)" } ]) }; ReactDOM.render(<Demo3 />, document.getElementById('demo3'));
js/messages/Post.js
andrej-kolic/A1terEg0
import React from 'react'; import moment from 'moment' import createLogger from '../logger'; const log = createLogger('components.Post'); export default class Post extends React.Component { constructor(props) { super(props); this.state = { dateDescription: this.getDateDescription() }; } getDateDescription = () => moment(this.props.message.createdAt * 1000).fromNow(); componentDidMount() { this.timerId = setInterval( () => this.setState({ dateDescription: this.getDateDescription() }), 30000 ); } componentWillUnmount() { log.debug('componentWillUnmount'); clearInterval(this.timerId); } render() { const highlightStyle = this.props.highlight ? styles.highlight : {}; const highlightArrowStyle = this.props.highlight ? styles.highlightArrow : {}; return ( <div> <div style={styles.container}> <img src={this.props.viewer.avatar} style={styles.avatar} /> <div style={{ ...styles.arrow, ...highlightArrowStyle }} /> <div style={styles.messageContainer}> <span style={{ ...styles.message, ...highlightStyle }}>{this.props.message.content}</span> </div> <button onClick={() => this.props.onStartEditing(this.props.message)} className="fa fa-pencil" style={{ ...styles.messageButton, ...styles.messageButtonEdit }} > </button> <button onClick={() => this.props.onDelete(this.props.message)} className="fa fa-times fa-2x" style={styles.messageButton} > </button> </div> <div style={styles.timestamp}>{this.state.dateDescription}</div> </div> ); } } const styles = { container: { display: 'flex', marginTop: 20, }, avatar: { width: 44, height: 44, marginRight: 5, borderRadius: 22, }, messageContainer: { flex: 'auto', }, arrow: { border: '7px solid transparent', borderRightColor: 'white', alignSelf: 'flex-start', marginTop: 7, }, message: { display: 'inline-block', padding: 10, backgroundColor: 'white', borderRadius: 4, alignSelf: 'center', fontSize: 16, color: '#555', wordWrap: 'break-word', overflow: 'hidden', }, timestamp: { paddingLeft: 61, fontSize: 12, color: '#999', }, highlight: { backgroundColor: '#ffff91', }, highlightArrow: { borderRightColor: '#ffff91', }, messageButton: { border: 0, background: 'none', marginLeft: 10, opacity: 0.4, fontSize: 16, borderWidth: 1, borderStyle: 'dotted', width: 26, height: 26, borderRadius: 13, }, messageButtonEdit: {} };
node_modules/react-bootstrap/es/MediaList.js
Chen-Hailin/iTCM.github.io
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var MediaList = function (_React$Component) { _inherits(MediaList, _React$Component); function MediaList() { _classCallCheck(this, MediaList); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaList.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('ul', _extends({}, elementProps, { className: classNames(className, classes) })); }; return MediaList; }(React.Component); export default bsClass('media-list', MediaList);
src/svg-icons/av/snooze.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSnooze = (props) => ( <SvgIcon {...props}> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-3-9h3.63L9 15.2V17h6v-2h-3.63L15 10.8V9H9v2z"/> </SvgIcon> ); AvSnooze = pure(AvSnooze); AvSnooze.displayName = 'AvSnooze'; AvSnooze.muiName = 'SvgIcon'; export default AvSnooze;
src/client/components/Html.js
BhumiSukhadiya/React_Project_Repo
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import serialize from 'serialize-javascript'; class Html extends React.Component { static propTypes = { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, styles: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string.isRequired, cssText: PropTypes.string.isRequired, }).isRequired), scripts: PropTypes.arrayOf(PropTypes.string.isRequired), // eslint-disable-next-line react/forbid-prop-types state: PropTypes.object, children: PropTypes.string.isRequired, }; static defaultProps = { styles: [], scripts: [], state: null, }; render() { const { title, description, styles, scripts, state, children } = this.props; return ( <html className="no-js" lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <title>{title}</title> <meta name="description" content={description} /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="apple-touch-icon" href="apple-touch-icon.png" /> <link rel="stylesheet" href="app.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/> {styles.map(style => <style key={style.id} id={style.id} // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: style.cssText }} />, )} </head> <body> <div id="app" // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: children }} /> {state && ( <script // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: `window.APP_STATE=${serialize(state, { isJSON: true })}` }} /> )} {scripts.map(script => <script key={script} src={script} />)} </body> </html> ); } } export default Html;
reflux-app/components/Status/PassiveStatus.js
Orientsoft/conalog-front
import React from 'react' import { FormattedMessage } from 'react-intl'; let message = require('antd/lib/message') let TimePicker = require('antd/lib/time-picker') let Switch = require('antd/lib/switch') let Tag = require('antd/lib/tag') let Modal = require('antd/lib/modal') let Icon = require('antd/lib/icon') import AppActions from '../../actions/AppActions' import AppStore from '../../stores/AppStore' import constants from '../../const' import _ from 'lodash' class PassiveStatus extends React.Component { constructor(props) { super(props) this.state = { passiveStatusList: [], passiveStatusListAll:[], messageModal:false, messageContent:'', passiveStatus:[] } } componentDidMount() { this.unsubscribe = AppStore.listen(function(state) { this.setState(state) }.bind(this)) AppActions.getPassiveStatusList() // start to get passive collector list in loop this.loop = setInterval(function() { AppActions.getPassiveStatusList() }, constants.STATUS_REFRESH_INTERVAL) } componentWillUnmount() { // stop list loop clearInterval(this.loop) if (_.isFunction(this.unsubscribe)) this.unsubscribe(); } setPassiveSwitch(switcher) { let id = this["data-id"] // console.log('setPassiveSwitch', {id: id, switch: switcher, category: 'passive'}) AppActions.setCollectorSwitch({id: id, switch: switcher, category: 'passive'}) } showAllStatus(index, e){ let id = e.target.getAttribute("data-id") this.setState({ messageModal:true, messageContent:this.state.passiveStatusListAll[index].status.lastActivity.data }) } showPartStatus(index, e){ this.setState({ messageModal:false }) } render() { // render status list let createPassiveStatus = (line, index) => { // line = { _id, name, ts, type, trigger, cmd, param, host, status } // status = { runningFlag, lastActivity } // lastActivity = { ts, success[, stdout, stderr] } let passiveStatus // console.log('PassiveStatus::render', line.status) let date = new Date(line.ts) date = date.toLocaleString() let idx = _.indexOf(this.state.passiveStatusChecklist, line._id) // console.log('createPassiveStatus', this.state.passiveStatusChecklist, line._id, idx) let triggerDate = new Date(parseInt(line.trigger)) // create status columns let lastActivityTs let lastActivityMsg let execCount let operation if (line.status.runningFlag) { execCount = line.status.lastActivity.execCounter lastActivityTs = new Date(parseInt(line.status.lastActivity.ts)).toLocaleString() switch (line.status.lastActivity.status) { case 'Success': if(line.status.lastActivity.data){ lastActivityMsg = <td> <Tag color="green"> stdout </Tag><Tag onClick={this.showAllStatus.bind(this, index)} color="green"> + </Tag> { line.status.lastActivity.data.toString() } </td> }else if (line.status.lastActivity.stderr){ lastActivityMsg = <td> <Tag color="red"> stderr </Tag> { line.status.lastActivity.stderr.toString() } </td> } break case 'Error': if(line.status.lastActivity.data){ lastActivityMsg = <td> <Tag color="red"> stderr </Tag><Tag onClick={this.showAllStatus.bind(this, index)} color="red"> + </Tag> { line.status.lastActivity.data.toString() } </td> } break default: lastActivityMsg = <td> <Tag color="yellow"> Pending </Tag> </td> break } operation = <Switch data-id={line._id} data-switch={false} defaultChecked={true} onChange={this.setPassiveSwitch} size="small" /> } else { execCount = 0 lastActivityTs = 'N/A' lastActivityMsg = <td> <Tag color="yellow"> N/A </Tag> </td> operation = <Switch data-id={line._id} data-switch={true} defaultChecked={false} onChange={this.setPassiveSwitch} size="small" /> } if (idx == -1) passiveStatus = <tr key={ index }> <td>{ line.name }</td> <td>{ date }</td> <td>{ line.type }</td> <td>{ (line.cmd == '') ? 'N/A' : line.cmd }</td> <td>{ line.param }</td> <td>{ line.host }</td> <td>{ execCount }</td> <td>{ lastActivityTs }</td> { lastActivityMsg } <td>{ operation }</td> </tr> else passiveStatus = <tr key={ index }> <td>{ line.name }</td> <td>{ date }</td> <td>{ line.type }</td> <td>{ (line.cmd == '') ? 'N/A' : line.cmd }</td> <td>{ line.param }</td> <td>{ line.host }</td> <td>{ execCount }</td> <td>{ lastActivityTs }</td> { lastActivityMsg } <td>{ operation }</td> </tr> return passiveStatus } let passiveStatusTable = this.state.passiveStatusList.map(createPassiveStatus.bind(this)) return ( <div> <Modal title = "Last Activity Message" visible = {this.state.messageModal} onOk = {this.showPartStatus.bind(this)} onCancel = {this.showPartStatus.bind(this)} footer = {null} className = 'statusModal' > {this.state.messageContent} </Modal> <div className=" p-b-10 p-t-10"> <table id="demo-custom-toolbar" data-toggle="table" data-toolbar="#demo-delete-row" data-search="true" data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-sort-name="id" data-page-list="[5, 10, 20]" data-page-size="5" data-pagination="true" data-show-pagination-switch="true" className="table table-bordered table-hover"> <thead> <tr> <th data-field="name" data-sortable="true"><FormattedMessage id="name"/></th> <th data-field="date" data-sortable="true" data-formatter="dateFormatter"><FormattedMessage id="date"/></th> <th data-field="amount" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="types"/></th> <th data-field="cmd" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="command"/></th> <th data-field="parameter" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="para"/></th> <th data-field="host" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="host"/></th> <th data-field="execCount" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="execCount"/></th> <th data-field="lastTs" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="lastActivityTime"/></th> <th data-field="lastMsg" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="lastActivityMessage"/></th> <th data-field="operation" data-align="center" data-sortable="true" data-sorter=""><FormattedMessage id="operation"/></th> </tr> </thead> <tbody> { passiveStatusTable } </tbody> </table> </div> </div> ) } } PassiveStatus.propTypes = { } PassiveStatus.defaultProps = { } export default PassiveStatus
src/modals/AddContact.js
galaxyfeeder/sschat-client
import React from 'react'; import ReactModal from 'react-modal'; class AddContact extends React.Component { constructor (props){ super(props); this.handleClose = this.handleClose.bind(this); this.handleCancel = this.handleCancel.bind(this); this.handleFileChange = this.handleFileChange.bind(this); this.handleTextChange = this.handleTextChange.bind(this); this.handleNameChange = this.handleNameChange.bind(this); this.state = { pub_key: undefined, name: undefined } } handleClose (e){ this.setState({pub_key: '', name: ''}); this.props.handleAddContact(this.state.pub_key, this.state.name); } handleCancel (e){ this.setState({pub_key: '', name: ''}); this.props.handleAddContact(undefined, undefined); } handleFileChange (e){ const fileToRead = e.target.files[0]; let reader = new FileReader(); reader.readAsBinaryString(fileToRead); reader.onload = (event) => { this.setState({pub_key: event.target.result}); }; reader.onerror = (event) => {}; } handleTextChange (e){ this.setState({pub_key: e.target.value}); } handleNameChange (e){ this.setState({name: e.target.value}); } render (){ return ( <ReactModal isOpen={this.props.showModal} contentLabel="Add new contact" style={{ content: { width: '35%', height: '50%', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' } }}> <h2>Add new contact</h2> <div className="form-group"> <label>Contact name</label> <input className="form-control" type="text" onChange={this.handleNameChange} value={this.state.name} /> </div> <div className="form-group"> <label>Public key (text or file)</label> <textarea className="form-control" onChange={this.handleTextChange} value={this.state.pub_key} rows={9}/> </div> <div className="form-group"> <input type="file" onChange={this.handleFileChange} /> </div> <button className="btn btn-success" onClick={this.handleClose}>Add this contact</button> <button className="btn btn-primary" onClick={this.handleCancel}>Cancel</button> </ReactModal> ); } } export default AddContact;
src/svg-icons/device/battery-90.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery90 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z"/><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z"/> </SvgIcon> ); DeviceBattery90 = pure(DeviceBattery90); DeviceBattery90.displayName = 'DeviceBattery90'; DeviceBattery90.muiName = 'SvgIcon'; export default DeviceBattery90;
bench/pages/stateless-big.js
dizlexik/next.js
import React from 'react' export default () => { return ( <ul> {items()} </ul> ) } const items = () => { var out = new Array(10000) for (let i = 0; i < out.length; i++) { out[i] = <li key={i}>This is row {i + 1}</li> } return out }
src/svg-icons/content/unarchive.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentUnarchive = (props) => ( <SvgIcon {...props}> <path d="M20.55 5.22l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.15.55L3.46 5.22C3.17 5.57 3 6.01 3 6.5V19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.49-.17-.93-.45-1.28zM12 9.5l5.5 5.5H14v2h-4v-2H6.5L12 9.5zM5.12 5l.82-1h12l.93 1H5.12z"/> </SvgIcon> ); ContentUnarchive = pure(ContentUnarchive); ContentUnarchive.displayName = 'ContentUnarchive'; ContentUnarchive.muiName = 'SvgIcon'; export default ContentUnarchive;
packages/react-error-overlay/src/containers/StackFrameCodeBlock.js
peopleticker/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React from 'react'; import CodeBlock from '../components/CodeBlock'; import { applyStyles } from '../utils/dom/css'; import { absolutifyCaret } from '../utils/dom/absolutifyCaret'; import type { ScriptLine } from '../utils/stack-frame'; import { primaryErrorStyle, secondaryErrorStyle } from '../styles'; import generateAnsiHTML from '../utils/generateAnsiHTML'; import codeFrame from 'babel-code-frame'; type StackFrameCodeBlockPropsType = {| lines: ScriptLine[], lineNum: number, columnNum: ?number, contextSize: number, main: boolean, |}; // Exact type workaround for spread operator. // See: https://github.com/facebook/flow/issues/2405 type Exact<T> = $Shape<T>; function StackFrameCodeBlock(props: Exact<StackFrameCodeBlockPropsType>) { const { lines, lineNum, columnNum, contextSize, main } = props; const sourceCode = []; let whiteSpace = Infinity; lines.forEach(function(e) { const { content: text } = e; const m = text.match(/^\s*/); if (text === '') { return; } if (m && m[0]) { whiteSpace = Math.min(whiteSpace, m[0].length); } else { whiteSpace = 0; } }); lines.forEach(function(e) { let { content: text } = e; const { lineNumber: line } = e; if (isFinite(whiteSpace)) { text = text.substring(whiteSpace); } sourceCode[line - 1] = text; }); const ansiHighlight = codeFrame( sourceCode.join('\n'), lineNum, columnNum == null ? 0 : columnNum - (isFinite(whiteSpace) ? whiteSpace : 0), { forceColor: true, linesAbove: contextSize, linesBelow: contextSize, } ); const htmlHighlight = generateAnsiHTML(ansiHighlight); const code = document.createElement('code'); code.innerHTML = htmlHighlight; absolutifyCaret(code); const ccn = code.childNodes; // eslint-disable-next-line oLoop: for (let index = 0; index < ccn.length; ++index) { const node = ccn[index]; const ccn2 = node.childNodes; for (let index2 = 0; index2 < ccn2.length; ++index2) { const lineNode = ccn2[index2]; const text = lineNode.innerText; if (text == null) { continue; } if (text.indexOf(' ' + lineNum + ' |') === -1) { continue; } // $FlowFixMe applyStyles(node, main ? primaryErrorStyle : secondaryErrorStyle); // eslint-disable-next-line break oLoop; } } return <CodeBlock main={main} codeHTML={code.innerHTML} />; } export default StackFrameCodeBlock;
app/javascript/flavours/glitch/features/favourited_statuses/index.js
glitch-soc/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import { fetchFavouritedStatuses, expandFavouritedStatuses } from 'flavours/glitch/actions/favourites'; import Column from 'flavours/glitch/features/ui/components/column'; import ColumnHeader from 'flavours/glitch/components/column_header'; import { addColumn, removeColumn, moveColumn } from 'flavours/glitch/actions/columns'; import StatusList from 'flavours/glitch/components/status_list'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ heading: { id: 'column.favourites', defaultMessage: 'Favourites' }, }); const mapStateToProps = state => ({ statusIds: state.getIn(['status_lists', 'favourites', 'items']), isLoading: state.getIn(['status_lists', 'favourites', 'isLoading'], true), hasMore: !!state.getIn(['status_lists', 'favourites', 'next']), }); export default @connect(mapStateToProps) @injectIntl class Favourites extends ImmutablePureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, statusIds: ImmutablePropTypes.list.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasMore: PropTypes.bool, isLoading: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchFavouritedStatuses()); } handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('FAVOURITES', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } handleLoadMore = debounce(() => { this.props.dispatch(expandFavouritedStatuses()); }, 300, { leading: true }) render () { const { intl, statusIds, columnId, multiColumn, hasMore, isLoading } = this.props; const pinned = !!columnId; const emptyMessage = <FormattedMessage id='empty_column.favourited_statuses' defaultMessage="You don't have any favourite posts yet. When you favourite one, it will show up here." />; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} name='favourites' label={intl.formatMessage(messages.heading)}> <ColumnHeader icon='star' title={intl.formatMessage(messages.heading)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} showBackButton /> <StatusList trackScroll={!pinned} statusIds={statusIds} scrollKey={`favourited_statuses-${columnId}`} hasMore={hasMore} isLoading={isLoading} onLoadMore={this.handleLoadMore} emptyMessage={emptyMessage} bindToDocument={!multiColumn} /> </Column> ); } }
src/index.js
td-ui/td-ui.github.io
/** * @Author: Zhengfeng.Yao <yzf> * @Date: 2017-06-08 15:14:16 * @Last modified by: yzf * @Last modified time: 2017-06-08 15:14:19 */ import React from 'react'; import ReactDOM from 'react-dom'; import { Router, match, useRouterHistory } from 'react-router'; import { createHistory } from 'history'; import { createElement, getRoutes } from './utils'; import docs from './d.DOCS'; const { pathname, search, hash } = window.location; const location = `${pathname}${search}${hash}`; const routes = getRoutes(docs); const basename = '/'; match({ routes, location, basename }, () => { const router = (<Router history={useRouterHistory(createHistory)({ basename })} routes={routes} createElement={createElement} />); ReactDOM.render( router, document.getElementById('app') ); }); window.docs = docs;
app/javascript/mastodon/features/account_timeline/components/header.js
pfm-eyesightjp/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import InnerHeader from '../../account/components/header'; import ActionBar from '../../account/components/action_bar'; import MissingIndicator from '../../../components/missing_indicator'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class Header extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map, me: PropTypes.number.isRequired, onFollow: PropTypes.func.isRequired, onBlock: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, onReport: PropTypes.func.isRequired, onMute: PropTypes.func.isRequired, onBlockDomain: PropTypes.func.isRequired, onUnblockDomain: PropTypes.func.isRequired, }; static contextTypes = { router: PropTypes.object, }; handleFollow = () => { this.props.onFollow(this.props.account); } handleBlock = () => { this.props.onBlock(this.props.account); } handleMention = () => { this.props.onMention(this.props.account, this.context.router.history); } handleReport = () => { this.props.onReport(this.props.account); } handleMute = () => { this.props.onMute(this.props.account); } handleBlockDomain = () => { const domain = this.props.account.get('acct').split('@')[1]; if (!domain) return; this.props.onBlockDomain(domain, this.props.account.get('id')); } handleUnblockDomain = () => { const domain = this.props.account.get('acct').split('@')[1]; if (!domain) return; this.props.onUnblockDomain(domain, this.props.account.get('id')); } render () { const { account, me } = this.props; if (account === null) { return <MissingIndicator />; } return ( <div className='account-timeline__header'> <InnerHeader account={account} me={me} onFollow={this.handleFollow} /> <ActionBar account={account} me={me} onBlock={this.handleBlock} onMention={this.handleMention} onReport={this.handleReport} onMute={this.handleMute} onBlockDomain={this.handleBlockDomain} onUnblockDomain={this.handleUnblockDomain} /> </div> ); } }
envkey-react/src/components/env_manager/env_cell/traits/flashable_cell.js
envkey/envkey-app
import React from 'react' import h from "lib/ui/hyperscript_with_helpers" import Flashable from 'components/shared/traits/flashable' const FlashableCell = Cell => class extends Flashable(Cell) { _renderCellContents(){ return super._renderCellContents().concat([ this._renderFlash() ]) } } export default FlashableCell
src/example/FluxOnly/FluxOnly.js
halhenke/component-router
import React from 'react'; import {Store, Url, Actions} from '../..'; import styles from './FluxOnly.css'; const Switch = React.createClass({ getInitialState() { return Store.getQuery(); }, componentDidMount() { this.unsubscribe = Store.subscribe(this.onChange); }, componentWillUnmount() { this.unsubscribe(); }, switchComponents() { let query = 'Nothing'; if ('switchBlock' in this.state) { query = this.state.switchBlock; } return query; }, onChange() { this.setState(Store.getQuery()); }, render() { return ( <div className={styles.content}> <p>Current state is: {this.switchComponents()} Clicked</p> </div> ); } }); const FluxWithUrls = React.createClass({ render() { return ( <div className={styles.fluxonly}> <div> <h2>Using component-router Urls</h2> </div> <div> <Url query={{switchBlock: 'First'}}> Render First Component </Url> <Url query={{switchBlock: 'Second'}}> Render Second Component </Url> <Switch /> </div> </div> ); } }); const PureFlux = React.createClass({ getInitialState() { return Store.getQuery(); }, componentDidMount() { this.unsubscribe = Store.subscribe(this.onChange); }, componentWillUnmount() { this.unsubscribe(); }, onChange() { this.setState(Store.getQuery()); }, onClick(newVal) { return event => { event.preventDefault(); Store.dispatch(Actions.navigateTo({pathname: '/', query: newVal})); }; }, activeClass({switchBlock: val}) { let cName = ''; if (this.state.switchBlock === val) { cName = 'active'; } return cName; }, render() { const first = {switchBlock: 'First'}; const second = {switchBlock: 'Second'}; return ( <div className={styles.fluxonly}> <div> <h2>Using only anchor elements</h2> </div> <div> <button className={this.activeClass(first)} onClick={this.onClick(first)}> Render First Component </button> <button className={this.activeClass(second)} onClick={this.onClick(second)}> Render Second Component </button> <Switch /> </div> </div> ); } }); const CompoundFlux = React.createClass({ componentWillUnmount() { Store.dispatch(Actions.removeParam({namespace: 'switchBlock'})); }, render() { return ( <div> <h1>Switch Components by subscribing directly to the Flux Store</h1> <div> <FluxWithUrls /> </div> <div className={styles.container}> <PureFlux /> </div> </div> ); } }); export default CompoundFlux;
app/javascript/flavours/glitch/util/react_router_helpers.js
Kirishima21/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { Switch, Route } from 'react-router-dom'; import ColumnLoading from 'flavours/glitch/features/ui/components/column_loading'; import BundleColumnError from 'flavours/glitch/features/ui/components/bundle_column_error'; import BundleContainer from 'flavours/glitch/features/ui/containers/bundle_container'; // Small wrapper to pass multiColumn to the route components export class WrappedSwitch extends React.PureComponent { render () { const { multiColumn, children } = this.props; return ( <Switch> {React.Children.map(children, child => React.cloneElement(child, { multiColumn }))} </Switch> ); } } WrappedSwitch.propTypes = { multiColumn: PropTypes.bool, children: PropTypes.node, }; // Small Wraper to extract the params from the route and pass // them to the rendered component, together with the content to // be rendered inside (the children) export class WrappedRoute extends React.Component { static propTypes = { component: PropTypes.func.isRequired, content: PropTypes.node, multiColumn: PropTypes.bool, componentParams: PropTypes.object, } static defaultProps = { componentParams: {}, }; renderComponent = ({ match }) => { const { component, content, multiColumn, componentParams } = this.props; return ( <BundleContainer fetchComponent={component} loading={this.renderLoading} error={this.renderError}> {Component => <Component params={match.params} multiColumn={multiColumn} {...componentParams}>{content}</Component>} </BundleContainer> ); } renderLoading = () => { return <ColumnLoading />; } renderError = (props) => { return <BundleColumnError {...props} />; } render () { const { component: Component, content, ...rest } = this.props; return <Route {...rest} render={this.renderComponent} />; } }
src/packages/@ncigdc/modern_components/CancerDistributionBarChart/CancerDistributionBarChart.js
NCI-GDC/portal-ui
// @flow import React from 'react'; import { compose, withState } from 'recompose'; import { sortBy, sum, get } from 'lodash'; import withRouter from '@ncigdc/utils/withRouter'; import { Row, Column } from '@ncigdc/uikit/Flex'; import DownloadVisualizationButton from '@ncigdc/components/DownloadVisualizationButton'; import { withTheme } from '@ncigdc/theme'; import BarChart from '@ncigdc/components/Charts/BarChart'; import FilteredStackedBarChart from '@ncigdc/components/Charts/FilteredStackedBarChart'; import wrapSvg from '@ncigdc/utils/wrapSvg'; import ExploreLink from '@ncigdc/components/Links/ExploreLink'; import ProjectsLink from '@ncigdc/components/Links/ProjectsLink'; import { IGroupFilter } from '@ncigdc/utils/filters/types'; import { cnvColors } from '@ncigdc/utils/filters/prepared/significantConsequences'; import { renderToString } from 'react-dom/server'; import { makeFilter, replaceFilters } from '@ncigdc/utils/filters'; import ExploreSSMLink from '@ncigdc/components/Links/ExploreSSMLink'; type TProps = { style: Object, filters: ?IGroupFilter, cases: { total: { project__project_id: { buckets: Array<{ key: string, doc_count: number, }>, }, }, filtered: { project__project_id: { buckets: Array<{ key: string, doc_count: number, }>, }, }, }, ssms: { hits: { total: number, }, }, aggregations: Object, theme: Object, push: Function, ChartTitle: ReactClass<{}>, }; const CHART_HEIGHT = 295; const CHART_MARGINS = { bottom: 75, left: 55, right: 50, top: 20, }; export type TChartTitleProps = { cases: number, projects: Array<{ project_id: string }>, ssms: number, filters: any, }; const DefaultChartTitle = ({ type = 'mutations', cases = 0, projects = [], ssms = 0, filters, }: TChartTitleProps) => { return ( <div style={{ textTransform: 'uppercase', padding: '0 2rem', }} > {type === 'cnvs' ? ( <span> <ExploreLink query={{ searchTableTab: 'cases', filters, }} > {cases.toLocaleString()} </ExploreLink> {' '} cases affected by {' '} {ssms.toLocaleString()} {' '} cnv events across {' '} </span> ) : ( <span> <ExploreSSMLink filters={filters} searchTableTab="cases"> {cases.toLocaleString()} </ExploreSSMLink> {' '} cases affected by {' '} <ExploreSSMLink filters={filters} searchTableTab="mutations"> {ssms.toLocaleString()} </ExploreSSMLink> {' '} mutations across {' '} </span> )} <ProjectsLink query={{ filters: { op: 'and', content: [ { op: 'in', content: { field: 'projects.project_id', value: projects.map(p => p.project_id), }, }, ], }, }} > {projects.length.toLocaleString()} </ProjectsLink> &nbsp; projects </div> ); }; const initalCnv = { gain: true, // amplification: true, loss: true, // shallow_loss: true, // deep_loss: true, }; export default compose( withRouter, withTheme, withState('cnv', 'setCnv', initalCnv), withState('collapsed', 'setCollapsed', false), )( ( { viewer: { explore: { cases, ssms } }, theme, push, ChartTitle = DefaultChartTitle, filters, chartType, cnv, setCnv, type, }: TProps = {}, ) => { let cnvFiltered = {}; let cnvCancerDistData = []; let cnvChartData = []; const cnvColumns = ['gain', 'loss']; // ['amplification', 'gain', 'shallowLoss', 'deepLoss']; if (chartType !== 'ssm') { cnvColumns.map(cnvType => cases[cnvType].project__project_id.buckets.map( b => (cnvFiltered = { ...cnvFiltered, [b.key]: { ...cnvFiltered[b.key], [cnvType]: b.doc_count, }, }), ),); cnvCancerDistData = Object.keys(cnvFiltered).map(p => { return { // deep_loss: cnvFiltered[p]['deepLoss'] || 0, loss: cnvFiltered[p].loss || 0, // shallowLoss gain: cnvFiltered[p].gain || 0, // amplification: cnvFiltered[p]['amplification'] || 0, project_id: p, num_cases_total: cases.cnvTotal.project__project_id.buckets.filter( f => f.key === p, )[0].doc_count, }; }); cnvChartData = sortBy( cnvCancerDistData, d => -cnvColors.reduce( (acc, f) => acc + d[f.key] / d.num_cases_total * cnv[f.key], 0, ), ) .slice(0, 20) .map(d => ({ symbol: d.project_id, // deep_loss: d.deep_loss / d.num_cases_total * 100, loss: d.loss / d.num_cases_total * 100, // shallow_loss: d.shallow_loss gain: d.gain / d.num_cases_total * 100, // amplification: d.amplification / d.num_cases_total * 100, total: d.num_cases_total, onClick: () => push(`/projects/${d.project_id}`), tooltips: cnvColors.reduce( (acc, f) => ({ ...acc, [f.key]: ( <span> {d[f.key].toLocaleString()} &nbsp;Case {d[f.key] > 1 ? 's ' : ' '} Affected in {' '} <b>{d.project_id}</b> <br /> {d[f.key].toLocaleString()} &nbsp;/&nbsp; {d.num_cases_total.toLocaleString()} &nbsp; ( {(d[f.key] / d.num_cases_total * 100).toFixed(2)} %) </span> ), }), 0, ), })); } const chartStyles = { xAxis: { stroke: theme.greyScale4, textFill: theme.greyScale3, }, yAxis: { stroke: theme.greyScale4, textFill: theme.greyScale3, }, bars: { fill: theme.secondary }, tooltips: { fill: '#fff', stroke: theme.greyScale4, textFill: theme.greyScale3, }, }; const mutationCancerDistData = (cases.filtered || { project__project_id: { buckets: [] }, }).project__project_id.buckets.map(b => { const casesByProjects = cases.total.project__project_id.buckets.filter( f => f.key === b.key, ); const totalCasesByProject = casesByProjects.length > 0 ? casesByProjects[0].doc_count : 0; return { freq: b.doc_count / totalCasesByProject, project_id: b.key, num_affected_cases: b.doc_count, num_cases_total: totalCasesByProject, }; }); const mutationChartData = sortBy(mutationCancerDistData, d => -d.freq) .slice(0, 20) .map(d => ({ label: d.project_id, value: d.freq * 100, onClick: () => push(`/projects/${d.project_id}`), tooltip: ( <span> {d.num_affected_cases.toLocaleString()} &nbsp;Case {d.num_affected_cases > 1 ? 's ' : ' '} Affected in {' '} <b>{d.project_id}</b> <br /> {d.num_affected_cases.toLocaleString()} &nbsp;/&nbsp; {d.num_cases_total.toLocaleString()} &nbsp; ( {(d.freq * 100).toFixed(2)} %) </span> ), })); const Legends = () => ( <Row style={{ display: 'flex', justifyContent: 'center', }} > {cnvColors.map(f => ( <label key={f.key} style={{ paddingRight: '10px' }}> <span onClick={() => setCnv({ ...cnv, [f.key]: !cnv[f.key], })} style={{ color: f.color, textAlign: 'center', border: '2px solid', height: '18px', width: '18px', cursor: 'pointer', display: 'inline-block', marginRight: '6px', marginTop: '3px', verticalAlign: 'middle', lineHeight: '16px', }} > {cnv[f.key] ? '✓' : <span>&nbsp;</span>} </span> {f.name} </label> ))} </Row> ); return ( <div> <Row style={{ width: '100%' }}> {mutationChartData.length >= 5 && ( <span style={{ width: chartType !== 'ssm' ? '50%' : '100%' }}> <Column style={{ padding: '0 0 0 2rem' }}> <Row style={{ justifyContent: 'space-between', alignItems: 'center', }} > <ChartTitle cases={sum( mutationCancerDistData.map(d => d.num_affected_cases), )} filters={filters} projects={mutationCancerDistData} ssms={get(ssms, 'hits.total', 0)} /> <DownloadVisualizationButton data={mutationChartData.map(d => ({ label: d.label, value: d.value, }))} noText slug="cancer-distribution-bar-chart" style={{ marginRight: '2rem' }} svg={() => wrapSvg({ selector: '#cancer-distribution svg', title: 'Cancer Distribution', })} tooltipHTML="Download image or data" /> </Row> <BarChart data={mutationChartData} height={CHART_HEIGHT} margin={CHART_MARGINS} styles={chartStyles} yAxis={{ title: '% of Cases Affected' }} /> </Column> </span> )} {chartType !== 'ssm' && cnvChartData.length >= 5 && ( <span style={{ width: '50%' }}> <Column style={{ padding: '0 0 0 2rem' }}> <Row style={{ justifyContent: 'space-between', alignItems: 'center', }} > <ChartTitle cases={cases.cnvTestedByGene.total} filters={replaceFilters( makeFilter([ { field: 'cases.available_variation_data', value: 'cnv', }, ]), filters, )} projects={cnvCancerDistData} ssms={cases.cnvAll.total} type="cnvs" /> <DownloadVisualizationButton data={cnvChartData.map(d => ({ symbol: d.symbol, // amplification: d.amplification, gain: d.gain, loss: d.loss, // shallow_loss: d.shallow_loss // deep_loss: d.deep_loss, total: d.total, }))} noText slug="cancer-distribution-bar-chart" style={{ marginRight: '2rem' }} svg={() => wrapSvg({ selector: '.test-stacked-bar-chart svg', title: 'CNV Distribution', legends: renderToString(<Legends />), })} tooltipHTML="Download image or data" /> </Row> <Column> <FilteredStackedBarChart colors={cnvColors.reduce( (acc, f) => ({ ...acc, [f.key]: f.color, }), 0, )} data={cnvChartData} displayFilters={cnv} height={200} margin={CHART_MARGINS} styles={chartStyles} yAxis={{ title: '% of Cases Affected' }} /> <Legends /> </Column> </Column> </span> )} </Row> </div> ); }, );
src/main/resources/public/js/components/CSVReader.js
SICTIAM/ozwillo-portal
import React from 'react'; import PropTypes from 'prop-types'; import Tools from "../util/tools"; import { i18n } from "../config/i18n-config" export default class CSVReader extends React.Component { constructor() { super(); this._tools = new Tools(); } state = { error: null, fileName: "" }; componentDidMount(){ this.props.fileName ? this.setState({fileName: this.props.fileName}) : null; } cleanInput = () => { this.inputFile.value = ""; this.setState({fileName: ""}); }; _sanitizeEmailArray = (emailArray) => { return emailArray.filter(email => this._tools.checkEmail(email)); }; _parseCSVData = (value) => { let resultArray = value.trim().split(/[\r\n]+/g); resultArray.filter(elm => elm !== ""); resultArray = this._sanitizeEmailArray(resultArray); this.props.onFileRead(resultArray); }; _extractData = (e) => { let reader = new FileReader(); let files = e.target.files; //check if that is a real csv try { if (files && files.length > 0 && files[0].name.match('.csv')) { this._extractFileName(); this.props.onFileReading(); reader.onload = () => { this._parseCSVData(reader.result) }; reader.readAsText(files[0]); this.setState({error: null}) } else if(files && files.length > 0) { this.setState({error: i18n._('error.msg.csv-file-required')}); this.cleanInput(); } } catch (e) { this.cleanInput(); this.setState({error: e}); } }; _extractFileName = () => { const fileName = this.inputFile.value.split(/.*[\/|\\]/).pop(); this.setState({fileName: fileName}) return fileName; }; render() { const {error, fileName} = this.state; const {requiered} = this.props; return ( <div className={"csv-reader"}> <label className="label btn btn-default" htmlFor="fileSelect"> {i18n._("organization.desc.choose-file")} </label> <p> {fileName} </p> <input ref={inputFile => this.inputFile = inputFile} className={"field"} required={requiered} id="fileSelect" type="file" accept=".csv" onChange={this._extractData}/> {error && <div className={"csv-error"}>{error}</div>} </div> ) } } CSVReader.propTypes = { onFileRead: PropTypes.func, onFileReading: PropTypes.func, fileName: PropTypes.string, };
example/examples/AnimatedViews.js
ksincennes/react-native-maps
import React from 'react'; import { StyleSheet, View, Dimensions, Animated, } from 'react-native'; import MapView from 'react-native-maps'; import PanController from './PanController'; import PriceMarker from './AnimatedPriceMarker'; const screen = Dimensions.get('window'); const ASPECT_RATIO = screen.width / screen.height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; const ITEM_SPACING = 10; const ITEM_PREVIEW = 10; const ITEM_WIDTH = screen.width - (2 * ITEM_SPACING) - (2 * ITEM_PREVIEW); const SNAP_WIDTH = ITEM_WIDTH + ITEM_SPACING; const ITEM_PREVIEW_HEIGHT = 150; const SCALE_END = screen.width / ITEM_WIDTH; const BREAKPOINT1 = 246; const BREAKPOINT2 = 350; const ONE = new Animated.Value(1); function getMarkerState(panX, panY, scrollY, i) { const xLeft = (-SNAP_WIDTH * i) + (SNAP_WIDTH / 2); const xRight = (-SNAP_WIDTH * i) - (SNAP_WIDTH / 2); const xPos = -SNAP_WIDTH * i; const isIndex = panX.interpolate({ inputRange: [xRight - 1, xRight, xLeft, xLeft + 1], outputRange: [0, 1, 1, 0], extrapolate: 'clamp', }); const isNotIndex = panX.interpolate({ inputRange: [xRight - 1, xRight, xLeft, xLeft + 1], outputRange: [1, 0, 0, 1], extrapolate: 'clamp', }); const center = panX.interpolate({ inputRange: [xPos - 10, xPos, xPos + 10], outputRange: [0, 1, 0], extrapolate: 'clamp', }); const selected = panX.interpolate({ inputRange: [xRight, xPos, xLeft], outputRange: [0, 1, 0], extrapolate: 'clamp', }); const translateY = Animated.multiply(isIndex, panY); const translateX = panX; const anim = Animated.multiply(isIndex, scrollY.interpolate({ inputRange: [0, BREAKPOINT1], outputRange: [0, 1], extrapolate: 'clamp', })); const scale = Animated.add(ONE, Animated.multiply(isIndex, scrollY.interpolate({ inputRange: [BREAKPOINT1, BREAKPOINT2], outputRange: [0, SCALE_END - 1], extrapolate: 'clamp', }))); // [0 => 1] let opacity = scrollY.interpolate({ inputRange: [BREAKPOINT1, BREAKPOINT2], outputRange: [0, 1], extrapolate: 'clamp', }); // if i === index: [0 => 0] // if i !== index: [0 => 1] opacity = Animated.multiply(isNotIndex, opacity); // if i === index: [1 => 1] // if i !== index: [1 => 0] opacity = opacity.interpolate({ inputRange: [0, 1], outputRange: [1, 0], }); let markerOpacity = scrollY.interpolate({ inputRange: [0, BREAKPOINT1], outputRange: [0, 1], extrapolate: 'clamp', }); markerOpacity = Animated.multiply(isNotIndex, markerOpacity).interpolate({ inputRange: [0, 1], outputRange: [1, 0], }); const markerScale = selected.interpolate({ inputRange: [0, 1], outputRange: [1, 1.2], }); return { translateY, translateX, scale, opacity, anim, center, selected, markerOpacity, markerScale, }; } class AnimatedViews extends React.Component { constructor(props) { super(props); const panX = new Animated.Value(0); const panY = new Animated.Value(0); const scrollY = panY.interpolate({ inputRange: [-1, 1], outputRange: [1, -1], }); const scrollX = panX.interpolate({ inputRange: [-1, 1], outputRange: [1, -1], }); const scale = scrollY.interpolate({ inputRange: [0, BREAKPOINT1], outputRange: [1, 1.6], extrapolate: 'clamp', }); const translateY = scrollY.interpolate({ inputRange: [0, BREAKPOINT1], outputRange: [0, -100], extrapolate: 'clamp', }); const markers = [ { id: 0, amount: 99, coordinate: { latitude: LATITUDE, longitude: LONGITUDE, }, }, { id: 1, amount: 199, coordinate: { latitude: LATITUDE + 0.004, longitude: LONGITUDE - 0.004, }, }, { id: 2, amount: 285, coordinate: { latitude: LATITUDE - 0.004, longitude: LONGITUDE - 0.004, }, }, ]; const animations = markers.map((m, i) => getMarkerState(panX, panY, scrollY, i)); this.state = { panX, panY, animations, index: 0, canMoveHorizontal: true, scrollY, scrollX, scale, translateY, markers, region: new Animated.Region({ latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }), }; } componentDidMount() { const { region, panX, panY, scrollX, markers } = this.state; panX.addListener(this.onPanXChange); panY.addListener(this.onPanYChange); region.stopAnimation(); region.timing({ latitude: scrollX.interpolate({ inputRange: markers.map((m, i) => i * SNAP_WIDTH), outputRange: markers.map(m => m.coordinate.latitude), }), longitude: scrollX.interpolate({ inputRange: markers.map((m, i) => i * SNAP_WIDTH), outputRange: markers.map(m => m.coordinate.longitude), }), duration: 0, }).start(); } onStartShouldSetPanResponder(e) { // we only want to move the view if they are starting the gesture on top // of the view, so this calculates that and returns true if so. If we return // false, the gesture should get passed to the map view appropriately. const { panY } = this.state; const { pageY } = e.nativeEvent; const topOfMainWindow = ITEM_PREVIEW_HEIGHT + panY.__getValue(); const topOfTap = screen.height - pageY; return topOfTap < topOfMainWindow; } onMoveShouldSetPanResponder(e) { const { panY } = this.state; const { pageY } = e.nativeEvent; const topOfMainWindow = ITEM_PREVIEW_HEIGHT + panY.__getValue(); const topOfTap = screen.height - pageY; return topOfTap < topOfMainWindow; } onPanXChange({ value }) { const { index } = this.state; const newIndex = Math.floor(((-1 * value) + (SNAP_WIDTH / 2)) / SNAP_WIDTH); if (index !== newIndex) { this.setState({ index: newIndex }); } } onPanYChange({ value }) { const { canMoveHorizontal, region, scrollY, scrollX, markers, index } = this.state; const shouldBeMovable = Math.abs(value) < 2; if (shouldBeMovable !== canMoveHorizontal) { this.setState({ canMoveHorizontal: shouldBeMovable }); if (!shouldBeMovable) { const { coordinate } = markers[index]; region.stopAnimation(); region.timing({ latitude: scrollY.interpolate({ inputRange: [0, BREAKPOINT1], outputRange: [ coordinate.latitude, coordinate.latitude - (LATITUDE_DELTA * 0.5 * 0.375), ], extrapolate: 'clamp', }), latitudeDelta: scrollY.interpolate({ inputRange: [0, BREAKPOINT1], outputRange: [LATITUDE_DELTA, LATITUDE_DELTA * 0.5], extrapolate: 'clamp', }), longitudeDelta: scrollY.interpolate({ inputRange: [0, BREAKPOINT1], outputRange: [LONGITUDE_DELTA, LONGITUDE_DELTA * 0.5], extrapolate: 'clamp', }), duration: 0, }).start(); } else { region.stopAnimation(); region.timing({ latitude: scrollX.interpolate({ inputRange: markers.map((m, i) => i * SNAP_WIDTH), outputRange: markers.map(m => m.coordinate.latitude), }), longitude: scrollX.interpolate({ inputRange: markers.map((m, i) => i * SNAP_WIDTH), outputRange: markers.map(m => m.coordinate.longitude), }), duration: 0, }).start(); } } } onRegionChange(/* region */) { // this.state.region.setValue(region); } render() { const { panX, panY, animations, canMoveHorizontal, markers, region, } = this.state; return ( <View style={styles.container}> <PanController style={styles.container} vertical horizontal={canMoveHorizontal} xMode="snap" snapSpacingX={SNAP_WIDTH} yBounds={[-1 * screen.height, 0]} xBounds={[-screen.width * (markers.length - 1), 0]} panY={panY} panX={panX} onStartShouldSetPanResponder={this.onStartShouldSetPanResponder} onMoveShouldSetPanResponder={this.onMoveShouldSetPanResponder} > <MapView.Animated provider={this.props.provider} style={styles.map} region={region} onRegionChange={this.onRegionChange} > {markers.map((marker, i) => { const { selected, markerOpacity, markerScale, } = animations[i]; return ( <MapView.Marker key={marker.id} coordinate={marker.coordinate} > <PriceMarker style={{ opacity: markerOpacity, transform: [ { scale: markerScale }, ], }} amount={marker.amount} selected={selected} /> </MapView.Marker> ); })} </MapView.Animated> <View style={styles.itemContainer}> {markers.map((marker, i) => { const { translateY, translateX, scale, opacity, } = animations[i]; return ( <Animated.View key={marker.id} style={[styles.item, { opacity, transform: [ { translateY }, { translateX }, { scale }, ], }]} /> ); })} </View> </PanController> </View> ); } } AnimatedViews.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, }, itemContainer: { backgroundColor: 'transparent', flexDirection: 'row', paddingHorizontal: (ITEM_SPACING / 2) + ITEM_PREVIEW, position: 'absolute', // top: screen.height - ITEM_PREVIEW_HEIGHT - 64, paddingTop: screen.height - ITEM_PREVIEW_HEIGHT - 64, // paddingTop: !ANDROID ? 0 : screen.height - ITEM_PREVIEW_HEIGHT - 64, }, map: { backgroundColor: 'transparent', ...StyleSheet.absoluteFillObject, }, item: { width: ITEM_WIDTH, height: screen.height + (2 * ITEM_PREVIEW_HEIGHT), backgroundColor: 'red', marginHorizontal: ITEM_SPACING / 2, overflow: 'hidden', borderRadius: 3, borderColor: '#000', }, }); module.exports = AnimatedViews;
examples/web/client/src/components/RequestsQueue.js
jevakallio/redux-offline
import React from 'react'; import { connect } from 'react-redux'; function RequestsQueue({ actions }) { if (actions.length === 0) { return <p>There are no requests</p>; } return ( <ul> {actions.map(action => ( <li key={action.meta.transaction}> <span>{action.type}</span> <span>#{action.meta.transaction}</span> </li> ))} </ul> ); } function mapStateToProps(state) { return { actions: state.offline.outbox }; } const ConnectedComponent = connect(mapStateToProps)(RequestsQueue); export { RequestsQueue as RawComponent }; export default ConnectedComponent;
src/components/TimeAndSalary/common/DashBoardTable.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import R from 'ramda'; import Table from 'common/table/Table'; import { InfoButton } from 'common/Modal'; import styles from '../TimeAndSalaryBoard/TimeAndSalaryBoard.module.css'; import { getCompany, getJobTitle, getFrequency, getWeekWorkTime, getSalary, formatWage, formatDate, getAboutThisJobButton, } from './formatter'; const DashBoardTable = ({ data, postProcessRows, toggleInfoSalaryModal, toggleInfoTimeModal, toggleAboutThisJobModal, }) => ( <Table className={styles.latestTable} data={data} primaryKey="_id" postProcessRows={postProcessRows} > <Table.Column className={styles.colCompany} title="公司名稱" dataField={getCompany} > 公司名稱 </Table.Column> <Table.Column className={styles.colCompany} title="職稱" dataField={getJobTitle} > 職稱 <span className="table-sector">廠區/門市/分公司</span> </Table.Column> <Table.Column className={styles.colWeekTime} title="一週總工時" dataField={getWeekWorkTime} > 一週總工時 </Table.Column> <Table.Column className={styles.colFrequency} title="加班頻率" dataField={getFrequency} > 加班頻率 </Table.Column> <Table.Column className={styles.colSalary} title="薪資" dataField={getSalary} alignRight > 薪資 </Table.Column> <Table.Column className={styles.colHourly} title="估計時薪" dataField={R.compose( formatWage, R.prop('estimated_hourly_wage'), )} alignRight > <InfoButton onClick={toggleInfoSalaryModal}>估計時薪</InfoButton> </Table.Column> <Table.Column className={styles.colDataTime} title="參考時間" dataField={R.compose( formatDate, R.prop('data_time'), )} > <InfoButton onClick={toggleInfoTimeModal}>參考時間</InfoButton> </Table.Column> <Table.Column className={styles.colAboutThisJob} title="關於此工作" dataField={getAboutThisJobButton(toggleAboutThisJobModal)} /> </Table> ); DashBoardTable.propTypes = { data: PropTypes.array.isRequired, postProcessRows: PropTypes.func.isRequired, toggleInfoSalaryModal: PropTypes.func.isRequired, toggleInfoTimeModal: PropTypes.func.isRequired, toggleAboutThisJobModal: PropTypes.func.isRequired, }; export default DashBoardTable;
src/svg-icons/action/view-quilt.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewQuilt = (props) => ( <SvgIcon {...props}> <path d="M10 18h5v-6h-5v6zm-6 0h5V5H4v13zm12 0h5v-6h-5v6zM10 5v6h11V5H10z"/> </SvgIcon> ); ActionViewQuilt = pure(ActionViewQuilt); ActionViewQuilt.displayName = 'ActionViewQuilt'; ActionViewQuilt.muiName = 'SvgIcon'; export default ActionViewQuilt;
node_modules/semantic-ui-react/src/elements/Step/StepContent.js
SuperUncleCat/ServerMonitoring
import cx from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { childrenUtils, createShorthand, customPropTypes, getElementType, getUnhandledProps, META, } from '../../lib' import StepDescription from './StepDescription' import StepTitle from './StepTitle' /** * A step can contain a content. */ function StepContent(props) { const { children, className, description, title } = props const classes = cx('content', className) const rest = getUnhandledProps(StepContent, props) const ElementType = getElementType(StepContent, props) if (!childrenUtils.isNil(children)) { return <ElementType {...rest} className={classes}>{children}</ElementType> } return ( <ElementType {...rest} className={classes}> {createShorthand(StepTitle, val => ({ title: val }), title)} {createShorthand(StepDescription, val => ({ description: val }), description)} </ElementType> ) } StepContent._meta = { name: 'StepContent', parent: 'Step', type: META.TYPES.ELEMENT, } StepContent.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for StepDescription. */ description: customPropTypes.itemShorthand, /** Shorthand for StepTitle. */ title: customPropTypes.itemShorthand, } export default StepContent
packages/material-ui-icons/src/EvStation.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let EvStation = props => <SvgIcon {...props}> <path d="M19.77 7.23l.01-.01-3.72-3.72L15 4.56l2.11 2.11c-.94.36-1.61 1.26-1.61 2.33 0 1.38 1.12 2.5 2.5 2.5.36 0 .69-.08 1-.21v7.21c0 .55-.45 1-1 1s-1-.45-1-1V14c0-1.1-.9-2-2-2h-1V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v16h10v-7.5h1.5v5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V9c0-.69-.28-1.32-.73-1.77zM18 10c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zM8 18v-4.5H6L10 6v5h2l-4 7z" /> </SvgIcon>; EvStation = pure(EvStation); EvStation.muiName = 'SvgIcon'; export default EvStation;
chrome/extension/window/index.js
theaidem/reachext
import React from 'react' import { render } from 'react-dom' import Root from './Root' window.addEventListener('load', () => { chrome.storage.local.get(null, (store) => { render(<Root />, document.querySelector('#root')) }) })
appsrc/js/plaster-app.js
esonderegger/plaster
import React from 'react'; import Podcast from './podcast.js'; import Snackbar from 'material-ui/Snackbar'; import Dialog from 'material-ui/Dialog'; import LinearProgress from 'material-ui/LinearProgress'; import FlatButton from 'material-ui/FlatButton'; import WelcomeScreen from './welcome-screen.js'; import PlasterUpdater from './plaster-updater.js'; export default class PlasterApp extends React.Component { constructor(props) { super(props); this.state = { podcastPath: '', snackbarOpen: false, snackbarMessage: '', snackbarDuration: 4000, errorOpen: false, errorMessage: '', enableAutoUpdates: false }; this.goHome = this.goHome.bind(this); this.setSnackbar = this.setSnackbar.bind(this); this.snackbarClose = this.snackbarClose.bind(this); this.setError = this.setError.bind(this); this.errorClose = this.errorClose.bind(this); this.updatePodcastPath = this.updatePodcastPath.bind(this); } componentDidMount() { var pathFromLocalStorage = localStorage.getItem('podcastDirectory'); if (pathFromLocalStorage && pathFromLocalStorage !== 'null') { this.setState({podcastPath: pathFromLocalStorage}); } } updatePodcastPath(p) { this.setState({podcastPath: p}); localStorage.setItem('podcastDirectory', p); } goHome() { this.setState({podcastPath: ''}); localStorage.setItem('podcastDirectory', null); } setSnackbar(message, duration) { this.setState({ snackbarOpen: true, snackbarMessage: message, snackbarDuration: duration }); } snackbarClose() { this.setState({ snackbarOpen: false }); } setError(message) { this.setState({ errorOpen: true, errorMessage: message }); } errorClose() { this.setState({ errorOpen: false }); } render() { var mainWindow = ( <WelcomeScreen updatePodcastPath={this.updatePodcastPath} setSnackbar={this.setSnackbar} setError={this.setError} /> ); if (this.state.podcastPath) { mainWindow = ( <Podcast directory={this.state.podcastPath} goHome={this.goHome} setSnackbar={this.setSnackbar} setError={this.setError} /> ); } const errorActions = [ <FlatButton label="Ok" primary={true} onTouchTap={this.errorClose} /> ]; var snackbarProgress = ( <div style={{ width: '2em', display: 'inline-block', position: 'relative', top: '-3px', left: '-9px' }}> <LinearProgress mode="indeterminate" /> </div> ); var snackbarJsx = ( <div> {this.state.snackbarDuration ? null : snackbarProgress} <span>{this.state.snackbarMessage}</span> </div> ); return ( <div className="plaster-app"> {mainWindow} <Snackbar open={this.state.snackbarOpen} message={snackbarJsx} autoHideDuration={this.state.snackbarDuration} onRequestClose={this.snackbarClose} /> <Dialog actions={errorActions} modal={false} open={this.state.errorOpen} onRequestClose={this.errorClose} >{this.state.errorMessage}</Dialog> {this.state.enableAutoUpdates ? <PlasterUpdater /> : null} </div> ); } }
src/svg-icons/av/radio.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvRadio = (props) => ( <SvgIcon {...props}> <path d="M3.24 6.15C2.51 6.43 2 7.17 2 8v12c0 1.1.89 2 2 2h16c1.11 0 2-.9 2-2V8c0-1.11-.89-2-2-2H8.3l8.26-3.34L15.88 1 3.24 6.15zM7 20c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm13-8h-2v-2h-2v2H4V8h16v4z"/> </SvgIcon> ); AvRadio = pure(AvRadio); AvRadio.displayName = 'AvRadio'; AvRadio.muiName = 'SvgIcon'; export default AvRadio;
docs/src/Anchor.js
albertojacini/react-bootstrap
import React from 'react'; const Anchor = React.createClass({ propTypes: { id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) }, render() { return ( <a id={this.props.id} href={'#' + this.props.id} className="anchor"> <span className="anchor-icon">#</span> {this.props.children} </a> ); } }); export default Anchor;
src/svg-icons/image/filter-2.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter2 = (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 16H7V3h14v14zm-4-4h-4v-2h2c1.1 0 2-.89 2-2V7c0-1.11-.9-2-2-2h-4v2h4v2h-2c-1.1 0-2 .89-2 2v4h6v-2z"/> </SvgIcon> ); ImageFilter2 = pure(ImageFilter2); ImageFilter2.displayName = 'ImageFilter2'; ImageFilter2.muiName = 'SvgIcon'; export default ImageFilter2;
packages/cf-component-label/test/Label.js
koddsson/cf-ui
import React from 'react'; import { felaSnapshot } from 'cf-style-provider'; import { Label } from '../../cf-component-label/src/index'; test('should render', () => { const snapshot = felaSnapshot(<Label type="default">A Label</Label>); expect(snapshot.component).toMatchSnapshot(); expect(snapshot.styles).toMatchSnapshot(); });
app/components/Button.js
jmcolella/unique-twitter-followers
import React from 'react'; import { Link } from 'react-router'; const Button = ( props ) => ( <Link to={ props.link }> <button type='button' > { props.children } </button> </Link> ); Button.propTypes = { link: React.PropTypes.string.isRequired, children: React.PropTypes.string.isRequired } export default Button;
server/boot/a-react.js
lawrence34/freecodecamp
import React from 'react'; import Router from 'react-router'; import Fetchr from 'fetchr'; import Location from 'react-router/lib/Location'; import debugFactory from 'debug'; import { app$ } from '../../common/app'; import { RenderToString } from 'thundercats-react'; const debug = debugFactory('freecc:react-server'); // add routes here as they slowly get reactified // remove their individual controllers const routes = [ '/hikes', '/hikes/*', '/jobs' ]; export default function reactSubRouter(app) { var router = app.loopback.Router(); routes.forEach(function(route) { router.get(route, serveReactApp); }); app.use(router); function serveReactApp(req, res, next) { const services = new Fetchr({ req }); const location = new Location(req.path, req.query); // returns a router wrapped app app$(location) // if react-router does not find a route send down the chain .filter(function({ initialState }) { if (!initialState) { debug('react tried to find %s but got 404', location.pathname); return next(); } return !!initialState; }) .flatMap(function({ initialState, AppCat }) { // call thundercats renderToString // prefetches data and sets up it up for current state debug('rendering to string'); return RenderToString( AppCat(null, services), React.createElement(Router, initialState) ); }) // makes sure we only get one onNext and closes subscription .flatMap(function({ data, markup }) { debug('react rendered'); res.expose(data, 'data'); // now render jade file with markup injected from react return res.render$('layout-react', { markup: markup }); }) .subscribe( function(markup) { debug('jade rendered'); res.send(markup); }, next ); } }
app/containers/FeaturePage/index.js
mmaedel/react-boilerplate
/* * FeaturePage * * List all the features */ import React from 'react'; import Helmet from 'react-helmet'; import messages from './messages'; import { FormattedMessage } from 'react-intl'; import H1 from 'components/H1'; import List from './List'; import ListItem from './ListItem'; import ListItemTitle from './ListItemTitle'; export default class FeaturePage extends React.Component { // eslint-disable-line react/prefer-stateless-function // Since state and props are static, // there's no need to re-render this component shouldComponentUpdate() { return false; } render() { return ( <div> <Helmet title="Feature Page" meta={[ { name: 'description', content: 'Feature page of React.js Boilerplate application' }, ]} /> <H1> <FormattedMessage {...messages.header} /> </H1> <List> <ListItem> <ListItemTitle> <FormattedMessage {...messages.scaffoldingHeader} /> </ListItemTitle> <p> <FormattedMessage {...messages.scaffoldingMessage} /> </p> </ListItem> <ListItem> <ListItemTitle> <FormattedMessage {...messages.feedbackHeader} /> </ListItemTitle> <p> <FormattedMessage {...messages.feedbackMessage} /> </p> </ListItem> <ListItem> <ListItemTitle> <FormattedMessage {...messages.routingHeader} /> </ListItemTitle> <p> <FormattedMessage {...messages.routingMessage} /> </p> </ListItem> <ListItem> <ListItemTitle> <FormattedMessage {...messages.networkHeader} /> </ListItemTitle> <p> <FormattedMessage {...messages.networkMessage} /> </p> </ListItem> <ListItem> <ListItemTitle> <FormattedMessage {...messages.intlHeader} /> </ListItemTitle> <p> <FormattedMessage {...messages.intlMessage} /> </p> </ListItem> </List> </div> ); } }
webpack/landing.js
CDCgov/SDP-Vocabulary-Service
require("styles/master.scss"); require("bootstrap-sass/assets/javascripts/bootstrap.js"); import 'react-dates/initialize'; import 'react-dates/lib/css/_datepicker.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { hashHistory, Router, Route, IndexRoute } from 'react-router'; import DashboardContainer from './containers/DashboardContainer'; import ResponseSetShowContainer from './containers/response_sets/ResponseSetShowContainer'; import SectionShowContainer from './containers/sections/SectionShowContainer'; import QuestionShowContainer from './containers/questions/QuestionShowContainer'; import ResponseSetEditContainer from './containers/response_sets/ResponseSetEditContainer'; import QuestionEditContainer from './containers/questions/QuestionEditContainer'; import SurveyEditContainer from './containers/surveys/SurveyEditContainer'; import SurveyImportContainer from './containers/surveys/SurveyImportContainer'; import SurveyDedupeContainer from './containers/surveys/SurveyDedupeContainer'; import SectionEditContainer from './containers/sections/SectionEditContainer'; import SurveyShowContainer from './containers/surveys/SurveyShowContainer'; import TermsOfService from './containers/TermsOfService'; import Help from './containers/Help'; import FHIRDoc from './components/FHIRDoc'; import AdminPanel from './containers/AdminPanel'; import App from './containers/App'; import AuthenticatedRoutes from './containers/AuthenticatedRoutes'; import AdminRoutes from './containers/AdminRoutes'; import ErrorPage, {GenericError, Forbidden403, NotFound404} from './containers/ErrorPages'; import store from './store/configure_store'; import {logPageViewed} from './utilities/AdobeAnalytics'; ReactDOM.render( <Provider store={store}> <Router history={hashHistory} onUpdate={logPageViewed}> <Route path='/' component={App}> <IndexRoute component={DashboardContainer} /> <Route component={AdminRoutes}> <Route path='/admin' component={AdminPanel} /> </Route> <Route component={AuthenticatedRoutes}> <Route path='/sections/new' component={SectionEditContainer} /> <Route path='/sections/:sectionId/:action' component={SectionEditContainer} /> <Route path='/responseSets/new' component={ResponseSetEditContainer} /> <Route path='/responseSets/:rsId/:action' component={ResponseSetEditContainer} /> <Route path='/questions/new' component={QuestionEditContainer} /> <Route path='/questions/:qId/:action' component={QuestionEditContainer} /> <Route path='/surveys/new' component={SurveyEditContainer} /> <Route path='/surveys/import' component={SurveyImportContainer} /> <Route path='/surveys/:surveyId/dedupe' component={SurveyDedupeContainer} /> <Route path='/surveys/:surveyId/:action' component={SurveyEditContainer} /> </Route> <Route path='/termsOfService' component={TermsOfService}/> <Route path='/help' component={Help}/> <Route path='/fhirDoc' component={FHIRDoc}/> <Route path='/sections/:sectionId' component={SectionShowContainer} /> <Route path='/responseSets/:rsId' component={ResponseSetShowContainer} /> <Route path='/questions/:qId' component={QuestionShowContainer} /> <Route path='/surveys/:surveyId' component={SurveyShowContainer} /> <Route path='/errors/' component={ErrorPage} > <Route path='403' component={Forbidden403} /> <Route path='404' component={NotFound404} /> <Route path='*' component={GenericError} /> </Route> </Route> </Router> </Provider>, document.getElementById("app"));
es/components/sidebar/panel-element-editor/element-editor.js
cvdlab/react-planner
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Map, fromJS } from 'immutable'; import AttributesEditor from './attributes-editor/attributes-editor'; import { GeometryUtils, MathUtils } from '../../../utils/export'; import * as SharedStyle from '../../../shared-style'; import convert from 'convert-units'; import { MdContentCopy, MdContentPaste } from 'react-icons/md'; var PRECISION = 2; var attrPorpSeparatorStyle = { margin: '0.5em 0.25em 0.5em 0', border: '2px solid ' + SharedStyle.SECONDARY_COLOR.alt, position: 'relative', height: '2.5em', borderRadius: '2px' }; var headActionStyle = { position: 'absolute', right: '0.5em', top: '0.5em' }; var iconHeadStyle = { float: 'right', margin: '-3px 4px 0px 0px', padding: 0, cursor: 'pointer', fontSize: '1.4em' }; var ElementEditor = function (_Component) { _inherits(ElementEditor, _Component); function ElementEditor(props, context) { _classCallCheck(this, ElementEditor); var _this = _possibleConstructorReturn(this, (ElementEditor.__proto__ || Object.getPrototypeOf(ElementEditor)).call(this, props, context)); _this.state = { attributesFormData: _this.initAttrData(_this.props.element, _this.props.layer, _this.props.state), propertiesFormData: _this.initPropData(_this.props.element, _this.props.layer, _this.props.state) }; _this.updateAttribute = _this.updateAttribute.bind(_this); return _this; } _createClass(ElementEditor, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { if (this.state.attributesFormData.hashCode() !== nextState.attributesFormData.hashCode() || this.state.propertiesFormData.hashCode() !== nextState.propertiesFormData.hashCode() || this.props.state.clipboardProperties.hashCode() !== nextProps.state.clipboardProperties.hashCode()) return true; return false; } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(_ref) { var element = _ref.element, layer = _ref.layer, state = _ref.state; var prototype = element.prototype, id = element.id; var scene = this.props.state.get('scene'); var selectedLayer = scene.getIn(['layers', scene.get('selectedLayer')]); var selected = selectedLayer.getIn([prototype, id]); if (selectedLayer.hashCode() !== layer.hashCode()) this.setState({ attributesFormData: this.initAttrData(element, layer, state), propertiesFormData: this.initPropData(element, layer, state) }); } }, { key: 'initAttrData', value: function initAttrData(element, layer, state) { element = _typeof(element.misc) === 'object' ? element.set('misc', new Map(element.misc)) : element; switch (element.prototype) { case 'items': { return new Map(element); } case 'lines': { var v_a = layer.vertices.get(element.vertices.get(0)); var v_b = layer.vertices.get(element.vertices.get(1)); var distance = GeometryUtils.pointsDistance(v_a.x, v_a.y, v_b.x, v_b.y); var _unit = element.misc.get('_unitLength') || this.context.catalog.unit; var _length = convert(distance).from(this.context.catalog.unit).to(_unit); return new Map({ vertexOne: v_a, vertexTwo: v_b, lineLength: new Map({ length: distance, _length: _length, _unit: _unit }) }); } case 'holes': { var line = layer.lines.get(element.line); var _layer$vertices$get = layer.vertices.get(line.vertices.get(0)), x0 = _layer$vertices$get.x, y0 = _layer$vertices$get.y; var _layer$vertices$get2 = layer.vertices.get(line.vertices.get(1)), x1 = _layer$vertices$get2.x, y1 = _layer$vertices$get2.y; var lineLength = GeometryUtils.pointsDistance(x0, y0, x1, y1); var startAt = lineLength * element.offset - element.properties.get('width').get('length') / 2; var _unitA = element.misc.get('_unitA') || this.context.catalog.unit; var _lengthA = convert(startAt).from(this.context.catalog.unit).to(_unitA); var endAt = lineLength - lineLength * element.offset - element.properties.get('width').get('length') / 2; var _unitB = element.misc.get('_unitB') || this.context.catalog.unit; var _lengthB = convert(endAt).from(this.context.catalog.unit).to(_unitB); return new Map({ offset: element.offset, offsetA: new Map({ length: MathUtils.toFixedFloat(startAt, PRECISION), _length: MathUtils.toFixedFloat(_lengthA, PRECISION), _unit: _unitA }), offsetB: new Map({ length: MathUtils.toFixedFloat(endAt, PRECISION), _length: MathUtils.toFixedFloat(_lengthB, PRECISION), _unit: _unitB }) }); } case 'areas': { return new Map({}); } default: return null; } } }, { key: 'initPropData', value: function initPropData(element, layer, state) { var catalog = this.context.catalog; var catalogElement = catalog.getElement(element.type); var mapped = {}; for (var name in catalogElement.properties) { mapped[name] = new Map({ currentValue: element.properties.has(name) ? element.properties.get(name) : fromJS(catalogElement.properties[name].defaultValue), configs: catalogElement.properties[name] }); } return new Map(mapped); } }, { key: 'updateAttribute', value: function updateAttribute(attributeName, value) { var _this2 = this; var attributesFormData = this.state.attributesFormData; switch (this.props.element.prototype) { case 'items': { attributesFormData = attributesFormData.set(attributeName, value); break; } case 'lines': { switch (attributeName) { case 'lineLength': { var v_0 = attributesFormData.get('vertexOne'); var v_1 = attributesFormData.get('vertexTwo'); var _GeometryUtils$orderV = GeometryUtils.orderVertices([v_0, v_1]), _GeometryUtils$orderV2 = _slicedToArray(_GeometryUtils$orderV, 2), v_a = _GeometryUtils$orderV2[0], v_b = _GeometryUtils$orderV2[1]; var v_b_new = GeometryUtils.extendLine(v_a.x, v_a.y, v_b.x, v_b.y, value.get('length'), PRECISION); attributesFormData = attributesFormData.withMutations(function (attr) { attr.set(v_0 === v_a ? 'vertexTwo' : 'vertexOne', v_b.merge(v_b_new)); attr.set('lineLength', value); }); break; } case 'vertexOne': case 'vertexTwo': { attributesFormData = attributesFormData.withMutations(function (attr) { attr.set(attributeName, attr.get(attributeName).merge(value)); var newDistance = GeometryUtils.verticesDistance(attr.get('vertexOne'), attr.get('vertexTwo')); attr.mergeIn(['lineLength'], attr.get('lineLength').merge({ 'length': newDistance, '_length': convert(newDistance).from(_this2.context.catalog.unit).to(attr.get('lineLength').get('_unit')) })); }); break; } default: { attributesFormData = attributesFormData.set(attributeName, value); break; } } break; } case 'holes': { switch (attributeName) { case 'offsetA': { var line = this.props.layer.lines.get(this.props.element.line); var orderedVertices = GeometryUtils.orderVertices([this.props.layer.vertices.get(line.vertices.get(0)), this.props.layer.vertices.get(line.vertices.get(1))]); var _orderedVertices = _slicedToArray(orderedVertices, 2), _orderedVertices$ = _orderedVertices[0], x0 = _orderedVertices$.x, y0 = _orderedVertices$.y, _orderedVertices$2 = _orderedVertices[1], x1 = _orderedVertices$2.x, y1 = _orderedVertices$2.y; var alpha = GeometryUtils.angleBetweenTwoPoints(x0, y0, x1, y1); var lineLength = GeometryUtils.pointsDistance(x0, y0, x1, y1); var widthLength = this.props.element.properties.get('width').get('length'); var halfWidthLength = widthLength / 2; var lengthValue = value.get('length'); lengthValue = Math.max(lengthValue, 0); lengthValue = Math.min(lengthValue, lineLength - widthLength); var xp = (lengthValue + halfWidthLength) * Math.cos(alpha) + x0; var yp = (lengthValue + halfWidthLength) * Math.sin(alpha) + y0; var offset = GeometryUtils.pointPositionOnLineSegment(x0, y0, x1, y1, xp, yp); var endAt = MathUtils.toFixedFloat(lineLength - lineLength * offset - halfWidthLength, PRECISION); var offsetUnit = attributesFormData.getIn(['offsetB', '_unit']); var offsetB = new Map({ length: endAt, _length: convert(endAt).from(this.context.catalog.unit).to(offsetUnit), _unit: offsetUnit }); attributesFormData = attributesFormData.set('offsetB', offsetB).set('offset', offset); var offsetAttribute = new Map({ length: MathUtils.toFixedFloat(lengthValue, PRECISION), _unit: value.get('_unit'), _length: MathUtils.toFixedFloat(convert(lengthValue).from(this.context.catalog.unit).to(value.get('_unit')), PRECISION) }); attributesFormData = attributesFormData.set(attributeName, offsetAttribute); break; } case 'offsetB': { var _line = this.props.layer.lines.get(this.props.element.line); var _orderedVertices2 = GeometryUtils.orderVertices([this.props.layer.vertices.get(_line.vertices.get(0)), this.props.layer.vertices.get(_line.vertices.get(1))]); var _orderedVertices3 = _slicedToArray(_orderedVertices2, 2), _orderedVertices3$ = _orderedVertices3[0], _x = _orderedVertices3$.x, _y = _orderedVertices3$.y, _orderedVertices3$2 = _orderedVertices3[1], _x2 = _orderedVertices3$2.x, _y2 = _orderedVertices3$2.y; var _alpha = GeometryUtils.angleBetweenTwoPoints(_x, _y, _x2, _y2); var _lineLength = GeometryUtils.pointsDistance(_x, _y, _x2, _y2); var _widthLength = this.props.element.properties.get('width').get('length'); var _halfWidthLength = _widthLength / 2; var _lengthValue = value.get('length'); _lengthValue = Math.max(_lengthValue, 0); _lengthValue = Math.min(_lengthValue, _lineLength - _widthLength); var _xp = _x2 - (_lengthValue + _halfWidthLength) * Math.cos(_alpha); var _yp = _y2 - (_lengthValue + _halfWidthLength) * Math.sin(_alpha); var _offset = GeometryUtils.pointPositionOnLineSegment(_x, _y, _x2, _y2, _xp, _yp); var startAt = MathUtils.toFixedFloat(_lineLength * _offset - _halfWidthLength, PRECISION); var _offsetUnit = attributesFormData.getIn(['offsetA', '_unit']); var offsetA = new Map({ length: startAt, _length: convert(startAt).from(this.context.catalog.unit).to(_offsetUnit), _unit: _offsetUnit }); attributesFormData = attributesFormData.set('offsetA', offsetA).set('offset', _offset); var _offsetAttribute = new Map({ length: MathUtils.toFixedFloat(_lengthValue, PRECISION), _unit: value.get('_unit'), _length: MathUtils.toFixedFloat(convert(_lengthValue).from(this.context.catalog.unit).to(value.get('_unit')), PRECISION) }); attributesFormData = attributesFormData.set(attributeName, _offsetAttribute); break; } default: { attributesFormData = attributesFormData.set(attributeName, value); break; } }; break; } default: break; } this.setState({ attributesFormData: attributesFormData }); this.save({ attributesFormData: attributesFormData }); } }, { key: 'updateProperty', value: function updateProperty(propertyName, value) { var propertiesFormData = this.state.propertiesFormData; propertiesFormData = propertiesFormData.setIn([propertyName, 'currentValue'], value); this.setState({ propertiesFormData: propertiesFormData }); this.save({ propertiesFormData: propertiesFormData }); } }, { key: 'reset', value: function reset() { this.setState({ propertiesFormData: this.initPropData(this.props.element, this.props.layer, this.props.state) }); } }, { key: 'save', value: function save(_ref2) { var propertiesFormData = _ref2.propertiesFormData, attributesFormData = _ref2.attributesFormData; if (propertiesFormData) { var properties = propertiesFormData.map(function (data) { return data.get('currentValue'); }); this.context.projectActions.setProperties(properties); } if (attributesFormData) { switch (this.props.element.prototype) { case 'items': { this.context.projectActions.setItemsAttributes(attributesFormData); break; } case 'lines': { this.context.projectActions.setLinesAttributes(attributesFormData); break; } case 'holes': { this.context.projectActions.setHolesAttributes(attributesFormData); break; } } } } }, { key: 'copyProperties', value: function copyProperties(properties) { this.context.projectActions.copyProperties(properties); } }, { key: 'pasteProperties', value: function pasteProperties() { this.context.projectActions.pasteProperties(); } }, { key: 'render', value: function render() { var _this3 = this; var _state = this.state, propertiesFormData = _state.propertiesFormData, attributesFormData = _state.attributesFormData, _context = this.context, projectActions = _context.projectActions, catalog = _context.catalog, translator = _context.translator, _props = this.props, appState = _props.state, element = _props.element; return React.createElement( 'div', null, React.createElement(AttributesEditor, { element: element, onUpdate: this.updateAttribute, attributeFormData: attributesFormData, state: appState }), React.createElement( 'div', { style: attrPorpSeparatorStyle }, React.createElement( 'div', { style: headActionStyle }, React.createElement( 'div', { title: translator.t('Copy'), style: iconHeadStyle, onClick: function onClick(e) { return _this3.copyProperties(element.properties); } }, React.createElement(MdContentCopy, null) ), appState.get('clipboardProperties') && appState.get('clipboardProperties').size ? React.createElement( 'div', { title: translator.t('Paste'), style: iconHeadStyle, onClick: function onClick(e) { return _this3.pasteProperties(); } }, React.createElement(MdContentPaste, null) ) : null ) ), propertiesFormData.entrySeq().map(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), propertyName = _ref4[0], data = _ref4[1]; var currentValue = data.get('currentValue'), configs = data.get('configs'); var _catalog$getPropertyT = catalog.getPropertyType(configs.type), Editor = _catalog$getPropertyT.Editor; return React.createElement(Editor, { key: propertyName, propertyName: propertyName, value: currentValue, configs: configs, onUpdate: function onUpdate(value) { return _this3.updateProperty(propertyName, value); }, state: appState, sourceElement: element, internalState: _this3.state }); }) ); } }]); return ElementEditor; }(Component); export default ElementEditor; ElementEditor.propTypes = { state: PropTypes.object.isRequired, element: PropTypes.object.isRequired, layer: PropTypes.object.isRequired }; ElementEditor.contextTypes = { projectActions: PropTypes.object.isRequired, catalog: PropTypes.object.isRequired, translator: PropTypes.object.isRequired };
docs/src/pages/layout/MediaQuery.js
AndriusBil/material-ui
// @flow weak import React from 'react'; import PropTypes from 'prop-types'; import compose from 'recompose/compose'; import { withStyles } from 'material-ui/styles'; import withWidth from 'material-ui/utils/withWidth'; import Typography from 'material-ui/Typography'; const styles = theme => ({ root: { padding: theme.spacing.unit, [theme.breakpoints.up('md')]: { backgroundColor: theme.palette.primary[500], }, [theme.breakpoints.down('md')]: { backgroundColor: theme.palette.secondary.A400, }, }, }); function MediaQuery(props) { const classes = props.classes; return ( <div className={classes.root}> <Typography type="subheading">{`Current width: ${props.width}`}</Typography> </div> ); } MediaQuery.propTypes = { classes: PropTypes.object.isRequired, width: PropTypes.string.isRequired, }; export default compose(withStyles(styles), withWidth())(MediaQuery);
blueocean-material-icons/src/js/components/svg-icons/content/backspace.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ContentBackspace = (props) => ( <SvgIcon {...props}> <path d="M22 3H7c-.69 0-1.23.35-1.59.88L0 12l5.41 8.11c.36.53.9.89 1.59.89h15c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-3 12.59L17.59 17 14 13.41 10.41 17 9 15.59 12.59 12 9 8.41 10.41 7 14 10.59 17.59 7 19 8.41 15.41 12 19 15.59z"/> </SvgIcon> ); ContentBackspace.displayName = 'ContentBackspace'; ContentBackspace.muiName = 'SvgIcon'; export default ContentBackspace;
app/components/List/index.js
aditigoel23/React-Car-App
import React from 'react'; import Ul from './Ul'; import Wrapper from './Wrapper'; function List(props) { const ComponentToRender = props.component; let content = (<div></div>); // If we have items, render them if (props.items) { content = props.items.map((item, index) => ( <ComponentToRender key={`item-${index}`} item={item} /> )); } else { // Otherwise render a single component content = (<ComponentToRender />); } return ( <Wrapper> <Ul> {content} </Ul> </Wrapper> ); } List.propTypes = { component: React.PropTypes.func.isRequired, items: React.PropTypes.array, }; export default List;
docs/src/App.js
byumark/react-table
import React from 'react' // import ReactStory, { defaultProps } from 'react-story' import './stories/utils/prism.css' import '../../react-table.css' import Readme from './stories/Readme.js' import Simple from './stories/Simple.js' import CellRenderers from './stories/CellRenderers.js' import DefaultSorting from './stories/DefaultSorting.js' import CustomSorting from './stories/CustomSorting.js' import CustomWidths from './stories/CustomWidths.js' import CustomComponentProps from './stories/CustomComponentProps.js' import ServerSide from './stories/ServerSide.js' import SubComponents from './stories/SubComponents.js' import Pivoting from './stories/Pivoting.js' import PivotingSubComponents from './stories/PivotingSubComponents.js' import OneHundredKRows from './stories/OneHundredKRows.js' import FunctionalRendering from './stories/FunctionalRendering.js' import CustomExpanderPosition from './stories/CustomExpanderPosition.js' import NoDataText from './stories/NoDataText.js' import Footers from './stories/Footers.js' import Filtering from './stories/Filtering.js' import ControlledTable from './stories/ControlledTable.js' import PivotingOptions from './stories/PivotingOptions.js' import EditableTable from './stories/EditableTable.js' export default class App extends React.Component { render () { return ( <ReactStory style={{ display: 'block', width: '100%', height: '100%' }} pathPrefix='story/' StoryWrapper={(props) => ( <defaultProps.StoryWrapper css={{ padding: 0 }} > <a href='//github.com/tannerlinsley/react-table' style={{ display: 'block', textAlign: 'center', borderBottom: 'solid 3px #cccccc' }} > <img src='//npmcdn.com/react-table/media/Banner.png' alt='React Table Logo' style={{ width: '100px' }} /> </a> <div {...props} style={{ padding: '10px' }} /> </defaultProps.StoryWrapper> )} stories={[ { name: 'Readme', component: Readme }, { name: 'Simple Table', component: Simple }, { name: 'Cell Renderers & Custom Components', component: CellRenderers }, { name: 'Default Sorting', component: DefaultSorting }, { name: 'Custom Sorting', component: CustomSorting }, { name: 'Custom Column Widths', component: CustomWidths }, { name: 'Custom Component Props', component: CustomComponentProps }, { name: 'Server-side Data', component: ServerSide }, { name: 'Sub Components', component: SubComponents }, { name: 'Pivoting & Aggregation', component: Pivoting }, { name: 'Pivoting & Aggregation w/ Sub Components', component: PivotingSubComponents }, { name: '100k Rows w/ Pivoting & Sub Components', component: OneHundredKRows }, { name: 'Pivoting Options', component: PivotingOptions }, { name: 'Functional Rendering', component: FunctionalRendering }, { name: 'Custom Expander Position', component: CustomExpanderPosition }, { name: 'Custom "No Data" Text', component: NoDataText }, { name: 'Footers', component: Footers }, { name: 'Custom Filtering', component: Filtering }, { name: 'Controlled Component', component: ControlledTable }, { name: 'Editable Table', component: EditableTable } ]} /> ) } }
src/components/comment.js
josebigio/PodCast
import React, { Component } from 'react'; import CountIcon from './count-icon' import ReplyList from './reply-list'; class Comment extends Component { constructor(props) { super(props); this.state = { selected:false } } handleClick() { this.setState({ selected:!this.state.selected }); } render() { const { comment, showReplies } = this.props; const { snippet, replies } = comment; const { likeCount, textDisplay, authorDisplayName } = snippet.topLevelComment.snippet; return <li className="list-group-item comment-list-group-item clickable" onClick={this.handleClick.bind(this)}> <h6>{authorDisplayName}</h6> <div dangerouslySetInnerHTML={{ __html: textDisplay }} /> <CountIcon count={likeCount} color="#ffaaff" radius="30px" /> {this.state.selected && <ReplyList replies={replies.comments} />} </li> } } export default Comment;
client/js/components/widget-create.js
ericwgreene/relay-practice
import React from 'react'; import PropTypes from 'prop-types'; import { createFragmentContainer, graphql } from 'react-relay'; import { WidgetForm } from './widget-form'; import { insertWidget } from '../mutations/insert-widget-mutation'; export class WidgetCreate extends React.Component { static propTypes = { router: PropTypes.shape({ push: PropTypes.func, }), viewer: PropTypes.object, relay: PropTypes.shape({ environment: PropTypes.object.isRequired, }).isRequired, }; constructor(props) { super(props); this.addWidget = this.addWidget.bind(this); } addWidget(widget) { insertWidget( // provided by relay import this.props.relay.environment, // normal widget object provided by widget form widget, // viewer prop which was populated by the graphql query defined // in widgets-app-container this.props.viewer, ).then(() => { this.props.router.push('/'); }); } render() { return <section> <WidgetForm onSave={this.addWidget} /> </section>; } } export const WidgetCreateContainer = createFragmentContainer(WidgetCreate, graphql` fragment widgetCreate_viewer on Viewer { id } `);
app/components/Contact.js
leckman/purlpal
import React from 'react'; import { connect } from 'react-redux' import { submitContactForm } from '../actions/contact'; import Messages from './Messages'; class Contact extends React.Component { constructor(props) { super(props); this.state = { name: '', email: '', message: '' }; } handleChange(event) { this.setState({ [event.target.name]: event.target.value }); } handleSubmit(event) { event.preventDefault(); this.props.dispatch(submitContactForm(this.state.name, this.state.email, this.state.message)); } render() { return ( <div className="container"> <div className="panel"> <div className="panel-heading"> <h3 className="panel-title">Contact Form</h3> </div> <div className="panel-body"> <Messages messages={this.props.messages}/> <form onSubmit={this.handleSubmit.bind(this)} className="form-horizontal"> <div className="form-group"> <label htmlFor="name" className="col-sm-2">Name</label> <div className="col-sm-8"> <input type="text" name="name" id="name" className="form-control" value={this.state.name} onChange={this.handleChange.bind(this)} autoFocus/> </div> </div> <div className="form-group"> <label htmlFor="email" className="col-sm-2">Email</label> <div className="col-sm-8"> <input type="email" name="email" id="email" className="form-control" value={this.state.email} onChange={this.handleChange.bind(this)}/> </div> </div> <div className="form-group"> <label htmlFor="message" className="col-sm-2">Body</label> <div className="col-sm-8"> <textarea name="message" id="message" rows="7" className="form-control" value={this.state.message} onChange={this.handleChange.bind(this)}></textarea> </div> </div> <div className="form-group"> <div className="col-sm-offset-2 col-sm-8"> <button type="submit" className="btn btn-success">Send</button> </div> </div> </form> </div> </div> </div> ); } } const mapStateToProps = (state) => { return { messages: state.messages }; }; export default connect(mapStateToProps)(Contact);
react-demos/undo_redo/src/index.js
konvajs/site
import React, { Component } from 'react'; import { createRoot } from 'react-dom/client'; import { Stage, Layer, Rect, Text } from 'react-konva'; let history = [ { x: 20, y: 20, }, ]; let historyStep = 0; class App extends Component { state = { position: history[0], }; handleUndo = () => { if (historyStep === 0) { return; } historyStep -= 1; const previous = history[historyStep]; this.setState({ position: previous, }); }; handleRedo = () => { if (historyStep === history.length - 1) { return; } historyStep += 1; const next = history[historyStep]; this.setState({ position: next, }); }; handleDragEnd = (e) => { history = history.slice(0, historyStep + 1); const pos = { x: e.target.x(), y: e.target.y(), }; history = history.concat([pos]); historyStep += 1; this.setState({ position: pos, }); }; render() { return ( <Stage width={window.innerWidth} height={window.innerHeight}> <Layer> <Text text="undo" onClick={this.handleUndo} /> <Text text="redo" x={40} onClick={this.handleRedo} /> <Rect x={this.state.position.x} y={this.state.position.y} width={50} height={50} fill="black" draggable onDragEnd={this.handleDragEnd} /> </Layer> </Stage> ); } } const container = document.getElementById('root'); const root = createRoot(container); root.render(<App />);
client/trello/src/app/routes/home/routes/boardView/components/Forms/CreateCard/CreateCard.js
Madmous/Trello-Clone
import React from 'react'; import { Field, reduxForm } from 'redux-form'; import FontAwesome from 'react-fontawesome'; import PropTypes from 'prop-types'; import './CreateCard.css'; const propTypes = { isCreateCardFormOpen: PropTypes.bool.isRequired, boardViewActions: PropTypes.object.isRequired } function CreateCard(props) { const focusOnForm = isFocusOnForm => { if (isFocusOnForm) { props.boardViewActions.focusOnBoard(); } else { props.boardViewActions.blurOnBoard(); } } const { boardViewActions, handleSubmit } = props; return ( <div className="Create-Card-Form" tabIndex="0" onFocus={() => { focusOnForm(true) }} onBlur={() => { focusOnForm(false) }} > <form onSubmit={ handleSubmit }> <Field className="Create-Card-Form-CardTitle" autoFocus={true} type="text" name="name" value="" placeholder="Add a card…" component="input" dir="auto" /> <div className="Create-Card-Form-Footer"> <button type="submit" className="Create-Card-Form-SubmitButton">Save</button> <FontAwesome name="times" size="2x" className="Create-Card-Form-Header-Close-Button" onClick={ () => boardViewActions.closeCreateCardForm() } /> </div> </form> </div> ); } CreateCard.propTypes = propTypes; export default reduxForm({ form: 'createCardForm' })(CreateCard);
src/client/songs/songlinklazy.react.js
steida/songary
import Component from '../components/component.react'; import React from 'react'; import SongLink from '../songs/songlink.react'; import listenSong from './listensong'; @listenSong export default class SongLinkLazy extends Component { static propTypes = { actions: React.PropTypes.object.isRequired, params: React.PropTypes.object.isRequired, song: React.PropTypes.object } render() { const {song} = this.props; if (!song) return null; return ( <SongLink song={song} /> ); } }
client/src/components/dashboard/Account.js
no-stack-dub-sack/alumni-network
import { connect } from 'react-redux'; import { connectScreenSize } from 'react-screen-size'; import { mapScreenSizeToProps } from '../Navbar'; import React from 'react'; import styled from 'styled-components'; import { addFlashMessage, clearFlashMessage } from '../../actions/flashMessages'; import { Button, Modal } from 'semantic-ui-react'; import { deleteUser, logoutUser } from '../../actions/user'; const Input = styled.input` width: 100%; border: 1px solid rgba(5,5,5,0.25); padding: 4px 6px !important; font-size: 22px !important; `; const ConfirmModal = ({ open, input, handleInput, deleteUser, close }) => { return ( <Modal open={open} size="small"> <Modal.Header style={{ background: 'rgb(225,225,225)' }}> <h1> <span> <i className="red warning sign icon" /> {'Type your username to confirm:'} </span> </h1> </Modal.Header> <Modal.Content> <form onSubmit={deleteUser}> <Input autoComplete='off' autoFocus id="deleteInput" onChange={handleInput} type="text" value={input} /> </form> </Modal.Content> <Modal.Actions style={{ textAlign: 'center' }}> <Button color="red" content='Delete Account' icon='remove' labelPosition='right' onClick={deleteUser} /> <Button color="green" content='Nevermind' icon='undo' labelPosition='right' onClick={close} positive /> </Modal.Actions> </Modal> ); }; class Account extends React.Component { state = { flashMessageCleared: false, input: '', modal: false, } componentWillMount() { /* bit of a hack here in CWM, just manually removing this node from dom (if it exists), since there should never be a flash message rendered when first rendering this route. This will only need to happen if user does not manually clear whatever flash message is there before switching routes. */ document.getElementsByClassName('flashMessage')[0] && document.getElementsByClassName('flashMessage')[0].remove(); } componentDidMount = () => { document.addEventListener('click', this.handleClick); } componentWillUnmount = () => { document.removeEventListener('click', this.handleClick) } // 'close' is className of close icon in flash message handleClick = (e) => { e.target.classList.contains('close') ? this.setState({ flashMessageCleared: true }) : this.setState({ flashMessageCleared: false }); } deleteUser = (e) => { if (e) e.preventDefault(); const { input } = this.state; this.setState({ input: '' }); if (input === this.props.user) { deleteUser().then(res => { this.props.logoutUser(); this.props.clearFlashMessage(); this.props.addFlashMessage({ text: { header: 'Your account has been deleted.', message: 'Goodbye!' }, type: 'error', }); this.props.history.push('/login'); }).catch(err => { this.props.addFlashMessage({ text: { header: 'Something went wrong...', message: 'Hmmm...' }, type: 'error', }); }) } else { this.toggleModal(); this.props.addFlashMessage({ text: { header: 'Delete User Error.', message: `You must enter your username correctly if you want to delete your account.` }, type: 'error', }); } } handleInput = (e) => this.setState({ input: e.target.value }); toggleModal = () => this.setState({ modal: !this.state.modal }); render() { const { isDesktop } = this.props.screen; const { flashMessageCleared } = this.state; /* handles margins when flash messages are rendered and also when subsequently removed. handleClick and flashMessageCleared state of this component are all related to this. */ const Container = styled.div` margin-top: ${document.getElementsByClassName('flashMessage').length > 0 && !flashMessageCleared ? '53px' : isDesktop ? '200px': '175px' } !important; `; return ( <Container className="ui main text center aligned container"> <div className='ui segment' style={{ padding: '25px' }}> <h1 className="ui header"> {`Account Settings for: ${this.props.user}`} </h1> <button className="ui red button" onClick={this.toggleModal}> {'Delete My Account'} </button> <br /><br /> <p>{'This cannot be undone.'}</p> <ConfirmModal close={this.toggleModal} deleteUser={this.deleteUser} handleInput={this.handleInput} input={this.state.input} open={this.state.modal} /> </div> </Container> ); } }; const mapStateToProps = (state) => ({ user: state.user.username }); const dispatchProps = { addFlashMessage, clearFlashMessage, logoutUser }; export default connectScreenSize(mapScreenSizeToProps)( connect(mapStateToProps, dispatchProps)(Account) );
src/components/MessageText.js
twhite96/checkyoself
/* jshint ignore: start */ import React from 'react'; import { Message } from 'reactbulma'; import '../smde-editor.css'; class MessageText extends React.Component { render() { return ( <React.Fragment> <div className="fit pad-bottom"> <Message className="change-body body-styles"> <Message.Body> <h2> Hey! <span role="img" aria-label="wave-emoji-brown"> 👋🏾 </span> </h2> <p> This is Check Yo Self, an app to check the{' '} <span className="highlight">grammar and spelling</span> of your{' '} <span className="highlight">markdown blog posts</span>. </p> </Message.Body> </Message> </div> <div className="fit"> <Message className="change-danger body-styles change-text"> <Message.Body> <div className="content"> FAQ: <ol> <li> Is my data on your server somewhere?<br /> In an upcoming release, I am going to be using Firebase to sync and store your texts so that in case you come back and want to have your data persisted, it will be there. See the Privacy Policy for more. </li> <li> Does this cost anything?<br /> Nope. It is free. If you like it you can buy me a{' '} <a href="https://www.paypal.me/codenewb/5">coffee</a>. </li> <li> How can I delete no longer needed texts?<br /> Selecting and hitting backspace! </li> </ol> </div> </Message.Body> </Message> </div> </React.Fragment> ); } } export default MessageText;
tests/react_native_tests/test_data/native_code/ReusableComponents/app/components/UserConnect/component.js
ibhubs/sketch-components
/** * @flow */ import React from 'react' import PropTypes from 'prop-types' import { observer } from 'mobx-react/native' import styles from './styles' import Button from '@rn/commons/app/components/VIButton/VIButton' import styled from 'styled-components/native' import { Text } from 'react-native' import { View } from 'react-native' const UserConnect = (props) => ( <UserConnectStyledView> <Text style={styles.peterStyle} >{props.name}</Text> <Text style={styles.oceanographerStyle} >{props.job}</Text> <Button buttonStyle={styles.group2ButtonStyle} onPress={props.onClick} textStyle={styles.group2TextStyle} title={props.buttonName} /> </UserConnectStyledView> ) export const UserConnectStyledView = styled.View` alignItems: center; backgroundColor: rgba(248, 248, 248, 1.0); borderRadius: 24; elevation: 2; flexDirection: column; height: 117.0; justifyContent: center; marginLeft: 118.0; marginTop: 112.0; overflow: hidden; shadowColor: rgba(0, 0, 0, 0.5); shadowOffset: {'height': 2, 'width': 2}; shadowOpacity: 1; shadowRadius: 3; width: 125.0; ` export default observer(UserConnect)
client/src/javascript/components/icons/ChevronLeftIcon.js
jfurrow/flood
import React from 'react'; import BaseIcon from './BaseIcon'; export default class ChevronLeftIcon extends BaseIcon { render() { return ( <svg className={`icon icon--chevron-left ${this.props.className}`} viewBox={this.getViewBox()}> <polygon points="41.34 1.2 47.35 7.21 24.6 29.96 47.42 52.79 41.41 58.8 12.58 29.96 41.34 1.2" /> </svg> ); } }
__tests__/index.android.js
PowerlineApp/powerline-rn
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/components/ArrowBottom/ArrowBottom.js
Zoomdata/nhtsa-dashboard-2.2
import styles from './ArrowBottom.css'; import React from 'react'; const ArrowBottom = ({ hoodAction, arrowVisibility }) => { const arrowBottomStyles = { display: 'none' }; return ( <div className={ hoodAction === 'OPEN_HOOD' ? styles.active : styles.normal } style={ arrowVisibility === 'HIDE_ARROW' ? arrowBottomStyles : null } > </div> ) }; export default ArrowBottom;
src/components/App.js
yingray/create-react-redux-app
import React from 'react' import Header from './Header' const App = ({ children }) => <div> <Header /> <div> {children} </div> </div> export default App
App/Containers/AllComponentsScreen.js
okmttdhr/YoutuVote
// @flow // An All Components Screen is a great way to dev and quick-test components import React from 'react'; import { Platform, View, ScrollView, Text, Image } from 'react-native'; import { Images } from '../Themes'; import styles from './Styles/AllComponentsScreenStyle'; // Components to show examples (only real point of merge conflict) import '../Components/AlertMessage'; import '../Components/ButtonDefault'; import '../Components/RoundedButton'; import '../Components/DrawerButton'; // import '../Components/MapCallout' // Examples Render Engine import ExamplesRegistry from '../Services/ExamplesRegistry'; class AllComponentsScreen extends React.Component { renderAndroidWarning() { if (Platform.OS === 'android') { return ( <Text style={styles.sectionText}> Android only: Animations are slow? You are probably running the app in debug mode. It will run more smoothly once your app will be built. </Text> ); } return null; } render() { return ( <View style={styles.mainContainer}> <Image source={Images.background} style={styles.backgroundImage} resizeMode="stretch" /> <ScrollView style={styles.container}> <View style={styles.section}> {this.renderAndroidWarning()} <Text style={styles.sectionText}> Sometimes called a 'Style Guide', or 'Pattern Library', Examples Screen is filled with usage examples of fundamental components for a given application. Use this merge-friendly way for your team to show/use/test components. Examples are registered inside each component's file for quick changes and usage identification. </Text> <Text style={styles.subtitle} > All components that register examples will be rendered below: </Text> </View> {ExamplesRegistry.render()} </ScrollView> </View> ); } } export default AllComponentsScreen;
app/index.js
foysalit/runkeeper-desktop
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router } from 'react-router'; import routes from './routes'; import configureStore from './store/configureStore'; import './app.css'; const store = configureStore(); render( <Provider store={store}> <Router> {routes} </Router> </Provider>, document.getElementById('root') ); if (process.env.NODE_ENV !== 'production') { // Use require because imports can't be conditional. // In production, you should ensure process.env.NODE_ENV // is envified so that Uglify can eliminate this // module and its dependencies as dead code. // require('./createDevToolsWindow')(store); }
src/svg-icons/image/timelapse.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTimelapse = (props) => ( <SvgIcon {...props}> <path d="M16.24 7.76C15.07 6.59 13.54 6 12 6v6l-4.24 4.24c2.34 2.34 6.14 2.34 8.49 0 2.34-2.34 2.34-6.14-.01-8.48zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/> </SvgIcon> ); ImageTimelapse = pure(ImageTimelapse); ImageTimelapse.displayName = 'ImageTimelapse'; ImageTimelapse.muiName = 'SvgIcon'; export default ImageTimelapse;
src/svg-icons/maps/place.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsPlace = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/> </SvgIcon> ); MapsPlace = pure(MapsPlace); MapsPlace.displayName = 'MapsPlace'; MapsPlace.muiName = 'SvgIcon'; export default MapsPlace;
src/svg-icons/image/panorama.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePanorama = (props) => ( <SvgIcon {...props}> <path d="M23 18V6c0-1.1-.9-2-2-2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2zM8.5 12.5l2.5 3.01L14.5 11l4.5 6H5l3.5-4.5z"/> </SvgIcon> ); ImagePanorama = pure(ImagePanorama); ImagePanorama.displayName = 'ImagePanorama'; export default ImagePanorama;
packages/cf-component-select/test/Select.js
koddsson/cf-ui
import React from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import Select from '../../cf-component-select/src/index'; test('should render', () => { const tree = shallow(<Select />); expect(toJson(tree)).toMatchSnapshot(); });
src/fluxtable/NewServerActionStateManager.js
MirekSz/avem
import React, { Component } from 'react'; import ContainersStore from './container/ContainersStore'; import {LoadAllContainers} from './container/ContainersActionCreator'; var NewServerActionStateManager = React.createClass({ componentDidMount(){ var store = this.props.store; store.addListener(this.storeChanged); }, componentWillUnmount(){ var store = this.props.store; store.removeListener(this.storeChanged); }, render: function () { return null; }, storeChanged(action){ var data = this.props.store.getActiveElements(); var length = data.length; if (length >= 5) { $("#newContainer").addClass('disabled'); } else { $("#newContainer").removeClass('disabled'); } } }); export default NewServerActionStateManager;
src/svg-icons/editor/border-clear.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderClear = (props) => ( <SvgIcon {...props}> <path d="M7 5h2V3H7v2zm0 8h2v-2H7v2zm0 8h2v-2H7v2zm4-4h2v-2h-2v2zm0 4h2v-2h-2v2zm-8 0h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2v-2H3v2zm0-4h2V7H3v2zm0-4h2V3H3v2zm8 8h2v-2h-2v2zm8 4h2v-2h-2v2zm0-4h2v-2h-2v2zm0 8h2v-2h-2v2zm0-12h2V7h-2v2zm-8 0h2V7h-2v2zm8-6v2h2V3h-2zm-8 2h2V3h-2v2zm4 16h2v-2h-2v2zm0-8h2v-2h-2v2zm0-8h2V3h-2v2z"/> </SvgIcon> ); EditorBorderClear = pure(EditorBorderClear); EditorBorderClear.displayName = 'EditorBorderClear'; EditorBorderClear.muiName = 'SvgIcon'; export default EditorBorderClear;
src/svg-icons/content/content-copy.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentContentCopy = (props) => ( <SvgIcon {...props}> <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/> </SvgIcon> ); ContentContentCopy = pure(ContentContentCopy); ContentContentCopy.displayName = 'ContentContentCopy'; ContentContentCopy.muiName = 'SvgIcon'; export default ContentContentCopy;
src/SplitButton.js
albertojacini/react-bootstrap
import React from 'react'; import BootstrapMixin from './BootstrapMixin'; import Button from './Button'; import Dropdown from './Dropdown'; import SplitToggle from './SplitToggle'; class SplitButton extends React.Component { render() { let { children, title, onClick, target, href, // bsStyle is validated by 'Button' component bsStyle, // eslint-disable-line ...props } = this.props; let { disabled } = props; let button = ( <Button onClick={onClick} bsStyle={bsStyle} disabled={disabled} target={target} href={href} > {title} </Button> ); return ( <Dropdown {...props}> {button} <SplitToggle aria-label={title} bsStyle={bsStyle} disabled={disabled} /> <Dropdown.Menu> {children} </Dropdown.Menu> </Dropdown> ); } } SplitButton.propTypes = { ...Dropdown.propTypes, ...BootstrapMixin.propTypes, /** * @private */ onClick() {}, target: React.PropTypes.string, href: React.PropTypes.string, /** * The content of the split button. */ title: React.PropTypes.node.isRequired }; SplitButton.defaultProps = { disabled: false, dropup: false, pullRight: false }; SplitButton.Toggle = SplitToggle; export default SplitButton;
blueocean-material-icons/src/js/components/svg-icons/social/mood.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const SocialMood = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/> </SvgIcon> ); SocialMood.displayName = 'SocialMood'; SocialMood.muiName = 'SvgIcon'; export default SocialMood;
monkey/monkey_island/cc/ui/src/components/attack/techniques/T1041.js
guardicore/monkey
import React from 'react'; import ReactTable from 'react-table'; import {ScanStatus} from './Helpers'; import MitigationsComponent from './MitigationsComponent'; class T1041 extends React.Component { constructor(props) { super(props); } static getC2Columns() { return ([{ Header: 'Data exfiltration channels', columns: [ {Header: 'Source', id: 'src', accessor: x => x.src, style: {'whiteSpace': 'unset'}}, {Header: 'Destination', id: 'dst', accessor: x => x.dst, style: {'whiteSpace': 'unset'}} ] }]) } render() { return ( <div> <div>{this.props.data.message_html}</div> <br/> {this.props.data.status === ScanStatus.USED ? <ReactTable columns={T1041.getC2Columns()} data={this.props.data.command_control_channel} showPagination={false} defaultPageSize={this.props.data.command_control_channel.length} /> : ''} <MitigationsComponent mitigations={this.props.data.mitigations}/> </div> ); } } export default T1041;
src/auth/Credentials.js
BushrootPDX/app
import React from 'react'; import styled from 'styled-components'; const Form = styled.form` text-align: center; label { display: block; } label, button { padding: 5px; } `; export default ({ submit}) => ( <Form onSubmit={e => { e.preventDefault(); const { elements } = e.target; const data = Object.keys(elements).reduce((obj, key) => { obj[key] = elements[key].value; return obj; }, {}); submit(data); }}> <label>email: <input name="email"/></label> <label>password: <input type="password" name="password"/></label> <button>Sign in!</button> </Form> );
src/components/Game.js
vgamula/poisoning
import React, { Component } from 'react'; import {gameStep} from 'bl'; class Cell extends Component { render() { const isInfected = this.props.data.infected; const isHealing = this.props.data.infected && this.props.data.ticks > 6; let style = { backgroundColor: 'green', }; if (isInfected) { style.backgroundColor = 'red'; } if (isHealing) { style.backgroundColor = 'blue'; } return <td width='10' height='10' style={style}></td> } } class Row extends Component { render() { return <tr>{this.props.data.map((x, i) => <Cell data={x} key={i} />)}</tr> } } export default class extends Component { constructor(props) { super(props); this.state = { data: props.data, step: 0 }; } render() { let sterStyle = { 'font-size': 16 + 'px', 'text-align': 'center', 'border': 1 + 'px solid #E81515', 'borderRadius': 5 + 'px', 'background-color': '#CBF3C4', 'padding': 20 + 'px', }; let tableStyle = { 'margin': 0 + ' auto', } return ( <div> <p style={sterStyle}> {`Step ${this.state.step}`} </p> <table style={tableStyle}> <tbody> {this.state.data.map((x, i) => <Row data={x} key={i} />)} </tbody> </table> </div> ); } componentWillUnmount() { clearTimeout(this.gameTimer); } componentDidMount() { this.gameTimer = setInterval(() => { this.setState({ data: gameStep(this.state.data), step: this.state.step + 1 }); }, 500); } }
react/features/base/react/components/native/NavigateSectionListEmptyComponent.js
gpolitis/jitsi-meet
// @flow import React, { Component } from 'react'; import { Text, View } from 'react-native'; import { translate } from '../../../i18n'; import { Icon, IconMenuDown } from '../../../icons'; import styles from './styles'; type Props = { /** * The translate function. */ t: Function, }; /** * Implements a React Native {@link Component} that is to be displayed when the * list is empty. * * @augments Component */ class NavigateSectionListEmptyComponent extends Component<Props> { /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { const { t } = this.props; return ( <View style = { styles.pullToRefresh }> <Text style = { styles.pullToRefreshText }> { t('sectionList.pullToRefresh') } </Text> <Icon src = { IconMenuDown } style = { styles.pullToRefreshIcon } /> </View> ); } } export default translate(NavigateSectionListEmptyComponent);
src/svg-icons/device/signal-wifi-off.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalWifiOff = (props) => ( <SvgIcon {...props}> <path d="M23.64 7c-.45-.34-4.93-4-11.64-4-1.5 0-2.89.19-4.15.48L18.18 13.8 23.64 7zm-6.6 8.22L3.27 1.44 2 2.72l2.05 2.06C1.91 5.76.59 6.82.36 7l11.63 14.49.01.01.01-.01 3.9-4.86 3.32 3.32 1.27-1.27-3.46-3.46z"/> </SvgIcon> ); DeviceSignalWifiOff = pure(DeviceSignalWifiOff); DeviceSignalWifiOff.displayName = 'DeviceSignalWifiOff'; DeviceSignalWifiOff.muiName = 'SvgIcon'; export default DeviceSignalWifiOff;
src/client/react/user/components/dashboards/PostRaceDashboard.js
bwyap/ptc-amazing-g-race
import React from 'react'; import { Route } from 'react-router-dom'; import { connect } from 'react-redux'; import { Switch, Redirect } from 'react-router-dom'; import Base from '../Base'; import PostRaceMenu from '../menus/PostRaceMenu'; import TeamDashboard from '../../views/TeamDashboard'; import Feed from '../../views/Feed'; import NotFound from '../../views/NotFound'; const mapStateToProps = (state, ownProps) => { return { authenticated: state.auth.login.authenticated } } @connect(mapStateToProps) class Dashboard extends React.Component { render() { if (!this.props.authenticated) { return <Redirect to={{ pathname: '/login', state: { next: '/dashboard' } }}/>; } const { url } = this.props.match; return ( <div className='pt-dark'> <Base/> <PostRaceMenu/> <Switch> <Route exact path={`${url}`}> <TeamDashboard hideChallenges/> </Route> <Route exact path={`${url}/feed`} component={Feed}/> <Route component={NotFound}/> </Switch> </div> ); } } export default Dashboard;
app/App.js
singun/kanban-app
import React from 'react'; import ReactDOM, { render } from 'react-dom'; import { Router, Route } from 'react-router'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import KanbanBoardContainer from './KanbanBoardContainer'; import KanbanBoard from './KanbanBoard'; import EditCard from './EditCard'; import NewCard from './NewCard'; let cards = [ { id: 1, title: "Read the Book", description: "I should read the **whole** book", color: '#BD8D31', status: "in-progress", tasks: [] }, { id: 2, title: "Write some code", description: "Code along with the samples in the book. The complete source can be found at [github](https://github.com/pro-react)", color: '#3A7E28', status: "to do", tasks: [ { id: 1, name: "ContactList Example", done: true }, { id: 2, name: "Kanban Example", done: false }, { id: 3, name: "My own experiments", done: false } ] } ] // ReactDOM.render(<KanbanBoard cards={cards} />, document.getElementById('root')); // ReactDOM.render(<KanbanBoardContainer />, document.getElementById('root')); render(( <Router history={createBrowserHistory()}> <Route component={KanbanBoardContainer}> <Route path="/" component={KanbanBoard}> <Route path="new" component={NewCard} /> <Route path="edit/:card_id" component={EditCard} /> </Route> </Route> </Router> ), document.getElementById('root'));
app/views/listing/add.js
jtparrett/countcals
import React from 'react' import { StyleSheet, View, TextInput, Button } from 'react-native' import Moment from 'moment' import Input from '../../components/input' export default class AddEntry extends React.Component { constructor(props) { super(props) this.state = { ...props, timestamp: props.currentDate.unix(), name: '', calories: '' } } submit = () => { this.state.API.post('foods/add', this.state).then((response) => { this.state.onNewEntry(response.data) this.setState({ name: '', calories: '' }) this.state.closeEvent() }) } render() { return ( <View style={ styles.container }> <Input value={ this.state.name } onChangeText={(value) => { this.setState({ name: value }) }} placeholder="Food name" /> <Input value={ this.state.calories } onChangeText={(value) => { this.setState({ calories: value }) }} placeholder="Calories" keyboardType="numeric" /> <Button title="Submit" onPress={ this.submit }></Button> <Button title="Cancel" onPress={ this.state.closeEvent }></Button> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, margin: 20 } })
src/parser/hunter/shared/modules/talents/BindingShot.js
FaideWW/WoWAnalyzer
import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import React from 'react'; /** * Fires a magical projectile, tethering the enemy and any other enemies within 5 yards for 10 sec, rooting them in place for 5 sec if they move more than 5 yards from the arrow. */ class BindingShot extends Analyzer { _roots = 0; _applications = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.BINDING_SHOT_TALENT.id); } on_byPlayer_applydebuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.BINDING_SHOT_ROOT.id && spellId !== SPELLS.BINDING_SHOT_TETHER.id) { return; } if (spellId === SPELLS.BINDING_SHOT_ROOT.id) { this._roots += 1; } if (spellId === SPELLS.BINDING_SHOT_TETHER.id) { this._applications += 1; } } statistic() { return ( <TalentStatisticBox talent={SPELLS.BINDING_SHOT_TALENT.id} value={`${this._roots} roots / ${this._applications} possible`} /> ); } } export default BindingShot;
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js
fanhc019/react-router
import React from 'react'; import { Link } from 'react-router'; export default class AnnouncementsSidebar extends React.Component { render () { var announcements = COURSES[this.props.params.courseId].announcements; return ( <div> <h3>Sidebar Assignments</h3> <ul> {announcements.map(announcement => ( <li key={announcement.id}> <Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}> {announcement.title} </Link> </li> ))} </ul> </div> ); } }
frontend/src/screens/qa/qa.js
linea-it/qlf
import React, { Component } from 'react'; import Steps from './widgets/steps/steps'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; const styles = { container: { display: 'flex', justifyContent: 'space-around', flexDirection: 'column', marginBottom: '1vh', flex: 1, }, green: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#008000', fontSize: 0, textIndent: '-9999em', }, yellow: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#ffff00', fontSize: 0, textIndent: '-9999em', }, red: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#ff0000', fontSize: 0, textIndent: '-9999em', }, lightgray: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#d3d3d3', fontSize: 0, textIndent: '-9999em', }, black: { display: 'inline-block', verticalAlign: 'top', width: '10px', height: '10px', borderRadius: '50%', border: 'solid 1px #333', background: '#000000', fontSize: 0, textIndent: '-9999em', }, }; class QA extends Component { static propTypes = { exposureId: PropTypes.string, qaTests: PropTypes.array, arms: PropTypes.array.isRequired, spectrographs: PropTypes.array.isRequired, mjd: PropTypes.string, date: PropTypes.string, time: PropTypes.string, navigateToMetrics: PropTypes.func, navigateToProcessingHistory: PropTypes.func, petalSizeFactor: PropTypes.number.isRequired, processId: PropTypes.number, monitor: PropTypes.bool, flavor: PropTypes.string, }; componentDidMount() { document.title = 'QA'; } renderMetrics = (step, spectrographNumber, arm) => { if (this.props.navigateToMetrics) { this.props.navigateToMetrics( step, spectrographNumber, arm, this.props.exposureId ); } }; renderSteps = () => { return ( <Steps navigateToProcessingHistory={this.props.navigateToProcessingHistory} qaTests={this.props.qaTests} renderMetrics={this.renderMetrics} mjd={this.props.mjd} exposureId={this.props.exposureId} date={this.props.date} time={this.props.time} petalSizeFactor={this.props.petalSizeFactor} processId={this.props.processId} monitor={this.props.monitor} flavor={this.props.flavor} /> ); }; render() { return <div style={styles.container}>{this.renderSteps()}</div>; } } export default withStyles(styles)(QA);
CalcScreen.js
stevenpan91/ChemicalEngineerHelper
'use strict' import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Button, TouchableHighlight, TouchableOpacity, TextInput, Navigator } from 'react-native'; class CalcScreen extends Component { render() { return ( <Navigator renderScene={this.renderScene.bind(this)} navigator={this.props.navigator} navigationBar={ <Navigator.NavigationBar style={{backgroundColor: '#246dd5'}} routeMapper={NavigationBarRouteMapper} /> } /> ); } renderScene(route, navigator) { return ( <View style={{flex: 1}}> <TextInput style={{textAlign: 'left', marginTop: 100}}>Input Test</TextInput> <Text style={{textAlign: 'left', marginTop:200}}>Result</Text> </View> ); } // gotoMain() { // this.props.navigator.push({ // id: 'MainScreen', // sceneConfig: Navigator.SceneConfigs.FloatFromBottom, // }); // } } var NavigationBarRouteMapper = { LeftButton(route, navigator, index, nextState) { return ( <TouchableOpacity style={{flex: 1, justifyContent: 'center'}} onPress={() => navigator.parentNavigator.pop()}> <Text style={{color: 'white', margin: 10,}}> Back </Text> </TouchableOpacity> ); }, RightButton(route, navigator, index, nextState) { return ( <TouchableOpacity style={{flex: 1, justifyContent: 'center'}} onPress={() => navigator.parentNavigator.push({id: 'unknown'})}> <Text style={{color: 'white', margin: 10,}}> Test </Text> </TouchableOpacity> ); }, Title(route, navigator, index, nextState) { return ( <TouchableOpacity style={{flex: 1, justifyContent: 'center'}} onPress={() => navigator.push({ id: 'MainScreen', sceneConfig: Navigator.SceneConfigs.FloatFromBottom, })}> <Text style={{color: 'white', margin: 10, fontSize: 16}}> Main Page </Text> </TouchableOpacity> ); } }; module.exports = CalcScreen;
webapp/imports/ui/layouts/SecurityDialog.js
clinical-meteor/meteor-on-fhir
// base layout import { CardHeader, CardText, CardTitle } from 'material-ui/Card'; import PropTypes from 'prop-types'; import { ReactMeteorData } from 'meteor/react-meteor-data'; import ReactMixin from 'react-mixin'; import React, { Component } from 'react'; import FlatButton from 'material-ui/FlatButton'; import { Session } from 'meteor/session'; import Dialog from 'material-ui/Dialog'; import { Container, Col, Row } from 'react-bootstrap'; import { get, has } from 'lodash'; import Interweave from 'interweave'; Session.setDefault('securityDialogOpen', false); Session.setDefault('securityDialogResourceType', ''); Session.setDefault('securityDialogResourceId', ''); Session.setDefault('securityDialogResourceJson', null); Session.setDefault('securityDialogDisplayRawJson', false); export class SecurityDialog extends React.Component { constructor(props) { super(props); } getMeteorData() { let data = { securityDialog: { open: Session.get('securityDialogOpen'), resourceType: Session.get('securityDialogResourceType'), resourceId: Session.get('securityDialogResourceId'), resourceJsonRaw: Session.get('securityDialogResourceJson'), resourceJson: JSON.stringify(Session.get('securityDialogResourceJson'), null, 2) }, fields: { mongoId: '', id: '', narrative: '', versionId: '', lastUpdated: '', sourceUrl: '', securityTags: [], extensions: [], tags: [], profiles: [] }, displayRawJson: Session.get('securityDialogDisplayRawJson') }; if(get(data, 'securityDialog.resourceJsonRaw.text.div')){ data.fields.narrative = get(data, 'securityDialog.resourceJsonRaw.text.div'); } if(get(data, 'securityDialog.resourceJsonRaw.meta.versionId')){ data.fields.versionId = get(data, 'securityDialog.resourceJsonRaw.meta.versionId'); } if(get(data, 'securityDialog.resourceJsonRaw.meta.lastUpdated')){ data.fields.lastUpdated = get(data, 'securityDialog.resourceJsonRaw.meta.lastUpdated'); } if(get(data, 'securityDialog.resourceJsonRaw.meta.source')){ data.fields.sourceUrl = get(data, 'securityDialog.resourceJsonRaw.meta.source'); } if(get(data, 'securityDialog.resourceJsonRaw.id')){ data.fields.id = get(data, 'securityDialog.resourceJsonRaw.id'); } if(get(data, 'securityDialog.resourceJsonRaw._id')){ data.fields.mongoId = get(data, 'securityDialog.resourceJsonRaw._id'); } if(get(data, 'securityDialog.resourceJsonRaw.extension')){ data.securityDialog.resourceJsonRaw.extension.forEach(function(extension){ //let parts = extension.url.split("/"); data.fields.extensions.push(extension.url.split("/")[extension.url.split("/").length - 1]) }) } if(get(data, 'securityDialog.resourceJsonRaw.meta.security')){ data.securityDialog.resourceJsonRaw.meta.security.forEach(function(securityTag){ data.fields.securityTags.push(get(securityTag, 'display')) }) } if(get(data, 'securityDialog.resourceJsonRaw.meta.tag')){ data.securityDialog.resourceJsonRaw.meta.tag.forEach(function(tag){ data.fields.tags.push(get(tag, 'text')) }) } if(get(data, 'securityDialog.resourceJsonRaw.meta.profile')){ data.securityDialog.resourceJsonRaw.meta.profile.forEach(function(profile){ data.fields.profiles.push(get(profile, 'url')) }) } // console.log("SecurityDialog[data]", data); return data; } handleCloseSecurityDialog(){ Session.set('securityDialogOpen', false); } toggleRawDataDisplay(){ Session.toggle('securityDialogDisplayRawJson'); } handleTextareaUpdate(){ } render(){ let securityTagChips = []; this.data.fields.securityTags.forEach(function(tag, index){ securityTagChips.push(<div key={index}> {tag} </div>) }); let profileChips = []; this.data.fields.profiles.forEach(function(tag, index){ profileChips.push(<div key={index}> <a href={tag} target="_blank">{tag}</a> </div>) }); let extensionChips = []; this.data.fields.extensions.forEach(function(tag, index){ extensionChips.push(<div key={index}> {tag} </div>) }); let tagChips = []; this.data.fields.tags.forEach(function(extension, index){ tagChips.push(<div key={index}> {extension} </div>) }); let dialogContent; let toggleButtonText = "Show Raw Data" if(get(this, 'data.displayRawJson')){ toggleButtonText = "Show Metadata Summary" dialogContent = <CardText style={{overflowY: "auto", marginTop: '60px'}}> <textarea id='securityDialogJson' onChange= { this.handleTextareaUpdate } value={get(this, 'data.securityDialog.resourceJson') } style={{width: '100%', position: 'relative', minHeight: '200px', height: '400px', backgroundColor: '#f5f5f5', borderColor: '#ccc', borderRadius: '4px', lineHeight: '16px'}} /> </CardText> } else { let dialogSectionStyle = { minHeight: '80px' } dialogContent = <CardText style={{overflowY: "auto", marginTop: '60px'}}> {/* <div style={dialogSectionStyle}> <Row> <Col md={4}> <h4>Source Id</h4> {get(this, 'data.fields.id')} </Col> <Col md={4}> <h4>Version</h4> {get(this, 'data.fields.versionId')} </Col> <Col md={4}> <h4>Last Updated</h4> {get(this, 'data.fields.lastUpdated')} </Col> </Row> </div> */} <div style={dialogSectionStyle}> <h4>Narrative</h4> <pre> <Interweave content={get(this, 'data.fields.narrative')} // matchers={[new UrlMatcher('url'), new HashtagMatcher('hashtag')]} /> <br /> </pre> </div> <Row> <Col md={6}> <div style={dialogSectionStyle}> <h4>Version: </h4> {get(this, 'data.fields.versionId')} </div> <div style={dialogSectionStyle}> <h4>Last Updated</h4> {get(this, 'data.fields.lastUpdated')} </div> <div style={dialogSectionStyle}> <h4>Source</h4> {get(this, 'data.fields.sourceUrl')} </div> <div style={dialogSectionStyle}> <h4>Source ID</h4> {get(this, 'data.fields.id')} </div> </Col> <Col md={6}> <div style={dialogSectionStyle}> <h4>Extentions</h4> {extensionChips} </div> <div style={dialogSectionStyle}> <h4>Profile</h4> {profileChips} </div> <div style={dialogSectionStyle}> <h4>Security Tags</h4> {securityTagChips} </div> <div style={dialogSectionStyle}> <h4>Tags</h4> {tagChips} </div> </Col> </Row> </CardText> } const securityActions = [ <FlatButton label={toggleButtonText} primary={true} onClick={this.toggleRawDataDisplay} style={{float: 'left'}} />, <FlatButton label="Close" primary={true} keyboardFocused={true} onClick={this.handleCloseSecurityDialog} /> ]; let cardTitle = "Resource Metadata"; return ( <Dialog actions={securityActions} modal={false} open={this.data.securityDialog.open} onRequestClose={this.handleCloseSecurityDialog} style={{minHeight: '560px'}} > <Row id='metaDataHeader' style={{height: '80px', position: 'absolute', width: '100%'}}> <CardTitle title="Metadata" /> <CardTitle title={get(this, 'data.fields.mongoId')} style={{right: '10px', position: 'absolute', top: '0px'}} className="barcode" /> </Row> { dialogContent } </Dialog> ); } } ReactMixin(SecurityDialog.prototype, ReactMeteorData); export default SecurityDialog;
src/svg-icons/action/history.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHistory = (props) => ( <SvgIcon {...props}> <path d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"/> </SvgIcon> ); ActionHistory = pure(ActionHistory); ActionHistory.displayName = 'ActionHistory'; ActionHistory.muiName = 'SvgIcon'; export default ActionHistory;
node_modules/react-bootstrap/es/ModalBody.js
newphew92/newphew92.github.io
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var ModalBody = function (_React$Component) { _inherits(ModalBody, _React$Component); function ModalBody() { _classCallCheck(this, ModalBody); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ModalBody.prototype.render = function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('div', _extends({}, elementProps, { className: classNames(className, classes) })); }; return ModalBody; }(React.Component); export default bsClass('modal-body', ModalBody);
src/components/EntryEditor/__tests__/EntryEditorToolbar.spec.js
dopry/netlify-cms
import React from 'react'; import { shallow } from 'enzyme'; import EntryEditorToolbar from '../EntryEditorToolbar'; describe('EntryEditorToolbar', () => { it('should have the Save button disabled initally, and the Cancel button enabled', () => { const component = shallow( <EntryEditorToolbar onPersist={() => {}} onCancelEdit={() => {}} onDelete={() => {}} /> ); const tree = component.html(); expect(tree).toMatchSnapshot(); }); it('should enable the Save button', () => { const component = shallow( <EntryEditorToolbar enableSave onPersist={() => {}} onCancelEdit={() => {}} onDelete={() => {}} /> ); const tree = component.html(); expect(tree).toMatchSnapshot(); }); it('should disable and update label of Save button when persisting', () => { const component = shallow( <EntryEditorToolbar isPersisting onPersist={() => {}} onCancelEdit={() => {}} onDelete={() => {}} /> ); const tree = component.html(); expect(tree).toMatchSnapshot(); }); });
example/src/TabOne.js
PlexChat/mobx-navigation
import React from 'react'; import { Button, Text, TextInput, StyleSheet, View } from 'react-native'; import { inject, observer } from 'mobx-react'; import { scene } from '../..'; import Circular from './Circular'; const styles = StyleSheet.create({ test: { backgroundColor: 'green', }, }); @scene('Tab1') @inject('testStore') @observer export class Tab1 extends React.Component { static navConfig = { tabAffinity: '1', tabBarVisible: true, navBarVisible: true, cardStyle: styles.test, templates: ['test'], }; onPress = () => { this.props.navState.push('Tab1Scene1'); }; onPress2 = () => { this.props.navState.push('Tab1Scene1Alt'); }; onPress3 = () => { this.props.navState.push('Tab2Scene1', { custom: ' there' }); }; onPress4 = () => { this.props.navState.push('Circular'); } onPress5 = () => { this.props.navState.reset(); } render() { return ( <View style={{ flex: 1 }}> <Button title={'scene 1'} onPress={this.onPress} style={{ backgroundColor: 'white' }} /> <Button title={'scene 1 alt'} onPress={this.onPress2} style={{ backgroundColor: 'white' }} /> <Button title={'Tab 2 scene 1'} onPress={this.onPress3} style={{ backgroundColor: 'white' }} /> <Button title={'Circular'} onPress={this.onPress4} /> <Button title={'reset'} onPress={this.onPress5} /> <Text style={{ color: 'white' }} > {this.props.testStore.data} </Text> </View> ); } } @scene class Tab1Scene1 extends React.Component { static navConfig = { custom: { myCustomConfig: 'custom config', }, navBarCenter: (props) => { return ( <View> <Text> {'Common config'} </Text> </View> ); } }; static multiNavConfig = { Tab1Scene1: { tabAffinity: '1', tabBarVisible: true, navBarVisible: true, }, Tab1Scene1Alt: { tabAffinity: '1', tabBarVisible: true, navBarVisible: true, navBarLeftDisabled: true, navBarStyle: { backgroundColor: 'red', } } } render() { return ( <View style={{ flex: 1, backgroundColor: 'green' }}> <Text> {this.props.navState.frontCustomConfig.myCustomConfig} </Text> <TextInput style={{ height: 40, borderColor: 'blue', borderWidth: 1 }} value="Test tab bar visibility" /> <Button title="Tab1Scene2" onPress={() => this.props.navState.push('Tab1Scene2')} /> </View> ); } } @scene('Tab1Scene2') export class Tab1Scene2 extends React.Component { static navConfig = { tabAffinity: '1', tabBarVisible: true, navBarVisible: true, }; render() { return ( <View style={{ flex: 1 }}> <Text> Tab 1 scene 2 </Text> <Button title="Tab1Scene3" onPress={() => this.props.navState.push('Tab1Scene3')} /> </View> ) } } @scene('Tab1Scene3') class Tab1Scene3 extends React.Component { static navConfig = { tabAffinity: '1', tabBarVisible: true, navBarVisible: true, }; render() { return ( <View style={{ flex: 1 }}> <Text> Tab 1 scene 3 </Text> <Button title="Pop to scene 1" onPress={() => this.props.navState.popTo('Tab1Scene1')} /> <Button title="Pop three times" onPress={() => this.props.navState.pop(3)} /> </View> ); } } export const CircularChild = (props) => { return ( <View> <Text> {props.message} </Text> </View> ) }
packages/watif-display/src/components/interactive-description.js
jwillesen/watif
import React from 'react' import {string, element, func, arrayOf} from 'prop-types' import Watext from './watext' import VerbBar from './verb-bar' import {verbShape} from '../property-shapes' import './interactive-description.css' export default class InteractiveDescription extends React.Component { static propTypes = { title: string, emptyText: string, watext: element, verbs: arrayOf(verbShape), onItemClick: func, // (item-id) onVerbClick: func, // (item-id, verb-id) } static defaultProps = { emptyText: 'No text', } watext() { if (this.props.watext) { return ( <div> <Watext watext={this.props.watext} onItemClick={this.props.onItemClick} /> </div> ) } return <div styleName="no-text">{this.props.emptyText}</div> } render() { return ( <div styleName="root"> <h2 styleName="heading">{this.props.title}</h2> <div styleName="content"> {this.watext()} <div styleName="verbs"> <VerbBar verbs={this.props.verbs} onVerbClick={this.props.onVerbClick} /> </div> </div> </div> ) } }
app/routes/index.js
vasanthk/redux-blog-example
import React from 'react'; import { Route } from 'react-router'; import App from './App'; import SignupRoute from './SignupRoute'; import LoginRoute from './LoginRoute'; import ProfileRoute from './ProfileRoute'; import NotFound from '../components/NotFound'; import redirectBackAfter from '../utils/redirectBackAfter'; import fillStore from '../utils/fillStore'; import DashboardRoute from './DashboardRoute'; import * as Posts from './Posts'; const routes = ( <Route component={App}> <Route path="/signup" component={SignupRoute} /> <Route path="/login" component={LoginRoute} /> <Route path="/" component={Posts.List} /> <Route path="/posts/:id" component={Posts.View} /> <Route requireAuth> <Route path="/profile" component={ProfileRoute} /> <Route path="/dashboard" component={DashboardRoute} /> <Route path="/dashboard/add" component={Posts.Edit} /> <Route path="/dashboard/edit/:id" component={Posts.Edit} /> </Route> <Route path="*" component={NotFound} /> </Route> ); function walk(routes, cb) { cb(routes); if (routes.childRoutes) { routes.childRoutes.forEach(route => walk(route, cb)); } return routes; } export default (store, client) => { return walk(Route.createRouteFromReactElement(routes), route => { route.onEnter = (nextState, transition) => { const loggedIn = !!store.getState().auth.token; if (route.requireAuth && !loggedIn) { transition.to(...redirectBackAfter('/login', nextState)); } else if (client) { fillStore(store, nextState, [route.component]); } }; }); };
node_modules/react-router/es6/IndexRoute.js
Win-Myint/ReactChallenge2
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils'; import { component, components, falsy } from './InternalPropTypes'; var func = React.PropTypes.func; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ var IndexRoute = React.createClass({ displayName: 'IndexRoute', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = _createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0; } } }, propTypes: { path: falsy, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRoute;
docs/src/examples/modules/Modal/Usage/ModalExampleCallbacks.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Button, Grid, Label, Modal, Segment } from 'semantic-ui-react' function exampleReducer(state, action) { switch (action.type) { case 'CLEAR_LOG': return { ...state, log: [] } case 'OPEN_MODAL': return { log: [ { event: action.event, date: new Date().toLocaleTimeString(), name: action.name, value: true, }, ...state.log, ], open: true, } case 'CLOSE_MODAL': return { log: [ { event: action.event, date: new Date().toLocaleTimeString(), name: action.name, value: true, }, ...state.log, ], open: false, } default: throw new Error() } } function ModalExampleCloseConfig() { const [state, dispatch] = React.useReducer(exampleReducer, { log: [], open: false, }) const { log, open } = state return ( <Grid> <Grid.Column width={4}> <Modal onOpen={(e) => dispatch({ event: e.type, name: 'onOpen', type: 'OPEN_MODAL' }) } onClose={(e) => dispatch({ event: e.type, name: 'onClose', type: 'CLOSE_MODAL' }) } open={open} trigger={<Button>Open a modal</Button>} > <Modal.Header>Delete Your Account</Modal.Header> <Modal.Content> <p>Are you sure you want to delete your account</p> </Modal.Content> <Modal.Actions> <Button onClick={(e) => dispatch({ event: e.type, name: 'onClick', type: 'CLOSE_MODAL', }) } negative > No </Button> <Button onClick={(e) => dispatch({ event: e.type, name: 'onClick', type: 'CLOSE_MODAL', }) } positive > Yes </Button> </Modal.Actions> </Modal> </Grid.Column> <Grid.Column width={12}> {log.length > 0 && ( <Segment attached='top' secondary> {log.map((entry, i) => ( <pre key={i}> [{entry.date}] {entry.name} ( {JSON.stringify({ e: { type: entry.event }, data: { open: entry.value }, })} ) </pre> ))} </Segment> )} <Segment attached={log.length > 0 ? 'bottom' : undefined} secondary> <Label>Entries: {log.length}</Label> <Button compact floated='right' onClick={() => dispatch({ type: 'CLEAR_LOG' })} size='tiny' > Clear </Button> </Segment> </Grid.Column> </Grid> ) } export default ModalExampleCloseConfig
tests/components/Header/Header.spec.js
arleighdickerson/react-redux-express
import React from 'react' import { Header } from 'components/Header/Header' import { IndexLink, Link } from 'react-router' import { shallow } from 'enzyme' describe('(Component) Header', () => { let _wrapper beforeEach(() => { _wrapper = shallow(<Header />) }) it('Renders a welcome message', () => { const welcome = _wrapper.find('h1') expect(welcome).to.exist expect(welcome.text()).to.match(/React Redux Starter Kit/) }) describe('Navigation links...', () => { it('Should render a Link to Home route', () => { expect(_wrapper.contains( <IndexLink activeClassName='route--active' to='/'> Home </IndexLink> )).to.be.true }) it('Should render a Link to Counter route', () => { expect(_wrapper.contains( <Link activeClassName='route--active' to='/counter'> Counter </Link> )).to.be.true }) }) })
cm19/ReactJS/your-first-react-app-exercises-master/exercise-16/complete/friends/Friends.entry.js
Brandon-J-Campbell/codemash
import React from 'react'; import getFriendsFromApi from './get-friends-from-api'; import Friends from './Friends'; export default class FriendsEntry extends React.Component { state = { friends: [] } async componentDidMount() { const friends = await getFriendsFromApi(); this.setState({ friends }); } render() { return <Friends friends={this.state.friends} />; } }
pilgrim3/components/optionsTable.js
opendoor-labs/pilgrim3
import React from 'react' import { map } from 'lodash' export default class OptionsTable extends React.Component { optionRow(value, key) { return ( <tr key={`${key}-${value}`}> <th>{key}</th> <td>{value.toString()}</td> </tr> ); } render() { if (!this.props.object) { return (<span/>); } else { return ( <table className='table table-hover'> <tbody> {map(this.props.object.options, this.optionRow)} </tbody> </table> ); } } }
src/svg-icons/image/linked-camera.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLinkedCamera = (props) => ( <SvgIcon {...props}> <circle cx="12" cy="14" r="3.2"/><path d="M16 3.33c2.58 0 4.67 2.09 4.67 4.67H22c0-3.31-2.69-6-6-6v1.33M16 6c1.11 0 2 .89 2 2h1.33c0-1.84-1.49-3.33-3.33-3.33V6"/><path d="M17 9c0-1.11-.89-2-2-2V4H9L7.17 6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9h-5zm-5 10c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/> </SvgIcon> ); ImageLinkedCamera = pure(ImageLinkedCamera); ImageLinkedCamera.displayName = 'ImageLinkedCamera'; export default ImageLinkedCamera;
app/assets/scripts/views/about.js
openaq/openaq.github.io
'use strict'; import React from 'react'; import { connect } from 'react-redux'; import _ from 'lodash'; import JoinFold from '../components/join-fold'; import SponsorList from '../components/sponsor-list'; import TeamList from '../components/team-list'; import content from '../../content/content.json'; import sponsors from '../../content/sponsors.json'; const teamData = { advisoryBoard: _(content.advisoryBoard) .values() .sortBy(['order']) .value(), governingBoard: _(content.governingBoard) .values() .sortBy(['order']) .value(), team: _(content.team) .values() .sortBy(['order']) .value() }; var About = React.createClass({ displayName: 'About', propTypes: { }, render: function () { return ( <section className='inpage'> <header className='inpage__header'> <div className='inner'> <div className='inpage__headline'> <h1 className='inpage__title'>About us</h1> <div className='inpage__introduction'> <p>Our mission is to fight air inequality by opening up air quality data and connecting a diverse global, grassroots community of individuals and organizations.</p> </div> </div> </div> <figure className='inpage__media inpage__media--cover media'> <div className='media__item'> <img src='/assets/graphics/content/view--about/cover--about.jpg' alt='Cover image' width='1440' height='712' /> </div> </figure> </header> <div className='inpage__body'> <section className='fold fold--intro' id='about-fold-intro'> <div className='inner'> <header className='fold__header'> <h1 className='fold__title'>We are guided by principles</h1> </header> <ul className='principles-list'> <li> <article className='card card--principle'> <div className='card__contents'> <figure className='card__media'> <div className='card__badge'> <img src='/assets/graphics/layout/oaq-icon-illu-48-historical.svg' width='40' height='40' alt='Illustration' /> </div> </figure> <header className='card__header'> <div className='card__headline'> <h1 className='card__title'>Historical + Programmatic access</h1> </div> </header> <div className='card__body'> <div className='card__prose prose prose--responsive'> <p>Giving air quality data a wider audience.</p> </div> </div> </div> </article> </li> <li> <article className='card card--principle'> <div className='card__contents'> <figure className='card__media'> <div className='card__badge'> <img src='/assets/graphics/layout/oaq-icon-illu-48-opensource.svg' width='40' height='40' alt='Illustration' /> </div> </figure> <header className='card__header'> <div className='card__headline'> <h1 className='card__title'>Open source</h1> </div> </header> <div className='card__body'> <div className='card__prose prose prose--responsive'> <p>Encouraging collaboration in the open.</p> </div> </div> </div> </article> </li> <li> <article className='card card--principle'> <div className='card__contents'> <figure className='card__media'> <div className='card__badge'> <img src='/assets/graphics/layout/oaq-icon-illu-48-community.svg' width='40' height='40' alt='Illustration' /> </div> </figure> <header className='card__header'> <div className='card__headline'> <h1 className='card__title'>Community driven</h1> </div> </header> <div className='card__body'> <div className='card__prose prose prose--responsive'> <p>Working to help each other do impactful work.</p> </div> </div> </div> </article> </li> </ul> </div> </section> <section className='fold fold--type-a' id='about-fold-story'> <div className='inner'> <header className='fold__header'> <h1 className='fold__title'>Our story</h1> <div className='fold__teaser prose prose--responsive'> <p>The idea for OpenAQ came from observing the impact of a lone air quality monitor producing open data, set up by the U.S. Embassy in Beijing.</p> <p>It spurred OpenAQ co-founders, Christa Hasenkopf, an atmospheric scientist, and Joe Flasher, a software developer, to set up a small open air quality project in Ulaanbaatar along with Mongolian colleagues.</p> <p>Eventually, they and a community of open data lovers from around the world decided to see what would happen if all of the world’s air quality data were made available for the public to explore.</p> </div> </header> <figure className='fold__media'> <aside className='aside-highlight'> <div className='aside-highlight__contents'> <div className='aside-highlight__prose'> <p>What if all of the world’s air quality data were available to explore?</p> </div> </div> </aside> </figure> </div> </section> <section className='fold fold--stacked' id='about-fold-main-board'> <div className='inner'> <header className='fold__header'> <h1 className='fold__title'>Our Team</h1> <div className='fold__teaser prose prose--responsive'> <p>Our team is passionate about fighting air inequality with open data. If you would like to make an inquiry to the team, please reach out to <a href='mailto:info@openaq.org'>info@openaq.org</a></p> </div> </header> <TeamList items={teamData.team} /> </div> </section> <section className='fold fold--stacked' id='about-fold-main-board'> <div className='inner'> <header className='fold__header'> <h1 className='fold__title'>Our Board</h1> <div className='fold__teaser prose prose--responsive'> <p>The Governing Board oversees the legal and financial operations of OpenAQ. If you would like to make an inquiry to the board, please reach out to <a href='mailto:info@openaq.org'>info@openaq.org</a>.</p> </div> </header> <TeamList items={teamData.governingBoard} /> </div> </section> <section className='fold fold--stacked' id='about-fold-advisory-board'> <div className='inner'> <header className='fold__header'> <h1 className='fold__title'>Our Advisory Board</h1> <div className='fold__teaser prose prose--responsive'> <p>The Advisory Board consists of world-class leaders in air quality, public health, and open data. The board advises OpenAQ on its overall strategy.</p> </div> </header> <TeamList items={teamData.advisoryBoard} /> </div> </section> <section className='fold fold--semi-light' id='about-fold-sponsors'> <div className='inner'> <header className='fold__header'> <h1 className='fold__title'>Partners and Sponsors</h1> </header> <SponsorList items={sponsors} /> <footer className='fold__footer'> <a href='mailto:info@openaq.org' className='sponsor-button' title='View page'><span>Become a sponsor</span></a> </footer> </div> </section> <section className='fold fold--type-b' id='about-fold-book'> <div className='inner'> <header className='fold__header'> <h1 className='fold__title'>We are an open book</h1> <div className='fold__teaser prose prose--responsive'> <p>We value transparency so all our records are publicly available.</p> <p className='fold__main-action'> <a href='/assets/files/openaq-990-2019.pdf' target='_blank' className='button-book-download' title='Download'><span>Download 2019 Form 990</span></a> </p> </div> </header> <figure className='fold__media'> <article className='card card--book'> <a href='/assets/files/openaq-990-2019.pdf' target='_blank' className='card__contents' title='Download'> <header className='card__header'> <div className='card__headline'> <p className='card__subtitle'>2019</p> <h1 className='card__title'>Form 990</h1> </div> </header> <figure className='card__media'> <div className='card__thumb'> <img src='/assets/graphics/content/view--about/card-book-media.jpg' width='724' height='348' alt='Card media' /> </div> </figure> <footer className='card__footer'> <img src='/assets/graphics/layout/oaq-logo-col-pos.svg' alt='OpenAQ logotype' width='72' height='40' /> </footer> </a> </article> </figure> </div> </section> <JoinFold /> </div> </section> ); } }); // /////////////////////////////////////////////////////////////////// // // Connect functions function selector (state) { return { }; } function dispatcher (dispatch) { return { }; } module.exports = connect(selector, dispatcher)(About);
actor-apps/app-web/src/app/components/modals/invite-user/InviteByLink.react.js
liruqi/actor-platform-v0.9
import { assign } from 'lodash'; import React from 'react'; import Modal from 'react-modal'; import addons from 'react/addons'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import { Styles, FlatButton, Snackbar } from 'material-ui'; import ReactZeroClipboard from 'react-zeroclipboard'; import classnames from 'classnames'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import InviteUserByLinkActions from 'actions/InviteUserByLinkActions'; import InviteUserActions from 'actions/InviteUserActions'; import InviteUserStore from 'stores/InviteUserStore'; const ThemeManager = new Styles.ThemeManager(); const appElement = document.getElementById('actor-web-app'); Modal.setAppElement(appElement); const {addons: { PureRenderMixin }} = addons; const getStateFromStores = () => { return { isShown: InviteUserStore.isInviteWithLinkModalOpen(), group: InviteUserStore.getGroup(), inviteUrl: InviteUserStore.getInviteUrl() }; }; @ReactMixin.decorate(IntlMixin) @ReactMixin.decorate(PureRenderMixin) class InviteByLink extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); this.state = assign({ isCopyButtonEnabled: false }, getStateFromStores()); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ button: { minWidth: 60 } }); InviteUserStore.addChangeListener(this.onChange); document.addEventListener('keydown', this.onKeyDown, false); } componentWillUnmount() { InviteUserStore.removeChangeListener(this.onChange); document.removeEventListener('keydown', this.onKeyDown, false); } render() { const { group } = this.state; const { inviteUrl, isShown, isCopyButtonEnabled } = this.state; const snackbarStyles = ActorTheme.getSnackbarStyles(); let groupName; if (group !== null) { groupName = <b>{group.name}</b>; } const copyButtonClassname = classnames('button button--blue pull-right', { 'hide': !isCopyButtonEnabled }); return ( <Modal className="modal-new modal-new--invite-by-link" closeTimeoutMS={150} isOpen={isShown} style={{width: 400}}> <header className="modal-new__header"> <svg className="modal-new__header__icon icon icon--blue" dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#back"/>'}} onClick={this.onBackClick}/> <h3 className="modal-new__header__title"> <FormattedMessage message={this.getIntlMessage('inviteByLinkModalTitle')}/> </h3> <div className="pull-right"> <FlatButton hoverColor="rgba(81,145,219,.17)" label="Done" labelStyle={{padding: '0 8px'}} onClick={this.onClose} secondary={true} style={{marginTop: -6}}/> </div> </header> <div className="modal-new__body"> <FormattedMessage groupName={groupName} message={this.getIntlMessage('inviteByLinkModalDescription')}/> <textarea className="invite-url" onClick={this.onInviteLinkClick} readOnly row="3" value={inviteUrl}/> </div> <footer className="modal-new__footer"> <button className="button button--light-blue pull-left hide"> <FormattedMessage message={this.getIntlMessage('inviteByLinkModalRevokeButton')}/> </button> <ReactZeroClipboard onCopy={this.onInviteLinkCopied} onReady={this.onZeroclipboardReady} text={inviteUrl}> <button className={copyButtonClassname}> <FormattedMessage message={this.getIntlMessage('inviteByLinkModalCopyButton')}/> </button> </ReactZeroClipboard> </footer> <Snackbar autoHideDuration={3000} message={this.getIntlMessage('inviteLinkCopied')} ref="inviteLinkCopied" style={snackbarStyles}/> </Modal> ); } onClose = () => { InviteUserByLinkActions.hide(); }; onBackClick = () => { this.onClose(); InviteUserActions.show(this.state.group); }; onInviteLinkClick = event => { event.target.select(); }; onChange = () => { this.setState(getStateFromStores()); }; onKeyDown = (event) => { if (event.keyCode === KeyCodes.ESC) { event.preventDefault(); this.onClose(); } }; onInviteLinkCopied = () => { this.refs.inviteLinkCopied.show(); }; onZeroclipboardReady = () => { this.setState({isCopyButtonEnabled: true}); }; } export default InviteByLink;
lib/components/Application.js
sljohnson32/networkr
import React, { Component } from 'react'; import firebase, { signIn, signOut } from '../firebase'; import { pick, map, extend } from 'lodash'; import WelcomeScreen from './WelcomeScreen'; import HomeScreen from './HomeScreen'; import moment from 'moment' export default class Application extends Component { constructor() { super(); this.state = { user: null, contactDatabase: [], contactzz: [], }; } componentDidMount() { firebase.auth().onAuthStateChanged(user => { this.createDatabaseRef(user) }); } createDatabaseRef(user) { this.setState({ user, contactDatabase: user ? firebase.database().ref(user.uid) : null, }, () => { this.createDatabaseListener(user); } ); } createDatabaseListener(user) { if (user) { firebase.database().ref(user.uid).on('value', (snapshot) => { const contactzz = snapshot.val() || {}; this.setState({ contactzz: map(contactzz, (val, key) => extend(val, { key })), }); }); } else { this.setState({ contactzz: [], }); } } addNewContact(newContact) { const newContactData = pick(newContact, 'contactID', 'existingContact','firstName', 'lastName', 'organization', 'email', 'socialFB', 'gitHub', 'twitter', 'followUp', 'notes', 'createdAt') this.state.contactDatabase.child(newContact.contactID).set(newContactData); } editContact(updatedContact) { const id = updatedContact.contactID; this.state.contactDatabase.child(id).update(updatedContact); } render() { const { user, contactzz } = this.state; return ( <div className="Application"> <div className='header'> <h1>Networkr</h1> </div> { user ? <HomeScreen user={ user } contactzz={ contactzz } addNewContact={ this.addNewContact.bind(this) } editContact={ this.editContact.bind(this) } signOut={ signOut.bind(this) } /> : <WelcomeScreen signIn={ signIn.bind(this) } /> } </div> ); } }
src/components/Background.js
shoegazer/shuffle-guru
import React from 'react' import {connect} from 'react-redux' @connect(state => ({ cover: state.track.current.cover })) class Background extends React.Component { render() { return pug`#background(style=${this.props.cover ? {backgroundImage: 'url(' + this.props.cover + ')'} : {}})`; } } export default Background
examples/Autocomplete.js
react-materialize/react-materialize
import React from 'react'; import Autocomplete from '../src/Autocomplete'; import Row from '../src/Row'; export default <Row> <Autocomplete title='Company' data={ { 'Apple': null, 'Microsoft': null, 'Google': 'http://placehold.it/250x250' } } /> </Row>;
examples/src/components/RemoteSelectField.js
nightwolfz/react-select
import React from 'react'; import Select from 'react-select'; var RemoteSelectField = React.createClass({ displayName: 'RemoteSelectField', propTypes: { hint: React.PropTypes.string, label: React.PropTypes.string, }, loadOptions (input, callback) { input = input.toLowerCase(); var rtn = { options: [ { label: 'One', value: 'one' }, { label: 'Two', value: 'two' }, { label: 'Three', value: 'three' } ], complete: true }; if (input.slice(0, 1) === 'a') { if (input.slice(0, 2) === 'ab') { rtn = { options: [ { label: 'AB', value: 'ab' }, { label: 'ABC', value: 'abc' }, { label: 'ABCD', value: 'abcd' } ], complete: true }; } else { rtn = { options: [ { label: 'A', value: 'a' }, { label: 'AA', value: 'aa' }, { label: 'AB', value: 'ab' } ], complete: false }; } } else if (!input.length) { rtn.complete = false; } setTimeout(function() { callback(null, rtn); }, 500); }, renderHint () { if (!this.props.hint) return null; return ( <div className="hint">{this.props.hint}</div> ); }, render () { return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select asyncOptions={this.loadOptions} className="remote-example" /> {this.renderHint()} </div> ); } }); module.exports = RemoteSelectField;
src/Parser/Mage/Frost/Modules/Items/Tier20_2set.js
enragednuke/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import Combatants from 'Parser/Core/Modules/Combatants'; import Analyzer from 'Parser/Core/Analyzer'; import HIT_TYPES from 'Parser/Core/HIT_TYPES'; import getDamageBonus from 'Parser/Mage/Shared/Modules/GetDamageBonus'; import ItemDamageDone from 'Main/ItemDamageDone'; const FROZEN_MASS_DAMAGE_BONUS = 0.2; /** * Frost Mage Tier20 2set * Frozen Orb increases your critical strike damage by 20% for 10 sec. */ class Tier20_2set extends Analyzer { static dependencies = { combatants: Combatants, }; damage = 0; on_initialized() { this.active = this.combatants.selected.hasBuff(SPELLS.FROST_MAGE_T20_2SET_BONUS_BUFF.id); } on_byPlayer_damage(event) { if (event.hitType !== HIT_TYPES.CRIT) { return; } if (this.combatants.selected.hasBuff(SPELLS.FROZEN_MASS.id)) { this.damage += getDamageBonus(event, FROZEN_MASS_DAMAGE_BONUS); } } item() { return { id: SPELLS.FROST_MAGE_T20_2SET_BONUS_BUFF.id, icon: <SpellIcon id={SPELLS.FROST_MAGE_T20_2SET_BONUS_BUFF.id} />, title: <SpellLink id={SPELLS.FROST_MAGE_T20_2SET_BONUS_BUFF.id} />, result: <ItemDamageDone amount={this.damage} />, }; } } export default Tier20_2set;