path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/index.js
tech-dojo/React-Task-Manager
import React from 'react'; import ReactDOM from 'react-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import ManagerView from './component/manager/managerView.js' import ProgrammerView from './component/programmer/programmerView' import ProgrammerTask from './component/programmer/programmerTask.js'; import TaskList from './component/manager/taskList.js'; import {browserHistory} from 'react-router'; import {Router, Route, IndexRoute} from 'react-router'; import CreateUser from './component/manager/createuser.js'; import UserSignIn from './component/manager/userSignin.js'; import injectTapEventPlugin from 'react-tap-event-plugin'; function loggedIn() { return retrievUser.user_type; } function isManager(retrievUser) { return retrievUser.user_type==='Manager' } function isProgrammer(retrievUser) { return retrievUser.user_type==='Programmer' } function requireAuth(nextState, replace) { var retrievUser = JSON.parse(localStorage.getItem('localStore')); if (retrievUser=== undefined || retrievUser===null) { replace({ pathname: '/userSignin' }) } else if(!isManager(retrievUser)) { replace({ pathname: '/userSignin' }) } } function requireAuthBeta(nextState, replace) { var retrievUser = JSON.parse(localStorage.getItem('localStore')); if (retrievUser=== undefined || retrievUser===null) { replace({ pathname: '/userSignin' }) } else if(!isProgrammer(retrievUser)) { replace({ pathname: '/userSignin' }) } } injectTapEventPlugin(); const App = () => { return ( <MuiThemeProvider> <Router history={browserHistory}> <Route path="/" component={ManagerView} onEnter={requireAuth} > <IndexRoute component={TaskList} /> <Route path="taskList" component={TaskList}/> </Route> <Route path="/programmerView" component={ProgrammerView} onEnter={requireAuthBeta}> <IndexRoute component={ProgrammerTask}/> <Route path="programmerView" component={ProgrammerTask}/> </Route> <Route path="userSignin" component={UserSignIn}/> <Route path="createUser" component={CreateUser}/> </Router> </MuiThemeProvider> ) }; ReactDOM.render( <App/>, document.getElementById('root'));
client/extensions/woocommerce/app/order/order-fulfillment/index.js
Automattic/woocommerce-connect-client
/** @format */ /** * External dependencies */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import classNames from 'classnames'; import { connect } from 'react-redux'; import { first, includes } from 'lodash'; import Gridicon from 'gridicons'; import { localize } from 'i18n-calypso'; /** * Internal dependencies */ import { areLabelsEnabled, getSelectedPaymentMethodId, } from 'woocommerce/woocommerce-services/state/label-settings/selectors'; import { areLabelsFullyLoaded, getLabels, isLabelDataFetchError, } from 'woocommerce/woocommerce-services/state/shipping-label/selectors'; import { ACCEPTED_USPS_ORIGIN_COUNTRIES, US_MILITARY_STATES, DOMESTIC_US_TERRITORIES, } from 'woocommerce/woocommerce-services/state/shipping-label/constants'; import { areSettingsGeneralLoaded, getStoreLocation, } from 'woocommerce/state/sites/settings/general/selectors'; import Button from 'components/button'; import { createNote } from 'woocommerce/state/sites/orders/notes/actions'; import Dialog from 'components/dialog'; import FormFieldset from 'components/forms/form-fieldset'; import FormLabel from 'components/forms/form-label'; import FormInputCheckbox from 'components/forms/form-checkbox'; import FormTextInput from 'components/forms/form-text-input'; import { isOrderFinished } from 'woocommerce/lib/order-status'; import { isOrderUpdating } from 'woocommerce/state/sites/orders/selectors'; import { isWcsEnabled, isWcsInternationalLabelsEnabled } from 'woocommerce/state/selectors/plugins'; import LabelPurchaseModal from 'woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal'; import Notice from 'components/notice'; import { openPrintingFlow } from 'woocommerce/woocommerce-services/state/shipping-label/actions'; import QueryLabels from 'woocommerce/woocommerce-services/components/query-labels'; import QuerySettingsGeneral from 'woocommerce/components/query-settings-general'; import { saveOrder } from 'woocommerce/state/sites/orders/actions'; class OrderFulfillment extends Component { static propTypes = { order: PropTypes.shape( { id: PropTypes.number.isRequired, } ), site: PropTypes.shape( { ID: PropTypes.number.isRequired, slug: PropTypes.string.isRequired, } ), }; state = { errorMessage: false, shouldEmail: false, showDialog: false, trackingNumber: '', }; toggleDialog = event => { event && event.preventDefault(); this.setState( { showDialog: ! this.state.showDialog, } ); }; updateTrackingNumber = event => { this.setState( { errorMessage: false, trackingNumber: event.target.value, } ); }; updateCustomerEmail = () => { this.setState( { errorMessage: false, shouldEmail: ! this.state.shouldEmail, } ); }; submit = () => { const { order, site, translate } = this.props; const { shouldEmail, trackingNumber } = this.state; if ( shouldEmail && ! trackingNumber ) { this.setState( { errorMessage: translate( 'Please enter a tracking number.' ) } ); return; } this.props.saveOrder( site.ID, { id: order.id, status: 'completed', } ); this.toggleDialog(); const note = { note: translate( 'Your order has been shipped. The tracking number is %(trackingNumber)s.', { args: { trackingNumber }, } ), customer_note: shouldEmail, }; if ( trackingNumber ) { this.props.createNote( site.ID, order.id, note ); } }; getOrderFulfilledMessage = () => { const { labelsLoaded, labels, translate } = this.props; const unknownCarrierMessage = translate( 'Order has been fulfilled' ); if ( ! labelsLoaded || ! labels.length ) { return unknownCarrierMessage; } const label = first( this.props.labels ); if ( ! label || 'usps' !== label.carrier_id ) { return unknownCarrierMessage; } return translate( 'Order has been fulfilled and will be shipped via USPS' ); }; getFulfillmentStatus = () => { const { order, translate } = this.props; switch ( order.status ) { case 'completed': return this.getOrderFulfilledMessage(); case 'cancelled': return translate( 'Order has been cancelled' ); case 'refunded': return translate( 'Order has been refunded' ); case 'failed': return translate( 'Order has failed' ); default: return translate( 'Order needs to be fulfilled' ); } }; isAddressValidForLabels( address, type ) { if ( this.props.internationalLabelsEnabled ) { // If international labels is enabled, origin must be a country with a USPS office, destination can be anywhere in the world return 'destination' === type || includes( ACCEPTED_USPS_ORIGIN_COUNTRIES, address.country ); } // If international labels is disabled, restrict origin and destination to "domestic", that is, US, Puerto Rico and Virgin Islands if ( ! DOMESTIC_US_TERRITORIES.includes( address.country ) ) { return false; } // Disable US military addresses too, since they require customs form if ( 'US' === address.country && US_MILITARY_STATES.includes( address.state ) ) { return false; } return true; } shouldShowLabels() { const { labelsLoaded, labelsEnabled, order, storeAddress, hasLabelsPaymentMethod } = this.props; if ( ! labelsLoaded ) { return false; } const { shipping } = order; return ( labelsEnabled && hasLabelsPaymentMethod && this.isAddressValidForLabels( storeAddress, 'origin' ) && this.isAddressValidForLabels( shipping, 'destination' ) ); } renderFulfillmentAction() { const { wcsEnabled, isSaving, labelsLoaded, labelsError, order, site, translate } = this.props; const orderFinished = isOrderFinished( order.status ); const labelsLoading = wcsEnabled && ! labelsLoaded; if ( orderFinished ) { return null; } if ( ! labelsError && labelsLoading ) { const buttonClassName = 'is-placeholder'; return <Button className={ buttonClassName }>{ translate( 'Fulfill' ) }</Button>; } if ( ! this.shouldShowLabels() ) { return ( <Button primary onClick={ this.toggleDialog } busy={ isSaving } disabled={ isSaving }> { translate( 'Fulfill' ) } </Button> ); } const onLabelPrint = () => this.props.openPrintingFlow( order.id, site.ID ); return ( <div className="order-fulfillment__print-container"> <Button borderless onClick={ this.toggleDialog } busy={ isSaving } disabled={ isSaving }> { translate( 'Fulfill without printing a label' ) } </Button> <Button primary={ labelsLoaded } onClick={ onLabelPrint } busy={ isSaving } disabled={ isSaving } > { translate( 'Print label & fulfill' ) } </Button> </div> ); } render() { const { wcsEnabled, order, site, translate } = this.props; const { errorMessage, showDialog, trackingNumber } = this.state; const dialogClass = 'woocommerce order-fulfillment'; // eslint/css specificity hack if ( ! order ) { return null; } const dialogButtons = [ <Button onClick={ this.toggleDialog }>{ translate( 'Cancel' ) }</Button>, <Button primary onClick={ this.submit }> { translate( 'Fulfill' ) } </Button>, ]; const classes = classNames( { 'order-fulfillment': true, 'is-completed': 'completed' === order.status, } ); return ( <div className={ classes }> <div className="order-fulfillment__label"> <Gridicon icon={ 'completed' === order.status ? 'checkmark' : 'shipping' } /> { this.getFulfillmentStatus() } </div> <div className="order-fulfillment__action">{ this.renderFulfillmentAction() }</div> <Dialog isVisible={ showDialog } onClose={ this.toggleDialog } className={ dialogClass } buttons={ dialogButtons } > <h1>{ translate( 'Fulfill order' ) }</h1> <form> <FormFieldset className="order-fulfillment__tracking"> <FormLabel className="order-fulfillment__tracking-label" htmlFor="tracking-number"> { translate( 'Enter a tracking number (optional)' ) } </FormLabel> <FormTextInput id="tracking-number" className="order-fulfillment__value" value={ trackingNumber } onChange={ this.updateTrackingNumber } placeholder={ translate( 'Tracking Number' ) } /> </FormFieldset> <FormLabel className="order-fulfillment__email"> <FormInputCheckbox checked={ this.state.shouldEmail } onChange={ this.updateCustomerEmail } /> <span>{ translate( 'Email tracking number to customer' ) }</span> </FormLabel> { errorMessage && ( <Notice status="is-error" showDismiss={ false }> { errorMessage } </Notice> ) } </form> </Dialog> <QuerySettingsGeneral siteId={ site.ID } /> { wcsEnabled && <QueryLabels orderId={ order.id } siteId={ site.ID } /> } { wcsEnabled && <LabelPurchaseModal orderId={ order.id } siteId={ site.ID } /> } </div> ); } } export default connect( ( state, { order, site } ) => { const wcsEnabled = isWcsEnabled( state, site.ID ); const labelsLoaded = wcsEnabled && Boolean( areLabelsFullyLoaded( state, order.id, site.ID ) ) && areSettingsGeneralLoaded( state ); const hasLabelsPaymentMethod = wcsEnabled && labelsLoaded && getSelectedPaymentMethodId( state, site.ID ); const storeAddress = labelsLoaded && getStoreLocation( state ); const isSaving = isOrderUpdating( state, order.id ); return { wcsEnabled, internationalLabelsEnabled: isWcsInternationalLabelsEnabled( state, site.ID ), isSaving, labelsLoaded, labelsError: isLabelDataFetchError( state, order.id, site.ID ), labelsEnabled: areLabelsEnabled( state, site.ID ), labels: getLabels( state, order.id, site.ID ), hasLabelsPaymentMethod, storeAddress, }; }, dispatch => bindActionCreators( { createNote, saveOrder, openPrintingFlow }, dispatch ) )( localize( OrderFulfillment ) );
packages/wix-style-react/src/CarouselWIP/Slide/Slide.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import { DATA_HOOKS } from '../constants'; const Slide = ({ dataHook, className, children, image, width, gutter, imagePosition, imageFit, }) => ( <div data-hook={dataHook} className={className} style={{ flex: '0 0 auto', width, marginInlineStart: gutter, objectPosition: imagePosition, objectFit: imageFit, }} > {image ? ( <img data-hook={DATA_HOOKS.carouselImage} src={image.src} /> ) : ( children )} </div> ); Slide.propTypes = { /** Applied as data-hook HTML attribute that can be used in the tests */ dataHook: PropTypes.string, /** A css class to be applied to the slide element */ className: PropTypes.string, /** Children to render inside the slide */ children: PropTypes.node, /** Object containing the src for the slide image */ image: PropTypes.object, /** Width of the slide */ width: PropTypes.string, /** Width for spacing before the slide */ gutter: PropTypes.string, /** Sets the image position */ imagePosition: PropTypes.string, /** Sets the image fit */ imageFit: PropTypes.oneOf(['fill', 'contain', 'cover', 'none', 'scale-down']), }; export default Slide;
src/FilePicker/FilePicker.driver.js
skyiea/wix-style-react
import React from 'react'; import ReactDOM from 'react-dom'; const filePickerDriverFactory = ({element, wrapper, component}) => { const error = element.querySelector(`[data-hook=filePicker-error]`); const input = element.querySelector(`input`); const subLabel = element.querySelector(`[data-hook="sub-label"]`); const mainLabel = element.querySelector(`[data-hook="main-label"]`); return { exists: () => !!element, hasError: () => !!error, errorMessage: () => error.textContent, getInput: () => input.textContent, getSubLabel: () => subLabel.textContent, getMainLabel: () => mainLabel.textContent, setProps: props => { const ClonedWithProps = React.cloneElement(component, Object.assign({}, component.props, props), ...(component.props.children || [])); ReactDOM.render(<div ref={r => element = r}>{ClonedWithProps}</div>, wrapper); } }; }; export default filePickerDriverFactory;
client/main.js
ahmetkasif/xox
import { Meteor } from 'meteor/meteor'; import React from 'react'; import { render } from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Noty from 'noty'; import App from '../imports/ui/App.jsx'; import '../imports/startup/accounts-config.js'; Meteor.startup(() => { injectTapEventPlugin(); render(<App />, document.getElementById('render-target')); Accounts.onLogin(function() { new Noty({ type: 'information', layout: 'topRight', theme: 'sunset', text: 'Logged In', timeout: 1000, progressBar: true, closeWith: ['click', 'button'], animation: { open: 'noty_effects_open', close: 'noty_effects_close' } }).show(); }); Accounts.onLogout(function() { new Noty({ type: 'information', layout: 'topRight', theme: 'sunset', text: 'Logged Out', timeout: 1000, progressBar: true, closeWith: ['click', 'button'], animation: { open: 'noty_effects_open', close: 'noty_effects_close' } }).show(); }); });
src/Hello.js
ChineseCubes/react-vtt
import React from 'react'; export const hello = 'hello, world'; export function Hello() { return ( <span>{hello}</span> ); }
src/components/shared/screen-description.js
gabrielecker/animapp
import React, { Component } from 'react'; import { Container } from 'semantic-ui-react'; export default class ScreenDescription extends Component { render() { return ( <Container text> {this.props.children} </Container> ); } } ScreenDescription.propTypes = { children: React.PropTypes.string.isRequired, };
app/javascript/mastodon/features/ui/components/column_header.js
Kirishima21/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; export default class ColumnHeader extends React.PureComponent { static propTypes = { icon: PropTypes.string, type: PropTypes.string, active: PropTypes.bool, onClick: PropTypes.func, columnHeaderId: PropTypes.string, }; handleClick = () => { this.props.onClick(); } render () { const { icon, type, active, columnHeaderId } = this.props; let iconElement = ''; if (icon) { iconElement = <Icon id={icon} fixedWidth className='column-header__icon' />; } return ( <h1 className={classNames('column-header', { active })} id={columnHeaderId || null}> <button onClick={this.handleClick}> {iconElement} {type} </button> </h1> ); } }
common/components/admin/CourseTableRow.js
ebertmi/webbox
import React from 'react'; import { Link } from 'react-router'; import { Time } from '../Time'; /** * Renders a course row */ export function CourseTableRow (props) { const courseDetailPath = `/admin/course/${props.data.id}`; const creatorDetailPath = `/admin/user/${props.data._creatorId}`; const courseViewPath = `/course/${props.data.slug}`; return ( <tr key={props.data.id}> <td> <Link to={courseDetailPath}>{props.data.title}</Link> </td> <td>{props.data.id}</td> <td>{props.data.description}</td> <td> <Link to={creatorDetailPath}>{props.data._creatorId}</Link> </td> <td> <Time value={props.data.createdAt} locale="de" relative={true}/> </td> <td> <Time value={props.data.lastUpdate} locale="de" relative={true}/> </td> <td> <a href={courseViewPath} target="blank">Zum Kurs</a> </td> </tr> ); }
src/parser/monk/brewmaster/modules/features/DamageTakenTable.js
fyruna/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import DamageTakenTableComponent, { MITIGATED_MAGICAL, MITIGATED_PHYSICAL, MITIGATED_UNKNOWN } from 'interface/others/DamageTakenTable'; import Panel from 'interface/others/Panel'; import SPELLS from 'common/SPELLS'; import SPECS from 'game/SPECS'; import SpellLink from 'common/SpellLink'; import HighTolerance from '../spells/HighTolerance'; import DamageTaken from '../core/DamageTaken'; const MIN_CLASSIFICATION_AMOUNT = 100; class DamageTakenTable extends Analyzer { static dependencies = { ht: HighTolerance, dmg: DamageTaken, }; // additive increase of 5% while isb is up abilityData = {}; // contains `ability` and `mitigatedAs` get tableData() { const vals = Object.values(this.abilityData) .map(raw => { const value = this.dmg.byAbility(raw.ability.guid); const staggered = this.dmg.staggeredByAbility(raw.ability.guid); // console.log(staggered); return { totalDmg: value.effective + staggered, largestSpike: value.largestHit, ...raw }; }); vals.sort((a, b) => b.largestSpike - a.largestSpike); return vals; } constructor(...args) { super(...args); this.active = false; } on_toPlayer_damage(event) { if (event.ability.guid === SPELLS.STAGGER_TAKEN.id) { return; } if (event.amount === 0) { return; } const mitigatedAs = this._classifyMitigation(event); this._addToAbility(event.ability, mitigatedAs); } _addToAbility(ability, mitigationType) { const spellId = ability.guid; if (!this.abilityData[spellId]) { this.abilityData[spellId] = { mitigatedAs: mitigationType, ability: ability, }; return; } const curMitAs = this.abilityData[spellId].mitigatedAs; this.abilityData[spellId].mitigatedAs = this._minMitigationType(curMitAs, mitigationType); } _minMitigationType(a, b) { return Math.min(a, b); } _classifyMitigation(event) { if (event.absorbed + event.amount <= MIN_CLASSIFICATION_AMOUNT) { return MITIGATED_UNKNOWN; } // additive increase of 35% const isbActive = this.selectedCombatant.hasBuff(SPELLS.IRONSKIN_BREW_BUFF.id); // additive increase of 10% const fbActive = this.selectedCombatant.hasBuff(SPELLS.FORTIFYING_BREW_BRM.id); // additive increase of 10% const hasHT = this.ht.active; const physicalStaggerPct = 0.4 + hasHT * 0.1 + isbActive * 0.35 + fbActive * 0.1; const actualPct = event.absorbed / (event.absorbed + event.amount); // multiply by 0.95 to allow for minor floating-point / integer // division error if (actualPct >= physicalStaggerPct * 0.95) { return MITIGATED_PHYSICAL; } else { return MITIGATED_MAGICAL; } } tab() { return { title: 'Damage Taken by Ability', url: 'damage-taken-by-ability', render: () => ( <Panel> <DamageTakenTableComponent data={this.tableData} spec={SPECS[this.selectedCombatant.specId]} total={this.dmg.total.effective} /> <div style={{ padding: '10px' }}> <strong>Note:</strong> Damage taken includes all damage put into the <SpellLink id={SPELLS.STAGGER_TAKEN.id} /> pool. </div> </Panel> ), }; } } export default DamageTakenTable;
src/js/app/components/svgs/add.js
ericf89/survey
import React from 'react'; export default () => ( <svg fill="#FFFFFF" height="36" viewBox="0 0 24 24" width="36" xmlns="http://www.w3.org/2000/svg"> <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/> <path d="M0 0h24v24H0z" fill="none"/> </svg> );
src/components/ListView.js
aryalprakash/backlect-design
import 'rc-dialog/assets/index.css'; import React, { Component } from 'react'; import Header from './Header' import Dialog from 'rc-dialog'; import NewDialog from "./NewDialog"; export default class ListElements extends Component { constructor(){ super() this.state = { visible: false, width: 1200, destroyOnClose: false, center: false } this.onClick = this.onClick.bind(this) this.onClose = this.onClose.bind(this) this.onDestroyOnCloseChange = this.onDestroyOnCloseChange.bind(this) this.changeWidth = this.changeWidth.bind(this) this.center = this.center.bind(this) } onClick(e) { this.setState({ mousePosition: { x: e.pageX, y: e.pageY }, visible: true }); } onClose(e) { console.log(e); this.setState({ visible: false }); } onDestroyOnCloseChange(e) { this.setState({ destroyOnClose: e.target.checked }); } changeWidth() { this.setState({ width: this.state.width === 600 ? 800 : 600 }); } center(e) { this.setState({ center: e.target.checked }); } render() { let dialog; if (this.state.visible || !this.state.destroyOnClose) { const style = { width: this.state.width }; let wrapClassName = ''; if (this.state.center) { wrapClassName = 'center'; } dialog = ( <Dialog visible={this.state.visible} wrapClassName={wrapClassName} animation="zoom" maskAnimation="fade" style={style} onClose={this.onClose} mousePosition={this.state.mousePosition} > <NewDialog close={this.onClose} /> </Dialog> ); } return ( <div className=""> <Header /> {dialog} <div className="table"> <div className="table-sidebar light-blue"> <div className="table-head"> <div className="table-title">Tables / Workouts</div> </div> <div className="menu-item-list"> <div className="menu-item"> <span className="menu-active"></span> <span className="menu-title">Tables</span> <span className="menu-plus">+</span> </div> <div className="menu-subitem"> Artists </div> <div className="menu-subitem subitem-active"> Workouts </div> <div className="menu-subitem"> Photos </div> <div className="menu-subitem"> Reviews </div> </div> <div className="menu-item-list"> <div className="menu-item"><span className=""></span><span className="menu-title">Analytics</span></div> </div> <div className="menu-item-list"> <div className="menu-item"><span className=""></span><span className="menu-title">Users & Permissions</span></div> </div> <div className="menu-item-list"> <div className="menu-item"><span className=""></span><span className="menu-title">Settings</span></div> </div> </div> <div className="table-content"> <div className="table-head light-blue"> <div className="search-box"> <input className="input-box" placeholder="Search" type="text" /> <img src="../../img/select-project.png" className="search-icon" /> </div> <div className="table-options"> <div className="table-total">1 of 28</div> <div className="table-paging"> <div className=" left-paging">L</div> <div className=" right-paging">R</div> </div> <div className="border-button table-new" onClick={this.onClick}><span className="bold">+</span>&nbsp;&nbsp;&nbsp; New Workout</div> <div className="border-button table-settings">S</div> </div> </div> <table className="table-main"> <thead> <tr className="table-row"> <th className="checkbox"><form> <input type="checkbox" className="checkbox"/> </form></th> <th>Prod. Image</th> <th>Product Title</th> <th>Description</th> <th>Num</th> <th>Currency</th> <th>Active</th> </tr> </thead> <tbody> <tr className="table-row"> <td className="checkbox"> <input type="checkbox" className="checkbox"/> </td> <td><img className="table-image" src="http://www.planwallpaper.com/static/images/free-hd-wallpaper-download.jpg" /></td> <td>Santorini Poster</td> <td>This Open Edition print was published by OvH in 2009. Silkscreen on 350gsm rag paper.</td> <td>85</td> <td>$554</td> <td>True</td> </tr> <tr className="table-row"> <td className="checkbox"> <input type="checkbox" className="checkbox"/> </td> <td><img className="table-image" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTExMWFRUXFh0YGBcXGRcYGBoZFxcYGBgdHRgYHSggGBolHRcVITEhJSkrLi4uFx8zODMtNygtLisBCgoK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UDmOTyfwHPSsrK3n1KFB52Tes3Auiw2hwZKBuJAEg+oKJynE46Diac2ngZ1oOuOvjzEpSlAbTuCuilGcwB0AnCucVlZWFQBG5xo9CBa0xbqsgrYVpb37y6gEhZGSCf6tqRgRGK47/Eq8wELVAON2MfAwPisrKwReUCgf7zofgu8S0mVhKpBIB4E8GOCf8ANUd1bu7C6UKCOhIIzMR+tZWUOtx2QaBa+ZmkMuKUJ9IPeqpm3SlCpyYJz7VlZSjF3c22GmNuMlaBBietRmvJcbJ/9x/KsrKJDwTB+xnrwskc9a6FYgRJ6VlZQtwwm6YMw6rCnDHqKgDGBwn+5pZqt6lxaWk+oFUqPNZWVOWMYig2fqB69cpLqQCJSjIrlPiBSm3z5R4UFgcyoTI78YxzWVlU4Rcnzj2RrqWvgMSsbSsQlJBHAEmQRHM/brS/wjpLN5epVcFQYPoISYKiG4BEiUokJE9yPeMrKPGioOSbAoPY2Tp627hbBW4WErKJEb1bpgpkGM4kwDwDMVTrsUlLLfltJU2A0lBIClbQkp8zbhw9T/8A1M8GsrKMKPIlIOp5Ia8afWpbYXt3jcJChEGNoI6DgDnHXmmniCxKGLJTz60eUZ8xCVLWXJhszMghLaenPaaysrATtUY45ctGfE1qy0zcOOOPLIKnVQkLTyk4EJKjJwPcyKktM1EOXLyA4tLK3lLQHAUHJCUtqKup9I+YzMVlZRkcmmx24ZrWuG4eRbWqUIVt3KTElZHUkcYnMk96i9f8MO+bKBggE/OZrKyovUZmxONfqJPeT//Z" /></td> <td>Amazon Forest </td> <td>This Open Edition print was published by OvH in 2009. Silkscreen on 350gsm rag paper.</td> <td>850</td> <td>$264</td> <td>False</td> </tr> <tr className="table-row"> <td className="checkbox"> <input type="checkbox" className="checkbox"/> </td> <td><img className="table-image" src="http://hdwallpaperbackgrounds.net/wp-content/uploads/2016/05/Wallpaper-Images-Download-3.jpg" /></td> <td>New York </td> <td>This Open Edition print was published by OvH in 2009. Silkscreen on 350gsm rag paper.</td> <td>850</td> <td>$264</td> <td>False</td> </tr> </tbody> </table> </div> </div> </div> ); } }
app/components/HowDoes.js
gidich/votrient-kiosk
import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './HowDoes.css'; export default class HowDoes extends Component { render() { return ( <div className={styles.container}> <Link to="/" className={styles.home}></Link> <Link to="/HowDoes/2" className={styles.powerAhead}><div /></Link> <Link to="/ProductInfo" className={styles.productInformation}></Link> <Link to="/" className={styles.logo}></Link> <Link to="/HowDoes/References" className={styles.references}></Link> <Link to="/HowDoes/2Diagram" className={styles.diagram}></Link> </div> ); } }
frontend/src/components/login/loginForm.js
unicef/un-partner-portal
import React from 'react'; import { reduxForm, SubmissionError, clearSubmitErrors } from 'redux-form'; import PropTypes from 'prop-types'; import Button from 'material-ui/Button'; import { withStyles } from 'material-ui/styles'; import Grid from 'material-ui/Grid'; import Snackbar from 'material-ui/Snackbar'; import Typography from 'material-ui/Typography'; import GridColumn from '../common/grid/gridColumn'; import { loginUser } from '../../reducers/session'; import TextFieldForm from '../forms/textFieldForm'; import PasswordFieldForm from '../forms/passwordFieldForm'; const styleSheet = (theme) => { const paddingFields = theme.spacing.unit * 5; const paddingField = theme.spacing.unit * 3; return { root: { minHeight: '50vh', }, fields: { padding: `${paddingFields}px`, }, logIn: { color: theme.palette.secondary[500], }, field: { paddingTop: `${paddingField}px`, }, lineHeight: { lineHeight: '24px', }, }; }; const handleLogin = (values, dispatch) => dispatch(loginUser(values)).catch((error) => { const errorMsg = error.response.data.non_field_errors || 'Login failed!'; throw new SubmissionError({ ...error.response.data, _error: errorMsg, }); }); const Login = (props) => { const { handleSubmit, pristine, submitting, error, classes, dispatch, form } = props; return ( <div > <form onSubmit={handleSubmit}> <GridColumn className={classes.root}> <Grid className={classes.field} container justify="center"> <Typography type="display1" className={classes.logIn}>Log in</Typography> </Grid> <div className={classes.fields}> <TextFieldForm label="E-mail" placeholder="Please use your email to login" fieldName="email" /> <div className={classes.field}> <PasswordFieldForm label="Password" fieldName="password" /> </div> </div> <Grid container justify="center" > <Button type="submit" onTouchTap={handleSubmit} raised color="accent" disabled={pristine || submitting} > Log in </Button> </Grid> <Snackbar anchorOrigin={{ vertical: 'bottom', horizontal: 'left', }} open={error} message={error} autoHideDuration={4e3} onClose={() => dispatch(clearSubmitErrors(form))} /> </GridColumn> </form> </div> ); }; Login.propTypes = { classes: PropTypes.object, /** * callback for form submit */ handleSubmit: PropTypes.func.isRequired, pristine: PropTypes.bool, submitting: PropTypes.bool, error: PropTypes.string, form: PropTypes.string, dispatch: PropTypes.func, }; const LoginForm = reduxForm({ form: 'login', onSubmit: handleLogin, })(Login); export default withStyles(styleSheet, { name: 'LoginForm' })(LoginForm);
src/templates/page-template.js
ivanminutillo/faircoopWebSite
import React from 'react' import PropTypes from 'prop-types' import Helmet from 'react-helmet' import PageTemplateDetails from '../components/PageTemplateDetails' import Header from '../components/Header' import Footer from '../components/Footer' class PageTemplate extends React.Component { render () { const { title, subtitle, menu, author } = this.props.data.site.siteMetadata // const page = this.props.data.markdownRemark return ( <div> <Helmet> <title>{`${title}`}</title> <meta name="description" /> </Helmet> <Header menu={menu} social={author} /> <PageTemplateDetails {...this.props} /> <Footer menu={menu} social={author} /> </div> ) } } PageTemplate.propTypes = { data: PropTypes.shape({ site: PropTypes.shape({ siteMetadata: PropTypes.shape({ title: PropTypes.string.isRequired, subtitle: PropTypes.string.isRequired }) }) }) } export default PageTemplate export const pageQuery = graphql` query PageBySlug($slug: String!) { site { siteMetadata { title subtitle copyright menu { label path } author { name email telegram twitter github } } } markdownRemark(fields: { slug: { eq: $slug } }) { id html frontmatter { title date description } } } `
front/src/components/Ebets.js
ethbets/ebets
/* Copyright (C) 2017 ethbets * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ import React, { Component } from 'react'; import Paginate from 'react-paginate'; import EbetsJson from 'build/contracts/Ebets.json'; import BetList from 'components/BetList'; import PropTypes from 'prop-types'; import {getParsedCategories} from 'utils/ebetsCategories'; import Web3Service from 'services/Web3Service'; import 'assets/stylesheets/pagination.css'; class Ebets extends Component { constructor(props) { super(props); this.state = { bets: [], ebetsContractInstance: null, currentPage: 0, pageCount: 1 } } getPageCount(bets) { return Math.ceil(bets.length / this.props.route.perPage) } getBetsByCategory = (category, ebetsContractInstance) => { console.log(category); return new Promise( async (resolve, reject) => { let betPromises = []; if (category === 'all_bets' || category === 'my_bets') { betPromises = getParsedCategories().map(category => ({ bets: ebetsContractInstance.methods.getBetsByCategory(category.key), category: category.key })); } else { betPromises = [{ bets: ebetsContractInstance.methods.getBetsByCategory(category), category: category }]; } const bets = (await Promise.all(betPromises.map(betCat => (betCat.bets.call())))) .reduce((before, bet, idx) => { return before.concat(bet.map(b => ({bet: b, category: betPromises[idx].category}))); }, []); resolve(bets); this.setState({pageCount: this.getPageCount(bets)}); }); } componentWillMount() { this.instantiateContract(); } componentWillUnmount () { if (this.state.betsEvents) this.state.betsEvents.stopWatching(); } componentWillReceiveProps(nextProps) { var category = nextProps.routeParams.category; if (nextProps.routeParams.subcategory) category += '/' + nextProps.routeParams.subcategory; if (this.state.ebetsContractInstance !== null && category !== undefined) { this.getBetsByCategory(category, this.state.ebetsContractInstance) .then(bets => { this.setState({bets: bets}) }); } } async instantiateContract() { const ebetsContract = new Web3Service.web3.eth.Contract( EbetsJson.abi, EbetsJson['networks'][Web3Service.networkId].address ); var category = this.props.routeParams.category; var bets = []; if (category !== undefined) { if (this.props.routeParams.subcategory) category += '/' + this.props.routeParams.subcategory; bets = await this.getBetsByCategory(category, ebetsContract); } //events // const betsEvents = ebetsContractInstance.allEvents({fromBlock: 'latest', toBlock: 'latest'}); // betsEvents.watch((error, response) => { // if (response.args.category === this.props.routeParams.category) // this.setState(previousState => ({bets: previousState.bets.concat(response.args.betAddr)})); // }) this.setState({ bets, //betsEvents: betsEvents, ebetsContractInstance: ebetsContract, pageCount: this.getPageCount(bets) }); } handlePageClick = (index) => { this.setState({ currentPage: index.selected }); }; displayedBets = () => { const initialPosition = this.state.currentPage * this.props.route.perPage; return this.state.bets.slice(initialPosition , initialPosition + this.props.route.perPage) } render() { return ( <div> <BetList bets={this.displayedBets()} routeParams={this.props.routeParams} location={this.props.location} /> {this.state.pageCount > 1 && <Paginate pageCount={this.state.pageCount} marginPagesDisplayed={this.props.route.perPage} pageRangeDisplayed={this.state.pageCount} containerClassName={"pagination"} initialPage={this.state.currentPage} onPageChange={this.handlePageClick} activeClassName={"active"} /> } </div> ); } } Ebets.contextTypes = { showUnfeatured: PropTypes.bool }; export default Ebets;
src/DropdownButton.js
xiaoking/react-bootstrap
import React from 'react'; import BootstrapMixin from './BootstrapMixin'; import Dropdown from './Dropdown'; import NavDropdown from './NavDropdown'; import CustomPropTypes from './utils/CustomPropTypes'; import deprecationWarning from './utils/deprecationWarning'; import omit from 'lodash/object/omit'; class DropdownButton extends React.Component { constructor(props) { super(props); } render() { let { title, navItem, ...props } = this.props; let toggleProps = omit(props, Dropdown.ControlledComponent.propTypes); if (navItem) { return <NavDropdown {...this.props}/>; } return ( <Dropdown {...props}> <Dropdown.Toggle {...toggleProps}> {title} </Dropdown.Toggle> <Dropdown.Menu> {this.props.children} </Dropdown.Menu> </Dropdown> ); } } DropdownButton.propTypes = { /** * When used with the `title` prop, the noCaret option will not render a caret icon, in the toggle element. */ noCaret: React.PropTypes.bool, /** * Specify whether this Dropdown is part of a Nav component * * @type {bool} * @deprecated Use the `NavDropdown` instead. */ navItem: CustomPropTypes.all([ React.PropTypes.bool, function(props) { if (props.navItem) { deprecationWarning('navItem', 'NavDropdown component', 'https://github.com/react-bootstrap/react-bootstrap/issues/526'); } } ]), title: React.PropTypes.node.isRequired, ...Dropdown.propTypes, ...BootstrapMixin.propTypes }; DropdownButton.defaultProps = { pullRight: false, dropup: false, navItem: false, noCaret: false }; export default DropdownButton;
CompositeUi/src/views/form/Register.js
kreta/kreta
/* * This file is part of the Kreta package. * * (c) Beñat Espiña <[email protected]> * (c) Gorka Laucirica <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import React from 'react'; import {connect} from 'react-redux'; import {Field, reduxForm} from 'redux-form'; import Button from './../component/Button'; import Form from './../component/Form'; import FormActions from './../component/FormActions'; import FormInput from './../component/FormInput'; import HelpText from './../component/HelpText'; import {Row, RowColumn} from './../component/Grid'; const validate = values => { const errors = {}, requiredFields = ['email', 'password', 'repeated_password']; if (typeof values.password !== 'undefined' && values.password.length < 6) { errors.password = 'Password must be at least 6 characters'; } if (values.password !== values.repeated_password) { errors.repeated_password = 'Passwords do not match'; } if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = 'Invalid email address'; } requiredFields.forEach(field => { if (!values[field] || values[field] === '') { errors[field] = 'Required'; } }); return errors; }; @connect(state => ({registering: state.user.processing})) @reduxForm({form: 'Register', validate}) class Register extends React.Component { static propTypes = { handleSubmit: React.PropTypes.func, }; render() { const {handleSubmit, registering} = this.props; return ( <Form onSubmit={handleSubmit}> <Row center> <RowColumn large={6}> <Field autoFocus component={FormInput} label="Email" name="email" tabIndex={1} /> <Field component={FormInput} label="Password" name="password" tabIndex={2} type="password" /> <Field component={FormInput} label="Repeat password" name="repeated_password" tabIndex={3} type="password" /> <FormActions expand> <Button color="green" disabled={registering} tabIndex={3} type="submit" > Sign up for Kreta </Button> </FormActions> <HelpText center> By clicking "Sign up for Kreta", you agree to our{' '} <a href="#">terms of service</a> and{' '} <a href="#">privacy policy</a>. We'll occasionally send you account related emails. </HelpText> </RowColumn> </Row> </Form> ); } } export default Register;
wp-content/plugins/liveblog/src/react/Editor/blocks/CreateBlockHOC.js
MinnPost/minnpost-wordpress
/* eslint-disable react/display-name */ /* eslint-disable react/prop-types */ import React, { Component } from 'react'; import { EditorState } from 'draft-js'; import removeBlock from '../modifiers/removeBlock'; const CreateBlock = (Block, editorState, onChange) => class extends Component { constructor() { super(); this.state = { edit: false, }; } /** * Handle whether or not the editor mode should be open by default. * We pass this as meta data whenever we create the block in the editor. */ componentDidMount() { const { setReadOnly, edit } = this.getMetadata(); if (edit) { this.setState({ edit: true }); setReadOnly(true); } } componentWillUnmount() { this.setEditMode(false); } /** * Set edit mode to new state. * @param {bool} state */ setEditMode(state) { const { setReadOnly } = this.getMetadata(); this.setState({ edit: state }); this.replaceMetadata({ edit: state }); setReadOnly(state); } /** * Retrieve metadata saved to block. */ getMetadata() { const { contentState, block } = this.props; return contentState.getEntity(block.getEntityAt(0)).getData(); } /** * Replace metadata daved to block. * @param {object} data * @param {boolean} update whether to trigger a re-render. Should be used cautiously as can * cause race conditions. We generally only need to re-render when we want to keep the raw html * input in sync. */ replaceMetadata(data, update = false) { const { contentState, block } = this.props; const newContentState = contentState.mergeEntityData(block.getEntityAt(0), data); if (update) { const newEditorState = EditorState.push( editorState, newContentState, 'replace-metadata', ); onChange( EditorState.forceSelection(newEditorState, newEditorState.getSelection()), ); } } /** * Set dataTransfer data on drag. We set the text key because nothing else will * move the cursor which is the behavior we want. It is worth noting that in development * builds of React this doesn't work in IE11. You can read why here - * https://github.com/facebook/react/issues/5700 */ startDrag(e) { const { block } = this.props; e.dataTransfer.dropEffect = 'move'; // eslint-disable-line no-param-reassign e.dataTransfer.setData('text', `DRAFT_BLOCK:${block.getKey()}`); } /** * Remove block from editor. */ removeBlock() { const { block } = this.props; const contentAfterRemove = removeBlock( editorState.getCurrentContent(), block.getKey(), ); onChange( EditorState.forceSelection( EditorState.push(editorState, contentAfterRemove, 'remove-block'), contentAfterRemove.getSelectionAfter(), ), ); } render() { const { blockProps } = this.props; const { edit } = this.state; return ( <div className={`liveblog-block ${edit ? 'is-editing' : ''} ${blockProps.isFocused ? 'is-focused' : ''}`} draggable={true} onDragStart={!edit ? this.startDrag.bind(this) : e => e.preventDefault()} > <Block {...this.props} edit={edit} setEditMode={this.setEditMode.bind(this)} getMetadata={this.getMetadata.bind(this)} replaceMetadata={this.replaceMetadata.bind(this)} removeBlock={this.removeBlock.bind(this)} /> </div> ); } }; export default CreateBlock;
src/components/Header/Refresher/index.js
RayBenefield/halo-forge
import React from 'react'; import equip from './equip'; const Refresher = ({ refresh }) => ( <svg onClick={refresh} style={{ display: 'inline-block', color: 'rgb(255, 255, 255)', fill: 'currentcolor', height: '24px', width: '24px', userSelect: 'none', transition: 'all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms', }} viewBox="0 0 24 24" > {// eslint-disable-next-line max-len }<path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" /> </svg> ); export default equip(Refresher);
src/views/inlet/Login.js
anysome/objective
/** * Created by Layman <[email protected]> (http://github.com/anysome) on 2016/11/9. */ import React from 'react'; import {View, StyleSheet, Image, Text, Dimensions, TouchableOpacity, Keyboard, LayoutAnimation} from 'react-native'; import {analytics, styles, colors, airloy, api, toast, L, hang} from '../../app'; import Button from 'react-native-button'; import * as WeiboAPI from 'react-native-weibo'; import TextField from '../../widgets/TextField'; import ResetPassword from './ResetPassword'; export default class Login extends React.Component { constructor(props) { super(props); this.onSigned = props.onSigned; this._email = null; this._password = null; this.state = { isKeyboardOpened: false, visibleHeight: Dimensions.get('window').height, openModal: false }; } componentDidMount() { this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', e => { let newSize = Dimensions.get('window').height - e.endCoordinates.height; this.setState({ isKeyboardOpened: true, visibleHeight: newSize }); }); this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', e => { this.setState({ isKeyboardOpened: false, visibleHeight: Dimensions.get('window').height }); }); } componentWillUnmount() { this.keyboardDidShowListener.remove(); this.keyboardDidHideListener.remove(); } componentWillUpdate(props, state) { if (state.isKeyboardOpened !== this.state.isKeyboardOpened) { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); } } async _weiboLogin() { WeiboAPI.login({scope: 'all', redirectURI: 'http://asfun.cn/m/login/weibo.html'}).then( async (response) => { hang(); let user = airloy.auth.formUser(airloy.device.getIdentifier(), ''); let token = { accessToken: response.accessToken, uid: response.userID, expirationDate: response.expirationDate, refreshToken: response.refreshToken, device: user.device, loginTime: user.loginTime }; let result = await airloy.net.httpPost(api.public.login.weibo, token); if (result.success) { await airloy.auth.saveUser(result.info); analytics.onProfileSignIn('' + result.info.id); this.onSigned(); } else { toast(L(result.message), 70); } hang(false); }, error => { console.log(error); toast(`暂时无法登录, 请重试或使用其它方式`); } ); } async _login() { if (this._email.value.length < 5) { this._email.focus(); return; } if (this._password.value.length < 6) { this._password.focus(); return; } hang(); let user = airloy.auth.formUser(this._email.value, this._password.value); let result = await airloy.net.httpPost(api.public.sign, user); if (result.success) { await airloy.auth.saveUser(result.info); analytics.onProfileSignIn('' + result.info.id); this.onSigned(); } else { toast(L(result.message), 70); } hang(false); } async _justIn() { hang(); let user = airloy.auth.formUser(airloy.device.getIdentifier(), ''); let result = await airloy.net.httpPost(api.public.try, user); if (result.success) { await airloy.auth.saveUser(result.info); analytics.onProfileSignIn('' + result.info.id); this.onSigned(); } else { toast(L(result.message), 70); } hang(false); } openModal() { this.setState({openModal: true}); } closeModal() { this.setState({openModal: false}); } render() { return ( <View style={style.window}> <View style={[styles.containerC, {height: this.state.visibleHeight}]}> <View style={style.body}> <View style={style.containerA}> <TouchableOpacity onPress={()=>this._weiboLogin()}> <Image style={style.third} source={require('../../../resources/images/weibo.png')}/> </TouchableOpacity> <Text style={styles.text}>微博帐号登录</Text> </View> <TextField ref={(c) => this._email = c} placeholder="注册邮箱 / 登录名" keyboardType="email-address" returnKeyType="next" onSubmitEditing={()=>this._password.focus()} /> <TextField ref={(c) => this._password = c} placeholder="密码" secureTextEntry={true} returnKeyType="join" onSubmitEditing={()=>this._login()} /> <Button style={styles.buttonText} containerStyle={[styles.button, {marginTop: 20}]} activeOpacity={0.5} onPress={()=>this._login()}> 注册 / 登录 </Button> <View style={[styles.containerF, {paddingTop:10, paddingBottom:10}]}> <Button style={style.link} onPress={()=>this.openModal()}> 忘记密码 ? </Button> <Button style={style.link} onPress={()=>this._justIn()}> 直接使用 &gt;&gt; </Button> </View> </View> </View> <ResetPassword visible={this.state.openModal} onBack={()=> this.closeModal()}/> </View> ); } } const style = StyleSheet.create({ window: { flex: 1, backgroundColor: 'gray' }, body: { flex: 1, height: 350, padding: 16, borderTopWidth: 1, borderTopColor: 'white', borderBottomWidth: 1, borderBottomColor: 'white', backgroundColor: colors.bright2 }, containerA: { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', paddingLeft: 16, paddingRight: 16, paddingBottom: 20, borderBottomWidth: 1, borderBottomColor: colors.bright2 }, third: { width: 64, height: 64, marginBottom: 10 }, link: { flex: 1, fontSize: 12, color: colors.accent } });
src/components/Drawer/MyDrawerComponent.js
trixyrabbit/Exile
import React from 'react' import './Drawer.scss' import { IndexLink, Link } from 'react-router' import Drawer from 'material-ui/Drawer' import MenuItem from 'material-ui/MenuItem' import Subheader from 'material-ui/Subheader' let leftNavTop = { fontSize: '24px', color: 'rgb(255, 255, 255)', lineHeight: '64px', fontWeight: 300, backgroundColor: 'rgb(0, 188, 212)', paddingLeft: '24px', marginBottom: '8px' } export const MyDrawer = (props) => ( <Drawer open={props.open} docked={false} onRequestChange={() => props.toggleDrawer()}> <Subheader style={leftNavTop} >Navigation</Subheader> <IndexLink to='/' activeClassName='route--active' style={{ 'textDecoration': 'none' }}> <MenuItem primaryText='Home' onTouchTap={() => { props.toggleDrawer() }} /> </IndexLink> <Link to='/counter' activeClassName='route--active' style={{ 'textDecoration': 'none' }}> <MenuItem primaryText='Counter' onTouchTap={() => { props.toggleDrawer() }} /> </Link> <Link to='/metacoin' activeClassName='route--active' style={{ 'textDecoration': 'none' }}> <MenuItem primaryText='Meta Coin' onTouchTap={() => { props.toggleDrawer() }} /> </Link> <Link to='/exile' activeClassName='route--active' style={{ 'textDecoration': 'none' }}> <MenuItem primaryText='Ad Exile' onTouchTap={() => { props.toggleDrawer() }} /> </Link> </Drawer> ) MyDrawer.propTypes = { open: React.PropTypes.bool.isRequired, toggleDrawer: React.PropTypes.func.isRequired } export default MyDrawer
src/pages/BranchQueue.js
branch-bookkeeper/pina
import classNames from 'classnames'; import { compose, map, prop, contains, } from 'ramda'; import ease from 'ease-component'; import React, { Component } from 'react'; import { withRouter } from 'react-router'; import PropTypes from 'prop-types'; import { setPropTypes, defaultProps, pure } from 'recompose'; import { withStyles } from '@material-ui/styles'; import { grey } from '@material-ui/core/colors'; import Collapse from '@material-ui/core/Collapse'; import Button from '@material-ui/core/Button'; import BranchQueueHeader from '../components/BranchQueueHeader'; import PageContent from '../components/PageContent'; import Queue from '../components/Queue'; import QueueItemCard from '../components/QueueItemCard'; import { userShape, queueShape, repositoryShape, pullRequestShape } from '../constants/propTypes'; import { requestShape, isNotMade, isMade } from '../lib/request'; import scrollToComponent from '../lib/scrollToComponent'; import noop from '../lib/noop'; import withPreloading from '../hocs/withPreloading'; const propTypes = { history: PropTypes.shape({ push: PropTypes.func.isRequired, }), theme: PropTypes.shape({ transitions: PropTypes.shape({ getAutoHeightDuration: PropTypes.func.isRequired, }).isRequired, }), repository: repositoryShape.isRequired, branch: PropTypes.string.isRequired, user: userShape, queue: queueShape.isRequired, selectedPullRequest: pullRequestShape, pullRequests: PropTypes.objectOf(pullRequestShape).isRequired, pullRequestsRequest: requestShape, loadBranchQueue: PropTypes.func, loadPullRequests: PropTypes.func, startQueueUpdates: PropTypes.func, stopQueueUpdates: PropTypes.func, onAddToBranchQueue: PropTypes.func, onRemoveFromBranchQueue: PropTypes.func, }; const styles = theme => ({ outOfQueueCardWrapper: { borderTop: `dashed 2px ${grey[300]}`, marginTop: theme.spacing(4), paddingTop: theme.spacing(4), paddingBottom: theme.spacing(2), }, outOfQueueCardWrapperEmpty: { borderTop: 'none', marginTop: 0, }, pullRequestActions: { paddingTop: theme.spacing(1), paddingBottom: theme.spacing(1), textAlign: 'center', }, cancelButton: { marginLeft: theme.spacing(1), }, }); const pullRequestIsInQueue = (pullRequest, queue) => { return pullRequest && contains(pullRequest.pullRequestNumber, map(prop('pullRequestNumber'), queue)); }; const scrollToCard = (theme, card) => { scrollToComponent(card, { duration: theme.transitions.getAutoHeightDuration, ease: ease.outSine, }); }; class BranchQueue extends Component { constructor(props) { super(props); const { selectedPullRequest, user, queue } = props; this.state = { showOutOfQueueCard: selectedPullRequest && user && !pullRequestIsInQueue(selectedPullRequest, queue), selectedPullRequest, }; } componentDidMount() { this.props.startQueueUpdates(); } componentWillUnmount() { this.props.stopQueueUpdates(); } componentDidUpdate(prevProps, prevState) { const { showOutOfQueueCard: prevShowOutOfQueueCard } = prevState; const { showOutOfQueueCard } = this.state; const { theme } = this.props; !prevShowOutOfQueueCard && showOutOfQueueCard && this.outOfQueueCard && setTimeout(() => scrollToCard(theme, this.outOfQueueCard), theme.transitions.duration.standard); } componentWillReceiveProps(nextProps) { const { selectedPullRequest: prevSelectedPullRequest } = this.state; const { selectedPullRequest, queue } = nextProps; if (!selectedPullRequest || pullRequestIsInQueue(selectedPullRequest, queue)) { this.setState({ showOutOfQueueCard: false, selectedPullRequest: pullRequestIsInQueue(prevSelectedPullRequest, queue) ? null : prevSelectedPullRequest, }); } else { this.setState({ showOutOfQueueCard: true, selectedPullRequest, }); } } render() { const { user, queue, repository, branch, pullRequests, removeFromBranchQueueRequest, onRemoveFromBranchQueue, } = this.props; const { showOutOfQueueCard } = this.state; return ( <div> <BranchQueueHeader repository={repository} branch={branch} /> {queue && <PageContent> <Queue user={user} repository={repository} queue={queue} pullRequests={pullRequests} onRemoveFromBranchQueue={onRemoveFromBranchQueue} removeFromBranchQueueRequest={removeFromBranchQueueRequest} showLinkToAddItems={!showOutOfQueueCard} /> </PageContent>} {this.renderOutOfQueueCard()} </div> ); } renderOutOfQueueCard() { const { classes, history, user, repository, branch, queue, addToBranchQueueRequest, onAddToBranchQueue, } = this.props; const { showOutOfQueueCard, selectedPullRequest } = this.state; const bookingInProgress = !isNotMade(addToBranchQueueRequest); const wrapperClasses = classNames(classes.outOfQueueCardWrapper, { [classes.outOfQueueCardWrapperEmpty]: queue.length === 0, }); return ( <Collapse in={showOutOfQueueCard} unmountOnExit> <PageContent> <div className={wrapperClasses}> {selectedPullRequest && selectedPullRequest.branch === branch && ( <QueueItemCard innerRef={this.setOutOfQueueCardRef} elevation={6} queueItem={{ pullRequestNumber: selectedPullRequest.pullRequestNumber, username: user.login, createdAt: '', }} pullRequest={selectedPullRequest} showPullRequestLink={false} loading={bookingInProgress} > <div className={classes.pullRequestActions}> <Button color="primary" variant="contained" disabled={bookingInProgress} onClick={() => onAddToBranchQueue(selectedPullRequest.pullRequestNumber)} > Add to queue </Button> <Button variant="outlined" className={classes.cancelButton} disabled={bookingInProgress} onClick={() => history.push(`/${repository.full_name}/${branch}`)} > Cancel </Button> </div> </QueueItemCard> )} </div> </PageContent> </Collapse> ); } setOutOfQueueCardRef = (ref) => { this.outOfQueueCard = ref; }; } const isLoadingNeeded = ({ queue, pullRequestsRequest }) => !queue || !isMade(pullRequestsRequest); const load = ({ queue, loadBranchQueue, pullRequestsRequest, loadPullRequests }) => { !queue && loadBranchQueue(); !isMade(pullRequestsRequest) && loadPullRequests(); }; export default compose( withPreloading(isLoadingNeeded, load), setPropTypes(propTypes), defaultProps({ loadBranchQueue: noop, }), pure, withStyles(styles, { withTheme: true }), withRouter, )(BranchQueue);
src/server.js
NicholasAzar/ntensitycustoms
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; const server = global.server = express(); server.set('port', (process.env.PORT || 5000)); server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '' }; const css = []; const context = { onInsertCss: value => css.push(value), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(server.get('port'), () => { /* eslint-disable no-console */ console.log('The server is running at http://localhost:' + server.get('port')); if (process.send) { process.send('online'); } });
blueocean-material-icons/src/js/components/svg-icons/image/filter-tilt-shift.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageFilterTiltShift = (props) => ( <SvgIcon {...props}> <path d="M11 4.07V2.05c-2.01.2-3.84 1-5.32 2.21L7.1 5.69c1.11-.86 2.44-1.44 3.9-1.62zm7.32.19C16.84 3.05 15.01 2.25 13 2.05v2.02c1.46.18 2.79.76 3.9 1.62l1.42-1.43zM19.93 11h2.02c-.2-2.01-1-3.84-2.21-5.32L18.31 7.1c.86 1.11 1.44 2.44 1.62 3.9zM5.69 7.1L4.26 5.68C3.05 7.16 2.25 8.99 2.05 11h2.02c.18-1.46.76-2.79 1.62-3.9zM4.07 13H2.05c.2 2.01 1 3.84 2.21 5.32l1.43-1.43c-.86-1.1-1.44-2.43-1.62-3.89zM15 12c0-1.66-1.34-3-3-3s-3 1.34-3 3 1.34 3 3 3 3-1.34 3-3zm3.31 4.9l1.43 1.43c1.21-1.48 2.01-3.32 2.21-5.32h-2.02c-.18 1.45-.76 2.78-1.62 3.89zM13 19.93v2.02c2.01-.2 3.84-1 5.32-2.21l-1.43-1.43c-1.1.86-2.43 1.44-3.89 1.62zm-7.32-.19C7.16 20.95 9 21.75 11 21.95v-2.02c-1.46-.18-2.79-.76-3.9-1.62l-1.42 1.43z"/> </SvgIcon> ); ImageFilterTiltShift.displayName = 'ImageFilterTiltShift'; ImageFilterTiltShift.muiName = 'SvgIcon'; export default ImageFilterTiltShift;
mdbreact/components/FreeBird.js
ryanwashburne/react-skeleton
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; class FreeBird extends Component { render() { const { className, tag: Tag, ...attributes } = this.props; const classes = classNames( 'container free-bird', className ); return ( <Tag {...attributes} className={classes} /> ); } } FreeBird.propTypes = { tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), className: PropTypes.string }; FreeBird.defaultProps = { tag: 'div' }; export default FreeBird;
src/components/about/about.js
javflores/dtl-react-training
import React from 'react'; class About extends React.Component { render(){ return( <div className="jumbotron"> <h1>We are Broadbandchoices</h1> <h2>The best broadband comparison tool in the market.</h2> <p>We are Damo, Ranj, Rob, Alex, Ben, Walshy, Sloat, Rich and Matt</p> </div> ); } } export default About;
src/react/LogMonitorEntryAction.js
taylorhakes/redux-devtools
import React from 'react'; import JSONTree from './JSONTree'; const styles = { actionBar: { paddingTop: 8, paddingBottom: 7, paddingLeft: 16 }, payload: { margin: 0, overflow: 'auto' } }; export default class LogMonitorAction extends React.Component { renderPayload(payload) { return ( <div style={{ ...styles.payload, backgroundColor: this.props.theme.base00 }}> { Object.keys(payload).length > 0 ? <JSONTree theme={this.props.theme} keyName={'action'} data={payload}/> : '' } </div> ); } render() { const { type, ...payload } = this.props.action; return ( <div style={{ backgroundColor: this.props.theme.base02, color: this.props.theme.base06, ...this.props.style }}> <div style={styles.actionBar} onClick={this.props.onClick}> {type} </div> {!this.props.collapsed ? this.renderPayload(payload) : ''} </div> ); } }
src/components/BookPage.js
nicolasletoublon/react-dnd
import React from 'react'; import {connect} from 'react-redux'; import * as bookActions from '../actions/bookActions'; class Book extends React.Component { constructor(props) { super(props); } submitBook(input){ this.props.createBook(input); } render(){ let titleInput; return( <div> <h3>Books</h3> <ul> {this.props.books.map((b, i) => <li key={i}>{b.title}</li> )} </ul> <div> <h3>Books Form</h3> <form onSubmit={e => { e.preventDefault(); let input = {title: titleInput.value}; this.submitBook(input); e.target.reset(); }}> <input type="text" name="title" ref={node => titleInput = node}/> <input type="submit" /> </form> </div> </div> ); } } const mapStateToProps = (state, ownProps) => { return { books: state.books }; }; const mapDispatchToProps = (dispatch) => { return { createBooks: (book) => dispatch(bookActions.createBook(book)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(Book);
src/client/index.android.js
mucsi96/react-native-lambda-starter
import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; import App from './components/App'; export default class reactNativeLambdaStarter extends Component { render() { return ( <App/> ); } } AppRegistry.registerComponent('reactNativeLambdaStarter', () => reactNativeLambdaStarter);
RN/RNFluxDemo/components/Error.js
puyanLiu/LPYFramework
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { StyleSheet, Text, View, Animated, Dimensions } from 'react-native'; import { Actions } from 'react-native-router-flux'; import Button from "react-native-button"; var { height: deviceHeight } = Dimensions.get('window'); class Error extends Component { constructor(props) { super(props); this.state = { offsetY: new Animated.Value(-deviceHeight) }; } componentDidMount() { Animated.timing(this.state.offsetY, { duration: 150, toValue: 0 }).start(); } closeModal() { Animated.timing(this.state.offsetY, { duration: 150, toValue: -deviceHeight }).start(Actions.pop); } render() { return ( <Animated.View style={[styles.container, {transform: [{translateY: this.state.offsetY}]}]}> <View style={{ width: 250, height: 250, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white'}}> <Text style={styles.welcome}> Error: {this.props.data} </Text> <Button onPress={this.closeModal.bind(this)}>Close</Button> </View> </Animated.View> ); } } const styles = StyleSheet.create({ container: { justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(52,52,52,0.5)', position: 'absolute', top: 0, left: 0, bottom: 0, right: 0, }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, } }); export default Error;
docs/src/app/components/pages/components/DatePicker/ExampleDisableDates.js
spiermar/material-ui
import React from 'react'; import DatePicker from 'material-ui/DatePicker'; function disableWeekends(date) { return date.getDay() === 0 || date.getDay() === 6; } function disableRandomDates() { return Math.random() > 0.7; } /** * `DatePicker` can disable specific dates based on the return value of a callback. */ const DatePickerExampleDisableDates = () => ( <div> <DatePicker hintText="Weekends Disabled" shouldDisableDate={disableWeekends} /> <DatePicker hintText="Random Dates Disabled" shouldDisableDate={disableRandomDates} /> </div> ); export default DatePickerExampleDisableDates;
js/components/inputgroup/index.js
yasster/Divide-react-native
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Container, Header, Title, Content, Button, Icon, InputGroup, Input, Textarea } from 'native-base'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; class NHInputGroup extends Component { // eslint-disable-line static propTypes = { openDrawer: React.PropTypes.func, } render() { return ( <Container style={styles.container}> <Header> <Title>InputGroup</Title> <Button transparent onPress={this.props.openDrawer}> <Icon name="ios-menu" /> </Button> </Header> <Content padder> <InputGroup borderType="regular" style={styles.mb}> <Input placeholder="Regular Textbox" /> </InputGroup> <InputGroup borderType="underline" style={styles.mb}> <Input placeholder="Underlined Textbox" /> </InputGroup> <InputGroup borderType="rounded" style={styles.mb}> <Input placeholder="Rounded Textbox" /> </InputGroup> <InputGroup style={styles.mb}> <Icon name="ios-home" style={{ color: '#00C497' }} /> <Input placeholder="Icon Textbox" /> </InputGroup> <InputGroup iconRight style={styles.mb}> <Icon name="ios-swap" style={{ color: '#00C497' }} /> <Input placeholder="Icon Alignment in Textbox" /> </InputGroup> <InputGroup iconRight success style={styles.mb}> <Icon name="ios-checkmark-circle" style={{ color: '#00C497' }} /> <Input placeholder="Textbox with Success Input" /> </InputGroup> <InputGroup iconRight error style={styles.mb}> <Icon name="ios-close-circle" style={{ color: 'red' }} /> <Input placeholder="Textbox with Error Input" /> </InputGroup> <InputGroup iconRight disabled style={styles.mb}> <Icon name="ios-information-circle" style={{ color: '#384850' }} /> <Input placeholder="Disabled Textbox" /> </InputGroup> <Textarea placeholder="Textarea" style={{ height: 60 }} /> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, }); export default connect(mapStateToProps, bindAction)(NHInputGroup);
node_modules/antd/es/transfer/index.js
prodigalyijun/demo-by-antd
import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import List from './list'; import Operation from './operation'; import Search from './search'; import injectLocale from '../locale-provider/injectLocale'; function noop() {} var Transfer = function (_React$Component) { _inherits(Transfer, _React$Component); function Transfer(props) { _classCallCheck(this, Transfer); var _this = _possibleConstructorReturn(this, (Transfer.__proto__ || Object.getPrototypeOf(Transfer)).call(this, props)); _this.moveTo = function (direction) { var _this$props = _this.props, _this$props$targetKey = _this$props.targetKeys, targetKeys = _this$props$targetKey === undefined ? [] : _this$props$targetKey, _this$props$dataSourc = _this$props.dataSource, dataSource = _this$props$dataSourc === undefined ? [] : _this$props$dataSourc, onChange = _this$props.onChange; var _this$state = _this.state, sourceSelectedKeys = _this$state.sourceSelectedKeys, targetSelectedKeys = _this$state.targetSelectedKeys; var moveKeys = direction === 'right' ? sourceSelectedKeys : targetSelectedKeys; // filter the disabled options var newMoveKeys = moveKeys.filter(function (key) { return !dataSource.some(function (data) { return !!(key === data.key && data.disabled); }); }); // move items to target box var newTargetKeys = direction === 'right' ? newMoveKeys.concat(targetKeys) : targetKeys.filter(function (targetKey) { return newMoveKeys.indexOf(targetKey) === -1; }); // empty checked keys var oppositeDirection = direction === 'right' ? 'left' : 'right'; _this.setState(_defineProperty({}, _this.getSelectedKeysName(oppositeDirection), [])); _this.handleSelectChange(oppositeDirection, []); if (onChange) { onChange(newTargetKeys, direction, newMoveKeys); } }; _this.moveToLeft = function () { return _this.moveTo('left'); }; _this.moveToRight = function () { return _this.moveTo('right'); }; _this.handleSelectAll = function (direction, filteredDataSource, checkAll) { var originalSelectedKeys = _this.state[_this.getSelectedKeysName(direction)] || []; var currentKeys = filteredDataSource.map(function (item) { return item.key; }); // Only operate current keys from original selected keys var newKeys1 = originalSelectedKeys.filter(function (key) { return currentKeys.indexOf(key) === -1; }); var newKeys2 = [].concat(_toConsumableArray(originalSelectedKeys)); currentKeys.forEach(function (key) { if (newKeys2.indexOf(key) === -1) { newKeys2.push(key); } }); var holder = checkAll ? newKeys1 : newKeys2; _this.handleSelectChange(direction, holder); if (!_this.props.selectedKeys) { _this.setState(_defineProperty({}, _this.getSelectedKeysName(direction), holder)); } }; _this.handleLeftSelectAll = function (filteredDataSource, checkAll) { return _this.handleSelectAll('left', filteredDataSource, checkAll); }; _this.handleRightSelectAll = function (filteredDataSource, checkAll) { return _this.handleSelectAll('right', filteredDataSource, checkAll); }; _this.handleFilter = function (direction, e) { _this.setState(_defineProperty({}, direction + 'Filter', e.target.value)); if (_this.props.onSearchChange) { _this.props.onSearchChange(direction, e); } }; _this.handleLeftFilter = function (e) { return _this.handleFilter('left', e); }; _this.handleRightFilter = function (e) { return _this.handleFilter('right', e); }; _this.handleClear = function (direction) { _this.setState(_defineProperty({}, direction + 'Filter', '')); }; _this.handleLeftClear = function () { return _this.handleClear('left'); }; _this.handleRightClear = function () { return _this.handleClear('right'); }; _this.handleSelect = function (direction, selectedItem, checked) { var _this$state2 = _this.state, sourceSelectedKeys = _this$state2.sourceSelectedKeys, targetSelectedKeys = _this$state2.targetSelectedKeys; var holder = direction === 'left' ? [].concat(_toConsumableArray(sourceSelectedKeys)) : [].concat(_toConsumableArray(targetSelectedKeys)); var index = holder.indexOf(selectedItem.key); if (index > -1) { holder.splice(index, 1); } if (checked) { holder.push(selectedItem.key); } _this.handleSelectChange(direction, holder); if (!_this.props.selectedKeys) { _this.setState(_defineProperty({}, _this.getSelectedKeysName(direction), holder)); } }; _this.handleLeftSelect = function (selectedItem, checked) { return _this.handleSelect('left', selectedItem, checked); }; _this.handleRightSelect = function (selectedItem, checked) { return _this.handleSelect('right', selectedItem, checked); }; _this.handleScroll = function (direction, e) { var onScroll = _this.props.onScroll; if (onScroll) { onScroll(direction, e); } }; _this.handleLeftScroll = function (e) { return _this.handleScroll('left', e); }; _this.handleRightScroll = function (e) { return _this.handleScroll('right', e); }; var _props$selectedKeys = props.selectedKeys, selectedKeys = _props$selectedKeys === undefined ? [] : _props$selectedKeys, _props$targetKeys = props.targetKeys, targetKeys = _props$targetKeys === undefined ? [] : _props$targetKeys; _this.state = { leftFilter: '', rightFilter: '', sourceSelectedKeys: selectedKeys.filter(function (key) { return targetKeys.indexOf(key) === -1; }), targetSelectedKeys: selectedKeys.filter(function (key) { return targetKeys.indexOf(key) > -1; }) }; return _this; } _createClass(Transfer, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var _state = this.state, sourceSelectedKeys = _state.sourceSelectedKeys, targetSelectedKeys = _state.targetSelectedKeys; if (nextProps.targetKeys !== this.props.targetKeys || nextProps.dataSource !== this.props.dataSource) { // clear cached splited dataSource this.splitedDataSource = null; if (!nextProps.selectedKeys) { // clear key nolonger existed // clear checkedKeys according to targetKeys var dataSource = nextProps.dataSource, _nextProps$targetKeys = nextProps.targetKeys, targetKeys = _nextProps$targetKeys === undefined ? [] : _nextProps$targetKeys; var newSourceSelectedKeys = []; var newTargetSelectedKeys = []; dataSource.forEach(function (_ref) { var key = _ref.key; if (sourceSelectedKeys.includes(key) && !targetKeys.includes(key)) { newSourceSelectedKeys.push(key); } if (targetSelectedKeys.includes(key) && targetKeys.includes(key)) { newTargetSelectedKeys.push(key); } }); this.setState({ sourceSelectedKeys: newSourceSelectedKeys, targetSelectedKeys: newTargetSelectedKeys }); } } if (nextProps.selectedKeys) { var _targetKeys = nextProps.targetKeys; this.setState({ sourceSelectedKeys: nextProps.selectedKeys.filter(function (key) { return !_targetKeys.includes(key); }), targetSelectedKeys: nextProps.selectedKeys.filter(function (key) { return _targetKeys.includes(key); }) }); } } }, { key: 'splitDataSource', value: function splitDataSource(props) { if (this.splitedDataSource) { return this.splitedDataSource; } var dataSource = props.dataSource, rowKey = props.rowKey, _props$targetKeys2 = props.targetKeys, targetKeys = _props$targetKeys2 === undefined ? [] : _props$targetKeys2; var leftDataSource = []; var rightDataSource = new Array(targetKeys.length); dataSource.forEach(function (record) { if (rowKey) { record.key = rowKey(record); } // rightDataSource should be ordered by targetKeys // leftDataSource should be ordered by dataSource var indexOfKey = targetKeys.indexOf(record.key); if (indexOfKey !== -1) { rightDataSource[indexOfKey] = record; } else { leftDataSource.push(record); } }); this.splitedDataSource = { leftDataSource: leftDataSource, rightDataSource: rightDataSource }; return this.splitedDataSource; } }, { key: 'handleSelectChange', value: function handleSelectChange(direction, holder) { var _state2 = this.state, sourceSelectedKeys = _state2.sourceSelectedKeys, targetSelectedKeys = _state2.targetSelectedKeys; var onSelectChange = this.props.onSelectChange; if (!onSelectChange) { return; } if (direction === 'left') { onSelectChange(holder, targetSelectedKeys); } else { onSelectChange(sourceSelectedKeys, holder); } } }, { key: 'getTitles', value: function getTitles() { var props = this.props; if (props.titles) { return props.titles; } var transferLocale = this.getLocale(); return transferLocale.titles; } }, { key: 'getSelectedKeysName', value: function getSelectedKeysName(direction) { return direction === 'left' ? 'sourceSelectedKeys' : 'targetSelectedKeys'; } }, { key: 'render', value: function render() { var locale = this.getLocale(); var _props = this.props, _props$prefixCls = _props.prefixCls, prefixCls = _props$prefixCls === undefined ? 'ant-transfer' : _props$prefixCls, className = _props.className, _props$operations = _props.operations, operations = _props$operations === undefined ? [] : _props$operations, showSearch = _props.showSearch, _props$notFoundConten = _props.notFoundContent, notFoundContent = _props$notFoundConten === undefined ? locale.notFoundContent : _props$notFoundConten, _props$searchPlacehol = _props.searchPlaceholder, searchPlaceholder = _props$searchPlacehol === undefined ? locale.searchPlaceholder : _props$searchPlacehol, body = _props.body, footer = _props.footer, listStyle = _props.listStyle, filterOption = _props.filterOption, render = _props.render, lazy = _props.lazy; var _state3 = this.state, leftFilter = _state3.leftFilter, rightFilter = _state3.rightFilter, sourceSelectedKeys = _state3.sourceSelectedKeys, targetSelectedKeys = _state3.targetSelectedKeys; var _splitDataSource = this.splitDataSource(this.props), leftDataSource = _splitDataSource.leftDataSource, rightDataSource = _splitDataSource.rightDataSource; var leftActive = targetSelectedKeys.length > 0; var rightActive = sourceSelectedKeys.length > 0; var cls = classNames(className, prefixCls); var titles = this.getTitles(); return React.createElement( 'div', { className: cls }, React.createElement(List, { prefixCls: prefixCls + '-list', titleText: titles[0], dataSource: leftDataSource, filter: leftFilter, filterOption: filterOption, style: listStyle, checkedKeys: sourceSelectedKeys, handleFilter: this.handleLeftFilter, handleClear: this.handleLeftClear, handleSelect: this.handleLeftSelect, handleSelectAll: this.handleLeftSelectAll, render: render, showSearch: showSearch, searchPlaceholder: searchPlaceholder, notFoundContent: notFoundContent, itemUnit: locale.itemUnit, itemsUnit: locale.itemsUnit, body: body, footer: footer, lazy: lazy, onScroll: this.handleLeftScroll }), React.createElement(Operation, { className: prefixCls + '-operation', rightActive: rightActive, rightArrowText: operations[0], moveToRight: this.moveToRight, leftActive: leftActive, leftArrowText: operations[1], moveToLeft: this.moveToLeft }), React.createElement(List, { prefixCls: prefixCls + '-list', titleText: titles[1], dataSource: rightDataSource, filter: rightFilter, filterOption: filterOption, style: listStyle, checkedKeys: targetSelectedKeys, handleFilter: this.handleRightFilter, handleClear: this.handleRightClear, handleSelect: this.handleRightSelect, handleSelectAll: this.handleRightSelectAll, render: render, showSearch: showSearch, searchPlaceholder: searchPlaceholder, notFoundContent: notFoundContent, itemUnit: locale.itemUnit, itemsUnit: locale.itemsUnit, body: body, footer: footer, lazy: lazy, onScroll: this.handleRightScroll }) ); } }]); return Transfer; }(React.Component); // For high-level customized Transfer @dqaria Transfer.List = List; Transfer.Operation = Operation; Transfer.Search = Search; Transfer.defaultProps = { dataSource: [], render: noop, showSearch: false }; Transfer.propTypes = { prefixCls: PropTypes.string, dataSource: PropTypes.array, render: PropTypes.func, targetKeys: PropTypes.array, onChange: PropTypes.func, height: PropTypes.number, listStyle: PropTypes.object, className: PropTypes.string, titles: PropTypes.array, operations: PropTypes.array, showSearch: PropTypes.bool, filterOption: PropTypes.func, searchPlaceholder: PropTypes.string, notFoundContent: PropTypes.node, body: PropTypes.func, footer: PropTypes.func, rowKey: PropTypes.func, lazy: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]) }; var injectTransferLocale = injectLocale('Transfer', { titles: ['', ''], searchPlaceholder: 'Search', notFoundContent: 'Not Found' }); export default injectTransferLocale(Transfer);
src/index.js
unikorp/king
import React from 'react'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import Root from './containers/Root'; import configureStore from './store/configureStore'; const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); render( <Root store={store} history={history} />, document.getElementById('app'), );
routes/assets-html.js
joeybaker/rachelandjoey
import path from 'path' import fs from 'fs' import ReactRoutes from '../components/_routes/' import ReactData from '../components/_routes/example/data.js' import versions from '../versions.json' import React from 'react' import ReactRouter from 'react-router' const expiresIn = 1000 * 60 * 60 * 24 const html = fs.readFileSync(path.join(__dirname, '..', 'static', 'index.html')).toString() .replace('/index.js', `/${versions.js}/index.js`) .replace('/entry.css', `/${versions.css}/entry.css`) const htmlCache = {} const handler = (req, reply) => { // TODO: move this to a server method if (htmlCache[req.path]) { const response = reply(htmlCache[req.path]).type('text/html') // TODO: remove this. it's because I fucked up and the cache needs to be busted response.ttl(expiresIn) } else { ReactRouter.run(ReactRoutes, req.path, (Handler) => { const initialHTML = React.renderToString(React.createElement(Handler, ReactData)) let title = 'Rachel & Joey' if (React.documentHead) { title = React.documentHead.title React.documentHead = {} } const outHtml = html .replace('id="app">', 'id="app">' + initialHTML) .replace('<title>Rachel & Joey</title>', `<title>${title}</title>`) const response = reply(outHtml).type('text/html') htmlCache[req.path] = outHtml // TODO: remove this. it's because I fucked up and the cache needs to be busted response.ttl(expiresIn) }) } } export default { path: '/{path*}' , method: 'GET' , config: { handler , cache: { privacy: 'public' , expiresIn: expiresIn } , tags: ['assets', 'html'] , description: 'single html file' } }
src/rocks/debugger-tab/index.js
animachine/animachine
import React from 'react' import DebuggerTab from './DebuggerTab' BETON.require('workspace', init) function init(workspace) { // workspace.setTabContent('debugger', () => <DebuggerTab/>) }
src/svg-icons/editor/border-clear.js
barakmitz/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;
docs/src/pages/components/tables/BasicTable.js
lgollut/material-ui
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; const useStyles = makeStyles({ table: { minWidth: 650, }, }); function createData(name, calories, fat, carbs, protein) { return { name, calories, fat, carbs, protein }; } const rows = [ createData('Frozen yoghurt', 159, 6.0, 24, 4.0), createData('Ice cream sandwich', 237, 9.0, 37, 4.3), createData('Eclair', 262, 16.0, 24, 6.0), createData('Cupcake', 305, 3.7, 67, 4.3), createData('Gingerbread', 356, 16.0, 49, 3.9), ]; export default function BasicTable() { const classes = useStyles(); return ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell>Dessert (100g serving)</TableCell> <TableCell align="right">Calories</TableCell> <TableCell align="right">Fat&nbsp;(g)</TableCell> <TableCell align="right">Carbs&nbsp;(g)</TableCell> <TableCell align="right">Protein&nbsp;(g)</TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row) => ( <TableRow key={row.name}> <TableCell component="th" scope="row"> {row.name} </TableCell> <TableCell align="right">{row.calories}</TableCell> <TableCell align="right">{row.fat}</TableCell> <TableCell align="right">{row.carbs}</TableCell> <TableCell align="right">{row.protein}</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ); }
client/src/__mocks__/monacoEditorMock.js
pahosler/freecodecamp
/* eslint-disable */ import React from 'react'; export default props => { const { width = '100%', height = '100%' } = props; const fixedWidth = width.toString().indexOf('%') !== -1 ? width : `${width}px`; const fixedHeight = height.toString().indexOf('%') !== -1 ? height : `${height}px`; const style = { width: fixedWidth, height: fixedHeight }; return <div style={style} className="react-monaco-editor-container" />; };
src/components/dashboard/ClassList.js
caoquan95/colorme-manage
import React from 'react'; import Switch from 'react-bootstrap-switch'; const ClassList = ({classes}) => { return ( <div className="panel-body"> <div className="table-responsive"> <table className="table table-bordered table-hover table-striped"> <thead> <tr> <th/> <th>Lớp</th> <th>Cơ sở</th> <th>Học viên đã nộp tiền</th> <th>Số người đăng kí</th> <th>Thời gian học</th> <th>Ngày khai giảng</th> <th>Trạng thái lớp</th> <th>Kích hoạt</th> </tr> </thead> <tbody> {classes.map(function (classes, index) { return ( <tr key={index}> <td><img src={classes.avatar_url} style={{width: "40px", height: "40px", borderRadius: "25px"}}/></td> <td>{classes.name}</td> <td>{classes.name}</td> <td> <div>{classes.total_paid + "/" + classes.paid_target}</div> <div className="progress" style={{height: "5px"}}> <div className="progress-bar progress-bar-success" role="progressbar" style={{width: (classes.total_paid / classes.paid_target) * 100 + "%"}}> </div> </div> </td> <td> <div>{classes.total_registers + "/" + classes.register_target}</div> <div className="progress" style={{height: "5px"}}> <div className="progress-bar progress-bar-info" role="progressbar" style={{width: (classes.total_registers / classes.register_target) * 100 + "%"}}> </div> </div> </td> <td>{classes.study_time}</td> <td>{classes.datestart}</td> <td><Switch bsSize="mini" onText="Bật" offText="Tắt" value={(classes.status != 0)}/></td> <td> <button type="button" className="btn btn-xs btn-success">Kích hoạt</button> </td> </tr> ) })} </tbody> </table> </div> </div> ) } export default ClassList;
src/components/NotFound.js
unikorp/king
import React from 'react'; const NotFound = () => ( <p> Sorry, we cannot found this page. </p> ); export default NotFound;
src/app/components/P/index.js
nhardy/web-scaffold
// @flow /* eslint-disable react/prop-types */ import React, { Component } from 'react'; import type { Node } from 'react'; import cx from 'classnames'; import { isScrolledIntoView } from 'app/lib/dom'; import throttle from 'app/lib/throttle'; import styles from './styles.styl'; type Props = { className?: string, children?: Node, }; type State = { visible: boolean, }; export default class P extends Component<Props, State> { state = { visible: false, }; componentDidMount() { window.addEventListener('scroll', this.update, { passive: true }); this.update(); } componentWillUnmount() { window.removeEventListener('scroll', this.update, { passive: true }); this.update.cancel(); } update = throttle(() => { const visible = this._node ? isScrolledIntoView(this._node) : false; if (this.state.visible !== visible) { this.setState({ visible, }); } }); _node: ?HTMLParagraphElement; render() { const { className, children, ...props } = this.props; return ( <p className={cx(styles.root, { [styles.visible]: this.state.visible }, className)} ref={ref => (this._node = ref)} {...props}> {children} </p> ); } }
react/features/base/react/components/web/NavigateSectionListItem.js
gpolitis/jitsi-meet
// @flow import React, { Component } from 'react'; import type { Item } from '../../Types'; import Container from './Container'; import Text from './Text'; /** * The type of the React {@code Component} props of * {@link NavigateSectionListItem}. */ type Props = { /** * Function to be invoked when an item is pressed. The item's URL is passed. */ onPress: ?Function, /** * A item containing data to be rendered. */ item: Item }; /** * Implements a React/Web {@link Component} for displaying an item in a * NavigateSectionList. * * @augments Component */ export default class NavigateSectionListItem<P: Props> extends Component<P> { /** * Renders the content of this component. * * @returns {ReactElement} */ render() { const { elementAfter, lines, title } = this.props.item; const { onPress } = this.props; /** * Initializes the date and duration of the conference to the an empty * string in case for some reason there is an error where the item data * lines doesn't contain one or both of those values (even though this * unlikely the app shouldn't break because of it). * * @type {string} */ let date = ''; let duration = ''; if (lines[0]) { date = lines[0]; } if (lines[1]) { duration = lines[1]; } const rootClassName = `navigate-section-list-tile ${ onPress ? 'with-click-handler' : 'without-click-handler'}`; return ( <Container className = { rootClassName } onClick = { onPress }> <Container className = 'navigate-section-list-tile-info'> <Text className = 'navigate-section-tile-title'> { title } </Text> <Text className = 'navigate-section-tile-body'> { date } </Text> <Text className = 'navigate-section-tile-body'> { duration } </Text> </Container> <Container className = { 'element-after' }> { elementAfter || null } </Container> </Container> ); } }
app/components/Report/ChartModal.js
Bullseyed/Bullseye
import React from 'react'; import { Row, Col, Modal } from 'react-materialize'; import Charts from './Charts'; import Piechart from './PieChart'; import Bargraph from './BarGraph'; const ChartModal = ({demoData}) => { return ( <Modal header="Statistics" trigger={ <div> <Charts /> </div> } style = {{height: '100%', width: '85%'}} > <Row className="valign-wrapper" height={ '100%' }> <Col l={12} height={'100%'}> { demoData.barGraph && demoData.barGraph.map((graph) => { return ( <Col l={6} key={graph.graphTitle} style={{ paddingBottom: 50 }}> {graph.graphTitle} <Bargraph demoData={graph} /> </Col> ); }) } { demoData.pieChart && demoData.pieChart.map((chart) => { return ( <Col l={6} key={chart.graphTitle} style={{ paddingBottom: 50 }}> {chart.graphTitle} <Piechart demoData={chart} /> </Col> ); }) } </Col> </Row> </Modal> ); }; export default ChartModal;
examples/basic/simple_usage/index.js
reactjs/react-modal
import React, { Component } from 'react'; import Modal from 'react-modal'; import MyModal from './modal'; const MODAL_A = 'modal_a'; const MODAL_B = 'modal_b'; const DEFAULT_TITLE = 'Default title'; class SimpleUsage extends Component { constructor(props) { super(props); this.state = { title1: DEFAULT_TITLE, currentModal: null }; } toggleModal = key => event => { event.preventDefault(); if (this.state.currentModal) { this.handleModalCloseRequest(); return; } this.setState({ ...this.state, currentModal: key, title1: DEFAULT_TITLE }); } handleModalCloseRequest = () => { // opportunity to validate something and keep the modal open even if it // requested to be closed this.setState({ ...this.state, currentModal: null }); } handleInputChange = e => { let text = e.target.value; if (text == '') { text = DEFAULT_TITLE; } this.setState({ ...this.state, title1: text }); } handleOnAfterOpenModal = () => { // when ready, we can access the available refs. this.heading && (this.heading.style.color = '#F00'); } render() { const { currentModal } = this.state; return ( <div> <button type="button" className="btn btn-primary" onClick={this.toggleModal(MODAL_A)}>Open Modal A</button> <button type="button" className="btn btn-primary" onClick={this.toggleModal(MODAL_B)}>Open Modal B</button> <MyModal title={this.state.title1} isOpen={currentModal == MODAL_A} onAfterOpen={this.handleOnAfterOpenModal} onRequestClose={this.handleModalCloseRequest} askToClose={this.toggleModal(MODAL_A)} onChangeInput={this.handleInputChange} /> <Modal ref="mymodal2" id="test2" aria={{ labelledby: "heading", describedby: "fulldescription" }} closeTimeoutMS={150} contentLabel="modalB" isOpen={currentModal == MODAL_B} shouldCloseOnOverlayClick={false} onAfterOpen={this.handleOnAfterOpenModal} onRequestClose={this.toggleModal(MODAL_B)}> <h1 id="heading" ref={h1 => this.heading = h1}>This is the modal 2!</h1> <div id="fulldescription" tabIndex="0" role="document"> <p>This is a description of what it does: nothing :)</p> <button onClick={this.toggleModal(MODAL_B)}>close</button> </div> </Modal> </div> ); } } export default { label: "Working with one modal at a time.", app: SimpleUsage };
app/jsx/courses/HomePagePromptContainer.js
djbender/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import PropTypes from 'prop-types' import CourseHomeDialog from './CourseHomeDialog' import I18n from 'i18n!home_page_prompt' import $ from 'jquery' import 'compiled/jquery.rails_flash_notifications' class HomePagePromptContainer extends React.Component { static propTypes = { store: PropTypes.object.isRequired, onSubmit: PropTypes.func.isRequired, wikiFrontPageTitle: PropTypes.string, wikiUrl: PropTypes.string.isRequired, courseId: PropTypes.string.isRequired, forceOpen: PropTypes.bool.isRequired, returnFocusTo: PropTypes.instanceOf(Element).isRequired } state = { dialogOpen: true } componentDidMount() { this.flashScreenReaderAlert() } componentWillReceiveProps(nextProps) { if (nextProps.forceOpen) { this.setState({dialogOpen: true}) this.flashScreenReaderAlert() } } flashScreenReaderAlert() { $.screenReaderFlashMessage( I18n.t( 'Before publishing your course, you must either publish a module or choose a different home page.' ) ) } render() { return this.state.dialogOpen ? ( <CourseHomeDialog store={this.props.store} open={this.state.dialogOpen} onRequestClose={this.onClose} courseId={this.props.courseId} wikiFrontPageTitle={this.props.wikiFrontPageTitle} wikiUrl={this.props.wikiUrl} onSubmit={this.props.onSubmit} returnFocusTo={this.props.returnFocusTo} isPublishing /> ) : ( <></> ) } onClose = () => { this.setState({dialogOpen: false}) } } export default HomePagePromptContainer
src/browser/components/Home/Home.js
2rajpx/gitux
import React from 'react' export default props => ( <p> Home </p> )
fixtures/react_native_windows_vnext/src/host.js
callstack-io/haul
import React from 'react'; import { AppRegistry, View, Text, Linking } from 'react-native'; import { createAppContainer, createBottomTabNavigator, NavigationActions } from 'react-navigation'; import { ApolloClient } from 'apollo-client'; import { ApolloProvider } from 'react-apollo'; import { createHttpLink } from 'apollo-link-http'; import { InMemoryCache } from 'apollo-cache-inmemory'; import EmptyHost from './EmptyHost'; import BundleRegistry from './BundleRegistry'; function makeScreenForAppBundle(bundleName) { const screen = (props) => { if (!BundleRegistry.isBundleLoaded(bundleName)) { throw new Error(`App bundle ${bundleName} was not loaded`); } const Component = BundleRegistry.getBundleExport(bundleName); return <Component {...props} /> }; return { screen, navigationOptions: { tabBarOnPress: ({ navigation, defaultHandler }) => { if (BundleRegistry.isBundleLoaded(bundleName)) { defaultHandler(); } else { const listener = ({ bundleName: currentlyLoadedBundle, loadStartTimestamp }) => { if (currentlyLoadedBundle === bundleName) { BundleRegistry.removeListener('bundleLoaded', listener); navigation.setParams({ loadStartTimestamp }); defaultHandler(); } }; BundleRegistry.addListener('bundleLoaded', listener); BundleRegistry.loadBundle(bundleName); } } } } } const AppContainer = createAppContainer( createBottomTabNavigator({ Initial: EmptyHost, app0: makeScreenForAppBundle('app0'), app1: makeScreenForAppBundle('app1'), }, { initialRouteName: 'Initial', }) ); BundleRegistry.enableLogging(); const cache = new InMemoryCache(); const apolloClient = new ApolloClient({ link: createHttpLink({ uri: "https://48p1r2roz4.sse.codesandbox.io" }), cache }); class RootComponent extends React.Component { constructor(props) { super(props) } navigatorRef = React.createRef(); handleURL = (event) => { const [, bundleName] = event.url.match(/.+\/\/(.+)/); BundleRegistry.loadBundle(bundleName); } onBundleLoaded = ({ bundleName, loadStartTimestamp }) => { if (this.navigatorRef.current) { this.navigatorRef.current.dispatch(NavigationActions.navigate({ routeName: bundleName, params: { loadStartTimestamp } })); } } async componentDidMount() { BundleRegistry.addListener('bundleLoaded', this.onBundleLoaded); Linking.addEventListener('url', this.handleURL); const initialUrl = await Linking.getInitialURL(); if (initialUrl) { this.handleURL({ url: initialUrl }); } } componentWillUnmount() { Linking.removeListener('url', this.handleURL); BundleRegistry.removeListener('bundleLoaded', this.onBundleLoaded); } render() { return ( <View style={{ flex: 1, width: '100%' }}> <ApolloProvider client={apolloClient}> <AppContainer ref={this.navigatorRef} // we handle deep linking manually enableURLHandling={false} /> </ApolloProvider> </View> ) } } AppRegistry.registerComponent('react_native_windows_current', () => RootComponent);
src/block.js
awkward/react-simple-masonry
import React from 'react' export default ({ width, height, x, y, children }) => { const style = { width, height, transform: `translate3d(${x}px, ${y}px, 0)`, position: 'absolute', top: 0, left: 0, border: `1px solid`, transition: `transform .2s` } return ( <div style={style}> {children} </div> ) }
examples/shared-root/app.js
freeyiyi1993/react-router
import React from 'react'; import { history } from 'react-router/lib/HashHistory'; import { Router, Route, Link } from 'react-router'; var App = React.createClass({ render() { return ( <div> <p> This illustrates how routes can share UI w/o sharing the url, when routes have no path, they never match themselves but their children can, allowing "/signin" and "/forgot-password" to both be render in the <code>SignedOut</code> component. </p> <ol> <li><Link to="/home">Home</Link></li> <li><Link to="/signin">Sign in</Link></li> <li><Link to="/forgot-password">Forgot Password</Link></li> </ol> {this.props.children} </div> ); } }); var SignedIn = React.createClass({ render() { return ( <div> <h2>Signed In</h2> {this.props.children} </div> ); } }); var Home = React.createClass({ render() { return ( <h3>Welcome home!</h3> ); } }); var SignedOut = React.createClass({ render() { return ( <div> <h2>Signed Out</h2> {this.props.children} </div> ); } }); var SignIn = React.createClass({ render() { return ( <h3>Please sign in.</h3> ); } }); var ForgotPassword = React.createClass({ render() { return ( <h3>Forgot your password?</h3> ); } }); React.render(( <Router history={history}> <Route path="/" component={App}> <Route component={SignedOut}> <Route path="signin" component={SignIn}/> <Route path="forgot-password" component={ForgotPassword}/> </Route> <Route component={SignedIn}> <Route path="home" component={Home}/> </Route> </Route> </Router> ), document.getElementById('example'));
src/containers/main/product-list-container.js
menthena/project-a
import React from 'react'; import { connect } from 'react-redux'; import Query from '../../components/query'; import Filter from '../../components/filter'; import Sorter from '../../components/sorter'; import './styles/product-list-container.css'; import { ProductList } from '../../components/generic-list'; import { selectProduct, filterProducts, sortProducts } from '../../actions/product-actions'; import { fetchCategories } from '../../actions/product-actions'; import LoadingIndicator from '../../components/common/loading-indicator'; class ProductListContainer extends React.Component { render() { const { isFetching, sortProducts, filterProducts, selectedCategory, products, selectedProduct, selectProduct, sortBy, displaySortOptions } = this.props; return ( <div className="product-list-content"> { isFetching && <LoadingIndicator /> } { selectedCategory && ( <div> <div className="flex"> <Filter labelText="Filter:" placeholder="Filter products..." handleOnChange={query => { filterProducts(selectedCategory.categoryId, query); }} /> <Sorter handleOnChange={sortIndex => { sortProducts(selectedCategory.categoryId, sortIndex); }} sortBy={sortBy} displayOptions={displaySortOptions} /> </div> <ProductList items={products} thumbnailURL={''} itemName={'productName'} dispatchEvent={selectProduct} selectedItem={selectedProduct} /> </div> )} </div> ); } } const mapStateToProps = (state, ownProps) => { return { selectedProduct: state.productReducer.selectedProduct, selectedCategory: state.categoryReducer.selectedCategory, products: state.productReducer.products, isFetching: state.productReducer.isFetching, sortBy: state.productReducer.sortBy, displaySortOptions: state.productReducer.displaySortOptions }; }; const mapDispatchToProps = (dispatch) => { return { selectProduct: (item) => dispatch(selectProduct(item)), filterProducts: (categoryId, query) => dispatch(filterProducts(categoryId, query)), sortProducts: (categoryId, sortBy) => dispatch(sortProducts(categoryId, sortBy)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(ProductListContainer);
src/pages/IndexPage.js
janimattiellonen/fgr
import React from 'react'; import { Link } from 'react-router'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PersonList from '../components/PersonList'; import styles from './IndexPage.pcss'; const IndexPage = props => { const { persons, deletePerson } = props; return ( <section className={styles.root}> <Link to="/courses">Courses</Link> <div className={styles.column}> <h2>Young ones</h2> <PersonList deletePerson={deletePerson} persons={persons.filter(p => p.age < 40)} /> </div> <div className={styles.column}> <h2>Old Ones</h2> <PersonList deletePerson={deletePerson} persons={persons.filterNot(p => p.age < 40)} /> </div> </section> ); }; IndexPage.propTypes = { }; export default IndexPage;
www/src/templates/community.js
yangshun/react
/** * Copyright (c) 2013-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. * * @emails react-core */ 'use strict'; import MarkdownPage from 'components/MarkdownPage'; import PropTypes from 'prop-types'; import React from 'react'; import {createLinkCommunity} from 'utils/createLink'; import {sectionListCommunity} from 'utils/sectionList'; const Community = ({data, location}) => ( <MarkdownPage createLink={createLinkCommunity} location={location} markdownRemark={data.markdownRemark} sectionList={sectionListCommunity} titlePostfix=" - React" /> ); Community.propTypes = { data: PropTypes.object.isRequired, }; // eslint-disable-next-line no-undef export const pageQuery = graphql` query TemplateCommunityMarkdown($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { title next prev } fields { path slug } } } `; export default Community;
react/features/invite/components/dial-in-summary/native/DialInSummary.js
bgrozev/jitsi-meet
// @flow import React, { Component } from 'react'; import { Linking, View } from 'react-native'; import { WebView } from 'react-native-webview'; import { type Dispatch } from 'redux'; import { openDialog } from '../../../../base/dialog'; import { translate } from '../../../../base/i18n'; import { JitsiModal, setActiveModalId } from '../../../../base/modal'; import { LoadingIndicator } from '../../../../base/react'; import { connect } from '../../../../base/redux'; import { DIAL_IN_SUMMARY_VIEW_ID } from '../../../constants'; import { getDialInfoPageURLForURIString } from '../../../functions'; import DialInSummaryErrorDialog from './DialInSummaryErrorDialog'; import styles, { INDICATOR_COLOR } from './styles'; type Props = { /** * The URL to display the summary for. */ _summaryUrl: ?string, dispatch: Dispatch<any> }; /** * Implements a React native component that displays the dial in info page for a specific room. */ class DialInSummary extends Component<Props> { /** * Initializes a new instance. * * @inheritdoc */ constructor(props: Props) { super(props); this._onError = this._onError.bind(this); this._onNavigate = this._onNavigate.bind(this); this._renderLoading = this._renderLoading.bind(this); } /** * Implements React's {@link Component#render()}. * * @inheritdoc */ render() { const { _summaryUrl } = this.props; return ( <JitsiModal headerProps = {{ headerLabelKey: 'info.label' }} modalId = { DIAL_IN_SUMMARY_VIEW_ID } style = { styles.backDrop } > <WebView onError = { this._onError } onShouldStartLoadWithRequest = { this._onNavigate } renderLoading = { this._renderLoading } source = {{ uri: getDialInfoPageURLForURIString(_summaryUrl) }} startInLoadingState = { true } style = { styles.webView } /> </JitsiModal> ); } _onError: () => void; /** * Callback to handle the error if the page fails to load. * * @returns {void} */ _onError() { this.props.dispatch(setActiveModalId()); this.props.dispatch(openDialog(DialInSummaryErrorDialog)); } _onNavigate: Object => Boolean; /** * Callback to intercept navigation inside the webview and make the native app handle the dial requests. * * NOTE: We don't navigate to anywhere else form that view. * * @param {any} request - The request object. * @returns {boolean} */ _onNavigate(request) { const { url } = request; if (url.startsWith('tel:')) { Linking.openURL(url); this.props.dispatch(setActiveModalId()); } return url === getDialInfoPageURLForURIString(this.props._summaryUrl); } _renderLoading: () => React$Component<any>; /** * Renders the loading indicator. * * @returns {React$Component<any>} */ _renderLoading() { return ( <View style = { styles.indicatorWrapper }> <LoadingIndicator color = { INDICATOR_COLOR } size = 'large' /> </View> ); } } /** * Maps part of the Redux state to the props of this component. * * @param {Object} state - The Redux state. * @returns {{ * _summaryUrl: ?string * }} */ function _mapStateToProps(state) { return { _summaryUrl: (state['features/base/modal'].modalProps || {}).summaryUrl }; } export default translate(connect(_mapStateToProps)(DialInSummary));
docs/src/app/components/pages/components/Dialog/ExampleCustomWidth.js
ruifortes/material-ui
import React from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; const customContentStyle = { width: '100%', maxWidth: 'none', }; /** * The dialog width has been set to occupy the full width of browser through the `contentStyle` property. */ export default class DialogExampleCustomWidth extends React.Component { state = { open: false, }; handleOpen = () => { this.setState({open: true}); }; handleClose = () => { this.setState({open: false}); }; render() { const actions = [ <FlatButton label="Cancel" primary={true} onTouchTap={this.handleClose} />, <FlatButton label="Submit" primary={true} onTouchTap={this.handleClose} />, ]; return ( <div> <RaisedButton label="Dialog With Custom Width" onTouchTap={this.handleOpen} /> <Dialog title="Dialog With Custom Width" actions={actions} modal={true} contentStyle={customContentStyle} open={this.state.open} > This dialog spans the entire width of the screen. </Dialog> </div> ); } }
docs/src/app/components/pages/components/DatePicker/ExampleControlled.js
ichiohta/material-ui
import React from 'react'; import DatePicker from 'material-ui/DatePicker'; /** * `DatePicker` can be implemented as a controlled input, * where `value` is handled by state in the parent component. */ export default class DatePickerExampleControlled extends React.Component { constructor(props) { super(props); this.state = { controlledDate: null, }; } handleChange = (event, date) => { this.setState({ controlledDate: date, }); }; render() { return ( <DatePicker hintText="Controlled Date Input" value={this.state.controlledDate} onChange={this.handleChange} /> ); } }
src/App.js
Florenz23/wifi_signals
import React, { Component } from 'react'; import Graph from './scripts/components/graph' export default class App extends React.Component { state = { dataSetIndex: 0 , } static defaultProps = {views: [["day"],["simpleDay"],["Macs"]]} selectDataset(event) { this.setState({dataSetIndex: event.target.value}); } render() { let options = this.props.views.map((value, index) => { return <option key={index} value={index}>Ansicht {value}</option> }); return ( <div> <select value={this.state.dataSetIndex} onChange={this.selectDataset.bind(this)} > {options} </select> <Graph data={this.props.datasets} viewSelection={this.state.dataSetIndex} /> </div> ) } }
app/javascript/mastodon/components/status_action_bar.js
ashfurrow/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import IconButton from './icon_button'; import DropdownMenuContainer from '../containers/dropdown_menu_container'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { me, isStaff } from '../initial_state'; import classNames from 'classnames'; const messages = defineMessages({ delete: { id: 'status.delete', defaultMessage: 'Delete' }, redraft: { id: 'status.redraft', defaultMessage: 'Delete & re-draft' }, edit: { id: 'status.edit', defaultMessage: 'Edit' }, direct: { id: 'status.direct', defaultMessage: 'Direct message @{name}' }, mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' }, mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' }, block: { id: 'account.block', defaultMessage: 'Block @{name}' }, reply: { id: 'status.reply', defaultMessage: 'Reply' }, share: { id: 'status.share', defaultMessage: 'Share' }, more: { id: 'status.more', defaultMessage: 'More' }, replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' }, reblog: { id: 'status.reblog', defaultMessage: 'Boost' }, reblog_private: { id: 'status.reblog_private', defaultMessage: 'Boost with original visibility' }, cancel_reblog_private: { id: 'status.cancel_reblog_private', defaultMessage: 'Unboost' }, cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' }, favourite: { id: 'status.favourite', defaultMessage: 'Favourite' }, bookmark: { id: 'status.bookmark', defaultMessage: 'Bookmark' }, removeBookmark: { id: 'status.remove_bookmark', defaultMessage: 'Remove bookmark' }, open: { id: 'status.open', defaultMessage: 'Expand this status' }, report: { id: 'status.report', defaultMessage: 'Report @{name}' }, muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' }, unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' }, pin: { id: 'status.pin', defaultMessage: 'Pin on profile' }, unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' }, embed: { id: 'status.embed', defaultMessage: 'Embed' }, admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' }, admin_status: { id: 'status.admin_status', defaultMessage: 'Open this status in the moderation interface' }, copy: { id: 'status.copy', defaultMessage: 'Copy link to status' }, blockDomain: { id: 'account.block_domain', defaultMessage: 'Block domain {domain}' }, unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' }, unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' }, unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' }, }); const mapStateToProps = (state, { status }) => ({ relationship: state.getIn(['relationships', status.getIn(['account', 'id'])]), }); export default @connect(mapStateToProps) @injectIntl class StatusActionBar extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, relationship: ImmutablePropTypes.map, onReply: PropTypes.func, onFavourite: PropTypes.func, onReblog: PropTypes.func, onDelete: PropTypes.func, onDirect: PropTypes.func, onMention: PropTypes.func, onMute: PropTypes.func, onUnmute: PropTypes.func, onBlock: PropTypes.func, onUnblock: PropTypes.func, onBlockDomain: PropTypes.func, onUnblockDomain: PropTypes.func, onReport: PropTypes.func, onEmbed: PropTypes.func, onMuteConversation: PropTypes.func, onPin: PropTypes.func, onBookmark: PropTypes.func, withDismiss: PropTypes.bool, withCounters: PropTypes.bool, scrollKey: PropTypes.string, intl: PropTypes.object.isRequired, }; // Avoid checking props that are functions (and whose equality will always // evaluate to false. See react-immutable-pure-component for usage. updateOnProps = [ 'status', 'relationship', 'withDismiss', ] handleReplyClick = () => { if (me) { this.props.onReply(this.props.status, this.context.router.history); } else { this._openInteractionDialog('reply'); } } handleShareClick = () => { navigator.share({ text: this.props.status.get('search_index'), url: this.props.status.get('url'), }).catch((e) => { if (e.name !== 'AbortError') console.error(e); }); } handleFavouriteClick = () => { if (me) { this.props.onFavourite(this.props.status); } else { this._openInteractionDialog('favourite'); } } handleReblogClick = e => { if (me) { this.props.onReblog(this.props.status, e); } else { this._openInteractionDialog('reblog'); } } _openInteractionDialog = type => { window.open(`/interact/${this.props.status.get('id')}?type=${type}`, 'mastodon-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes'); } handleBookmarkClick = () => { this.props.onBookmark(this.props.status); } handleDeleteClick = () => { this.props.onDelete(this.props.status, this.context.router.history); } handleRedraftClick = () => { this.props.onDelete(this.props.status, this.context.router.history, true); } handleEditClick = () => { this.props.onEdit(this.props.status, this.context.router.history); } handlePinClick = () => { this.props.onPin(this.props.status); } handleMentionClick = () => { this.props.onMention(this.props.status.get('account'), this.context.router.history); } handleDirectClick = () => { this.props.onDirect(this.props.status.get('account'), this.context.router.history); } handleMuteClick = () => { const { status, relationship, onMute, onUnmute } = this.props; const account = status.get('account'); if (relationship && relationship.get('muting')) { onUnmute(account); } else { onMute(account); } } handleBlockClick = () => { const { status, relationship, onBlock, onUnblock } = this.props; const account = status.get('account'); if (relationship && relationship.get('blocking')) { onUnblock(account); } else { onBlock(status); } } handleBlockDomain = () => { const { status, onBlockDomain } = this.props; const account = status.get('account'); onBlockDomain(account.get('acct').split('@')[1]); } handleUnblockDomain = () => { const { status, onUnblockDomain } = this.props; const account = status.get('account'); onUnblockDomain(account.get('acct').split('@')[1]); } handleOpen = () => { this.context.router.history.push(`/@${this.props.status.getIn(['account', 'acct'])}/${this.props.status.get('id')}`); } handleEmbed = () => { this.props.onEmbed(this.props.status); } handleReport = () => { this.props.onReport(this.props.status); } handleConversationMuteClick = () => { this.props.onMuteConversation(this.props.status); } handleCopy = () => { const url = this.props.status.get('url'); const textarea = document.createElement('textarea'); textarea.textContent = url; textarea.style.position = 'fixed'; document.body.appendChild(textarea); try { textarea.select(); document.execCommand('copy'); } catch (e) { } finally { document.body.removeChild(textarea); } } render () { const { status, relationship, intl, withDismiss, withCounters, scrollKey } = this.props; const anonymousAccess = !me; const publicStatus = ['public', 'unlisted'].includes(status.get('visibility')); const pinnableStatus = ['public', 'unlisted', 'private'].includes(status.get('visibility')); const mutingConversation = status.get('muted'); const account = status.get('account'); const writtenByMe = status.getIn(['account', 'id']) === me; let menu = []; menu.push({ text: intl.formatMessage(messages.open), action: this.handleOpen }); if (publicStatus) { menu.push({ text: intl.formatMessage(messages.copy), action: this.handleCopy }); menu.push({ text: intl.formatMessage(messages.embed), action: this.handleEmbed }); } menu.push(null); menu.push({ text: intl.formatMessage(status.get('bookmarked') ? messages.removeBookmark : messages.bookmark), action: this.handleBookmarkClick }); if (writtenByMe && pinnableStatus) { menu.push({ text: intl.formatMessage(status.get('pinned') ? messages.unpin : messages.pin), action: this.handlePinClick }); } menu.push(null); if (writtenByMe || withDismiss) { menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick }); menu.push(null); } if (writtenByMe) { // menu.push({ text: intl.formatMessage(messages.edit), action: this.handleEditClick }); menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick }); menu.push({ text: intl.formatMessage(messages.redraft), action: this.handleRedraftClick }); } else { menu.push({ text: intl.formatMessage(messages.mention, { name: account.get('username') }), action: this.handleMentionClick }); menu.push({ text: intl.formatMessage(messages.direct, { name: account.get('username') }), action: this.handleDirectClick }); menu.push(null); if (relationship && relationship.get('muting')) { menu.push({ text: intl.formatMessage(messages.unmute, { name: account.get('username') }), action: this.handleMuteClick }); } else { menu.push({ text: intl.formatMessage(messages.mute, { name: account.get('username') }), action: this.handleMuteClick }); } if (relationship && relationship.get('blocking')) { menu.push({ text: intl.formatMessage(messages.unblock, { name: account.get('username') }), action: this.handleBlockClick }); } else { menu.push({ text: intl.formatMessage(messages.block, { name: account.get('username') }), action: this.handleBlockClick }); } menu.push({ text: intl.formatMessage(messages.report, { name: account.get('username') }), action: this.handleReport }); if (account.get('acct') !== account.get('username')) { const domain = account.get('acct').split('@')[1]; menu.push(null); if (relationship && relationship.get('domain_blocking')) { menu.push({ text: intl.formatMessage(messages.unblockDomain, { domain }), action: this.handleUnblockDomain }); } else { menu.push({ text: intl.formatMessage(messages.blockDomain, { domain }), action: this.handleBlockDomain }); } } if (isStaff) { menu.push(null); menu.push({ text: intl.formatMessage(messages.admin_account, { name: account.get('username') }), href: `/admin/accounts/${status.getIn(['account', 'id'])}` }); menu.push({ text: intl.formatMessage(messages.admin_status), href: `/admin/accounts/${status.getIn(['account', 'id'])}/statuses?id=${status.get('id')}` }); } } let replyIcon; let replyTitle; if (status.get('in_reply_to_id', null) === null) { replyTitle = intl.formatMessage(messages.reply); replyIcon = 'reply'; } else { replyTitle = intl.formatMessage(messages.replyAll); replyIcon = 'reply-all'; } const reblogPrivate = status.getIn(['account', 'id']) === me && status.get('visibility') === 'private'; let reblogTitle = ''; if (status.get('reblogged')) { reblogTitle = intl.formatMessage(messages.cancel_reblog_private); } else if (publicStatus) { reblogTitle = intl.formatMessage(messages.reblog); } else if (reblogPrivate) { reblogTitle = intl.formatMessage(messages.reblog_private); } else { reblogTitle = intl.formatMessage(messages.cannot_reblog); } const shareButton = ('share' in navigator) && publicStatus && ( <IconButton className='status__action-bar-button' title={intl.formatMessage(messages.share)} icon='share-alt' onClick={this.handleShareClick} /> ); return ( <div className='status__action-bar'> <IconButton className='status__action-bar-button' title={replyTitle} icon={status.get('in_reply_to_account_id') === status.getIn(['account', 'id']) ? 'reply' : replyIcon} onClick={this.handleReplyClick} counter={status.get('replies_count')} obfuscateCount /> <IconButton className={classNames('status__action-bar-button', { reblogPrivate })} disabled={!publicStatus && !reblogPrivate} active={status.get('reblogged')} pressed={status.get('reblogged')} title={reblogTitle} icon='retweet' onClick={this.handleReblogClick} counter={withCounters ? status.get('reblogs_count') : undefined} /> <IconButton className='status__action-bar-button star-icon' animate active={status.get('favourited')} pressed={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} counter={withCounters ? status.get('favourites_count') : undefined} /> {shareButton} <div className='status__action-bar-dropdown'> <DropdownMenuContainer scrollKey={scrollKey} disabled={anonymousAccess} status={status} items={menu} icon='ellipsis-h' size={18} direction='right' title={intl.formatMessage(messages.more)} /> </div> </div> ); } }
src/sentry/static/sentry/app/icons/icon-user.js
gencer/sentry
import React from 'react'; import Icon from 'react-icon-base'; function IconUser(props) { return ( <Icon viewBox="0 0 24 24" {...props}> <g fill="currentColor"> <path d="M4.57694084,15.0573642 C3.09845147,15.2679649 2,16.5339712 2,18.0273845 L2,20.5 C2,21.3284271 2.67157288,22 3.5,22 L20.5,22 C21.3284271,22 22,21.3284271 22,20.5 L22,18.0273845 C22,16.5339712 20.9015485,15.2679649 19.4230592,15.0573642 L15.9042257,14.5561303 C14.8548438,15.4562022 13.4909273,16 12,16 C10.5090727,16 9.14515623,15.4562022 8.0957743,14.5561303 L4.57694084,15.0573642 Z M4.2949014,13.0773506 L8.7103901,12.4483943 L9.39785869,13.0380473 C10.1184044,13.656071 11.0299588,14 12,14 C12.9700412,14 13.8815956,13.656071 14.6021413,13.0380473 L15.2896099,12.4483943 L19.7050986,13.0773506 C22.1692475,13.4283518 24,15.5383623 24,18.0273845 L24,20.5 C24,22.4329966 22.4329966,24 20.5,24 L3.5,24 C1.56700338,24 0,22.4329966 0,20.5 L8.8817842e-16,18.0273845 C8.8817842e-16,15.5383623 1.83075245,13.4283518 4.2949014,13.0773506 Z M12,2 C9.790861,2 8,3.790861 8,6 L8,10 C8,12.209139 9.790861,14 12,14 C14.209139,14 16,12.209139 16,10 L16,6 C16,3.790861 14.209139,2 12,2 Z M12,8.8817842e-16 C15.3137085,-1.11022302e-15 18,2.6862915 18,6 L18,10 C18,13.3137085 15.3137085,16 12,16 C8.6862915,16 6,13.3137085 6,10 L6,6 C6,2.6862915 8.6862915,6.66133815e-16 12,8.8817842e-16 Z" /> </g> </Icon> ); } export default IconUser;
src/routes/error/index.js
muidea/magicSite
import React from 'react' import { Icon } from 'antd' import styles from './index.less' const Error = () => (<div className="content-inner"> <div className={styles.error}> <Icon type="frown-o" /> <h1>404 Not Found</h1> </div> </div>) export default Error
docs/src/app/components/pages/components/RefreshIndicator/Page.js
pomerantsev/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import refreshIndicatorReadmeText from './README'; import RefreshIndicatorExampleReady from './ExampleReady'; import refreshIndicatorExampleReadyCode from '!raw!./ExampleReady'; import RefreshIndicatorExampleLoading from './ExampleLoading'; import refreshIndicatorExampleLoadingCode from '!raw!./ExampleLoading'; import refreshIndicatorCode from '!raw!material-ui/RefreshIndicator/RefreshIndicator'; const descriptions = { ready: 'The `ready` status can be used in response to a pull-to-refresh action, with the `percentage` tracking ' + 'the depth of the "pull". The `size` property determines the icon size in pixels, and the `color` property its ' + 'color, except at `percentage` 100, when the colour switches to the secondary color.', loading: 'The `loading` status displays an indeterminate indicator, intended to to be used while content is ' + 'loading. The `loadingColor` prop can be used to set the indicator color, which defaults to the secondary color.', }; const RefreshIndicatorPage = () => ( <div> <Title render={(previousTitle) => `Refresh Indicator - ${previousTitle}`} /> <MarkdownElement text={refreshIndicatorReadmeText} /> <CodeExample title="Ready" description={descriptions.ready} code={refreshIndicatorExampleReadyCode} > <RefreshIndicatorExampleReady /> </CodeExample> <CodeExample title="Loading" description={descriptions.loading} code={refreshIndicatorExampleLoadingCode} > <RefreshIndicatorExampleLoading /> </CodeExample> <PropTypeDescription code={refreshIndicatorCode} /> </div> ); export default RefreshIndicatorPage;
app/App.js
calebgregory/react-app
'use strict'; import React from 'react'; import Router from 'react-router'; import ReactDOM from 'react-dom'; import routes from './config/routes'; ReactDOM.render(( <Router> {routes} </Router> ), document.getElementById('app'));
client-src/components/pager/PagerButtonLast.js
minimus/final-task
import React from 'react' import { NavLink } from 'react-router-dom' import propTypes from 'prop-types' export default function PagerButtonLast({ base, category, page }) { return ( <NavLink to={`/${base}/${category}/${page}`} activeClassName="active" activeStyle={{ color: '#be3131' }} > <i className="material-icons">last_page</i> </NavLink> ) } PagerButtonLast.propTypes = { base: propTypes.string.isRequired, category: propTypes.string.isRequired, page: propTypes.number.isRequired, }
node_modules/react-router/es/Router.js
nikhil-ahuja/Express-React
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import invariant from 'invariant'; import React from 'react'; import _createTransitionManager from './createTransitionManager'; import { routes } from './InternalPropTypes'; import RouterContext from './RouterContext'; import { createRoutes } from './RouteUtils'; import { createRouterObject as _createRouterObject, assignRouterState } from './RouterUtils'; import warning from './routerWarning'; var _React$PropTypes = React.PropTypes, func = _React$PropTypes.func, object = _React$PropTypes.object; /** * A <Router> is a high-level API for automatically setting up * a router that renders a <RouterContext> with all the props * it needs each time the URL changes. */ var Router = React.createClass({ displayName: 'Router', propTypes: { history: object, children: routes, routes: routes, // alias for children render: func, createElement: func, onError: func, onUpdate: func, // PRIVATE: For client-side rehydration of server match. matchContext: object }, getDefaultProps: function getDefaultProps() { return { render: function render(props) { return React.createElement(RouterContext, props); } }; }, getInitialState: function getInitialState() { return { location: null, routes: null, params: null, components: null }; }, handleError: function handleError(error) { if (this.props.onError) { this.props.onError.call(this, error); } else { // Throw errors by default so we don't silently swallow them! throw error; // This error probably occurred in getChildRoutes or getComponents. } }, createRouterObject: function createRouterObject(state) { var matchContext = this.props.matchContext; if (matchContext) { return matchContext.router; } var history = this.props.history; return _createRouterObject(history, this.transitionManager, state); }, createTransitionManager: function createTransitionManager() { var matchContext = this.props.matchContext; if (matchContext) { return matchContext.transitionManager; } var history = this.props.history; var _props = this.props, routes = _props.routes, children = _props.children; !history.getCurrentLocation ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You have provided a history object created with history v4.x or v2.x ' + 'and earlier. This version of React Router is only compatible with v3 ' + 'history objects. Please change to history v3.x.') : invariant(false) : void 0; return _createTransitionManager(history, createRoutes(routes || children)); }, componentWillMount: function componentWillMount() { var _this = this; this.transitionManager = this.createTransitionManager(); this.router = this.createRouterObject(this.state); this._unlisten = this.transitionManager.listen(function (error, state) { if (error) { _this.handleError(error); } else { // Keep the identity of this.router because of a caveat in ContextUtils: // they only work if the object identity is preserved. assignRouterState(_this.router, state); _this.setState(state, _this.props.onUpdate); } }); }, /* istanbul ignore next: sanity check */ componentWillReceiveProps: function componentWillReceiveProps(nextProps) { process.env.NODE_ENV !== 'production' ? warning(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : void 0; process.env.NODE_ENV !== 'production' ? warning((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : void 0; }, componentWillUnmount: function componentWillUnmount() { if (this._unlisten) this._unlisten(); }, render: function render() { var _state = this.state, location = _state.location, routes = _state.routes, params = _state.params, components = _state.components; var _props2 = this.props, createElement = _props2.createElement, render = _props2.render, props = _objectWithoutProperties(_props2, ['createElement', 'render']); if (location == null) return null; // Async match // Only forward non-Router-specific props to routing context, as those are // the only ones that might be custom routing context props. Object.keys(Router.propTypes).forEach(function (propType) { return delete props[propType]; }); return render(_extends({}, props, { router: this.router, location: location, routes: routes, params: params, components: components, createElement: createElement })); } }); export default Router;
jenkins-design-language/src/js/components/material-ui/svg-icons/content/reply-all.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ContentReplyAll = (props) => ( <SvgIcon {...props}> <path d="M7 8V5l-7 7 7 7v-3l-4-4 4-4zm6 1V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z"/> </SvgIcon> ); ContentReplyAll.displayName = 'ContentReplyAll'; ContentReplyAll.muiName = 'SvgIcon'; export default ContentReplyAll;
src/docs/components/animate/AnimateSlideExample.js
karatechops/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Animate from 'grommet/components/Animate'; import Box from 'grommet/components/Box'; import Button from 'grommet/components/Button'; import Paragraph from 'grommet/components/Paragraph'; import Example from '../../Example'; export default class AnimateSlideExample extends Component { constructor () { super(); this.state = { active: true }; } render () { const { active } = this.state; return ( <Example code={ <Box pad={{between: 'small'}}> <Button label="Slide" primary={true} onClick={() => this.setState({active: !active})} /> <Animate enter={{ animation: 'slide-up', duration: 1000 }} leave={{ animation: 'slide-down', duration: 1000 }} visible={active}> <Paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </Paragraph> </Animate> </Box> } /> ); } };
src/store/shared/app.js
cezerin/cezerin
import React from 'react'; import { Route } from 'react-router'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { animateScroll } from 'react-scroll'; import IndexContainer from './containers/index'; import SharedContainer from './containers/shared'; import CategoryContainer from './containers/category'; import ProductContainer from './containers/product'; import PageContainer from './containers/page'; import CheckoutContainer from './containers/checkout'; import CheckoutSuccessContainer from './containers/checkoutSuccess'; import NotFoundContainer from './containers/notfound'; import SearchContainer from './containers/search'; import { setCurrentPage } from './actions'; import { PAGE, PRODUCT_CATEGORY, PRODUCT, RESERVED, SEARCH } from './pageTypes'; class SwitchContainers extends React.Component { constructor(props) { super(props); } componentWillReceiveProps(nextProps) { this.props.setCurrentPage(nextProps.location); if (nextProps.location && this.props.location) { const pathnameChanged = nextProps.location.pathname !== this.props.location.pathname; const queryChanged = nextProps.location.search !== this.props.location.search; const isSearchPage = nextProps.location.pathname === '/search'; if (pathnameChanged || (queryChanged && isSearchPage)) { animateScroll.scrollToTop({ duration: 500, delay: 100, smooth: true }); } } } render() { const { history, location, currentPage } = this.props; const locationPathname = location && location.pathname ? location.pathname : '/'; switch (currentPage.type) { case PRODUCT: return <ProductContainer />; case PRODUCT_CATEGORY: return <CategoryContainer />; case SEARCH: return <SearchContainer />; case PAGE: if (locationPathname === '/') { return <IndexContainer />; } else if (locationPathname === '/checkout') { return <CheckoutContainer />; } if (locationPathname === '/checkout-success') { return <CheckoutSuccessContainer />; } else { return <PageContainer />; } default: return <NotFoundContainer />; } } } const mapStateToProps = (state, ownProps) => { return { currentPage: state.app.currentPage }; }; const mapDispatchToProps = (dispatch, ownProps) => { return { setCurrentPage: location => { dispatch(setCurrentPage(location)); } }; }; const SwitchContainersConnected = connect( mapStateToProps, mapDispatchToProps )(SwitchContainers); const App = () => ( <SharedContainer> <Route component={SwitchContainersConnected} /> </SharedContainer> ); export default App;
app/templates/src/app.js
jermspeaks/generator-react-vertical
import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import FastClick from 'fastclick'; import Dispatcher from './core/Dispatcher'; import getRoutes from './routes' import Location from './core/Location'; import ActionTypes from './common/constants/ActionTypes'; import { addEventListener, removeEventListener } from './common/utils/DOMUtils'; import App from './main/components/App' import ContactPage from './main/components/ContactPage'; import Router from 'react-router'; import createBrowserHistory from 'history/lib/createBrowserHistory' import LoginActions from './auth/actions/LoginActions'; // Create application containers for React app and CSS let appContainer = document.getElementById('app'); let cssContainer = document.getElementById('css'); // Set context of the DOM let context = { onSetTitle: value => document.title = value, onSetMeta: (name, content) => { // Remove and create a new <meta /> tag in order to make it work // with bookmarks in Safari let elements = document.getElementsByTagName('meta'); [].slice.call(elements).forEach((element) => { if (element.getAttribute('name') === name) { element.parentNode.removeChild(element); } }); let meta = document.createElement('meta'); meta.setAttribute('name', name); meta.setAttribute('content', content); document.getElementsByTagName('head')[0].appendChild(meta); } }; /** * Render React App on Client */ function render() { // set routes with history const history = createBrowserHistory(); let routes = getRoutes(history); // Render routes ReactDOM.render(routes, appContainer); } /** * Authenticate user with localStorage jwt (JSON Web Token) */ function authenticateUser() { let jwt = localStorage.getItem('jwt'); if (jwt) { LoginActions.loginUser(jwt); } } /** * Run React Application */ function run() { let currentLocation = null; let currentState = null; // Make taps on links and buttons work fast on mobiles FastClick.attach(document.body); // Re-render the app when window.location changes const unlisten = Location.listen( location => { currentLocation = location; currentState = Object.assign({}, location.state, { path: location.pathname, query: location.query, state: location.state, context }); render(); }); // Save the page scroll position into the current location's state var supportPageOffset = window.pageXOffset !== undefined; var isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat'); const setPageOffset = () => { currentLocation.state = currentLocation.state || Object.create(null); currentLocation.state.scrollX = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft; currentLocation.state.scrollY = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop; }; addEventListener(window, 'scroll', setPageOffset); addEventListener(window, 'pagehide', () => { removeEventListener(window, 'scroll', setPageOffset); unlisten(); }); } // Run the application when both DOM is ready // and page content is loaded if (window.addEventListener) { window.addEventListener('DOMContentLoaded', run); } else { window.attachEvent('onload', run); }
src/svg-icons/av/pause.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvPause = (props) => ( <SvgIcon {...props}> <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/> </SvgIcon> ); AvPause = pure(AvPause); AvPause.displayName = 'AvPause'; AvPause.muiName = 'SvgIcon'; export default AvPause;
src/svg-icons/communication/call-end.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationCallEnd = (props) => ( <SvgIcon {...props}> <path d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"/> </SvgIcon> ); CommunicationCallEnd = pure(CommunicationCallEnd); CommunicationCallEnd.displayName = 'CommunicationCallEnd'; CommunicationCallEnd.muiName = 'SvgIcon'; export default CommunicationCallEnd;
features/common/components/searchInput.js
zymokey/mission-park
import React from 'react'; import { connect } from 'react-redux'; import { searchInput } from '../actions'; class SearchInput extends React.Component { constructor(props){ super(props); this.state = { search: '' } } handleInputChange(event){ const { model, attr, parentId } = this.props; const target = event.target; const value = target.value; const name = target.name; this.setState({ [name]: value }); let searchObj = {}; searchObj[attr.keyName] = value; this.props.searchInput(model, searchObj, parentId); } render(){ return( <div className="toolbar-btn" role="group" aria-label="search"> <input className="form-control" name="search" placeholder={`按${this.props.attr.name}查找`} onChange={this.handleInputChange.bind(this)} value={this.state.search} /> </div> ); } } const mapDispatchToProps = dispatch => ({ searchInput: (value, model, keyName, parentId) => { dispatch(searchInput(value, model, keyName, parentId)); } }); export default connect(null, mapDispatchToProps)(SearchInput);
apps/wmb/priv/www/static/js/src/containers/filters/index.js
black13ua/wmb
import React from 'react'; import FiltersMenuView from '../../view/filters/main'; // import RandomButtonContainer from './random-button'; import FiltersContainer from './filters/main-filter'; const RightSidebarContainer = () => <FiltersMenuView> {/* <RandomButtonContainer />*/} <FiltersContainer /> </FiltersMenuView>; export default RightSidebarContainer;
definitions/npm/styled-components_v2.x.x/flow_v0.42.x-v0.52.x/test_styled-components_native_v2.x.x.js
orlandoc01/flow-typed
// @flow import nativeStyled, { ThemeProvider as NativeThemeProvider, withTheme as nativeWithTheme, keyframes as nativeKeyframes, } from 'styled-components/native' import React from 'react' import type { Theme as NativeTheme, Interpolation as NativeInterpolation, // Temporary ReactComponentFunctional as NativeReactComponentFunctional, ReactComponentClass as NativeReactComponentClass, ReactComponentStyled as NativeReactComponentStyled, ReactComponentStyledTaggedTemplateLiteral as NativeReactComponentStyledTaggedTemplateLiteral, ReactComponentUnion as NativeReactComponentUnion, ReactComponentIntersection as NativeReactComponentIntersection, } from 'styled-components' const NativeTitleTaggedTemplateLiteral: NativeReactComponentStyledTaggedTemplateLiteral<*> = nativeStyled.Text; const NativeTitleStyled: NativeReactComponentStyled<*> = nativeStyled.Text` font-size: 1.5em; `; const NativeTitleGeneric: NativeReactComponentIntersection<*> = nativeStyled.Text` font-size: 1.5em; `; const NativeTitleFunctional: NativeReactComponentFunctional<*> = nativeStyled.Text` font-size: 1.5em; `; const NativeTitleClass: NativeReactComponentClass<*> = nativeStyled.Text` font-size: 1.5em; `; declare var nativeNeedsReactComponentFunctional: NativeReactComponentFunctional<*> => void declare var nativeNeedsReactComponentClass: NativeReactComponentClass<*> => void nativeNeedsReactComponentFunctional(NativeTitleStyled) nativeNeedsReactComponentClass(NativeTitleStyled) const NativeExtendedTitle: NativeReactComponentIntersection<*> = nativeStyled(NativeTitleStyled)` font-size: 2em; `; const NativeWrapper: NativeReactComponentIntersection<*> = nativeStyled.View` padding: 4em; background: ${({theme}) => theme.background}; `; // ---- EXTEND ---- const NativeAttrs0ReactComponent: NativeReactComponentStyled<*> = nativeStyled.View.extend``; const NativeAttrs0ExtendReactComponent: NativeReactComponentIntersection<*> = NativeAttrs0ReactComponent.extend``; const NativeAttrs0SyledComponent: NativeReactComponentStyledTaggedTemplateLiteral<*> = nativeStyled.View; const NativeAttrs0ExtendStyledComponent: NativeReactComponentIntersection<*> = NativeAttrs0SyledComponent.extend``; // ---- ATTRIBUTES ---- const NativeAttrs1: NativeReactComponentStyledTaggedTemplateLiteral<*> = nativeStyled.View.attrs({ testProp: 'foo' }); // $ExpectError const NativeAttrs1Error: NativeReactComponentStyledTaggedTemplateLiteral<*> = nativeStyled.View.attrs({ testProp: 'foo' })``; declare var needsString: string => void nativeNeedsReactComponentFunctional(nativeStyled.View.attrs({})``) nativeNeedsReactComponentClass(nativeStyled.View.attrs({})``) // $ExpectError needsString(nativeStyled.View.attrs({})``) const NativeAttrs2: NativeReactComponentStyledTaggedTemplateLiteral<*> = nativeStyled.View .attrs({ testProp1: 'foo' }) .attrs({ testProp2: 'bar' }); const NativeAttrs3Styled: NativeReactComponentStyled<*> = nativeStyled.View.attrs({ testProp: 'foo' })` background-color: red; `; const NativeAttrs3Generic: NativeReactComponentIntersection<*> = nativeStyled.View.attrs({ testProp: 'foo' })` background-color: red; `; const NativeAttrs3Functional: NativeReactComponentFunctional<*> = nativeStyled.View.attrs({ testProp: 'foo' })` background-color: red; `; const NativeAttrs3Class: NativeReactComponentClass<*> = nativeStyled.View.attrs({ testProp: 'foo' })` background-color: red; `; const nativeTheme: NativeTheme = { background: "papayawhip" }; // ---- WithComponent ---- const NativeWithComponent1: NativeReactComponentStyled<*> = nativeStyled.View.withComponent('Text'); const NativeWithComponent2: NativeReactComponentStyled<*> = nativeStyled.View.withComponent(NativeWithComponent1); const NativeWithComponent3: NativeReactComponentStyled<*> = nativeStyled.View.withComponent(NativeAttrs3Class); // $ExpectError const NativeWithComponentError1: NativeReactComponentStyled<*> = nativeStyled.View.withComponent(0); // $ExpectError const NativeWithComponentError2: NativeReactComponentStyled<*> = nativeStyled.View.withComponent('NotHere'); // ---- WithTheme ---- const NativeComponent: NativeReactComponentFunctional<{ theme: NativeTheme }> = ({ theme }) => ( <NativeThemeProvider theme={theme}> <NativeWrapper> <NativeTitleStyled>Hello World, this is my first styled component!</NativeTitleStyled> </NativeWrapper> </NativeThemeProvider> ); const NativeComponentWithTheme: NativeReactComponentFunctional<{}> = nativeWithTheme(NativeComponent); const NativeComponent2: NativeReactComponentFunctional<{}> = () => ( <NativeThemeProvider theme={outerTheme => outerTheme}> <NativeWrapper> <NativeTitleStyled>Hello World, this is my first styled component!</NativeTitleStyled> </NativeWrapper> </NativeThemeProvider> ); const NativeOpacityKeyFrame: string = nativeKeyframes` 0% { opacity: 0; } 100% { opacity: 1; } `; // $ExpectError const NativeNoExistingElementWrapper = nativeStyled.nonexisting` padding: 4em; background: papayawhip; `; const nativeNum: 9 = 9 // $ExpectError const NativeNoExistingComponentWrapper = nativeStyled()` padding: 4em; background: papayawhip; `; // $ExpectError const NativeNumberWrapper = nativeStyled(nativeNum)` padding: 4em; background: papayawhip; `; // ---- COMPONENT CLASS TESTS ---- class NativeNeedsThemeReactClass extends React.Component { props: { foo: string, theme: NativeTheme } render() { return <div />; } } class NativeReactClass extends React.Component { props: { foo: string } render() { return <div />; } } const NativeStyledClass: NativeReactComponentClass<{ foo: string, theme: NativeTheme }> = nativeStyled(NativeNeedsThemeReactClass)` color: red; `; const NativeNeedsFoo1Class: NativeReactComponentClass<{ foo: string }, { theme: NativeTheme }> = nativeWithTheme(NativeNeedsThemeReactClass); // $ExpectError const NativeNeedsFoo0ClassError: NativeReactComponentClass<{ foo: string }> = nativeWithTheme(NativeReactClass); // $ExpectError const NativeNeedsFoo1ClassError: NativeReactComponentClass<{ foo: string }> = nativeWithTheme(NeedsFoo1Class); // $ExpectError const NativeNeedsFoo1ErrorClass: NativeReactComponentClass<{ foo: number }> = nativeWithTheme(NativeNeedsThemeReactClass); // $ExpectError const NativeNeedsFoo2ErrorClass: NativeReactComponentClass<{ foo: string }, { theme: string }> = nativeWithTheme(NativeNeedsThemeReactClass); // $ExpectError const NativeNeedsFoo3ErrorClass: NativeReactComponentClass<{ foo: string, theme: NativeTheme }> = nativeWithTheme(NativeNeedsFoo1Class); // $ExpectError const NativeNeedsFoo4ErrorClass: NativeReactComponentClass<{ foo: number }> = nativeWithTheme(NativeNeedsFoo1Class); // $ExpectError const NativeNeedsFoo5ErrorClass: NativeReactComponentClass<{ foo: string, theme: string }> = nativeWithTheme(NativeNeedsFoo1Class); // ---- INTERPOLATION TESTS ---- const nativeInterpolation: Array<NativeInterpolation> = nativeStyled.css` background-color: red; `; // $ExpectError const nativeInterpolationError: Array<NativeInterpolation | boolean> = nativeStyled.css` background-color: red; `; // ---- DEFAULT COMPONENT TESTS ---- const NativeDefaultComponent: NativeReactComponentIntersection<{}> = nativeStyled.View` background-color: red; `; // $ExpectError const NativeDefaultComponentError: {} => string = nativeStyled.View` background-color: red; `; // ---- FUNCTIONAL COMPONENT TESTS ---- declare var View: ({}) => React$Element<*> const NativeFunctionalComponent: NativeReactComponentFunctional<{ foo: string, theme: NativeTheme }> = props => <View />; const NativeNeedsFoo1: NativeReactComponentFunctional<{ foo: string, theme: NativeTheme }> = nativeStyled(NativeFunctionalComponent)` background-color: red; `; // $ExpectError const NativeNeedsFoo1Error: NativeReactComponentFunctional<{ foo: number }> = nativeStyled(NativeFunctionalComponent)` background-color: red; `; const NativeNeedsFoo2: NativeReactComponentFunctional<{ foo: string, theme: NativeTheme }> = nativeStyled(NativeNeedsFoo1)` background-color: red; `; // $ExpectError const NativeNeedsFoo2Error: NativeReactComponentFunctional<{ foo: number }> = nativeStyled(NativeNeedsFoo1)` background-color: red; `; // ---- FUNCTIONAL COMPONENT TESTS (nativeWithTheme)---- const NativeNeedsFoo1Functional: NativeReactComponentFunctional<{ foo: string }> = nativeWithTheme(NativeFunctionalComponent); const NativeNeedsFoo2Functional: NativeReactComponentFunctional<{ foo: string }> = nativeWithTheme(NativeNeedsFoo1Functional); // $ExpectError const NativeNeedsFoo1ErrorFunctional: NativeReactComponentFunctional<{ foo: number }> = nativeWithTheme(NativeFunctionalComponent); // $ExpectError const NativeNeedsFoo2ErrorFunctional: NativeReactComponentFunctional<{ foo: string }, { theme: string }> = nativeWithTheme(NativeFunctionalComponent); // $ExpectError const NativeNeedsFoo3ErrorFunctional: NativeReactComponentFunctional<{ foo: number, theme: NativeTheme }> = nativeWithTheme(NativeFunctionalComponent); // $ExpectError const NativeNeedsFoo4ErrorFunctional: NativeReactComponentFunctional<{ foo: number }> = nativeWithTheme(NativeNeedsFoo1Functional); // $ExpectError const NativeNeedsFoo5ErrorFunctional: NativeReactComponentFunctional<{ foo: string }, { theme: string }> = nativeWithTheme(NativeNeedsFoo1Functional); // $ExpectError const NativeNeedsFoo6ErrorFunctional: NativeReactComponentFunctional<{ foo: number }, { theme: NativeTheme }> = nativeWithTheme(NativeNeedsFoo1Functional);
src/interface/report/Results/Character/PlayerInfo/Gear.js
sMteX/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import Icon from 'common/Icon'; import ItemLink from 'common/ItemLink'; import ITEM_QUALITIES from 'game/ITEM_QUALITIES'; const EPIC_ITEMS_ILVL = 340; class Gear extends React.PureComponent { static propTypes = { gear: PropTypes.array.isRequired, }; render() { const { gear } = this.props; return ( <> { gear.filter(item => item.id !== 0) .map(item => { // Items seem to turn epic from 340 item level, but WCL doesn't show this properly let quality = item.itemLevel >= EPIC_ITEMS_ILVL ? ITEM_QUALITIES.EPIC : item.quality; if (!quality) { quality = ITEM_QUALITIES.EPIC; // relics don't have a quality, but they're always epic } const gearSlot = gear.indexOf(item); return ( <div key={`${gearSlot}_${item.id}`} style={{ display: 'inline-block', textAlign: 'center', gridArea: `item-slot-${gearSlot}` }} className={`item-slot-${gearSlot}`}> <ItemLink id={item.id} quality={quality} details={item} style={{ display: 'block', fontSize: '46px', lineHeight: 1 }} icon={false} > <Icon className="gear-icon icon" icon={item.icon} /> <div className="gear-ilvl">{item.itemLevel}</div> </ItemLink> </div> ); }) } </> ); } } export default Gear;
src/parser/druid/guardian/modules/features/FrenziedRegenGoEProcs.js
FaideWW/WoWAnalyzer
import React from 'react'; import { formatPercentage } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import SPELLS from 'common/SPELLS'; import Analyzer from 'parser/core/Analyzer'; import GuardianOfElune from './GuardianOfElune'; class FrenziedRegenGoEProcs extends Analyzer { static dependencies = { guardianOfElune: GuardianOfElune, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.GUARDIAN_OF_ELUNE_TALENT.id); } statistic() { const nonGoEFRegen = this.guardianOfElune.nonGoEFRegen; const GoEFRegen = this.guardianOfElune.GoEFRegen; if ((nonGoEFRegen + GoEFRegen) === 0) { return null; } return ( <StatisticBox icon={<SpellIcon id={SPELLS.FRENZIED_REGENERATION.id} />} value={`${formatPercentage(nonGoEFRegen / (nonGoEFRegen + GoEFRegen))}%`} label="Unbuffed Frenzied Regen" tooltip={`You cast <b>${nonGoEFRegen + GoEFRegen}</b> total ${SPELLS.FRENZIED_REGENERATION.name} and <b> ${GoEFRegen}</b> were buffed by 20%.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(8); } export default FrenziedRegenGoEProcs;
lib/Highlighter/stories/Highlighter.stories.js
folio-org/stripes-components
import React from 'react'; import { storiesOf } from '@storybook/react'; import withReadme from 'storybook-readme/with-readme'; import readme from '../readme.md'; import BasicUsage from './BasicUsage'; storiesOf('Highlighter', module) .addDecorator(withReadme(readme)) .add('Basic Usage', () => <BasicUsage />);
src/modules/keywords/routes/index.js
CtrHellenicStudies/Commentary
import React from 'react'; import { Route } from 'react-router'; import PrivateRoute from '../../../routes/PrivateRoute'; import EditKeywordLayout from '../layouts/EditKeywordLayout'; import KeywordPage from '../components/KeywordPage'; import KeywordDetailContainer from '../containers/KeywordDetailContainer'; const editKeywordRoute = ( <PrivateRoute exact path="/tags/:slug/edit" component={EditKeywordLayout} roles={['commenter', 'editor', 'admin']} /> ); const addKeywordRoute = ( <PrivateRoute exact path="/tags/create" component={EditKeywordLayout} roles={['commenter', 'editor', 'admin']} /> ); const keywordDetailRoute = ( <Route exact path="/tags/:slug" component={KeywordDetailContainer} /> ); const wordsListRoute = ( <Route path="/words" render={() => ( <KeywordPage type="word" title="Words" /> )} /> ); const ideasListRoute = ( <Route path="/ideas" render={() => ( <KeywordPage type="idea" title="Ideas" /> )} /> ); export { editKeywordRoute, addKeywordRoute, keywordDetailRoute, wordsListRoute, ideasListRoute, };
app/javascript/mastodon/components/relative_timestamp.js
primenumber/mastodon
import React from 'react'; import { injectIntl, defineMessages } from 'react-intl'; import PropTypes from 'prop-types'; const messages = defineMessages({ today: { id: 'relative_time.today', defaultMessage: 'today' }, just_now: { id: 'relative_time.just_now', defaultMessage: 'now' }, seconds: { id: 'relative_time.seconds', defaultMessage: '{number}s' }, minutes: { id: 'relative_time.minutes', defaultMessage: '{number}m' }, hours: { id: 'relative_time.hours', defaultMessage: '{number}h' }, days: { id: 'relative_time.days', defaultMessage: '{number}d' }, moments_remaining: { id: 'time_remaining.moments', defaultMessage: 'Moments remaining' }, seconds_remaining: { id: 'time_remaining.seconds', defaultMessage: '{number, plural, one {# second} other {# seconds}} left' }, minutes_remaining: { id: 'time_remaining.minutes', defaultMessage: '{number, plural, one {# minute} other {# minutes}} left' }, hours_remaining: { id: 'time_remaining.hours', defaultMessage: '{number, plural, one {# hour} other {# hours}} left' }, days_remaining: { id: 'time_remaining.days', defaultMessage: '{number, plural, one {# day} other {# days}} left' }, }); const dateFormatOptions = { hour12: false, year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', }; const shortDateFormatOptions = { month: 'short', day: 'numeric', }; const SECOND = 1000; const MINUTE = 1000 * 60; const HOUR = 1000 * 60 * 60; const DAY = 1000 * 60 * 60 * 24; const MAX_DELAY = 2147483647; const selectUnits = delta => { const absDelta = Math.abs(delta); if (absDelta < MINUTE) { return 'second'; } else if (absDelta < HOUR) { return 'minute'; } else if (absDelta < DAY) { return 'hour'; } return 'day'; }; const getUnitDelay = units => { switch (units) { case 'second': return SECOND; case 'minute': return MINUTE; case 'hour': return HOUR; case 'day': return DAY; default: return MAX_DELAY; } }; export const timeAgoString = (intl, date, now, year, timeGiven = true) => { const delta = now - date.getTime(); let relativeTime; if (delta < DAY && !timeGiven) { relativeTime = intl.formatMessage(messages.today); } else if (delta < 10 * SECOND) { relativeTime = intl.formatMessage(messages.just_now); } else if (delta < 7 * DAY) { if (delta < MINUTE) { relativeTime = intl.formatMessage(messages.seconds, { number: Math.floor(delta / SECOND) }); } else if (delta < HOUR) { relativeTime = intl.formatMessage(messages.minutes, { number: Math.floor(delta / MINUTE) }); } else if (delta < DAY) { relativeTime = intl.formatMessage(messages.hours, { number: Math.floor(delta / HOUR) }); } else { relativeTime = intl.formatMessage(messages.days, { number: Math.floor(delta / DAY) }); } } else if (date.getFullYear() === year) { relativeTime = intl.formatDate(date, shortDateFormatOptions); } else { relativeTime = intl.formatDate(date, { ...shortDateFormatOptions, year: 'numeric' }); } return relativeTime; }; const timeRemainingString = (intl, date, now, timeGiven = true) => { const delta = date.getTime() - now; let relativeTime; if (delta < DAY && !timeGiven) { relativeTime = intl.formatMessage(messages.today); } else if (delta < 10 * SECOND) { relativeTime = intl.formatMessage(messages.moments_remaining); } else if (delta < MINUTE) { relativeTime = intl.formatMessage(messages.seconds_remaining, { number: Math.floor(delta / SECOND) }); } else if (delta < HOUR) { relativeTime = intl.formatMessage(messages.minutes_remaining, { number: Math.floor(delta / MINUTE) }); } else if (delta < DAY) { relativeTime = intl.formatMessage(messages.hours_remaining, { number: Math.floor(delta / HOUR) }); } else { relativeTime = intl.formatMessage(messages.days_remaining, { number: Math.floor(delta / DAY) }); } return relativeTime; }; export default @injectIntl class RelativeTimestamp extends React.Component { static propTypes = { intl: PropTypes.object.isRequired, timestamp: PropTypes.string.isRequired, year: PropTypes.number.isRequired, futureDate: PropTypes.bool, }; state = { now: this.props.intl.now(), }; static defaultProps = { year: (new Date()).getFullYear(), }; shouldComponentUpdate (nextProps, nextState) { // As of right now the locale doesn't change without a new page load, // but we might as well check in case that ever changes. return this.props.timestamp !== nextProps.timestamp || this.props.intl.locale !== nextProps.intl.locale || this.state.now !== nextState.now; } componentWillReceiveProps (nextProps) { if (this.props.timestamp !== nextProps.timestamp) { this.setState({ now: this.props.intl.now() }); } } componentDidMount () { this._scheduleNextUpdate(this.props, this.state); } componentWillUpdate (nextProps, nextState) { this._scheduleNextUpdate(nextProps, nextState); } componentWillUnmount () { clearTimeout(this._timer); } _scheduleNextUpdate (props, state) { clearTimeout(this._timer); const { timestamp } = props; const delta = (new Date(timestamp)).getTime() - state.now; const unitDelay = getUnitDelay(selectUnits(delta)); const unitRemainder = Math.abs(delta % unitDelay); const updateInterval = 1000 * 10; const delay = delta < 0 ? Math.max(updateInterval, unitDelay - unitRemainder) : Math.max(updateInterval, unitRemainder); this._timer = setTimeout(() => { this.setState({ now: this.props.intl.now() }); }, delay); } render () { const { timestamp, intl, year, futureDate } = this.props; const timeGiven = timestamp.includes('T'); const date = new Date(timestamp); const relativeTime = futureDate ? timeRemainingString(intl, date, this.state.now, timeGiven) : timeAgoString(intl, date, this.state.now, year, timeGiven); return ( <time dateTime={timestamp} title={intl.formatDate(date, dateFormatOptions)}> {relativeTime} </time> ); } }
src/svg-icons/action/event.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionEvent = (props) => ( <SvgIcon {...props}> <path d="M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z"/> </SvgIcon> ); ActionEvent = pure(ActionEvent); ActionEvent.displayName = 'ActionEvent'; ActionEvent.muiName = 'SvgIcon'; export default ActionEvent;
fields/types/relationship/RelationshipField.js
helloworld3q3q/keystone
import async from 'async'; import Field from '../Field'; import { listsByKey } from '../../../admin/client/utils/lists'; import React from 'react'; import Select from 'react-select'; import xhr from 'xhr'; import { Button, InputGroup } from 'elemental'; import _ from 'lodash'; function compareValues (current, next) { const currentLength = current ? current.length : 0; const nextLength = next ? next.length : 0; if (currentLength !== nextLength) return false; for (let i = 0; i < currentLength; i++) { if (current[i] !== next[i]) return false; } return true; } module.exports = Field.create({ displayName: 'RelationshipField', statics: { type: 'Relationship', }, getInitialState () { return { value: null, createIsOpen: false, }; }, componentDidMount () { this._itemsCache = {}; this.loadValue(this.props.value); }, componentWillReceiveProps (nextProps) { if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return; this.loadValue(nextProps.value); }, shouldCollapse () { if (this.props.many) { // many:true relationships have an Array for a value return this.props.collapse && !this.props.value.length; } return this.props.collapse && !this.props.value; }, buildFilters () { var filters = {}; _.forEach(this.props.filters, (value, key) => { if (typeof value === 'string' && value[0] === ':') { var fieldName = value.slice(1); var val = this.props.values[fieldName]; if (val) { filters[key] = val; return; } // check if filtering by id and item was already saved if (fieldName === ':_id' && Keystone.item) { filters[key] = Keystone.item.id; return; } } else { filters[key] = value; } }, this); var parts = []; _.forEach(filters, function (val, key) { parts.push('filters[' + key + '][value]=' + encodeURIComponent(val)); }); return parts.join('&'); }, cacheItem (item) { item.href = Keystone.adminPath + '/' + this.props.refList.path + '/' + item.id; this._itemsCache[item.id] = item; }, loadValue (values) { if (!values) { return this.setState({ loading: false, value: null, }); }; values = Array.isArray(values) ? values : values.split(','); const cachedValues = values.map(i => this._itemsCache[i]).filter(i => i); if (cachedValues.length === values.length) { this.setState({ loading: false, value: this.props.many ? cachedValues : cachedValues[0], }); return; } this.setState({ loading: true, value: null, }); async.map(values, (value, done) => { xhr({ url: Keystone.adminPath + '/api/' + this.props.refList.path + '/' + value + '?basic', responseType: 'json', }, (err, resp, data) => { if (err || !data) return done(err); this.cacheItem(data); done(err, data); }); }, (err, expanded) => { if (!this.isMounted()) return; this.setState({ loading: false, value: this.props.many ? expanded : expanded[0], }); }); }, // NOTE: this seems like the wrong way to add options to the Select loadOptionsCallback: {}, loadOptions (input, callback) { // NOTE: this seems like the wrong way to add options to the Select this.loadOptionsCallback = callback; const filters = this.buildFilters(); xhr({ url: Keystone.adminPath + '/api/' + this.props.refList.path + '?basic&search=' + input + '&' + filters, responseType: 'json', }, (err, resp, data) => { if (err) { console.error('Error loading items:', err); return callback(null, []); } data.results.forEach(this.cacheItem); callback(null, { options: data.results, complete: data.results.length === data.count, }); }); }, valueChanged (value) { this.props.onChange({ path: this.props.path, value: value, }); }, openCreate () { this.setState({ createIsOpen: true, }); }, closeCreate () { this.setState({ createIsOpen: false, }); }, onCreate (item) { this.cacheItem(item); if (Array.isArray(this.state.value)) { // For many relationships, append the new item to the end const values = this.state.value.map((item) => item.id); values.push(item.id); this.valueChanged(values.join(',')); } else { this.valueChanged(item.id); } // NOTE: this seems like the wrong way to add options to the Select this.loadOptionsCallback(null, { complete: true, options: Object.keys(this._itemsCache).map((k) => this._itemsCache[k]), }); this.closeCreate(); }, renderSelect (noedit) { return ( <Select.Async multi={this.props.many} disabled={noedit} loadOptions={this.loadOptions} labelKey="name" name={this.getInputName(this.props.path)} onChange={this.valueChanged} simpleValue value={this.state.value} valueKey="id" /> ); }, renderInputGroup () { // TODO: find better solution // when importing the CreateForm using: import CreateForm from '../../../admin/client/App/shared/CreateForm'; // CreateForm was imported as a blank object. This stack overflow post suggested lazilly requiring it: // http://stackoverflow.com/questions/29807664/cyclic-dependency-returns-empty-object-in-react-native // TODO: Implement this somewhere higher in the app, it breaks the encapsulation of the RelationshipField component const CreateForm = require('../../../admin/client/App/shared/CreateForm'); return ( <InputGroup> <InputGroup.Section grow> {this.renderSelect()} </InputGroup.Section> <InputGroup.Section> <Button onClick={this.openCreate} type="success">+</Button> </InputGroup.Section> <CreateForm list={listsByKey[this.props.refList.key]} isOpen={this.state.createIsOpen} onCreate={this.onCreate} onCancel={this.closeCreate} /> </InputGroup> ); }, renderValue () { return this.renderSelect(true); }, renderField () { if (this.props.createInline) { return this.renderInputGroup(); } else { return this.renderSelect(); } }, });
css-modules-demo/demo01/index.js
zhangjunhd/react-examples
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; ReactDOM.render( <App/>, document.body.appendChild(document.createElement('div')) );
packages/react/components/block.js
AdrianV/Framework7
import React from 'react'; import Utils from '../utils/utils'; import Mixins from '../utils/mixins'; import __reactComponentEl from '../runtime-helpers/react-component-el.js'; import __reactComponentDispatchEvent from '../runtime-helpers/react-component-dispatch-event.js'; import __reactComponentSlots from '../runtime-helpers/react-component-slots.js'; import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js'; class F7Block extends React.Component { constructor(props, context) { super(props, context); } onTabShow(e) { this.dispatchEvent('tabShow tab:show', e); } onTabHide(e) { this.dispatchEvent('tabHide tab:hide', e); } render() { const self = this; const props = self.props; const { className, inset, strong, accordionList, tabletInset, tabs, tab, tabActive, noHairlines, noHairlinesIos, noHairlinesMd, id, style } = props; const classes = Utils.classNames(className, 'block', { inset, 'block-strong': strong, 'accordion-list': accordionList, 'tablet-inset': tabletInset, tabs, tab, 'tab-active': tabActive, 'no-hairlines': noHairlines, 'no-hairlines-md': noHairlinesMd, 'no-hairlines-ios': noHairlinesIos }, Mixins.colorClasses(props)); return React.createElement('div', { id: id, style: style, className: classes }, this.slots['default']); } componentWillUnmount() { const el = this.el; if (!el) return; el.removeEventListener('tab:show', this.onTabShowBound); el.removeEventListener('tab:hide', this.onTabHideBound); } componentDidMount() { const el = this.el; if (!el) return; this.onTabShowBound = this.onTabShow.bind(this); this.onTabHideBound = this.onTabHide.bind(this); el.addEventListener('tab:show', this.onTabShowBound); el.addEventListener('tab:hide', this.onTabHideBound); } get slots() { return __reactComponentSlots(this.props); } get el() { return __reactComponentEl(this); } dispatchEvent(events, ...args) { return __reactComponentDispatchEvent(this, events, ...args); } } __reactComponentSetProps(F7Block, Object.assign({ id: [String, Number], inset: Boolean, tabletInset: Boolean, strong: Boolean, tabs: Boolean, tab: Boolean, tabActive: Boolean, accordionList: Boolean, noHairlines: Boolean, noHairlinesMd: Boolean, noHairlinesIos: Boolean }, Mixins.colorProps)); F7Block.displayName = 'f7-block'; export default F7Block;
src/native/todos/Todos.js
skallet/este
// @flow import type { State, Todo } from '../../common/types'; import Checkbox from './Checkbox'; import Footer from './Footer'; import React from 'react'; import todosMessages from '../../common/todos/todosMessages'; import { Box, Text, TextInput } from '../../common/components'; import { FormattedMessage } from 'react-intl'; import { Image, ScrollView, StyleSheet } from 'react-native'; import { compose, isEmpty, prop, reverse, sortBy, values } from 'ramda'; import { connect } from 'react-redux'; import { toggleTodoCompleted } from '../../common/todos/actions'; type TodoItemProps = { todo: Todo, toggleTodoCompleted: typeof toggleTodoCompleted, }; const TodoItem = ({ todo, toggleTodoCompleted, }: TodoItemProps) => ( <Box borderBottomWidth={1} flexDirection="row" flexWrap="nowrap" height={2} style={theme => ({ borderBottomColor: theme.colors.open.gray3, borderBottomWidth: StyleSheet.hairlineWidth, })} > <Checkbox alignItems="center" checked={todo.completed} height={2} marginVertical={0} onPress={() => toggleTodoCompleted(todo)} width={2} /> <TextInput editable={false} flex={1} height={2} marginHorizontal={0.5} value={todo.title} /> </Box> ); const IsEmpty = () => ( <Box alignItems="center" justifyContent="center" flex={1}> <Image source={require('./img/EmptyState.png')} /> <FormattedMessage {...todosMessages.empty}> {message => <Text bold color="gray" marginTop={1} size={1} >{message}</Text> } </FormattedMessage> </Box> ); type TodosProps = { todos: Array<Todo>, toggleTodoCompleted: typeof toggleTodoCompleted, }; const Todos = ({ todos, toggleTodoCompleted, }: TodosProps) => { if (isEmpty(todos)) { return <IsEmpty />; } const sortedTodos = compose( reverse, sortBy(prop('createdAt')), values, // object values to array )(todos); return ( <ScrollView> {sortedTodos.map(todo => <TodoItem todo={todo} toggleTodoCompleted={toggleTodoCompleted} key={todo.id} />, )} <Footer /> </ScrollView> ); }; export default connect( (state: State) => ({ todos: state.todos.all, }), { toggleTodoCompleted }, )(Todos);
src/components/Start/Start.js
foglerek/yn-mafia
import React from 'react' import { IndexLink, Link } from 'react-router' // import classes from './Start.scss' import { FormGroup, FormControl, ControlLabel, ButtonToolbar, Button } from 'react-bootstrap'; import { connect } from 'react-redux'; import { addUser } from '../../redux/modules/UserActions'; import { bindActionCreators } from 'redux'; import io from 'socket.io-client'; const Start = React.createClass({ getInitialState() { return { name: '' }; }, addUser() { console.log(this.state.name); this.socket.emit('JOIN_GAME', { name: this.state.name }); }, handleNameChange(e) { this.setState({name: e.target.value}); }, componentWillMount() { this.socket = io('http://localhost:3000'); this.socket.on('state', (state) => { console.log('state', state); }); }, render() { return (<div> <FormGroup> <FormControl type="text" placeholder="Pick a name" onChange={this.handleNameChange} /> </FormGroup> <Button onClick={this.addUser} bsStyle="primary">Join Game</Button> </div>); } }); function mapDispatchToProps(dispatch) { return { ...bindActionCreators({ addUser }), dispatch }; } export default connect(null, mapDispatchToProps)(Start);
app/components/Header/index.js
gihrig/react-boilerplate
import React from 'react'; import { FormattedMessage } from 'react-intl'; import A from './A'; import Img from './Img'; import NavBar from './NavBar'; import HeaderLink from './HeaderLink'; import Banner from './banner.jpg'; import messages from './messages'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <A href="https://twitter.com/mxstbr"> <Img src={Banner} alt="react-boilerplate - Logo" /> </A> <NavBar> <HeaderLink to="/"> <FormattedMessage {...messages.home} /> </HeaderLink> <HeaderLink to="/features"> <FormattedMessage {...messages.features} /> </HeaderLink> </NavBar> </div> ); } } export default Header;
src/svg-icons/communication/stay-current-landscape.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationStayCurrentLandscape = (props) => ( <SvgIcon {...props}> <path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/> </SvgIcon> ); CommunicationStayCurrentLandscape = pure(CommunicationStayCurrentLandscape); CommunicationStayCurrentLandscape.displayName = 'CommunicationStayCurrentLandscape'; CommunicationStayCurrentLandscape.muiName = 'SvgIcon'; export default CommunicationStayCurrentLandscape;
src/svg-icons/image/filter-tilt-shift.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterTiltShift = (props) => ( <SvgIcon {...props}> <path d="M11 4.07V2.05c-2.01.2-3.84 1-5.32 2.21L7.1 5.69c1.11-.86 2.44-1.44 3.9-1.62zm7.32.19C16.84 3.05 15.01 2.25 13 2.05v2.02c1.46.18 2.79.76 3.9 1.62l1.42-1.43zM19.93 11h2.02c-.2-2.01-1-3.84-2.21-5.32L18.31 7.1c.86 1.11 1.44 2.44 1.62 3.9zM5.69 7.1L4.26 5.68C3.05 7.16 2.25 8.99 2.05 11h2.02c.18-1.46.76-2.79 1.62-3.9zM4.07 13H2.05c.2 2.01 1 3.84 2.21 5.32l1.43-1.43c-.86-1.1-1.44-2.43-1.62-3.89zM15 12c0-1.66-1.34-3-3-3s-3 1.34-3 3 1.34 3 3 3 3-1.34 3-3zm3.31 4.9l1.43 1.43c1.21-1.48 2.01-3.32 2.21-5.32h-2.02c-.18 1.45-.76 2.78-1.62 3.89zM13 19.93v2.02c2.01-.2 3.84-1 5.32-2.21l-1.43-1.43c-1.1.86-2.43 1.44-3.89 1.62zm-7.32-.19C7.16 20.95 9 21.75 11 21.95v-2.02c-1.46-.18-2.79-.76-3.9-1.62l-1.42 1.43z"/> </SvgIcon> ); ImageFilterTiltShift = pure(ImageFilterTiltShift); ImageFilterTiltShift.displayName = 'ImageFilterTiltShift'; ImageFilterTiltShift.muiName = 'SvgIcon'; export default ImageFilterTiltShift;
web/src/viewer/DateLabel.js
bolddp/pixerva
import React, { Component } from 'react'; export default class DateLabel extends Component { toDate(timestamp) { return new Date(timestamp * 1000).toISOString().substring(0,10); } render() { return ( this.props.dateTaken ? ( <label id="imageDate" style={{ fontSize: '20px', float: 'right' }}> {this.toDate(this.props.dateTaken)} </label> ) : null ); } }
packages/showcase/axes/custom-axes-orientation.js
uber/react-vis
// Copyright (c) 2016 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import { XYPlot, XAxis, YAxis, HorizontalGridLines, VerticalGridLines, LineSeries } from 'react-vis'; export default function Example() { return ( <XYPlot margin={{top: 40, right: 40, left: 10, bottom: 10}} width={300} height={300} > <HorizontalGridLines /> <VerticalGridLines /> <XAxis orientation="top" title="X Axis" /> <YAxis orientation="right" title="Y Axis" /> <LineSeries data={[ {x: 1, y: 3, z: 10}, {x: 2, y: 4, z: 10}, {x: 3, y: 8, z: 10}, {x: 4, y: 11, z: 10} ]} /> <LineSeries data={null} /> <LineSeries data={[ {x: 1, y: 3, z: 10}, {x: 2, y: 9, z: 10}, {x: 3, y: 2, z: 10}, {x: 4, y: 11, z: 10} ]} /> </XYPlot> ); }
app/src/index.js
grantrules/bikeindustryjobs
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/common/components/Routes.js
suttonj/topshelf
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import LoginPage from '../../pages/login/page'; import HomePage from '../../pages/home/page'; import TopicPage from '../../pages/topic/page'; import BookListPage from '../../pages/booklist/page'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage} /> <Route path="/topic/:id" component={TopicPage} /> <Route path="/booklist/:id" component={BookListPage} /> </Route> ); // <Route path="/" component={App}> // <IndexRoute component={LoginPage} /> // <Route path="home" component={HomePage} /> // </Route>
node_modules/semantic-ui-react/src/views/Item/ItemImage.js
mowbell/clickdelivery-fed-test
import React from 'react' import { createShorthandFactory, getUnhandledProps, META, } from '../../lib' import Image from '../../elements/Image' /** * An item can contain an image. */ function ItemImage(props) { const { size } = props const rest = getUnhandledProps(ItemImage, props) return <Image {...rest} size={size} ui={!!size} wrapped /> } ItemImage._meta = { name: 'ItemImage', parent: 'Item', type: META.TYPES.VIEW, } ItemImage.propTypes = { /** An image may appear at different sizes. */ size: Image.propTypes.size, } ItemImage.create = createShorthandFactory(ItemImage, src => ({ src })) export default ItemImage
analysis/warriorarms/src/modules/core/Execute/EarlyDotRefresh.js
anom0ly/WoWAnalyzer
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import React from 'react'; import EarlyDotRefreshesCore from './EarlyDotRefreshes'; const MINOR_THRESHOLD = 0.9; const AVERAGE_THRESHOLD = 0.8; const MAJOR_THRESHOLD = 0.6; class EarlyDotRefresh extends EarlyDotRefreshesCore { get suggestionThresholdsDeepwoundsEfficiency() { return this.makeSuggestionThresholds( SPELLS.MORTAL_STRIKE, MINOR_THRESHOLD, AVERAGE_THRESHOLD, MAJOR_THRESHOLD, ); } static dots = [ { name: 'Deepwounds', debuffId: SPELLS.MASTERY_DEEP_WOUNDS_DEBUFF.id, castId: SPELLS.MORTAL_STRIKE.id, duration: 12000, }, ]; // Checks the status of the last cast and marks it accordingly. getLastBadCastText(event, dot) { return super.getLastBadCastText(event, dot); } suggestions(when) { when(this.suggestionThresholdsDeepwoundsEfficiency).addSuggestion( (suggest, actual, recommended) => suggest( <> You refreshed <SpellLink id={SPELLS.MASTERY_DEEP_WOUNDS_DEBUFF.id} icon /> early{' '} {this.suggestionThresholdsDeepwoundsEfficiency.count} times on a target in{' '} <SpellLink id={SPELLS.EXECUTE.id} icon /> range. Try to prioritize{' '} <SpellLink id={SPELLS.EXECUTE.id} icon /> as it deals more damage than{' '} <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon />. </>, ) .icon(SPELLS.MASTERY_DEEP_WOUNDS_DEBUFF.icon) .actual( t({ id: 'shared.suggestions.dots.badRefreshes', message: `${formatPercentage(actual)}% bad dot refreshes.`, }), ) .recommended(`<${formatPercentage(recommended)}% is recommended`), ); } } export default EarlyDotRefresh;
src/pages/organize/list.js
yiweimatou/admin-antd
import React, { Component } from 'react'; import { Table, message, Button } from 'antd' import { Link } from 'react-router' import { info, list } from 'services/organize' import SearchInput from '../../components/SearchInput' class OrganizeList extends Component { constructor(props) { super(props) this.state = { title: '', total: 0, current: 1, dataSource: [], loading: false } } componentWillMount() { this.getInfo() } getInfo = () => { info({ title: this.state.title }).then((data) => { if (data.count === 0) { this.setState({ total: data.count, dataSource: [] }) } else { this.setState({ total: data.count, current: 1 }) this.getList(1) } }).catch(error => message.error(error)) } getList = (offset) => { this.setState({ loading: true, current: offset }) list({ title: this.state.title, offset, limit: 6 }).then((data) => { this.setState({ loading: false, dataSource: data.list }) }).catch((error) => { this.setState({ loading: false }) message.error(error) }) } render() { const { loading, dataSource, total, current } = this.state const pagination = { total, current, showTotal: num => `共${num}条`, pageSize: 6, onChange: this.getList } const columns = [{ title: '机构名称', dataIndex: 'title', key: 'title' }, { title: '创建时间', dataIndex: 'add_ms', key: 'add_ms', render: text => (new Date(text * 1000)).toLocaleString() }, { title: '操作', key: 'operate', render: (text, record) => <Button><Link to={`/organize/edit/${record.id}`}>编辑</Link></Button> }] return ( <div> <SearchInput placeholder="机构名称" onSearch={(value) => { Promise.resolve(this.setState({ title: value })) .then(this.getInfo) }} style={{ width: 200, marginBottom: 20 }} /> <Button style={{ float: 'right' }} type="primary"><Link to="/organize/add">添加机构</Link></Button> <Table columns={columns} loading={loading} pagination={pagination} dataSource={dataSource} /> </div> ); } } export default OrganizeList;
src/client/js/components/App.js
dstaver/greedy-alligator
import React, { Component } from 'react'; import Header from '../containers/Header'; export default class App extends Component { render() { return ( <div> <Header /> {this.props.children} </div> ); } }
lib/codemod/src/transforms/__testfixtures__/storiesof-to-csf/story-parameters.input.js
storybooks/react-storybook
/* eslint-disable */ import React from 'react'; import Button from './Button'; import { storiesOf } from '@storybook/react'; storiesOf('Button', module) .add('with story parameters', () => <Button label="The Button" />, { header: false, inline: true, }) .add('foo', () => <Button label="Foo" />, { bar: 1, });
app/src/chart/chart.js
tmlewallen/PongPing
import React from 'react'; import 'whatwg-fetch'; import d3 from './d3'; import moment from 'moment'; import * as _ from 'lodash'; export default class Chart extends React.Component { constructor() { super(); this.state = { data: [], maxPoints : 1000, pollPeriod : 5, timeWindow : 10 }; this.getPongStats(moment().subtract(this.state.timeWindow,'minutes')); this.pollPongStats(this.state.pollPeriod * 1000); } componentDidMount() { this.svg = d3.select('.chart'); d3.select(window).on('resize', this.rebuildChart.bind(this)); this.svg.append('g') .attr('class', 'path-container') .append('path'); this.svg.append('g') .attr('class', 'x-axis'); this.svg.append('g') .attr('class', 'y-axis'); this.rebuildChart(); } rebuildChart() { console.info(`Num of Points : ${this.state.data.length}`) let width = Number.parseFloat(_.trim(this.svg.style('width'), 'px')); let height = Number.parseFloat(_.trim(this.svg.style('height'), 'px')); let paddingRight = Number.parseFloat(_.trim(this.svg.style('padding-right'), 'px')); let paddingLeft = Number.parseFloat(_.trim(this.svg.style('padding-left'), 'px')); let paddingTop = Number.parseFloat(_.trim(this.svg.style('padding-top'), 'px')); let paddingBottom = Number.parseFloat(_.trim(this.svg.style('padding-bottom'), 'px')); width = width - paddingRight - paddingLeft; height = height - paddingTop - paddingBottom; let timeFormat = d3.timeFormat('%b %d %I:%M:%S %p') let x = d3.scaleLinear() .domain([d3.min(this.state.data, (d) => d.timestamp * 1000), d3.max(this.state.data, (d) => d.timestamp * 1000)]) .range([0, width]); let y = d3.scaleLinear() .domain([d3.min(this.state.data, (d) => d.delta), d3.max(this.state.data, (d) => d.delta)]) .range([height - 20, 0]); let graph = d3.line() .x((d) => x(new Date(d.timestamp * 1000))) .y((d) => y(d.delta)); let xAxis = d3.axisBottom(x) .ticks(this.state.timeWindow * 5) .tickSizeInner(-height) .tickFormat(timeFormat); // .tickPadding(5); let yAxis = d3.axisLeft(y) .tickSizeInner(-width) .tickPadding(5); let p = this.svg.select('path') .datum(this.state.data) .attr('stroke', '#F96302') .attr('stroke-width', 1) .attr('fill', 'none'); // .transition() if (this.state.data.length < this.state.maxPoints){ p = p.transition(); } p.attr('d', graph); this.svg.select('.x-axis') .attr('transform', 'translate(0,' + (height - 20) + ')') .call(xAxis) .selectAll('text') .attr("transform", "rotate(-45)") .style("text-anchor", "end"); this.svg.select('.y-axis') .call(yAxis); } getPongStats(d) { let dt = d ? d : moment().subtract(this.state.timeWindow, 'minutes'); console.log(dt.format()); fetch(`./data/list/${dt.format()}`).then((response) => { response.json().then((d) => { this.state.data = d; // let newSize = this.state.data.length + d.length; // if (this.state.data.length === 0 && d.length > this.state.maxPoints){ // d = d.splice(d.length - this.state.maxPoints); // } // else if (newSize > this.state.maxPoints){ // this.state.data = this.state.data.splice(newSize - this.state.maxPoints); // } // d.forEach( (el) => { // this.state.data.push(el); // }); this.rebuildChart(); }); }).catch((err) => { console.error(err); }); } pollPongStats(period) { setTimeout(() => { this.getPongStats(); this.pollPongStats(period); }, period); } render() { return ( <div id="chart-container" className="col-md-12"> <svg className="chart"/> </div> ); } }
src/js/components/icons/base/Multiple.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-multiple`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'multiple'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M19,15 L23,15 L23,1 L9,1 L9,5 M15,19 L19,19 L19,5 L5,5 L5,9 M1,23 L15,23 L15,9 L1,9 L1,23 L1,23 L1,23 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Multiple'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/Components/Header/index.js
gabriel-lopez-lopez/gll-billin-code-challenge
/** * Componente cabecera principal de navegación de la aplicación * */ import React, { Component } from 'react'; import { Link, withRouter } from 'react-router-dom'; import { connect } from 'react-redux'; // Logo import image from '../../assets/images/logo-billin.png'; // Estilos personalizados import './navbar.less'; // Exportar y utilizar el nombre de la clase no conectada para los tests export class Header extends Component { constructor(props) { super(props); this.handleHome = this.handleHome.bind(this); this.handleActive = this.handleActive.bind(this); this.clearActiveMenu = this.clearActiveMenu.bind(this); } /** * Limpia los estilos de las opciones del menú de la aplicación */ clearActiveMenu () { document.getElementById('header-navbar-collapse').childNodes[0].childNodes.forEach(li => { li.classList.remove('active'); }); } /** * Va a la página principal de la aplicación previa limpieza de estilos del menú */ handleHome () { this.clearActiveMenu(); this.props.history.push('/'); } /** * Marca la opción de menú seleccionada * @param {Event} e Evento */ handleActive (e) { // Si no se recibe el evento if (e === undefined) { // Ruta actual let pathname = this.props.history.location.pathname; if (document.getElementById('header-navbar-collapse')) { // Elementos LI del menú principal de la aplicación document.getElementById('header-navbar-collapse').childNodes[0].childNodes.forEach(function (elem) { // Se restablecen las clases del elemento LI elem.classList.remove('active'); // Se itera por los nodos que puede tener el elemento elem.childNodes.forEach(function (node) { // Si el nodo es un enlace y su valor de enlace es igual que la ruta actual // se le agrega la clase "active" al elemento LI if (node.tagName === 'A' && pathname.indexOf(node.attributes.href.value) !== -1) { node.parentNode.className = 'active'; } }); }); } return; } // Antes se eliminan estilos previos this.clearActiveMenu(); // Se marca la opción con el estilo e.currentTarget.parentNode.classList.add('active'); } // Cuando el componente ha sido montado componentDidMount () { // this.selectOptionMenu(); this.handleActive(); } // Cuando el componente se actualiza componentDidUpdate () { // this.selectOptionMenu(); this.handleActive(); } render () { return ( <nav className="navbar navbar-default navbar-fixed-top"> <div className="container-fluid"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#header-navbar-collapse" aria-expanded="false"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <img src={image} alt="Billin code-challenge" onClick={ this.handleHome } /> <Link to='/' onClick={ this.clearActiveMenu } className="navbar-brand"> code-challenge </Link> </div> <div className="collapse navbar-collapse" id="header-navbar-collapse"> <ul className="nav navbar-nav navbar-right"> <li> <Link to='/authors' onClick={ this.handleActive }>Autores</Link> </li> <li> <Link to='/articles' onClick={ this.handleActive }>Artículos</Link> </li> </ul> </div> </div> </nav> ); } } const mapStateToProps = null; const mapDispatchToProps = null; /** * Para poder navegar desde el código react-router-dom * ofrece un decorador withRouter() para envolver cualquier * componente en el árbol del router (al estilo connect() de Redux), * es decir, cualquier componente que sea hijo de alguno de los que * se están pintando como parte de la ruta. * Va a inyectar como prop un objeto router con métodos al componente que está envolviendo. */ // Utilizar la exportación predeterminada para el componente conectado pra la aplicación export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Header));