path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
docs/app/Examples/modules/Dropdown/Usage/DropdownExampleRemoveNoResultsMessage.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Dropdown } from 'semantic-ui-react' const DropdownExampleRemoveNoResultsMessage = () => ( <Dropdown options={[]} search selection placeholder='No message...' noResultsMessage={null} /> ) export default DropdownExampleRemoveNoResultsMessage
test/UserList.spec.js
dylanavery720/shoot-the-breeze
import React from 'react'; import Sinon from 'sinon'; import { shallow, mount, render } from 'enzyme'; import { assert, expect } from 'chai'; import { fakeMessages } from './helpers/stubData' import UserList from '../lib/components/UserList'; require('locus'); describe('<UserList />', () => { it('renders as a <div>', () => { const wrapper = shallow(<UserList messages={fakeMessages}/>) assert.equal(wrapper.type(), 'div'); }); it('renders the title from prop', () => { const wrapper = shallow(<UserList text="Users" messages={fakeMessages}/>); const heading = wrapper.find('.user-list-header'); expect(heading.text()).to.contain('Users'); }); it('renders Users from message list', () => { const wrapper = render(<UserList text="Users" messages={fakeMessages}/>); const users = wrapper.find('.user-list-user'); expect(users).to.have.length(2); }); });
app/views/Watches/main.js
herereadthis/redwall
import React from 'react'; import Router from 'react-router'; import FluxComponent from 'flummox/component'; import AppFlux from 'AppFlux'; import AppStore from 'AppStore'; import Watches from './Watches'; var {DefaultRoute, Route} = Router, routes; const flux = new AppFlux(); routes = ( <Route> <Route name="watches" path="/watches/" handler={Watches}/> <DefaultRoute handler={Watches}/> </Route> ); // Router.HistoryLocation gets rid of the the /#/ hash by using html5 history // API for cleaner URLs // Router.run(routes, Router.HistoryLocation, (Handler) => { Router.run(routes, Router.HistoryLocation, (Handler) => { React.render( <FluxComponent flux={flux} connectToStores={[AppStore.ID]}> <Handler/> </FluxComponent>, document.getElementById('app') ); });
docs/src/app/components/pages/components/Checkbox/ExampleSimple.js
skarnecki/material-ui
import React from 'react'; import Checkbox from 'material-ui/Checkbox'; import ActionFavorite from 'material-ui/svg-icons/action/favorite'; import ActionFavoriteBorder from 'material-ui/svg-icons/action/favorite-border'; const styles = { block: { maxWidth: 250, }, checkbox: { marginBottom: 16, }, }; const CheckboxExampleSimple = () => ( <div style={styles.block}> <Checkbox label="Simple" style={styles.checkbox} /> <Checkbox label="Checked by default" defaultChecked={true} style={styles.checkbox} /> <Checkbox checkedIcon={<ActionFavorite />} uncheckedIcon={<ActionFavoriteBorder />} label="Custom icon" style={styles.checkbox} /> <Checkbox label="Disabled unchecked" disabled={true} style={styles.checkbox} /> <Checkbox label="Disabled checked" checked={true} disabled={true} style={styles.checkbox} /> <Checkbox label="Label on the left" labelPosition="left" style={styles.checkbox} /> </div> ); export default CheckboxExampleSimple;
dist/react-calendar-icon.esm.js
kkostov/react-calendar-icon
import React from 'react'; import styled from '@emotion/styled'; var themedConfig = (theme => ({ textColor: 'white', // text color of the header and footer primaryColor: '#e85650', // used as background of the header and footer backgroundColor: '#fafafa', ...(theme === null || theme === void 0 ? void 0 : theme.calendarIcon) })); const IconDiv = styled('div')(props => ({ fontSize: '0.7em', backgroundColor: themedConfig(props.theme).backgroundColor, height: '8em', width: '8em', borderRadius: '0.7em', overflow: 'hidden', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between' })); const HeaderDiv = styled('div')(props => ({ color: themedConfig(props.theme).textColor, backgroundColor: themedConfig(props.theme).primaryColor, width: '100%', textAlign: 'center', fontSize: '1.2em', lineHeight: '1.4em' })); const ValueDiv = styled('div')({ letterSpacing: '-0.05em', fontSize: '2.6rem', marginRight: '0.15em', marginTop: '0.1em' }); const FooterDiv = styled('div')(props => ({ color: themedConfig(props.theme).textColor, backgroundColor: themedConfig(props.theme).primaryColor, width: '100%', textAlign: 'center', fontSize: '1.2em', lineHeight: '1.4em' })); const defaultOptions = { header: { weekday: 'long' }, footer: { month: 'long' }, value: { day: '2-digit' }, locale: [] }; function formatDate(date, locale, formatOptions) { return date.toLocaleDateString(locale, formatOptions); } function CalendarIcon(_ref) { let { date, options = defaultOptions } = _ref; return /*#__PURE__*/React.createElement(IconDiv, null, /*#__PURE__*/React.createElement(HeaderDiv, null, formatDate(date, options.locale, options.header)), /*#__PURE__*/React.createElement(ValueDiv, null, formatDate(date, options.locale, options.value)), /*#__PURE__*/React.createElement(FooterDiv, null, formatDate(date, options.locale, options.footer))); } export { CalendarIcon, CalendarIcon as default };
src/views/Home/index.js
JounQin/1stg
import React from 'react' import PropTypes from 'prop-types' import { Grid } from './Grid' import styles from './index.scss' const GRIDS = [ { title: 'GitHub', link: 'https://github.com/JounQin', className: 'github', }, { title: 'Rubick', text: 'Vue SSR + TS', link: 'https://rubick.1stg.me/', className: 'rubick', }, { title: 'React Hackernews', text: 'View React HN', link: 'https://react-hn.now.sh', className: 'react-hn', }, { title: 'My Blog', text: 'Personal Website', link: 'https://blog.1stg.me', className: 'blog', }, ] export const Home = () => ( <main className={styles.main}> {GRIDS.map((info, index) => ( <Grid key={index} {...info} /> ))} </main> ) Home.propTypes = { style: PropTypes.object, }
app/assets/scripts/components/Curves/index.js
bartoszkrawczyk2/curves.js
import React, { Component } from 'react'; import { drawSpline } from '../../core'; import './style.scss'; class Curves extends Component { componentDidMount() { this.canvas = this.refs.canvas; this.canvas.width = 280; this.canvas.height = 280; this.ctx = this.canvas.getContext('2d'); drawSpline( this.canvas, this.ctx, this.props.currentCurves[this.props.currentChannel].xs, this.props.currentCurves[this.props.currentChannel].ys ); } componentWillUpdate(nextProps, nextState) { drawSpline( this.canvas, this.ctx, nextProps.currentCurves[nextProps.currentChannel].xs, nextProps.currentCurves[nextProps.currentChannel].ys ); } render() { return ( <div> <p>Select channel:</p> <select className='channel-select' value={this.props.currentChannel} onChange={(e) => this.props.changeChannel(e.target.value)}> <option value='a'>Brightness</option> <option value='r'>Red</option> <option value='g'>Green</option> <option value='b'>Blue</option> </select> <canvas ref='canvas' onMouseDown={(e) => this.props.mouseDown( e, this.canvas || null, this.props.currentCurves[this.props.currentChannel] )} onMouseMove={(e) => this.props.mouseMove( e, this.canvas || null, this.ctx || null )} onMouseUp={this.props.mouseUp} onDoubleClick={(e) => this.props.doubleClick(e, this.props.currentCurves[this.props.currentChannel])} /> <span className='curves-desc'>Double click to add point.</span> <span className='curves-desc'>Hold shift and click on point to remove.</span> </div> ); } } export default Curves;
src/modules/Rooms/components/Chat/Chat.js
prjctrft/mantenuto
/* eslint-disable */ import React from 'react'; import Messages from './Messages'; export default (props) => { const styles = require('./Chat.scss'); return ( <div className={styles.Chat}> <div className={styles.ChatHeader}> <button className={styles.closeChat} onClick={props.toggleChat}> <i className={`fa ${styles.faTimesThin} fa-2x`} aria-hidden="true"></i> </button> </div> <p className='text-center'> <button disabled={props.disableLoadMore} onClick={props.loadMore} className='btn btn-default btn-sm btn-outline-dark'> ... </button> </p> <Messages /> <div className={`${styles.MessageInput}`}> <textarea placeholder='Send some love.' onKeyPress={props.handleSubmit} onChange={props.handleChange} value={props.content} className={`${styles.flexItem} form-control`} /> {/* <button onClick={props.handleSubmit} className={`btn btn-primary`}>Send</button> */} </div> </div> ) }
client/views/omnichannel/components/Label.js
VoiSmart/Rocket.Chat
import { Box } from '@rocket.chat/fuselage'; import React from 'react'; const Label = (props) => <Box mbe='x8' fontScale='p2' color='default' {...props} />; export default Label;
node_modules/react-router-dom/es/NavLink.js
rwarr/futaba-db
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import PropTypes from 'prop-types'; import Route from './Route'; import Link from './Link'; /** * A <Link> wrapper that knows if it's "active" or not. */ var NavLink = function NavLink(_ref) { var to = _ref.to, exact = _ref.exact, strict = _ref.strict, location = _ref.location, activeClassName = _ref.activeClassName, className = _ref.className, activeStyle = _ref.activeStyle, style = _ref.style, getIsActive = _ref.isActive, ariaCurrent = _ref.ariaCurrent, rest = _objectWithoutProperties(_ref, ['to', 'exact', 'strict', 'location', 'activeClassName', 'className', 'activeStyle', 'style', 'isActive', 'ariaCurrent']); return React.createElement(Route, { path: (typeof to === 'undefined' ? 'undefined' : _typeof(to)) === 'object' ? to.pathname : to, exact: exact, strict: strict, location: location, children: function children(_ref2) { var location = _ref2.location, match = _ref2.match; var isActive = !!(getIsActive ? getIsActive(match, location) : match); return React.createElement(Link, _extends({ to: to, className: isActive ? [className, activeClassName].filter(function (i) { return i; }).join(' ') : className, style: isActive ? _extends({}, style, activeStyle) : style, 'aria-current': isActive && ariaCurrent }, rest)); } }); }; NavLink.propTypes = { to: Link.propTypes.to, exact: PropTypes.bool, strict: PropTypes.bool, location: PropTypes.object, activeClassName: PropTypes.string, className: PropTypes.string, activeStyle: PropTypes.object, style: PropTypes.object, isActive: PropTypes.func, ariaCurrent: PropTypes.oneOf(['page', 'step', 'location', 'true']) }; NavLink.defaultProps = { activeClassName: 'active', ariaCurrent: 'true' }; export default NavLink;
examples/src/Examples.js
BD2KGenomics/react-autosuggest
require('./Examples.less'); require('./Autosuggest.less'); import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import BasicExample from './BasicExample/BasicExample'; import CustomRenderer from './CustomRenderer/CustomRenderer'; import MultipleSections from './MultipleSections/MultipleSections'; import ControlledComponent from './ControlledComponent/ControlledComponent'; import EventsPlayground from './EventsPlayground/EventsPlayground'; import EventsLog from './EventsLog/EventsLog'; export default class Examples extends Component { constructor() { super(); this.examples = [ 'Basic example', 'Custom renderer', 'Multiple sections', 'Controlled component', 'Events playground' ]; this.eventsPlaceholder = { type: 'placeholder', text: 'Once you interact with the Autosuggest, events will appear here.' }; this.eventQueue = []; this.state = { activeExample: decodeURI(location.hash).split('#')[1] || this.examples[0], events: [this.eventsPlaceholder] }; } changeExample(example) { this.setState({ activeExample: example }); } renderMenu() { return ( <div className="examples__menu" role="menu"> {this.examples.map(example => { const classes = 'examples__menu-item' + (example === this.state.activeExample ? ' examples__menu-item--active' : ''); return ( <div className={classes} key={example} role="menuitem" tabIndex="0" onClick={this.changeExample.bind(this, example)}> {example} </div> ); })} </div> ); } clearEvents() { this.setState({ events: [this.eventsPlaceholder] }); } eventsExist() { return this.state.events[0].type !== 'placeholder'; } renderEventsLog() { if (this.state.activeExample === 'Events playground') { return ( <div className="examples__events-log-wrapper"> { this.eventsExist() && <button onClick={::this.clearEvents}>Clear</button> } <EventsLog ref="eventsLog" events={this.state.events} /> </div> ); } return null; } isEventQueueEmpty() { return this.eventQueue.length === 0; } processEvents() { if (this.isEventQueueEmpty()) { return; } const event = this.eventQueue[0]; this.setState({ events: this.eventsExist() ? this.state.events.concat([event]) : [event] }, () => { this.eventQueue.shift(); this.processEvents(); // Scroll to the bottom findDOMNode(this.refs.eventsLog.refs.eventsLogWrapper).scrollTop = Number.MAX_SAFE_INTEGER; }); } onEventAdded(event) { const eventQueueWasEmpty = this.isEventQueueEmpty(); this.eventQueue.push(event); if (eventQueueWasEmpty) { this.processEvents(); } } focusOn(id) { document.getElementById(id).focus(); } renderExample() { switch (this.state.activeExample) { case 'Basic example': return <BasicExample ref={() => this.focusOn('basic-example')} />; case 'Custom renderer': return <CustomRenderer ref={() => this.focusOn('custom-renderer')} />; case 'Multiple sections': return <MultipleSections ref={() => this.focusOn('multiple-sections')} />; case 'Controlled component': return <ControlledComponent ref={() => this.focusOn('controlled-component-from')} />; case 'Events playground': return <EventsPlayground onEventAdded={::this.onEventAdded} ref={() => this.focusOn('events-playground')} />; } } render() { return ( <div className="examples"> <div className="examples__column"> {this.renderMenu()} {this.renderEventsLog()} </div> <div className="examples__column"> {this.renderExample()} </div> </div> ); } }
src/containers/App.js
zackbleach/react-transform-boilerplate
import React, { Component } from 'react'; import { compose, createStore, combineReducers } from 'redux'; import { Provider } from 'react-redux'; import { devTools, persistState } from 'redux-devtools'; import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react'; import CounterApp from './CounterApp'; import * as reducers from '../reducers'; import {incrementCounter} from '../actions/Actions'; const reducer = combineReducers(reducers); // TODO: refactor this out to own class which switches on config const finalCreateStore = compose( devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) )(createStore); const store = finalCreateStore(reducer); export default class App extends Component { render() { return ( <div> <Provider store={store}> {() => <CounterApp /> } </Provider> <DebugPanel top right bottom> <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> </div> ); } }
src/Alert.js
collinwu/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Alert = React.createClass({ mixins: [BootstrapMixin], propTypes: { onDismiss: React.PropTypes.func, dismissAfter: React.PropTypes.number, closeLabel: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'alert', bsStyle: 'info', closeLabel: 'Close Alert' }; }, renderDismissButton() { return ( <button type="button" className="close" aria-label={this.props.closeLabel} onClick={this.props.onDismiss}> <span aria-hidden="true">&times;</span> </button> ); }, render() { let classes = this.getBsClassSet(); let isDismissable = !!this.props.onDismiss; classes['alert-dismissable'] = isDismissable; return ( <div {...this.props} role='alert' className={classNames(this.props.className, classes)}> {isDismissable ? this.renderDismissButton() : null} {this.props.children} </div> ); }, componentDidMount() { if (this.props.dismissAfter && this.props.onDismiss) { this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter); } }, componentWillUnmount() { clearTimeout(this.dismissTimer); } }); export default Alert;
src/helpers/__tests__/makeRouteHooksSafe-test.js
gregsabo/redux-decagon
import { expect } from 'chai'; import React from 'react'; import { IndexRoute, Route } from 'react-router'; import makeRouteHooksSafe from '../makeRouteHooksSafe'; describe('makeRouteHooksSafe', () => { it('should work with JSX routes', () => { const onEnter = () => { throw new Error('Shouldn\'t call onEnter'); }; const getRoutes = makeRouteHooksSafe(() => { return ( <Route path="/" > <IndexRoute onEnter={onEnter} /> <Route path="1" /> <Route onEnter={onEnter}> <Route path="2" /> <Route path="3" onEnter={onEnter}/> </Route> </Route> ); }); const routes = getRoutes(null); expect(routes[0].indexRoute.onEnter).to.not.throw(Error); expect(routes[0].childRoutes[1].onEnter).to.not.throw(Error); expect(routes[0].childRoutes[1].childRoutes[1].onEnter).to.not.throw(Error); }); it('should work with JS routes', () => { const onEnter = () => { throw new Error('Shouldn\'t call onEnter'); }; const getRoutes = makeRouteHooksSafe(() => { return { path: '/', indexRoute: { onEnter: onEnter }, onEnter: onEnter, childRoutes: [ {path: '1'}, { onEnter: onEnter, childRoutes: [ {path: '2'}, {path: '3'} ], } ] }; }); const routes = getRoutes(null); expect(routes[0].indexRoute.onEnter).to.not.throw(Error); expect(routes[0].onEnter).to.not.throw(Error); expect(routes[0].childRoutes[1].onEnter).to.not.throw(Error); }); it('should call onEnter if store is initialised', (done) => { const store = { getState: () => {} }; const getRoutes = makeRouteHooksSafe(() => { return { onEnter: () => { done(); } }; }); const routes = getRoutes(store); routes[0].onEnter(); }); it('should call callback', (done) => { const getRoutes = makeRouteHooksSafe(() => { return { onEnter: (nextState, replaceState, cb) => {} // eslint-disable-line no-unused-vars }; }); const routes = getRoutes(null); routes[0].onEnter(null, null, done); }); it('should not call callback', () => { const callback = () => { throw new Error('Should not be called'); }; const getRoutes = makeRouteHooksSafe(() => { return { onEnter: (nextState, replaceState) => {} // eslint-disable-line no-unused-vars }; }); const routes = getRoutes(null); routes[0].onEnter(null, null, callback); }); });
examples/redux-saga/cancellable-counter/src/components/Counter.js
ioof-holdings/redux-subspace
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { INCREMENT, DECREMENT, INCREMENT_IF_ODD, INCREMENT_ASYNC, CANCEL_INCREMENT_ASYNC } from '../actionTypes' function Counter({counter, countdown, dispatch}) { const action = (type, value) => () => dispatch({type, value}) return ( <div> Clicked: {counter} times {' '} <button onClick={action(INCREMENT)}>+</button> {' '} <button onClick={action(DECREMENT)}>-</button> {' '} <button onClick={action(INCREMENT_IF_ODD)}>Increment if odd</button> {' '} <button onClick={countdown ? action(CANCEL_INCREMENT_ASYNC) : action(INCREMENT_ASYNC, 5)} style={{color: countdown ? 'red' : 'black'}}> {countdown ? `Cancel increment (${countdown})` : 'increment after 5s'} </button> </div> ) } Counter.propTypes = { // dispatch actions dispatch: PropTypes.func.isRequired, // state counter: PropTypes.number.isRequired, countdown: PropTypes.number.isRequired } function mapStateToProps(state) { return { counter: state.counter, countdown: state.countdown } } export default connect(mapStateToProps)(Counter)
src/App.js
omerak/webpack-react-less-mocha-css-modules
import React, { Component } from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import router from './router'; import 'ui/less/main.less'; export default class App extends Component { constructor() { super(); this.state = { currentRoute: { component: 'div' } }; this.routeChange = this.routeChange.bind(this); } componentDidMount() { router(this.routeChange); } routeChange(route) { this.setState({ currentRoute: route }, () => { this.forceUpdate(); }); } renderComponent(component, props) { return component && React.createElement(component, props); } render() { const { component, props } = this.state.currentRoute; return ( <div className="appWrapper"> <ReactCSSTransitionGroup transitionName="anim-route" transitionAppear={true} transitionAppearTimeout={1000} transitionEnterTimeout={1000} transitionLeaveTimeout={1000} > <div> {this.renderComponent(component, props)} </div> </ReactCSSTransitionGroup> </div> ); } }
docs/src/app/components/pages/components/DropDownMenu/Page.js
spiermar/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import dropDownMenuReadmeText from './README'; import DropDownMenuSimpleExample from './ExampleSimple'; import dropDownMenuSimpleExampleCode from '!raw!./ExampleSimple'; import DropDownMenuOpenImmediateExample from './ExampleOpenImmediate'; import dropDownMenuOpenImmediateExampleCode from '!raw!./ExampleOpenImmediate'; import DropDownMenuLongMenuExample from './ExampleLongMenu'; import dropDownMenuLongMenuExampleCode from '!raw!./ExampleLongMenu'; import DropDownMenuLabeledExample from './ExampleLabeled'; import dropDownMenuLabeledExampleCode from '!raw!./ExampleLabeled'; import dropDownMenuCode from '!raw!material-ui/DropDownMenu/DropDownMenu'; const descriptions = { simple: '`DropDownMenu` is implemented as a controlled component, with the current selection set through the ' + '`value` property.', openImmediate: 'With `openImmediately` property set, the menu will open on mount.', long: 'With the `maxHeight` property set, the menu will be scrollable if the number of items causes the height ' + 'to exceed this limit.', label: 'With a `label` applied to each `MenuItem`, `DropDownMenu` displays a complementary description ' + 'of the selected item.', }; const DropDownMenuPage = () => ( <div> <Title render={(previousTitle) => `Drop Down Menu - ${previousTitle}`} /> <MarkdownElement text={dropDownMenuReadmeText} /> <CodeExample title="Simple example" description={descriptions.simple} code={dropDownMenuSimpleExampleCode} > <DropDownMenuSimpleExample /> </CodeExample> <CodeExample title="Open Immediate example" description={descriptions.openImmediate} code={dropDownMenuOpenImmediateExampleCode} > <DropDownMenuOpenImmediateExample /> </CodeExample> <CodeExample title="Long example" description={descriptions.long} code={dropDownMenuLongMenuExampleCode} > <DropDownMenuLongMenuExample /> </CodeExample> <CodeExample title="Label example" description={descriptions.label} code={dropDownMenuLabeledExampleCode} > <DropDownMenuLabeledExample /> </CodeExample> <PropTypeDescription code={dropDownMenuCode} /> </div> ); export default DropDownMenuPage;
packages/neos-ui-editors/src/Editors/Boolean/index.js
neos/neos-ui
import React from 'react'; import PropTypes from 'prop-types'; import mergeClassNames from 'classnames'; import CheckBox from '@neos-project/react-ui-components/src/CheckBox/'; import Label from '@neos-project/react-ui-components/src/Label/'; import I18n from '@neos-project/neos-ui-i18n'; import style from './style.css'; // ToDo: Move into re-usable fn - Maybe into `util-helpers`? const toBoolean = val => { if (typeof val === 'string') { switch (true) { case val.toLowerCase() === 'true': case val.toLowerCase() === 'on': case val.toLowerCase() === '1': return true; default: return false; } } return Boolean(val); }; const defaultOptions = { disabled: false }; const BooleanEditor = props => { const {value, label, commit, options, className} = props; const finalOptions = Object.assign({}, defaultOptions, options); const wrapperClassName = mergeClassNames({ [className]: true, [style.boolean__wrapper]: true }); const finalClassName = mergeClassNames({ [style.boolean__disabled]: finalOptions.disabled, [style.boolean__label]: true }); return ( <div className={wrapperClassName}> <Label className={finalClassName}> <CheckBox isChecked={toBoolean(value)} disabled={finalOptions.disabled} onChange={commit}/> <span> <I18n id={label}/> {props.renderHelpIcon ? props.renderHelpIcon() : ''} </span> </Label> </div> ); }; BooleanEditor.propTypes = { className: PropTypes.string, identifier: PropTypes.string.isRequired, label: PropTypes.string.isRequired, value: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]), commit: PropTypes.func.isRequired, renderHelpIcon: PropTypes.func, options: PropTypes.object }; export default BooleanEditor;
src/shared/Home/Home.js
kashisau/enroute
/** * Home.js * */ import React from 'react'; import ArticleHero from '../ArticleHero/ArticleHero'; import HeroPicker from '../HeroPicker/HeroPicker'; import classnames from 'classnames'; import './Home.scss'; class Home extends React.Component { constructor(props) { super(props); this.state = { active: false, activeArticle: 0, nextArticle: undefined, sliding: false }; this.changeArticle = this.changeArticle.bind(this); this.initHeroTransition = this.initHeroTransition.bind(this); } /** * Switches to the article indicated. * @param {Number} index The index of the article to switch to. */ changeArticle(index) { if (this.state.activeArticle === index) return; this.setState({ activeArticle: index, sliding: true }); } initHeroTransition(e) { if ( ! e.target.classList.contains("ArticleHero")) return; this.setState({ sliding: false }); } render() { var articles = this.props.articles; return <div className={ classnames( "Home", "Home-article-" + this.state.activeArticle, { "is-sliding" : this.state.sliding } ) } onTransitionEnd={this.initHeroTransition} ref={ homeContainer => this.homeContainer = homeContainer }> {articles.map((article, key) => <ArticleHero article={article} key={key} active={this.state.activeArticle === key} />)} <HeroPicker changeArticle={this.changeArticle} articles={articles} activeArticle={this.state.activeArticle} /> </div> } } export default Home;
app/javascript/mastodon/features/compose/index.js
tri-star/mastodon
import React from 'react'; import ComposeFormContainer from './containers/compose_form_container'; import NavigationContainer from './containers/navigation_container'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import { mountCompose, unmountCompose } from '../../actions/compose'; import { Link } from 'react-router-dom'; import { injectIntl, defineMessages } from 'react-intl'; import SearchContainer from './containers/search_container'; import Motion from '../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import SearchResultsContainer from './containers/search_results_container'; import { changeComposing } from '../../actions/compose'; import { openModal } from 'mastodon/actions/modal'; import elephantUIPlane from '../../../images/elephant_ui_plane.svg'; import { mascot } from '../../initial_state'; import Icon from 'mastodon/components/icon'; import { logOut } from 'mastodon/utils/log_out'; const messages = defineMessages({ start: { id: 'getting_started.heading', defaultMessage: 'Getting started' }, home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' }, notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' }, public: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' }, community: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, logout: { id: 'navigation_bar.logout', defaultMessage: 'Logout' }, compose: { id: 'navigation_bar.compose', defaultMessage: 'Compose new toot' }, logoutMessage: { id: 'confirmations.logout.message', defaultMessage: 'Are you sure you want to log out?' }, logoutConfirm: { id: 'confirmations.logout.confirm', defaultMessage: 'Log out' }, }); const mapStateToProps = (state, ownProps) => ({ columns: state.getIn(['settings', 'columns']), showSearch: ownProps.multiColumn ? state.getIn(['search', 'submitted']) && !state.getIn(['search', 'hidden']) : ownProps.isSearchPage, }); export default @connect(mapStateToProps) @injectIntl class Compose extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, columns: ImmutablePropTypes.list.isRequired, multiColumn: PropTypes.bool, showSearch: PropTypes.bool, isSearchPage: PropTypes.bool, intl: PropTypes.object.isRequired, }; componentDidMount () { const { isSearchPage } = this.props; if (!isSearchPage) { this.props.dispatch(mountCompose()); } } componentWillUnmount () { const { isSearchPage } = this.props; if (!isSearchPage) { this.props.dispatch(unmountCompose()); } } handleLogoutClick = e => { const { dispatch, intl } = this.props; e.preventDefault(); e.stopPropagation(); dispatch(openModal('CONFIRM', { message: intl.formatMessage(messages.logoutMessage), confirm: intl.formatMessage(messages.logoutConfirm), onConfirm: () => logOut(), })); return false; } onFocus = () => { this.props.dispatch(changeComposing(true)); } onBlur = () => { this.props.dispatch(changeComposing(false)); } render () { const { multiColumn, showSearch, isSearchPage, intl } = this.props; let header = ''; if (multiColumn) { const { columns } = this.props; header = ( <nav className='drawer__header'> <Link to='/getting-started' className='drawer__tab' title={intl.formatMessage(messages.start)} aria-label={intl.formatMessage(messages.start)}><Icon id='bars' fixedWidth /></Link> {!columns.some(column => column.get('id') === 'HOME') && ( <Link to='/timelines/home' className='drawer__tab' title={intl.formatMessage(messages.home_timeline)} aria-label={intl.formatMessage(messages.home_timeline)}><Icon id='home' fixedWidth /></Link> )} {!columns.some(column => column.get('id') === 'NOTIFICATIONS') && ( <Link to='/notifications' className='drawer__tab' title={intl.formatMessage(messages.notifications)} aria-label={intl.formatMessage(messages.notifications)}><Icon id='bell' fixedWidth /></Link> )} {!columns.some(column => column.get('id') === 'COMMUNITY') && ( <Link to='/timelines/public/local' className='drawer__tab' title={intl.formatMessage(messages.community)} aria-label={intl.formatMessage(messages.community)}><Icon id='users' fixedWidth /></Link> )} {!columns.some(column => column.get('id') === 'PUBLIC') && ( <Link to='/timelines/public' className='drawer__tab' title={intl.formatMessage(messages.public)} aria-label={intl.formatMessage(messages.public)}><Icon id='globe' fixedWidth /></Link> )} <a href='/settings/preferences' className='drawer__tab' title={intl.formatMessage(messages.preferences)} aria-label={intl.formatMessage(messages.preferences)}><Icon id='cog' fixedWidth /></a> <a href='/auth/sign_out' className='drawer__tab' title={intl.formatMessage(messages.logout)} aria-label={intl.formatMessage(messages.logout)} onClick={this.handleLogoutClick}><Icon id='sign-out' fixedWidth /></a> </nav> ); } return ( <div className='drawer' role='region' aria-label={intl.formatMessage(messages.compose)}> {header} {(multiColumn || isSearchPage) && <SearchContainer /> } <div className='drawer__pager'> {!isSearchPage && <div className='drawer__inner' onFocus={this.onFocus}> <NavigationContainer onClose={this.onBlur} /> <ComposeFormContainer /> <div className='drawer__inner__mastodon'> <img alt='' draggable='false' src={mascot || elephantUIPlane} /> </div> </div>} <Motion defaultStyle={{ x: isSearchPage ? 0 : -100 }} style={{ x: spring(showSearch || isSearchPage ? 0 : -100, { stiffness: 210, damping: 20 }) }}> {({ x }) => ( <div className='drawer__inner darker' style={{ transform: `translateX(${x}%)`, visibility: x === -100 ? 'hidden' : 'visible' }}> <SearchResultsContainer /> </div> )} </Motion> </div> </div> ); } }
docs/tutorial/DO_NOT_TOUCH/09/src/index.js
idream3/cerebral
import React from 'react' import {render} from 'react-dom' import {Controller} from 'cerebral' import App from './components/App' import {Container} from 'cerebral/react' import Devtools from 'cerebral/devtools' import HttpProvider from 'cerebral-provider-http' import {set, debounce} from 'cerebral/operators' import {state, input, string} from 'cerebral/tags' import starsSum from './computeds/starsSum' const toastDebounce = debounce.shared() function showToast (message, ms, type = null) { return [ set(state`toast`, {type}), set(state`toast.message`, message), toastDebounce(ms), { continue: [ set(state`toast`, null) ], discard: [] } ] } function getRepo (repoName) { function get ({http, path}) { return http.get(`/repos/cerebral/${repoName}`) .then(response => path.success({data: response.result})) .catch(error => path.error({data: error.result})) } return get } const controller = Controller({ devtools: Devtools(), state: { title: 'Hello from Cerebral!', subTitle: 'Working on my state management', toast: null, repos: {}, starsSum: 0 }, signals: { buttonClicked: [ [ ...showToast('Loading data for repos', 2000), getRepo('cerebral'), { success: [set(state`repos.cerebral`, input`data`)], error: [] }, getRepo('addressbar'), { success: [set(state`repos.addressbar`, input`data`)], error: [] } ], ...showToast(string`The repos has a total star count of ${starsSum}`, 4000, 'success') ] }, providers: [ HttpProvider({ baseUrl: 'https://api.github.com' }) ] }) render(( <Container controller={controller}> <App /> </Container> ), document.querySelector('#root'))
login/__tests__/index.ios.js
bobmacneal/react-native-firebase-auth
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/components/tooltips/Tooltips.js
metasfresh/metasfresh-webui-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; /** * @file Class based component. * @module Filters * @extends Component */ class Tooltips extends Component { constructor(props) { super(props); this.state = { opacity: 0, }; } /** * @method componentDidMount * @summary ToDo: Describe the method. */ componentDidMount() { const { delay } = this.props; this.timeout = setTimeout( () => { this.setState({ opacity: 1, }); }, delay ? delay : 1000 ); } /** * @method componentWillUnmount * @summary ToDo: Describe the method. */ componentWillUnmount() { clearTimeout(this.timeout); } /** * @method render * @summary ToDo: Describe the method. */ render() { const { name, action, type, extraClass, tooltipOnFirstlevelPositionLeft, className, } = this.props; const cx = classNames( 'tooltip-wrapp', { [`tooltip-${type}`]: type }, { [`${extraClass}`]: extraClass }, { [`${className}`]: className } ); const { opacity } = this.state; return ( <div style={{ opacity: opacity }}> <div className={cx} style={{ left: tooltipOnFirstlevelPositionLeft + 'px' }} > <div className="tooltip-shortcut">{name}</div> <div className="tooltip-name">{action}</div> </div> </div> ); } } /** * @typedef {object} Props Component props * @prop {*} action * @prop {*} className * @prop {*} delay * @prop {*} extraClass * @prop {*} name * @prop {*} tooltipOnFirstlevelPositionLeft * @prop {*} type */ Tooltips.propTypes = { action: PropTypes.any, className: PropTypes.any, delay: PropTypes.any, extraClass: PropTypes.any, name: PropTypes.any, tooltipOnFirstlevelPositionLeft: PropTypes.any, type: PropTypes.any, }; export default Tooltips;
client/src/containers/AssetAdmin/AssetAdminRouter.js
silverstripe/silverstripe-asset-admin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import AssetAdmin from 'containers/AssetAdmin/AssetAdmin'; import { decodeQuery } from 'lib/DataFormat'; import qs from 'qs'; import CONSTANTS from 'constants/index'; import configShape from 'lib/configShape'; const sectionConfigKey = 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin'; const actions = Object.keys(CONSTANTS.ACTIONS).map((key) => CONSTANTS.ACTIONS[key]); /** * Build URL from raw components * * @param {String} base * @param {Number} folderId * @param {Number} fileId * @param {Object} query * @param {String} action * @return {String} */ function buildUrl({ base, folderId, fileId, query, action }) { if (action && actions.indexOf(action) === -1) { throw new Error(`Invalid action provided: ${action}`); } let url = null; if (fileId) { url = `${base}/show/${folderId}/${CONSTANTS.ACTIONS.EDIT_FILE}/${fileId}`; } else if (folderId) { url = `${base}/show/${folderId}`; } else { url = `${base}/`; } if (action === CONSTANTS.ACTIONS.CREATE_FOLDER) { url = `${base}/show/${folderId || 0}/${action}`; } const hasQuery = query && Object.keys(query).length > 0; if (hasQuery) { url = `${url}?${qs.stringify(query)}`; } return url; } class AssetAdminRouter extends Component { constructor(props) { super(props); this.handleBrowse = this.handleBrowse.bind(this); this.handleReplaceUrl = this.handleReplaceUrl.bind(this); this.getUrl = this.getUrl.bind(this); } /** * Generates the Url for a given folder and file ID. * * @param {Number} folderId * @param {Number} fileId * @param {Object} query * @param {String} action * @returns {String} */ getUrl(folderId = 0, fileId = null, query = {}, action = CONSTANTS.ACTIONS.EDIT_FILE) { const newFolderId = parseInt(folderId || 0, 10); const newFileId = parseInt(fileId || 0, 10); // Remove pagination selector if already on first page, or changing folder const hasFolderChanged = newFolderId !== this.getFolderId(); const newQuery = Object.assign({}, query); if (hasFolderChanged || newQuery.page <= 1) { delete newQuery.page; } return buildUrl({ base: `/${this.props.sectionConfig.url}`, folderId: newFolderId, fileId: newFileId, query: newQuery, action, }); } /** * @return {Number} Folder ID being viewed */ getFolderId() { if (this.props.match.params && this.props.match.params.folderId) { return parseInt(this.props.match.params.folderId, 10); } return 0; } /** * @return {Number} File ID being viewed */ getFileId() { if (this.props.match.params && this.props.match.params.fileId) { return parseInt(this.props.match.params.fileId, 10); } return 0; } getViewAction() { if (this.props.match.params && this.props.match.params.viewAction) { return this.props.match.params.viewAction; } return CONSTANTS.ACTIONS.EDIT_FILE; } /** * Generates the properties for this section * * @returns {object} */ getSectionProps() { return { sectionConfig: this.props.sectionConfig, type: 'admin', folderId: this.getFolderId(), viewAction: this.getViewAction(), fileId: this.getFileId(), query: this.getQuery(), getUrl: this.getUrl, onBrowse: this.handleBrowse, onReplaceUrl: this.handleReplaceUrl, }; } /** * Get decoded query object * * @returns {Object} */ getQuery() { return decodeQuery(this.props.location.search); } /** * Handle browsing with the router. * * @param {number} [folderId] * @param {number} [fileId] * @param {object} [query] * @param {string} [action] */ handleBrowse(folderId, fileId, query, action) { const pathname = this.getUrl(folderId, fileId, query, action); this.props.history.push(pathname); } /** * Handle browsing with the router but does not add to history, useful for * cases when the user is redirected to a correct url. * * @param {number} [folderId] * @param {number} [fileId] * @param {object} [query] * @param {string} [action] */ handleReplaceUrl(folderId, fileId, query, action) { const pathname = this.getUrl(folderId, fileId, query, action); this.props.history.replace(pathname); } render() { if (!this.props.sectionConfig) { return null; } return ( <AssetAdmin {...this.getSectionProps()} /> ); } } AssetAdminRouter.propTypes = { sectionConfig: configShape, location: PropTypes.shape({ pathname: PropTypes.string, query: PropTypes.object, search: PropTypes.string, }), params: PropTypes.object, router: PropTypes.object, }; function mapStateToProps(state) { const sectionConfig = state.config.sections.find((section) => section.name === sectionConfigKey); return { sectionConfig, }; } export { AssetAdminRouter as Component, buildUrl }; export default withRouter(connect(mapStateToProps)(AssetAdminRouter));
src/Hidden/HiddenJs.spec.js
dsslimshaddy/material-ui
// @flow weak /* eslint-disable no-loop-func */ import React from 'react'; import { assert } from 'chai'; import { createShallow } from '../test-utils'; import HiddenJs from './HiddenJs'; import type { Breakpoint } from '../styles/breakpoints'; import Typography from '../Typography'; describe('<HiddenJs />', () => { let shallow; before(() => { shallow = createShallow({ untilSelector: 'EventListener', }); }); function resolvePropName(upDownOnly, breakpoint) { if (upDownOnly === 'only') { return 'only'; } return `${breakpoint}${upDownOnly}`; } function isHidden( hiddenBreakpoints: Array<*>, upDownOnly: 'Up' | 'Down' | 'only', width: Breakpoint, ) { hiddenBreakpoints.forEach(breakpoint => { const prop = resolvePropName(upDownOnly, breakpoint); const descriptions = { Up: `${prop} is hidden for width: ${width} >= ${breakpoint}`, Down: `${prop} is hidden for width: ${width} <= ${breakpoint}`, only: `${prop} is hidden for width: ${width} === ${breakpoint}`, }; it(descriptions[upDownOnly], () => { const props = { width, [prop]: breakpoint }; // children let wrapper = shallow( <HiddenJs component="div" {...props}> foo </HiddenJs>, ); assert.isNull(wrapper.type(), 'should render null'); // element wrapper = shallow( <HiddenJs component={<Typography>foo</Typography>} {...props}> foo </HiddenJs>, ); assert.isNull(wrapper.type(), 'should render null'); }); }); } function isVisible( visibleBreakpoints: Array<*>, upDownOnly: 'Up' | 'Down' | 'only', width: Breakpoint, ) { visibleBreakpoints.forEach(breakpoint => { const prop = resolvePropName(upDownOnly, breakpoint); const descriptions = { Up: `${prop} is visible for width: ${width} < ${breakpoint}`, Down: `${prop} is visible for width: ${width} > ${breakpoint}`, only: `${prop} is visible for width: ${width} !== ${breakpoint}`, }; it(descriptions[upDownOnly], () => { const props = { width, [prop]: breakpoint }; // children let wrapper = shallow( <HiddenJs {...props}> <div>foo</div> </HiddenJs>, ); assert.isNotNull(wrapper.type(), 'should render'); assert.strictEqual(wrapper.name(), 'div'); assert.strictEqual(wrapper.first().text(), 'foo', 'should render children'); // element wrapper = shallow( <HiddenJs {...props}> <Typography>foo</Typography> </HiddenJs>, ); assert.isNotNull(wrapper.type(), 'should render'); assert.strictEqual(wrapper.name(), 'withStyles(Typography)'); }); }); } describe('screen width: xs', () => { describe('up', () => { isHidden(['xs'], 'Up', 'xs'); isVisible(['sm', 'md', 'lg', 'xl'], 'Up', 'xs'); }); describe('down', () => { isHidden(['xs', 'sm', 'md', 'lg', 'xl'], 'Down', 'xs'); }); describe('only', () => { isHidden(['xs', ['xs', 'xl']], 'only', 'xs'); isVisible(['sm', 'md', 'lg', 'xl', ['sm', 'md', 'lg', 'xl']], 'only', 'xs'); }); }); describe('screen width: sm', () => { describe('up', () => { isHidden(['xs', 'sm'], 'Up', 'sm'); isVisible(['md', 'lg', 'xl'], 'Up', 'sm'); }); describe('down', () => { isHidden(['sm', 'md', 'lg', 'xl'], 'Down', 'sm'); isVisible(['xs'], 'Down', 'sm'); }); describe('only', () => { isHidden(['sm', ['sm', 'md']], 'only', 'sm'); isVisible(['xs', 'md', 'lg', 'xl', ['xs', 'md', 'lg', 'xl']], 'only', 'sm'); }); }); describe('screen width: md', () => { describe('up', () => { isHidden(['xs', 'sm', 'md'], 'Up', 'md'); isVisible(['lg', 'xl'], 'Up', 'md'); }); describe('down', () => { isHidden(['md', 'lg', 'xl'], 'Down', 'md'); isVisible(['xs', 'sm'], 'Down', 'md'); }); describe('only', () => { isHidden(['md', ['md', 'lg']], 'only', 'md'); isVisible(['xs', 'sm', 'lg', 'xl', ['xs', 'sm', 'lg', 'xl']], 'only', 'md'); }); }); describe('screen width: lg', () => { describe('up', () => { isHidden(['xs', 'sm', 'md', 'lg'], 'Up', 'lg'); isVisible(['xl'], 'Up', 'lg'); }); describe('down', () => { isHidden(['lg', 'xl'], 'Down', 'lg'); isVisible(['xs', 'sm', 'md'], 'Down', 'lg'); }); describe('only', () => { isHidden(['lg', ['lg', 'xl']], 'only', 'lg'); isVisible(['xs', 'sm', 'md', 'xl', ['xs', 'sm', 'md', 'xl']], 'only', 'lg'); }); }); describe('screen width: xl', () => { describe('up', () => { isHidden(['xs', 'sm', 'md', 'lg', 'xl'], 'Up', 'xl'); }); describe('down', () => { isHidden(['xl'], 'Down', 'xl'); isVisible(['xs', 'sm', 'md', 'lg'], 'Down', 'xl'); }); describe('only', () => { isHidden(['xl', ['xl', 'xs']], 'only', 'xl'); isVisible(['xs', 'sm', 'md', 'lg', ['xs', 'sm', 'md', 'lg']], 'only', 'xl'); }); }); });
app/ecoModules/forms/static-input.js
aoshmyanskaya/tko
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; class StaticInput extends Component { render() { const formControl = <FormControl.Static> {this.props.value} </FormControl.Static>; return ( <FormGroup> <ControlLabel className={this.props.labelClass}>{this.props.label}</ControlLabel> {!this.props.horizontal && formControl} {this.props.horizontal && <div className={this.props.wrapClass}> {formControl} </div> } </FormGroup> ) } } StaticInput.defaultProps = { horizontal: false, }; StaticInput.propTypes = { horizontal: PropTypes.bool, wrapClass: PropTypes.string, labelClass: PropTypes.string, label: PropTypes.string, }; export default StaticInput;
src/router.js
mansters/fetch-request
import React from 'react'; import { Router, Route } from 'dva/router'; import IndexPage from './routes/IndexPage'; function RouterConfig ( { history } ) { return ( <Router history={ history }> <Route path="/" component={ IndexPage }/> </Router> ); } export default RouterConfig;
app/javascript/mastodon/components/avatar_overlay.js
alarky/mastodon
import React from 'react'; import PropTypes from 'prop-types'; export default class AvatarOverlay extends React.PureComponent { static propTypes = { staticSrc: PropTypes.string.isRequired, overlaySrc: PropTypes.string.isRequired, }; render() { const { staticSrc, overlaySrc } = this.props; const baseStyle = { backgroundImage: `url(${staticSrc})`, }; const overlayStyle = { backgroundImage: `url(${overlaySrc})`, }; return ( <div className='account__avatar-overlay'> <div className='account__avatar-overlay-base' style={baseStyle} /> <div className='account__avatar-overlay-overlay' style={overlayStyle} /> </div> ); } }
stories/shared/Spinner.stories.js
buildkite/frontend
/* global module */ import React from 'react'; import { storiesOf } from '@storybook/react'; import { boolean, number } from '@storybook/addon-knobs'; import Spinner from '../../app/components/shared/Spinner'; storiesOf('Spinner', module) .add('Standard', () => <Spinner color={boolean('Color', true)} size={number('Size', 20)} />) .add('Mono', () => <Spinner color={boolean('Color', false)} size={number('Size', 20)} />);
src/main.js
gravitron07/brentayersV6
/** * App entry point */ // Polyfill import 'babel-polyfill'; // Libraries import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; // Routes import Routes from './common/components/Routes'; // Base styling import './common/base.css'; // ID of the DOM element to mount app on const DOM_APP_EL_ID = 'app'; // Render the router ReactDOM.render(( <Router history={browserHistory}> {Routes} </Router> ), document.getElementById(DOM_APP_EL_ID));
src/mongostick/frontend/src/screens/Settings.js
RockingRolli/mongostick
import React from 'react' import { Menu, Icon, Row, Col } from 'antd' import { Link, Route, withRouter } from 'react-router-dom' import { TransitionGroup } from 'react-transition-group' import OperationSettings from './OperationSettings' import SettingsHome from './SettingsHome' class Settings extends React.Component { render() { const { location } = this.props; const currentPath = location.pathname return ( <Row gutter={16}> <Col xs={4}> <Menu mode="inline" defaultSelectedKeys={[currentPath]}> <Menu.Item key="/settings/operations"> <Link to="/settings/operations"><Icon type="rocket" /> Operations</Link> </Menu.Item> </Menu> </Col> <Col xs={20}> <Route render={({ location }) => ( <TransitionGroup> <Route key='settings_home' exact path='/settings' component={SettingsHome} /> <Route key='operations_settings' exact path='/settings/operations' component={OperationSettings} /> </TransitionGroup> )} /> </Col> </Row> ) } } export default withRouter(Settings)
src/index.js
panlw/react-lab
import './theme'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import App from './app/app'; import { configStore, getDevTools } from './lib/createStore'; const store = configStore(); const DevTools = getDevTools(); render( <Provider store={store}> <div> <App renderOnly /> <DevTools /> </div> </Provider>, document.getElementById('root') );
packages/material-ui-icons/src/SmokingRooms.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SmokingRooms = props => <SvgIcon {...props}> <path d="M2 16h15v3H2zm18.5 0H22v3h-1.5zM18 16h1.5v3H18zm.85-8.27c.62-.61 1-1.45 1-2.38C19.85 3.5 18.35 2 16.5 2v1.5c1.02 0 1.85.83 1.85 1.85S17.52 7.2 16.5 7.2v1.5c2.24 0 4 1.83 4 4.07V15H22v-2.24c0-2.22-1.28-4.14-3.15-5.03zm-2.82 2.47H14.5c-1.02 0-1.85-.98-1.85-2s.83-1.75 1.85-1.75v-1.5c-1.85 0-3.35 1.5-3.35 3.35s1.5 3.35 3.35 3.35h1.53c1.05 0 1.97.74 1.97 2.05V15h1.5v-1.64c0-1.81-1.6-3.16-3.47-3.16z" /> </SvgIcon>; SmokingRooms = pure(SmokingRooms); SmokingRooms.muiName = 'SvgIcon'; export default SmokingRooms;
index.android.js
octopitus/RNAnimatedBarChart
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import ChartContainer from './src/ChartContainer' export default class RNBarChart extends Component { render() { return <ChartContainer />; } } AppRegistry.registerComponent('RNBarChart', () => RNBarChart);
app/js/typer.js
mattiaslundberg/typer
import React from 'react' import Input from './components/input' import StatusDisplay from './components/status-display' import ResultDisplay from './components/result-display' export default class Typer extends React.Component { constructor(props) { super(props) this.state = { typedSequence: "", charsTyped: 0, } this.onType = this.onType.bind(this) } onType(evt) { if ( evt.keyCode == 16 || evt.keyCode == 9 || evt.getModifierState("Fn") || evt.getModifierState("Hyper") || evt.getModifierState("OS") || evt.getModifierState("Super") || evt.getModifierState("Win") ) { evt.preventDefault() return } if (this.state.charsTyped == 0) { this.setState({startedTyping: new Date().getTime()}) } if (evt.target.value == this.props.fullText.join("") && !this.state.finished) { this.setState({finished: new Date().getTime()}) } this.setState({ typedSequence: evt.target.value, charsTyped: this.state.charsTyped + 1 }) } render() { if (this.state.finished) { const milliseconds = this.state.finished - this.state.startedTyping const writtenChars = this.props.fullText.length return ( <div className="typer"> <ResultDisplay time={milliseconds} textLength={writtenChars} onNewClick={this.props.onNewClick} /> </div> ) } return ( <div className="typer"> <StatusDisplay typedSequence={this.state.typedSequence} fullText={this.props.fullText} startTime={this.state.startedTyping} /> <Input onType={this.onType} /> </div> ) } }
src/components/stories/Icon.js
radekzz/netlify-cms-test
import React from 'react'; import { Icon } from '../UI'; import { storiesOf } from '@kadira/storybook'; const style = { width: 600, margin: 20, fontSize: 30 }; storiesOf('Icon', module) .add('Default View', () => ( <div style={style}> <Icon type="bold"/> <Icon type="italic"/> <Icon type="list"/> <Icon type="font"/> <Icon type="text-height"/> <Icon type="text-width"/> <Icon type="align-left"/> <Icon type="align-center"/> <Icon type="align-right"/> <Icon type="align-justify"/> <Icon type="indent-left"/> <Icon type="indent-right"/> <Icon type="list-bullet"/> <Icon type="list-numbered"/> <Icon type="strike"/> <Icon type="underline"/> <Icon type="table"/> <Icon type="superscript"/> <Icon type="subscript"/> <Icon type="header"/> <Icon type="h1"/> <Icon type="h2"/> <Icon type="paragraph"/> <Icon type="link"/> <Icon type="unlink"/> <Icon type="quote-left"/> <Icon type="quote-right"/> <Icon type="code"/> <Icon type="picture"/> <Icon type="video"/> <Icon type="note"/> <Icon type="note-beamed"/> <Icon type="music"/> <Icon type="search"/> <Icon type="flashlight"/> <Icon type="mail"/> <Icon type="heart"/> <Icon type="heart-empty"/> <Icon type="star"/> <Icon type="star-empty"/> <Icon type="user"/> <Icon type="users"/> <Icon type="user-add"/> <Icon type="video"/> <Icon type="picture"/> <Icon type="camera"/> <Icon type="layout"/> <Icon type="menu"/> <Icon type="check"/> <Icon type="cancel"/> <Icon type="cancel-circled"/> <Icon type="cancel-squared"/> <Icon type="plus"/> <Icon type="plus-circled"/> <Icon type="plus-squared"/> <Icon type="minus"/> <Icon type="minus-circled"/> <Icon type="minus-squared"/> <Icon type="help"/> <Icon type="help-circled"/> <Icon type="info"/> <Icon type="info-circled"/> <Icon type="back"/> <Icon type="home"/> <Icon type="link-alt"/> <Icon type="attach"/> <Icon type="lock"/> <Icon type="lock-open"/> <Icon type="eye"/> <Icon type="tag"/> <Icon type="bookmark"/> <Icon type="bookmarks"/> <Icon type="flag"/> <Icon type="thumbs-up"/> <Icon type="thumbs-down"/> <Icon type="download"/> <Icon type="upload"/> <Icon type="upload-cloud"/> <Icon type="reply"/> <Icon type="reply-all"/> <Icon type="forward"/> <Icon type="quote"/> <Icon type="code-alt"/> <Icon type="export"/> <Icon type="pencil"/> <Icon type="feather"/> <Icon type="print"/> <Icon type="retweet"/> <Icon type="keyboard"/> <Icon type="comment"/> <Icon type="chat"/> <Icon type="bell"/> <Icon type="attention"/> <Icon type="alert"/> <Icon type="vcard"/> <Icon type="address"/> <Icon type="location"/> <Icon type="map"/> <Icon type="direction"/> <Icon type="compass"/> <Icon type="cup"/> <Icon type="trash"/> <Icon type="doc"/> <Icon type="docs"/> <Icon type="doc-landscape"/> <Icon type="doc-text"/> <Icon type="doc-text-inv"/> <Icon type="newspaper"/> <Icon type="book-open"/> <Icon type="book"/> <Icon type="folder"/> <Icon type="archive"/> <Icon type="box"/> <Icon type="rss"/> <Icon type="phone"/> <Icon type="cog"/> <Icon type="tools"/> <Icon type="share"/> <Icon type="shareable"/> <Icon type="basket"/> <Icon type="bag"/> <Icon type="calendar"/> <Icon type="login"/> <Icon type="logout"/> <Icon type="mic"/> <Icon type="mute"/> <Icon type="sound"/> <Icon type="volume"/> <Icon type="clock"/> <Icon type="hourglass"/> <Icon type="lamp"/> <Icon type="light-down"/> <Icon type="light-up"/> <Icon type="adjust"/> <Icon type="block"/> <Icon type="resize-full"/> <Icon type="resize-small"/> <Icon type="popup"/> <Icon type="publish"/> <Icon type="window"/> <Icon type="arrow-combo"/> <Icon type="down-circled"/> <Icon type="left-circled"/> <Icon type="right-circled"/> <Icon type="up-circled"/> <Icon type="down-open"/> <Icon type="left-open"/> <Icon type="right-open"/> <Icon type="up-open"/> <Icon type="down-open-mini"/> <Icon type="left-open-mini"/> <Icon type="right-open-mini"/> <Icon type="up-open-mini"/> <Icon type="down-open-big"/> <Icon type="left-open-big"/> <Icon type="right-open-big"/> <Icon type="up-open-big"/> <Icon type="down"/> <Icon type="left"/> <Icon type="right"/> <Icon type="up"/> <Icon type="down-dir"/> <Icon type="left-dir"/> <Icon type="right-dir"/> <Icon type="up-dir"/> <Icon type="down-bold"/> <Icon type="left-bold"/> <Icon type="right-bold"/> <Icon type="up-bold"/> <Icon type="down-thin"/> <Icon type="left-thin"/> <Icon type="right-thin"/> <Icon type="up-thin"/> <Icon type="ccw"/> <Icon type="cw"/> <Icon type="arrows-ccw"/> <Icon type="level-down"/> <Icon type="level-up"/> <Icon type="shuffle"/> <Icon type="loop"/> <Icon type="switch"/> <Icon type="play"/> <Icon type="stop"/> <Icon type="pause"/> <Icon type="record"/> <Icon type="to-end"/> <Icon type="to-start"/> <Icon type="fast-forward"/> <Icon type="fast-backward"/> <Icon type="progress-0"/> <Icon type="progress-1"/> <Icon type="progress-2"/> <Icon type="progress-3"/> <Icon type="target"/> <Icon type="palette"/> <Icon type="list"/> <Icon type="list-add"/> <Icon type="signal"/> <Icon type="trophy"/> <Icon type="battery"/> <Icon type="back-in-time"/> <Icon type="monitor"/> <Icon type="mobile"/> <Icon type="network"/> <Icon type="cd"/> <Icon type="inbox"/> <Icon type="install"/> <Icon type="globe"/> <Icon type="cloud"/> <Icon type="cloud-thunder"/> <Icon type="flash"/> <Icon type="moon"/> <Icon type="flight"/> <Icon type="paper-plane"/> <Icon type="leaf"/> <Icon type="lifebuoy"/> <Icon type="mouse"/> <Icon type="briefcase"/> <Icon type="suitcase"/> <Icon type="dot"/> <Icon type="dot-2"/> <Icon type="dot-3"/> <Icon type="brush"/> <Icon type="magnet"/> <Icon type="infinity"/> <Icon type="erase"/> <Icon type="chart-pie"/> <Icon type="chart-line"/> <Icon type="chart-bar"/> <Icon type="chart-area"/> <Icon type="tape"/> <Icon type="graduation-cap"/> <Icon type="language"/> <Icon type="ticket"/> <Icon type="water"/> <Icon type="droplet"/> <Icon type="air"/> <Icon type="credit-card"/> <Icon type="floppy"/> <Icon type="clipboard"/> <Icon type="megaphone"/> <Icon type="database"/> <Icon type="drive"/> <Icon type="bucket"/> <Icon type="thermometer"/> <Icon type="key"/> <Icon type="flow-cascade"/> <Icon type="flow-branch"/> <Icon type="flow-tree"/> <Icon type="flow-line"/> <Icon type="flow-parallel"/> <Icon type="rocket"/> <Icon type="gauge"/> <Icon type="traffic-cone"/> <Icon type="cc"/> <Icon type="cc-by"/> <Icon type="cc-nc"/> <Icon type="cc-nc-eu"/> <Icon type="cc-nc-jp"/> <Icon type="cc-sa"/> <Icon type="cc-nd"/> <Icon type="cc-pd"/> <Icon type="cc-zero"/> <Icon type="cc-share"/> <Icon type="cc-remix"/> <Icon type="github"/> <Icon type="github-circled"/> <Icon type="flickr"/> <Icon type="flickr-circled"/> <Icon type="vimeo"/> <Icon type="vimeo-circled"/> <Icon type="twitter"/> <Icon type="twitter-circled"/> <Icon type="facebook"/> <Icon type="facebook-circled"/> <Icon type="facebook-squared"/> <Icon type="gplus"/> <Icon type="gplus-circled"/> <Icon type="pinterest"/> <Icon type="pinterest-circled"/> <Icon type="tumblr"/> <Icon type="tumblr-circled"/> <Icon type="linkedin"/> <Icon type="linkedin-circled"/> <Icon type="dribbble"/> <Icon type="dribbble-circled"/> <Icon type="stumbleupon"/> <Icon type="stumbleupon-circled"/> <Icon type="lastfm"/> <Icon type="lastfm-circled"/> <Icon type="rdio"/> <Icon type="rdio-circled"/> <Icon type="spotify"/> <Icon type="spotify-circled"/> <Icon type="qq"/> <Icon type="instagrem"/> <Icon type="dropbox"/> <Icon type="evernote"/> <Icon type="flattr"/> <Icon type="skype"/> <Icon type="skype-circled"/> <Icon type="renren"/> <Icon type="sina-weibo"/> <Icon type="paypal"/> <Icon type="picasa"/> <Icon type="soundcloud"/> <Icon type="mixi"/> <Icon type="behance"/> <Icon type="google-circles"/> <Icon type="vkontakte"/> <Icon type="smashing"/> <Icon type="sweden"/> <Icon type="db-shape"/> <Icon type="logo-db"/> </div> ));
app/app/pages/fetch/component.js
snowkeeper/systemjs-reactjs-hot-reload
import React from 'react'; import Fetch from './fetch'; import Debug from 'debug' let debug = Debug('lodge:app:pages:fetch:component'); export default (page, returnType, options) => { class GenericFetch extends React.Component { constructor(props) { super(props) this.displayName = 'Generic ' + page this.state = { html: props.html || props.response } this.props = props } render() { debug('render fetch component', this.state, page); if('function' === typeof this.state.html) { return (<div> <this.state.html { ...this.props } /> </div>); } else { return (<div dangerouslySetInnerHTML={{ __html: this.state.html }} />) } } } return Fetch(page, GenericFetch, returnType, options) }
node_modules/rc-hammerjs/es/Hammer.js
prodigalyijun/demo-by-antd
import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; // https://github.com/hammerjs/hammer.js/issues/930 // https://github.com/JedWatson/react-hammerjs/issues/14 // wait to see if we need the condition require hack for ssr import Hammer from 'hammerjs'; var privateProps = { children: true, direction: true, options: true, recognizeWith: true, vertical: true }; /** * Hammer Component * ================ */ var handlerToEvent = { action: 'tap press', onDoubleTap: 'doubletap', onPan: 'pan', onPanCancel: 'pancancel', onPanEnd: 'panend', onPanStart: 'panstart', onPinch: 'pinch', onPinchCancel: 'pinchcancel', onPinchEnd: 'pinchend', onPinchIn: 'pinchin', onPinchOut: 'pinchout', onPinchStart: 'pinchstart', onPress: 'press', onPressUp: 'pressup', onRotate: 'rotate', onRotateCancel: 'rotatecancel', onRotateEnd: 'rotateend', onRotateMove: 'rotatemove', onRotateStart: 'rotatestart', onSwipe: 'swipe', onSwipeRight: 'swiperight', onSwipeLeft: 'swipeleft', onSwipeUp: 'swipeup', onSwipeDown: 'swipedown', onTap: 'tap' }; Object.keys(handlerToEvent).forEach(function (i) { privateProps[i] = true; }); function updateHammer(hammer, props) { var _this = this; if (props.hasOwnProperty('vertical')) { console.warn('vertical is deprecated, please use `direction` instead'); } var directionProp = props.direction; if (directionProp || props.hasOwnProperty('vertical')) { var direction = directionProp ? directionProp : props.vertical ? 'DIRECTION_ALL' : 'DIRECTION_HORIZONTAL'; hammer.get('pan').set({ direction: Hammer[direction] }); hammer.get('swipe').set({ direction: Hammer[direction] }); } if (props.options) { Object.keys(props.options).forEach(function (option) { if (option === 'recognizers') { Object.keys(props.options.recognizers).forEach(function (gesture) { var recognizer = hammer.get(gesture); recognizer.set(props.options.recognizers[gesture]); if (props.options.recognizers[gesture].requireFailure) { recognizer.requireFailure(props.options.recognizers[gesture].requireFailure); } }, _this); } else { var key = option; var optionObj = {}; optionObj[key] = props.options[option]; hammer.set(optionObj); } }, this); } if (props.recognizeWith) { Object.keys(props.recognizeWith).forEach(function (gesture) { var recognizer = hammer.get(gesture); recognizer.recognizeWith(props.recognizeWith[gesture]); }, this); } Object.keys(props).forEach(function (p) { var e = handlerToEvent[p]; if (e) { hammer.off(e); hammer.on(e, props[p]); } }); } var HammerComponent = function (_React$Component) { _inherits(HammerComponent, _React$Component); function HammerComponent() { _classCallCheck(this, HammerComponent); return _possibleConstructorReturn(this, (HammerComponent.__proto__ || Object.getPrototypeOf(HammerComponent)).apply(this, arguments)); } _createClass(HammerComponent, [{ key: 'componentDidMount', value: function componentDidMount() { this.hammer = new Hammer(ReactDOM.findDOMNode(this)); updateHammer(this.hammer, this.props); } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { if (this.hammer) { updateHammer(this.hammer, this.props); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.hammer) { this.hammer.stop(); this.hammer.destroy(); } this.hammer = null; } }, { key: 'render', value: function render() { var props = {}; Object.keys(this.props).forEach(function (i) { if (!privateProps[i]) { props[i] = this.props[i]; } }, this); // Reuse the child provided // This makes it flexible to use whatever element is wanted (div, ul, etc) return React.cloneElement(React.Children.only(this.props.children), props); } }]); return HammerComponent; }(React.Component); HammerComponent.displayName = 'Hammer'; HammerComponent.propTypes = { className: PropTypes.string }; export default HammerComponent;
node_modules/react-router/modules/RouteUtils.js
Maxwelloff/react-football
import React from 'react' import warning from './routerWarning' function isValidChild(object) { return object == null || React.isValidElement(object) } export function isReactChildren(object) { return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild)) } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent' for (const propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { const error = propTypes[propName](props, propName, componentName) /* istanbul ignore if: error logging */ if (error instanceof Error) warning(false, error.message) } } } function createRoute(defaultProps, props) { return { ...defaultProps, ...props } } export function createRouteFromReactElement(element) { const type = element.type const route = createRoute(type.defaultProps, element.props) if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route) if (route.children) { const childRoutes = createRoutesFromReactChildren(route.children, route) if (childRoutes.length) route.childRoutes = childRoutes delete route.children } return route } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { const routes = [] React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { const route = element.type.createRouteFromReactElement(element, parentRoute) if (route) routes.push(route) } else { routes.push(createRouteFromReactElement(element)) } } }) return routes } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes) } else if (routes && !Array.isArray(routes)) { routes = [ routes ] } return routes }
src/development/index.js
RedgooseDev/react-photo-layout-editor
import React from 'react'; import ReactDOM from 'react-dom'; import PhotoLayoutEditor from '../PhotoLayoutEditor'; import * as util from './util'; import '../PhotoLayoutEditor/style/app.scss'; import './index.scss'; class App extends React.Component { constructor(props) { super(props); this._photoLayoutEditor = null; } action(id, value) { let result = null; let keys = []; let preference = null; switch(id) { // SIDE case 'side.add': this._photoLayoutEditor.api.side.add(util.pickImages(3)); break; case 'side.selection': result = this._photoLayoutEditor.api.side.selection([0,2,4,6,8,10]); break; case 'side.select': this._photoLayoutEditor.api.side.select({ 0: { active: false }, 1: { active: true }, 2: { active: false }, 3: { active: true } }); break; case 'side.toggleSelectAll': this._photoLayoutEditor.api.side.toggleSelectAll(); break; case 'side.selectedRemoveItems': keys = this._photoLayoutEditor.api.side.getKeys('selected'); this._photoLayoutEditor.api.side.remove(keys); break; case 'side.clear': this._photoLayoutEditor.api.side.clear(); break; case 'side.attachToGrid': keys = this._photoLayoutEditor.api.side.getKeys('selected'); this._photoLayoutEditor.api.side.attachToGrid(keys); break; case 'side.upload': this._photoLayoutEditor.api.side.upload(value.target.files); break; case 'side.getItems': keys = this._photoLayoutEditor.api.side.getKeys('selected'); result = this._photoLayoutEditor.api.side.getItems(keys); console.log('side.getItems', result); break; case 'side.getImages': keys = this._photoLayoutEditor.api.side.getKeys('selected'); result = this._photoLayoutEditor.api.side.getImages(keys); console.log('side.getImages', result); break; // GRID case 'grid.getKeys': //result = this._photoLayoutEditor.api.grid.getKeys('all'); result = this._photoLayoutEditor.api.grid.getKeys('selected'); //result = this._photoLayoutEditor.api.grid.getKeys('value', [0,2,4,6,8]); console.log('get keys:', result); break; case 'grid.getBlocks': //result = this._photoLayoutEditor.api.grid.getBlocks('all'); result = this._photoLayoutEditor.api.grid.getBlocks('selected'); //result = this._photoLayoutEditor.api.grid.getBlocks('value', [0,2,4,6,8]); console.log('get blocks:', result); break; case 'grid.shuffle': this._photoLayoutEditor.api.grid.shuffle({ w: 3, h: 3 }); break; case 'grid.assignImages': this._photoLayoutEditor.api.grid.assignImages(util.pickImages(4)); break; case 'grid.assignImage': this._photoLayoutEditor.api.grid.assignImage(0, util.pickImages(1)[0]); break; case 'grid.update': let result = {}; let blocks = this._photoLayoutEditor.api.grid.getBlocks('selected'); if (!Object.keys(blocks).length) return; Object.keys(blocks).forEach((k) => { blocks[k].color = 'rgba(126,211,33,1)'; }); this._photoLayoutEditor.api.grid.update(blocks); break; case 'grid.add': this._photoLayoutEditor.api.grid.add([{ layout: { w: 1, h: 1 }, color: 'rgba(126,211,33,1)', }]); break; case 'grid.remove': let keys = this._photoLayoutEditor.api.grid.getKeys('selected'); this._photoLayoutEditor.api.grid.remove(keys); //this._photoLayoutEditor.api.grid.remove([0,1]); break; case 'grid.select': this._photoLayoutEditor.api.grid.select([0,2,3]); break; case 'grid.unselect': this._photoLayoutEditor.api.grid.unselect([2,3]); break; case 'grid.toggleSelectAll': this._photoLayoutEditor.api.grid.toggleSelectAll(); break; case 'grid.duplicate': keys = this._photoLayoutEditor.api.grid.getKeys('selected'); this._photoLayoutEditor.api.grid.duplicate(keys); break; case 'grid.getPreference': result = this._photoLayoutEditor.api.grid.getPreference(); console.log('side.getPreference', result); break; case 'grid.setPreference': this._photoLayoutEditor.api.grid.setPreference({ width: 80, column: 6, innerMargin: 5, }); break; // Util case 'util.toggleSide': this._photoLayoutEditor.api.util.toggleSide(); break; case 'util.export.side': result = this._photoLayoutEditor.api.util.export('side'); console.log('export(side)', result); break; case 'util.export.grid': result = this._photoLayoutEditor.api.util.export('grid'); console.log('export(grid)', result); break; case 'util.export.preference': result = this._photoLayoutEditor.api.util.export('preference'); console.log('export(preference)', result); break; case 'util.export.all': result = this._photoLayoutEditor.api.util.export('all'); console.log('export(all)', result); break; case 'util.import.side': result = this._photoLayoutEditor.api.util.import({ side: util.pickImages(3) }, true); break; case 'util.import.grid': this._photoLayoutEditor.api.util.import({ grid: [ { color: '#ee4149', layout: { w: 1, h: 1, x: 0 } }, { color: '#36b40d', layout: { w: 2, h: 2, x: Infinity } }, { color: '#b188ff', layout: { w: 3, h: 1, y: 2, x: 0 } }, ] }, true); break; case 'util.import.preference': preference = this._photoLayoutEditor.api.util.export('preference'); preference = Object.assign({}, preference, { width: 120, height: 80, innerMargin: 2, bgColor: '#ffefc2' }); this._photoLayoutEditor.api.util.import({ preference }); break; case 'util.import.all': preference = this._photoLayoutEditor.api.util.export('preference'); this._photoLayoutEditor.api.util.import({ side: util.pickImages(3), grid: [ { color: '#ee4149', layout: { w: 1, h: 1, x: 0 } }, { color: '#36b40d', layout: { w: 2, h: 2, x: Infinity } }, ], preference: Object.assign({}, preference, { width: 120, height: 80, innerMargin: 2, bgColor: '#ffefc2' }) }); break; case 'util.makeImage': let makeImage = this._photoLayoutEditor.api.util.makeImage('jpg', .9, 2, 'base64'); makeImage.progress(function(total, current, image) { console.log('PROGRESS', total, current, image); }); makeImage.done(function(src) { console.warn('DONE'); let output = document.getElementById('makeImageArea'); output.innerHTML = `<img src="${src}" alt="output image"/>`; }); makeImage.fail(function(error) { console.error('ERROR', error); }); break; } } render() { return ( <div className="app"> <PhotoLayoutEditor ref={(r) => { this._photoLayoutEditor = r }} side={{ files: util.pickImages(5) }} body={{ grid: [ { layout: { x: 0, y: 0, w: 2, h: 2 } }, { layout: { x: 2, y: 0, w: 1, h: 2 } }, { layout: { x: 3, y: 0, w: 2, h: 1 } }, { layout: { x: 3, y: 1, w: 1, h: 1 } }, { layout: { x: 4, y: 1, w: 1, h: 1 } }, ] }} //uploadScript="http://localhost/lab/uploader/upload.php" uploadParamsConvertFunc={(file) => { return file.url; }} updateStoreFunc={() => console.warn('update store')} callback={{ init: () => { console.log('init component') }, sideUploadStart: () => { console.log('side/upload start'); }, sideUploadProgress: (loaded, total, percent) => { console.log('side/upload progress', loaded, total, percent); }, sideUploadComplete: (res) => { console.log('side/upload complete', res); }, sideUploadCompleteAll: () => { console.log('side/upload complete all'); }, sideUploadFail: (error) => { console.log('side/upload fail', error); }, sideRemove: (images) => { console.log('side/remove', images); }, }} /> <article className="api-control"> <section> <h1>Side</h1> <nav> <p> <button type="button" onClick={() => this.action('side.add')}> add files </button> <button type="button" onClick={() => this.action('side.selectedRemoveItems')}> remove items </button> <button type="button" onClick={() => this.action('side.clear')}> clear </button> <button type="button" onClick={() => this.action('side.attachToGrid')}> attach to grid </button> <button type="button" onClick={() => this.action('side.selection')}> selection </button> <button type="button" onClick={() => this.action('side.select')}> select </button> <button type="button" onClick={() => this.action('side.toggleSelectAll')}> toggle select all </button> <button type="button" onClick={() => this.action('side.getItems')}> get items </button> <button type="button" onClick={() => this.action('side.getImages')}> get images </button> </p> <p> <label> <strong>upload image</strong><br/> <input type="file" multiple={true} onChange={(e) => this.action('side.upload', e)}/> </label> </p> </nav> </section> <section> <h1>Grid</h1> <nav> <p> <button type="button" onClick={() => this.action('grid.getKeys')}>get keys</button> <button type="button" onClick={() => this.action('grid.getBlocks')}>get blocks</button> <button type="button" onClick={() => this.action('grid.getPreference')}>get preference</button> <button type="button" onClick={() => this.action('grid.setPreference')}>set preference</button> <button type="button" onClick={() => this.action('grid.update')}>update</button> <button type="button" onClick={() => this.action('grid.add')}>add</button> <button type="button" onClick={() => this.action('grid.remove')}>remove</button> <button type="button" onClick={() => this.action('grid.shuffle')}>shuffle</button> <button type="button" onClick={() => this.action('grid.assignImages')}>assign images</button> <button type="button" onClick={() => this.action('grid.assignImage')}>assign image</button> <button type="button" onClick={() => this.action('grid.duplicate')}>duplicate</button> <button type="button" onClick={() => this.action('grid.select')}>select</button> <button type="button" onClick={() => this.action('grid.unselect')}>unselect</button> <button type="button" onClick={() => this.action('grid.toggleSelectAll')}>toggle select all</button> </p> </nav> </section> <section> <h1>Util</h1> <nav> <p> <button type="button" onClick={() => this.action('util.toggleSide')}>Toggle side</button> </p> <p> <button type="button" onClick={() => this.action('util.export.side')}>Export(side)</button> <button type="button" onClick={() => this.action('util.export.grid')}>Export(grid)</button> <button type="button" onClick={() => this.action('util.export.preference')}>Export(preference)</button> <button type="button" onClick={() => this.action('util.export.all')}>Export(all)</button> <button type="button" onClick={() => this.action('util.makeImage')}>Make image</button> </p> <p> <button type="button" onClick={() => this.action('util.import.side')}>Import(side)</button> <button type="button" onClick={() => this.action('util.import.grid')}>Import(grid)</button> <button type="button" onClick={() => this.action('util.import.preference')}>Import(preference)</button> <button type="button" onClick={() => this.action('util.import.all')}>Import(all)</button> </p> </nav> </section> <section> <h1>Make image area</h1> <figure id="makeImageArea"/> </section> </article> </div> ); } } ReactDOM.render(<App/>, document.getElementById('app'));
src/views/syllabus/Aspect.js
bostontrader/senmaker
// @flow import React from 'react' import LessonNavigator from './LessonNavigator' import {VerbdPanelLevel} from '../../data/dictionary/verbd/VerbdConstants' function Aspect(props:Object):Object { const style:Object = { border: '1px solid black', margin: '5px' } const q:Object = props.quiz const s:Object = props.strings.aspect /*const quizInsertVerbFlag = q.getIn(['verbd','insertAspect']) ? <img id="insertAspectCheck" className="checkmark" src="/img/Checked.png" alt="checkmark"/> : '' const quizUpdateVerbFlag = q.getIn(['verbd','updateAspect']) ? <img id="updateAspectCheck" className="checkmark" src="/img/Checked.png" alt="checkmark"/> : '' const quizDeleteVerbFlag = q.getIn(['verbd','deleteAspect']) ? <img id="deleteAspectCheck" className="checkmark" src="/img/Checked.png" alt="checkmark"/> : ''*/ return( <div> <div className="help" style={style}> <h1>Aspect</h1> {s.map(h => (<p>{h}</p>))} </div> <div className="quiz" style={style}> <h3>{props.strings.quiz}</h3> <table> <tbody> </tbody> </table> </div> <LessonNavigator {...props} /> </div> ) } export default Aspect
react/life-cycle/src/LifeCycle.js
kobeCan/practices
import React from 'react'; class LifeCycle extends React.Component { constructor (props) { super(props); } state = { color: 'red' } /* 当组件第一次挂载的时候 */ // 1. componentWillMount = () => { console.log('componentWillMount'); } // 2. 在render之后执行 componentDidMount = () => { console.log('componentDidMount'); } /* 当接收到父组件的props或state发生改变的时候 */ // 1. componentWillReceiveProps = (nextProps, nextState) => { console.log('componentWillReceiveProps'); } // 2. shouldComponentUpdate = (nextProps, nextState) => { console.log('shouldComponentUpdate'); return true; } // 3. componentWillUpdate = (nextProps, nextState) => { console.log('componentWillUpdate'); } // 4. 在render之后执行 componentDidUpdate = () => { console.log('componentDidUpdate'); } handleClick = () => { this.setState({ color: '#' + Math.round(Math.random() * 0xffffff).toString(16) }) } render () { const { text } = this.props; const { color } = this.state; return <div> <h2 onClick={this.handleClick} style={{color: color}}>{text}</h2> </div>; } } export default LifeCycle
src/components/ChartBase.js
somonus/react-echarts
import React, { Component } from 'react'; export default class ChartBase extends Component { static propTypes = { hasChart: React.PropTypes.bool, }; constructor(props) { super(props); if (this.props.hasChart !== true) { throw new Error('There is no Chart wrapper.'); } } render() { return null; } }
egghead-redux/redux-app/src/components/app2.js
Mad-Labs/open-lab
import React, { Component } from 'react'; import Debug from './debug'; import {runTestSuite} from '../reducers/multipleCountersReducer'; class App2 extends Component { render() { return ( <div> <h1>Test add/remove counters</h1> <Debug result={runTestSuite()} /> </div> ); } } export default App2;
node_modules/react-sparklines/src/SparklinesCurve.js
aleksandrsmolin/react-redux-weather
import React from 'react'; export default class SparklinesCurve extends React.Component { static propTypes = { color: React.PropTypes.string, style: React.PropTypes.object }; static defaultProps = { style: {} }; render() { const { points, width, height, margin, color, style, divisor = 0.25 } = this.props; let prev; const curve = (p) => { let res; if (!prev) { res = [p.x, p.y] } else { const len = (p.x - prev.x) * divisor; res = [ "C", //x1 prev.x + len, //y1 prev.y, //x2, p.x - len, //y2, p.y, //x, p.x, //y p.y ]; } prev = p; return res; } const linePoints = points .map((p) => curve(p)) .reduce((a, b) => a.concat(b)); const closePolyPoints = [ "L" + points[points.length - 1].x, height - margin, margin, height - margin, margin, points[0].y ]; const fillPoints = linePoints.concat(closePolyPoints); const lineStyle = { stroke: color || style.stroke || 'slategray', strokeWidth: style.strokeWidth || '1', strokeLinejoin: style.strokeLinejoin || 'round', strokeLinecap: style.strokeLinecap || 'round', fill: 'none' }; const fillStyle = { stroke: style.stroke || 'none', strokeWidth: '0', fillOpacity: style.fillOpacity || '.1', fill: style.fill || color || 'slategray' }; return ( <g> <path d={"M"+fillPoints.join(' ')} style={fillStyle} /> <path d={"M"+linePoints.join(' ')} style={lineStyle} /> </g> ) } }
src/svg-icons/hardware/sim-card.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareSimCard = (props) => ( <SvgIcon {...props}> <path d="M19.99 4c0-1.1-.89-2-1.99-2h-8L4 8v12c0 1.1.9 2 2 2h12.01c1.1 0 1.99-.9 1.99-2l-.01-16zM9 19H7v-2h2v2zm8 0h-2v-2h2v2zm-8-4H7v-4h2v4zm4 4h-2v-4h2v4zm0-6h-2v-2h2v2zm4 2h-2v-4h2v4z"/> </SvgIcon> ); HardwareSimCard = pure(HardwareSimCard); HardwareSimCard.displayName = 'HardwareSimCard'; HardwareSimCard.muiName = 'SvgIcon'; export default HardwareSimCard;
webui/components/users/FormInsurance.js
stiftungswo/izivi_relaunch
import React from 'react'; import { Grid } from 'semantic-ui-react'; import AutoField from 'uniforms-semantic/AutoField'; import SubmitField from 'uniforms-semantic/SubmitField'; import ErrorsField from 'uniforms-semantic/ErrorsField'; import AutoForm from 'uniforms-semantic/AutoForm'; import FormMaskedInput from '../../lib/FormMaskedInput'; const FormInsurance = formProps => ( <AutoForm showInlineError {...formProps} > <Grid stackable columns={3}> <Grid.Row> <Grid.Column computer={4} tablet={5}> <AutoField name="healthInsuranceNumber" placeholder="00000" /> </Grid.Column> <Grid.Column computer={8} tablet={11}> <AutoField name="healthInsuranceName" /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column computer={4} tablet={5}> <AutoField name="socialSecurityNumber" component={FormMaskedInput} mask="756.9999.9999.99" maskChar="_" alwaysShowMask /> </Grid.Column> </Grid.Row> <Grid.Row columns={1}> <Grid.Column> <ErrorsField /> <SubmitField value="Speichern" className="primary" /> </Grid.Column> </Grid.Row> </Grid> </AutoForm> ); export default FormInsurance;
pootle/static/js/admin/components/Search.js
translate/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import cx from 'classnames'; import React from 'react'; import ItemTable from './ItemTable'; import SearchBox from './SearchBox'; const Search = React.createClass({ propTypes: { fields: React.PropTypes.array.isRequired, onSearch: React.PropTypes.func.isRequired, onSelectItem: React.PropTypes.func.isRequired, items: React.PropTypes.object.isRequired, selectedItem: React.PropTypes.object, searchLabel: React.PropTypes.string.isRequired, searchPlaceholder: React.PropTypes.string.isRequired, resultsCaption: React.PropTypes.string.isRequired, searchQuery: React.PropTypes.string.isRequired, }, /* Lifecycle */ getInitialState() { return { isLoading: false, }; }, /* State-changing callbacks */ onResultsFetched() { this.setState({ isLoading: false }); }, fetchResults(query) { this.setState({ isLoading: true }); this.props.onSearch(query).then(this.onResultsFetched); }, loadMore() { this.fetchResults(this.props.searchQuery); }, /* Layout */ render() { const { isLoading } = this.state; const { items } = this.props; let loadMoreBtn; if (items.count > 0 && items.length < items.count) { loadMoreBtn = ( <button className="btn" onClick={this.loadMore} > {gettext('Load More')} </button> ); } const resultsClassNames = cx({ 'search-results': true, loading: isLoading, }); return ( <div className="search"> <div className="hd"> <h2>{this.props.searchLabel}</h2> </div> <div className="bd"> <div className="search-box"> <SearchBox onSearch={this.props.onSearch} placeholder={this.props.searchPlaceholder} searchQuery={this.props.searchQuery} /> </div> <div className={resultsClassNames}> {isLoading && this.props.items.length === 0 ? <div>{gettext('Loading...')}</div> : <div> <ItemTable fields={this.props.fields} items={items} resultsCaption={this.props.resultsCaption} selectedItem={this.props.selectedItem} onSelectItem={this.props.onSelectItem} /> {loadMoreBtn} </div> } </div> </div> </div> ); }, }); export default Search;
geonode/contrib/monitoring/frontend/src/components/cels/geonode-data/index.js
simod/geonode
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { getResponseData } from '../../../utils'; import AverageResponseTime from '../../molecules/average-response-time'; import MaxResponseTime from '../../molecules/max-response-time'; import TotalRequests from '../../molecules/total-requests'; import styles from './styles'; import actions from './actions'; const mapStateToProps = (state) => ({ interval: state.interval.interval, response: state.geonodeAverageResponse.response, timestamp: state.interval.timestamp, }); @connect(mapStateToProps, actions) class GeonodeData extends React.Component { static propTypes = { get: PropTypes.func.isRequired, interval: PropTypes.number, reset: PropTypes.func.isRequired, response: PropTypes.object, timestamp: PropTypes.instanceOf(Date), } constructor(props) { super(props); this.get = (interval = this.props.interval) => { this.props.get(interval); }; } componentWillMount() { this.get(); } componentWillReceiveProps(nextProps) { if (nextProps) { if (nextProps.timestamp && nextProps.timestamp !== this.props.timestamp) { this.get(nextProps.interval); } } } componentWillUnmount() { this.props.reset(); } render() { let averageResponseTime = 0; let maxResponseTime = 0; let totalRequests = 0; [ averageResponseTime, maxResponseTime, totalRequests, ] = getResponseData(this.props.response); return ( <div style={styles.content}> <h5>Geonode Data Overview</h5> <div style={styles.geonode}> <AverageResponseTime time={averageResponseTime} /> <MaxResponseTime time={maxResponseTime} /> </div> <TotalRequests requests={totalRequests} /> </div> ); } } export default GeonodeData;
admin/client/components/ItemsTable/ItemsTable.js
Tangcuyu/keystone
import React from 'react'; import classnames from 'classnames'; import Columns from '../../columns'; import CurrentListStore from '../../stores/CurrentListStore'; import ListControl from '../List/ListControl'; import TableRow from './ItemsTableRow'; import DrapDrop from './ItemsTableDragDrop'; const TABLE_CONTROL_COLUMN_WIDTH = 26; // icon + padding const ItemsTable = React.createClass({ propTypes: { columns: React.PropTypes.array, items: React.PropTypes.object, list: React.PropTypes.object, }, renderCols () { var cols = this.props.columns.map((col) => <col width={col.width} key={col.path} />); // add delete col when applicable if (!this.props.list.nodelete) { cols.unshift(<col width={TABLE_CONTROL_COLUMN_WIDTH} key="delete" />); } // add sort col when applicable if (this.props.list.sortable) { cols.unshift(<col width={TABLE_CONTROL_COLUMN_WIDTH} key="sortable" />); } return <colgroup>{cols}</colgroup>; }, renderHeaders () { let listControls = 0; if (this.props.list.sortable) listControls++; if (!this.props.list.nodelete) listControls++; // span first col for controls when present let cellPadding = null; if (listControls) { cellPadding = <th colSpan={listControls}></th>; } let cells = this.props.columns.map((col, i) => { return <th key={col.path} colSpan="1">{col.label}</th>; }); return <thead><tr>{cellPadding}{cells}</tr></thead>; }, render () { const { items, list } = this.props; if (!items.results.length) return null; const currentPage = CurrentListStore.getCurrentPage(); const pageSize = CurrentListStore.getPageSize(); const totalPages = Math.ceil(items.count / pageSize); const tableBody = (this.props.list.sortable) ? ( <DrapDrop { ...this.props } /> ) : ( <tbody > {items.results.map((item, i) => { return ( <TableRow key={item.id} deleteTableItem={this.props.deleteTableItem} index={i} sortOrder={item.sortOrder || 0} id={item.id} item={item} { ...this.props } /> ); })} </tbody> ); return ( <div className="ItemList-wrapper"> <table cellPadding="0" cellSpacing="0" className="Table ItemList"> {this.renderCols()} {this.renderHeaders()} {tableBody} </table> </div> ); }, }); module.exports = exports = ItemsTable;
dataTool/stories/examples/index.js
bitmoremedia/mygi
import React from 'react' import { storiesOf } from '@kadira/storybook' import globalStyles from '../../src/global-styles'; globalStyles(); import ButtonToggle from './ButtonToggle' import ButtonToggleModal from './ButtonToggleModal' import SearchUtility from './SearchUtility' storiesOf('Toggle Display', module) .add('ButtonToggle', () => ( <ButtonToggle /> )) .add('ButtonToggleModal', () => ( <ButtonToggleModal /> )) storiesOf('Utilities', module) .add('SearchUtility', () => ( <SearchUtility /> ))
front/app/app/rh-components/rh-Spinner.js
nudoru/React-Starter-2-app
import React from 'react'; const Spinner = ({type}) => { let cls = ['spinner']; if(type) { cls.push(type); } return (<div className={cls.join(' ')}></div>) }; export default Spinner;
test/FadeMixinSpec.js
roderickwang/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import FadeMixin from '../src/FadeMixin'; let Component; describe('FadeMixin', function () { beforeEach(function() { Component = React.createClass({ mixins: [ FadeMixin ], render() { return ( <div {...this.props} className='fade'> <span className='fade'/> </div> ); } }); }); afterEach(()=> { if (console.warn.calledWithMatch('FadeMixin is deprecated')){ console.warn.reset(); } }); it('Should add the in class to all elements', function (done) { let instance = ReactTestUtils.renderIntoDocument(<Component />); let child = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'span'); setTimeout(function(){ assert.ok(React.findDOMNode(instance).className.match(/\bin\b/)); assert.ok(React.findDOMNode(instance).className.match(/\bfade\b/)); assert.ok(React.findDOMNode(child).className.match(/\bin\b/)); assert.ok(React.findDOMNode(child).className.match(/\bfade\b/)); done(); }, 25); }); it('Should remove the in class for all elements', function (done) { let instance = ReactTestUtils.renderIntoDocument(<Component />); setTimeout(function(){ instance.componentWillUnmount(); let element = instance._fadeOutEl.children[0]; let child = element.children[0]; assert.ok(element.className.match(/\bin\b/)); assert.ok(child.className.match(/\bin\b/)); setTimeout(function(){ assert.ok(!element.className.match(/\bin\b/)); assert.ok(element.className.match(/\bfade\b/)); assert.ok(!child.className.match(/\bin\b/)); assert.ok(child.className.match(/\bfade\b/)); done(); }, 25); }, 25); }); });
src/pages/404.js
jgaehring/jgaehring.github.io
import React from 'react'; import Layout from '../components/Layout'; const NotFoundPage = () => ( <Layout> <h1>NOT FOUND</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </Layout> ) export default NotFoundPage
app/javascript/mastodon/features/explore/links.js
musashino205/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Story from './components/story'; import LoadingIndicator from 'mastodon/components/loading_indicator'; import { connect } from 'react-redux'; import { fetchTrendingLinks } from 'mastodon/actions/trends'; const mapStateToProps = state => ({ links: state.getIn(['trends', 'links', 'items']), isLoading: state.getIn(['trends', 'links', 'isLoading']), }); export default @connect(mapStateToProps) class Links extends React.PureComponent { static propTypes = { links: ImmutablePropTypes.list, isLoading: PropTypes.bool, dispatch: PropTypes.func.isRequired, }; componentDidMount () { const { dispatch } = this.props; dispatch(fetchTrendingLinks()); } render () { const { isLoading, links } = this.props; return ( <div className='explore__links'> {isLoading ? (<LoadingIndicator />) : links.map(link => ( <Story key={link.get('id')} url={link.get('url')} title={link.get('title')} publisher={link.get('provider_name')} sharedTimes={link.getIn(['history', 0, 'accounts']) * 1 + link.getIn(['history', 1, 'accounts']) * 1} thumbnail={link.get('image')} blurhash={link.get('blurhash')} /> ))} </div> ); } }
src/components/amount-input.js
mozilla/donate.mozilla.org
import React from 'react'; var AmountInput = React.createClass({ contextTypes: { intl: React.PropTypes.object }, getInitialState: function() { var amount = this.props.amount; if (amount) { amount = this.context.intl.formatNumber(amount); } return { inputValue: amount }; }, componentWillReceiveProps: function(nextProps) { var amount = nextProps.amount; var inputValue = this.state.inputValue; if (!amount && inputValue) { this.setState({ inputValue: "" }); } else if (amount && !inputValue) { this.setState({ inputValue: this.context.intl.formatNumber(amount) }); } }, onInputChange: function(e) { var inputValue = e.currentTarget.value; var amount = ""; // TODO: This needs to be refactored to use regex replace // and needs documentation for what they are matching. // See https://github.com/mozilla/donate.mozilla.org/issues/1917 if (/^[\d]*[.]?\d{0,2}$/.test(inputValue)) { amount = inputValue.replace(/,/g, ""); } else if (/^[\d]*[,]?\d{0,2}$/.test(inputValue)) { amount = inputValue.replace(/\./g, "").replace(",", "."); } else if (/^[\d,]*[.]?\d{0,2}$/.test(inputValue)) { amount = inputValue.replace(/,/g, ""); } else if (/^[\d.]*[,]?\d{0,2}$/.test(inputValue)) { amount = inputValue.replace(/\./g, "").replace(",", "."); } else { inputValue = this.state.inputValue; } if (this.state.inputValue !== inputValue) { this.setState({ inputValue: inputValue }); this.props.onInputChange(amount); } }, onClick: function(e) { if (this.props.onInputClick) { this.props.onInputClick(e); } }, render: function() { var inputValue = this.state.inputValue; if (!this.props.amount) { inputValue = ""; } var id = this.props.id || ""; var className = this.props.className || ""; var placeholder = this.props.placeholder || ""; var type = this.props.type || ""; return ( <input id={id} autoComplete="off" className={className} type={type} value={inputValue} onClick={this.onClick} placeholder={placeholder} onChange={this.onInputChange} /> ); } }); module.exports = AmountInput;
src/svg-icons/maps/terrain.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsTerrain = (props) => ( <SvgIcon {...props}> <path d="M14 6l-3.75 5 2.85 3.8-1.6 1.2C9.81 13.75 7 10 7 10l-6 8h22L14 6z"/> </SvgIcon> ); MapsTerrain = pure(MapsTerrain); MapsTerrain.displayName = 'MapsTerrain'; MapsTerrain.muiName = 'SvgIcon'; export default MapsTerrain;
src/containers/app.js
mrGGoodbye/react-redux-API-unsplash
// подключаем необходимые модули React и Unsplash import React from 'react'; import { connect } from 'react-redux' import { action_SET_list_photos } from '../actions'; import {unsplash} from '../../src/index.js'; import {Router, Route, hashHistory, Link} from 'react-router'; // счетчик страниц и количества фоток на каждой странице let page = 1; const n = 10; // функция загруки первого списка фотографий const func_list_photo=(func_new_list_photo)=>{ console.log('unsplash in app.js==',unsplash); // делаем запрос в unsplash unsplash.photos.listPhotos(page, n, "latest") .then(res => res.json()) .then(json => { console.log('JSON_list_photo__TOKEN--- ', json); let propValue=[]; // разбираем полученный результат и сохраняем его в propValue for(let prop in json){ if(json.hasOwnProperty(prop)){ // let propValue = json[prop].urls.small; propValue = [ ...propValue, { id: json[prop].id, url: json[prop].urls.small, url_full: json[prop].urls.full, author_name: json[prop].user.name, author_link: json[prop].user.links.html, date: json[prop].created_at, likes: json[prop].likes, liked_by_user: json[prop].liked_by_user } ]; console.log(prop+' : ', propValue); } } console.log('MASSSIVE_PHOTO : ', propValue); // для каждого элемента propValue вызываем функцию, // которая вызовет action-creators "action_SET_list_photos" propValue.map((item, i)=>{ func_new_list_photo(propValue[i]); }) }); } // эта функция будет загружать новые списки фото // будем листать страницы const func_load_foto=(func_new_list_photo, load_ok)=>{ console.log('Загружаем еще фото...'); // листаем следующую станицу page = page + 1; // делаем запрос в UNSPLASH unsplash.photos.listPhotos(page, n, "latest") .then(res => res.json()) .then(json => { // Your code console.log('NEW_JSON_list_photo__TOKEN--- ', json); let propValue=[]; // разбираем полученный результат и сохраняем его в propValue for(let prop in json){ if(json.hasOwnProperty(prop)){ propValue = [ ...propValue, { id: json[prop].id, url: json[prop].urls.small, url_full: json[prop].urls.full, author_name: json[prop].user.name, author_link: json[prop].user.links.html, date: json[prop].created_at, likes: json[prop].likes, liked_by_user: json[prop].liked_by_user } ]; console.log(prop+' : ', propValue); } } console.log('NEW_MASSSIVE_NEW_PHOTO : ', propValue); // для каждого элемента propValue вызываем функцию, // которая вызовет action-creators "action_SET_list_photos" propValue.map((item, i)=>{ func_new_list_photo(propValue[i]); }) load_ok = true; }); // end my code } // делаем счетчик рендинга при первоначальной загрузке странице // чтобы не загружать несколько раз пока незагружен первый результат, // так как ему нужно время для получения результата и загрузки let nn=0; let load_first = true; let func_log = () => { console.log("Сработало! ---- ", nn++); load_first = false; } // Создаем компонен App_Con // основной компонент будет показывать список фотографий let App_Con = (props) =>{ console.log('PROPS_QWERTY==', props); // загружаем первый списко через Timeout // иначе из unsplash загрузятся не актульные данные по лайкам польлзователя const for_timeout=()=>{ func_list_photo(props.func_new_list_photo); console.log('Timeout Ok'); } if(nn==1){ setTimeout(for_timeout, 1000); } func_log(); // load_ok - для подстраховки если пока незагрузились новые фото // будут крутить скролом на месте удовлетворяющем условиям let load_ok = true; // функция для отлавливания момента скрола вниз для загрузки новых фото window.onscroll = function() { var app2 = document.querySelector('#app2'); if((load_ok)&&(window.scrollY>=app2.clientHeight - window.innerHeight+26)&&(window.location.hash=='#/')) { console.log('END!!! ',window.scrollY); load_ok = false; func_load_foto(props.func_new_list_photo, load_ok); } } // сторим наше приложение // загружаем первый список фото // новый список загружаем при скроле в самый низ или по нажатии кнопки return ( <div > <h2> Мой Unsplash </h2> <div> {props.IMGGESS.map((el,i) =>{ var date = new Date(el.date); return <div key={i} > <div><Link to={`/photo/${el.id}`} key={i+100}><img src={el.url} /></Link></div> <div><a href={el.author_link+'?utm_source=over&utm_medium=referral&utm_campaign=api-credit'} target="_blank" key={i+10}>{el.author_name}</a></div> <div>Дата публикации: {date.toUTCString()}</div> <div>Количество лайков: {el.likes}</div> </div> })} </div> <button className={'button_load_foto'} onClick={ev=>func_load_foto(props.func_new_list_photo)} >Загрузить еще...</button> </div> ) } // создаем store и action-creators const mapStateToProps = (state, ownProps) => { return { todos: state.todos, IMGGESS: state.IMGGESS, ownProps } } const mapDispatchToProps = (dispatch) => { return { // функция для listPhotos func_new_list_photo: (props) => { dispatch(action_SET_list_photos(props)) } } } let App_Con22 = connect( mapStateToProps, mapDispatchToProps )(App_Con) export default App_Con22;
src/pages/components/Books/utils.js
H3yfinn/finbarmaunsell.com
// @flow import React from 'react' import type { _Book } from './types' // Note that this is different from `renderWiki` in the Elm, // as we cannot return an Html.Attribute msg (attribute assignment) // as a single value in JS in the same way that we can in Elm. export const deduceUrl = (book: _Book) => book.wiki || '' export const renderErr = (error: ?string) => ( (typeof error === 'string') ? <div>{error}</div> : null ) export const isComplete = (book: _Book) => (typeof book.end === 'string') // this synthesises the check in Elm, but important // to mention null values in JS and their nuances
app/javascript/mastodon/components/animated_number.js
tri-star/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedNumber } from 'react-intl'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import { reduceMotion } from 'mastodon/initial_state'; const obfuscatedCount = count => { if (count < 0) { return 0; } else if (count <= 1) { return count; } else { return '1+'; } }; export default class AnimatedNumber extends React.PureComponent { static propTypes = { value: PropTypes.number.isRequired, obfuscate: PropTypes.bool, }; state = { direction: 1, }; componentWillReceiveProps (nextProps) { if (nextProps.value > this.props.value) { this.setState({ direction: 1 }); } else if (nextProps.value < this.props.value) { this.setState({ direction: -1 }); } } willEnter = () => { const { direction } = this.state; return { y: -1 * direction }; } willLeave = () => { const { direction } = this.state; return { y: spring(1 * direction, { damping: 35, stiffness: 400 }) }; } render () { const { value, obfuscate } = this.props; const { direction } = this.state; if (reduceMotion) { return obfuscate ? obfuscatedCount(value) : <FormattedNumber value={value} />; } const styles = [{ key: `${value}`, data: value, style: { y: spring(0, { damping: 35, stiffness: 400 }) }, }]; return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}> {items => ( <span className='animated-number'> {items.map(({ key, data, style }) => ( <span key={key} style={{ position: (direction * style.y) > 0 ? 'absolute' : 'static', transform: `translateY(${style.y * 100}%)` }}>{obfuscate ? obfuscatedCount(data) : <FormattedNumber value={data} />}</span> ))} </span> )} </TransitionMotion> ); } }
examples/todomvc/containers/Root.js
ariporad/redux
import React, { Component } from 'react'; import TodoApp from './TodoApp'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import rootReducer from '../reducers'; const store = createStore(rootReducer); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <TodoApp /> } </Provider> ); } }
WorldMoodTracker/js/components/Header.js
kavithaenair/kavithaenair.github.io
import React from 'react'; import styles from '../../../css/bootstrap.min.css'; import customStyles from '../../css/style.css'; export default class Header extends React.Component { render() { return ( <nav className={[styles.navbar].join(' ')}> <div className={styles.container}> <div className={styles.navbarHeader} style={{marginLeft: '10px'}}> <h1> <span>World Mood Tracker</span> </h1> <h3> Powered by&nbsp; <span className={customStyles.loklak}> <a href="http://loklak.org" target="_blank">loklak</a> </span> </h3> </div> <div className={[styles.collapse, styles.navbarCollapse].join(' ')}> <ul className={[styles.nav, styles.navbarNav, styles.navbarRight].join(' ')}> <li><a href="/">Home</a></li> <li><a href="#">About</a></li> <li><a href="https://github.com/fossasia/apps.loklak.org/tree/master/WorldMoodTracker" target="_blank">Github</a></li> </ul> </div> </div> </nav> ) } }
src/js/components/dailyTracker/UnitTimer.js
angelm/sinuous
import React from 'react'; class UnitTimer extends React.Component { constructor(props) { super(props); let time = new Date(); time.setMinutes(props.unitDuration || 25); time.setSeconds(0); this.state = { timeoutId: null, remainingTime: time }; this.startTimer = this.startTimer.bind(this); this.pauseTimer = this.pauseTimer.bind(this); this.resetTimer = this.resetTimer.bind(this); } startTimer() { this.setState({timeoutId: setTimeout(this.onInterval.bind(this), this.state.interval)}); } pauseTimer() { if(this.state && this.state.timeoutId){ clearTimeout(this.state.timeoutId); } } resetTimer() { if(this.state && this.state.timeoutId){ clearTimeout(this.state.timeoutId); } let time = new Date(); time.setMinutes(this.props.unitDuration || 25); time.setSeconds(0); this.setState({remainingTime: time}); } onInterval(){ var mins = this.state.remainingTime.getMinutes(); var secs = this.state.remainingTime.getSeconds(); let remainingTime = new Date(this.state.remainingTime.getTime()); remainingTime.setSeconds(remainingTime.getSeconds() - 1); this.setState({remainingTime: remainingTime}); if(mins == 0 && secs == 0){ this.onCountdownEnded() } else { clearTimeout(this.state.timeoutId); this.setState({timeoutId: setTimeout(this.onInterval.bind(this), 1000)}); } } onCountdownEnded() { // Todo: notify of unit complete to the TaskManager and DailySummary console.log("Unit Completed"); } formatClock(){ let mins = this.state.remainingTime.getMinutes(); let secs = this.state.remainingTime.getSeconds(); let strMins = mins < 10 ? "0" + mins : mins; let strSecs = secs < 10 ? "0" + secs : secs; return strMins + ':' + strSecs; } render() { return ( <div className="timer"> <div className="clock">{this.formatClock()}</div> <div className="control-panel"> <div className="control time start fa fa-play-circle" onClick={this.startTimer}></div> <div className="control stop fa fa-pause-circle" onClick={this.pauseTimer}></div> <div className="control reset fa fa-stop-circle" onClick={this.resetTimer}></div> </div> </div> ); } } export default UnitTimer;
__tests__/index.ios.js
J1aDong/Fleet
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
client/App.js
Trulsabe/reactLinuxMern
/** * Root Component */ import React from 'react'; import { Provider } from 'react-redux'; import { Router, browserHistory } from 'react-router'; import IntlWrapper from './modules/Intl/IntlWrapper'; // Import Routes import routes from './routes'; // Base stylesheet require('./main.css'); export default function App(props) { return ( <Provider store={props.store}> <IntlWrapper> <Router history={browserHistory}> {routes} </Router> </IntlWrapper> </Provider> ); } App.propTypes = { store: React.PropTypes.object.isRequired, };
src/LabelNumberDisplay/index.js
christianalfoni/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import Icon from '../Icon'; import Typography from '../Typography'; import classNames from 'classnames'; import styles from './styles.css'; function LabelNumberDisplay(props) { return ( <div className={classNames(styles.outerWrapper, props.className)}> <Icon className={styles.icon} icon={props.icon || 'icon-leaf'} size={'standard'} style={{color: props.color ? props.color : '#00ab97'}} /> <Typography className={classNames(styles.value, {[styles.valueDark]: props.theme === 'dark'})} type={'display1'} > {props.value} </Typography> <Typography className={classNames(styles.label, {[styles.labelDark]: props.theme === 'dark'})} type={'bodyTextNormal'} >{props.label}</Typography> </div> ); } LabelNumberDisplay.propTypes = { className: PropTypes.string, color: PropTypes.string, icon: PropTypes.string, label: PropTypes.string, theme: PropTypes.string, value: PropTypes.number }; export default LabelNumberDisplay;
Backup/AwesomeProject/components/TaskList.js
victorditadi/IQApp
import React, { Component } from 'react'; import { View, TextInput, Text, Button, AlertIOS } from 'react-native'; import HeaderIQMail from './Faixa'; import { Container, Content, InputGroup, Input } from 'native-base'; export default class TaskList extends Component{ constructor(){ super(); this.state = { todoTxt: '', todos: [] } } render(){ return( <View> <HeaderIQMail></HeaderIQMail> <View> <InputGroup borderType='regular' > <Input onChangeText={ this.handleChange } value={ this.state.todoTxt } placeholder='Digite sua Lista'/> </InputGroup> <Button title='New Todo' onPress={this.save}> </Button> </View> <View> { this.state.todos.map((item, key) => ( <Text key = {key}>{item}</Text> ))} </View> </View> ); } handleChange = (txt) => { this.setState({ todoTxt:txt }) } save = () => { if(!this.state.todoTxt) { AlertIOS.alert('Por favor, preencha o campo.'); } this.state.todos.push(this.state.todoTxt); this.setState({ todoTxt: '', todos : this.state.todos }); } }
src/components/header/ThemeSwitcher.js
TechyFatih/Nuzlog
import React from 'react'; import { ToggleButton, ToggleButtonGroup } from 'react-bootstrap' const stylesheet = document.getElementById('bootstrap'); export default class ThemeSwitcher extends React.Component { constructor(props) { super(props); this.state = {value: 'default'}; this.onChange = this.onChange.bind(this); } onChange(value) { this.setState({ value }); const link = 'bootstrap/css/bootstrap' + (value == 'dark' ? '-dark' : '') + '.min.css'; stylesheet.setAttribute('href', link); } render() { return ( <ToggleButtonGroup type='radio' name='theme' value={this.state.value} onChange={this.onChange}> <ToggleButton value='default'>Default</ToggleButton> <ToggleButton value='dark'>Dark</ToggleButton> </ToggleButtonGroup> ) } }
part4/src/components/Button/index.js
vulcan-estudios/web-testing
import React from 'react'; function Button (props = {}) { const { className, icon } = props; let { children } = props; let cls = 'mybutton'; if (className) { cls += ` ${className}`; } if (icon) { children = ( <i className='myicon' /> ); } return ( <button className={cls}> {children} </button> ); } export default Button;
src/svg-icons/action/schedule.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSchedule = (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 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/> </SvgIcon> ); ActionSchedule = pure(ActionSchedule); ActionSchedule.displayName = 'ActionSchedule'; ActionSchedule.muiName = 'SvgIcon'; export default ActionSchedule;
pkg/interface/groups/src/js/components/lib/group-sidebar.js
ngzax/urbit
import React, { Component } from 'react'; import { Route, Link } from 'react-router-dom'; import { GroupItem } from '/components/lib/group-item'; import { Sigil } from '/components/lib/icons/sigil'; import { SidebarInvite } from '/components/lib/sidebar-invite'; import { Welcome } from '/components/lib/welcome'; import { cite } from '/lib/util'; export class GroupSidebar extends Component { // drawer to the left render() { const { props, state } = this; let selectedClass = (props.selected === "me") ? "bg-gray4 bg-gray1-d" : "bg-white bg-gray0-d"; let rootIdentity = <Link key={1} to={"/~groups/me"}> <div className={ "w-100 pl4 pt1 pb1 f9 flex justify-start content-center " + selectedClass}> <Sigil ship={window.ship} color="#000000" classes="mix-blend-diff" size={32}/> <p className="f9 w-70 dib v-mid ml2 nowrap mono" style={{paddingTop: 6}}> {cite(window.ship)} </p> </div> </Link> let inviteItems = Object.keys(props.invites) .map((uid) => { let invite = props.invites[uid]; return ( <SidebarInvite key={uid} api={api} invite={invite} uid={uid} history={props.history} /> ); }); let groupItems = Object.keys(props.contacts) .filter((path) => { return ( (!path.startsWith("/~/")) && (path in props.groups) ); }) .filter((path) => { let selectedGroups = !!props.selectedGroups ? props.selectedGroups : []; if (selectedGroups.length === 0) { return true; } let selectedPaths = selectedGroups.map((e => {return e[0]})); return (selectedPaths.includes(path)); }) .sort((a, b) => { let aName = a.substr(1); let bName = b.substr(1); let aChannel = `${a}/contacts${a}` let bChannel = `${b}/contacts${b}` if ( props.associations[a] && props.associations[a][aChannel] && props.associations[a][aChannel].metadata ) { aName = props.associations[a][aChannel].metadata.title !== "" ? props.associations[a][aChannel].metadata.title : a.substr(1); } if ( props.associations[b] && props.associations[b][bChannel] && props.associations[b][bChannel].metadata ) { bName = props.associations[b][bChannel].metadata.title !== "" ? props.associations[b][bChannel].metadata.title : b.substr(1); } return aName.toLowerCase().localeCompare(bName.toLowerCase()); }) .map((path) => { let name = path.substr(1); let selected = props.selected === path; let groupChannel = `${path}/contacts${path}` if ( props.associations[path] && props.associations[path][groupChannel] && props.associations[path][groupChannel].metadata ) { name = props.associations[path][groupChannel].metadata.title !== "" ? props.associations[path][groupChannel].metadata.title : path.substr(1); } return ( <GroupItem key={path} link={path} selected={selected} name={name} group={props.groups[path]} contacts={props.contacts[path]} /> ) }); let activeClasses = (this.props.activeDrawer === "groups") ? "" : "dn-s"; return ( <div className={"bn br-m br-l br-xl b--gray4 b--gray1-d lh-copy h-100 " + "flex-basis-30-ns flex-shrink-0 mw5-m mw5-l mw5-xl flex-basis-100-s " + "relative overflow-hidden pt3 pt0-m pt0-l pt0-xl " + activeClasses}> <a className="db dn-m dn-l dn-xl f8 pb6 pl3" href="/">⟵ Landscape</a> <div className="overflow-auto pb8 h-100"> <Link to="/~groups/new" className="dib"> <p className="f9 pt4 pl4 green2 bn">Create Group</p> </Link> <Welcome contacts={props.contacts}/> <h2 className="f9 pt4 pr4 pb2 pl4 gray2 c-default">Your Identity</h2> {rootIdentity} {inviteItems} <h2 className="f9 pt4 pr4 pb2 pl4 gray2 c-default">Groups</h2> {groupItems} </div> </div> ); } }
src/svg-icons/navigation/fullscreen-exit.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationFullscreenExit = (props) => ( <SvgIcon {...props}> <path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/> </SvgIcon> ); NavigationFullscreenExit = pure(NavigationFullscreenExit); NavigationFullscreenExit.displayName = 'NavigationFullscreenExit'; NavigationFullscreenExit.muiName = 'SvgIcon'; export default NavigationFullscreenExit;
src/components/Main.js
diaotai/gallery
require('normalize.css/normalize.css'); require('styles/App.scss'); var imageDatas=require("../data/imageDatas.json") import React from 'react'; // let yeomanImage = require('../images/1.jpg'); //将图片名信息转化为图片URL信息 function genURLImageData(datas){ for(let i=0;i<datas.length;i++) { let singleImageData=datas[i]; singleImageData.imageURL=require('../images/'+singleImageData.fileName) datas[i]=singleImageData } return datas; } imageDatas=genURLImageData(imageDatas) //获取区间内的随机值 function getRangeRandom(low,high){ return Math.ceil(Math.random()*(high-low)+low); } //用于获取0~30度之间的任意一个正负值 function get30DegRandom(){ return (Math.random()>0.5?'':'-')+Math.ceil(Math.random()*30) } class ImgFigure extends React.Component{ constructor(props){ super(props) this.handleClick=this.handleClick.bind(this) } handleClick(e){ if(this.props.arrange.isCenter){ this.props.inverse(); }else{ this.props.center(); } e.stopPropagation(); e.preventDefault(); } render(){ let styleObj = {}; //如果props属性中制定了这张图片的位置,则使用 if(this.props.arrange.pos){ styleObj=this.props.arrange.pos; } //如过图片的旋转角度有值且不为0,则使用 否则添加旋转角度 if(this.props.arrange.rotate){ (['MozTransfrom','msTransfrom','WebkitTransfrom','transform']).forEach(function(value){ styleObj[value]='rotate('+this.props.arrange.rotate+'deg)'; },this); } if(this.props.arrange.isCenter){ styleObj.zIndex=11; } //本处可能有错 let imgFigureClassName='img-figure'; imgFigureClassName+=this.props.arrange.isInverse?' is-inverse':''; return( <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}> <img src={this.props.data.imageURL} alt={this.props.data.title}/> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick}> <p>{this.props.data.desc}</p> </div> </figcaption> </figure> ) } } class ControllerUnit extends React.Component{ constructor(props){ super(props) this.handleClick=this.handleClick.bind(this) } handleClick(e){ //如果点击选中态按钮,则反转,否则居中 if(this.props.arrange.isCenter){ this.props.inverse(); }else{ this.props.center(); } e.preventDefault(); e.stopPropagation(); } render(){ let controllerUnitClassName="controller-unit"; //如果对应剧中图片,显示居中态 if(this.props.arrange.isCenter){ controllerUnitClassName+=" is-center"; //如果同时还是翻转态 if(this.props.arrange.isInverse) controllerUnitClassName+=" is-inverse"; } return( <span className={controllerUnitClassName} onClick={this.handleClick} ></span> ); } } // var ControllerUnit = React.createClass({ // handleClick: function(e){ // //如果点击的是当前选中态的按钮,则翻转图片,否则将对应的图片居中 // if(this.props.arrange.isCenter){ // this.props.inverse(); // } else{ // this.props.center(); // } // e.preventDefault(); // e.stopPropagation(); // }, // render: function(){ // var controllerUnitClassName = 'controller-unit'; // //如果对应的是居中的图片,显示控制按钮的居中态 // if(this.props.arrange.isCenter){ // controllerUnitClassName += ' is-center'; // //如果同时对应的是反转图片,显示控制按钮的翻转态 // if(this.props.arrange.isInverse){ // controllerUnitClassName += ' is-inverse'; // } // } // return( // <span className={controllerUnitClassName} onClick={this.handleClick}></span> // ); // } // }) class AppComponent extends React.Component { constructor(props){ super(props) this.state={ imgsArrangeArr:[ { pos:{ left:'0', right:'0' }, rotate:0,//旋转角度 isInverse:false, //图片正反,默认为正面, isCenter:false } ] } this.Constant={ centerPos:{ left:0, right:0 }, hPosRange:{ leftSecX:[0,0], rightSecX:[0,0], y:[0,0] }, vPosRange:{ x:[0,0], topY:[0,0] } } this.rearrane=this.rearrane.bind(this); this.center=this.center.bind(this); this.inverse=this.inverse.bind(this); } center(index){ return function(){ this.rearrane(index); }.bind(this); } inverse(index){ //console.log(this); return function(){ // console.log(this.state); let imgsArrangeArr=this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse=!imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr:imgsArrangeArr }) }.bind(this); } /* *重新布局所有图片 *param centerIndex指定哪一个图片居中 */ rearrane(centerIndex){ let imgsArrangeArr=this.state.imgsArrangeArr; let Constant=this.Constant, centerPos=Constant.centerPos, hPosRange=Constant.hPosRange, vPosRange=Constant.vPosRange, hPosRangeLeftSecX=hPosRange.leftSecX, hPosRangeRightSecX=hPosRange.rightSecX, hPosRangeY=hPosRange.y, vPosRangeTopY=vPosRange.topY, vPosRangeX=vPosRange.x, imgsArrangeTopArr=[], topImgNum=Math.floor(Math.random()*2) //取一个或者不取 let topImgSpliceIndex=0, imgsArrangeCenterArr=imgsArrangeArr.splice(centerIndex,1); //首先居中centerIndex的图片 imgsArrangeCenterArr[0]={ pos:centerPos, rotate:0, isCenter:true } //去除布局上侧图片的状态信息 topImgSpliceIndex=Math.ceil(Math.random()*(imgsArrangeArr,length-topImgNum)); imgsArrangeTopArr=imgsArrangeArr.splice(topImgSpliceIndex,topImgNum); //布局位于上侧的图片 imgsArrangeTopArr.forEach(function(value,index){ imgsArrangeTopArr[index]={ pos:{ top:getRangeRandom(vPosRangeTopY[0],vPosRangeTopY[1]), left:getRangeRandom(vPosRangeX[0],vPosRangeX[1]) }, rotate:get30DegRandom(), isCenter:false } }); for (var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) { var hPosRangeLORX = null; // 前半部分布局左边, 右半部分布局右边 if (i < k) { hPosRangeLORX = hPosRangeLeftSecX; } else { hPosRangeLORX = hPosRangeRightSecX; } imgsArrangeArr[i] = { pos: { top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate:get30DegRandom(), isCenter:false }; } //布局左右两侧的图片 // for(let i=0;i<imgsArrangeArr.length;i++){ // let hPosRangeLORX=null; // if(i<imgsArrangeArr/2){ // hPosRangeLORX= hPosRangeLeftSecX; // }else{ // hPosRangeLORX=hPosRangeRightSecX; // } // imgsArrangeArr[i].pos={ // top:getRangeRandom(hPosRangeY[0],hPosRangeY[1]), // left:getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1]) // } // } if(imgsArrangeTopArr&&imgsArrangeTopArr[0]) { imgsArrangeArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIndex,0,imgsArrangeCenterArr[0]); //console.log(imgsArrangeCenterArr[0].pos.left,imgsArrangeCenterArr[0].pos.top) this.setState({ imgsArrangeArr:imgsArrangeArr }); } componentDidMount(){ //获取舞台的大小 var stageDOM = this.refs.stage, stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW=Math.ceil(stageW/2), halfStageH=Math.ceil(stageH/2); //拿到一个imageFigure的大小 let imgFigureDOM=this.refs.imgFigure0, imgW=320, imgH=360, halfImgW=Math.ceil(imgW / 2), halfImgH=Math.ceil(imgH / 2); /* console.log(imgFigureDOM) console.log('stage'+stageW+' '+stageH) console.log('img'+imgW+' '+imgH) */ this.Constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH } // console.log('center'+this.Constant.centerPos.left) //计算左侧,右侧区域图片排布位置的取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[0] = stageH - halfImgH; //计算上侧区域图片排布位置的取值范围 this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.Constant.vPosRange.x[0] = halfStageW - imgW; this.Constant.vPosRange.x[1] = halfImgW; // this.rearrange(0); // //计算中心图片的位置点 // this.Constant.centerPos={ // left:halfStageW - halfImgW, // top:halfStageH - halfImgH // } // //左侧及右侧区域的位置数据 // this.Constant.hPosRange.leftSecX[0]=-halfImgW; // this.Constant.hPosRange.leftSecX[1]=halfStageW - 3 * halfImgW; // this.Constant.hPosRange.rightSecX[0]=halfStageW + halfImgW; // this.Constant.hPosRange.rightSecX[1]=stageW - halfImgW; // this.Constant.hPosRange.y[0]=-halfImgH; // this.Constant.hPosRange.y[1]=stageH - halfImgH; // //上侧区域位置数据 // this.Constant.vPosRange.topY[0]=-halfImgH; // this.Constant.vPosRange.topY[1]=halfStageH - halfImgH * 3; // this.Constant.vPosRange.x[0]=halfStageW - imgW; // this.Constant.vPosRange.x[1]=halfStageW; this.rearrane(0); } render() { let controlers=[],imgFigures=[]; imageDatas.forEach(function(value,index){ if(!this.state.imgsArrangeArr[index]){ this.state.imgsArrangeArr[index]={ pos:{ left:0, top:0 }, rotate:0, isInverse:false, isCenter:false } } imgFigures.push(<ImgFigure data={value} key={index} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>); controlers.push(<ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>) },this); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controlers} </nav> </section> ); } } AppComponent.defaultProps = { }; export default AppComponent;
src/index.js
alexras/truepeacein.space
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './views/App'; import DocumentTitle from 'react-document-title'; import './index.css'; ReactDOM.render( ( <DocumentTitle title='truepeacein.space | Metroid Password Generator'> <App /> </DocumentTitle> ), document.getElementById('root'));
examples/huge-apps/routes/Calendar/components/Calendar.js
moudy/react-router
import React from 'react'; class Calendar extends React.Component { render () { var events = [{ id: 0, title: 'essay due' }]; return ( <div> <h2>Calendar</h2> <ul> {events.map(event => ( <li key={event.id}>{event.title}</li> ))} </ul> </div> ); } } export default Calendar;
consoles/my-joy-instances/src/containers/instances/__tests__/summary.spec.js
yldio/joyent-portal
import React from 'react'; import renderer from 'react-test-renderer'; import 'jest-styled-components'; import { Summary } from '../summary'; import Theme from '@mocks/theme'; it('renders <Summary /> without throwing', () => { expect( renderer .create( <Theme> <Summary /> </Theme> ) .toJSON() ).toMatchSnapshot(); }); it('renders <Summary loading /> without throwing', () => { expect( renderer .create( <Theme> <Summary loading /> </Theme> ) .toJSON() ).toMatchSnapshot(); }); it('renders <Summary loadingError /> without throwing', () => { expect( renderer .create( <Theme> <Summary loadingError /> </Theme> ) .toJSON() ).toMatchSnapshot(); }); it('renders <Summary mutationError /> without throwing', () => { expect( renderer .create( <Theme> <Summary mutationError="some mutation error" /> </Theme> ) .toJSON() ).toMatchSnapshot(); }); it('renders <Summary starting stopping rebooting removing /> without throwing', () => { expect( renderer .create( <Theme> <Summary starting stopping rebooting removing /> </Theme> ) .toJSON() ).toMatchSnapshot(); }); it('renders <Summary starting stopping rebooting removing /> without throwing', () => { const instance1 = { id: '2252839a-e698-ceec-afac-9549ad0c6624', // eslint-disable-next-line camelcase compute_node: '70bb1cee-dba3-11e3-a799-002590e4f2b0', image: { id: '19aa3328-0025-11e7-a19a-c39077bfd4cf', name: 'Alpine 3' }, // eslint-disable-next-line camelcase primary_ip: '72.2.119.146', ips: { public: ['72.2.119.146', '72.2.119.146'], private: ['10.112.5.63', '10.112.5.63'] }, package: { name: 'g4-highcpu-128M' }, brand: 'KVM', state: 'RUNNING' }; expect( renderer .create( <Theme> <Summary instance={instance1} /> </Theme> ) .toJSON() ).toMatchSnapshot(); const instance2 = { id: '2252839a-e698-ceec-afac-9549ad0c6624', // eslint-disable-next-line camelcase compute_node: '70bb1cee-dba3-11e3-a799-002590e4f2b0', image: { id: '19aa3328-0025-11e7-a19a-c39077bfd4cf' }, // eslint-disable-next-line camelcase primary_ip: '72.2.119.146', ips: { public: ['72.2.119.146', '72.2.119.146'], private: ['10.112.5.63', '10.112.5.63'] }, package: { name: 'g4-highcpu-128M' }, brand: 'LX', state: 'RUNNING' }; expect( renderer .create( <Theme> <Summary instance={instance2} /> </Theme> ) .toJSON() ).toMatchSnapshot(); });
__tests__/components.spec.js
serkansokmen/connect4
import expect from 'expect' import React from 'react' import TestUtils from 'react-addons-test-utils' import { SplashScreenComponent, Game, Board, Piece } from '../app/Components' const setup = () => { let props = { onNewGame: expect.createSpy() } let renderer = TestUtils.createRenderer() renderer.render(<SplashScreenComponent onNewGame={props.onNewGame} />) let output = renderer.getRenderOutput() return { props, output, renderer } } // describe('components', () => { // describe('SplashScreen', () => { // // const onNewGame = expect.createSpy() // // const splashScreen = TestUtils.renderIntoDocument(<SplashScreen onNewGame={onNewGame}/>) // it('should render correctly', () => { // const { output } = setup() // // expect(splashScreen.props.className).toBe('jumbotron') // // let [ h1, button ] = output.props.children // // expect(h1.type).toBe('h1') // // expect(h1.props.children).toBe('CONNECT4') // }) // }) // })
src/components/Select/Select-story.js
jzhang300/carbon-components-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import Select from '../Select'; import SelectItem from '../SelectItem'; import SelectItemGroup from '../SelectItemGroup'; const selectProps = { onChange: action('onChange'), className: 'some-class', }; storiesOf('Select', module) .addWithInfo( 'enabled', ` Select displays a list below its title when selected. They are used primarily in forms, where a user chooses one option from a list. Once the user selects an item, the dropdown will dissapear and the field will reflect the user's choice. Create Select Item components for each option in the list. The example below shows an enabled Select component with three items. `, () => ( <Select {...selectProps} id="select-1" defaultValue="placeholder-item"> <SelectItem disabled hidden value="placeholder-item" text="Choose an option" /> <SelectItemGroup label="Category 1"> <SelectItem value="option-1" text="Option 1" /> <SelectItem value="option-2" text="Option 2" /> </SelectItemGroup> <SelectItemGroup label="Category 2"> <SelectItem value="option-3" text="Option 3" /> <SelectItem value="option-4" text="Option 4" /> </SelectItemGroup> </Select> ) ) .addWithInfo( 'inline', ` Inline select is for use when there will be multiple elements in a row `, () => ( <Select {...selectProps} inline id="select-1" defaultValue="placeholder-item"> <SelectItem disabled hidden value="placeholder-item" text="Choose an option" /> <SelectItemGroup label="Starter"> <SelectItem value="option-1" text="Option 1" /> <SelectItem value="option-2" text="Option 2" /> </SelectItemGroup> <SelectItemGroup label="Advanced"> <SelectItem value="option-3" text="Option 3" /> </SelectItemGroup> </Select> ) ) .addWithInfo( 'disabled', ` Select displays a list below its title when selected. They are used primarily in forms, where a user chooses one option from a list. Once the user selects an item, the dropdown will dissapear and the field will reflect the user's choice. Create SelectItem components for each option in the list. The example below shows an disabled Select component. `, () => ( <Select disabled {...selectProps} id="select-2"> <SelectItem disabled hidden value="placeholder-item" text="Choose an option" /> <SelectItemGroup label="Category 1"> <SelectItem value="option-1" text="Option 1" /> <SelectItem value="option-2" text="Option 2" /> </SelectItemGroup> <SelectItemGroup label="Category 2"> <SelectItem value="option-3" text="Option 3" /> </SelectItemGroup> </Select> ) ) .addWithInfo( 'no label', ` Select displays a list below its title when selected. They are used primarily in forms, where a user chooses one option from a list. Once the user selects an item, the dropdown will dissapear and the field will reflect the user's choice. Create SelectItem components for each option in the list. The example below shows a Select component without a label. `, () => ( <Select {...selectProps} id="select-3" defaultValue="placeholder-item" hideLabel> <SelectItem disabled hidden value="placeholder-item" text="Choose an option" /> <SelectItemGroup label="Starter"> <SelectItem value="option-1" text="Option 1" /> <SelectItem value="option-2" text="Option 2" /> </SelectItemGroup> <SelectItemGroup label="Category 2"> <SelectItem value="option-3" text="Option 3" /> <SelectItem value="option-4" text="Option 4" /> </SelectItemGroup> </Select> ) );
app/javascript/mastodon/features/community_timeline/components/column_settings.js
sylph-sin-tyaku/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { injectIntl, FormattedMessage } from 'react-intl'; import SettingToggle from '../../notifications/components/setting_toggle'; export default @injectIntl class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, }; render () { const { settings, onChange } = this.props; return ( <div> <div className='column-settings__row'> <SettingToggle settings={settings} settingPath={['other', 'onlyMedia']} onChange={onChange} label={<FormattedMessage id='community.column_settings.media_only' defaultMessage='Media only' />} /> </div> </div> ); } }
client/src/components/UploadField/UploadFieldItem.js
open-sausages/silverstripe-asset-admin
import i18n from 'i18n'; import React, { Component } from 'react'; import CONSTANTS from 'constants'; import fileShape from 'lib/fileShape'; import { fileSize } from 'lib/DataFormat'; import PropTypes from 'prop-types'; class UploadFieldItem extends Component { constructor(props) { super(props); this.handleRemove = this.handleRemove.bind(this); this.handleItemClick = this.handleItemClick.bind(this); this.handleView = this.handleView.bind(this); } /** * Gets props for thumbnail * * @returns {Object} */ getThumbnailStyles() { if (this.isImage() && (this.exists() || this.uploading())) { const thumbnail = this.props.item.smallThumbnail || this.props.item.url; return { backgroundImage: `url(${thumbnail})`, }; } return {}; } /** * Retrieve list of thumbnail classes * * @returns {string} */ getThumbnailClassNames() { const thumbnailClassNames = ['uploadfield-item__thumbnail']; if (this.isImageSmallerThanThumbnail()) { thumbnailClassNames.push('uploadfield-item__thumbnail--small'); } return thumbnailClassNames.join(' '); } /** * Retrieves class names for the item * * @returns {string} */ getItemClassNames() { const category = this.props.item.category || 'none'; const itemClassNames = [ 'fill-width', 'uploadfield-item', `uploadfield-item--${category}`, ]; if (this.missing()) { itemClassNames.push('uploadfield-item--missing'); } if (this.hasError()) { itemClassNames.push('uploadfield-item--error'); } return itemClassNames.join(' '); } /** * Checks if the component has an error set. * * @return {boolean} */ hasError() { if (this.props.item.message) { return this.props.item.message.type === 'error'; } return false; } /** * Determine if this is an image type * * @returns {Boolean} */ isImage() { return this.props.item.category === 'image'; } /** * Validate that the file backing this record is not missing * * @returns {Boolean} */ exists() { return this.props.item.exists; } /** * Check if this item is in the process uploaded. * If false this file was attached to this editor instead. * * @returns {boolean} */ uploading() { return this.props.item.queuedId && !this.saved(); } /** * Check if this item has been successfully uploaded. * Excludes items not uploaded in this request. * * @returns {Boolean} */ complete() { // Uploading is complete if saved with a DB id return this.props.item.queuedId && this.saved(); } /** * Check if this item has been saved, either in this request or in a prior one * * @return {Boolean} */ saved() { return this.props.item.id > 0; } /** * Check if this item should have a file, but is missing. * * @return {Boolean} */ missing() { return !this.exists() && this.saved(); } /** * Determine that this record is an image, and the thumbnail is smaller than the given * thumbnail area * * @returns {boolean} */ isImageSmallerThanThumbnail() { if (!this.isImage() || this.missing()) { return false; } const width = this.props.item.width; const height = this.props.item.height; // Note: dimensions will be null if the back-end image is lost return ( height && width && height < CONSTANTS.SMALL_THUMBNAIL_HEIGHT && width < CONSTANTS.SMALL_THUMBNAIL_WIDTH ); } /** * Handles remove (x) button click * * @param {Object} event */ handleRemove(event) { event.preventDefault(); if (this.props.onRemove) { this.props.onRemove(event, this.props.item); } } /** * Handles edit button click * * @param {Object} event */ handleView(event) { event.preventDefault(); if (this.props.onView) { this.props.onView(event, this.props.item); } } /** * Handles click of an item * * @param {Object} event */ handleItemClick(event) { event.preventDefault(); if (this.props.onItemClick) { this.props.onItemClick(event, this.props.item); } } renderStatus() { if (this.props.item.draft) { return ( <span className="uploadfield-item__status">{i18n._t('File.DRAFT', 'Draft')}</span> ); } else if (this.props.item.modified) { return ( <span className="uploadfield-item__status">{i18n._t('File.MODIFIED', 'Modified')}</span> ); } return null; } /** * Returns markup for an error message if one is set. * * @returns {Object} */ renderErrorMessage() { let message = null; if (this.hasError()) { message = this.props.item.message.value; } else if (this.missing()) { message = i18n._t('AssetAdmin.FILE_MISSING', 'File cannot be found'); } if (message !== null) { return ( <div className="uploadfield-item__error-message" title={message}> {message} </div> ); } return null; } /** * Gets upload progress bar * * @returns {object} */ renderProgressBar() { const progressBarProps = { className: 'uploadfield-item__progress-bar', style: { width: `${this.props.item.progress}%`, }, }; if (!this.hasError() && this.props.item.queuedId) { if (this.complete()) { return ( <div className="uploadfield-item__complete-icon" /> ); } return ( <div className="uploadfield-item__upload-progress"> <div {...progressBarProps} /> </div> ); } return null; } /** * Gets the remove item button * * @returns {object} */ renderRemoveButton() { if (!this.props.canEdit) { return null; } const classes = [ 'btn', 'uploadfield-item__remove-btn', 'btn-secondary', 'btn--no-text', 'font-icon-cancel', 'btn--icon-md', ].join(' '); return ( <button className={classes} onClick={this.handleRemove} /> ); } /** * Gets the edit item button * * @returns {object} */ renderViewButton() { if (!this.props.canEdit || !this.props.item.id) { return null; } const classes = [ 'btn', 'uploadfield-item__view-btn', 'btn-secondary', 'btn--no-text', 'font-icon-eye', 'btn--icon-md', ].join(' '); return ( <button className={classes} onClick={this.handleView} /> ); } /** * Get file title / metadata block * * @returns {object} */ renderFileDetails() { let size = ''; if (this.props.item.size) { size = `, ${fileSize(this.props.item.size)}`; } return ( <div className="uploadfield-item__details fill-height flexbox-area-grow"> <div className="fill-width"> <span className="uploadfield-item__title flexbox-area-grow"> {this.props.item.title} </span> </div> <div className="fill-width uploadfield-item__meta"> <span className="uploadfield-item__specs"> {this.props.item.extension}{size} </span> {this.renderStatus()} </div> </div> ); } renderThumbnail() { return ( <div className={this.getThumbnailClassNames()} style={this.getThumbnailStyles()} onClick={this.handleItemClick} role="button" tabIndex={this.props.onItemClick ? 0 : -1} /> ); } /** * * @returns {object} */ render() { const fieldName = `${this.props.name}[Files][]`; return ( <div className={this.getItemClassNames()}> <input type="hidden" value={this.props.item.id} name={fieldName} /> {this.renderThumbnail()} {this.renderFileDetails()} {this.renderProgressBar()} {this.renderErrorMessage()} {this.renderViewButton()} {this.renderRemoveButton()} </div> ); } } UploadFieldItem.propTypes = { canEdit: PropTypes.bool, name: PropTypes.string.isRequired, item: fileShape, onRemove: PropTypes.func, onItemClick: PropTypes.func, onView: PropTypes.func, }; export default UploadFieldItem;
frontend/src/Settings/DownloadClients/DownloadClients/DownloadClients.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Card from 'Components/Card'; import FieldSet from 'Components/FieldSet'; import Icon from 'Components/Icon'; import PageSectionContent from 'Components/Page/PageSectionContent'; import { icons } from 'Helpers/Props'; import translate from 'Utilities/String/translate'; import AddDownloadClientModal from './AddDownloadClientModal'; import DownloadClient from './DownloadClient'; import EditDownloadClientModalConnector from './EditDownloadClientModalConnector'; import styles from './DownloadClients.css'; class DownloadClients extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { isAddDownloadClientModalOpen: false, isEditDownloadClientModalOpen: false }; } // // Listeners onAddDownloadClientPress = () => { this.setState({ isAddDownloadClientModalOpen: true }); }; onAddDownloadClientModalClose = ({ downloadClientSelected = false } = {}) => { this.setState({ isAddDownloadClientModalOpen: false, isEditDownloadClientModalOpen: downloadClientSelected }); }; onEditDownloadClientModalClose = () => { this.setState({ isEditDownloadClientModalOpen: false }); }; // // Render render() { const { items, onConfirmDeleteDownloadClient, ...otherProps } = this.props; const { isAddDownloadClientModalOpen, isEditDownloadClientModalOpen } = this.state; return ( <FieldSet legend={translate('DownloadClients')}> <PageSectionContent errorMessage={translate('UnableToLoadDownloadClients')} {...otherProps} > <div className={styles.downloadClients}> { items.map((item) => { return ( <DownloadClient key={item.id} {...item} onConfirmDeleteDownloadClient={onConfirmDeleteDownloadClient} /> ); }) } <Card className={styles.addDownloadClient} onPress={this.onAddDownloadClientPress} > <div className={styles.center}> <Icon name={icons.ADD} size={45} /> </div> </Card> </div> <AddDownloadClientModal isOpen={isAddDownloadClientModalOpen} onModalClose={this.onAddDownloadClientModalClose} /> <EditDownloadClientModalConnector isOpen={isEditDownloadClientModalOpen} onModalClose={this.onEditDownloadClientModalClose} /> </PageSectionContent> </FieldSet> ); } } DownloadClients.propTypes = { isFetching: PropTypes.bool.isRequired, error: PropTypes.object, items: PropTypes.arrayOf(PropTypes.object).isRequired, onConfirmDeleteDownloadClient: PropTypes.func.isRequired }; export default DownloadClients;
src/routes.js
tylerchilds/pokedex
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './pages/app'; import Type from './pages/type'; import PokemonList from './pages/pokemon-list'; import Pokemon from './pages/pokemon'; const routes = ( <Route path="/" component={ App }> <IndexRoute component={ PokemonList } /> <Route path="type/:type" component={ Type } /> <Route path="pokemon/:pokemon" component={ Pokemon } /> </Route> ); export default routes;
javascript/ShareAdmin/AuthKeyForm.js
AppStateESS/stories
'use strict' import React from 'react' import PropTypes from 'prop-types' import InputField from '@essappstate/canopy-react-inputfield' const AuthKeyForm = ({host, update, save}) => { if (!host) { return <div></div> } return (<div> <InputField value={host.authkey} change={update} placeholder="Paste in authkey received from host."/> <button className="btn btn-primary" onClick={save}>Save</button> </div>) } AuthKeyForm.propTypes = { host: PropTypes.object, update: PropTypes.func, save: PropTypes.func, } export default AuthKeyForm
node_modules/semantic-ui-react/src/elements/List/ListContent.js
SuperUncleCat/ServerMonitoring
import cx from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { childrenUtils, createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META, SUI, useValueAndKey, useVerticalAlignProp, } from '../../lib' import ListDescription from './ListDescription' import ListHeader from './ListHeader' /** * A list item can contain a content. */ function ListContent(props) { const { children, className, content, description, floated, header, verticalAlign, } = props const classes = cx( useValueAndKey(floated, 'floated'), useVerticalAlignProp(verticalAlign), 'content', className, ) const rest = getUnhandledProps(ListContent, props) const ElementType = getElementType(ListContent, props) if (!childrenUtils.isNil(children)) return <ElementType {...rest} className={classes}>{children}</ElementType> return ( <ElementType {...rest} className={classes}> {ListHeader.create(header)} {ListDescription.create(description)} {content} </ElementType> ) } ListContent._meta = { name: 'ListContent', parent: 'List', type: META.TYPES.ELEMENT, } ListContent.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, /** Shorthand for ListDescription. */ description: customPropTypes.itemShorthand, /** An list content can be floated left or right. */ floated: PropTypes.oneOf(SUI.FLOATS), /** Shorthand for ListHeader. */ header: customPropTypes.itemShorthand, /** An element inside a list can be vertically aligned. */ verticalAlign: PropTypes.oneOf(SUI.VERTICAL_ALIGNMENTS), } ListContent.create = createShorthandFactory(ListContent, content => ({ content })) export default ListContent
docs/src/components/Playground/Playground.js
seekinternational/seek-asia-style-guide
import styles from './Playground.less'; import React, { Component } from 'react'; import { Alert, TextField, Button, ButtonGroup, StarIcon, MailIcon, PageBlock, Section, AsidedLayout, Columns, Card, CardGroup, Text, Positive, Critical, Secondary, Strong, Footer } from 'seek-asia-style-guide/react'; import JobStreetHeader from 'seek-asia-style-guide/jobStreet/Header/Header'; import TextLink from './Atoms/TextLink/TextLink'; import IconButton from './Atoms/IconButton/IconButton'; import Tab from './Atoms/Tab/Tab'; const renderAsideProfile = () => ( <Card transparent> <Section> <Text shouting>Profile visibility</Text> <Text secondary>Employers cant view your profile or resumes or contact you with job opportunities.</Text> </Section> </Card> ); const renderAsideProfilePhoto = () => ( <div> <Text screaming>Tom Cliff</Text> <Text waving> <div>0412 345 678</div> <div>Add a home location</div> <div>t.cliff@email.com</div> </Text> </div> ); const renderAsideSignIn = () => ( <Card transparent> <Section className={styles.marketing}> <Text shouting>Make the most of SEEK</Text> <Text>Only employers registered with SEEK can see your profile</Text> <Text>Save time everytime with pre-filled application forms</Text> <Text>Be the first to receive latest jobs and industry insights</Text> </Section> </Card> ); const renderAsideRegister = renderAsideSignIn; const renderAsideRecommendedJobs = () => ( <Card> <Section> <Text shouting>How it works</Text> <Text>Every day we look for new opportunities for you based on your profile, search, save and apply activity.</Text> <Text><TextLink href="https://www.seek.com.au">Review your profile</TextLink></Text> <Text><TextLink href="https://www.seek.com.au">Start a new search</TextLink></Text> </Section> </Card> ); const renderAsideMyActivity = () => ( <div className={styles.activityPanel}> <Text>Applied on SEEK 20 Dec 2016</Text> <div className={styles.activityMobileCustom}> <div className={styles.touchable}> No Cover Letter </div> <TextLink href="https://www.seek.com.au">Download Resume</TextLink> </div> </div> ); const renderAsideMyActivityActions = () => ( <div> <IconButton icon="delete">Remove Job</IconButton> </div> ); const renderJobDetailDate = () => ( <Text yelling secondary>18 Jan 2017</Text> ); const renderJobDetailMetadata = () => ( <div> <Card> <Section> <Button color="pink" className={styles.fullWidthTextField}>Apply for this job</Button> <Text secondary> <br /> {'Applications for this role will take you to the advertiser\'s site.'} <br /> <br /> </Text> <Columns tight> <Button color="gray" className={styles.fullWidthTextField}><StarIcon /> Save Job</Button> <Button color="gray" className={styles.fullWidthTextField}><MailIcon /> Send Job</Button> </Columns> </Section> </Card> <Card> <Section> <Text strong raw>Melbourne,</Text> <Text>CBD & Inner Suburbs</Text> <Text strong>Base + Super</Text> <Text strong>Full time</Text> <Text strong raw>Information & Communication Technology</Text> <Text>Architects</Text> </Section> </Card> </div> ); const jobDetailsContent = '<HTML><p><strong>About SEEK</strong></p> <p>We are&nbsp;the global leader in the creation and operation of online employment markets. In the ASX Top 50, SEEK has enjoyed being one of Australia\'s fastest growing businesses with a consistent and formidable position of market leadership across Australia and New Zealand and ownership stakes in leading companies across China, Brazil, Mexico, Africa and SE Asia.&nbsp;</p> <p><strong>Multiple Opportunities&nbsp;</strong></p> <p>We&nbsp;have three Software Architect opportunities currently&nbsp;available&nbsp;at SEEK. All three roles are similar from a role and day to day&nbsp;perspective, however they have&nbsp;different development and technology strategy focus&nbsp;areas, being:&nbsp;Core Business, Mobile and Cloud.</p> <p><strong>About the Opportunities&nbsp;</strong></p> <p>The Software Architect is a technology leadership position at SEEK: you\'ll drive large transformational change across IT on behalf of the business. These opportunities will enable you to:&nbsp;</p> <ul><li>Work in a passionate,&nbsp;fast growing environment where the ability to learn and adapt quickly to new methodologies and technologies is valued.</li><li>Collaborate with&nbsp;cross-functional, multi-disciplinary teams to deliver excellent software for our customers in an agile environment.</li><li>Be part of a fun, successful global online business with a diverse team of development, operations and security minded folks.</li><li>Act as an enabler for the team, removing obstacles and identifying process and technological improvements.</li><li>Strive for technical excellence and help facilitate the healthy tension between the delivery and the long term viability of the code base</li><li>Actively participate and contribute to communities of practice at SEEK and beyond.</li></ul> <p><strong>Your Work</strong></p> <p>Your work will be a compelling mix of working embedded within delivery teams and of broader architectural responsibilities, which will include:</p> <ul><li>Getting your hands dirty delivering working software</li><li>Paving the way for development streams to adopt new technology, software patterns and approaches</li><li>Providing guidance to delivery</li><li>Developing solutions, tools and processes and technological roadmaps</li><li>Leading external vendor and emergent technology evaluation</li><li>Running and supporting the technical communities of practice</li></ul> <p><strong>To Succeed&nbsp;</strong></p> <p>To be successful as a Software Architect at SEEK&nbsp;you will ideally have experiences in:</p> <ul><li>The design, build, operations and evolution of high traffic applications, networks and business critical systems on AWS or native mobile applications&nbsp;OR the modernisation of software systems while delivering on aggressive revenue focussed roadmaps&nbsp;</li><li>Ability to effectively communicate trade-offs and impacts to stakeholders&nbsp;</li><li>In-depth technical knowledge of enterprise, solution and application architectures.</li><li>Practice Evolutionary Design, posses a deep understanding of Solution Design, and be proficient in Domain Driven Design, Design Patterns and Data Modelling, OO principles etc.</li><li>Highly competent in multiple languages across multiple layers of the technology stack.</li><li>Ability to mentor and coach developers and testers to author testable, effective and clean code</li><li>Demonstrated ability to lead and coach others in agile methodologies and development practices such as: CI TDD, BDD, Kanban and Lean.</li></ul> <p><strong>Culture and Benefits</strong></p> <p>SEEK\'s commitment to fostering a productive work environment has helped us drive growth and maintain a consistently high ranking in the annual Hewitt Best Employer Award. The work environment is Agile and fast-paced, with a strong emphasis on outcomes. People like to come here – and we\'re proud of that! And we don\'t have a dress code.</p> <p><strong>How to Apply</strong></p> <p>Click the &quot;Apply for this job&quot; link&nbsp;to begin your application. If you want to know more about the role please do not hesitate to contact<strong> Melanie Whitehouse</strong>, Talent Acquisition Consultant on <strong>(03) 8517 4571</strong>,<strong>&nbsp;</strong>for a confidential conversation.</p> <p><strong>Privacy Policy</strong></p> <p>All personal information received by us from you or about you will be stored, used and disclosed by us in accordance with our privacy policy, a copy of which can be found at www.seek.com.au/privacy. &nbsp;If you&nbsp;have any questions in relation to how we may use and store your personal information please contact us at usersupport@seek.com.au.</p></HTML> <HTML>Multiple opportunities available specialising in cloud, mobile and core business Pursue mastery of software delivery and inspire software craftsmanship in others Join a bunch of like minded, smart people doing great things</HTML>'; const footerProps = { country: 'hk', language: 'en' }; export default class Playground extends Component { render() { return ( <div> <Alert hideIcon tone="info" level="primary" onClose={() => {}}><Text>Welcome to our new search page. <span className={styles.alertBreaker}>Find your dream job faster.</span></Text></Alert> <JobStreetHeader language="en" country="my" user={{}} /> <PageBlock> <Section header> <Text screaming>Button Groups</Text> </Section> <AsidedLayout reverse size="340px"> <Card> <Section> <ButtonGroup> <Button color="pink">Sign In</Button> </ButtonGroup> </Section> </Card> <Card> <Section> <ButtonGroup> <Button color="pink">Create a Profile</Button> <Button color="transparent">Cancel</Button> </ButtonGroup> </Section> </Card> <Card> <Section> <ButtonGroup> <Button color="grey">Save job</Button> <Button color="grey">Send job</Button> </ButtonGroup> </Section> </Card> <Card> <Section> <ButtonGroup> <Button color="pink">Save</Button> <Button color="transparent">Clear</Button> <Button color="transparent">Cancel</Button> </ButtonGroup> </Section> </Card> <Card> <Section> <ButtonGroup> <Button color="pink">Save</Button> <Button color="grey">Clear</Button> <Button color="grey">Cancel</Button> </ButtonGroup> </Section> </Card> </AsidedLayout> </PageBlock> <PageBlock className={styles.header}> <AsidedLayout size="340px"> <Section> <AsidedLayout renderAside={renderAsideProfilePhoto} size="400px"> <Text screaming className={styles.photo}>TC</Text> </AsidedLayout> </Section> </AsidedLayout> </PageBlock> <PageBlock> <AsidedLayout reverse renderAside={renderAsideProfile} size="340px"> <Card> <Section> <Text shouting>Personal summary</Text> <Text>Add a personal summary to your profile as a way to introduce who you are.</Text> <IconButton icon="plus">Add summary</IconButton> </Section> </Card> <Card> <Section> <Text shouting>Career history</Text> <Text>The more you let employers know about your experince the more you can stand out from other candidates.</Text> <IconButton icon="plus">Add Role</IconButton> </Section> </Card> <Card> <Section> <Text shouting>Resumé</Text> <Text waving>Default Resumé</Text> <Text secondary><TextLink href="https://www.seek.com.au">20140714_-_cc11017_development...orm.pdf</TextLink> (75.82KB Added - 16 Dec 2016)</Text> <Text>Your “Default” resumé is not visible to employers.</Text> <Text>Update your privacy setting to “Standard” so that employers can view your resumé and get in contact with job opportunities. <TextLink href="https://www.seek.com.au">Learn more</TextLink> about your privacy.</Text> <Text waving>Other Resumés</Text> <Text secondary><TextLink href="https://www.seek.com.au">Ohter_Resume.pdf</TextLink> (75.82KB Added - 16 Dec 2016)</Text> <IconButton icon="plus">Add summary</IconButton> </Section> </Card> <Card> <Section> <Text shouting>About the role you are looking for</Text> <Text secondary>Classification/s of interest:</Text> <Text secondary>Role type</Text> </Section> </Card> </AsidedLayout> </PageBlock> <PageBlock> <Section header> <Text screaming>Candidate Sign in</Text> </Section> <AsidedLayout reverse renderAside={renderAsideSignIn} size="360px"> <Card> <Section className={styles.cardHeader}> <TextLink href="https://www.seek.com.au" chevron="right">Are you an Employer?</TextLink> </Section> <Section> <TextField value="" id="email" label="Email address" inputProps={{ type: 'email' }} className={styles.fullWidthTextField} /> <TextField value="" id="password" label="Password" inputProps={{ type: 'password' }} className={styles.fullWidthTextField} /> <div> <TextLink href="https://www.seek.com.au">Forgot your password?</TextLink> </div> <Button color="pink">Sign In</Button> <Text>Don’t have an account? <TextLink href="https://www.seek.com.au">Register</TextLink></Text> </Section> </Card> </AsidedLayout> </PageBlock> <PageBlock> <Section header> <Text screaming>Register</Text> </Section> <AsidedLayout reverse renderAside={renderAsideRegister} size="360px"> <Card> <Section className={styles.cardHeader}> <TextLink href="https://www.seek.com.au" chevron="right">Are you an Employer?</TextLink> </Section> <Section> <Columns> <TextField value="" id="fname" label="First name" inputProps={{ type: 'text' }} className={styles.fullWidthTextField} /> <TextField value="" id="lname" label="Last name" inputProps={{ type: 'text' }} className={styles.fullWidthTextField} /> </Columns> <TextField value="" id="email" label="Email address" inputProps={{ type: 'email' }} className={styles.fullWidthTextField} /> <TextField value="" id="password" label="Password" inputProps={{ type: 'password' }} className={styles.fullWidthTextField} /> <Text secondary>By registering you agree to the <TextLink href="https://www.seek.com.au">SEEK privacy policy</TextLink></Text> <Button color="pink">Register</Button> <Text>Already have an account? <TextLink href="https://www.seek.com.au">Sign in</TextLink></Text> </Section> </Card> </AsidedLayout> </PageBlock> <PageBlock> <Section header> <Text screaming>Recommended jobs</Text> <Text>24 jobs showing</Text> <Tab>All</Tab> <Tab selected>New</Tab> </Section> <AsidedLayout reverse renderAside={renderAsideRecommendedJobs} size="240px"> <CardGroup> { [0, 1, 2, 3].map(n => ( <Card key={n}> <Section> <TextLink subheading href="https://www.seek.com.au">Building Supervisor</TextLink> <Text>A1 Building Group</Text> <Text>CBD & Inner Suburbs, Melbourne</Text> </Section> </Card> )) } </CardGroup> </AsidedLayout> </PageBlock> <PageBlock> <Section header> <Text screaming>Activity</Text> <Tab selected>Saved</Tab> <Tab>Applied</Tab> </Section> <CardGroup> { [0, 1, 2, 3].map(n => ( <Card key={n}> <Section> <AsidedLayout renderAside={renderAsideMyActivity} size="270px"> <TextLink subheading href="https://www.seek.com.au">Local Health District Registered Nurse</TextLink> <Text>Western NSW Local Health District</Text> <Text raw>Job posted 30d+ ago</Text> <Text raw secondary>Dubbo & Central NSW</Text> <Text secondary>Salary Rate: $29.32 to $41.18 ph</Text> <Text> Are you a Registered Nurse and looking for variety and challenges on a daily basis? Yes? Here is your chance - Full Time or Part-time available. </Text> </AsidedLayout> <AsidedLayout renderAside={renderAsideMyActivityActions} size="270px"> <IconButton icon="plus">Add Notes</IconButton> </AsidedLayout> </Section> </Card> )) } </CardGroup> </PageBlock> <PageBlock> <Section> <TextLink>Back to search results</TextLink> <AsidedLayout renderAside={renderJobDetailDate}> <Text yelling>Software Architect</Text> </AsidedLayout> <TextLink>More jobs from SEEK Limited</TextLink> </Section> <AsidedLayout reverse renderAside={renderJobDetailMetadata} size="360px"> <CardGroup> <Card> <Section> <Text> <div dangerouslySetInnerHTML={{ __html: jobDetailsContent }} // eslint-disable-line react/no-danger /> </Text> </Section> </Card> <Card> <Section> <Text>You must have the <Strong>right to live and work</Strong> in this location to apply for this job.</Text> </Section> </Card> </CardGroup> </AsidedLayout> </PageBlock> <PageBlock> <Section header> <Text screaming>This job is no longer advertised</Text> </Section> <Card> <Section> <Text> Expired jobs remain on SEEK for 90 days after last advertised, or until they are removed by the advertiser. <br /> <br /> </Text> <Button color="pink">Search for another job</Button> </Section> </Card> </PageBlock> <PageBlock> <Section header> <Text screaming>Two columns</Text> </Section> <Columns> <Card> <Section> <Text shouting>The quick brown fox</Text> <Text waving>The quick brown fox jumps over the lazy dog</Text> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel sapien lorem. Duis viverra semper lacus. Vestibulum ipsum ipsum, imperdiet a nulla eget, consequat mattis urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ultricies placerat mattis. Vestibulum ac laoreet mauris. Cras ut turpis ultrices mi placerat cursus. Sed bibendum odio eget convallis blandit. Nullam placerat elit ut porttitor dignissim. Curabitur a risus enim. Nullam sit amet nulla finibus, rutrum diam a, viverra nisi. Ut turpis sapien, convallis ut lacus sed, luctus lobortis neque. Nulla facilisi. Cras vitae orci est. Etiam nec dictum orci. Morbi nisl nulla, dictum vitae nunc quis, varius hendrerit erat.</Text> <Text>Integer at ipsum a velit elementum luctus. Sed quis odio vitae lorem gravida ornare. Integer pharetra facilisis faucibus. Nullam dignissim, justo hendrerit lacinia pulvinar, nulla sapien condimentum lacus, a tincidunt est nibh non neque. Fusce quis leo accumsan, tempus nisl nec, gravida leo. Ut non augue eget enim tempor fringilla. Nulla pellentesque condimentum risus at consequat. Sed nibh nunc, consectetur sed massa eleifend, dapibus sollicitudin nisl. Nullam leo lorem, mollis vel dolor quis, tristique laoreet ligula. Nam id mi in ante consectetur sagittis vitae ac magna. Fusce iaculis, nibh ac pellentesque luctus, eros lacus ultrices ligula, eget tincidunt metus est at nisl. Nam consectetur eros odio, nec molestie nibh rhoncus at. Aenean augue tortor, sodales non faucibus eget, hendrerit vitae quam. Integer tincidunt laoreet euismod.</Text> </Section> </Card> <Card> <Section> <Text shouting>The quick brown fox</Text> <Text waving>The quick brown fox jumps over the lazy dog</Text> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel sapien lorem. Duis viverra semper lacus. Vestibulum ipsum ipsum, imperdiet a nulla eget, consequat mattis urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ultricies placerat mattis. Vestibulum ac laoreet mauris. Cras ut turpis ultrices mi placerat cursus. Sed bibendum odio eget convallis blandit. Nullam placerat elit ut porttitor dignissim. Curabitur a risus enim. Nullam sit amet nulla finibus, rutrum diam a, viverra nisi. Ut turpis sapien, convallis ut lacus sed, luctus lobortis neque. Nulla facilisi. Cras vitae orci est. Etiam nec dictum orci. Morbi nisl nulla, dictum vitae nunc quis, varius hendrerit erat.</Text> <Text>Integer at ipsum a velit elementum luctus. Sed quis odio vitae lorem gravida ornare. Integer pharetra facilisis faucibus. Nullam dignissim, justo hendrerit lacinia pulvinar, nulla sapien condimentum lacus, a tincidunt est nibh non neque. Fusce quis leo accumsan, tempus nisl nec, gravida leo. Ut non augue eget enim tempor fringilla. Nulla pellentesque condimentum risus at consequat. Sed nibh nunc, consectetur sed massa eleifend, dapibus sollicitudin nisl. Nullam leo lorem, mollis vel dolor quis, tristique laoreet ligula. Nam id mi in ante consectetur sagittis vitae ac magna. Fusce iaculis, nibh ac pellentesque luctus, eros lacus ultrices ligula, eget tincidunt metus est at nisl. Nam consectetur eros odio, nec molestie nibh rhoncus at. Aenean augue tortor, sodales non faucibus eget, hendrerit vitae quam. Integer tincidunt laoreet euismod.</Text> </Section> </Card> </Columns> </PageBlock> <PageBlock> <Section header> <Text screaming>Three columns</Text> </Section> <Columns> <Card> <Section> <Text shouting>The quick brown fox</Text> <Text waving>The quick brown fox jumps over the lazy dog</Text> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel sapien lorem. Duis viverra semper lacus. Vestibulum ipsum ipsum, imperdiet a nulla eget, consequat mattis urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ultricies placerat mattis. Vestibulum ac laoreet mauris. Cras ut turpis ultrices mi placerat cursus. Sed bibendum odio eget convallis blandit. Nullam placerat elit ut porttitor dignissim. Curabitur a risus enim. Nullam sit amet nulla finibus, rutrum diam a, viverra nisi. Ut turpis sapien, convallis ut lacus sed, luctus lobortis neque. Nulla facilisi. Cras vitae orci est. Etiam nec dictum orci. Morbi nisl nulla, dictum vitae nunc quis, varius hendrerit erat.</Text> <Text>Integer at ipsum a velit elementum luctus. Sed quis odio vitae lorem gravida ornare. Integer pharetra facilisis faucibus. Nullam dignissim, justo hendrerit lacinia pulvinar, nulla sapien condimentum lacus, a tincidunt est nibh non neque. Fusce quis leo accumsan, tempus nisl nec, gravida leo. Ut non augue eget enim tempor fringilla. Nulla pellentesque condimentum risus at consequat. Sed nibh nunc, consectetur sed massa eleifend, dapibus sollicitudin nisl. Nullam leo lorem, mollis vel dolor quis, tristique laoreet ligula. Nam id mi in ante consectetur sagittis vitae ac magna. Fusce iaculis, nibh ac pellentesque luctus, eros lacus ultrices ligula, eget tincidunt metus est at nisl. Nam consectetur eros odio, nec molestie nibh rhoncus at. Aenean augue tortor, sodales non faucibus eget, hendrerit vitae quam. Integer tincidunt laoreet euismod.</Text> </Section> </Card> <Card> <Section> <Text shouting>The quick brown fox</Text> <Text waving>The quick brown fox jumps over the lazy dog</Text> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel sapien lorem. Duis viverra semper lacus. Vestibulum ipsum ipsum, imperdiet a nulla eget, consequat mattis urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ultricies placerat mattis. Vestibulum ac laoreet mauris. Cras ut turpis ultrices mi placerat cursus. Sed bibendum odio eget convallis blandit. Nullam placerat elit ut porttitor dignissim. Curabitur a risus enim. Nullam sit amet nulla finibus, rutrum diam a, viverra nisi. Ut turpis sapien, convallis ut lacus sed, luctus lobortis neque. Nulla facilisi. Cras vitae orci est. Etiam nec dictum orci. Morbi nisl nulla, dictum vitae nunc quis, varius hendrerit erat.</Text> <Text>Integer at ipsum a velit elementum luctus. Sed quis odio vitae lorem gravida ornare. Integer pharetra facilisis faucibus. Nullam dignissim, justo hendrerit lacinia pulvinar, nulla sapien condimentum lacus, a tincidunt est nibh non neque. Fusce quis leo accumsan, tempus nisl nec, gravida leo. Ut non augue eget enim tempor fringilla. Nulla pellentesque condimentum risus at consequat. Sed nibh nunc, consectetur sed massa eleifend, dapibus sollicitudin nisl. Nullam leo lorem, mollis vel dolor quis, tristique laoreet ligula. Nam id mi in ante consectetur sagittis vitae ac magna. Fusce iaculis, nibh ac pellentesque luctus, eros lacus ultrices ligula, eget tincidunt metus est at nisl. Nam consectetur eros odio, nec molestie nibh rhoncus at. Aenean augue tortor, sodales non faucibus eget, hendrerit vitae quam. Integer tincidunt laoreet euismod.</Text> </Section> </Card> <Card> <Section> <Text shouting>The quick brown fox</Text> <Text waving>The quick brown fox jumps over the lazy dog</Text> <Text>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vel sapien lorem. Duis viverra semper lacus. Vestibulum ipsum ipsum, imperdiet a nulla eget, consequat mattis urna. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin ultricies placerat mattis. Vestibulum ac laoreet mauris. Cras ut turpis ultrices mi placerat cursus. Sed bibendum odio eget convallis blandit. Nullam placerat elit ut porttitor dignissim. Curabitur a risus enim. Nullam sit amet nulla finibus, rutrum diam a, viverra nisi. Ut turpis sapien, convallis ut lacus sed, luctus lobortis neque. Nulla facilisi. Cras vitae orci est. Etiam nec dictum orci. Morbi nisl nulla, dictum vitae nunc quis, varius hendrerit erat.</Text> <Text>Integer at ipsum a velit elementum luctus. Sed quis odio vitae lorem gravida ornare. Integer pharetra facilisis faucibus. Nullam dignissim, justo hendrerit lacinia pulvinar, nulla sapien condimentum lacus, a tincidunt est nibh non neque. Fusce quis leo accumsan, tempus nisl nec, gravida leo. Ut non augue eget enim tempor fringilla. Nulla pellentesque condimentum risus at consequat. Sed nibh nunc, consectetur sed massa eleifend, dapibus sollicitudin nisl. Nullam leo lorem, mollis vel dolor quis, tristique laoreet ligula. Nam id mi in ante consectetur sagittis vitae ac magna. Fusce iaculis, nibh ac pellentesque luctus, eros lacus ultrices ligula, eget tincidunt metus est at nisl. Nam consectetur eros odio, nec molestie nibh rhoncus at. Aenean augue tortor, sodales non faucibus eget, hendrerit vitae quam. Integer tincidunt laoreet euismod.</Text> </Section> </Card> </Columns> </PageBlock> <PageBlock> <Section header> <Text screaming>Text variants</Text> </Section> <CardGroup> <Card> <Section> <Text shouting>Text component modifiers</Text> <Text positive>Positive text</Text> <Text critical>Critical text</Text> <Text secondary>Secondary text</Text> <Text strong>Strong text</Text> </Section> </Card> <Card> <Section> <Text shouting>Inline variant components</Text> <Text><Positive>Positive text</Positive></Text> <Text><Critical>Critical text</Critical></Text> <Text><Secondary>Secondary text</Secondary></Text> <Text><Strong>Strong text</Strong></Text> </Section> </Card> </CardGroup> </PageBlock> <Footer {...footerProps} /> <br /> <Footer {...{ ...footerProps, country: 'sg' }} /> </div> ); } }
pages/index.js
turntwogg/final-round
import React from 'react'; import { Row, Col, useTheme } from '@turntwo/react-ui'; import LazyLoad from 'react-lazyload'; import { FaAngleDoubleRight } from 'react-icons/fa'; import Page from '../components/Page'; import PageContent from '../components/PageContent'; import Container from '../components/Container'; import Heading from '../components/Heading'; import HomePageScreenshot from '../components/HomePageScreenshot'; import CornerBox from '../components/CornerBox'; import Button from '../components/Button'; import ButtonGroup from '../components/ButtonGroup'; import Slice from '../components/Slice'; import GameGrid from '../components/GameGrid'; import Redirect from '../components/Redirect'; import Typography from '../components/Typography'; import useUser from '../hooks/useUser'; import useGames from '../hooks/useGames'; const introSliceColStyles = { margin: 0, backgroundPosition: 'center center', backgroundSize: 'cover', }; const Index = () => { const user = useUser(); const games = useGames(); const theme = useTheme(); const pageHero = ( <div className="page-hero"> <Container> <div className="page-hero__inner"> <div className="page-hero__content"> <div className="page-hero__content-inner"> <div className="line-decoration"> <Typography is="h3" variant="caps" className="tk-rift" style={{ display: 'inline-block', margin: 0, backgroundColor: '#fafafc', position: 'relative', zIndex: 10, paddingRight: 14, color: 'rgba(28, 19, 52, .6)', fontWeight: 400, }} > Stay Connected </Typography> </div> <Typography is="h2" variant="caps" style={{ lineHeight: 1.03, marginBottom: 24, }} className="page-hero-title tk-rift" > Your Favorite <br /> Esports Teams <br /> and Players. </Typography> <ButtonGroup spacing={16}> <Button variant={['fancy', 'dull']} size="xlarge" href="/sign-up" > Sign Up </Button> <Button variant="fancy" size="xlarge" href="/welcome"> Try It Today{' '} <FaAngleDoubleRight style={{ marginLeft: 12 }} size={16} /> </Button> </ButtonGroup> </div> </div> <div className="page-hero__media"> <HomePageScreenshot /> </div> </div> </Container> <style jsx>{` .page-hero__inner { display: flex; flex-flow: column wrap; align-items: center; padding: ${theme.su(1.5)} ${theme.su()}; } .page-hero__content { margin-bottom: ${theme.su(2)}; } .page-hero__media { position: relative; display: flex; width: 100%; flex-basis: 100%; } :global(.page-hero-title) { font-size: 36px; } .line-decoration { position: relative; margin-bottom: 16px; } .line-decoration::after { position: absolute; top: 50%; left: 0; right: 16px; height: 1px; background-color: rgba(28, 19, 52, 0.25); transform: translateY(-50%); content: ''; } @media (min-width: ${theme.breakpoints.m}px) { .page-hero { background-image: url(${require('../static/images/home-screenshot-bg.png')}); background-size: contain; background-repeat: no-repeat; background-position: top right; } .page-hero__inner { flex-flow: row nowrap; justify-content: center; padding: ${theme.su()}; } .page-hero__content { display: flex; flex: 0 0 50%; width: 50%; } .page-hero__content-inner { margin-left: auto; } .page-hero__media { flex: 0 0 50%; max-width: 50%; width: 50%; position: relative; display: flex; flex-direction: column; justify-content: center; height: auto; height: calc(100vh - 90px - 15%); padding-left: 80px; } } @media (min-width: ${theme.breakpoints.mTweak}px) { .page-hero__inner { height: calc(100vh - ${theme.headerHeight.desktop}px); padding: 7.5% 0; } :global(.page-hero-title) { font-size: 60px; } } @media (min-width: ${theme.breakpoints.l}px) { .page-hero__content { display: flex; flex: 0 0 33.33%; width: 33.33%; } .page-hero__media { flex: 0 0 66.66%; max-width: 66.66%; width: 66.66%; } } `}</style> </div> ); if (user && user.uid) { return <Redirect to="/dashboard" />; } return ( <Page style={{ padding: 0 }}> {pageHero} <PageContent fullWidth> <Slice name="intro" noPadding> <Row style={{ margin: 0 }}> <Col sizes={{ m: 3 }} style={{ ...introSliceColStyles, backgroundImage: 'url(/static/images/deck-left.jpg)', }} /> <Col sizes={{ m: 6 }} style={{ ...introSliceColStyles, padding: theme.baseSpacingUnit, backgroundImage: 'url(/static/images/deck-center.jpg)', backgroundColor: 'rgba(255, 255, 255, 0.3)', }} > <CornerBox style={{ paddingTop: theme.baseSpacingUnit * 2, paddingBottom: theme.baseSpacingUnit * 2, color: '#fff', }} > <Heading caps center style={{ fontSize: 28, fontWeight: 700, }} className="slice__title tk-rift" > All the latest news and updates </Heading> <p className="into-slice-p" style={{ margin: '0 auto 0', color: 'rgba(255, 255, 255, .8)', }} > Bringing together the latest news in competitive gaming, providing you with up to date information on tournaments, rosters, and esports news. </p> </CornerBox> </Col> <Col sizes={{ m: 3 }} style={{ ...introSliceColStyles, backgroundImage: 'url(/static/images/deck-right.jpg)', }} /> </Row> </Slice> <Slice name="favorite-games"> <Container> <Heading className="slice__title tk-rift" center style={{ marginBottom: theme.baseSpacingUnit }} > We've got your favorite games </Heading> <div className="slice__content"> <GameGrid games={games} /> </div> </Container> </Slice> <Slice name="teams"> <Container> <Heading className="slice__title tk-rift" center caps style={{ fontWeight: 700, marginBottom: theme.baseSpacingUnit }} > Latest News, Roster Changes, &amp; More </Heading> <ul className="logos-list"> <li> <a href="/"> <img src="/static/images/team-tl.png" alt="Team Liquid" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-fnc.png" alt="Fnatic" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-c9.png" alt="Cloud 9" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-tsm.png" alt="TSM" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-imt.png" alt="Immortals" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-og.png" alt="Optic Gaming" /> </a> </li> <li> <a href="/"> <img src="/static/images/team-p1.png" alt="Pheonix1" /> </a> </li> </ul> <div className="slice__footer"> <Button href="/teams" variant="ghost" size="large"> Start Following Teams </Button> </div> </Container> </Slice> <Slice name="tournaments" textAlign="left"> <Container> <Row style={{ alignItems: 'center' }}> <Col sizes={{ m: 6 }}> <CornerBox variant="dark" style={{ display: 'inline-block' }}> <LazyLoad offset={100} height={300}> <img src="/static/images/tournaments-lol.jpg" alt="Final Round keeps you up to date with eSports tournaments" /> </LazyLoad> </CornerBox> </Col> <Col sizes={{ m: 6 }}> <Heading className="slice__title tk-rift"> Catch the Latest Pro Matches </Heading> <p> Stay up-to-date with your favorite teams and players in the biggest tournaments and matches. </p> <Button href="/tournaments" size="large"> Get Tournament Info </Button> </Col> </Row> </Container> </Slice> </PageContent> <style jsx>{` .logos-list { display: flex; flex-flow: row nowrap; justify-content: space-between; margin-bottom: ${theme.baseSpacingUnit}px; } .logos-list img { max-width: 75px; } :global(.slice--teams) { background-color: rgba(4, 19, 59, 1); background-image: url(${require('../static/images/banner-teams-small.jpg')}); background-size: cover; color: #fff; } @media (max-width: 599px) { .logos-list > li { flex: 0 50%; } } @media (max-width: ${theme.breakpoints.l - 1}px) { .logos-list { flex-flow: wrap; } .logos-list > li { flex: 0 33.33%; } .logos-list > li:last-child { margin: auto; } } @media (min-width: ${theme.breakpoints.sm}px) { .logos-list { margin-bottom: ${theme.baseSpacingUnit * 2}px; } } @media (min-width: ${theme.breakpoints.m}px) { :global(.slice--teams) { background-image: url(${require('../static/images/banner-teams.jpg')}); } .intro-slice-p { max-width: 75%; } .logos-list img { max-width: 110px; } } `}</style> </Page> ); }; export default Index;
src/routes/error/index.js
AntonyKwok/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import ErrorPage from './ErrorPage'; export default { path: '/error', action({ error }) { return { title: error.name, description: error.message, component: <ErrorPage error={error} />, status: error.status || 500, }; }, };
information/blendle-frontend-react-source/app/modules/issue/components/Region.js
BramscoChill/BlendleParser
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'components/Link'; function getStyle({ region }) { return { left: `${region.position[0]}%`, right: `${100 - region.position[2]}%`, top: `${region.position[1]}%`, bottom: `${100 - region.position[3]}%`, position: 'absolute', }; } const Region = ({ region, onClick, onMouseMove, onMouseLeave, onMouseEnter, url }) => ( <Link href={url} className="v-page-item-region" style={getStyle({ region })} onClick={onClick} onMouseEnter={onMouseEnter} onMouseMove={onMouseMove} onMouseLeave={onMouseLeave} analytics={{ type: 'page' }} /> ); Region.propTypes = { region: PropTypes.object.isRequired, onClick: PropTypes.func, onMouseMove: PropTypes.func, onMouseLeave: PropTypes.func, onMouseEnter: PropTypes.func, url: PropTypes.string.isRequired, }; export default Region; // WEBPACK FOOTER // // ./src/js/app/modules/issue/components/Region.js
src/components/upload-form.js
coding-lemur/nodefilestore
import React from 'react'; import Dropzone from 'react-dropzone'; import AddFilesButton from './add-files-button'; import EmptyFiles from './empty-files'; import FilesList from './files-list'; import FilesActionArea from './files-action-area'; import ResultContainer from './result-container'; import DataService from '../helper/data-service'; import FileViewModel from '../viewmodels/file.viewmodel'; export default class UploadForm extends React.Component { static get defaultState() { return { files: [], uploading: false, uploadFinished: false, apiResult: { downloadUrl: '', expirationDate: '', token: '' } }; } constructor(props) { super(props); this.state = UploadForm.defaultState; } render() { let filesNode; let resultContainerNode; let filesActionAreaNode; if (this.state.files.length > 0) { // has files filesNode = ( <FilesList files={this.state.files} showDeleteButtons={!(this.state.uploading || this.state.uploadFinished)} onDeleteFile={this.handleDeleteFile.bind(this)} /> ); if (this.state.uploadFinished) { resultContainerNode = ( <ResultContainer apiResult={this.state.apiResult} /> ); } else { // upload not finished filesActionAreaNode = ( <FilesActionArea disabled={this.state.uploading} onClearFiles={this.handleClearFiles.bind(this)} onUploadFiles={this.handleFilesUpload.bind(this)} /> ); } } else { // hasn't files filesNode = <EmptyFiles />; } return ( <Dropzone disableClick className="drop-zone" activeClassName="drag-over" rejectClassName="drop-rejected" onDrop={this.onDrop.bind(this)}> <div className="upload-form container"> {filesNode} {resultContainerNode} {filesActionAreaNode} <AddFilesButton disabled={this.state.uploading} onFilesAdded={this.handleFilesAdded.bind(this)} /> </div> </Dropzone> ); } handleFilesAdded(files) { if (this.state.uploadFinished) { // reset view const newState = UploadForm.defaultState; newState.files = files; this.setState(newState); } else { // add files to current queue this.setState({ files: this.state.files.concat(files) }); } } handleFilesUpload() { const dataService = new DataService(); const notify = (file, fileIndex) => { const newFiles = this.state.files; newFiles[fileIndex] = file; this.setState({ files: newFiles }); }; this.setState({ uploading: true }); dataService.uploadFiles(this.state.files, notify) .then((response) => { // upload finished this.setState({ uploading: false, uploadFinished: true, apiResult: { downloadUrl: response.downloadUrl, expirationDate: response.expirationDate, token: response.token } }); }, (error) => { console.error(error); this.setState({ uploading: false }); }); } handleClearFiles() { this.setState({ files: [] }); } handleDeleteFile(file) { if (!file) { return; } const files = this.state.files; const index = files.indexOf(file); if (index > -1) { files.splice(index, 1); this.setState({ files: files }); } } onDrop(files) { this.handleFilesAdded(files.map(file => { return new FileViewModel(file); })); } }
newclient/scripts/components/modal/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import ReactModal from 'react-modal'; import React from 'react'; import styles from './style'; export default function(props) { const onClose = props.onRequestClose !== undefined ? props.onRequestClose : () => {}; return ( <ReactModal isOpen={props.isOpen !== undefined ? props.isOpen : true} onRequestClose={onClose} className={styles.modal} overlayClassName={styles.overlay} style={props.style !== undefined ? props.style : undefined} > <div className={styles.top}> <i className={`fa fa-times ${styles.closeIcon}`} aria-hidden="true" onClick={onClose} /> </div> {props.children ? props.children : null} </ReactModal> ); }
jest-integration/tests/cleanup/2-remove-test-and-update/ClickCounter.spec.js
bruderstein/unexpected-react
import React from 'react'; import ClickCounter from '../ClickCounter'; import TestRenderer from 'react-test-renderer'; import Unexpected from 'unexpected'; import jestSnapshot from 'jest-snapshot'; import UnexpectedReact from '../../unexpected-react-test-renderer'; const expect = Unexpected.clone().use(UnexpectedReact); describe('ClickCounter', function () { it('renders with default props', function () { const renderer = TestRenderer.create(<ClickCounter />); expect(renderer, 'to match snapshot'); }); it('counts multiple clicks', function () { const renderer = TestRenderer.create(<ClickCounter />); expect(renderer, 'with event click', 'with event click', 'with event click', 'to match snapshot'); }); it('passes multiple snapshots in a single test', function () { let renderer = TestRenderer.create(<ClickCounter />); expect(renderer, 'to match snapshot'); renderer = TestRenderer.create(<ClickCounter />); expect(renderer, 'with event click', 'with event click', 'with event click', 'to match snapshot'); }); });
rallyboard-v2/client/src/LoadingStatus.js
tylerjw/rallyscores
import React, { Component } from 'react'; import { Progress, Segment, Header } from 'semantic-ui-react'; class LoadingStatus extends Component { render() { const { status } = this.props; let percent = 0; if (status === 'started') { percent = 25; } else if (status === 'pending') { percent = 50; } else if (status === 'running') { percent = 75; } else if (status === 'finished') { percent = 100; } return ( <Segment> <Header>Updating results</Header> <Progress percent={percent} indicating > Job status: {status} </Progress> </Segment> ); } } export default LoadingStatus;
redux/todoList/src/main.js
yuanzhaokang/myAwesomeSimpleDemo
import AppContainer from './appContainer'; import ReactDOM from 'react-dom'; import React from 'react'; ReactDOM.render(<AppContainer />, document.getElementById('app'));
app/src/components/Footer/Social/index.js
AlexandreBourdeaudhui/abourdeaudhui.fr
/* * Package Import */ import React from 'react'; /* * Local Import */ /* * Code */ const links = [ { label: 'Twitter', url: 'https://twitter.com/qlex_', img: '/images/twitter.svg', }, { label: 'LinkedIn', url: 'https://www.linkedin.com/in/alexandrebourdeaudhui/', img: '/images/linkedin.svg', }, { label: 'Github', url: 'https://github.com/alexandrebourdeaudhui', img: '/images/github.svg', }, ]; /* * Component */ const Social = () => ( <div id="footer-container-social"> {links.map(link => ( <span className="footer-social-items" key={link.label}> <a href={link.url}> <img alt={`Lien ${link.label}`} className="footer-social-items-image" src={link.img} /> </a> </span> ))} </div> ); /* * Export */ export default Social;
src/components/Sidebar/Contacts/Contacts.js
ryanermita/ryanermita.github.io
// @flow strict import React from 'react'; import { getContactHref, getIcon } from '../../../utils'; import Icon from '../../Icon'; import styles from './Contacts.module.scss'; type Props = { contacts: { [string]: string, }, }; const Contacts = ({ contacts }: Props) => ( <div className={styles['contacts']}> <ul className={styles['contacts__list']}> {Object.keys(contacts).map((name) => (!contacts[name] ? null : ( <li className={styles['contacts__list-item']} key={name}> <a className={styles['contacts__list-item-link']} href={getContactHref(name, contacts[name])} rel="noopener noreferrer" target="_blank" > <Icon name={name} icon={getIcon(name)} /> </a> </li> )))} </ul> </div> ); export default Contacts;
modules/experimental/AsyncProps.js
jeffreywescott/react-router
import React from 'react'; import invariant from 'invariant'; var { func, array, shape, object } = React.PropTypes; var contextTypes = { asyncProps: shape({ reloadComponent: func, propsArray: array, componentsArray: array }) }; var _serverPropsArray = null; function setServerPropsArray(array) { invariant(!_serverPropsArray, 'You cannot call AsyncProps.hydrate more than once'); _serverPropsArray = array; } export function _clearCacheForTesting() { _serverPropsArray = null; } function hydrate(routerState, cb) { var { components, params } = routerState; var flatComponents = filterAndFlattenComponents(components); loadAsyncProps(flatComponents, params, cb); } function eachComponents(components, iterator) { for (var i = 0, l = components.length; i < l; i++) { if (typeof components[i] === 'object') { for (var key in components[i]) { iterator(components[i][key], i, key); } } else { iterator(components[i], i); } } } function filterAndFlattenComponents(components) { var flattened = []; eachComponents(components, function(Component) { if (Component.loadProps) flattened.push(Component); }); return flattened; } function loadAsyncProps(components, params, cb) { var propsArray = []; var componentsArray = []; var canceled = false; var needToLoadCounter = components.length; components.forEach(function(Component, index) { Component.loadProps(params, function(error, props) { needToLoadCounter--; propsArray[index] = props; componentsArray[index] = Component; maybeFinish(); }); }); function maybeFinish() { if (canceled === false && needToLoadCounter === 0) cb(null, {propsArray, componentsArray}); } return { cancel () { canceled = true; } }; } function getPropsForComponent(Component, componentsArray, propsArray) { var index = componentsArray.indexOf(Component); return propsArray[index]; } function mergeAsyncProps(current, changes) { for (var i = 0, l = changes.propsArray.length; i < l; i++) { let Component = changes.componentsArray[i]; let position = current.componentsArray.indexOf(Component); let isNew = position === -1; if (isNew) { current.propsArray.push(changes.propsArray[i]); current.componentsArray.push(changes.componentsArray[i]); } else { current.propsArray[position] = changes.propsArray[i]; } } } function arrayDiff(previous, next) { var diff = []; for (var i = 0, l = next.length; i < l; i++) if (previous.indexOf(next[i]) === -1) diff.push(next[i]); return diff; } function shallowEqual(a, b) { var key; var ka = 0; var kb = 0; for (key in a) { if (a.hasOwnProperty(key) && a[key] !== b[key]) return false; ka++; } for (key in b) if (b.hasOwnProperty(key)) kb++; return ka === kb; } var RouteComponentWrapper = React.createClass({ contextTypes: contextTypes, // this is here to meet the case of reloading the props when a component's params change, // the place we know that is here, but the problem is we get occasional waterfall loads // when clicking links quickly at the same route, AsyncProps doesn't know to load the next // props until the previous finishes rendering. // // if we could tell that a component needs its props reloaded in AsyncProps instead of here // (by the arrayDiff stuff in componentWillReceiveProps) then we wouldn't need this code at // all, and we coudl get rid of the terrible forceUpdate hack as well. I'm just not sure // right now if we can know to reload a pivot transition. componentWillReceiveProps(nextProps, context) { var paramsChanged = !shallowEqual( this.props.routerState.routeParams, nextProps.routerState.routeParams ); if (paramsChanged) { this.reloadProps(nextProps.routerState.routeParams); } }, reloadProps(params) { this.context.asyncProps.reloadComponent( this.props.Component, params || this.props.routerState.routeParams, this ); }, render() { var { Component, routerState } = this.props; var { componentsArray, propsArray, loading } = this.context.asyncProps; var asyncProps = getPropsForComponent(Component, componentsArray, propsArray); return <Component {...routerState} {...asyncProps} loading={loading} reloadAsyncProps={this.reloadProps} />; } }); var AsyncProps = React.createClass({ statics: { hydrate: hydrate, rehydrate: setServerPropsArray, createElement(Component, state) { return typeof Component.loadProps === 'function' ? <RouteComponentWrapper Component={Component} routerState={state}/> : <Component {...state}/>; } }, childContextTypes: contextTypes, getChildContext() { return { asyncProps: Object.assign({ reloadComponent: this.reloadComponent, loading: this.state.previousProps !== null }, this.state.asyncProps), }; }, getInitialState() { return { asyncProps: { propsArray: _serverPropsArray, componentsArray: _serverPropsArray ? filterAndFlattenComponents(this.props.components) : null, }, previousProps: null }; }, componentDidMount() { var initialLoad = this.state.asyncProps.propsArray === null; if (initialLoad) { hydrate(this.props, (err, asyncProps) => { this.setState({ asyncProps }); }); } }, componentWillReceiveProps(nextProps) { var routerTransitioned = nextProps.location !== this.props.location; if (!routerTransitioned) return; var oldComponents = this.props.components; var newComponents = nextProps.components; var components = arrayDiff( filterAndFlattenComponents(oldComponents), filterAndFlattenComponents(newComponents) ); if (components.length === 0) return; this.loadAsyncProps(components, nextProps.params); }, beforeLoad(cb) { this.setState({ previousProps: this.props }, cb); }, afterLoad(err, asyncProps, cb) { this.inflightLoader = null; mergeAsyncProps(this.state.asyncProps, asyncProps); this.setState({ previousProps: null, asyncProps: this.state.asyncProps }, cb); }, loadAsyncProps(components, params, cb) { if (this.inflightLoader) { this.inflightLoader.cancel(); } this.beforeLoad(() => { this.inflightLoader = loadAsyncProps(components, params, (err, asyncProps) => { this.afterLoad(err, asyncProps, cb); }); }); }, reloadComponent(Component, params, instance) { this.loadAsyncProps([Component], params, () => { // gotta fix this hack ... change in context doesn't cause the // RouteComponentWrappers to rerender (first one will because // of cloneElement) if (instance.isMounted()) instance.forceUpdate(); }); }, render() { var { route } = this.props; var { asyncProps, previousProps } = this.state; var initialLoad = asyncProps.propsArray === null; if (initialLoad) return route.renderInitialLoad ? route.renderInitialLoad() : null; else if (previousProps) return React.cloneElement(previousProps.children, { loading: true }); else return this.props.children; } }); export default AsyncProps;
src/svg-icons/action/copyright.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionCopyright = (props) => ( <SvgIcon {...props}> <path d="M10.08 10.86c.05-.33.16-.62.3-.87s.34-.46.59-.62c.24-.15.54-.22.91-.23.23.01.44.05.63.13.2.09.38.21.52.36s.25.33.34.53.13.42.14.64h1.79c-.02-.47-.11-.9-.28-1.29s-.4-.73-.7-1.01-.66-.5-1.08-.66-.88-.23-1.39-.23c-.65 0-1.22.11-1.7.34s-.88.53-1.2.92-.56.84-.71 1.36S8 11.29 8 11.87v.27c0 .58.08 1.12.23 1.64s.39.97.71 1.35.72.69 1.2.91 1.05.34 1.7.34c.47 0 .91-.08 1.32-.23s.77-.36 1.08-.63.56-.58.74-.94.29-.74.3-1.15h-1.79c-.01.21-.06.4-.15.58s-.21.33-.36.46-.32.23-.52.3c-.19.07-.39.09-.6.1-.36-.01-.66-.08-.89-.23-.25-.16-.45-.37-.59-.62s-.25-.55-.3-.88-.08-.67-.08-1v-.27c0-.35.03-.68.08-1.01zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/> </SvgIcon> ); ActionCopyright = pure(ActionCopyright); ActionCopyright.displayName = 'ActionCopyright'; ActionCopyright.muiName = 'SvgIcon'; export default ActionCopyright;
src/svg-icons/content/flag.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentFlag = (props) => ( <SvgIcon {...props}> <path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/> </SvgIcon> ); ContentFlag = pure(ContentFlag); ContentFlag.displayName = 'ContentFlag'; ContentFlag.muiName = 'SvgIcon'; export default ContentFlag;
node_modules/react-bootstrap/es/NavItem.js
skinsshark/skinsshark.github.io
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { active: React.PropTypes.bool, disabled: React.PropTypes.bool, role: React.PropTypes.string, href: React.PropTypes.string, onClick: React.PropTypes.func, onSelect: React.PropTypes.func, eventKey: React.PropTypes.any }; var defaultProps = { active: false, disabled: false }; var NavItem = function (_React$Component) { _inherits(NavItem, _React$Component); function NavItem(props, context) { _classCallCheck(this, NavItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } NavItem.prototype.handleClick = function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, e); } } }; NavItem.prototype.render = function render() { var _props = this.props; var active = _props.active; var disabled = _props.disabled; var onClick = _props.onClick; var className = _props.className; var style = _props.style; var props = _objectWithoutProperties(_props, ['active', 'disabled', 'onClick', 'className', 'style']); delete props.onSelect; delete props.eventKey; // These are injected down by `<Nav>` for building `<SubNav>`s. delete props.activeKey; delete props.activeHref; if (!props.role) { if (props.href === '#') { props.role = 'button'; } } else if (props.role === 'tab') { props['aria-selected'] = active; } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, props, { disabled: disabled, onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return NavItem; }(React.Component); NavItem.propTypes = propTypes; NavItem.defaultProps = defaultProps; export default NavItem;
src/decorators.js
rgerstenberger/nuka-carousel
'use strict'; import React from 'react'; const DefaultDecorators = [ { component: React.createClass({ render() { return ( <button style={this.getButtonStyles(this.props.currentSlide === 0)} onClick={this.props.previousSlide}>PREV</button> ) }, getButtonStyles(disabled) { return { border: 0, background: 'rgba(0,0,0,0.4)', color: 'white', padding: 10, outline: 0, opacity: disabled ? 0.3 : 1, cursor: 'pointer' } } }), position: 'CenterLeft' }, { component: React.createClass({ render() { return ( <button style={this.getButtonStyles(this.props.currentSlide + this.props.slidesToScroll >= this.props.slideCount)} onClick={this.props.nextSlide}>NEXT</button> ) }, getButtonStyles(disabled) { return { border: 0, background: 'rgba(0,0,0,0.4)', color: 'white', padding: 10, outline: 0, opacity: disabled ? 0.3 : 1, cursor: 'pointer' } } }), position: 'CenterRight' }, { component: React.createClass({ render() { var self = this; var indexes = this.getIndexes(self.props.slideCount, self.props.slidesToScroll); return ( <ul style={self.getListStyles()}> { indexes.map(function(index) { return ( <li style={self.getListItemStyles()} key={index}> <button style={self.getButtonStyles(self.props.currentSlide === index)} onClick={self.props.goToSlide.bind(null, index)}> &bull; </button> </li> ) }) } </ul> ) }, getIndexes(count, inc) { var arr = []; for (var i = 0; i < count; i += inc) { arr.push(i); } return arr; }, getListStyles() { return { position: 'relative', margin: 0, top: -10, padding: 0 } }, getListItemStyles() { return { listStyleType: 'none', display: 'inline-block' } }, getButtonStyles(active) { return { border: 0, background: 'transparent', color: 'black', cursor: 'pointer', padding: 10, outline: 0, fontSize: 24, opacity: active ? 1 : 0.5 } } }), position: 'BottomCenter' } ]; export default DefaultDecorators;