path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/svg-icons/social/group.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialGroup = (props) => ( <SvgIcon {...props}> <path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/> </SvgIcon> ); SocialGroup = pure(SocialGroup); SocialGroup.displayName = 'SocialGroup'; SocialGroup.muiName = 'SvgIcon'; export default SocialGroup;
packages/mineral-ui-icons/src/IconKitchen.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconKitchen(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M18 2.01L6 2a2 2 0 0 0-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.11-.9-1.99-2-1.99zM18 20H6v-9.02h12V20zm0-11H6V4h12v5zM8 5h2v3H8zm0 7h2v5H8z"/> </g> </Icon> ); } IconKitchen.displayName = 'IconKitchen'; IconKitchen.category = 'places';
src/components/Header/Header.js
Galernaya20/galernaya20.com
//@flow import React from 'react' import styled from 'styled-components' const Video = styled.div` width: 300px; height: 200px; @media screen and (min-width: 576px) { width: 500px; height: 400px; } @media screen and (min-width: 768px) { width: 600px; height: 400px; } @media screen and (min-width: 992px) { width: 840px; height: 555px; } ` const VideoWrapper = styled.div` display: flex; justify-content: center; ` const Description = styled.p` margin-top: 30px; margin-bottom: 30px; ` const StyledHeader = styled.h2` margin-top: 30px; margin-bottom: 0; ` const Self = styled.div` background: #353535; color: #fff; text-align: center; padding-top: 30px; padding-bottom: 30px; ` const Iframe = styled.iframe` width: 100%; height: 150px; @media screen and (min-width: 576px) { height: 350px; } @media screen and (min-width: 768px) { height: 350px; } @media screen and (min-width: 992px) { height: 450px; } ` export type PropsT = { title: string, description: {description: string}, media?: {src: {src: string}}, } export const Header = ({title, description, media}: PropsT) => ( <Self> <div> <StyledHeader>{title}</StyledHeader> <Description>{description.description}</Description> {media && ( <VideoWrapper> <Video> <Iframe src={media.src.src} frameBorder="0" allowFullscreen /> </Video> </VideoWrapper> )} </div> </Self> )
tosort/2016/jspm/lib_react_004_x.js
Offirmo/html_tests
import React from 'react'; import ReactDOM from 'react-dom'; // https://facebook.github.io/react/docs/reusable-components.html class CoolComponent extends React.Component { constructor (props) { console.info('~~ constructor', arguments) // TODO define initial state ? super(props) // <-- really needed ? } // inheriting : // .state => NEVER mutate this.state directly, treat this.state as if it were immutable. // .setState(nextState, [callback]) // .replaceState(nextState, [callback]) XXX do not use, pending removal // .forceUpdate([callback]) // setProps // NO "This is only supported for classes created using React.createClass. // Did you mean to define a state property instead?" /*getInitialState () { console.info('~~ getInitialState') return { foo: 42 } }*/ // NO "This is only supported for classes created using React.createClass. // Use a static property to define defaultProps instead." /*getDefaultProps () { console.info('~~ getDefaultProps') return { value: 'default value' } }*/ // invoked once componentWillMount () { console.info('~~ componentWillMount', arguments) } render () { console.count('~~ render', arguments) console.info('~~ render', arguments) return ( <p> Hello, <input type="text" placeholder="Your name here" /> !<br /> {this.props.children} </p> ) } // invoked once, client only componentDidMount () { console.info('~~ componentDidMount', arguments) } // https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops // REM : props way NOT have changed // cf. https://facebook.github.io/react/blog/2016/01/08/A-implies-B-does-not-imply-B-implies-A.html componentWillReceiveProps (nextProps) { console.info('~~ componentWillReceiveProps', arguments) } // https://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate shouldComponentUpdate (nextProps, nextState) { console.info('~~ shouldComponentUpdate', arguments) return true // optimisation possible } // https://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate // REM : NOT called in the initial rendering componentWillUpdate (nextProps, nextState) { console.info('~~ componentWillUpdate', arguments) return true // optimisation possible } // https://facebook.github.io/react/docs/component-specs.html#updating-componentdidupdate componentDidUpdate (prevProps, prevState) { console.info('~~ componentDidUpdate', arguments) } // https://facebook.github.io/react/docs/component-specs.html#unmounting-componentwillunmount componentWillUnmount () { console.info('~~ componentWillUnmount', arguments) } } // https://facebook.github.io/react/docs/reusable-components.html#prop-validation CoolComponent.propTypes = { initialCount: React.PropTypes.number, children: React.PropTypes.node.isRequired } CoolComponent.defaultProps = { initialCount: 0 } // CoolComponent.mixins // CoolComponent.statics ReactDOM.render( <CoolComponent>Meow</CoolComponent>, document.getElementById('example') )
docs/src/pages/components/drawers/SwipeableTemporaryDrawer.js
lgollut/material-ui
import React from 'react'; import clsx from 'clsx'; import { makeStyles } from '@material-ui/core/styles'; import SwipeableDrawer from '@material-ui/core/SwipeableDrawer'; import Button from '@material-ui/core/Button'; import List from '@material-ui/core/List'; import Divider from '@material-ui/core/Divider'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemText from '@material-ui/core/ListItemText'; import InboxIcon from '@material-ui/icons/MoveToInbox'; import MailIcon from '@material-ui/icons/Mail'; const useStyles = makeStyles({ list: { width: 250, }, fullList: { width: 'auto', }, }); export default function SwipeableTemporaryDrawer() { const classes = useStyles(); const [state, setState] = React.useState({ top: false, left: false, bottom: false, right: false, }); const toggleDrawer = (anchor, open) => (event) => { if (event && event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) { return; } setState({ ...state, [anchor]: open }); }; const list = (anchor) => ( <div className={clsx(classes.list, { [classes.fullList]: anchor === 'top' || anchor === 'bottom', })} role="presentation" onClick={toggleDrawer(anchor, false)} onKeyDown={toggleDrawer(anchor, false)} > <List> {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> <Divider /> <List> {['All mail', 'Trash', 'Spam'].map((text, index) => ( <ListItem button key={text}> <ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon> <ListItemText primary={text} /> </ListItem> ))} </List> </div> ); return ( <div> {['left', 'right', 'top', 'bottom'].map((anchor) => ( <React.Fragment key={anchor}> <Button onClick={toggleDrawer(anchor, true)}>{anchor}</Button> <SwipeableDrawer anchor={anchor} open={state[anchor]} onClose={toggleDrawer(anchor, false)} onOpen={toggleDrawer(anchor, true)} > {list(anchor)} </SwipeableDrawer> </React.Fragment> ))} </div> ); }
examples/with-sentry-simple/pages/_error.js
BlancheXu/test
import React from 'react' import Error from 'next/error' import * as Sentry from '@sentry/node' const MyError = ({ statusCode, hasGetInitialPropsRun, err }) => { if (!hasGetInitialPropsRun && err) { // getInitialProps is not called in case of // https://github.com/zeit/next.js/issues/8592. As a workaround, we pass // err via _app.js so it can be captured Sentry.captureException(err) } return <Error statusCode={statusCode} /> } MyError.getInitialProps = async ({ res, err, asPath }) => { const errorInitialProps = await Error.getInitialProps({ res, err }) // Workaround for https://github.com/zeit/next.js/issues/8592, mark when // getInitialProps has run errorInitialProps.hasGetInitialPropsRun = true if (res) { // Running on the server, the response object is available. // // Next.js will pass an err on the server if a page's `getInitialProps` // threw or returned a Promise that rejected if (res.statusCode === 404) { // Opinionated: do not record an exception in Sentry for 404 return { statusCode: 404 } } if (err) { Sentry.captureException(err) return errorInitialProps } } else { // Running on the client (browser). // // Next.js will provide an err if: // // - a page's `getInitialProps` threw or returned a Promise that rejected // - an exception was thrown somewhere in the React lifecycle (render, // componentDidMount, etc) that was caught by Next.js's React Error // Boundary. Read more about what types of exceptions are caught by Error // Boundaries: https://reactjs.org/docs/error-boundaries.html if (err) { Sentry.captureException(err) return errorInitialProps } } // If this point is reached, getInitialProps was called without any // information about what the error might be. This is unexpected and may // indicate a bug introduced in Next.js, so record it in Sentry Sentry.captureException( new Error(`_error.js getInitialProps missing data at path: ${asPath}`) ) return errorInitialProps } export default MyError
hosted-demo/src/components/PokemonCardHeader.js
learnapollo/pokedex-react
import React from 'react' import { propType } from 'graphql-anywhere' import gql from 'graphql-tag' import styled from 'styled-components' const Title = styled.div` color: #7F7F7F; font-size: 32px; font-weight: 300; max-width: 400px; margin-top: 50px; ` export default class PokemonCardHeader extends React.Component { static fragments = { pokemon: gql` fragment PokemonCardHeaderPokemon on Pokemon { name trainer { name } } ` } static propTypes = { pokemon: propType(PokemonCardHeader.fragments.pokemon).isRequired, } render () { return ( <div className='w-100 flex justify-center'> <Title>{this.props.pokemon.name} owned by {this.props.pokemon.trainer.name}</Title> </div> ) } }
src/components/Footer.js
jansplichal2/reactnd-project-readable-starter
import React from 'react'; const Footer = () => { return ( <footer className="footer"> <p>&copy; Jan Splichal 2017</p> </footer> ); }; export default Footer;
app/components/Institution/InsufficientPermissionMsg.js
klpdotorg/tada-frontend
import React from 'react'; const InsufficientPermissionMsg = () => { return ( <div> <div className="alert alert-danger"> <i className="fa fa-lock fa-lg" aria-hidden="true" /> Insufficient Privileges. Please contact administrator for permissions to modify the institution. </div> </div> ); }; export { InsufficientPermissionMsg };
packages/material-ui-icons/src/Battery50Sharp.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M17 4h-3V2h-4v2H7v9h10V4z" /><path d="M7 13v9h10v-9H7z" /></React.Fragment> , 'Battery50Sharp');
src/components/Text/index.js
khankuan/asset-library-demo
import cx from 'classnames'; import React from 'react'; export default class Text extends React.Component { static propTypes = { children: React.PropTypes.node, bold: React.PropTypes.bool, italics: React.PropTypes.bool, underline: React.PropTypes.bool, size: React.PropTypes.string, padding: React.PropTypes.string, block: React.PropTypes.bool, className: React.PropTypes.string, } static defaultProps = { size: 'base', padding: 'none', block: false, } getClasses() { return cx( 'text', { 'bold': this.props.bold, 'italics': this.props.italics, 'underline': this.props.underline, 'block': this.props.block, }, 'text-size-' + this.props.size, 'text-padding-' + this.props.padding, this.props.className ); } render() { return ( <span className={ this.getClasses() }> { this.props.children } </span> ); } }
src/components/ActivePlayerPage/ActivePlayerPage.js
RetroGameNight/rgn-ui
/* * Retro Game Night * Copyright (c) 2015 Sasha Fahrenkopf, Cameron White * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import './ActivePlayerPage.less' import React from 'react' import FluxComponent from 'flummox/component' import _ from 'underscore' export default class ActivePlayerPage extends React.Component { render() { return ( <FluxComponent connectToStores={['api']}> <ActivePlayerPageInner /> </FluxComponent> ) } } class ActivePlayerPageInner extends React.Component { loggedIn() { if (this.props.activeUser) { return true } else { return false } } render() { let content = [] if (this.loggedIn()) { const rows = _.pairs(this.props.activeUser) .map((pair) => { return ( <tr> <td>{pair[0]}</td> <td>{pair[1]}</td> </tr> ) }) content = ( <table className="table"> <tr> <th>Key</th> <th>Value</th> </tr> {rows} </table> ) } else { content = [ <h2>Not Logged In</h2> ] } return ( <div> <h1>Active Player Page</h1> {content} </div> ) } }
fields/types/number/NumberField.js
pr1ntr/keystone
import React from 'react'; import Field from '../Field'; import { FormInput } from 'elemental'; module.exports = Field.create({ displayName: 'NumberField', statics: { type: 'Number', }, valueChanged (event) { var newValue = event.target.value; if (/^-?\d*\.?\d*$/.test(newValue)) { this.props.onChange({ path: this.props.path, value: newValue, }); } }, renderField () { return ( <FormInput name={this.getInputName(this.props.path)} ref="focusTarget" value={this.props.value} onChange={this.valueChanged} autoComplete="off" /> ); }, });
src/svg-icons/file/cloud-queue.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCloudQueue = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6c-2.21 0-4-1.79-4-4s1.79-4 4-4h.71C7.37 7.69 9.48 6 12 6c3.04 0 5.5 2.46 5.5 5.5v.5H19c1.66 0 3 1.34 3 3s-1.34 3-3 3z"/> </SvgIcon> ); FileCloudQueue = pure(FileCloudQueue); FileCloudQueue.displayName = 'FileCloudQueue'; export default FileCloudQueue;
frontends/xcms/app/routes.js
suryakencana/niimanga
/** @flow */ import React from 'react'; import { Route, DefaultRoute, NotFoundRoute } from'react-router'; import App from 'handlers'; import Index from 'handlers/Home'; import Group from 'handlers/Group'; import Series from 'handlers/Series'; import SeriesPage from 'handlers/Series/page'; import Chapters from 'handlers/Chapters'; module.exports = () => { return [ <Route name="root" path="/cms" handler={App}> <DefaultRoute name="home" handler={Index} /> <Route name="group" path="/cms/group" handler={Group} /> <Route name="series" path="/cms/series" handler={Series} /> <Route name="series_edit" path="/cms/series/:seriesSlug" handler={SeriesPage} /> <Route name="chapters" path="/cms/chapters" handler={Chapters} /> <Route name="genre" path="/cms/genres" handler={Chapters} /> <Route name="chapter" path="/cms/genres" handler={Chapters} /> </Route> ]; };
actor-apps/app-web/src/app/index.js
x303597316/actor-platform
import crosstab from 'crosstab'; import React from 'react'; import Router from 'react-router'; import Raven from 'utils/Raven'; // eslint-disable-line import isMobile from 'utils/isMobile'; import ReactMixin from 'react-mixin'; import Intl from 'intl'; // eslint-disable-line import LocaleData from 'intl/locale-data/jsonp/en-US'; // eslint-disable-line import { IntlMixin } from 'react-intl'; import { english, russian } from 'l18n'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Deactivated from 'components/Deactivated.react'; import Login from 'components/Login.react'; import Main from 'components/Main.react'; import JoinGroup from 'components/JoinGroup.react'; import Install from 'components/Install.react'; import LoginStore from 'stores/LoginStore'; import LoginActionCreators from 'actions/LoginActionCreators'; //import AppCache from 'utils/AppCache'; // eslint-disable-line import Pace from 'pace'; Pace.start({ ajax: false, restartOnRequestAfter: false, restartOnPushState: false }); const DefaultRoute = Router.DefaultRoute; const Route = Router.Route; const RouteHandler = Router.RouteHandler; const ActorInitEvent = 'concurrentActorInit'; if (crosstab.supported) { crosstab.on(ActorInitEvent, (msg) => { if (msg.origin !== crosstab.id && window.location.hash !== '#/deactivated') { window.location.assign('#/deactivated'); window.location.reload(); } }); } // Check for mobile device, and force users to install native apps. if (isMobile() && window.location.hash !== '#/install') { window.location.assign('#/install'); document.body.classList.add('overflow'); } else if (window.location.hash === '#/install') { window.location.assign('/'); } @ReactMixin.decorate(IntlMixin) class App extends React.Component { render() { return <RouteHandler/>; } } // Internationalisation // TODO: Move to preferences const language = 'en-US'; //const language = 'ru-RU'; let intlData; switch (language) { case 'ru-RU': intlData = russian; break; case 'en-US': intlData = english; break; } const initReact = () => { if (window.location.hash !== '#/deactivated') { if (crosstab.supported) { crosstab.broadcast(ActorInitEvent, {}); } if (location.pathname === '/app/index.html') { window.messenger = new window.actor.ActorApp(['ws://' + location.hostname + ':9080/']); } else { window.messenger = new window.actor.ActorApp(); } } const routes = ( <Route handler={App} name="app" path="/"> <Route handler={Main} name="main" path="/"/> <Route handler={JoinGroup} name="join" path="/join/:token"/> <Route handler={Login} name="login" path="/auth"/> <Route handler={Deactivated} name="deactivated" path="/deactivated"/> <Route handler={Install} name="install" path="/install"/> <DefaultRoute handler={Main}/> </Route> ); const router = Router.run(routes, Router.HashLocation, function (Handler) { injectTapEventPlugin(); React.render(<Handler {...intlData}/>, document.getElementById('actor-web-app')); }); if (window.location.hash !== '#/deactivated') { if (LoginStore.isLoggedIn()) { LoginActionCreators.setLoggedIn(router, {redirect: false}); } } }; window.jsAppLoaded = () => { setTimeout(initReact, 0); };
src/events/event-host.js
FederationOfFathers/ui
import React, { Component } from 'react'; import moment from 'moment-timezone'; import InputMoment from 'input-moment'; import '../input-moment.css' class EventHost extends Component { constructor(props) { super(props) // 🤷🏽‍♂️ somethign about getting the time/dams. ported from original. ask DK var initialMoment = moment() var initialOffMinutes = initialMoment.get('minute') % 5 if ( initialOffMinutes !== 0 ) { initialMoment.set( 'minute', initialMoment.get('minute') + ( 5 - initialOffMinutes ) ) } var initialOffSeconds = initialMoment.get('second') initialMoment.set( 'second', initialMoment.get('minute') - initialOffSeconds ) var maxDays = 14 if ( this.props.state.admin === true ) { maxDays = 365 } this.state = { title: "", channel: "", m: initialMoment, now: moment(initialMoment), max: moment().add(maxDays, 'days'), tz: moment.tz.zone(moment.tz.guess()).abbr(moment()), need: 0, } } changeChannel = ( e ) => { this.setState({channel: e.target.value}) } changeTitle = ( e ) => { this.setState({title: e.target.value}) } momentString = () => { return this.state.m.format('MM/DD hh:mma') + ' ' + this.state.tz } changeMoment = ( m ) => { this.setState({m: m}) } save = async () => { var err = this.errors() if ( err.Moment !== false ) { return } var body = { where: this.state.channel, title: this.state.title, when: this.state.m.format('X'), // IMPORTANT Go uses Unix/Seconds, not milliseconds } // we ask how many MORE members... but we want to record how many // total that we need... so add an additional slot for the host body.need = this.state.need + 1; try { await this.props.state.api.team.host(body) this.props.state.hasher.set({event: null}) } catch(error) { console.error("event save failed " + error) } } stateComponentWillMount = () => { this.change( moment() ) } errors = () => { var rval = { Moment: false, MomentGood: false, Title: false, Chan: false, } if ( this.state.channel === "" ) { rval.Chan = (<div className="alert alert-danger">Pick a channel</div>) } if ( this.state.title.length < 5 ) { rval.Title = (<div className="alert alert-danger">Title must be more substantial</div>) } if ( this.state.now.isAfter( this.state.m ) ) { rval.Moment = (<div className="mx-4 alert alert-danger">Be <strong>after</strong> {moment().format('llll')}</div>) } else if ( this.state.m.isAfter( this.state.max ) ) { rval.Moment = (<div className="mx-4 alert alert-danger">Be <strong>before</strong> {this.state.max.format('llll')}</div>) } else { rval.MomentGood = (<div className="mx-4 alert alert-success">Event Time: [{this.momentString()}]</div>) } return rval } isHostableChannel = (channel) => { if (this.props.state.admin === true) { // admins host anywhere return true } if (this.props.state.verified === false) { // unverified can't host return false } let hostableCategories = [ "444608078411989012", // PC Games "444608230140674059", // PS4 "439890949569642498", // Xbox "444608367118516225", // Switch "440693691192049675", // Random ] return hostableCategories.indexOf(channel.categoryID) > -1; } renderChanSelect = () => { var channels = [ (<option key="none" value="">Select A Channel</option>) ] for ( let i in this.props.state.eventChannels ) { let channel = this.props.state.eventChannels[i]; if (this.isHostableChannel(channel)) { let channelName = channel.categoryName === "" ? channel.name : channel.categoryName + ": " + channel.name; channels.push(<option key={i} value={channel.channelID}>{channelName}</option>) } } return( <div className="form-group"> <form> <div className="my-2 mx-4"> <select onChange={this.changeChannel} className="form-control" id="echan"> {channels} </select> </div> </form> </div> ) } renderTitleInput = () => { if ( this.state.channel === "" ) { return null } return( <div className="form-group"> <form> <div className="my-2 mx-4"> <input value={this.state.title} onChange={this.changeTitle} type="text" id="ename" className="form-control" placeholder="Example Event Name"/> </div> </form> </div> ) } renderMomentSelect = () => { if ( this.state.title.length < 5 ) { return null } var err = this.errors() return( <div className="form-group"> <form> <div className="my-2"> { err.MomentGood || err.Moment } <div style={{textAlign: "center"}}> <InputMoment moment={this.state.m} onChange={this.changeMoment} onSave={this.save} minStep={5} /> </div> </div> </form> </div> ) } decrNeed = () => { this.setState({need: this.state.need - 1}) } decrNeedBtn = () => { return (<button type="button" className="btn btn-link border-1" onClick={this.decrNeed}>-</button>) } incrNeed = () => { this.setState({need: this.state.need + 1}) } incrNeedBtn = () => { return (<button type="button" className="btn btn-link border-1" onClick={this.incrNeed}>+</button>) } renderNeedInput = () => { if ( this.state.title.length < 5 ) { return } if ( this.state.need < 1 ) { return ( <div className="form-group"> <form> <div className="my-2 mx-4 text-center"> <input type="text" onClick={this.incrNeed} value="" className="form-control w-100" placeholder="How many players do you need?"/> </div> </form> </div> ) } return( <div className="form-group"> <form> <div className="my-2 mx-4 text-center border"> looking for {this.decrNeedBtn()} {this.state.need} {this.incrNeedBtn()} more </div> </form> </div> ) } render = () => { return ( <div> {this.renderChanSelect()} {this.renderTitleInput()} {this.renderNeedInput()} {this.renderMomentSelect()} </div> ) } } export default EventHost
client/modules/App/__tests__/App.spec.js
trantuthien/React-Test
import React from 'react'; import test from 'ava'; import sinon from 'sinon'; import { shallow, mount } from 'enzyme'; import { App } from '../App'; import styles from '../App.css'; import { intlShape } from 'react-intl'; import { intl } from '../../../util/react-intl-test-helper'; import { toggleAddPost } from '../AppActions'; const intlProp = { ...intl, enabledLanguages: ['en', 'fr'] }; const children = <h1>Test</h1>; const dispatch = sinon.spy(); const props = { children, dispatch, intl: intlProp, }; test('renders properly', t => { const wrapper = shallow( <App {...props} /> ); // t.is(wrapper.find('Helmet').length, 1); t.is(wrapper.find('Header').length, 1); t.is(wrapper.find('Footer').length, 1); t.is(wrapper.find('Header').prop('toggleAddPost'), wrapper.instance().toggleAddPostSection); t.truthy(wrapper.find('Header + div').hasClass(styles.container)); t.truthy(wrapper.find('Header + div').children(), children); }); test('calls componentDidMount', t => { sinon.spy(App.prototype, 'componentDidMount'); mount( <App {...props} />, { context: { router: { isActive: sinon.stub().returns(true), push: sinon.stub(), replace: sinon.stub(), go: sinon.stub(), goBack: sinon.stub(), goForward: sinon.stub(), setRouteLeaveHook: sinon.stub(), createHref: sinon.stub(), }, intl, }, childContextTypes: { router: React.PropTypes.object, intl: intlShape, }, }, ); t.truthy(App.prototype.componentDidMount.calledOnce); App.prototype.componentDidMount.restore(); }); test('calling toggleAddPostSection dispatches toggleAddPost', t => { const wrapper = shallow( <App {...props} /> ); wrapper.instance().toggleAddPostSection(); t.truthy(dispatch.calledOnce); t.truthy(dispatch.calledWith(toggleAddPost())); });
app/components/App.js
kensworth/Filebrew
import React, { Component } from 'react'; import WebTorrent from 'webtorrent'; import dragDrop from 'drag-drop'; import GitHub from 'react-icons/lib/fa/github'; import styles from '../styles/App.css'; import coffee from '../../images/coffee.png'; import Receive from './Receive'; import LinkArea from './LinkArea'; import $ from 'jquery'; // TODO: fix prod build // TODO: UX for invalid hashes // TODO: UX for closed seeds class App extends Component { constructor(props) { super(props); this.client = new WebTorrent(); this.state = { seeding: window.location.pathname !== '/' }; this.createTorrent = this.createTorrent.bind(this); this.updateSeeding = this.updateSeeding.bind(this); dragDrop('body', this.createTorrent); } createTorrent(files) { if (this.state.seeding) { return; } this.client.seed(files, (torrent) => { console.log('Client is seeding ' + torrent.magnetURI); $.ajax({ type: 'POST', url: '/create-hash', data: { magnet: torrent.magnetURI } }) .done((data) => { this.setState({ hash: data.hash, torrent: torrent, URI: window.location.host + '/' + data.hash, seeding: true }); }); }); } updateSeeding() { this.setState({seeding: false}); } render() { const firstPrompt = this.state.seeding ? 'Your file is being brewed.' : 'Drop a file into the cup to start seeding.'; const secondPrompt = this.state.seeding ? 'Please keep your browser open until the download finishes!' : 'Copy/Paste the URL to a friend to share the file. Make sure you keep your browser open!'; const coffeeStyle = this.state.seeding ? [styles.StaticLogo, styles.MovingLogo].join(' ') : styles.StaticLogo; return ( <div className={styles.App}> <div className={styles.AppHeader}> <h1>File Brew</h1> <p>{firstPrompt}</p> <p>{secondPrompt}</p> <img src={coffee} id="coffee" className={coffeeStyle} /> </div> { this.state.URI && <LinkArea URI={this.state.URI} /> } <Receive seeding={this.state.seeding} client={this.client} updateSeeding={this.updateSeeding.bind(this)} /> <div className={styles.GitHub} > <a href="https://github.com/kensworth/Filebrew"> <GitHub className={styles.Icon}/> Brewed by Kenneth Zhang </a> </div> </div> ); } } export default App;
src/js/components/Box/stories/Background.js
HewlettPackard/grommet
import React from 'react'; import { Grommet, Box, Text } from 'grommet'; import { grommet } from '../../../themes'; export const BackgroundBox = () => ( <Grommet theme={grommet}> <Box pad="small" gap="small" align="start"> <Box pad="small" background={{ color: 'brand', opacity: true }} elevation="large" > brand opacity </Box> <Box pad="small" background="brand" elevation="large"> brand </Box> <Box pad="small" background={{ color: 'brand' }} elevation="large"> brand object </Box> <Box pad="small" background={{ image: 'url(https://images.unsplash.com/photo-1487088678257-3a541e6e3922?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2167&q=80)', opacity: 'strong', }} > image </Box> <Box pad="small" background={{ color: 'accent-2', image: 'url(https://images.unsplash.com/photo-1487088678257-3a541e6e3922?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2167&q=80)', }} > image + color </Box> <Box background="dark-1" pad="medium"> <Box background="#FFFFFF08" pad="small"> low opacity on dark background </Box> </Box> <Box background="light-5" pad="medium"> <Box background="#11111108" pad="small"> low opacity on light background </Box> </Box> <Box background={{ color: 'background', dark: true }} pad="medium"> <Text color="brand">force dark background</Text> </Box> <Box background="dark-1" pad="medium"> <Box background={{ color: 'background', dark: false }} pad="medium"> <Text color="brand">force light background</Text> </Box> </Box> <Box background={{ color: { dark: 'darkgrey', light: 'lightgrey' }, dark: true, }} pad="medium" > <Text color="brand">force dark background with color as object</Text> </Box> <Box background="dark-1" pad="medium"> <Box background={{ color: { dark: 'darkgrey', light: 'lightgrey' }, dark: false, }} pad="medium" > <Text color="brand">force light background with color as object</Text> </Box> </Box> </Box> </Grommet> ); BackgroundBox.storyName = 'Background'; export default { title: 'Layout/Box/Background', };
app/containers/DebugPage.js
soosgit/vessel
// @flow import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { Redirect } from 'react-router'; import { connect } from 'react-redux'; import { Button, Table } from 'semantic-ui-react'; import MenuBar from './MenuBar'; import ContentBar from '../components/ContentBar'; import * as PreferencesActions from '../actions/preferences'; import * as KeysActions from '../actions/keys'; class DebugPage extends Component { unlock = (e, props) => { console.log("unlock", props.value); } send = (e, props) => { // const wif = this.props.actions.getKey(props.value); const account = props.value; const { permissions } = this.props.keys; this.props.actions.useKey('transfer', { from: 'webdev', to: 'webdev', amount: '0.001 STEEM', memo: '' }, permissions[account]) // this.props.actions.transfer(wif, "webdev", "webdev", "0.001 STEEM", "") } render() { console.log("props", this.props.keys.permissions['webdev']); const accounts = Object.keys(this.props.keys.permissions); const permissions = this.props.keys.permissions; if (!this.props.keys.isUser) { return <Redirect to="/" />; } return ( <ContentBar> <Table celled unstackable attached> <Table.Body> {accounts.map((account, i) => ( <Table.Row key={account}> <Table.Cell> {account} </Table.Cell> <Table.Cell> {/* <Button content="Unlock" value={account} onClick={this.unlock} /> */} <Button content="Send" value={account} onClick={this.send} /> </Table.Cell> <Table.Cell> {(permissions[account].encrypted) ? 'True' : 'False'} </Table.Cell> <Table.Cell> {permissions[account].type} </Table.Cell> <Table.Cell> {permissions[account].key} </Table.Cell> </Table.Row> ))} </Table.Body> </Table> <MenuBar /> </ContentBar> ); } } function mapStateToProps(state) { return { account: state.account, keys: state.keys, preferences: state.preferences }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({ ...KeysActions, ...PreferencesActions }, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(DebugPage);
src/modules/texts/components/ReadingEnvironment/ReadingEnvironment.js
cltk/cltk_frontend
import React from 'react'; import { Link } from 'react-router'; import './ReadingEnvironment.css'; const ReadingEnvironment = ({ textNodes, id, english_title, original_title, slug, textLocationPrev, textLocationNext })=> { if (!id) { return null; } return ( <div className="readingEnvironment"> <div className="pageReadingHead" style={{ backgroundImage: 'url(/images/chariots_boar.jpg)', backgroundSize: 'cover', backgroundPosition: 'center', }} /> <div className="readingEnvironmentText"> {textNodes.map(textNode => { const number = textNode.location[textNode.location.length - 1]; let location = ''; textNode.location.forEach((n, i) => { if (i === 0) { location = `${n}`; } else { location = `${location}.${n}`; } }); return ( <div className="readingEnvironmentTextNode" key={textNode.location.join('.')} > <span className={` readingEnvironmentTextNodeNumber ${ (number % 5 === 0) ? 'readingEnvironmentTextNodeNumberShow' : '' } `}> {location} </span> <p className="readingEnvironmentTextNodeText" dangerouslySetInnerHTML={{ __html: textNode.text }} /> </div> ); })} </div> <div className="readingEnvironmentPagination"> {textLocationPrev ? <Link to={`/texts/${id}/${slug}/${textLocationPrev.join('.')}`} className="readingEnvironmentPaginationLink readingEnvironmentPaginationLinkPrevious" > Previous </Link> : ''} {textLocationNext ? <Link to={`/texts/${id}/${slug}/${textLocationNext.join('.')}`} className="readingEnvironmentPaginationLink readingEnvironmentPaginationLinkNext" > Next </Link> : ''} </div> </div> ); }; export default ReadingEnvironment;
WebDev/BE/JS/electron/chatApp/src/Pages/NotFound/NotFound.js
ParkDyel/practice
import React, { Component } from 'react'; export default class NotFound extends Component { render(){ return( <div> <h1>Not Found, 404</h1> </div> ) } }
dpxdt/server/static/release-config/src/index.js
bslatkin/dpxdt
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
examples/react/CheckboxWithLabel.js
mpontus/jest
// Copyright 2004-present Facebook. All Rights Reserved. import React from 'react'; export default class CheckboxWithLabel extends React.Component { constructor(props) { super(props); this.state = {isChecked: false}; // bind manually because React class components don't auto-bind // http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding this.onChange = this.onChange.bind(this); } onChange() { this.setState({isChecked: !this.state.isChecked}); } render() { return ( <label> <input type="checkbox" checked={this.state.isChecked} onChange={this.onChange} /> {this.state.isChecked ? this.props.labelOn : this.props.labelOff} </label> ); } }
docs/src/app/components/pages/components/AutoComplete/ExampleSimple.js
nathanmarks/material-ui
import React from 'react'; import AutoComplete from 'material-ui/AutoComplete'; export default class AutoCompleteExampleSimple extends React.Component { constructor(props) { super(props); this.state = { dataSource: [], }; } handleUpdateInput = (value) => { this.setState({ dataSource: [ value, value + value, value + value + value, ], }); }; render() { return ( <div> <AutoComplete hintText="Type anything" dataSource={this.state.dataSource} onUpdateInput={this.handleUpdateInput} /> <AutoComplete hintText="Type anything" dataSource={this.state.dataSource} onUpdateInput={this.handleUpdateInput} floatingLabelText="Full width" fullWidth={true} /> </div> ); } }
client/pages/examples/threejs/graphing/elements/pendulum.js
fdesjardins/webgl
import React from 'react' import * as THREE from 'three' import { createAxes, createPoint, addControls, addAxesLabels } from '../utils' const WHITE = 0xffffff const BLACK = 0x000000 const setupCamera = ({ domain, margin }) => { const camera = new THREE.OrthographicCamera( domain[0] - margin[0], domain[1] + margin[1], domain[1] + margin[2], domain[0] - margin[3], 0.1, 1000 ) camera.updateProjectionMatrix() camera.position.z = 100 camera.position.x = 0 camera.position.y = 0 return camera } const init = ({ state }) => { const canvas = document.getElementById('pendulum') const domain = [-10, 10] const gridSize = 1 // left, right, top, bottom const margin = [2, 2, 2, 2] let scene = new THREE.Scene() const camera = setupCamera({ domain, margin }) let renderer = new THREE.WebGLRenderer({ canvas, antialias: true }) renderer.setSize(canvas.clientWidth, canvas.clientWidth) scene.background = new THREE.Color(WHITE) const light = new THREE.AmbientLight(WHITE) scene.add(light) const p = createPoint({ size: 0.25, color: 0x0000ff }) scene.add(p) addControls({ camera, renderer }) const radius = 4 // initial time const t_0 = 0 // initial displacement const d_0 = 0 // initial angular velocity const w_0 = 0.5 * Math.PI // initial angular acceleration const a = 0 const grid = new THREE.GridHelper( domain[1] - domain[0], (domain[1] - domain[0]) / gridSize, 0x000000, 0xbbbbbb ) grid.rotation.x = Math.PI / 2 scene.add(grid) const axes = createAxes({ size: (domain[1] - domain[0]) / 2, fontSize: 0 }) scene.add(axes) addAxesLabels({ scene, domain, gridSize }) const ellipseCurve = new THREE.EllipseCurve( 0, 0, radius, radius, 0, Math.PI, false, 0 ) const points = ellipseCurve.getPoints(20) const pointsGeometry = new THREE.BufferGeometry().setFromPoints(points) const pointsMaterial = new THREE.LineDashedMaterial({ color: BLACK, linewidth: 2, scale: 1, dashSize: 0.25, gapSize: 0.25, }) const curve = new THREE.Line(pointsGeometry, pointsMaterial) scene.add(curve) let lastMousePos = { x: 0.5, y: 0.5 } const mousePos = (event) => { const bounds = event.target.getBoundingClientRect() // const center = { // x: (bounds.right - bounds.left) / 2, // y: (bounds.bottom - bounds.top) / 2 // } const xy = { x: event.clientX - bounds.left, y: event.clientY - bounds.top, } const x = xy.x / event.target.clientWidth const y = xy.y / event.target.clientHeight // const x = event.target.clientX / event.target.clientWidth // const x = (event.clientX / window.innerWidth) * 2 - 1 // const y = event.clientY / event.target.clientHeight return [x, y] } canvas.onmousemove = (event) => { const [x, y] = mousePos(event) lastMousePos = { x, y, } } canvas.onmouseleave = () => { lastMousePos = { x: 0.5, y: 0.5 } } const arrowHelper = new THREE.ArrowHelper( new THREE.Vector3(1, 0, 0).normalize(), new THREE.Vector3(0, 0, 0), radius, BLACK ) scene.add(arrowHelper) const objectState = state.select('object') let thenSecs = 0 const animate = (now) => { if (!renderer) { return } requestAnimationFrame(animate) const nowSecs = now * 0.001 const deltaSecs = nowSecs - thenSecs thenSecs = nowSecs const rad2deg = (rad) => rad * (180 / Math.PI) const deg2rad = (deg) => deg / (180 / Math.PI) const t = nowSecs const w_i = w_0 + a * t const d_i = deg2rad(0 + rad2deg(w_i * t)) const d_x = radius * Math.cos(d_i) const d_y = radius * Math.sin(d_i) p.position.set(d_x, d_y, 0) arrowHelper.setDirection(new THREE.Vector3(d_x, d_y, 0).normalize()) const crv = new THREE.EllipseCurve(0, 0, radius, radius, 0, d_i, false, 0) curve.geometry.setFromPoints(crv.getPoints(32)) curve.computeLineDistances() curve.geometry.verticesNeedUpdate = true // arrows.map(arrow => { // const newDir = new THREE.Vector3( // Math.cos(arrow.position.y + nowSecs * 3), // Math.sin(arrow.position.x + nowSecs), // Math.sin(arrow.position.x + nowSecs) * 2 // ) // const newLength = newDir.length() * gridSize * 0.6 // arrow.setDirection(newDir.normalize()) // const headLength = 0.5 * newLength // const headWidth = 0.35 * headLength // arrow.setLength(newLength, headLength, headWidth) // }) // // mouseArrows.map(arrow => { // const newDir = new THREE.Vector3( // (lastMousePos.x * 2 - 1) * (domain[1] + 1) - arrow.position.x, // -1 * (lastMousePos.y * 2 - 1) * (domain[1] + 1) - arrow.position.y, // 0 // ) // const newLength = Math.min(1, 3 / newDir.length()) // arrow.setDirection(newDir.normalize()) // const headLength = 0.5 * newLength // const headWidth = 0.35 * headLength // arrow.setLength(newLength, headLength, headWidth) // }) if (deltaSecs) { const rotationSpeed = objectState.get('rotationSpeed') // objects.map(object => { // object.rotation.x += rotationSpeed.x * deltaSecs // object.rotation.y += rotationSpeed.y * deltaSecs // object.rotation.z += rotationSpeed.z * deltaSecs // // const dir = new THREE.Vector3( // Math.cos(object.position.y + nowSecs * 3) * 0.1 + // ((lastMousePos.x * 2 - 1) * domain[1] - object.position.x) / 200, // Math.sin(object.position.x + nowSecs) * 0.1 + // (-1 * (lastMousePos.y * 2 - 1) * domain[1] - object.position.y) / // 200, // 0 // ) // object.position.x += dir.x / object.mass / 10 // object.position.y += dir.y / object.mass / 10 // object.position.z = dir.z / object.mass / 10 // if (object.position.x < domain[0]) { // object.position.x = domain[1] // } // if (object.position.y < domain[0]) { // object.position.y = domain[1] // } // if (object.position.x > domain[1]) { // object.position.x = domain[0] // } // if (object.position.y > domain[1]) { // object.position.y = domain[0] // } // }) } renderer.render(scene, camera) } animate() return () => { renderer.dispose() scene = null renderer = null } } const Pendulum = ({ state, labels }) => { console.log(labels) React.useEffect(() => { if (document.getElementById('pendulum')) { return init({ state }) } }) return <canvas id="pendulum" /> } export { init } export default Pendulum
node_modules/@material-ui/core/es/Card/Card.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import Paper from '../Paper'; import withStyles from '../styles/withStyles'; export const styles = { /* Styles applied to the root element. */ root: { overflow: 'hidden' } }; const Card = React.forwardRef(function Card(props, ref) { const { classes, className, raised = false } = props, other = _objectWithoutPropertiesLoose(props, ["classes", "className", "raised"]); return React.createElement(Paper, _extends({ className: clsx(classes.root, className), elevation: raised ? 8 : 1, ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? Card.propTypes = { /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * If `true`, the card will use raised styling. */ raised: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiCard' })(Card);
src/client/hocs/require_unauth.js
ap-o/intro
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router'; import PropTypes from 'prop-types'; export default function(ComposedComponent) { class RequireUnAuth extends Component { static propTypes = { authenticated : PropTypes.bool.isRequired } render() { return this.props.authenticated ? ( <Redirect to="/"/> ) : ( <ComposedComponent {...this.props} /> ); } } function mapStateToProps(state) { return { authenticated : state.authenticated }; } return connect(mapStateToProps)(RequireUnAuth); }
frontend/src/Settings/Indexers/Restrictions/RestrictionsConnector.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { deleteRestriction, fetchRestrictions } from 'Store/Actions/settingsActions'; import createTagsSelector from 'Store/Selectors/createTagsSelector'; import Restrictions from './Restrictions'; function createMapStateToProps() { return createSelector( (state) => state.settings.restrictions, createTagsSelector(), (restrictions, tagList) => { return { ...restrictions, tagList }; } ); } const mapDispatchToProps = { fetchRestrictions, deleteRestriction }; class RestrictionsConnector extends Component { // // Lifecycle componentDidMount() { this.props.fetchRestrictions(); } // // Listeners onConfirmDeleteRestriction = (id) => { this.props.deleteRestriction({ id }); }; // // Render render() { return ( <Restrictions {...this.props} onConfirmDeleteRestriction={this.onConfirmDeleteRestriction} /> ); } } RestrictionsConnector.propTypes = { fetchRestrictions: PropTypes.func.isRequired, deleteRestriction: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(RestrictionsConnector);
examples/admin/pages/About.js
minwe/amazeui-react
import React from 'react'; import PageContainer from '../components/PageContainer'; const About = React.createClass({ render() { return ( <PageContainer {...this.props} > <h2>系统信息</h2> <hr /> <p>只是一个 Amaze UI React 后台模板骨架。欢迎完善。</p> </PageContainer> ); } }); export default About;
public/js/components/class_view_v2.js
AC287/wdi_final_arrowlense2.0_FE
import React from 'react' import $ from 'jquery' export default React.createClass({ contextTypes: { classes: React.PropTypes.object, userid: React.PropTypes.string, router: React.PropTypes.object.isRequired, }, getInitialState: function(){ return { instructor_firstname: '', instructor_lastname: '', instructor_email: '', instructor_imgurl: '', current_class: {}, } }, componentWillMount: function(){ this.state.current_class = Object.keys(this.context.classes) .filter((key)=>{ return key===this.props.params.id; }) .map((key)=> this.context.classes[key]); this.setState({current_class: this.state.current_class}); const getUserInfo = new Firebase(`https://arrowlense2-0.firebaseio.com/users/${this.state.current_class[0].created_by}`); getUserInfo.on('value',(snapshot) => { var instructorInfo = snapshot.val(); this.state.instructor_firstname = instructorInfo.firstname; this.state.instructor_lastname = instructorInfo.lastname; this.state.instructor_email = instructorInfo.email; this.state.instructor_imgurl = instructorInfo.imgurl; }) this.setState({ instructor_firstname: this.state.instructor_firstname, instructor_lastname: this.state.instructor_lastname, instructor_email: this.state.instructor_email, instructor_imgurl: this.state.instructor_imgurl, }) }, changeCurrentClass: function(data){ this.state.current_class[0] = data; this.setState({current_class: this.state.current_class}) }, renderEdit: function(){ if(this.context.userid === this.state.current_class[0].created_by) { return( <button>EDIT</button> ) } }, render: function(){ return ( <div> {/*THIS IS CLASS PAGE FOR CLASS ID: {this.props.params.id}*/} <div className="container-fluid"> <div className="row"> <div className="col-md-3 instructorInfo"> <img src={this.state.instructor_imgurl}/><br/> <p><strong>{this.state.instructor_firstname} {this.state.instructor_lastname}</strong></p> <p>{this.state.instructor_email}</p> </div> {/* end instructorInfo */} <div className="col-md-9 classInfo"> <h3>{this.state.current_class[0].name}</h3> <p>{this.state.current_class[0].semester} {this.state.current_class[0].year}</p> <p>The class is currently active: <strong>{(this.state.current_class[0].active).toString().toUpperCase()}</strong></p> <p><strong>Description: </strong>{this.state.current_class[0].description}</p> <div> <RenderEdit userid={this.context.userid} classinfo={this.state.current_class[0]} changeCurrentClass={this.changeCurrentClass}/> </div> </div> {/* end classInfo*/} </div> {/* end row container */} <hr/> <h3>Enrolled Students: </h3> </div> {/* end container-fluid */} </div> ) } }); const RenderEdit= React.createClass({ contextTypes: { classes: React.PropTypes.object, userid: React.PropTypes.string, editClass: React.PropTypes.func, }, handleEditClass: function(event){ event.preventDefault(); $('.editClass').attr('disabled', 'disabled'); $('.editClass').attr('value', 'updating...'); var newClassInfo = { section: { name: (this.refs.classname.value).toUpperCase(), active: $.parseJSON(this.refs.isactive.value), created_by: this.context.userid, semester: this.refs.semester.value, year: this.refs.year.value, description: this.refs.description.value, } }; $.ajax({ method: "PUT", url: `http://localhost:3000/sections/${this.props.classinfo.id}`, data: newClassInfo, }).done((data) => { console.log(data) this.context.editClass(data); this.props.changeCurrentClass(data); }) }, handleClose: function(event) { $('.editClass').removeAttr('disabled'); $('.editClass').attr('value', 'Create'); this.refs.editclass.reset(); }, render: function(){ if(this.props.userid === this.props.classinfo.created_by) { return( <div> <form className="form-group"> <button type="button" className="btn btn-default" data-toggle="modal" data-target=".edit-class-form">EDIT</button> </form> <div className="modal fade edit-class-form" tabIndex="-1" role="dialog" aria-labelledby="EditClassForm"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 className="modal-title" id="EditClassForm"> Edit Class Info </h4> </div> {/* end modal-header */} <div className="modal-body"> <form ref="editclass" onSubmit={this.handleEditClass}> <div className="form-group"> <div className="row"> <div className="col-sm-6"> <label>Term / Semester</label> <select className="form-control" ref="semester" required="required" defaultValue={this.props.classinfo.semester}> <option value="" disabled>SELECT ONE</option> <option value="fall">FALL</option> <option value="winter">WINTER</option> <option value="spring">SPRING</option> <option value="summer">SUMMER</option> <option value="other">OTHER</option> </select> </div> <div className="col-sm-6"> <label>Year</label> <input type="number" className="form-control" ref="year" min="2016" step="1" placeholder="2016" required="required" defaultValue={this.props.classinfo.year}/> </div> {/* */} </div> {/* end semester and year row. */} </div> {/* end form-group */} <div className="form-group"> <label>Class ID</label> <input type="text" className="form-control upcaseform" ref="classname" placeholder="Class ID" required="required" defaultValue={this.props.classinfo.name}/> </div> {/* end form-group */} <div className="form-group"> <label>Currently Active?</label> <select className="form-control" ref="isactive" required="required" defaultValue={this.props.classinfo.active}> <option value="" disabled>SELECT ONE</option> <option value="true">ACTIVE</option> <option value="false">INACTIVE</option> </select> </div> {/* end form-group */} <div className="form-group"> <label>Description</label> <textarea ref="description" className="form-control" rows="3" placeholder="Brief description of the class." defaultValue={this.props.classinfo.description}></textarea> </div> {/* end form-group */} <div className="row"> <div className="col-sm-6"> <input type="submit" className="btn btn-primary btn-lg btn-block editClass" ref="editClass" value="Update" /> </div> <div className="col-sm-6"> <input type="button" className="btn btn-default btn-lg btn-block closeModal" value="Close" data-dismiss="modal" onClick={this.handleClose}/> </div> </div> </form> </div> {/* end modal-body. */} </div> {/* end modal-content */} </div> {/* end modal-dialog */} </div> {/* end modal */} </div> ) } } });
blueprints/view/files/__root__/views/__name__View/__name__View.js
nnti3n/pc-checker-client
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
demo/client/index.js
redux-autoform/redux-autoform-material-ui
import React from 'react'; import { Router } from 'react-router' import routes from '../shared/routes/Routes'; import configureStore from '../shared/redux/store/Store'; import { Provider } from 'react-redux'; import { syncHistoryWithStore } from 'react-router-redux'; import { browserHistory } from 'react-router' import ReactDOM from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import numbro from 'numbro'; import moment from 'moment'; import { numbroLocalizer, momentLocalizer } from 'redux-autoform'; import 'babel-polyfill'; import './styles/Styles.less'; numbroLocalizer(numbro); momentLocalizer(moment); injectTapEventPlugin(); const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); ReactDOM.render( <Provider store={store}> <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}> <Router history={history} routes={routes} /> </MuiThemeProvider> </Provider>, document.getElementById('app') );
src/components/squads/squad-create.js
sunpietro/LeagueManager
import React, { Component } from 'react'; import Form from './squad-form'; import Player from './squad-player'; import DefaultLayout from '../layouts/default'; class SquadCreate extends Component { constructor(props) { super(props); this.state = { players: [] }; } updatePlayersList(player) { this.setState({ players: [...this.state.players, player] }); } renderPlayer(player) { return <Player key={player.id} data={player} onRemove={this.removePlayer.bind(this)} /> } removePlayer(event) { event.preventDefault(); console.log('removePlayer not implemented yet'); } render() { return ( <DefaultLayout subtitle="Create a new squad" isLoading={this.state.inProgress}> <Form onAddPlayer={this.updatePlayersList.bind(this)} /> <div className="squad-create__players"> {this.state.players.map(this.renderPlayer.bind(this))} </div> </DefaultLayout> ); } } export default SquadCreate;
admin/client/Signin/Signin.js
sendyhalim/keystone
/** * The actual Sign In view, with the login form */ import assign from 'object-assign'; import classnames from 'classnames'; import React from 'react'; import xhr from 'xhr'; import Alert from './components/Alert'; import Brand from './components/Brand'; import UserInfo from './components/UserInfo'; import LoginForm from './components/LoginForm'; var SigninView = React.createClass({ getInitialState () { return { email: '', password: '', isAnimating: false, isInvalid: false, invalidMessage: '', signedOut: window.location.search === '?signedout', }; }, componentDidMount () { // Focus the email field when we're mounted if (this.refs.email) { this.refs.email.select(); } }, handleInputChange (e) { // Set the new state when the input changes const newState = {}; newState[e.target.name] = e.target.value; this.setState(newState); }, handleSubmit (e) { e.preventDefault(); // If either password or mail are missing, show an error if (!this.state.email || !this.state.password) { return this.displayError('Please enter an email address and password to sign in.'); } xhr({ url: `${Keystone.adminPath}/api/session/signin`, method: 'post', json: { email: this.state.email, password: this.state.password, }, headers: assign({}, Keystone.csrf.header), }, (err, resp, body) => { if (err || body && body.error) { return body.error === 'invalid csrf' ? this.displayError('Something went wrong; please refresh your browser and try again.') : this.displayError('The email and password you entered are not valid.'); } else { // Redirect to where we came from or to the default admin path if (Keystone.redirect) { top.location.href = Keystone.redirect; } else { top.location.href = this.props.from ? this.props.from : Keystone.adminPath; } } }); }, /** * Display an error message * * @param {String} message The message you want to show */ displayError (message) { this.setState({ isAnimating: true, isInvalid: true, invalidMessage: message, }); setTimeout(this.finishAnimation, 750); }, // Finish the animation and select the email field finishAnimation () { // TODO isMounted was deprecated, find out if we need this guard if (!this.isMounted()) return; if (this.refs.email) { this.refs.email.select(); } this.setState({ isAnimating: false, }); }, render () { const boxClassname = classnames('auth-box', { 'auth-box--has-errors': this.state.isAnimating, }); return ( <div className="auth-wrapper"> <Alert isInvalid={this.state.isInvalid} signedOut={this.state.signedOut} invalidMessage={this.state.invalidMessage} /> <div className={boxClassname}> <h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1> <div className="auth-box__inner"> <Brand logo={this.props.logo} brand={this.props.brand} /> {this.props.user ? ( <UserInfo adminPath={this.props.from ? this.props.from : Keystone.adminPath} signoutPath={`${Keystone.adminPath}/signout`} userCanAccessKeystone={this.props.userCanAccessKeystone} userName={this.props.user.name} /> ) : ( <LoginForm email={this.state.email} handleInputChange={this.handleInputChange} handleSubmit={this.handleSubmit} isAnimating={this.state.isAnimating} password={this.state.password} /> )} </div> </div> <div className="auth-footer"> <span>Powered by </span> <a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a> </div> </div> ); }, }); module.exports = SigninView;
src/index.js
vanfvl/JabbaTracker
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { BrowserRouter as Router } from 'react-router-dom'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <Router> <App /> </Router> </Provider> , document.querySelector('.container'));
app/javascript/components/Stepper/Stepper.js
SumOfUs/Champaign
/* */ import React, { Component } from 'react'; import Step from './Step'; export default class Stepper extends Component { changeStep(index) { if (this.props.currentStep > index) { this.props.changeStep(index); } } renderStep(step, index) { const { currentStep } = this.props; return ( <Step key={index} index={index} label={step} active={currentStep === index} complete={currentStep > index} onClick={() => this.changeStep(index)} /> ); } render() { return ( <div className="Stepper fundraiser-bar__top"> <h2 className="Stepper__header">{this.props.title}</h2> <div className="Stepper__steps"> <hr className="Stepper__line" /> <div className="Step__wrapper"> {this.props.steps.map((step, index) => this.renderStep(step, index) )} </div> </div> </div> ); } }
src/Parser/Druid/Restoration/Modules/Traits/EternalRestoration.js
hasseboulen/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import {HOTS_AFFECTED_BY_ESSENCE_OF_GHANIR} from '../../Constants'; const ETERNAL_RESTORATION_INCREASE = 1; const EOG_BASE_DURATION = 8; /** * Eternal Restoration (Artifact Trait) * Increases the duration of Essence of G'Hanir by 1 sec */ class EternalRestoration extends Analyzer { static dependencies = { combatants: Combatants, }; rank = 0; healing = 0; lastEoGApplied = null; eogDuration = 0; on_initialized() { this.rank = this.combatants.selected.traitsBySpellId[SPELLS.ETERNAL_RESTORATION.id]; this.active = this.rank > 0; this.eogDuration = ((this.rank * ETERNAL_RESTORATION_INCREASE)+EOG_BASE_DURATION)*1000; } on_byPlayer_heal(event) { const spellId = event.ability.guid; // We are interested in the healing done on the last second of EoG if(this.lastEoGApplied != null && (this.lastEoGApplied + this.eogDuration - 1000) <= event.timestamp && this.combatants.selected.hasBuff(SPELLS.ESSENCE_OF_GHANIR.id) && HOTS_AFFECTED_BY_ESSENCE_OF_GHANIR.includes(spellId)) { if(!event.tick) { return; } this.healing += (event.amount + (event.absorbed || 0))/2; } } on_byPlayer_cast(event) { if (SPELLS.ESSENCE_OF_GHANIR.id !== event.ability.guid) { return; } this.lastEoGApplied = event.timestamp; } subStatistic() { return ( <div className="flex"> <div className="flex-main"> <SpellLink id={SPELLS.ETERNAL_RESTORATION.id}> <SpellIcon id={SPELLS.ETERNAL_RESTORATION.id} noLink /> Eternal Restoration </SpellLink> </div> <div className="flex-sub text-right"> {formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.healing))} % </div> </div> ); } } export default EternalRestoration;
front_end/app/components/common/Input.js
DaniGlass/OneStopShop
import React from 'react'; import { TextInput, View, Text } from 'react-native'; const Input = ({ label, value, onChangeText, placeholder, secureTextEntry }) => { const { inputStyle, labelStyle, containerStyle } = styles; return ( <View style={containerStyle}> <Text style={labelStyle}>{label}</Text> <TextInput secureTextEntry={secureTextEntry} placeholder={placeholder} autoCorrect={false} style={inputStyle} value={value} onChangeText={onChangeText} /> </View> ); }; const styles = { inputStyle: { color: '#000', paddingRight: 5, paddingLeft: 5, fontSize: 18, lineHeight: 23, flex: 2 }, labelStyle: { fontSize: 18, paddingLeft: 20, flex: 1 }, containerStyle: { height: 40, flex: 1, flexDirection: 'row', alignItems: 'center' } }; export { Input };
src/containers/Table.js
iX315/cards-react
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import * as tableActions from '../actions/table' import TableComponent from '../components/Table' const mapStateToProps = state => { return { table: state.currentTable } } const mapDispatchToProps = dispatch => { return { actions: bindActionCreators(tableActions, dispatch) } } export default connect( mapStateToProps, mapDispatchToProps )(TableComponent)
src/components/StatsLegend/LegendContainer.js
clhenrick/nyc-crash-mapper
import React from 'react'; export default () => ( <div className="legend-container"> <div className="legend-crash-types"> <ul> <li> <span className="type-fatality" /> <p>Fatality</p> </li> <li> <span className="type-injury" /> <p>Injury</p> </li> <li> <span className="type-no-inj-fat" /> <p>None</p> </li> </ul> </div> <div className="legend-crash-count"> {/* generated using https://github.com/susielu/d3-legend https://bl.ocks.org/clhenrick/ba0e4795ec2c273ef366a78911e1e2d7 */} <svg> <g transform="translate(20, 0)"> <g className="legendCells"> <g className="cell" transform="translate(0, 25)"> <circle className="swatch" r="12.5" style={{ r: '12.5px' }}> <title>74 or fewer crashes</title> </circle> <text className="label" transform="translate(15.5,5)">{'> 67'}</text> </g> <g className="cell" transform="translate(0, 54.33333396911621)"> <circle className="swatch" r="9.666666666666666" style={{ r: '9.66667px' }}> <title>46 or fewer crashes</title> </circle> <text className="label" transform="translate(24.5,5)">53</text> </g> <g className="cell" transform="translate(0, 78.00000095367432)"> <circle className="swatch" r="6.833333333333333" style={{ r: '6.83333px' }}> <title>32 or fewer crashes</title> </circle> <text className="label" transform="translate(24.5,5)">32</text> </g> <g className="cell" transform="translate(0, 96.00000095367432)"> <circle className="swatch" r="4" style={{ r: '4px' }}> <title>11 or fewer crashes</title> </circle> <text className="label" transform="translate(13.5,5)">{'<=11'}</text> </g> </g> </g> </svg> </div> </div> );
packages/icons/src/md/device/GpsOff.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdGpsOff(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M41.88 22C40.96 13.66 34.34 7.04 26 6.12V2h-4v4.12c-2.26.25-4.38.93-6.31 1.94l3 3C20.33 10.38 22.12 10 24 10c7.73 0 14 6.27 14 14 0 1.88-.38 3.67-1.05 5.31l3 3c1.01-1.93 1.68-4.05 1.93-6.31H46v-4h-4.12zM6 8.55L8.55 6 42 39.46 39.45 42l-4.07-4.08c-2.62 2.14-5.84 3.57-9.38 3.96V46h-4v-4.12C13.66 40.96 7.04 34.34 6.12 26H2v-4h4.12c.39-3.54 1.81-6.76 3.95-9.38L6 8.55zm26.53 26.53L12.92 15.47A13.916 13.916 0 0 0 10 24c0 7.73 6.27 14 14 14 3.22 0 6.17-1.1 8.53-2.92z" /> </IconBase> ); } export default MdGpsOff;
src/components/drupal/plain-wordmark/DrupalPlainWordmark.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './DrupalPlainWordmark.svg' /** DrupalPlainWordmark */ function DrupalPlainWordmark({ width, height, className }) { return ( <SVGDeviconInline className={'DrupalPlainWordmark' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } DrupalPlainWordmark.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default DrupalPlainWordmark
src/native/main.js
TheoMer/Gyms-Of-The-World
// @flow import type { Action } from '../common/types'; import FBSDK from 'react-native-fbsdk'; import React from 'react'; import ReactNativeI18n from 'react-native-i18n'; import Root from './app/Root'; import configureStorage from '../common/configureStorage'; import configureStore from '../common/configureStore'; import initialState from './initialState'; import uuid from 'react-native-uuid'; import { AppRegistry, AsyncStorage } from 'react-native'; import { persistStore } from 'redux-persist'; const getDefaultDeviceLocale = () => { const { defaultLocale, locales } = initialState.intl; const deviceLocale = ReactNativeI18n.locale.split('-')[0]; const isSupported = locales.indexOf(deviceLocale) !== -1; return isSupported ? deviceLocale : defaultLocale; }; const createNativeInitialState = () => ({ ...initialState, device: { ...initialState.device, }, intl: { ...initialState.intl, currentLocale: getDefaultDeviceLocale(), }, }); const store = configureStore({ initialState: createNativeInitialState(), platformDeps: { FBSDK, uuid }, }); const Este = () => <Root store={store} />; persistStore( store, { ...configureStorage(initialState.config.appName), storage: AsyncStorage, }, () => { // Don't import appStarted action creator since it would break hot reload. store.dispatch(({ type: 'APP_STARTED' }: Action)); }, ); AppRegistry.registerComponent('Este', () => Este);
Inspector/js/screen.js
ymin/WebDriverAgent
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import PropTypes from 'prop-types'; import React from 'react'; import HTTP from 'js/http'; import GestureRecognizer from 'js/gesture_recognizer'; var Button = require('react-button'); require('css/screen.css'); const HOMESCREEN = 'wda/homescreen'; const SWIPE = 'wda/dragfromtoforduration' const STATUS = 'status'; const ORIENTATION_ENDPOINT = 'orientation'; const SCREENSHOT_ENDPOINT = 'screenshot'; class Screen extends React.Component { constructor(props) { super(props) this.state = { sessionId: {}, windowSize: {}, osInfo: {}, unlockCode: '0000', }; } componentDidMount() { this.statusCheck(); var sleep = new Promise((resolve, reject) => { setTimeout(resolve, 2000, "one"); }); Promise.all([sleep]).then(values => { this.getScreenWindowSize(); }); } statusCheck() { HTTP.fget(STATUS, (data) => { console.log('sessionId', data.sessionId); this.setState({ sessionId: data.sessionId, osInfo: data.value.os, }); this.getScreenWindowSize(); }) } getScreenWindowSize() { var window_size_path = 'session/' + this.state.sessionId + '/window/size'; HTTP.fget(window_size_path, (data) => { console.log('window_size', data.value); if (data.value == "Session does not exist") { console.log('Session does not exist, refetch session') // this.setState({ // sessionId: data.sessionId // }) this.statusCheck(); } else { console.log('Got window size') this.setState({ windowSize: data.value }) } }); } homeSrc() { return "image/home_button.png" } homeButtonStyle() { return { width: 60, height: 60, }; } homeClick(i) { console.log('i', i); HTTP.post(HOMESCREEN, (data) => { console.log(data); }); this.screenRefresh(); } unlockSwipe(i) { console.log('unlockswipe', i); var screen_size = this.state.windowSize; if (parseInt(this.state.osInfo.version.replace(/\./gi, '')) >= 1000) { this.homeClick(); var sleep_fetchScreenshot = new Promise((resolve, reject) => { setTimeout(resolve, 1000, "one"); }); Promise.all([sleep_fetchScreenshot]).then(values => { this.homeClick(); }); } else { this.homeClick(); var x = screen_size.width; var y = screen_size.height; var swipe_path = 'session/' + this.state.sessionId + SWIPE; console.log(JSON.stringify({ fromX: 0.22 * x, toX: 0.86 * x, fromY: 0.86 * y, toY: 0.86 * y, duration: 0 })); HTTP.fpost(swipe_path, JSON.stringify({ fromX: 50, toX: 0.8 * x, fromY: 0.9 * y, toY: 0.9 * y, duration: 0 }), (data) => { console.log(data); }); } this.screenRefresh(); var sleep_fetchScreenshot = new Promise((resolve, reject) => { setTimeout(resolve, 3000, "one"); }); Promise.all([sleep_fetchScreenshot]).then(values => { this.unlockWithPasscode(); }); } unlockWithPasscode() { var passcode = this.state.unlockCode; var find_element_path = 'session/' + this.state.sessionId + '/element'; for (var i = 0; i < passcode.length; i++) { console.log('passcode', passcode[i]); HTTP.fpost(find_element_path, JSON.stringify({ using: 'link text', value: 'label=' + passcode[i] }), (data) => { console.log(data); var elementId = data.value.ELEMENT; var click_element_path = find_element_path + '/' + elementId + '/click'; HTTP.fpost(click_element_path, (data) => { console.log(data); }); }); } var sleep_fetchScreenshot = new Promise((resolve, reject) => { setTimeout(resolve, 5000, "one"); }); Promise.all([sleep_fetchScreenshot]).then(values => { this.screenRefresh(); }); } refreshAll() { if (this.props.onFetchedChange != false) { this.props.onFetchedChange(false); } } screenRefresh() { var sleep_fetchScreenshot = new Promise((resolve, reject) => { setTimeout(resolve, 2000, "one"); }); Promise.all([sleep_fetchScreenshot]).then(values => { this.props.screenRefresh(); }); } updateScreenshotScaleValue(e) { this.props.changeScreenshotScale(e); } updateUnlockCode(e) { this.setState({ unlockCode: e.currentTarget.value, }) } render() { return ( <div id="screen" className="section first"> <div className="section-caption"> Screen </div> <div> <Button onClick={(ev) => {this.home(ev); }} > Home </Button> <Button onClick={this.props.refreshApp} > Refresh </Button> </div> <div className="section-content-container"> <div className="screen-screenshot-container" style={this.styleWithScreenSize()}> {this.renderScreenshot()} {this.renderHighlightedNode()} </div> </div> <div className="section-button"> <div onClick={this.homeClick.bind(this)}> <img className="home-button" src={this.homeSrc()} style={this.homeButtonStyle()}/> </div> <div> Screenshot scale: <input className="screen-scale" placeholder="90" value={this.state.screenshotScaleValue} onChange={this.updateScreenshotScaleValue.bind(this)}/> % </div> <button className="screen-refresh-button" onClick={this.screenRefresh.bind(this)}> Refresh </button> <div> Passcode: <input className="unlock-code" placeholder="0000" value={this.state.unlockCode} onChange={this.updateUnlockCode.bind(this)}/> <button className="unlock-swipe-button" onClick={this.unlockSwipe.bind(this)}> Unlock Swipe </button> </div> </div> </div> ); } gestureRecognizer() { if (!this._gestureRecognizer) { this._gestureRecognizer = new GestureRecognizer({ onClick: (ev) => { this.onScreenShotClick(ev); }, onDrag: (params) => { this.onScreenShotDrag(params); }, }); } return this._gestureRecognizer; } styleWithScreenSize() { var screenshot = this.screenshot(); return { width: screenshot.width * screenshot.scale, height: screenshot.height * screenshot.scale, }; } screenshot() { return this.props.screenshot ? this.props.screenshot : {}; } screenClick(i) { var screenshot = this.styleWithScreenSize(); var screen_size = this.state.windowSize; console.log('screen_size', screen_size); console.log(i.nativeEvent.offsetX); console.log(i.nativeEvent.offsetY); console.log(screenshot); var realX = i.nativeEvent.offsetX / screenshot.width * screen_size.width; var realY = i.nativeEvent.offsetY / screenshot.height * screen_size.height; console.log(realX); console.log(realY); var tap_on_path = 'session/' + this.state.sessionId + '/wda/tap/nil'; HTTP.fpost(tap_on_path, JSON.stringify({ x: realX, y: realY }), (data) => { console.log(data); }); console.log('props', this.props); this.screenRefresh(); } onScreenShotDrag(params) { var fromX = params.origin.x - document.getElementById('screenshot').offsetLeft; var fromY = params.origin.y - document.getElementById('screenshot').offsetTop; var toX = params.end.x - document.getElementById('screenshot').offsetLeft; var toY = params.end.y - document.getElementById('screenshot').offsetTop; fromX = this.scaleCoord(fromX); fromY = this.scaleCoord(fromY); toX = this.scaleCoord(toX); toY = this.scaleCoord(toY); HTTP.get( 'status', (status_result) => { var session_id = status_result.sessionId; HTTP.post( 'session/' + session_id + '/wda/element/0/dragfromtoforduration', JSON.stringify({ 'fromX': fromX, 'fromY': fromY, 'toX': toX, 'toY': toY, 'duration': params.duration, }), (tap_result) => { this.props.refreshApp(); }, ); }, ); } scaleCoord(coord) { var screenshot = this.screenshot(); var pxPtScale = screenshot.width / this.props.rootNode.rect.size.width; return coord / screenshot.scale / pxPtScale; } onMouseDown(ev) { this.gestureRecognizer().onMouseDown(ev); } onMouseMove(ev) { this.gestureRecognizer().onMouseMove(ev); } onMouseUp(ev) { this.gestureRecognizer().onMouseUp(ev); } home(ev) { HTTP.post( '/wda/homescreen', JSON.stringify({}), (result) => { this.props.refreshApp(); }, ); } renderScreenshot() { return ( <img className = "screen-screenshot" src = { this.screenshot().source } style = { this.styleWithScreenSize() } onMouseDown = { (ev) => this.onMouseDown(ev) } onMouseMove = { (ev) => this.onMouseMove(ev) } onMouseUp = { (ev) => this.onMouseUp(ev) } draggable = "false" id = "screenshot" /> ); } renderHighlightedNode() { if (this.props.highlightedNode == null) { return null; } const rect = this.props.highlightedNode.rect; return ( < div className = "screen-highlighted-node" style = { this.styleForHighlightedNodeWithRect(rect) } /> ); } styleForHighlightedNodeWithRect(rect) { var screenshot = this.screenshot(); const elementsMargins = 4; const topOffset = screenshot.height; var scale = screenshot.scale; // Rect attribute use pt, but screenshot use px. // So caculate its px/pt scale automatically. var pxPtScale = screenshot.width / this.props.rootNode.rect.size.width; // hide nodes with rect out of bound if (rect.origin.x < 0 || rect.origin.x * pxPtScale >= screenshot.width || rect.origin.y < 0 || rect.origin.y * pxPtScale >= screenshot.height) { return {}; } return { left: rect.origin.x * scale * pxPtScale, top: rect.origin.y * scale * pxPtScale - topOffset * scale - elementsMargins, width: rect.size.width * scale * pxPtScale, height: rect.size.height * scale * pxPtScale, }; } } Screen.propTypes = { highlightedNode: React.PropTypes.object, screenshot: React.PropTypes.object, screenshotScaleValue: React.PropTypes.object, }; module.exports = Screen;
src/components/subjects/BookSubjectForm.js
great-design-and-systems/cataloguing-app
import { LABEL_THESAURUS, LABEL_TYPE_OF_HEADING } from '../../labels/'; import { getAllSecondIndicatorTopicalTermsForDropDown, getAllSubjectsForDropDown, getFirstIndicatorSelector, getSubjectHeadingsForDropdown } from '../../selectors/subjectSelectors'; import PropTypes from 'prop-types'; import React from 'react'; import { Selector, HiddenButton } from '../common/'; import { Subject } from '../../api/subjects'; import { SubjectFieldFormControls } from './form/SubjectFieldFormControls'; export const BookSubjectForm = ({ subjects, onChange, subjectFields, subjectHeadings, managedSubject, onSubmit }) => { return (<form className="form container-fluid" onSubmit={onSubmit}> <HiddenButton/> <Selector required={true} onChange={onChange} name={Subject.TYPE_OF_HEADINGS} label={LABEL_TYPE_OF_HEADING} value={managedSubject[Subject.TYPE_OF_HEADINGS]} options={getSubjectHeadingsForDropdown(subjectHeadings)}/> {managedSubject[Subject.TYPE_OF_HEADINGS] && <Selector required={true} value={managedSubject.data[Subject.FIRST_INDICATOR]} onChange={onChange} name={Subject.FIRST_INDICATOR} {...getFirstIndicatorSelector(managedSubject[Subject.TYPE_OF_HEADINGS])} />} <Selector required={true} value={managedSubject.data[Subject.SECOND_INDICATOR]} onChange={onChange} options={getAllSecondIndicatorTopicalTermsForDropDown()} label={LABEL_THESAURUS} name={Subject.SECOND_INDICATOR}/> {managedSubject[Subject.TYPE_OF_HEADINGS] && <SubjectFieldFormControls subjectCode={managedSubject[Subject.TYPE_OF_HEADINGS]} subjectOptions={getAllSubjectsForDropDown(subjects)} subjectField={subjectFields[managedSubject[Subject.TYPE_OF_HEADINGS]]} typeOfHeading={managedSubject[Subject.TYPE_OF_HEADINGS]} data={managedSubject.data} onChange={onChange}/>} </form>); }; BookSubjectForm.propTypes = { onChange: PropTypes.func.isRequired, subjectHeadings: PropTypes.array.isRequired, subjectFields: PropTypes.object.isRequired, managedSubject: PropTypes.object.isRequired, subjects: PropTypes.array.isRequired, onSubmit: PropTypes.func.isRequired };
app/js/display/App.js
peterugh/react-from-angular
import Globals from 'Globals'; import React from 'react'; class App extends React.Component { constructor(props) { super(props); } render() { return ( <div className='App'> <img src='/images/react.png'/> <p>React from Angular Boilerplate Success</p> </div> ); } } export default App;
docs/src/PropTable.js
HPate-Riptide/react-bootstrap
import merge from 'lodash/merge'; import React from 'react'; import Glyphicon from '../../src/Glyphicon'; import Label from '../../src/Label'; import Table from '../../src/Table'; import capitalize from '../../src/utils/capitalize'; function cleanDocletValue(str) { return str.trim().replace(/^\{/, '').replace(/\}$/, ''); } function getPropsData(component, metadata) { let componentData = metadata[component] || {}; let props = componentData.props || {}; if (componentData.composes) { componentData.composes.forEach(other => { if (other !== component) { props = merge({}, getPropsData(other, metadata), props); } }); } if (componentData.mixins) { componentData.mixins.forEach( other => { if (other !== component && componentData.composes.indexOf(other) === -1) { props = merge({}, getPropsData(other, metadata), props); } }); } return props; } const PropTable = React.createClass({ contextTypes: { metadata: React.PropTypes.object }, componentWillMount() { this.propsData = getPropsData(this.props.component, this.context.metadata); }, render() { let propsData = this.propsData; if (!Object.keys(propsData).length) { return <div className="text-muted"><em>There are no public props for this component.</em></div>; } return ( <Table bordered striped className="prop-table"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> { this._renderRows(propsData) } </tbody> </Table> ); }, _renderRows(propsData) { return Object.keys(propsData) .sort() .filter(propName => propsData[propName].type && !propsData[propName].doclets.private ) .map(propName => { let propData = propsData[propName]; return ( <tr key={propName} className="prop-table-row"> <td> {propName} {this.renderRequiredLabel(propData)} </td> <td> <div>{this.getType(propData)}</div> </td> <td>{propData.defaultValue}</td> <td> { propData.doclets.deprecated && <div className="prop-desc-heading"> <strong className="text-danger">{'Deprecated: ' + propData.doclets.deprecated + ' '}</strong> </div> } { this.renderControllableNote(propData, propName) } <div className="prop-desc" dangerouslySetInnerHTML={{__html: propData.descHtml }} /> </td> </tr> ); }); }, renderRequiredLabel(prop) { if (!prop.required) { return null; } return ( <Label>required</Label> ); }, renderControllableNote(prop, propName) { let controllable = prop.doclets.controllable; let isHandler = this.getDisplayTypeName(prop.type.name) === 'function'; if (!controllable) { return false; } let text = isHandler ? ( <span> controls <code>{controllable}</code> </span> ) : ( <span> controlled by: <code>{controllable}</code>, initial prop: <code>{'default' + capitalize(propName)}</code> </span> ); return ( <div className="prop-desc-heading"> <small> <em className="text-info"> <Glyphicon glyph="info-sign"/> &nbsp;{ text } </em> </small> </div> ); }, getType(prop) { let type = prop.type || {}; let name = this.getDisplayTypeName(type.name); let doclets = prop.doclets || {}; switch (name) { case 'object': return name; case 'union': return type.value.reduce((current, val, i, list) => { let item = this.getType({ type: val }); if (React.isValidElement(item)) { item = React.cloneElement(item, {key: i}); } current = current.concat(item); return i === (list.length - 1) ? current : current.concat(' | '); }, []); case 'array': let child = this.getType({ type: type.value }); return <span>{'array<'}{child}{'>'}</span>; case 'enum': return this.renderEnum(type); case 'custom': return cleanDocletValue(doclets.type || name); default: return name; } }, getDisplayTypeName(typeName) { if (typeName === 'func') { return 'function'; } else if (typeName === 'bool') { return 'boolean'; } return typeName; }, renderEnum(enumType) { const enumValues = enumType.value || []; const renderedEnumValues = []; enumValues.forEach(function renderEnumValue(enumValue, i) { if (i > 0) { renderedEnumValues.push( <span key={`${i}c`}>, </span> ); } renderedEnumValues.push( <code key={i}>{enumValue}</code> ); }); return ( <span>one of: {renderedEnumValues}</span> ); } }); export default PropTable;
libs/transition/index.js
CrazyFork/element-react
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import requestAnimationFrame from 'raf'; export default class Transition extends Component { constructor(props) { super(props); const { children } = props; this.state = { children: children && this.enhanceChildren(children) } this.didEnter = this.didEnter.bind(this); this.didLeave = this.didLeave.bind(this); } componentWillReceiveProps(nextProps) { const children = React.isValidElement(this.props.children) && React.Children.only(this.props.children); const nextChildren = React.isValidElement(nextProps.children) && React.Children.only(nextProps.children); if (!nextProps.name) { this.setState({ children: nextChildren }); return; } if (this.isViewComponent(nextChildren)) { this.setState({ children: this.enhanceChildren(nextChildren, { show: children ? children.props.show : true }) }) } else { if (nextChildren) { this.setState({ children: this.enhanceChildren(nextChildren) }) } } } componentDidUpdate(preProps) { if (!this.props.name) return; const children = React.isValidElement(this.props.children) && React.Children.only(this.props.children); const preChildren = React.isValidElement(preProps.children) && React.Children.only(preProps.children); if (this.isViewComponent(children)) { if ((!preChildren || !preChildren.props.show) && children.props.show) { this.toggleVisible(); } else if (preChildren && preChildren.props.show && !children.props.show) { this.toggleHidden(); } } else { if (!preChildren && children) { this.toggleVisible(); } else if (preChildren && !children) { this.toggleHidden(); } } } enhanceChildren(children, props) { return React.cloneElement(children, Object.assign({ ref: (el) => { this.el = el } }, props)) } get transitionClass() { const { name } = this.props; return { enter: `${name}-enter`, enterActive: `${name}-enter-active`, enterTo: `${name}-enter-to`, leave: `${name}-leave`, leaveActive: `${name}-leave-active`, leaveTo: `${name}-leave-to`, } } isViewComponent(element) { return element && element.type._typeName === 'View'; } /* css animation fix when animation applyied to .{action} instanceof .{action}-active */ animateElement(element, action, active, fn) { element.classList.add(active); const styles = getComputedStyle(element); const duration = parseFloat(styles['animationDuration']) || parseFloat(styles['transitionDuration']); element.classList.add(action); if (duration === 0) { const styles = getComputedStyle(element); const duration = parseFloat(styles['animationDuration']) || parseFloat(styles['transitionDuration']); clearTimeout(this.timeout); this.timeout = setTimeout(() => { fn(); }, duration * 1000) } element.classList.remove(action, active); } didEnter(e) { const childDOM = ReactDOM.findDOMNode(this.el); if (!e || e.target !== childDOM) return; const { onAfterEnter } = this.props; const { enterActive, enterTo } = this.transitionClass; childDOM.classList.remove(enterActive, enterTo); childDOM.removeEventListener('transitionend', this.didEnter); childDOM.removeEventListener('animationend', this.didEnter); onAfterEnter && onAfterEnter(); } didLeave(e) { const childDOM = ReactDOM.findDOMNode(this.el); if (!e || e.target !== childDOM) return; const { onAfterLeave, children } = this.props; const { leaveActive, leaveTo } = this.transitionClass; new Promise((resolve) => { if (this.isViewComponent(children)) { childDOM.removeEventListener('transitionend', this.didLeave); childDOM.removeEventListener('animationend', this.didLeave); requestAnimationFrame(() => { childDOM.style.display = 'none'; childDOM.classList.remove(leaveActive, leaveTo); requestAnimationFrame(resolve); }) } else { this.setState({ children: null }, resolve); } }).then(() => { onAfterLeave && onAfterLeave() }) } toggleVisible() { const { onEnter } = this.props; const { enter, enterActive, enterTo, leaveActive, leaveTo } = this.transitionClass; const childDOM = ReactDOM.findDOMNode(this.el); childDOM.addEventListener('transitionend', this.didEnter); childDOM.addEventListener('animationend', this.didEnter); // this.animateElement(childDOM, enter, enterActive, this.didEnter); requestAnimationFrame(() => { // when hidden transition not end if (childDOM.classList.contains(leaveActive)) { childDOM.classList.remove(leaveActive, leaveTo); childDOM.removeEventListener('transitionend', this.didLeave); childDOM.removeEventListener('animationend', this.didLeave); } childDOM.style.display = ''; childDOM.classList.add(enter, enterActive); onEnter && onEnter(); requestAnimationFrame(() => { childDOM.classList.remove(enter); childDOM.classList.add(enterTo); }) }) } toggleHidden() { const { onLeave } = this.props; const { leave, leaveActive, leaveTo, enterActive, enterTo } = this.transitionClass; const childDOM = ReactDOM.findDOMNode(this.el); childDOM.addEventListener('transitionend', this.didLeave); childDOM.addEventListener('animationend', this.didLeave); // this.animateElement(childDOM, leave, leaveActive, this.didLeave); requestAnimationFrame(() => { // when enter transition not end if (childDOM.classList.contains(enterActive)) { childDOM.classList.remove(enterActive, enterTo); childDOM.removeEventListener('transitionend', this.didEnter); childDOM.removeEventListener('animationend', this.didEnter); } childDOM.classList.add(leave, leaveActive); onLeave && onLeave(); requestAnimationFrame(() => { childDOM.classList.remove(leave); childDOM.classList.add(leaveTo); }) }) } render() { return this.state.children || null; } } Transition.propTypes = { name: PropTypes.string, onEnter: PropTypes.func, // triggered when enter transition start onAfterEnter: PropTypes.func, // triggered when enter transition end onLeave: PropTypes.func, // triggered when leave transition start onAfterLeave: PropTypes.func // tiggered when leave transition end };
src/CollapseButton/CollapseButton.js
AbhiPrasad/vizi
import React from 'react'; import { Button } from 'reactstrap'; import './CollapseButton.css'; const CollapseButton = ({ children, onClick, isLoading }) => { if (isLoading) { return ( <Button type="button" onClick={onClick} className="btn-go" disabled > {children} </Button> ); } else { return ( <Button type="button" onClick={onClick} className="btn-go" > {children} </Button> ); } } export default CollapseButton;
src/js/components/List.js
odedre/grommet-final
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import SpinningIcon from './icons/Spinning'; import InfiniteScroll from '../utils/InfiniteScroll'; import Selection from '../utils/Selection'; import CSSClassnames from '../utils/CSSClassnames'; import KeyboardAccelerators from '../utils/KeyboardAccelerators'; import Intl from '../utils/Intl'; import { announce } from '../utils/Announcer'; const CLASS_ROOT = CSSClassnames.LIST; const LIST_ITEM = CSSClassnames.LIST_ITEM; const SELECTED_CLASS = `${CLASS_ROOT}-item--selected`; const ACTIVE_CLASS = `${CLASS_ROOT}-item--active`; /** * @description A list of items. The preferred method of populating items in the List is to use ListItem children. * * @example * import List from 'grommet/components/List'; * import ListItem from 'grommet/components/ListItem'; * * <List> * <ListItem justify='between' * separator='horizontal'> * <span> * Alan * </span> * <span className='secondary'> * happy * </span> * </ListItem> * <ListItem justify='between'> * <span> * Chris * </span> * <span className='secondary'> * cool * </span> * </ListItem> * <ListItem justify='between'> * <span> * Eric * </span> * <span className='secondary'> * odd * </span> * </ListItem> * </List> * */ export default class List extends Component { constructor(props, context) { super(props, context); this._onClick = this._onClick.bind(this); this._fireClick = this._fireClick.bind(this); this._announceItem = this._announceItem.bind(this); this._onPreviousItem = this._onPreviousItem.bind(this); this._onNextItem = this._onNextItem.bind(this); this._onEnter = this._onEnter.bind(this); this.state = { activeItem: undefined, mouseActive: false, selected: Selection.normalizeIndexes(props.selected) }; } componentDidMount () { const { onMore, selectable } = this.props; this._setSelection(); if (onMore) { this._scroll = InfiniteScroll.startListeningForScroll( this.moreRef, onMore ); } if (selectable) { // only listen for navigation keys if the list row can be selected this._keyboardHandlers = { left: this._onPreviousItem, up: this._onPreviousItem, right: this._onNextItem, down: this._onNextItem, enter: this._onEnter, space: this._onEnter }; KeyboardAccelerators.startListeningToKeyboard( this, this._keyboardHandlers ); } } componentWillReceiveProps (nextProps) { if (this._scroll) { InfiniteScroll.stopListeningForScroll(this._scroll); this._scroll = undefined; } if (nextProps.hasOwnProperty('selected')) { this.setState({ selected: Selection.normalizeIndexes(nextProps.selected) }); } } componentDidUpdate (prevProps, prevState) { const { onMore, selectable } = this.props; const { selected } = this.state; if (JSON.stringify(selected) !== JSON.stringify(prevState.selected)) { this._setSelection(); } if (onMore && !this._scroll) { this._scroll = InfiniteScroll.startListeningForScroll(this.moreRef, onMore); } if (selectable) { // only listen for navigation keys if the list row can be selected this._keyboardHandlers = { left: this._onPreviousItem, up: this._onPreviousItem, right: this._onNextItem, down: this._onNextItem, enter: this._onEnter, space: this._onEnter }; KeyboardAccelerators.startListeningToKeyboard( this, this._keyboardHandlers ); } } componentWillUnmount () { const { selectable } = this.props; if (this._scroll) { InfiniteScroll.stopListeningForScroll(this._scroll); } if (selectable) { KeyboardAccelerators.stopListeningToKeyboard( this, this._keyboardHandlers ); } } _announceItem (label) { const { intl } = this.context; const enterSelectMessage = Intl.getMessage(intl, 'Enter Select'); announce(`${label} ${enterSelectMessage}`); } _setSelection () { if (this.listRef) { Selection.setClassFromIndexes({ containerElement: this.listRef, childSelector: `.${LIST_ITEM}`, selectedClass: SELECTED_CLASS, selectedIndexes: this.state.selected }); }; } _onPreviousItem (event) { if (this.listRef.contains(document.activeElement)) { event.preventDefault(); const { activeItem } = this.state; const rows = this.listRef.querySelectorAll('ul li'); if (rows && rows.length > 0) { if (activeItem === undefined) { rows[0].classList.add(ACTIVE_CLASS); this.setState({ activeItem: 0 }, () => { this._announceItem( rows[this.state.activeItem].innerText ); }); } else if (activeItem - 1 >= 0) { rows[activeItem].classList.remove(ACTIVE_CLASS); rows[activeItem - 1].classList.add(ACTIVE_CLASS); this.setState({ activeItem: activeItem - 1 }, () => { this._announceItem( rows[this.state.activeItem].innerText ); }); } } //stop event propagation return true; } } _onNextItem (event) { if (this.listRef.contains(document.activeElement)) { event.preventDefault(); const { activeItem } = this.state; const rows = this.listRef.querySelectorAll('ul li'); if (rows && rows.length > 0) { if (activeItem === undefined) { rows[0].classList.add(ACTIVE_CLASS); this.setState({ activeItem: 0 }, () => { this._announceItem( rows[this.state.activeItem].innerText ); }); } else if (activeItem + 1 <= rows.length - 1) { rows[activeItem].classList.remove(ACTIVE_CLASS); rows[activeItem + 1].classList.add(ACTIVE_CLASS); this.setState({ activeItem: activeItem + 1 }, () => { this._announceItem( rows[this.state.activeItem].innerText ); }); } } //stop event propagation return true; } } _fireClick (element, shiftKey) { let event; try { event = new MouseEvent('click', { 'bubbles': true, 'cancelable': true, 'shiftKey': shiftKey }); } catch (e) { // IE11 workaround. event = document.createEvent('Event'); event.initEvent('click', true, true); } // We use dispatchEvent to have the browser fill out the event fully. element.dispatchEvent(event); } _onEnter (event) { const { activeItem } = this.state; const { intl } = this.context; if (this.listRef.contains(document.activeElement) && activeItem !== undefined) { const rows = this.listRef.querySelectorAll('ul li'); this._fireClick(rows[activeItem], event.shiftKey); rows[activeItem].classList.remove(ACTIVE_CLASS); const label = rows[activeItem].innerText; const selectedMessage = Intl.getMessage(intl, 'Selected'); announce(`${label} ${selectedMessage}`); } } _onClick (event) { const { onSelect, selectable, selected } = this.props; if (!this.props.selectable) { return; } let selection = Selection.onClick(event, { containerElement: this.listRef, childSelector: `.${LIST_ITEM}`, selectedClass: SELECTED_CLASS, multiSelect: ('multiple' === selectable), priorSelectedIndexes: this.state.selected }); // only set the selected state and classes if the caller isn't managing it. if (selected === undefined) { this.setState({ selected: selection }, this._setSelection); } if (onSelect) { onSelect(selection.length === 1 ? selection[0] : selection); } } render () { const { a11yTitle, children, className, emptyIndicator, onBlur, onFocus, onMore, onMouseDown, onMouseUp, selectable, ...props } = this.props; const { activeItem, focus, mouseActive } = this.state; const { intl } = this.context; const classes = classnames( CLASS_ROOT, { [`${CLASS_ROOT}--focus`]: focus, [`${CLASS_ROOT}--selectable`]: selectable, [`${CLASS_ROOT}--moreable`]: onMore }, className ); let empty; if (emptyIndicator) { empty = ( <li className={`${CLASS_ROOT}__empty`}> {emptyIndicator} </li> ); } let more; if (onMore) { more = ( <li ref={(ref) => this.moreRef = ref} className={`${CLASS_ROOT}__more`}> <SpinningIcon /> </li> ); } let selectableProps; if (selectable) { const multiSelectMessage = selectable === 'multiple' ? `(${Intl.getMessage(intl, 'Multi Select')})` : ''; const listMessage = a11yTitle || Intl.getMessage(intl, 'List'); const navigationHelpMessage = Intl.getMessage(intl, 'Navigation Help'); selectableProps = { 'aria-label': ( `${listMessage} ${multiSelectMessage} ${navigationHelpMessage}` ), tabIndex: '0', onClick: this._onClick, onMouseDown: (event) => { this.setState({ mouseActive: true }); if (onMouseDown) { onMouseDown(event); } }, onMouseUp: (event) => { this.setState({ mouseActive: false }); if (onMouseUp) { onMouseUp(event); } }, onFocus: (event) => { if (mouseActive === false) { this.setState({ focus: true }); } if (onFocus) { onFocus(event); } }, onBlur: (event) => { if (activeItem) { const rows = this.listRef.querySelectorAll('ul li'); rows[activeItem].classList.remove(ACTIVE_CLASS); } this.setState({ focus: false, activeItem: undefined }); if (onBlur) { onBlur(event); } } }; } return ( <ul {...props} ref={(ref) => this.listRef = ref} className={classes} {...selectableProps}> {empty} {children} {more} </ul> ); } } List.contextTypes = { intl: PropTypes.object }; List.propTypes = { emptyIndicator: PropTypes.node, /** * @property {PropTypes.func} onMore - Function that will be called when more data is needed. */ onMore: PropTypes.func, /** * @property {PropTypes.func} onSelect - Function that will be called when the user selects something. When only one item is selected, it returns the zero based index for that item. When multiple items are selected, it returns an array of those item's zero based indexes. */ onSelect: PropTypes.func, /** * @property {true|false|multiple} selectable - Whether rows are selectable. multiple indicates that multiple rows may be selected */ selectable: PropTypes.oneOfType([ PropTypes.bool, PropTypes.oneOf(['multiple']) ]), /** * @property {PropTypes.number|PropTypes.number[]} selected - The currently selected item(s) using a zero based index. */ selected: PropTypes.oneOfType([ PropTypes.number, PropTypes.arrayOf(PropTypes.number) ]) }; List.defaultProps = { role: 'list' };
packages/react-scripts/fixtures/kitchensink/src/index.js
ontruck/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
app/components/magnetopause/MagnetopauseMapY.js
sheldhur/Vector
// @flow import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { NoDataAlert } from '../widgets/ChartAlert'; import LineChart from '../chart/LineChart'; import MagnetopauseMapMenu from './MagnetopauseMapMenu'; import { magnetopausePoint } from '../../lib/geopack'; import { numberIsBetween } from '../../utils/helper'; class MagnetopauseMapY extends Component { handlerContextMenu = (e) => { if (!e.ctrlKey) { e.preventDefault(); MagnetopauseMapMenu(); } }; getDotPosition = function (angle, ringRad) { const center = 0; const radians = angle * Math.PI / 180.0; return [(ringRad * Math.cos(radians) + center), (ringRad * Math.sin(radians) + center)]; }; prepareData = (values) => { if (!values) { return null; } const magnetopause = new magnetopausePoint(values); const tmp = []; const lines = []; for (let j = 0; j < 180; j += 5) { const line = { name: 'Magnetopause', si: 'Z (Re)', curve: 'BasisOpen', style: { stroke: '#ff7f0e', strokeWidth: 1, }, points: [] }; for (let i = 0; i < 360; i++) { const coordinates = this.getDotPosition(i, j); const point = magnetopause.calculate(coordinates[0], coordinates[1]).toCartesian(); if (numberIsBetween(point.x, [-10, 10])) { line.points.push({ x: point.y, y: point.z }); } tmp.push([point.x, point.y, point.z]); // line.points.push({ // x: coordinates[0], // y: coordinates[1] // }); } lines.push(line); } const chartLines = [ { si: 'Z (Re)', extent: { x: [-30, 30], y: [-30, 30] }, lines }, ]; return chartLines; }; render = () => { const { wind } = this.props; const data = this.prepareData(wind); return ( <div id="magnetopauseMap" className="magnetopause-map" onContextMenu={this.handlerContextMenu}> <LineChart width={this.props.width} height={this.props.height} data={data} tooltipDelay={100} ticks={{ x: 5, y: 5 }} showTooltip={false} showTimeCursor={false} labelY="Y (Re)" antiAliasing={this.props.antiAliasing} emptyMessage={<NoDataAlert />} /> </div> ); }; } MagnetopauseMapY.propTypes = { width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), }; MagnetopauseMapY.defaultProps = { width: '100%', height: '100%', wind: null }; export default MagnetopauseMapY;
src/svg-icons/device/battery-90.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery90 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z"/><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z"/> </SvgIcon> ); DeviceBattery90 = pure(DeviceBattery90); DeviceBattery90.displayName = 'DeviceBattery90'; DeviceBattery90.muiName = 'SvgIcon'; export default DeviceBattery90;
src/compos/AudioMessage.js
Blacktoviche/RNChat
import React, { Component } from 'react'; import { StyleSheet, View, } from 'react-native'; import { Icon, Button, Text } from 'native-base'; import * as Progress from 'react-native-progress'; import Sound from 'react-native-sound'; export default class AudioMessage extends Component { constructor(props) { super(props); this.onPlayPause = this.onPlayPause.bind(this); this.state = { sound: null, playing: false, currentTime: 0, duration: 0, progress: 0, progressTimer: null, } } componentWillMount() { this.setState({ progress: -1 }); } onPlayPause() { var progressTimer = null; if (this.state.playing === true) { var sound = this.state.sound; sound.stop(); sound.release(); this.setState({ playing: false, progress: 0 }); if (progressTimer) { clearTimeout(progressTimer); } } else { console.log('audio ', this.props.audio); var sound = new Sound(this.props.audio, '', (error) => { if (error) { console.log('failed to load the sound', error); } this.setState({ sound: sound, duration: sound.getDuration(), playing: true }); progressTimer = setInterval(() => { sound.getCurrentTime((seconds) => { currentProgress = 1 * seconds / this.state.duration; console.log('seconds ', seconds); console.log('currentProgress ', currentProgress); this.setState({ progress: currentProgress }); }); }, 50); console.log('play recorded audio'); sound.play((success) => { if (success) { this.setState({ playing: false, progress: 0 }); sound.release(); if (progressTimer) { clearTimeout(progressTimer); } } else { console.log('playback failed due to audio decoding errors'); this.setState({ playing: false, progress: 0 }); if (progressTimer) { clearTimeout(progressTimer); } } }); }); } } renderIcon() { if (this.state.playing === true) { return (<Icon name='ios-pause' />); } return (<Icon name='ios-play' />); } render() { return ( <View style={styles.containerStyle}> <Button style={{ flex: 2, alignItems: 'center', justifyContent: 'center', height: 30 }} transparent onPress={() => this.onPlayPause()}> {this.renderIcon()} </Button> <Progress.Bar progress={this.state.progress} style={styles.progressStyle} color={'black'} unfilledColor={'white'} height={7} /> </View> ); } } const styles = StyleSheet.create({ containerStyle: { width: 210, height: 30, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: 18 }, progressStyle: { flex: 10, alignItems: 'center', justifyContent: 'center', width: 140 }, container: { flex: 1 } });
frontend/src/components/task/task-interested.js
worknenjoy/gitpay
import React from 'react' import Avatar from '@material-ui/core/Avatar' import AvatarGroup from '@material-ui/lab/AvatarGroup' export default function TaskInterested ({ assigns }) { return ( <AvatarGroup max={ 4 }> { assigns && assigns.map(a => <Avatar alt={ a.User && a.User.name } src={ a.User && a.User.picture_url } />) } </AvatarGroup> ) }
src/svg-icons/social/mood.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialMood = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/> </SvgIcon> ); SocialMood = pure(SocialMood); SocialMood.displayName = 'SocialMood'; SocialMood.muiName = 'SvgIcon'; export default SocialMood;
index.web.js
johannessiig/clac
import React from 'react' import ReactDOM from 'react-dom' import Routes from './src/client/components/Routes'; import {Provider} from 'react-redux'; import Index from './src/client/components/Index/Index'; import configureStore from './src/client/configureStore'; const store = configureStore('web'); store.dispatch({type: 'SET_PLATFORM', platform: 'web'}); ReactDOM.render( <Provider store={store}> <Routes /> </Provider> , document.getElementById('app') )
app/utils/SlateEditor/HRule.js
GolosChain/tolstoy
import React from 'react' export default class HRule extends React.Component { render() { const { node, state } = this.props const isFocused = state.selection.hasEdgeIn(node) const className = isFocused ? 'active' : null return <hr className={className} /> } }
generators/js-framework/modules/react/components/Account/Profile.js
sahat/boilerplate
import React from 'react'; import { connect } from 'react-redux' import { updateProfile, changePassword, deleteAccount } from '../../actions/auth'; import { link, unlink } from '../../actions/oauth'; import Messages from '../Messages'; class Profile extends React.Component { constructor(props) { super(props); this.state = { email: props.user.email, name: props.user.name, gender: props.user.gender, location: props.user.location, website: props.user.website, gravatar: props.user.gravatar, password: '', confirm: '' }; } handleChange(event) { this.setState({ [event.target.name]: event.target.value }); } handleProfileUpdate(event) { event.preventDefault(); this.props.dispatch(updateProfile(this.state, this.props.token)); } handleChangePassword(event) { event.preventDefault(); this.props.dispatch(changePassword(this.state.password, this.state.confirm, this.props.token)); } handleDeleteAccount(event) { event.preventDefault(); this.props.dispatch(deleteAccount(this.props.token)); } handleLink(provider) { this.props.dispatch(link(provider)) } handleUnlink(provider) { this.props.dispatch(unlink(provider)); } render() { //= PROFILE_RENDER_INDENT2 } } const mapStateToProps = (state) => { return { token: state.auth.token, user: state.auth.user, messages: state.messages }; }; export default connect(mapStateToProps)(Profile);
app/components/moviespanel.js
shrihari/moviemonkey
import React from 'react' import ReactDOM from 'react-dom' import Movie from './movie.js' export default class MoviesPanel extends React.Component { constructor(props) { super(props); } render() { var t = this; var movies = this.props.data.map(function(movie) { return ( <Movie data={movie} key={movie.imdbid} onClick={t.props.onMovieSelect} /> ); }); return ( <div id="movies"> {movies} </div> ); } }
src/components/DataTable/TableSelectRow.js
carbon-design-system/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import PropTypes from 'prop-types'; import React from 'react'; import InlineCheckbox from '../InlineCheckbox'; import RadioButton from '../RadioButton'; const TableSelectRow = ({ ariaLabel, checked, id, name, onSelect, disabled, radio, className, }) => { const selectionInputProps = { id, name, onClick: onSelect, checked, disabled, }; const InlineInputComponent = radio ? RadioButton : InlineCheckbox; return ( <td className={className}> <InlineInputComponent {...selectionInputProps} {...radio && { labelText: ariaLabel, hideLabel: true, }} {...!radio && { ariaLabel }} /> </td> ); }; TableSelectRow.propTypes = { /** * Specify the aria label for the underlying input control */ ariaLabel: PropTypes.string.isRequired, /** * Specify whether all items are selected, or not */ checked: PropTypes.bool.isRequired, /** * Specify whether the control is disabled */ disabled: PropTypes.bool, /** * Provide an `id` for the underlying input control */ id: PropTypes.string.isRequired, /** * Provide a `name` for the underlying input control */ name: PropTypes.string.isRequired, /** * Provide a handler to listen to when a user initiates a selection request */ onSelect: PropTypes.func.isRequired, /** * Specify whether the control should be a radio button or inline checkbox */ radio: PropTypes.bool, /** * The CSS class names of the cell that wraps the underlying input control */ className: PropTypes.string, }; export default TableSelectRow;
src/svg-icons/action/zoom-in.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionZoomIn = (props) => ( <SvgIcon {...props}> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm2.5-4h-2v2H9v-2H7V9h2V7h1v2h2v1z"/> </SvgIcon> ); ActionZoomIn = pure(ActionZoomIn); ActionZoomIn.displayName = 'ActionZoomIn'; ActionZoomIn.muiName = 'SvgIcon'; export default ActionZoomIn;
actor-apps/app-web/src/app/components/sidebar/RecentSectionItem.react.js
alihalabyah/actor-platform
import React from 'react'; import classNames from 'classnames'; import DialogActionCreators from 'actions/DialogActionCreators'; import DialogStore from 'stores/DialogStore'; import AvatarItem from 'components/common/AvatarItem.react'; class RecentSectionItem extends React.Component { static propTypes = { dialog: React.PropTypes.object.isRequired }; constructor(props) { super(props); } onClick = () => { DialogActionCreators.selectDialogPeer(this.props.dialog.peer.peer); } render() { const dialog = this.props.dialog, selectedDialogPeer = DialogStore.getSelectedDialogPeer(); let isActive = false, title; if (selectedDialogPeer) { isActive = (dialog.peer.peer.id === selectedDialogPeer.id); } if (dialog.counter > 0) { const counter = <span className="counter">{dialog.counter}</span>; const name = <span className="col-xs title">{dialog.peer.title}</span>; title = [name, counter]; } else { title = <span className="col-xs title">{dialog.peer.title}</span>; } let recentClassName = classNames('sidebar__list__item', 'row', { 'sidebar__list__item--active': isActive, 'sidebar__list__item--unread': dialog.counter > 0 }); return ( <li className={recentClassName} onClick={this.onClick}> <AvatarItem image={dialog.peer.avatar} placeholder={dialog.peer.placeholder} size="tiny" title={dialog.peer.title}/> {title} </li> ); } } export default RecentSectionItem;
demo/index.android.js
vlad-doru/react-native-calendar-datepicker
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; class demo extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flexGrow: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('demo', () => demo);
examples/05 Customize/Drop Effects/Container.js
globexdesigns/react-dnd
import React, { Component } from 'react'; import { DragDropContext } from 'react-dnd'; import HTML5Backend from 'react-dnd-html5-backend'; import SourceBox from './SourceBox'; import TargetBox from './TargetBox'; @DragDropContext(HTML5Backend) export default class Container extends Component { render() { return ( <div style={{ overflow: 'hidden', clear: 'both', marginTop: '1.5rem' }}> <div style={{ float: 'left' }}> <SourceBox showCopyIcon /> <SourceBox /> </div> <div style={{ float: 'left' }}> <TargetBox /> </div> </div> ); } }
app/components/notes/Notes.js
zhentian-wan/ReactApp
import React from 'react'; import Router from 'react-router'; import NoteList from './Noteslist'; import AddNote from './AddNote'; class Note extends React.Component{ render(){ return ( <div> <h3>Notes for {this.props.username}</h3> <AddNote username={this.props.username} addNote={this.props.addNote}/> <NoteList notes={this.props.notes}/> </div> ) } } Note.propTypes = { username: React.PropTypes.string.isRequired, notes: React.PropTypes.array.isRequired, addNote: React.PropTypes.func.isRequired }; export default Note;
src/routes.js
lzm854676408/big-demo
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App.js'; import Home from './components/Home/Home.js'; import About from './components/About/About.js'; import Blog from './components/Blog/Blog.js'; import Post from './components/Blog/Post.js'; export default ( <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="blog" component={Blog} /> <Route path="about" component={About} /> <Route path="blog/:title" component={Post} /> </Route> )
fields/types/code/CodeField.js
lojack/keystone
import _ from 'underscore'; import CodeMirror from 'codemirror'; import Field from '../Field'; import React from 'react'; import { FormInput } from 'elemental'; /** * TODO: * - Remove dependency on underscore */ // See CodeMirror docs for API: // http://codemirror.net/doc/manual.html module.exports = Field.create({ displayName: 'CodeField', getInitialState () { return { isFocused: false }; }, componentDidMount () { if (!this.refs.codemirror) { return; } var options = _.defaults({}, this.props.editor, { lineNumbers: true, readOnly: this.shouldRenderField() ? false : true }); this.codeMirror = CodeMirror.fromTextArea(this.refs.codemirror.getDOMNode(), options); this.codeMirror.on('change', this.codemirrorValueChanged); this.codeMirror.on('focus', this.focusChanged.bind(this, true)); this.codeMirror.on('blur', this.focusChanged.bind(this, false)); this._currentCodemirrorValue = this.props.value; }, componentWillUnmount () { // todo: is there a lighter-weight way to remove the cm instance? if (this.codeMirror) { this.codeMirror.toTextArea(); } }, componentWillReceiveProps (nextProps) { if (this.codeMirror && this._currentCodemirrorValue !== nextProps.value) { this.codeMirror.setValue(nextProps.value); } }, focus () { if (this.codeMirror) { this.codeMirror.focus(); } }, focusChanged (focused) { this.setState({ isFocused: focused }); }, codemirrorValueChanged (doc, change) {//eslint-disable-line no-unused-vars var newValue = doc.getValue(); this._currentCodemirrorValue = newValue; this.props.onChange({ path: this.props.path, value: newValue }); }, renderCodemirror () { var className = 'CodeMirror-container'; if (this.state.isFocused && this.shouldRenderField()) { className += ' is-focused'; } return ( <div className={className}> <FormInput multiline ref="codemirror" name={this.props.path} value={this.props.value} onChange={this.valueChanged} autoComplete="off" /> </div> ); }, renderValue () { return this.renderCodemirror(); }, renderField () { return this.renderCodemirror(); } });
src/components/Header/Header.js
mikemunsie/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; import styles from './Header.css'; import withStyles from '../../decorators/withStyles'; import Link from '../Link'; import Navigation from '../Navigation'; @withStyles(styles) class Header extends Component { render() { return ( <div className="Header"> <div className="Header-container"> <a className="Header-brand" href="/" onClick={Link.handleClick}> <img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" /> <span className="Header-brandTxt">Your Company</span> </a> <Navigation className="Header-nav" /> <div className="Header-banner"> <h1 className="Header-bannerTitle">React</h1> <p className="Header-bannerDesc">Complex web apps made easy</p> </div> </div> </div> ); } } export default Header;
src/modules/shell/index.js
pborrego/demo-cep-base
import React from 'react'; import Helmet from 'react-helmet'; import { Route, Switch } from 'react-router-dom'; import Header from '../header'; // routing import routes from '../../routes'; // global application styles import './styles.css'; function App() { return ( <div> <Helmet titleTemplate="%s - CNN.com" defaultTitle="CNN React Starter Kit" > <meta name="description" content="A simple starter kit for building React applications." /> </Helmet> <Header /> <Switch> {routes.map((route, i) => ( <Route key={i} {...route} /> ))} </Switch> </div> ); } export default App;
nlyyAPP/component/消息中心/MLNewsList.js
a497500306/nlyy_APP
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, Navigator, ScrollView, ListView, Alert, DeviceEventEmitter, Modal } from 'react-native'; import Pickers from 'react-native-picker'; var Dimensions = require('Dimensions'); var {width, height} = Dimensions.get('window'); var List = require('../../node_modules/antd-mobile/lib/list/index'); var MLActivityIndicatorView = require('../MLActivityIndicatorView/MLActivityIndicatorView'); const Item = List.Item; const Brief = Item.Brief; var Users = require('../../entity/Users'); var researchParameter = require('../../entity/researchParameter'); var MLNavigatorBar = require('../MLNavigatorBar/MLNavigatorBar'); var MLLookNews = require('./查看消息/MLLookNews'); var MLAddNews = require('./发送消息/MLAddNews') var settings = require("../../settings"); var Popup = require('../../node_modules/antd-mobile/lib/popup/index'); var netTool = require('../../kit/net/netTool'); //网络请求 var Toast = require('../../node_modules/antd-mobile/lib/toast/index'); //时间操作 var moment = require('moment'); moment().format(); var NewsList = React.createClass({ getInitialState() { return { animating: true,//是否显示菊花 //ListView设置 dataSource: null, tableData:[], isScreen:false, zhongxin:"", suiji:"", tupian:"", bianhao:"", shuju:"", yonghuID:"", yuedu:"", biaoji:"", yemamokuai:"", userData:[], USubjIDs:[], selectUser : null, // 全部中心号 sites:[] } }, getDefaultProps(){ return { } }, componentWillUnmount(){ this.subscription.remove(); }, //更新数据 updateNews(){ if (this.state.zhongxin == "" && this.state.yonghuID == "" && this.state.suiji == "" && this.state.yuedu == "" && this.state.biaoji == ""){ this.httpData() }else{ this.clickScreenConfirm() } }, //耗时操作,网络请求 componentDidMount(){ this.subscription = DeviceEventEmitter.addListener('updateNews',this.updateNews); this.subscription = DeviceEventEmitter.addListener('updateMoKuai',this.updateNews); this.httpData() this.getUserData() //判断用户是否为全部中心权限 var isUserSiteYN = false for (var i = 0 ; i < Users.Users.length ; i++) { if (Users.Users[i].UserSiteYN == 1) { isUserSiteYN = true break } } if (isUserSiteYN == true){ this.getSite() } }, // 获取全部中心 getSite(){ netTool.post(settings.fwqUrl +"/app/getSite",{ StudyID : Users.Users[0].StudyID, }) .then((responseJson) => { var siteIDs = [] for (var i = 0 ; i < responseJson.data.length ; i++) { siteIDs.push(responseJson.data[i].SiteID) } this.setState({ sites : siteIDs }) }) .catch((error)=>{ Toast.hide() //错误 Alert.alert( '请检查您的网络111', null, [ {text: '确定'} ] ) }) }, // 搜索选项用户 getUserData(){ var UserSite = ''; for (var i = 0 ; i < Users.Users.length ; i++) { if (Users.Users[i].UserSite != null) { if (Users.Users[i].UserFun == 'H2' || Users.Users[i].UserFun == 'H3' || Users.Users[i].UserFun == 'S1' || Users.Users[i].UserFun == 'H4' || Users.Users[i].UserFun == 'H1' || Users.Users[i].UserFun == 'M8' || Users.Users[i].UserFun == 'H5'){ UserSite = Users.Users[i].UserSite } } } for (var i = 0 ; i < Users.Users.length ; i++) { if (Users.Users[i].UserFun == 'H2' || Users.Users[i].UserFun == 'H3' || Users.Users[i].UserFun == 'S1' || Users.Users[i].UserFun == 'H4' || Users.Users[i].UserFun == 'H1'){ if (Users.Users[i].UserSiteYN == 1) { UserSite = '' } } } if (this.props.isImage == 1){ for (var i = 0 ; i < Users.Users.length ; i++) { var data = Users.Users[i] if (data.UserFun == 'S1' || data.UserFun == 'H3' || data.UserFun == 'H2' || data.UserFun == 'H5' || data.UserFun == 'M7' || data.UserFun == 'M8' || data.UserFun == 'M4' || data.UserFun == 'M5' || data.UserFun == 'M1' || data.UserFun == 'C2'){ if (Users.Users[i].UserSiteYN == 1) { UserSite = '' }else{ UserSite = data.UserSite } } } } Toast.loading('请稍候',60); netTool.post(settings.fwqUrl +"/app/getImageVagueBasicsDataUser",{ str : "", SiteID : UserSite, bianhao : "按编号排序", StudyID : Users.Users[0].StudyID, zhongxin:"", suiji:"", tupian:"", shuju:"", }) .then((responseJson) => { Toast.hide() let data = [] for (var i = 0 ; i < responseJson.data.length ; i++) { data.push(responseJson.data[i].USubjID) } this.setState({ userData : responseJson.data, USubjIDs : data }) }) .catch((error)=>{ Toast.hide() //错误 Alert.alert( '请检查您的网络111', null, [ {text: '确定'} ] ) }) }, httpData(){ //发送登录网络请求 fetch(settings.fwqUrl + "/app/getNewsList", { method: 'POST', headers: { 'Accept': 'application/json; charset=utf-8', 'Content-Type': 'application/json', }, body: JSON.stringify({ StudyID : Users.Users[0].StudyID, UserMP : Users.Users[0].UserMP }) }) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); if (responseJson.isSucceed != 400){ //移除等待 this.setState({animating:false}); }else{ //ListView设置 var tableData = responseJson.data; this.state.tableData = tableData; var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); this.setState({dataSource: ds.cloneWithRows(this.state.tableData)}); //移除等待 this.setState({animating:false}); } }) .catch((error) => {//错误 //移除等待,弹出错误 this.setState({animating:false}); //错误 Alert.alert( '提示:', '请检查您的网络', [ {text: '确定'} ] ) }); }, render() { if (this.state.animating == true){ return ( <View style={styles.container}> <MLNavigatorBar title={"消息中心"} isBack={true} backFunc={() => { this.props.navigator.pop() }} leftTitle={'首页'} leftFunc={()=>{ this.props.navigator.popToRoute(this.props.navigator.getCurrentRoutes()[1]) }} newTitle={"plus-circle"} newFunc={()=>{ // 页面的切换 this.props.navigator.push({ component: MLAddNews, }); }} right2Title={"筛选"} right2Func={()=>{ this.setState({ isScreen : true }) }}/> {/*设置完了加载的菊花*/} <MLActivityIndicatorView /> </View> ); }else{ return( <View style={styles.container}> <MLNavigatorBar title={'消息中心'} isBack={true} backFunc={() => { this.props.navigator.pop() }} leftTitle={'首页'} leftFunc={()=>{ this.props.navigator.popToRoute(this.props.navigator.getCurrentRoutes()[1]) }} newTitle={"plus-circle"} newFunc={()=>{ // 页面的切换 this.props.navigator.push({ component: MLAddNews, }); }} right2Title={"筛选"} right2Func={()=>{ this.setState({ isScreen : true }) }}/> <ListView removeClippedSubviews={false} showsVerticalScrollIndicator={false} dataSource={this.state.dataSource}//数据源 renderRow={this.renderRow} /> {this.screenUI()} </View> ) } }, //返回具体的cell renderRow(rowData){ var markTypeStr = "" //标记状态,0:未解决,1:已解决,2:不需要解决,3:取消标记 if (rowData.markType == 0){ markTypeStr = "未解决" }else if (rowData.markType == 1){ markTypeStr = "已解决" }else if (rowData.markType == 2){ markTypeStr = "不需要解决" }else if (rowData.markType == 3){ markTypeStr = "" } return( <TouchableOpacity onLongPress={()=>{ //错误 this.cellOnLongPress(rowData) }} onPress={()=> { // 页面的切换 this.props.navigator.push({ component: MLLookNews, // 具体路由的版块http://codecloud.b0.upaiyun.com/wp-content/uploads/20160826_57c0288325536.png //传递参数 passProps: { //出生年月 data: rowData } }); }}> <View style={{ borderBottomColor:'#dddddd', borderBottomWidth:0.5, backgroundColor:'white', width:width }}> <View style={{ flexDirection:'row', width:width, height:32, justifyContent:'space-between' }}> <Text style={{ left:15, top:6 }}>{rowData.CRFModeule != null ? ((typeof(rowData.CRFModeule.Subjects.persons.USubjID) == "undefined" ? rowData.CRFModeule.Subjects.persons.USubjectID : rowData.CRFModeule.Subjects.persons.USubjID) + "_" + rowData.CRFModeule.CRFModeulesName + (rowData.CRFModeule.CRFModeulesNum + 1)) : rowData.addUsers.UserNam + '发送的消息'}</Text> <Text style={{ right:15, top:6, color:rowData.voiceType == 0 ? 'red' : 'gray' }}>{rowData.voiceType == 0 ? '未读' : '已读'}</Text> </View> <View style={{ flexDirection:'row', width:width, height:22, justifyContent:'space-between' }}> <Text style={{ left:15, }}>{moment(rowData.Date).format("YYYY/MM/DD H:mm:ss")}</Text> <Text style={{ right:15, // color:rowData.voiceType == 0 ? 'red' : 'gray' }}>{markTypeStr}</Text> </View> </View> </TouchableOpacity> ) }, // 长按回调 cellOnLongPress(rowData){ var array = ["请选择你想做的","已解决","不需要解决","取消标记","取消"]; Popup.show( <View> <List renderHeader={this.renderHeader} className="popup-list" > {array.map((i, index) => ( <List.Item key={index} style = {{ textAlign:'center' }} onClick={()=>{ if (index == array.length - 1 || index == 0){ Popup.hide(); return; } var url = "/app/getMarkType" Toast.loading('请稍候...',60); netTool.post(settings.fwqUrl + url,{messageIDNum : rowData.messageIDNum , markType : index}) .then((responseJson) => { Toast.hide() this.updateNews() //错误 Alert.alert( '提示:', responseJson.msg, [ {text: '确定'} ], {cancelable : false} ) }) .catch((error)=>{ Toast.hide() //错误 Alert.alert( '提示:', '请检查您的网络111', [ {text: '确定'} ] ) }) Popup.hide(); }} > <View style={{ width:width - 30, alignItems:'center', justifyContent: 'center', }}> <Text style={{ fontSize:index == 0 ? 12 : 16, color:(index == array.length - 1 ? 'red' : (index == 0 ? 'gray':'black')) }}>{i}</Text> </View> </List.Item> ))} </List> </View>, {maskClosable: true,animationType: 'slide-up' } ) }, screenUI(){ return([ <Modal visible={this.state.isScreen} transparent={true}> <View style={[styles.container,{justifyContent: 'center',backgroundColor:'rgba(0,0,0,0.5)'}]}> <View style={{backgroundColor:'white'}}> <TouchableOpacity style = {[styles.screenStayle]} onPress={()=>{this.clickScreen("zhongxin")}}> <Text style = {[styles.selectTitleStayle]}>中心:</Text> <Text style = {[styles.selectTextStayle]}>{this.state.zhongxin == "" ? "未选择" : this.state.zhongxin}</Text> </TouchableOpacity> <TouchableOpacity style = {[styles.screenStayle]} onPress={()=>{this.clickScreen("yonghuID")}}> <Text style = {[styles.selectTitleStayle]}>受试者编号:</Text> <Text style = {[styles.selectTextStayle]}>{this.state.yonghuID == "" ? "未选择" : this.state.yonghuID}</Text> </TouchableOpacity> <TouchableOpacity style = {[styles.screenStayle]} onPress={()=>{this.clickScreen("shuju")}}> <Text style = {[styles.selectTitleStayle]}>页码/模块数据行状态:</Text> <Text style = {[styles.selectTextStayle]}>{this.state.shuju == "" ? "未选择" : this.state.shuju}</Text> </TouchableOpacity> <TouchableOpacity style = {[styles.screenStayle]} onPress={()=>{this.clickScreen("yuedu")}}> <Text style = {[styles.selectTitleStayle]}>已读/未读:</Text> <Text style = {[styles.selectTextStayle]}>{this.state.yuedu == "" ? "未选择" : this.state.yuedu}</Text> </TouchableOpacity> <TouchableOpacity style = {[styles.screenStayle]} onPress={()=>{this.clickScreen("biaoji")}}> <Text style = {[styles.selectTitleStayle]}>解决的标记状态:</Text> <Text style = {[styles.selectTextStayle]}>{this.state.biaoji == "" ? "未选择" : this.state.biaoji}</Text> </TouchableOpacity> <TouchableOpacity style={[styles.dengluBtnStyle,{marginTop:20}]} onPress={()=>{this.clickScreenConfirm()}}> <Text style={{color:'white',fontSize: 14}}> 确 定 </Text> </TouchableOpacity> <TouchableOpacity style={[styles.dengluBtnStyle]} onPress={()=>{ Pickers.hide(); this.setState({ isScreen : false, zhongxin:"", suiji:"", tupian:"", bianhao:"", shuju:"", yonghuID:"", biaoji:"", yuedu:"" }) }}> <Text style={{color:'white',fontSize: 14}}> 取 消 </Text> </TouchableOpacity> </View> </View> </Modal> ]) }, //筛选条件 clickScreen(type){ var array = []; if (type == "zhongxin"){ if (this.state.sites.length != 0){ array = this.state.sites }else{ for (var i = 0 ; i < Users.Users.length ; i++) { if (Users.Users[i].UserSite != null) { if (Users.Users[i].UserSite.indexOf(',') != -1 ) { var sites = Users.Users[i].UserSite.split(","); for (var j = 0 ; j < sites.length ; j++) { array.push(sites[j]) } }else{ array.push(Users.Users[i].UserSite) } } } } //去重 array = Array.from(new Set(array)) if (array.length == 0){ Alert.alert( '提示:', '无中心可选', [ {text: '确定'} ] ) return } }else if (type == "suiji"){ array = ["筛选中","已随机","筛选失败","已完成或退出"]; }else if (type == "tupian"){ array = ["是","否"]; }else if (type == "yonghuID"){ if (this.state.USubjIDs.length == 0){ Alert.alert( '提示:', '没有受试者', [ {text: '确定'} ] ) return } array = this.state.USubjIDs; }else if (type == "shuju"){ array = ["点击上传图片","等待核查","正在核查","质疑处理中","冻结"]; }else if (type == "yuedu"){ array = ["已读","未读"]; }else if (type == "biaoji"){ array = ["未解决","已解决","不需要解决"]; }else if (type == "yemamokuai") { array = ["页码","模块"]; } Pickers.init({ pickerData: array, onPickerConfirm: pickedValue => { if (type == "zhongxin"){ this.setState({zhongxin:pickedValue[0]}) }else if (type == "suiji"){ this.setState({suiji:pickedValue[0]}) }else if (type == "tupian"){ this.setState({tupian:pickedValue[0]}) }else if (type == "yonghuID"){ this.setState({yonghuID:pickedValue[0]}) }else if (type == "shuju"){ this.setState({shuju:pickedValue[0]}) }else if (type == "yuedu"){ this.setState({yuedu:pickedValue[0]}) }else if (type == "biaoji"){ this.setState({biaoji:pickedValue[0]}) } }, onPickerCancel: pickedValue => { if (type == "zhongxin"){ this.setState({zhongxin:""}) }else if (type == "suiji"){ this.setState({suiji:""}) }else if (type == "tupian"){ this.setState({tupian:""}) }else if (type == "yonghuID"){ this.setState({yonghuID:""}) }else if (type == "shuju"){ this.setState({shuju:""}) }else if (type == "yuedu"){ this.setState({yuedu:""}) }else if (type == "biaoji"){ this.setState({biaoji:""}) } }, onPickerSelect: pickedValue => { } }); Pickers.show(); }, clickScreenConfirm(){ if (this.state.zhongxin == "" && this.state.shuju == "" && this.state.yonghuID == "" && this.state.suiji == "" && this.state.yuedu == "" && this.state.biaoji == ""){ this.httpData() Pickers.hide(); this.setState({ isScreen : false, }) return } Pickers.hide(); this.setState({ isScreen : false, }) var UserSite = ''; for (var i = 0 ; i < Users.Users.length ; i++) { if (Users.Users[i].UserSite != null) { if (Users.Users[i].UserFun == 'H2' || Users.Users[i].UserFun == 'H3' || Users.Users[i].UserFun == 'S1' || Users.Users[i].UserFun == 'H4' || Users.Users[i].UserFun == 'H1' || Users.Users[i].UserFun == 'M8' || Users.Users[i].UserFun == 'H5'){ UserSite = Users.Users[i].UserSite } } } for (var i = 0 ; i < Users.Users.length ; i++) { if (Users.Users[i].UserFun == 'H2' || Users.Users[i].UserFun == 'H3' || Users.Users[i].UserFun == 'S1' || Users.Users[i].UserFun == 'H4' || Users.Users[i].UserFun == 'H1'){ if (Users.Users[i].UserSiteYN == 1) { UserSite = '' } } } if (this.props.isImage == 1){ for (var i = 0 ; i < Users.Users.length ; i++) { var data = Users.Users[i] if (data.UserFun == 'S1' || data.UserFun == 'H3' || data.UserFun == 'H2' || data.UserFun == 'H5' || data.UserFun == 'M7' || data.UserFun == 'M8' || data.UserFun == 'M4' || data.UserFun == 'M5' || data.UserFun == 'M1' || data.UserFun == 'C2'){ if (Users.Users[i].UserSiteYN == 1) { UserSite = '' }else{ UserSite = data.UserSite } } } } Toast.loading('查询中...',60); netTool.post(settings.fwqUrl +"/app/getImageVagueBasicsDataUser",{ str : "", SiteID : UserSite, StudyID : Users.Users[0].StudyID, zhongxin : this.state.zhongxin, suiji : this.state.suiji, tupian : this.state.tupian, yonghuID : this.state.yonghuID, shuju : this.state.shuju, }) .then((responseJson) => { this.getUserNewsList(responseJson) }) .catch((error)=>{ Toast.hide() //错误 Alert.alert( '请检查您的网络111', null, [ {text: '确定'} ] ) }) }, //获取消息数据 getUserNewsList(data){ netTool.post(settings.fwqUrl +"/app/getUserNewsList",{ StudyID : Users.Users[0].StudyID, UserMP : Users.Users[0].UserMP, users : data.data, yuedu: this.state.yuedu, biaoji : this.state.biaoji }) .then((responseJson) => { Toast.hide() //ListView设置 var tableData = responseJson.data; this.state.tableData = tableData; var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2}); this.setState({dataSource: ds.cloneWithRows(this.state.tableData)}); //移除等待 this.setState({animating:false}); }) .catch((error)=>{ Toast.hide() //错误 Alert.alert( '请检查您的网络222', null, [ {text: '确定'} ] ) }) } }); const styles = StyleSheet.create({ container: { flex: 1, // justifyContent: 'center', // alignItems: 'center', backgroundColor: 'rgba(233,234,239,1.0)', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, dengluBtnStyle:{ // 设置主轴的方向 flexDirection:'row', // 垂直居中 ---> 设置侧轴的对齐方式 alignItems:'center', // 设置主轴的对齐方式 justifyContent:'center', width:width - 40, marginBottom:20, marginLeft:20, height:40, backgroundColor:'rgba(0,136,212,1.0)', // 设置圆角 borderRadius:5, }, screenStayle:{ marginLeft:20, height:40, marginRight:20, borderBottomWidth : 1, borderColor : "rgba(0,136,212,1.0)", // 设置主轴的方向 flexDirection:'row', alignItems:'center', }, selectTitleStayle:{ fontSize: 14, }, selectTextStayle:{ fontSize: 14, color: 'gray' } }); // 输出组件类 module.exports = NewsList;
source/client/components/Withdraw.js
NAlexandrov/yaw
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styled from 'react-emotion'; import axios from 'axios'; import errorHandler from './helpers/errorHandler'; import { Card, Title, Button, Island, Input } from './'; const WithdrawTitle = styled(Title)` text-align: center; `; const WithdrawLayout = styled(Island)` width: 440px; display: flex; flex-direction: column; align-items: center; `; const InputField = styled.div` margin: 20px 0; position: relative; `; const SumInput = styled(Input)` max-width: 200px; padding-right: 20px; background-color: rgba(0, 0, 0, 0.08); color: '#000'; `; const Currency = styled.span` font-size: 12px; position: absolute; right: 10; top: 8px; `; /** * Класс компонента Withdraw */ class Withdraw extends Component { /** * Конструктор * @param {Object} props свойства компонента Withdraw */ constructor(props) { super(props); this.state = { selectedCard: props.inactiveCardsList[0], sum: 0, }; } /** * Обработка изменения значения в input * @param {Event} event событие изменения значения input */ onChangeInputValue(event) { if (!event) { return; } const { name, value } = event.target; this.setState({ [name]: value, }); } /** * Отправка формы * @param {Event} event событие отправки формы */ onSubmitForm(event) { if (event) { event.preventDefault(); } const { selectedCard, sum } = this.state; const { activeCard, inactiveCardsList } = this.props; let selectedCardId = selectedCard.id; const isFound = inactiveCardsList.find((v) => v.id === selectedCard.id); if (!isFound) { this.setState({ selectedCard: inactiveCardsList[0], }); selectedCardId = inactiveCardsList[0].id; } const isNumber = !isNaN(parseFloat(sum)) && isFinite(sum); if (!isNumber || sum <= 0) { return errorHandler('Введите корректную сумму для вывода с карты'); } if (activeCard.balance < Number(sum)) { return errorHandler('У вас недостаточно средств'); } const options = { method: 'post', url: `/cards/${activeCard.id}/transfer`, data: { target: selectedCardId, sum, }, }; return axios(options) .then(() => { this.props.onTransaction(); this.setState({ sum: 0 }); }) .catch(errorHandler); } /** * Функция отрисовки компонента * @returns {JSX} */ render() { const { inactiveCardsList } = this.props; if (!inactiveCardsList.length) { return ''; } return ( <form onSubmit={(event) => this.onSubmitForm(event)}> <WithdrawLayout> <WithdrawTitle>Вывести деньги на карту</WithdrawTitle> <Card type='select' data={inactiveCardsList} /> <InputField> <SumInput textColor='#000' name='sum' type='number' min='1' required='required' step='any' value={this.state.sum} onChange={(event) => this.onChangeInputValue(event)} /> <Currency>₽</Currency> </InputField> <Button type='submit'>Перевести</Button> </WithdrawLayout> </form> ); } } Withdraw.propTypes = { activeCard: PropTypes.shape({ id: PropTypes.number, }), inactiveCardsList: PropTypes.arrayOf(PropTypes.object).isRequired, onTransaction: PropTypes.func.isRequired, }; export default Withdraw;
assets/js/Home.js
bclynch/packonmybike
import React, { Component } from 'react'; export default class Home extends Component { render() { return ( <div> Pack On My Bike Bitches </div> ) } }
src/routes/chart/lineChart/index.js
zhouchao0924/SLCOPY
import React from 'react' import PropTypes from 'prop-types' import { Row, Col, Card, Button } from 'antd' import Container from '../Container' import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, } from 'recharts' const data = [ { name: 'Page A', uv: 4000, pv: 2400, amt: 2400, }, { name: 'Page B', uv: 3000, pv: 1398, amt: 2210, }, { name: 'Page C', uv: 2000, pv: 9800, amt: 2290, }, { name: 'Page D', uv: 2780, pv: 3908, amt: 2000, }, { name: 'Page E', uv: 1890, pv: 4800, amt: 2181, }, { name: 'Page F', uv: 2390, pv: 3800, amt: 2500, }, { name: 'Page G', uv: 3490, pv: 4300, amt: 2100, }, ] const colProps = { lg: 12, md: 24, } const SimpleLineChart = () => ( <Container> <LineChart data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5, }}> <XAxis dataKey="name" /> <YAxis /> <CartesianGrid strokeDasharray="3 3" /> <Tooltip /> <Legend /> <Line type="monotone" dataKey="pv" stroke="#8884d8" activeDot={{ r: 8, }} /> <Line type="monotone" dataKey="uv" stroke="#82ca9d" /> </LineChart> </Container> ) const VerticalLineChart = () => ( <Container> <LineChart layout="vertical" width={600} height={300} data={data} margin={{ top: 20, right: 30, left: 20, bottom: 5, }}> <XAxis type="number" /> <YAxis dataKey="name" type="category" /> <CartesianGrid strokeDasharray="3 3" /> <Tooltip /> <Legend /> <Line dataKey="pv" stroke="#8884d8" /> <Line dataKey="uv" stroke="#82ca9d" /> </LineChart> </Container> ) const DashedLineChart = () => ( <Container> <LineChart width={600} height={300} data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5, }}> <XAxis dataKey="name" /> <YAxis /> <CartesianGrid strokeDasharray="3 3" /> <Tooltip /> <Legend /> <Line type="monotone" dataKey="pv" stroke="#8884d8" strokeDasharray="5 5" /> <Line type="monotone" dataKey="uv" stroke="#82ca9d" strokeDasharray="3 4 5 2" /> </LineChart> </Container> ) // CustomizedDotLineChart const CustomizedDot = ({ cx, cy, payload }) => { if (payload.value > 2500) { return ( <svg x={cx - 10} y={cy - 10} width={20} height={20} fill="red" viewBox="0 0 1024 1024"> <path d="M512 1009.984c-274.912 0-497.76-222.848-497.76-497.76s222.848-497.76 497.76-497.76c274.912 0 497.76 222.848 497.76 497.76s-222.848 497.76-497.76 497.76zM340.768 295.936c-39.488 0-71.52 32.8-71.52 73.248s32.032 73.248 71.52 73.248c39.488 0 71.52-32.8 71.52-73.248s-32.032-73.248-71.52-73.248zM686.176 296.704c-39.488 0-71.52 32.8-71.52 73.248s32.032 73.248 71.52 73.248c39.488 0 71.52-32.8 71.52-73.248s-32.032-73.248-71.52-73.248zM772.928 555.392c-18.752-8.864-40.928-0.576-49.632 18.528-40.224 88.576-120.256 143.552-208.832 143.552-85.952 0-164.864-52.64-205.952-137.376-9.184-18.912-31.648-26.592-50.08-17.28-18.464 9.408-21.216 21.472-15.936 32.64 52.8 111.424 155.232 186.784 269.76 186.784 117.984 0 217.12-70.944 269.76-186.784 8.672-19.136 9.568-31.2-9.12-40.096z" /> </svg> ) } return ( <svg x={cx - 10} y={cy - 10} width={20} height={20} fill="green" viewBox="0 0 1024 1024"> <path d="M517.12 53.248q95.232 0 179.2 36.352t145.92 98.304 98.304 145.92 36.352 179.2-36.352 179.2-98.304 145.92-145.92 98.304-179.2 36.352-179.2-36.352-145.92-98.304-98.304-145.92-36.352-179.2 36.352-179.2 98.304-145.92 145.92-98.304 179.2-36.352zM663.552 261.12q-15.36 0-28.16 6.656t-23.04 18.432-15.872 27.648-5.632 33.28q0 35.84 21.504 61.44t51.2 25.6 51.2-25.6 21.504-61.44q0-17.408-5.632-33.28t-15.872-27.648-23.04-18.432-28.16-6.656zM373.76 261.12q-29.696 0-50.688 25.088t-20.992 60.928 20.992 61.44 50.688 25.6 50.176-25.6 20.48-61.44-20.48-60.928-50.176-25.088zM520.192 602.112q-51.2 0-97.28 9.728t-82.944 27.648-62.464 41.472-35.84 51.2q-1.024 1.024-1.024 2.048-1.024 3.072-1.024 8.704t2.56 11.776 7.168 11.264 12.8 6.144q25.6-27.648 62.464-50.176 31.744-19.456 79.36-35.328t114.176-15.872q67.584 0 116.736 15.872t81.92 35.328q37.888 22.528 63.488 50.176 17.408-5.12 19.968-18.944t0.512-18.944-3.072-7.168-1.024-3.072q-26.624-55.296-100.352-88.576t-176.128-33.28z" /> </svg> ) } CustomizedDot.propTypes = { cx: PropTypes.number, cy: PropTypes.number, payload: PropTypes.object, } const CustomizedDotLineChart = () => ( <Container> <LineChart width={600} height={300} data={data} margin={{ top: 5, right: 30, left: 20, bottom: 5, }}> <XAxis dataKey="name" /> <YAxis /> <CartesianGrid strokeDasharray="3 3" /> <Tooltip /> <Legend /> <Line type="monotone" dataKey="pv" stroke="#8884d8" dot={< CustomizedDot />} /> <Line type="monotone" dataKey="uv" stroke="#82ca9d" /> </LineChart> </Container> ) const EditorPage = () => ( <div className="content-inner"> <Button type="primary" size="large" style={{ position: 'absolute', right: 0, top: -48, }}> <a href="http://recharts.org/#/en-US/examples/TinyBarChart" target="blank">Show More</a> </Button> <Row gutter={32}> <Col {...colProps}> <Card title="SimpleLineChart"> <SimpleLineChart /> </Card> </Col> <Col {...colProps}> <Card title="DashedLineChart"> <DashedLineChart /> </Card> </Col> <Col {...colProps}> <Card title="CustomizedDotLineChart"> <CustomizedDotLineChart /> </Card> </Col> <Col {...colProps}> <Card title="VerticalLineChart"> <VerticalLineChart /> </Card> </Col> </Row> </div> ) export default EditorPage
app/javascript/mastodon/features/status/components/action_bar.js
honpya/taketodon
import React from 'react'; import PropTypes from 'prop-types'; import IconButton from '../../../components/icon_button'; import ImmutablePropTypes from 'react-immutable-proptypes'; import DropdownMenuContainer from '../../../containers/dropdown_menu_container'; import { defineMessages, injectIntl } from 'react-intl'; import { me } from '../../../initial_state'; const messages = defineMessages({ delete: { id: 'status.delete', defaultMessage: 'Delete' }, mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' }, reply: { id: 'status.reply', defaultMessage: 'Reply' }, reblog: { id: 'status.reblog', defaultMessage: 'Boost' }, cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' }, favourite: { id: 'status.favourite', defaultMessage: 'Favourite' }, mute: { id: 'status.mute', defaultMessage: 'Mute @{name}' }, muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' }, unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' }, block: { id: 'status.block', defaultMessage: 'Block @{name}' }, report: { id: 'status.report', defaultMessage: 'Report @{name}' }, share: { id: 'status.share', defaultMessage: 'Share' }, pin: { id: 'status.pin', defaultMessage: 'Pin on profile' }, unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' }, embed: { id: 'status.embed', defaultMessage: 'Embed' }, }); @injectIntl export default class ActionBar extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, onReply: PropTypes.func.isRequired, onReblog: PropTypes.func.isRequired, onFavourite: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, onMute: PropTypes.func, onMuteConversation: PropTypes.func, onBlock: PropTypes.func, onReport: PropTypes.func, onPin: PropTypes.func, onEmbed: PropTypes.func, intl: PropTypes.object.isRequired, }; handleReplyClick = () => { this.props.onReply(this.props.status); } handleReblogClick = (e) => { this.props.onReblog(this.props.status, e); } handleFavouriteClick = () => { this.props.onFavourite(this.props.status); } handleDeleteClick = () => { this.props.onDelete(this.props.status); } handleMentionClick = () => { this.props.onMention(this.props.status.get('account'), this.context.router.history); } handleMuteClick = () => { this.props.onMute(this.props.status.get('account')); } handleConversationMuteClick = () => { this.props.onMuteConversation(this.props.status); } handleBlockClick = () => { this.props.onBlock(this.props.status.get('account')); } handleReport = () => { this.props.onReport(this.props.status); } handlePinClick = () => { this.props.onPin(this.props.status); } handleShare = () => { navigator.share({ text: this.props.status.get('search_index'), url: this.props.status.get('url'), }); } handleEmbed = () => { this.props.onEmbed(this.props.status); } render () { const { status, intl } = this.props; const publicStatus = ['public', 'unlisted'].includes(status.get('visibility')); const mutingConversation = status.get('muted'); let menu = []; if (publicStatus) { menu.push({ text: intl.formatMessage(messages.embed), action: this.handleEmbed }); } if (me === status.getIn(['account', 'id'])) { if (publicStatus) { menu.push({ text: intl.formatMessage(status.get('pinned') ? messages.unpin : messages.pin), action: this.handlePinClick }); } menu.push(null); menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick }); menu.push(null); menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick }); } else { menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick }); menu.push(null); menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick }); menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick }); menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport }); } const shareButton = ('share' in navigator) && status.get('visibility') === 'public' && ( <div className='detailed-status__button'><IconButton title={intl.formatMessage(messages.share)} icon='share-alt' onClick={this.handleShare} /></div> ); let reblogIcon = 'retweet'; if (status.get('visibility') === 'direct') reblogIcon = 'envelope'; else if (status.get('visibility') === 'private') reblogIcon = 'lock'; let reblog_disabled = (status.get('visibility') === 'direct' || status.get('visibility') === 'private'); return ( <div className='detailed-status__action-bar'> <div className='detailed-status__button'><IconButton title={intl.formatMessage(messages.reply)} icon={status.get('in_reply_to_id', null) === null ? 'reply' : 'reply-all'} onClick={this.handleReplyClick} /></div> <div className='detailed-status__button'><IconButton disabled={reblog_disabled} active={status.get('reblogged')} title={reblog_disabled ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} /></div> <div className='detailed-status__button'><IconButton animate active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} activeStyle={{ color: '#ca8f04' }} /></div> {shareButton} <div className='detailed-status__action-bar-dropdown'> <DropdownMenuContainer size={18} icon='ellipsis-h' items={menu} direction='left' title='More' /> </div> </div> ); } }
src/components/Map.js
samkarp/murmuration
import React from 'react'; import L from 'leaflet'; import Draw from 'leaflet-draw'; let config = {}; config.params = { center: [39.745, -104.99], zoom: 14, minZoom: 2, maxZoom: 20, zoomControl: true, attributionControl: false }; config.tileLayer = { uri: 'http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', params: {} }; export class Map extends React.Component { constructor(props) { super(props); this.state = { map: null, tileLayer: null, targetGroupLayer: null, regionGroupLayer: null, filterRegion: null, editableLayers: null }; this._mapNode = null; this.pointToLayer = this.pointToLayer.bind(this); } componentDidMount() { if (!this.state.map) this.init(this._mapNode); } componentWillUnmount() { // code to run just before unmounting the component // this destroys the Leaflet map object & related event listeners this.state.map.remove(); } init(id) { if (this.state.map) return; // this function creates the Leaflet map object and is called after the Map component mounts let map = L.map(id, config.params); // a TileLayer is used as the "basemap" const tileLayer = L.tileLayer(config.tileLayer.uri, config.tileLayer.params).addTo(map); const editableLayers = L.featureGroup(); map.addLayer(editableLayers); // L.drawLocal.draw.toolbar.buttons.polygon = 'Draw a polygon'; // L.drawLocal.draw.handlers.rectangle.tooltip.start = 'Not telling...'; var options = { position: 'topright', draw: { polyline: false, polygon: { allowIntersection: false, // Restricts shapes to simple polygons drawError: { color: '#e1e100', // Color the shape will turn when intersects message: '<strong>Nope!<strong> You can\'t intersect yourself!' // Message that will show when intersect }, shapeOptions: { color: '#bada55' } }, circle: false, // Turns off this drawing tool marker: false, rectangle: { shapeOptions: { clickable: false } } }, edit: { featureGroup: editableLayers, //REQUIRED!! remove: true } }; var drawControl = new L.Control.Draw(options); map.addControl(drawControl); var _this = this; //Add the layer and fire the layer state map.on(L.Draw.Event.CREATED, function (e) { var type = e.layerType, layer = e.layer; console.log(layer.getLatLngs()); //Clear the layers so that there is only one drawn item at a time editableLayers.clearLayers(); editableLayers.addLayer(layer); _this.setState({filterRegion: layer.getLatLngs()[0]}); }); //Remove the layers and modify the layer state map.on(L.Draw.Event.DELETED, function (e) { //Clear the layers so that there is only one drawn item at a time editableLayers.clearLayers(); _this.setState({filterRegion: null}); }); // set our state to include the tile layer this.setState({map, tileLayer}); } addRegionLayer(regionsARL) { if(regionsARL.length > 0) { //Clear the existing markers only if there already are some if (this.state.regionGroupLayer) { console.log("Clearning Regions Layers"); this.state.regionGroupLayer.clearLayers(); } var geojsonArray = []; //Add a new marker for each target for (var i = 0; i < regionsARL.length; i++) { geojsonArray.push(new L.geoJSON((regionsARL[i]._source.loc))); } const regionGroupLayer = L.featureGroup(geojsonArray); this.setState({regionGroupLayer: regionGroupLayer}); regionGroupLayer.addTo(this.state.map); } else { this.state.regionGroupLayer.clearLayers(); } } addTargetLayer(targetsATL) { //Add the markers to the map if we have any selected targets if (targetsATL.length > 0) { //Clear the existing markers only if there already are some if (this.state.targetGroupLayer) { this.state.targetGroupLayer.clearLayers(); } var markerArray = []; //Add a new marker for each target for (var i = 0; i < targetsATL.length; i++) { markerArray.push(new L.marker([targetsATL[i]._source.loc[1], targetsATL[i]._source.loc[0]])); } //Add the markers to a featureGroup const targetGroupLayer = L.featureGroup(markerArray); this.setState({targetGroupLayer: targetGroupLayer}); //Add the group to the map targetGroupLayer.addTo(this.state.map); //Zoom to the group this.zoomToFeature(targetGroupLayer); } else { //If the current marker array is empty this.state.targetGroupLayer.clearLayers(); } } zoomToFeature(target) { // pad fitBounds() so features aren't hidden under the Filter UI element var fitBoundsParams = { paddingTopLeft: [200, 10], paddingBottomRight: [10, 10], maxZoom: 14 }; // set the map's center & zoom so that it fits the geographic extent of the layer this.state.map.fitBounds(target.getBounds(), fitBoundsParams); } // handleMapPolygonFilter(obj){ // // } handleMapPolygonFilter(item) { this.props.onClick(item); } pointToLayer(feature, latlng) { // renders our GeoJSON points as circle markers, rather than Leaflet's default image markers // parameters to style the GeoJSON markers var markerParams = { radius: 4, fillColor: 'orange', color: '#fff', weight: 1, opacity: 0.5, fillOpacity: 0.8 }; return L.circleMarker(latlng, markerParams); } componentDidUpdate(prevProps, prevState) { // code to run when the component receives new props or state // check to see if geojson is stored, map is created, and geojson overlay needs to be added console.log("Updating with updated items:"+new Date()); // if(Object.keys(this.state.editableLayers._layers).length > 0) { if(prevState.filterRegion != this.state.filterRegion) { this.handleMapPolygonFilter(this.state.filterRegion); } function isTarget(entry) { return entry._type == "target" } function isRegion(entry) { return entry._type == "region" } var prevTgtArray = prevProps.items.filter(isTarget); var prevRgnArray = prevProps.items.filter(isRegion); var targetArray = this.props.items.filter(isTarget); var regionArray = this.props.items.filter(isRegion); // if (this.state.map && !this.state.targetGroupLayer ) { if (prevTgtArray.length !== targetArray.length) { this.addTargetLayer(targetArray); } if (prevRgnArray.length !== regionArray.length) { this.addRegionLayer(regionArray); } } render() { return ( <div ref={(node) => this._mapNode = node } id='map' style={this.props.size}>Loading Map...</div> ) } } export default Map
frontend/src/components/dialog/sysadmin-dialog/sysadmin-add-repo-dialog.js
miurahr/seahub
import React from 'react'; import PropTypes from 'prop-types'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter, Input, Form, FormGroup, Label } from 'reactstrap'; import { gettext } from '../../../utils/constants'; import { seafileAPI } from '../../../utils/seafile-api'; import { Utils } from '../../../utils/utils'; const propTypes = { toggle: PropTypes.func.isRequired, groupID: PropTypes.string.isRequired, onRepoChanged: PropTypes.func.isRequired, }; class AddRepoDialog extends React.Component { constructor(props) { super(props); this.state = { repoName: '', errMessage: '', }; this.newInput = React.createRef(); } componentDidMount() { this.newInput.focus(); this.newInput.setSelectionRange(0, 0); } handleSubmit = () => { let isValid = this.validateName(); if (isValid) { seafileAPI.sysAdminAddRepoInDepartment(this.props.groupID, this.state.repoName.trim()).then((res) => { this.props.toggle(); this.props.onRepoChanged(); }).catch(error => { let errorMsg = Utils.getErrorMsg(error); this.setState({ errMessage: errorMsg }); }); } } validateName = () => { let errMessage = ''; const name = this.state.repoName.trim(); if (!name.length) { errMessage = gettext('Name is required'); this.setState({ errMessage: errMessage }); return false; } return true; } handleChange = (e) => { this.setState({ repoName: e.target.value, }); } handleKeyPress = (e) => { if (e.key === 'Enter') { this.handleSubmit(); e.preventDefault(); } } render() { return ( <Modal isOpen={true} toggle={this.props.toggle}> <ModalHeader toggle={this.props.toggle}>{gettext('New Library')}</ModalHeader> <ModalBody> <Form> <FormGroup> <Label for="repoName">{gettext('Name')}</Label> <Input id="repoName" onKeyPress={this.handleKeyPress} value={this.state.repoName} onChange={this.handleChange} innerRef={input => {this.newInput = input;}} /> </FormGroup> </Form> {this.state.errMessage && <p className="error">{this.state.errMessage}</p> } </ModalBody> <ModalFooter> <Button color="primary" onClick={this.handleSubmit}>{gettext('Submit')}</Button> </ModalFooter> </Modal> ); } } AddRepoDialog.propTypes = propTypes; export default AddRepoDialog;
actor-apps/app-web/src/app/components/JoinGroup.react.js
ganquan0910/actor-platform
import React from 'react'; import requireAuth from 'utils/require-auth'; import DialogActionCreators from 'actions/DialogActionCreators'; import JoinGroupActions from 'actions/JoinGroupActions'; import JoinGroupStore from 'stores/JoinGroupStore'; // eslint-disable-line class JoinGroup extends React.Component { static propTypes = { params: React.PropTypes.object }; static contextTypes = { router: React.PropTypes.func }; constructor(props) { super(props); JoinGroupActions.joinGroup(props.params.token) .then((peer) => { this.context.router.replaceWith('/'); DialogActionCreators.selectDialogPeer(peer); }).catch((e) => { console.warn(e, 'User is already a group member'); this.context.router.replaceWith('/'); }); } render() { return null; } } export default requireAuth(JoinGroup);
src/index.js
gcedo/react-bootstrap-ui-builder
import React from 'react'; import UIBuilder from './components/UIBuilder.jsx'; React.render(<UIBuilder />, document.getElementById('root'));
local-cli/generator/templates/index.android.js
hayeah/react-native
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; class <%= name %> extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('<%= name %>', () => <%= name %>);
src/svg-icons/hardware/keyboard-return.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardReturn = (props) => ( <SvgIcon {...props}> <path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/> </SvgIcon> ); HardwareKeyboardReturn = pure(HardwareKeyboardReturn); HardwareKeyboardReturn.displayName = 'HardwareKeyboardReturn'; export default HardwareKeyboardReturn;
plugins/subschema-plugin-template-object/src/index.js
subschema/subschema-devel
import React, { Component } from 'react'; export class ObjectTemplate extends Component { static displayName = 'ObjectTemplate'; render() { const { children, className, fieldAttrs, ...rest } = this.props; return (<div className={className} {...fieldAttrs}> {children} </div>); } } export default ({ template: { ObjectTemplate } });
src/svg-icons/communication/call-received.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationCallReceived = (props) => ( <SvgIcon {...props}> <path d="M20 5.41L18.59 4 7 15.59V9H5v10h10v-2H8.41z"/> </SvgIcon> ); CommunicationCallReceived = pure(CommunicationCallReceived); CommunicationCallReceived.displayName = 'CommunicationCallReceived'; CommunicationCallReceived.muiName = 'SvgIcon'; export default CommunicationCallReceived;
imports/ui/components/Pagination/Pagination.js
hwillson/meteor-solr-demo
/* global window */ /* eslint-disable react/prefer-es6-class */ import React from 'react'; import RcPagination from 'rc-pagination'; import { _ } from 'meteor/underscore'; const Pagination = React.createClass({ propTypes: { searchMetadata: React.PropTypes.object.isRequired, searchParams: React.PropTypes.object.isRequired, handleSearchParamsUpdate: React.PropTypes.func.isRequired, }, onChange(page) { const newSearchParams = _.extend({}, this.props.searchParams); newSearchParams.currentPage = page; this.props.handleSearchParamsUpdate(newSearchParams); window.scroll(0, 0); }, totalResults() { return this.props.searchMetadata.totalResults ? this.props.searchMetadata.totalResults : 0; }, render() { return ( <div className="search-pagination"> <RcPagination current={this.props.searchParams.currentPage} onChange={this.onChange} total={this.totalResults()} pageSize={this.props.searchParams.resultsPerPage} /> </div> ); }, }); export default Pagination;
node_modules/rc-tabs/es/utils.js
yhx0634/foodshopfront
import _defineProperty from 'babel-runtime/helpers/defineProperty'; import React from 'react'; export function toArray(children) { // allow [c,[a,b]] var c = []; React.Children.forEach(children, function (child) { if (child) { c.push(child); } }); return c; } export function getActiveIndex(children, activeKey) { var c = toArray(children); for (var i = 0; i < c.length; i++) { if (c[i].key === activeKey) { return i; } } return -1; } export function getActiveKey(children, index) { var c = toArray(children); return c[index].key; } export function setTransform(style, v) { style.transform = v; style.webkitTransform = v; style.mozTransform = v; } export function isTransformSupported(style) { return 'transform' in style || 'webkitTransform' in style || 'MozTransform' in style; } export function setTransition(style, v) { style.transition = v; style.webkitTransition = v; style.MozTransition = v; } export function getTransformPropValue(v) { return { transform: v, WebkitTransform: v, MozTransform: v }; } export function isVertical(tabBarPosition) { return tabBarPosition === 'left' || tabBarPosition === 'right'; } export function getTransformByIndex(index, tabBarPosition) { var translate = isVertical(tabBarPosition) ? 'translateY' : 'translateX'; return translate + '(' + -index * 100 + '%) translateZ(0)'; } export function getMarginStyle(index, tabBarPosition) { var marginDirection = isVertical(tabBarPosition) ? 'marginTop' : 'marginLeft'; return _defineProperty({}, marginDirection, -index * 100 + '%'); } export function getStyle(el, property) { return +getComputedStyle(el).getPropertyValue(property).replace('px', ''); } export function setPxStyle(el, value, vertical) { value = vertical ? '0px, ' + value + 'px, 0px' : value + 'px, 0px, 0px'; setTransform(el.style, 'translate3d(' + value + ')'); } export function getDataAttr(props) { return Object.keys(props).reduce(function (prev, key) { if (key.substr(0, 5) === 'aria-' || key.substr(0, 5) === 'data-' || key === 'role') { prev[key] = props[key]; } return prev; }, {}); }
components/time_picker/Clock.js
KerenChandran/react-toolbox
import React from 'react'; import CssTransitionGroup from 'react-addons-css-transition-group'; import { ZoomIn, ZoomOut } from '../animations'; import style from './style.clock'; import time from '../utils/time'; import Hours from './ClockHours'; import Minutes from './ClockMinutes'; class Clock extends React.Component { static propTypes = { className: React.PropTypes.string, display: React.PropTypes.oneOf(['hours', 'minutes']), format: React.PropTypes.oneOf(['24hr', 'ampm']), onChange: React.PropTypes.func, onHandMoved: React.PropTypes.func, time: React.PropTypes.object }; static defaultProps = { className: '', display: 'hours', format: '24hr', time: new Date() }; state = { center: {x: null, y: null}, radius: 0 }; componentDidMount () { window.addEventListener('resize', this.handleCalculateShape); setTimeout(() => { this.handleCalculateShape(); }); } componentWillUnmount () { window.removeEventListener('resize', this.handleCalculateShape); } handleHourChange = (hours) => { if (this.props.time.getHours() !== hours) { this.props.onChange(time.setHours(this.props.time, this.adaptHourToFormat(hours))); } }; handleMinuteChange = (minutes) => { if (this.props.time.getMinutes() !== minutes) { this.props.onChange(time.setMinutes(this.props.time, minutes)); } }; handleCalculateShape = () => { const { top, left, width } = this.refs.placeholder.getBoundingClientRect(); this.setState({ center: { x: left + width / 2 - window.scrollX, y: top + width / 2 - window.scrollX }, radius: width / 2 }); }; adaptHourToFormat (hour) { if (this.props.format === 'ampm') { if (time.getTimeMode(this.props.time) === 'pm') { return hour < 12 ? hour + 12 : hour; } else { return hour === 12 ? 0 : hour; } } else { return hour; } } renderHours () { return ( <Hours center={this.state.center} format={this.props.format} onChange={this.handleHourChange} radius={this.state.radius} selected={this.props.time.getHours()} spacing={this.state.radius * 0.18} onHandMoved={this.props.onHandMoved} /> ); } renderMinutes () { return ( <Minutes center={this.state.center} onChange={this.handleMinuteChange} radius={this.state.radius} selected={this.props.time.getMinutes()} spacing={this.state.radius * 0.18} onHandMoved={this.props.onHandMoved} /> ); } render () { const animation = this.props.display === 'hours' ? ZoomOut : ZoomIn; return ( <div data-react-toolbox='clock' className={style.root}> <div ref='placeholder' className={style.placeholder} style={{height: this.state.radius * 2}}> <CssTransitionGroup transitionName={animation} transitionEnterTimeout={500} transitionLeaveTimeout={500}> <div key={this.props.display} className={style.wrapper} style={{height: this.state.radius * 2}}> {this.props.display === 'hours' ? this.renderHours() : null} {this.props.display === 'minutes' ? this.renderMinutes() : null} </div> </CssTransitionGroup> </div> </div> ); } } export default Clock;
src/components/Privacy/Privacy.react.js
uday96/chat.susi.ai
import '../Terms/Terms.css'; import $ from 'jquery'; import Footer from '../Footer/Footer.react'; import PropTypes from 'prop-types'; import StaticAppBar from '../StaticAppBar/StaticAppBar.react'; import React, { Component } from 'react'; class Privacy extends Component { constructor(props) { super(props); this.state = { open: false, showOptions: false, anchorEl: null, login: false, signup: false, video: false, openDrawer: false, }; } componentDidMount() { // Adding title tag to page document.title = 'Privacy Policy - SUSI.AI, Open Source Artificial Intelligence for Personal Assistants, Robots, Help Desks and Chatbots'; // Scrolling to top of page when component loads $('html, body').animate({ scrollTop: 0 }, 'fast'); } showOptions = (event) => { event.preventDefault(); this.setState({ showOptions: true, anchorEl: event.currentTarget }) } _onReady(event) { // access to player in all event handlers via event.target event.target.pauseVideo(); } render() { document.body.style.setProperty('background-image', 'none'); return ( <div> <StaticAppBar {...this.props} location={this.props.location} /> <div className='head_section'> <div className='container'> <div className="heading"> <h1>Privacy</h1> <p>Privacy Policy for SUSI</p> </div> </div> </div> <div className='section'> <div className="section-container" > <div className="terms-list"> <br /><br /> <h2>Welcome to SUSI!</h2> <p>Thanks for using our products and services (“Services”). The Services are provided by SUSI Inc. (“SUSI”), located at 93 Mau Than, Can Tho City, Viet Nam. By using our Services, you are agreeing to these terms. Please read them carefully. </p> <h2>Using our Services</h2> <p>You must follow any policies made available to you within the Services. <br /><br /> Don’t misuse our Services. For example, don’t interfere with our Services or try to access them using a method other than the interface and the instructions that we provide. You may use our Services only as permitted by law, including applicable export and re-export control laws and regulations. We may suspend or stop providing our Services to you if you do not comply with our terms or policies or if we are investigating suspected misconduct. <br /><br /> Using our Services does not give you ownership of any intellectual property rights in our Services or the content you access. You may not use content from our Services unless you obtain permission from its owner or are otherwise permitted by law. These terms do not grant you the right to use any branding or logos used in our Services. Don’t remove, obscure, or alter any legal notices displayed in or along with our Services. <br /><br /> Our Services display some content that is not SUSI’s. This content is the sole responsibility of the entity that makes it available. We may review content to determine whether it is illegal or violates our policies, and we may remove or refuse to display content that we reasonably believe violates our policies or the law. But that does not necessarily mean that we review content, so please don’t assume that we do. <br /><br /> In connection with your use of the Services, we may send you service announcements, administrative messages, and other information. You may opt out of some of those communications. <br /><br /> Some of our Services are available on mobile devices. Do not use such Services in a way that distracts you and prevents you from obeying traffic or safety laws. <br /><br /> </p> <h2>Your SUSI Account</h2> <p> You may need a SUSI Account in order to use some of our Services. You may create your own SUSI Account, or your SUSI Account may be assigned to you by an administrator, such as your employer or educational institution. If you are using a SUSI Account assigned to you by an administrator, different or additional terms may apply and your administrator may be able to access or disable your account. <br /><br /> To protect your SUSI Account, keep your password confidential. You are responsible for the activity that happens on or through your SUSI Account. Try not to reuse your SUSI Account password on third-party applications. If you learn of any unauthorized use of your password or SUSI Account, change your password and take measures to secure your account. <br /><br /> </p> <h2>Privacy and Copyright Protection</h2> <p>SUSI’s privacy policies ensures that your personal data is safe and protected. By using our Services, you agree that SUSI can use such data in accordance with our privacy policies. <br /><br /> We respond to notices of alleged copyright infringement and terminate accounts of repeat infringers. If you think somebody is violating your copyrights and want to notify us, you can find information about submitting notices and SUSI’s policy about responding to notices on our website. <br /><br /> </p> <h2>Your Content in our Services</h2> <p>Some of our Services allow you to upload, submit, store, send or receive content. You retain ownership of any intellectual property rights that you hold in that content. In short, what belongs to you stays yours. <br /><br /> When you upload, submit, store, send or receive content to or through our Services, you give SUSI (and those we work with) a worldwide license to use, host, store, reproduce, modify, create derivative works (such as those resulting from translations, adaptations or other changes we make so that your content works better with our Services), communicate, publish, publicly perform, publicly display and distribute such content. The rights you grant in this license are for the limited purpose of operating, promoting, and improving our Services, and to develop new ones. This license continues even if you stop using our Services (for example, for a business listing you have added to SUSI Maps). Some Services may offer you ways to access and remove content that has been provided to that Service. Also, in some of our Services, there are terms or settings that narrow the scope of our use of the content submitted in those Services. Make sure you have the necessary rights to grant this license for any content that you submit to our Services. <br /><br /> If you have a SUSI Account, we may display your Profile name, Profile photo, and actions you take on SUSI or on third-party applications connected to your SUSI Account in our Services, including displaying in ads and other commercial contexts. We will respect the choices you make to limit sharing or visibility settings in your SUSI Account. <br /><br /> </p> <h2>About Software in our Services</h2> <p>When a Service requires or includes downloadable software, this software may update automatically on your device once a new version or feature is available. Some Services may let you adjust your automatic update settings. <br /><br /> SUSI gives you a personal, worldwide, royalty-free, non-assignable and non-exclusive license to use the software provided to you by SUSI as part of the Services. This license is for the sole purpose of enabling you to use and enjoy the benefit of the Services as provided by SUSI, in the manner permitted by these terms. <br /><br /> Most of our services are offered through Free Software and/or Open Source Software. You may copy, modify, distribute, sell, or lease these applications and share the source code of that software as stated in the License agreement provided with the Software. <br /><br /> </p> <h2>Modifying and Terminating our Services</h2> <p>We are constantly changing and improving our Services. We may add or remove functionalities or features, and we may suspend or stop a Service altogether. <br /><br /> You can stop using our Services at any time. SUSI may also stop providing Services to you, or add or create new limits to our Services at any time. <br /><br /> We believe that you own your data and preserving your access to such data is important. If we discontinue a Service, where reasonably possible, we will give you reasonable advance notice and a chance to get information out of that Service. <br /><br /> </p> <h2>Our Warranties and Disclaimers</h2> <p>We provide our Services using a reasonable level of skill and care and we hope that you will enjoy using them. But there are certain things that we don’t promise about our Services. <br /><br /> Other than as expressly set out in these terms or additional terms, neither SUSI nor its suppliers or distributors make any specific promises about the Services. For example, we don’t make any commitments about the content within the Services, the specific functions of the Services, or their reliability, availability, or ability to meet your needs. We provide the Services “as is”. <br /><br /> Some jurisdictions provide for certain warranties, like the implied warranty of merchantability, fitness for a particular purpose and non-infringement. To the extent permitted by law, we exclude all warranties. <br /><br /> </p> <h2>Liability for our Services</h2> <p>When permitted by law, SUSI, and SUSI’s suppliers and distributors, will not be responsible for lost profits, revenues, or data, financial losses or indirect, special, consequential, exemplary, or punitive damages. <br /><br /> To the extent permitted by law, the total liability of SUSI, and its suppliers and distributors, for any claims under these terms, including for any implied warranties, is limited to the amount you paid us to use the Services (or, if we choose, to supplying you the Services again). <br /><br /> In all cases, SUSI, and its suppliers and distributors, will not be liable for any loss or damage that is not reasonably foreseeable. <br /><br /> We recognize that in some countries, you might have legal rights as a consumer. If you are using the Services for a personal purpose, then nothing in these terms or any additional terms limits any consumer legal rights which may not be waived by contract. <br /><br /> </p> <h2>Business uses of our Services</h2> <p>If you are using our Services on behalf of a business, that business accepts these terms. It will hold harmless and indemnify SUSI and its affiliates, officers, agents, and employees from any claim, suit or action arising from or related to the use of the Services or violation of these terms, including any liability or expense arising from claims, losses , damages, suits, judgments, litigation costs and attorneys’ fees. <br /><br /></p> <h2>About these Terms</h2> <p>We may modify these terms or any additional terms that apply to a Service to, for example, reflect changes to the law or changes to our Services. You should look at the terms regularly. We’ll post notice of modifications to these terms on this page. We’ll post notice of modified additional terms in the applicable Service. Changes will not apply retroactively and will become effective no sooner than fourteen days after they are posted. However,changes addressing new functions for a Service or changes made for legal reasons will be effective immediately. If you do not agree to the modified terms for a Service, you should discontinue your use of that Service. <br /><br /> If there is a conflict between these terms and the additional terms, the additional terms will control for that conflict. <br /> These terms control the relationship between SUSI and you. They do not create any third party beneficiary rights. <br /><br /> If you do not comply with these terms, and we don’t take action right away, this doesn’t mean that we are giving up any rights that we may have (such as taking action in the future). <br /><br /> If it turns out that a particular term is not enforceable, this will not affect any other terms.<br /><br /> You agree that the laws of Can Tho, Viet Nam will apply to any disputes arising out of or relating to these terms or the Services. All claims arising out of or relating to these terms or the services will be litigated exclusively in the courts of Can Tho City, Viet Nam, and you and SUSI consent to personal jurisdiction in those courts. <br /><br /> For information about how to contact SUSI, please visit our contact page. <br /><br /> </p> </div> </div> </div> <Footer /> </div> ); }; } Privacy.propTypes = { history: PropTypes.object, location: PropTypes.object } export default Privacy;
packages/shared/ReactSharedInternals.js
yiminghe/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; const ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions. // Current owner and dispatcher used to share the same ref, // but PR #14548 split them out to better support the react-debug-tools package. if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) { ReactSharedInternals.ReactCurrentDispatcher = { current: null, }; } if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) { ReactSharedInternals.ReactCurrentBatchConfig = { suspense: null, }; } export default ReactSharedInternals;
3.ArrayDemo/src/ArrayDemo.js
hiren2728/ReactDemo
import React from 'react'; export default class ArrayDemo extends React.Component{ constructor(props){ super(props); this.state = { values : [ {"name" : "Hiren"}, {"name" : "Harpla"}, {"name" : "A"}, {"name" : "B"} ], userInput : "" } } render(){ return <div> Enter Name : <input onChange={this.onTextChage}/> <button value={this.state.userInput} onClick={this.onClick} key={"textfield"}>Add Value</button> <ul> { // This code for print the value of Array, here in Map Funciton, item = valeu and index = key , we need to assign key to li tag so react dom can identifiedy it uniquly // this.state.values.map((item,index) => // <li key={index}><h2>{item}</h2></li> // ) this.state.values.map((item,index) => <li key={index}>{item.name}</li> ) } </ul> </div>; } onClick = () =>{ let tmp = this.state.values tmp.push({"name":this.state.userInput}) this.setState({ userInput : "", values : tmp }); console.log(this.state.userInput) }; onTextChage = (e) => { this.setState( { userInput : e.target.value } ); }; }
components/animals/skunkPruhovany.child.js
marxsk/zobro
import React, { Component } from 'react'; import { Text } from 'react-native'; import styles from '../../styles/styles'; import InPageImage from '../inPageImage'; import AnimalText from '../animalText'; import AnimalTemplate from '../animalTemplate'; const IMAGES = [ require('../../images/animals/skunkPruhovany/01.jpg'), require('../../images/animals/skunkPruhovany/02.jpg'), require('../../images/animals/skunkPruhovany/03.jpg'), ]; const THUMBNAILS = [ require('../../images/animals/skunkPruhovany/01-thumb.jpg'), require('../../images/animals/skunkPruhovany/02-thumb.jpg'), require('../../images/animals/skunkPruhovany/03-thumb.jpg'), ]; var AnimalDetail = React.createClass({ render() { return ( <AnimalTemplate firstIndex={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}> <AnimalText> Ahoj děti! Dovolte, abychom se vám představili, jsme skunkové pruhovaní. Jak se máte? My dnes pouze posedáváme a poleháváme, občas se proběhneme, ale úplně nejradši si dáme něco dobrého na zub. Spořádáme v&nbsp;podstatě všechno, co nám kdo dá, takže to s&nbsp;námi není vůbec složité. Nepohrdneme masem, oříšky, ovocem ani vajíčky. </AnimalText> <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Jsme krásně černobílí, přesněji řečeno černí s&nbsp;bílými pruhy. Ale nebojte, od zeber nás snadno rozeznáte. V&nbsp;dospělosti vážíme asi tolik jako menší jezevčík, takže si nás se zebrou opravdu nespletete. </AnimalText> <AnimalText> Moc rádi se procházíme ve zdejším výběhu. Jestli však nikoho z&nbsp;nás zrovna nevidíte, nejspíš spíme v&nbsp;některém z&nbsp;úkrytů nebo v&nbsp;boudě. </AnimalText> <InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Jsme noční zvířata a denní světlo nás unavuje. Pokud by se nás někdo pokusil v&nbsp;našem odpočívání obtěžovat, jsme připraveni ho postříkat pěkně smradlavou kolínskou. Když totiž nepřítele nezastrašíme hrozivým dupáním, můžeme ze žláz pod ocáskem vystříknout páchnoucí olejovitou tekutinu, kterou jen tak nesmyjete. A&nbsp;to dokonce až na tři metry daleko! Ale to už jste o&nbsp;nás jistě slyšeli. Tak pozor na to a nezlobte! </AnimalText> </AnimalTemplate> ); } }); module.exports = AnimalDetail;
app/views/FrontPage/Overview/Overview.js
RcKeller/STF-Refresh
import React from 'react' class Overview extends React.Component { render () { return ( <div> <h2>Technology Fee</h2> <p> The Student Technology Fee is a $38 per quarter fee paid by all matriculated students of the University of Washington. The committee appropriates roughly $5 million in student funding across almost one hundred proposals annually. All projects funded by the STF are not-for-profit and for student use. </p> <h2>Proposal Process</h2> <p> Funding is allocated via a proposal/grant cycle run by the committee. At the beginning of the year, a Request for Proposals (RFP) is issued. Proposal submissions are accepted at the beginning of each quarter, and authors are asked to present the request at a weekly board meeting. At the end of each quarter, the committee votes and issues funding decisions. Those who receive awards must spend and report expenditures by the end of the academic year. </p> <h2>Student Outreach</h2> <p> All STF projects involve student outreach, where project leaders reach out and inform the student body about resources they can benefit from. The STF holds <a href='http://apps.leg.wa.gov/rcw/default.aspx?cite=42.30'>Open Meetings</a> every week during the academic year to hear, deliberate and vote on campus projects. We encourage students to attend. </p> </div> ) } } export default Overview
app/components/ProgressIndicator.js
RichAbrahams/electron-project
import React from 'react'; import Button from './stc/Button'; import * as colors from '../colors'; import Icon from './stc/Icon'; import H2Centered from './stc/H2-Centered'; import DivCentered from './stc/DivCentered'; function ProgressIndicator(props) { const { text } = props; return ( <div className="download-indicator" > <H2Centered color="#999">{text}</H2Centered> <Icon name="cog" size="3x" color="#999" spin /> </div> ); } // AddConsignmentProducts.propTypes = { addConsignmentProduct: // React.PropTypes.func.isRequired }; export default ProgressIndicator;
static/src/components/NotFound.js
agelarry/online_quiz
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as actionCreators from '../actions/auth'; function mapStateToProps(state) { return { token: state.auth.token, userName: state.auth.userName, isAuthenticated: state.auth.isAuthenticated, }; } function mapDispatchToProps(dispatch) { return bindActionCreators(actionCreators, dispatch); } @connect(mapStateToProps, mapDispatchToProps) class NotFound extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div className="col-md-8"> <h1>Not Found</h1> </div> ); } } export default NotFound;
src/hocs/withD3Renderer.js
tibotiber/rd3
import React from 'react' import _ from 'lodash' import {shallowEqual} from 'recompose' const withD3Renderer = ({ resizeOn = ['width', 'height'], updateOn = ['data'] }) => WrappedComponent => { return class WithD3Renderer extends React.Component { setRef = wrappedComponentInstance => { this.component = wrappedComponentInstance } componentDidMount() { this.props.incrementRenderCount('component') this.props.incrementRenderCount('d3') this.component.renderD3('render') } componentDidUpdate(prevProps, prevState) { this.props.incrementRenderCount('component') const shouldResize = props => _.pick(props, resizeOn) if (!shallowEqual(shouldResize(this.props), shouldResize(prevProps))) { this.props.incrementRenderCount('d3') return this.component.renderD3('resize') } const shouldUpdate = props => _.pick(props, updateOn) if (!shallowEqual(shouldUpdate(this.props), shouldUpdate(prevProps))) { this.props.incrementRenderCount('d3') this.component.renderD3('update') } } render() { const {incrementRenderCount, ...otherProps} = this.props return <WrappedComponent ref={this.setRef} {...otherProps} /> } } } export default withD3Renderer
src/components/with-clear-div.js
sievins/sarahs-footsteps
import React from 'react' function withClearDiv(element, height = 0) { const style = { height, clear: 'both', } return ( <div> {element} <div style={style} /> </div> ) } export default withClearDiv
src/components/gearratioinfo.js
prexsa/m3specs
import React, { Component } from 'react'; import { List } from 'semantic-ui-react'; class GearRatioInfo extends Component { render() { return ( <div> <List bulleted> <List.Item>Tire Diameter (25.596) - 275/30R19</List.Item> <List.Item>Final Drive Ratio (3.62)</List.Item> <List.Item>Coefficient (336)</List.Item> <List.Item>Redline RPM (8,000)</List.Item> <List.Item>Gear Ratio <List.List> <List.Item>First Gear: 4.23</List.Item> <List.Item>Second Gear: 2.53</List.Item> <List.Item>Third Gear: 1.67</List.Item> <List.Item>Fourth Gear: 1.23</List.Item> <List.Item>Fifth Gear: 1.00</List.Item> <List.Item>Sixth Gear: 0.83</List.Item> </List.List> </List.Item> </List> </div> ) } } export default GearRatioInfo;
imports/ui/components/bookmark.js
dklisiaris/boomabu
import React from 'react'; import { Meteor } from 'meteor/meteor'; import {ReactPageClick} from 'react-page-click'; import { removeBookmark, refreshBookmark, updateBookmark, incBookmarkViews } from '../../api/bookmarks/methods'; import {can} from '/imports/modules/permissions.js'; import {Loading} from '/imports/ui/components/loading'; import ReactTooltip from 'react-tooltip'; export class Bookmark extends React.Component { constructor(props) { super(props); this.state = { isShowingActions: false, isModalOpen: false, isLoading: false }; this._handleActionsToggle = this._handleActionsToggle.bind(this); this._handleRemoveAction = this._handleRemoveAction.bind(this); this._handleBookmarkRefresh = this._handleBookmarkRefresh.bind(this); this._handleBookmarkEdit = this._handleBookmarkEdit.bind(this); this._handeBookmarkClick = this._handeBookmarkClick.bind(this); } /** * Helpers */ _shortUrl() { return this.props.url.replace(/.*?:\/\//g,"").replace("www.",""); } _thumbnail() { let thumbSrc = '/img/no-image.png'; if(this.props.webshotUrl){ thumbSrc = this.props.webshotUrl } else if (this.props.image){ thumbSrc = this.props.image } return <img src={thumbSrc} alt="thumbnail" width="100%" /> } /** * Renderers */ _renderBookmarkActions() { const bookmarkActions = ( <ul className="bookmark-actions"> <li> <a onClick={this._handeBookmarkClick} href={this.props.url} target="_blank"> <i className="fa fa-eye"></i> <span className="bookmark-action-text"> View</span> </a> </li> <li> <a onClick={this._handleBookmarkRefresh}><i className="fa fa-refresh"></i> <span className="bookmark-action-text"> Refresh</span> </a> </li> <li> <a onClick={this._handleBookmarkEdit}><i className="fa fa-pencil"></i> <span className="bookmark-action-text"> Edit</span> </a> </li> <li> <a onClick={this._handleRemoveAction} ><i className="fa fa-trash"></i> <span className="bookmark-action-text"> Remove</span> </a> </li> </ul> ); return bookmarkActions; } _renderBookmarkThumb() { const bookmarkThumb = ( <a onClick={this._handeBookmarkClick} href={this.props.url} target="_blank" className="clickable-url"> {this._thumbnail()} </a> ); return bookmarkThumb; } _renderThumbOrActions() { if(this.state.isShowingActions && !this.props.readOnly){ return this._renderBookmarkActions(); } else { return this._renderBookmarkThumb(); } } _renderActionsToggleBtn() { const actionsToggleBtn = ( <span className="bookmark-actions-toggle" onClick={this._handleActionsToggle}> <i className={this.state.isShowingActions ? 'fa fa-undo' : 'fa fa-cog'}></i> </span> ) if(!this.props.readOnly){ return actionsToggleBtn; } } _renderBookmarkInner() { const innerContent = ( <div className="inner"> <h4 data-tip={this.props.title} data-for={this.props.id}> <a href={this.props.url} target="_blank">{this.props.title}</a> </h4> <div className="bookmark-content"> {this._renderThumbOrActions()} </div> <div className="bookmark-footer"> <div className="bookmark-url-wrapper"> <span className="bookmark-url">{this._shortUrl()}</span> </div> {this._renderActionsToggleBtn()} </div> </div> ); const innerLoading = ( <div className="inner"> <Loading/> </div> ) return !this.state.isLoading ? innerContent : innerLoading; } /** * Handlers */ _handleActionsToggle(e) { e.preventDefault(); this.setState(prevState => ({ isShowingActions: !prevState.isShowingActions })); } _handleRemoveAction(e) { e.preventDefault(); removeBookmark.call({bookmarkId: this.props.id}, (error) => { if (error) { Bert.alert(error.reason, 'danger'); } }); } _handleBookmarkRefresh(e) { e.preventDefault(); this.setState({isLoading: true, isShowingActions: false}); refreshBookmark.call({bookmarkId: this.props.id}, (err) => { this.setState({isLoading: false}) }); } _handleBookmarkEdit(e) { e.preventDefault(); this.props.editBookmarkHandler(this.props.id); } _handeBookmarkClick(e) { incBookmarkViews.call({bookmarkId: this.props.id}, null); } render() { return ( <div id={this.props.id} className="bookmark-card"> {this._renderBookmarkInner()} <ReactTooltip id={this.props.id} place="top" multiline={true} effect="solid" /> </div> ); } } Bookmark.propTypes = { id: React.PropTypes.string, title: React.PropTypes.string, url: React.PropTypes.string, image: React.PropTypes.string, folderId: React.PropTypes.string, webshotUrl: React.PropTypes.string, editBookmarkHandler: React.PropTypes.func, readOnly: React.PropTypes.bool, };
src/layout.js
wi2/auto-admin
"use strict"; import React from 'react' import Nav from './nav' export default class { render() { return ( <div> <Nav {...this.props} /> {this.props.children} </div> ) } }