path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/settings/SettingsPageHeader.js
great-design-and-systems/cataloguing-app
import FontAwesome from 'react-fontawesome'; import { LABEL_SETTINGS } from '../../labels/'; import React from 'react'; export const SettingsPageHeader = () => { return (<h3 className="page-header-title text-primary"><FontAwesome name="gears" size="lg" fixedWidth={true} />{LABEL_SETTINGS}</h3>); };
examples/website/src/parsers/lua/luaparse.js
w-y/ecma262-jison
import React from 'react'; import defaultParserInterface from '../utils/defaultParserInterface'; import pkg from 'luaparse/package.json'; const ID = 'luaparse'; export default { ...defaultParserInterface, id: ID, displayName: ID, version: `${pkg.version}`, homepage: pkg.homepage, locationProps: new Set(['range', 'loc']), loadParser(callback) { require(['luaparse'], callback); }, parse(luaparse, code, options={}) { return luaparse.parse(code, options); }, getDefaultOptions() { return { ranges: true, locations: false, comments: true, scope: false, luaVersion: '5.1', }; }, _getSettingsConfiguration() { return { fields: [ 'ranges', 'locations', 'comments', 'scope', ['luaVersion', ['5.1', '5.2', '5.3']], ], required: new Set(['ranges']), }; }, renderSettings(parserSettings, onChange) { return ( <div> <p> <a href="https://oxyc.github.io/luaparse/#parser-interface" target="_blank" rel="noopener noreferrer"> Option descriptions </a> </p> {defaultParserInterface.renderSettings.call( this, parserSettings, onChange, )} </div> ); }, };
src/parser/paladin/holy/modules/talents/AvengingCrusader.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import { formatNumber, formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS/index'; import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox'; import ItemHealingDone from 'interface/others/ItemHealingDone'; import Events from 'parser/core/Events'; import BeaconHealSource from '../beacons/BeaconHealSource.js'; /** * Avenging Crusader * * You become the ultimate crusader of light, increasing your Crusader Strike, Judgment, and auto-attack damage by 30%. * Crusader Strike and Judgment cool down 30% faster and heal up to 3 injured allies for 250% of the damage they deal. Lasts 20 sec. * Example Log: https://www.warcraftlogs.com/reports/QNJxrchLwB3WtXqP#fight=last&type=healing&source=7 */ class AvengingCrusader extends Analyzer { static dependencies = { beaconHealSource: BeaconHealSource, }; healing = 0; healingTransfered = 0; hits = 0; crits = 0; overHealing = 0; beaconOverhealing = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.AVENGING_CRUSADER_TALENT.id); if (!this.active) { return; } this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.AVENGING_CRUSADER_HEAL_NORMAL), this.onHit); this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(SPELLS.AVENGING_CRUSADER_HEAL_CRIT), this.onCrit); this.addEventListener(this.beaconHealSource.beacontransfer.by(SELECTED_PLAYER), this.onBeaconTransfer); } onHit(event) { this.hits += 1; this.healing += event.amount + (event.absorbed || 0); this.overHealing += (event.overheal || 0); } onCrit(event){ this.crits += 1; this.onHit(event); } onBeaconTransfer(event) { const spellId = event.originalHeal.ability.guid; if (spellId !== SPELLS.AVENGING_CRUSADER_HEAL_NORMAL.id && spellId !== SPELLS.AVENGING_CRUSADER_HEAL_CRIT.id) { return; } this.healingTransfered += event.amount + (event.absorbed || 0); this.beaconOverhealing += (event.overheal || 0); } get critRate() { return (this.crits / this.hits) || 0; } get totalHealing() { return this.healing + this.healingTransfered; } statistic() { return ( <TraitStatisticBox position={STATISTIC_ORDER.OPTIONAL()} trait={SPELLS.AVENGING_CRUSADER_TALENT.id} value={( <> <ItemHealingDone amount={this.totalHealing} /><br /> {formatPercentage(this.critRate)}% Crit Rate </> )} tooltip={( <> Hits: <b>{this.hits}</b> Crits: <b>{this.crits}</b><br /> Overhealed: <b>{formatPercentage(this.overHealing / (this.healing + this.overHealing))}%</b><br /> Beacon healing: <b>{formatNumber(this.healingTransfered)}</b><br /> Beacon overhealed: <b>{formatPercentage(this.beaconOverhealing / (this.beaconOverhealing + this.healingTransfered))}%</b><br /> </> )} /> ); } } export default AvengingCrusader;
app/packs/src/components/ContainerDatasetModal.js
ComPlat/chemotion_ELN
import React, { Component } from 'react'; import { Modal, ButtonToolbar, Button } from 'react-bootstrap'; import ContainerDataset from './ContainerDataset'; export default class ContainerDatasetModal extends Component { constructor(props) { super(props); this.datasetInput = React.createRef(); this.handleSave = this.handleSave.bind(this); } handleSave() { this.datasetInput.current.handleSave(); } render() { const { show, dataset_container, onHide, onChange, readOnly, disabled, kind } = this.props; if (show) { return ( <Modal show={show} backdrop="static" bsSize="large" dialogClassName="attachment-dataset-modal" onHide={() => (disabled ? onHide() : this.handleSave())}> <Modal.Header> <Modal.Title> {dataset_container.name} <ButtonToolbar> <Button bsStyle="light" onClick={() => (disabled ? onHide() : this.handleSave())}> <i className="fa fa-times" /> </Button> </ButtonToolbar> </Modal.Title> </Modal.Header> <Modal.Body> <ContainerDataset ref={this.datasetInput} readOnly={readOnly} dataset_container={dataset_container} kind={kind} onModalHide={() => onHide()} onChange={dataset_container => onChange(dataset_container)} /> </Modal.Body> </Modal> ); } return <div />; } }
FPL.DraftLeague.APP/src/server.js
olehhe/fpl-draft-league
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import { match } from 'react-router'; import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect'; import createHistory from 'react-router/lib/createMemoryHistory'; import {Provider} from 'react-redux'; import getRoutes from './routes'; const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort; const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: targetUrl, ws: true }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(Express.static(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res, {target: targetUrl}); }); app.use('/ws', (req, res) => { proxy.web(req, res, {target: targetUrl + '/ws'}); }); server.on('upgrade', (req, socket, head) => { proxy.ws(req, socket, head); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } json = {error: 'proxy_error', reason: error.message}; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const history = createHistory(req.originalUrl); const store = createStore(history, client); function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (renderProps) { loadOnServer({...renderProps, store, helpers: {client}}).then(() => { const component = ( <Provider store={store} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); res.status(200); global.navigator = {userAgent: req.headers['user-agent']}; res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }); } else { res.status(404).send('Not found'); } }); }); if (config.port) { server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
src/svg-icons/action/explore.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionExplore = (props) => ( <SvgIcon {...props}> <path d="M12 10.9c-.61 0-1.1.49-1.1 1.1s.49 1.1 1.1 1.1c.61 0 1.1-.49 1.1-1.1s-.49-1.1-1.1-1.1zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm2.19 12.19L6 18l3.81-8.19L18 6l-3.81 8.19z"/> </SvgIcon> ); ActionExplore = pure(ActionExplore); ActionExplore.displayName = 'ActionExplore'; ActionExplore.muiName = 'SvgIcon'; export default ActionExplore;
packages/maps/src/components/result/GoogleMapMarker.js
appbaseio/reactivesearch
/** @jsx jsx */ import { jsx } from '@emotion/core'; import React from 'react'; import types from '@appbaseio/reactivecore/lib/utils/types'; import { connect, ReactReduxContext } from '@appbaseio/reactivesearch/lib/utils'; import { InfoWindow, Marker } from '@react-google-maps/api'; import MarkerWithLabel from './addons/components/MarkerWithLabel'; import { MapPin, MapPinArrow, mapPinWrapper } from './addons/styles/MapPin'; class GoogleMapMarker extends React.Component { static contextType = ReactReduxContext; shouldComponentUpdate(nextProps) { if ( nextProps.markerOnTop === this.props.marker._id || (this.props.marker._id === this.props.markerOnTop && nextProps.markerOnTop === null) ) { return true; } if ( this.props.openMarkers[this.props.marker._id] !== nextProps.openMarkers[this.props.marker._id] ) { return true; } return false; } triggerAnalytics = () => { // click analytics would only work client side and after javascript loads const { triggerClickAnalytics, marker, index } = this.props; triggerClickAnalytics(index, marker._id); }; openMarker = () => { const { setOpenMarkers: handleOpenMarkers, openMarkers, marker, autoClosePopover, handlePreserveCenter, } = this.props; const id = marker._id; const newOpenMarkers = autoClosePopover ? { [id]: true } : { ...openMarkers, [id]: true }; handleOpenMarkers(newOpenMarkers); handlePreserveCenter(true); this.triggerAnalytics(); }; closeMarker = () => { const { setOpenMarkers: handleOpenMarkers, marker, autoClosePopover, handlePreserveCenter, openMarkers, } = this.props; const id = marker._id; const { [id]: del, ...activeMarkers } = openMarkers; const newOpenMarkers = autoClosePopover ? {} : activeMarkers; handleOpenMarkers(newOpenMarkers); handlePreserveCenter(true); }; renderPopover = (item, includeExternalSettings = false) => { let additionalProps = {}; const { getPosition, onPopoverClick, openMarkers } = this.props; if (includeExternalSettings) { // to render pop-over correctly with MarkerWithLabel additionalProps = { position: getPosition(item), defaultOptions: { pixelOffset: new window.google.maps.Size(0, -30), }, }; } if (item._id in openMarkers) { return ( <InfoWindow zIndex={500} key={`${item._id}-InfoWindow`} onCloseClick={() => this.closeMarker()} {...additionalProps} > <div>{onPopoverClick(item)}</div> </InfoWindow> ); } return null; }; increaseMarkerZIndex = () => { const { setMarkerOnTop: handleTopMarker, handlePreserveCenter, marker } = this.props; handleTopMarker(marker._id); handlePreserveCenter(true); }; removeMarkerZIndex = () => { const { setMarkerOnTop: handleTopMarker, handlePreserveCenter } = this.props; handleTopMarker(null); handlePreserveCenter(true); }; render() { const { getPosition, renderItem, defaultPin, autoClosePopover, handlePreserveCenter, onPopoverClick, marker, markerOnTop, clusterer, } = this.props; const markerProps = { position: getPosition(marker), }; if (markerOnTop === marker._id) { markerProps.zIndex = window.google.maps.Marker.MAX_ZINDEX + 1; } if (renderItem) { const data = renderItem(marker); if ('label' in data) { return ( <MarkerWithLabel key={marker._id} labelAnchor={new window.google.maps.Point(0, 0)} icon="https://i.imgur.com/h81muef.png" // blank png to remove the icon onClick={this.openMarker} onMouseOver={this.increaseMarkerZIndex} onFocus={this.increaseMarkerZIndex} onMouseOut={this.removeMarkerZIndex} onBlur={this.removeMarkerZIndex} {...markerProps} clusterer={clusterer} > <div css={mapPinWrapper}> <MapPin>{data.label}</MapPin> <MapPinArrow /> {onPopoverClick ? this.renderPopover(marker, true) : null} </div> </MarkerWithLabel> ); } else if ('icon' in data) { markerProps.icon = data.icon; } else { return ( <MarkerWithLabel key={marker._id} labelAnchor={new window.google.maps.Point(0, 0)} icon="https://i.imgur.com/h81muef.png" // blank png to remove the icon onClick={this.openMarker} onMouseOver={this.increaseMarkerZIndex} onFocus={this.increaseMarkerZIndex} onMouseOut={this.removeMarkerZIndex} onBlur={this.removeMarkerZIndex} {...markerProps} clusterer={clusterer} > <div css={mapPinWrapper}> {data.custom} {onPopoverClick ? this.renderPopover(marker, true) : null} </div> </MarkerWithLabel> ); } } else if (defaultPin) { markerProps.icon = defaultPin; } return ( <Marker key={marker._id} onClick={() => this.openMarker(marker._id, autoClosePopover || false, handlePreserveCenter) } onMouseOver={this.increaseMarkerZIndex} onFocus={this.increaseMarkerZIndex} onMouseOut={this.removeMarkerZIndex} onBlur={this.removeMarkerZIndex} {...markerProps} clusterer={clusterer} > {onPopoverClick ? this.renderPopover(marker) : null} </Marker> ); } } const mapStateToProps = state => ({ config: state.config, headers: state.appbaseRef.headers, analytics: state.analytics, }); GoogleMapMarker.propTypes = { getPosition: types.func, renderItem: types.func, defaultPin: types.string, autoClosePopover: types.bool, handlePreserveCenter: types.func, onPopoverClick: types.func, markerProps: types.props, marker: types.props, openMarkers: types.props, openMarkerInfo: types.func, closeMarkerInfo: types.func, setMarkerOnTop: types.func, markerOnTop: types.string, setOpenMarkers: types.func, index: types.number, config: types.props, analytics: types.props, headers: types.headers, }; export default connect(mapStateToProps, null)(GoogleMapMarker);
docs/pages/api-docs/step-content.js
lgollut/material-ui
import React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const pageFilename = 'api/step-content'; const requireRaw = require.context('!raw-loader!./', false, /\/step-content\.md$/); export default function Page({ docs }) { return <MarkdownDocs docs={docs} />; } Page.getInitialProps = () => { const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw }); return { demos, docs }; };
src/components/course/CourseForm.js
panel/pluralsight-react-redux
import React from 'react'; import TextInput from '../common/TextInput'; import SelectInput from '../common/SelectInput'; const CourseForm = ({course, allAuthors, onSave, onChange, onDelete, loading, deleting, errors}) => { return ( <form> <h1>Manage Course <small><a href="#" id="delete-button" disable={loading || deleting} onClick={onDelete} >{deleting ? 'Deleting...' : 'Delete'}</a></small></h1> <TextInput name="title" label="Title" value={course.title} onChange={onChange} error={errors.title} /> <SelectInput name="authorId" label="Author" value={course.authorId} defaultOption="Select Author" options={allAuthors} onChange={onChange} error={errors.authorId} /> <TextInput name="category" label="Category" value={course.category} onChange={onChange} error={errors.category} /> <TextInput name="length" label="Length" value={course.length} onChange={onChange} error={errors.length} /> <input type="submit" disable={loading || deleting} value={loading ? 'Saving...' : 'Save'} className="btn btn-primary" onClick={onSave} /> </form> ); }; CourseForm.propTypes = { course: React.PropTypes.object.isRequired, allAuthors: React.PropTypes.array, onSave: React.PropTypes.func.isRequired, onChange: React.PropTypes.func.isRequired, onDelete: React.PropTypes.func.isRequired, loading: React.PropTypes.bool, deleting: React.PropTypes.bool, errors: React.PropTypes.object }; export default CourseForm;
examples/with-now/src/App.js
jaredpalmer/react-production-starter
import './App.css'; import React from 'react'; const App = () => <div>Welcome to Razzle.</div>; export default App;
src/Create.js
mauchede/fork-api-platform-admin
import Api from '@api-platform/api-doc-parser/lib/Api'; import Resource from '@api-platform/api-doc-parser/lib/Resource'; import {Create as BaseCreate, SimpleForm} from 'react-admin'; import PropTypes from 'prop-types'; import React from 'react'; const resolveProps = props => { const {options} = props; const {inputFactory: defaultInputFactory, resource} = options; const { createFields: customFields, createProps = {}, writableFields: defaultFields, } = resource; const {options: {inputFactory: customInputFactory} = {}} = createProps; return { ...props, ...createProps, options: { ...options, fields: customFields || defaultFields.filter(({deprecated}) => !deprecated), inputFactory: customInputFactory || defaultInputFactory, }, }; }; const Create = props => { const { options: {api, fields, inputFactory, resource}, } = resolveProps(props); return ( <BaseCreate {...props}> <SimpleForm> {fields.map(field => inputFactory(field, { api, resource, }), )} </SimpleForm> </BaseCreate> ); }; Create.propTypes = { options: PropTypes.shape({ api: PropTypes.instanceOf(Api).isRequired, inputFactory: PropTypes.func.isRequired, resource: PropTypes.instanceOf(Resource).isRequired, }), }; export default Create;
blueocean-material-icons/src/js/components/svg-icons/action/settings-bluetooth.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionSettingsBluetooth = (props) => ( <SvgIcon {...props}> <path d="M11 24h2v-2h-2v2zm-4 0h2v-2H7v2zm8 0h2v-2h-2v2zm2.71-18.29L12 0h-1v7.59L6.41 3 5 4.41 10.59 10 5 15.59 6.41 17 11 12.41V20h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 3.83l1.88 1.88L13 7.59V3.83zm1.88 10.46L13 16.17v-3.76l1.88 1.88z"/> </SvgIcon> ); ActionSettingsBluetooth.displayName = 'ActionSettingsBluetooth'; ActionSettingsBluetooth.muiName = 'SvgIcon'; export default ActionSettingsBluetooth;
node_modules/react-navigation/lib-rn/views/withNavigation.js
joan17cast/Enigma
import React from 'react'; import propTypes from 'prop-types'; import hoistStatics from 'hoist-non-react-statics'; var babelPluginFlowReactPropTypes_proptype_NavigationAction = require('../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationAction || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_NavigationState = require('../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationState || require('prop-types').any; export default function withNavigation(Component) { const componentWithNavigation = (props, { navigation }) => <Component {...props} navigation={navigation} />; componentWithNavigation.displayName = `withNavigation(${Component.displayName || Component.name})`; componentWithNavigation.contextTypes = { navigation: propTypes.object.isRequired }; return hoistStatics(componentWithNavigation, Component); }
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
NajibOsman/Githubuser
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
src/containers/Search/SearchResults.js
codaco/Network-Canvas
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import Loading from '../../components/Loading'; import CardList from '../../components/CardList'; // This provides a workaround for visibility when a softkeyboard scrolls the viewport // (for example, on iOS). TODO: better solution once animation is in place. function styleForSoftKeyboard() { let style = {}; const scrollTop = window.pageYOffset || window.scrollY || 0; if (scrollTop > 0) { style = { height: `calc(100% - 320px - ${scrollTop}px)`, minHeight: '10em', }; } return style; } /** * @class SearchResults * @extends Component * * @description * Thin wrapper to render {@link Search} component results in a CardList. * * @param props.hasInput {boolean} true if there is user input to the search component * @param props.results {array} the search results to render. See CardList for formatters. */ class SearchResults extends Component { getResults() { const { hasInput, awaitingResults, results, ...rest } = this.props; if (awaitingResults) { return <Loading message="Performing search..." />; } if (results.length) { return ( <CardList className="card-list--single" items={results} {...rest} /> ); } if (hasInput) { return (<p>Nothing matching that search</p>); } return null; } render() { const { hasInput, } = this.props; const style = styleForSoftKeyboard(); const classNames = cx( 'search__results', { 'search__results--collapsed': !hasInput }, ); return ( <div className={classNames} style={style}> {this.getResults()} </div> ); } } SearchResults.propTypes = { hasInput: PropTypes.bool.isRequired, results: PropTypes.array.isRequired, }; export default SearchResults;
examples/src/components/MultiSelectField.js
jwarning/react-select
import React from 'react'; import Select from 'react-select'; function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } var MultiSelectField = React.createClass({ displayName: 'MultiSelectField', propTypes: { label: React.PropTypes.string, }, getInitialState () { return { disabled: false, value: [] }; }, handleSelectChange (value, values) { logChange('New value:', value, 'Values:', values); this.setState({ value: value }); }, toggleDisabled (e) { this.setState({ 'disabled': e.target.checked }); }, render () { var ops = [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla' }, { label: 'Strawberry', value: 'strawberry' }, { label: 'Caramel', value: 'caramel' }, { label: 'Cookies and Cream', value: 'cookiescream' }, { label: 'Peppermint', value: 'peppermint' } ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select multi={true} disabled={this.state.disabled} value={this.state.value} placeholder="Select your favourite(s)" options={ops} onChange={this.handleSelectChange} /> <div className="checkbox-list"> <label className="checkbox"> <input type="checkbox" className="checkbox-control" checked={this.state.disabled} onChange={this.toggleDisabled} /> <span className="checkbox-label">Disabled</span> </label> </div> </div> ); } }); module.exports = MultiSelectField;
website/src/BrowserAppContainer.js
Steviey/win-react-navigation
import React from 'react'; import { NavigationActions, addNavigationHelpers } from 'react-navigation'; function getAction(router, path, params) { const action = router.getActionForPathAndParams(path, params); if (action) { return action; } return NavigationActions.navigate({ params: { path }, routeName: 'NotFound', }); } module.exports = (NavigationAwareView) => { const initialAction = getAction(NavigationAwareView.router, window.location.pathname.substr(1)); const initialState = NavigationAwareView.router.getStateForAction(initialAction); console.log({initialAction, initialState}); class NavigationContainer extends React.Component { state = initialState; componentDidMount() { document.title = NavigationAwareView.router.getScreenConfig({state: this.state.routes[this.state.index], dispatch: this.dispatch}, 'title'); window.onpopstate = (e) => { e.preventDefault(); const action = getAction(NavigationAwareView.router, window.location.pathname.substr(1)); if (action) this.dispatch(action); }; } componentWillUpdate(props, state) { const {path} = NavigationAwareView.router.getPathAndParamsForState(state); const uri = `/${path}`; if (window.location.pathname !== uri) { window.history.pushState({}, state.title, uri); } document.title = NavigationAwareView.router.getScreenConfig({state: state.routes[state.index], dispatch: this.dispatch}, 'title'); } dispatch = (action) => { const state = NavigationAwareView.router.getStateForAction(action, this.state); if (!state) { console.log('Dispatched action did not change state: ', {action}); } else if (console.group) { console.group('Navigation Dispatch: '); console.log('Action: ', action); console.log('New State: ', state); console.log('Last State: ', this.state); console.groupEnd(); } else { console.log('Navigation Dispatch: ', {action, newState: state, lastState: this.state}); } if (!state) { return true; } if (state !== this.state) { this.setState(state); return true; } return false; }; render() { return <NavigationAwareView navigation={addNavigationHelpers({state: this.state, dispatch: this.dispatch})} /> } getURIForAction = (action) => { const state = NavigationAwareView.router.getStateForAction(action, this.state) || this.state; const {path} = NavigationAwareView.router.getPathAndParamsForState(state); return `/${path}`; } getActionForPathAndParams = (path, params) => { return NavigationAwareView.router.getActionForPathAndParams(path, params); } static childContextTypes = { getActionForPathAndParams: React.PropTypes.func.isRequired, getURIForAction: React.PropTypes.func.isRequired, dispatch: React.PropTypes.func.isRequired, }; getChildContext() { return { getActionForPathAndParams: this.getActionForPathAndParams, getURIForAction: this.getURIForAction, dispatch: this.dispatch, }; } } return NavigationContainer; };
client/modules/App/__tests__/App.spec.js
eantler/google
import React from 'react'; import test from 'ava'; import sinon from 'sinon'; import { shallow, mount } from 'enzyme'; import { App } from '../App'; import styles from '../App.css'; import { intlShape } from 'react-intl'; import { intl } from '../../../util/react-intl-test-helper'; import { toggleAddPost } from '../AppActions'; const intlProp = { ...intl, enabledLanguages: ['en', 'fr'] }; const children = <h1>Test</h1>; const dispatch = sinon.spy(); const props = { children, dispatch, intl: intlProp, }; test('renders properly', t => { const wrapper = shallow( <App {...props} /> ); // t.is(wrapper.find('Helmet').length, 1); t.is(wrapper.find('Header').length, 1); t.is(wrapper.find('Footer').length, 1); t.is(wrapper.find('Header').prop('toggleAddPost'), wrapper.instance().toggleAddPostSection); t.truthy(wrapper.find('Header + div').hasClass(styles.container)); t.truthy(wrapper.find('Header + div').children(), children); }); test('calls componentDidMount', t => { sinon.spy(App.prototype, 'componentDidMount'); mount( <App {...props} />, { context: { router: { isActive: sinon.stub().returns(true), push: sinon.stub(), replace: sinon.stub(), go: sinon.stub(), goBack: sinon.stub(), goForward: sinon.stub(), setRouteLeaveHook: sinon.stub(), createHref: sinon.stub(), }, intl, }, childContextTypes: { router: React.PropTypes.object, intl: intlShape, }, }, ); t.truthy(App.prototype.componentDidMount.calledOnce); App.prototype.componentDidMount.restore(); }); test('calling toggleAddPostSection dispatches toggleAddPost', t => { const wrapper = shallow( <App {...props} /> ); wrapper.instance().toggleAddPostSection(); t.truthy(dispatch.calledOnce); t.truthy(dispatch.calledWith(toggleAddPost())); });
packages/es-components/src/components/controls/answer-group/AnswerButton.js
jrios/es-components
/* eslint react/prop-types: 0 */ import React from 'react'; import styled from 'styled-components'; import useUniqueId from '../../util/useUniqueId'; import { useTheme } from '../../util/useTheme'; import ValidationContext from '../ValidationContext'; const AnswerLabel = styled.label` flex-grow: 1; @media (min-width: ${props => props.theme.screenSize.tablet}) { flex-grow: 0; min-width: ${props => props.itemWidth}; } `; const AnswerDisplay = styled.div` background-color: ${props => props.buttonStyle.bgColor}; border-color: transparent; box-shadow: 0 4px 0 0 ${props => props.buttonStyle.boxShadowColor}; color: ${props => props.buttonStyle.textColor}; font-weight: ${props => props.buttonSize.fontWeight || 'normal'}; font-size: ${props => props.buttonSize.fontSize}; line-height: ${props => props.buttonSize.lineHeight}; margin-bottom: 4px; margin-top: 0; padding-top: ${props => props.buttonSize.paddingTop}; padding-right: ${props => props.buttonSize.paddingSides}; padding-bottom: ${props => props.buttonSize.paddingBottom}; padding-left: ${props => props.buttonSize.paddingSides}; text-align: center; text-transform: ${props => props.buttonSize.textTransform ? props.buttonSize.textTransform : 'none'}; transition: background-color 250ms linear, color 250ms linear; user-select: none; &:active { background-color: ${props => props.buttonStyle.activeBgColor}; box-shadow: 0 0 0 0 transparent; color: ${props => props.buttonStyle.activeTextColor}; margin-bottom: 0; margin-top: 4px; } &:hover { background-color: ${props => props.buttonStyle.hoverBgColor}; color: ${props => props.buttonStyle.hoverTextColor}; } &[disabled] { cursor: not-allowed; opacity: 0.65; > * { pointer-events: none; } } `; const OutlineAnswerDisplay = styled(AnswerDisplay)` background-color: ${props => props.isChecked ? props.buttonStyle.hoverBgColor : props.buttonStyle.bgColor}; border: 2px solid ${props => props.buttonStyle.borderColor}; box-shadow: ${props => (props.isChecked ? '0 0 0 0' : 'none')} ${props => props.isChecked && props.buttonStyle.boxShadowColor}; box-sizing: border-box; color: ${props => props.isChecked ? props.buttonStyle.hoverTextColor : props.buttonStyle.textColor}; margin: 0; &:active { margin: 0; } `; const AnswerInput = styled.input` clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; &:focus + div { background-color: ${props => props.buttonStyle.activeBgColor}; color: ${props => props.buttonStyle.activeTextColor}; } `; function AnswerButton({ name, children, itemWidth, styleType, selectedType, size, isOutline, checked, ...radioProps }) { const id = useUniqueId(radioProps.id); const isChecked = radioProps.checked || radioProps.defaultChecked; const theme = useTheme(); const validationState = React.useContext(ValidationContext); const buttonType = isOutline ? 'outlineButton' : 'button'; const buttonSize = theme.buttonStyles[buttonType].size[size]; const variant = validationState !== 'default' && !isOutline ? validationState : styleType; const validationBorder = theme.buttonStyles[buttonType].variant[validationState].borderColor; let selectedStyles = theme.buttonStyles[buttonType].variant[selectedType]; let unSelectedStyles = theme.buttonStyles[buttonType].variant[variant]; if (isOutline && validationState !== 'default') { selectedStyles = { ...selectedStyles, borderColor: validationBorder }; unSelectedStyles = { ...unSelectedStyles, borderColor: validationBorder }; } const buttonStyle = isChecked ? selectedStyles : unSelectedStyles; const buttonProps = { disabled: radioProps.disabled, isChecked, buttonStyle, buttonSize }; const labelProps = { disabled: radioProps.disabled, itemWidth, htmlFor: id, validationState }; const Display = isOutline ? OutlineAnswerDisplay : AnswerDisplay; return ( <AnswerLabel {...labelProps}> <AnswerInput type="radio" name={name} id={id} buttonStyle={buttonStyle} {...radioProps} /> <Display {...buttonProps}>{children}</Display> </AnswerLabel> ); } export default AnswerButton;
frontend/components/host/host_home_container.js
qydchen/SafeHavn
import React from 'react'; import HostHome from './host_home'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { createHome } from '../../actions/home_actions'; import { fetchMapInfo } from '../../actions/map_actions'; const mapStateToProps = ({session, homes, map}) => { return { loggedIn: !!session.currentUser, currentUser: session.currentUser, lat: map.lat, lng: map.lng, address: map.address, } }; const mapDispatchToProps = (dispatch) => { return { createHome: home => dispatch(createHome(home)), fetchMapInfo: info => dispatch(fetchMapInfo(info)), } }; export default withRouter(connect( mapStateToProps, mapDispatchToProps )(HostHome));
src/svg-icons/content/text-format.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentTextFormat = (props) => ( <SvgIcon {...props}> <path d="M5 17v2h14v-2H5zm4.5-4.2h5l.9 2.2h2.1L12.75 4h-1.5L6.5 15h2.1l.9-2.2zM12 5.98L13.87 11h-3.74L12 5.98z"/> </SvgIcon> ); ContentTextFormat = pure(ContentTextFormat); ContentTextFormat.displayName = 'ContentTextFormat'; ContentTextFormat.muiName = 'SvgIcon'; export default ContentTextFormat;
src/svg-icons/action/settings.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettings = (props) => ( <SvgIcon {...props}> <path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"/> </SvgIcon> ); ActionSettings = pure(ActionSettings); ActionSettings.displayName = 'ActionSettings'; ActionSettings.muiName = 'SvgIcon'; export default ActionSettings;
src/React/Widgets/SelectionEditorWidget/range/FiveClauseRender.js
Kitware/paraviewweb
import React from 'react'; import PropTypes from 'prop-types'; import style from 'PVWStyle/ReactWidgets/SelectionEditorWidget.mcss'; import Ineq from '../../../../../svg/Operations/Ineq.svg'; import Ineqq from '../../../../../svg/Operations/Ineqq.svg'; import LegendIcon from '../LegendIcon'; import NumberFormatter, { sciNotationRegExp, } from '../../../../Common/Misc/NumberFormatter'; import SvgIconWidget from '../../SvgIconWidget'; const CHOICE_LABELS = { o: Ineq, '*': Ineqq, }; const NEXT_VALUE = { o: '*', '*': 'o', }; // typical intervalSpec we are rendering as 5 clauses: // { // "interval": [ // 233, // 1.7976931348623157e+308 // ], // "endpoints": "oo", // "uncertainty": 15 // } export default function render(props) { const { intervalSpec, fieldName } = props; const terms = [ intervalSpec.interval[0], intervalSpec.endpoints.slice(0, 1), fieldName, intervalSpec.endpoints.slice(1, 2), intervalSpec.interval[1], ]; const formatter = new NumberFormatter(3, [ Number(terms[0]), Number(terms[4]), ]); function onChange(e, force = false) { if (!e.target.validity.valid) { return; } const value = e.target.value; const shouldBeNumber = e.target.nodeName === 'INPUT'; const path = [].concat(props.path, Number(e.target.dataset.path)); if (shouldBeNumber) { path.push(!force ? value : Number(formatter.eval(Number(value)))); } else { path.push(value); } props.onChange(path, !force); } function onBlur(e) { onChange(e, true); } function onDelete() { props.onDelete(props.path); } function toggleIneq(e) { let target = e.target; while (!target.dataset) { target = target.parentNode; } const idx = Number(target.dataset.path); const path = [].concat(props.path, idx, NEXT_VALUE[terms[idx]]); props.onChange(path); } return ( <section className={style.fiveClauseContainer}> <input className={style.numberInput} type="text" pattern={sciNotationRegExp} data-path="0" value={terms[0]} onChange={onChange} onBlur={onBlur} /> <div className={style.activeInequality} data-path="1" onClick={toggleIneq} > <SvgIconWidget style={{ pointerEvents: 'none' }} width="20px" height="20px" icon={CHOICE_LABELS[terms[1]]} /> </div> <div className={style.inequality} title={terms[2]}> <LegendIcon width="20px" height="20px" getLegend={props.getLegend} name={terms[2]} /> </div> <div className={style.activeInequality} data-path="3" onClick={toggleIneq} > <SvgIconWidget style={{ pointerEvents: 'none' }} width="20px" height="20px" icon={CHOICE_LABELS[terms[3]]} /> </div> <input className={style.numberInput} type="text" pattern={sciNotationRegExp} data-path="4" value={terms[4]} // formatter.eval(terms[1]) onChange={onChange} onBlur={onBlur} /> <i className={style.deleteButton} onClick={onDelete} /> </section> ); } render.propTypes = { getLegend: PropTypes.func.isRequired, fieldName: PropTypes.string.isRequired, intervalSpec: PropTypes.object.isRequired, path: PropTypes.array.isRequired, onChange: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, };
screens/MeditationListScreen.js
FuzzyHatPublishing/isleep
import React, { Component } from 'react'; import { Image, Platform, StyleSheet, Text, TouchableHighlight, View } from 'react-native'; class MeditationListScreen extends Component { static navigationOptions = ({ navigation }) => ({ title: 'Meditations', headerStyle: { marginTop: Platform.OS === 'android' ? 24: 0, backgroundColor: "#000" }, headerTitleStyle: { color: '#fff', fontSize: 22, fontWeight: 'bold', marginHorizontal: 8, alignSelf: 'center' } }); state = { meditations: [] }; componentWillMount() { let meditationData = require('../assets/data/meditation_data'); this.setState({ meditations: meditationData }); } _getImage(meditation) { return meditation.id == 1 ? require('../assets/images/sky-moon-cloud-min.jpg') : require('../assets/images/beach-meditation-min.jpg') } render() { const { navigate } = this.props.navigation; return ( <View style={styles.container}> { this.state.meditations.map((meditation) => ( <TouchableHighlight key={meditation.id} underlayColor={'#181818'} onPress={ () => navigate('meditation', {meditation}) } > <View> <Image style={styles.imageStyle} source={ this._getImage(meditation) } > <View style={styles.textContainer}> <View style={styles.textRow}> <Text style={styles.textStyle}>{meditation.title}</Text> <Text style={styles.textStyle}>{meditation.length}</Text> </View> </View> </Image> </View> </TouchableHighlight> )) } </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'black', justifyContent: 'space-between', paddingTop: 50, paddingBottom: 5 }, imageStyle: { height: 200, width: null }, textContainer: { flex: 1, flexDirection: 'column', justifyContent: 'flex-end', paddingBottom: 5, paddingLeft: 20, paddingRight: 20, }, textRow: { flexDirection: 'row', justifyContent: 'space-between' }, textStyle: { color: '#fff', fontWeight: 'bold', fontSize: 16 } }); export default MeditationListScreen;
frontend/src/Datarow.js
b00lduck/raspberry_soundboard
import React from 'react'; import './Datarow.css'; import Rainbow from './Rainbow.js'; export default class Sound extends React.Component { constructor(props) { super(props); var newState = props.data; var rainbow = new Rainbow(); newState.color = '#' + rainbow.colourAt(props.data.Temperature); this.state = newState; } componentWillReceiveProps(props) { var newState = props.data; var rainbow = new Rainbow(); newState.color = '#' + rainbow.colourAt(props.data.Temperature); this.setState(newState); } render() { return ( <div className="Datarow"> <div className="left" style={{background: this.state.color}}>{this.state.Count}x</div> <div className="right" style={{background: this.state.color}}>{Math.round(this.state.Temperature * 100) / 100}°</div> </div> ) } }
packages/web/src/components/shared/SearchSvg.js
appbaseio/reactivesearch
import React from 'react'; const SearchSvg = (props = {}) => ( <svg alt="Search" className="search-icon" height="12" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15" style={{ transform: 'scale(1.35)', position: 'relative', ...(props.style ? props.style : {}), }} > <title>Search</title> <path d=" M6.02945,10.20327a4.17382,4.17382,0,1,1,4.17382-4.17382A4.15609,4.15609, 0,0,1,6.02945,10.20327Zm9.69195,4.2199L10.8989,9.59979A5.88021,5.88021, 0,0,0,12.058,6.02856,6.00467,6.00467,0,1,0,9.59979,10.8989l4.82338, 4.82338a.89729.89729,0,0,0,1.29912,0,.89749.89749,0,0,0-.00087-1.29909Z " /> </svg> ); export default SearchSvg;
fields/types/relationship/RelationshipColumn.js
ONode/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; const moreIndicatorStyle = { color: '#bbb', fontSize: '.8rem', fontWeight: 500, marginLeft: 8, }; var RelationshipColumn = React.createClass({ displayName: 'RelationshipColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderMany (value) { if (!value || !value.length) return; const refList = this.props.col.field.refList; const items = []; for (let i = 0; i < 3; i++) { if (!value[i]) break; if (i) { items.push(<span key={'comma' + i}>, </span>); } items.push( <ItemsTableValue interior truncate={false} key={'anchor' + i} to={Keystone.adminPath + '/' + refList.path + '/' + value[i].id}> {value[i].name} </ItemsTableValue> ); } if (value.length > 3) { items.push(<span key="more" style={moreIndicatorStyle}>[...{value.length - 3} more]</span>); } return ( <ItemsTableValue field={this.props.col.type}> {items} </ItemsTableValue> ); }, renderValue (value) { if (!value) return; const refList = this.props.col.field.refList; return ( <ItemsTableValue to={Keystone.adminPath + '/' + refList.path + '/' + value.id} padded interior field={this.props.col.type}> {value.name} </ItemsTableValue> ); }, render () { const value = this.props.data.fields[this.props.col.path]; const many = this.props.col.field.many; return ( <ItemsTableCell> {many ? this.renderMany(value) : this.renderValue(value)} </ItemsTableCell> ); }, }); module.exports = RelationshipColumn;
src/svg-icons/image/flash-off.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFlashOff = (props) => ( <SvgIcon {...props}> <path d="M3.27 3L2 4.27l5 5V13h3v9l3.58-6.14L17.73 20 19 18.73 3.27 3zM17 10h-4l4-8H7v2.18l8.46 8.46L17 10z"/> </SvgIcon> ); ImageFlashOff = pure(ImageFlashOff); ImageFlashOff.displayName = 'ImageFlashOff'; export default ImageFlashOff;
src/components/Example.js
Abrax20/snap-react
// @flow import React, { Component } from 'react'; import { View, Text, StyleSheet, TouchableHighlight } from 'react-native'; import { Container, Header, Content, Footer, Title, Icon } from 'native-base'; import { Actions } from 'react-native-router-flux'; export default class Example extends Component { render() { return ( <Container> <Header> <Title>Header</Title> </Header> <Content> <Text>Hallo</Text> </Content> <Footer> <TouchableHighlight onPress={Actions.camera} > <Title> <Text > Klick mich </Text> {/* <Icon name="camera" style={{fontSize: 50}} onPress={Actions.camera} /> */} </Title> </TouchableHighlight> </Footer> </Container> ); } }
code/workspaces/web-app/src/containers/modal/LoadUserManagementModalWrapper.js
NERC-CEH/datalab
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { mapKeys, get, find } from 'lodash'; import dataStorageActions from '../../actions/dataStorageActions'; import userActions from '../../actions/userActions'; import notify from '../../components/common/notify'; class LoadUserManagementModalWrapper extends Component { constructor(props, context) { super(props, context); this.addUser = this.addUser.bind(this); this.removeUser = this.removeUser.bind(this); } componentDidMount() { // Added .catch to prevent unhandled promise error, when lacking permission to view content this.props.actions.listUsers() .catch(() => {}); } shouldComponentUpdate(nextProps) { const isFetching = nextProps.dataStorage.fetching; return !isFetching; } addUser({ value }) { const { name } = this.getDataStore(); this.props.actions.addUserToDataStore(this.props.projectKey, { name, users: [value] }) .then(() => notify.success('User added to data store')) .then(() => this.props.actions.loadDataStorage(this.props.projectKey)); } removeUser({ value }) { if (this.props.loginUserId !== value) { const { name } = this.getDataStore(); this.props.actions.removeUserFromDataStore(this.props.projectKey, { name, users: [value] }) .then(() => notify.success('User removed from data store')) .then(() => this.props.actions.loadDataStorage(this.props.projectKey)); } else { notify.error('Unable to remove self'); } } remapKeys(users) { if (this.props.userKeysMapping) { return users.map(user => mapKeys(user, (value, key) => get(this.props.userKeysMapping, key))); } return users; } getDataStore() { return find(this.props.dataStorage.value, ({ id }) => id === this.props.dataStoreId); } getCurrentUsers() { const { users } = this.getDataStore(); const invertedMapping = Object.entries(this.props.userKeysMapping) .map(([key, value]) => ({ [value]: key })) .reduce((previous, current) => ({ ...previous, ...current }), {}); let currentUsers; if (!this.props.users.fetching && this.props.users.value.length > 0) { currentUsers = users.map(user => find(this.props.users.value, { [invertedMapping.value]: user })); } else { currentUsers = []; } return this.remapKeys(currentUsers); } render() { const { Dialog } = this.props; return ( <Dialog onCancel={this.props.onCancel} title={this.props.title} currentUsers={this.getCurrentUsers()} userList={this.remapKeys(this.props.users.value)} loadUsersPromise={this.props.users} addUser={this.addUser} removeUser={this.removeUser} stack={this.props.stack} typeName={this.props.typeName} projectKey={this.props.projectKey} /> ); } } LoadUserManagementModalWrapper.propTypes = { title: PropTypes.string.isRequired, onCancel: PropTypes.func.isRequired, Dialog: PropTypes.func.isRequired, dataStoreId: PropTypes.string.isRequired, projectKey: PropTypes.string.isRequired, userKeysMapping: PropTypes.object.isRequired, }; function mapStateToProps({ authentication: { identity: { sub } }, dataStorage, users }) { return { loginUserId: sub, dataStorage, users }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({ ...dataStorageActions, ...userActions, }, dispatch), }; } export { LoadUserManagementModalWrapper as PureLoadUserManagementModalWrapper }; // export for testing export default connect(mapStateToProps, mapDispatchToProps)(LoadUserManagementModalWrapper);
fixtures/browser/graphql-with-mjs/src/index.js
IamJoseph/create-react-app
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
src/js/pages/Proposals/Project/AvailabilityDatesPage.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import translate from '../../../i18n/Translate'; import TopNavBar from '../../../components/TopNavBar/TopNavBar.js'; import '../../../../scss/pages/proposals/project/availability-dates.scss'; import connectToStores from "../../../utils/connectToStores"; import * as ProposalActionCreators from "../../../actions/ProposalActionCreators"; import AvailabilityEdit from "../../../components/Availability/AvailabilityEdit/AvailabilityEdit"; import LocaleStore from "../../../stores/LocaleStore"; import CreatingProposalStore from "../../../stores/CreatingProposalStore"; import {INFINITE_CALENDAR_BLUE_THEME} from "../../../constants/InfiniteCalendarConstants"; function getState() { const interfaceLanguage = LocaleStore.locale; const availability = CreatingProposalStore.availability; return { interfaceLanguage, availability }; } @translate('ProposalsProjectAvailabilityDatesPage') @connectToStores([LocaleStore, CreatingProposalStore], getState) export default class AvailabilityDatesPage extends Component { static propTypes = { // Injected by @translate: strings : PropTypes.object, // Injected by @connectToStores: availability : PropTypes.object, interfaceLanguage : PropTypes.string, }; static contextTypes = { router : PropTypes.object.isRequired }; constructor(props) { super(props); this.topNavBarLeftLinkClick = this.topNavBarLeftLinkClick.bind(this); this.topNavBarRightLinkClick = this.topNavBarRightLinkClick.bind(this); this.onSave = this.onSave.bind(this); this.onClick = this.onClick.bind(this); this.state = { showUI: true, }; } topNavBarLeftLinkClick() { this.context.router.push('/proposals-project-availability'); } topNavBarRightLinkClick() { this.context.router.push('/proposals-project-availability'); } onSave(availability) { const proposal = { availability : availability, }; ProposalActionCreators.mergeCreatingProposal(proposal); } onClick(showUI) { this.setState({showUI: showUI}); } render() { const {availability, interfaceLanguage, strings} = this.props; const canContinue = (!(availability.dynamic.length === 0 && availability.static.length === 0)); return ( <div className="views"> <div className="view view-main proposals-project-availability-dates-view"> {this.state.showUI && <TopNavBar background={canContinue ? '#63caff' : 'transparent'} color={canContinue ? '#FFFFFF' : '#000'} iconLeft={canContinue ? 'check' : ''} firstIconRight={'x'} textCenter={strings.publishProposal} textSize={'small'} onLeftLinkClickHandler={this.topNavBarLeftLinkClick} onRightLinkClickHandler={this.topNavBarRightLinkClick}/> } <div className="proposals-project-availability-dates-wrapper"> <AvailabilityEdit theme={INFINITE_CALENDAR_BLUE_THEME} color={'blue'} title={strings.title} availability={availability} interfaceLanguage={interfaceLanguage} onSave={this.onSave} onClick={this.onClick}/> </div> </div> </div> ); } } AvailabilityDatesPage.defaultProps = { strings: { publishProposal : 'Publish proposal', title : 'What availability do you need for the project?' } };
src/icons/IosFootballOutline.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosFootballOutline extends React.Component { render() { if(this.props.bare) { return <g> <path d="M256,48C141.137,48,48,141.136,48,256c0,114.864,93.137,208,208,208c114.872,0,208-93.138,208-208 C464,141.138,370.87,48,256,48z M297.151,442.179c-13.514,2.657-30.327,4.187-44,4.45c-13.198-0.195-26.074-1.735-38.5-4.493 c-2.144-0.549-4.383-1.138-6.805-1.777l-24.417-65.435L203.074,336h105.854l0.57,1.076l19.34,38.852L305.22,440.21 C302.553,440.924,299.862,441.579,297.151,442.179z M89.317,163.522l18.188,52.284l0.175,0.504L65.376,252.92 C65.892,220.535,74.52,190.088,89.317,163.522z M189.578,77.28L247,116.576v58.147l-70.997,60.067L126.6,212.28l-4.167-1.899 l-22.332-64.019C122.11,115.158,153.239,90.83,189.578,77.28z M325.025,247.206l0.921,0.765L307.569,320H204.431l-18.485-72.453 l0.445-0.376l68.873-58.27L325.025,247.206z M446.626,252.921l-42.454-36.738l0.127-0.364l18.298-52.451 C437.447,189.972,446.109,220.473,446.626,252.921z M411.564,146.067l-22.432,64.483l-53.992,24.388L264,174.723v-58.147 l57.596-39.415C357.958,90.644,389.501,114.913,411.564,146.067z M66.144,273.414l53.756-46.518l49.539,22.599l0.559,0.255 l19.718,77.287l-20.433,38.529l-69.86-0.915C81.075,338.291,69.209,307.105,66.144,273.414z M342.719,365.565l-20.434-38.529 l19.752-77.416l49.997-22.781l53.822,46.575c-3.065,33.691-14.932,64.877-33.277,91.236L342.719,365.565z M255.257,102.67 l-46.126-31.498c15-3.806,30.701-5.836,46.869-5.835c15.961,0,31.466,1.982,46.293,5.694L255.257,102.67z M166.423,381.529 l0.848,2.511l19.946,49.781c-29.239-11.351-55.011-29.704-75.232-53.006L166.423,381.529z M324.563,433.904l17.934-48.608 l1.627-3.748l55.892-0.732C379.744,404.175,353.893,422.562,324.563,433.904z"></path> </g>; } return <IconBase> <path d="M256,48C141.137,48,48,141.136,48,256c0,114.864,93.137,208,208,208c114.872,0,208-93.138,208-208 C464,141.138,370.87,48,256,48z M297.151,442.179c-13.514,2.657-30.327,4.187-44,4.45c-13.198-0.195-26.074-1.735-38.5-4.493 c-2.144-0.549-4.383-1.138-6.805-1.777l-24.417-65.435L203.074,336h105.854l0.57,1.076l19.34,38.852L305.22,440.21 C302.553,440.924,299.862,441.579,297.151,442.179z M89.317,163.522l18.188,52.284l0.175,0.504L65.376,252.92 C65.892,220.535,74.52,190.088,89.317,163.522z M189.578,77.28L247,116.576v58.147l-70.997,60.067L126.6,212.28l-4.167-1.899 l-22.332-64.019C122.11,115.158,153.239,90.83,189.578,77.28z M325.025,247.206l0.921,0.765L307.569,320H204.431l-18.485-72.453 l0.445-0.376l68.873-58.27L325.025,247.206z M446.626,252.921l-42.454-36.738l0.127-0.364l18.298-52.451 C437.447,189.972,446.109,220.473,446.626,252.921z M411.564,146.067l-22.432,64.483l-53.992,24.388L264,174.723v-58.147 l57.596-39.415C357.958,90.644,389.501,114.913,411.564,146.067z M66.144,273.414l53.756-46.518l49.539,22.599l0.559,0.255 l19.718,77.287l-20.433,38.529l-69.86-0.915C81.075,338.291,69.209,307.105,66.144,273.414z M342.719,365.565l-20.434-38.529 l19.752-77.416l49.997-22.781l53.822,46.575c-3.065,33.691-14.932,64.877-33.277,91.236L342.719,365.565z M255.257,102.67 l-46.126-31.498c15-3.806,30.701-5.836,46.869-5.835c15.961,0,31.466,1.982,46.293,5.694L255.257,102.67z M166.423,381.529 l0.848,2.511l19.946,49.781c-29.239-11.351-55.011-29.704-75.232-53.006L166.423,381.529z M324.563,433.904l17.934-48.608 l1.627-3.748l55.892-0.732C379.744,404.175,353.893,422.562,324.563,433.904z"></path> </IconBase>; } };IosFootballOutline.defaultProps = {bare: false}
src/pages/dynamic/Catalan/Catalan.js
hyy1115/react-redux-webpack2
import React from 'react' class Catalan extends React.Component { render() { return ( <div>Catalan</div> ) } } export default Catalan
src/routes.js
clothiersphere/kioskPocalypse
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './app'; // import Main from './components/main.js'; import Admin from './components/admin.js'; export default ( <Route path="/" component={App}> <IndexRoute component={Admin} /> <Route path="/admin" component={Admin} /> </Route> );
src/app/components/Footer.js
preeminence/react-redux-skeleton
import React from 'react'; class Footer extends React.Component { render() { return null; } } export default Footer;
src/index.js
hotbeatles/time-range-picker-react
import ReactDOM from 'react-dom'; import React from 'react'; import App from './App'; const rootElement = document.getElementById('root'); ReactDOM.render(<App/>, rootElement);
app/components/TodoApp/TodoApp.js
ninetails/feijoada-um
import React from 'react'; import TodoList from 'components/TodoList/TodoList'; const TodoApp = ({TodoStore, dispatch}) => ( <section className='todoapp'> <TodoList dispatch={dispatch} todos={TodoStore.get('todos')}/> </section> ); export default TodoApp;
admin/client/App/shared/AlertMessages.js
matthewstyers/keystone
import React from 'react'; import { Alert } from '../elemental'; import { upcase } from '../../utils/string'; /** * This renders alerts for API success and error responses. * Error format: { * error: 'validation errors' // The unique error type identifier * detail: { ... } // Optional details specific to that error type * } * Success format: { * success: 'item updated', // The unique success type identifier * details: { ... } // Optional details specific to that success type * } * Eventually success and error responses should be handled individually * based on their type. For example: validation errors should be displayed next * to each invalid field and signin errors should promt the user to sign in. */ var AlertMessages = React.createClass({ displayName: 'AlertMessages', propTypes: { alerts: React.PropTypes.shape({ error: React.PropTypes.Object, success: React.PropTypes.Object, }), }, getDefaultProps () { return { alerts: {}, }; }, renderValidationErrors () { let errors = this.props.alerts.error.detail; if (errors.name === 'ValidationError') { errors = errors.errors; } let errorCount = Object.keys(errors).length; let alertContent; let messages = Object.keys(errors).map((path) => { if (errorCount > 1) { return ( <li key={path}> {upcase(errors[path].error || errors[path].message)} </li> ); } else { return ( <div key={path}> {upcase(errors[path].error || errors[path].message)} </div> ); } }); if (errorCount > 1) { alertContent = ( <div> <h4>There were {errorCount} errors creating the new item:</h4> <ul>{messages}</ul> </div> ); } else { alertContent = messages; } return <Alert color="danger">{alertContent}</Alert>; }, render () { let { error, success } = this.props.alerts; if (error) { // Render error alerts switch (error.error) { case 'validation errors': return this.renderValidationErrors(); case 'error': if (error.detail.name === 'ValidationError') { return this.renderValidationErrors(); } else { return <Alert color="danger">{upcase(error.error)}</Alert>; } default: return <Alert color="danger">{upcase(error.error)}</Alert>; } } if (success) { // Render success alerts return <Alert color="success">{upcase(success.success)}</Alert>; } return null; // No alerts, render nothing }, }); module.exports = AlertMessages;
src/svg-icons/action/group-work.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGroupWork = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM8 17.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5zM9.5 8c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5S9.5 9.38 9.5 8zm6.5 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/> </SvgIcon> ); ActionGroupWork = pure(ActionGroupWork); ActionGroupWork.displayName = 'ActionGroupWork'; ActionGroupWork.muiName = 'SvgIcon'; export default ActionGroupWork;
blueocean-material-icons/src/js/components/svg-icons/image/assistant.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageAssistant = (props) => ( <SvgIcon {...props}> <path d="M19 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5.12 10.88L12 17l-1.88-4.12L6 11l4.12-1.88L12 5l1.88 4.12L18 11l-4.12 1.88z"/> </SvgIcon> ); ImageAssistant.displayName = 'ImageAssistant'; ImageAssistant.muiName = 'SvgIcon'; export default ImageAssistant;
app/components/EmailVerificationSuccess/index.js
vvnsze/Nexcast
/** * * EmailVerificationSuccess * */ import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import Paper from 'material-ui/Paper'; import { browserHistory } from 'react-router'; import EmailVerificationPodcastItem from '../../containers/EmailVerificationPodcastItem'; // import styled from 'styled-components'; const styles = { heading: { fontSize: '15px', fontFamily: 'Lato, sans-serif', textAlign: 'center', paddingBottom: '10px', paddingTop: '5px', fontWeight: 'bold', }, message: { fontSize: '15px', fontFamily: 'Lato, sans-serif', textAlign: 'center', paddingBottom: '10px', paddingTop: '5px', }, }; class EmailVerificationSuccess extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <div style={styles.heading}>SUCCESS!</div> <div style={styles.message}>Your email matches our records for the podcast you have chosen</div> <EmailVerificationPodcastItem /> <RaisedButton backgroundColor="#02dd78" onTouchTap={() => { browserHistory.push('/main'); }} label="START TAGGING" /> </div> ); } } EmailVerificationSuccess.propTypes = { }; export default EmailVerificationSuccess;
src/svg-icons/editor/format-line-spacing.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatLineSpacing = (props) => ( <SvgIcon {...props}> <path d="M6 7h2.5L5 3.5 1.5 7H4v10H1.5L5 20.5 8.5 17H6V7zm4-2v2h12V5H10zm0 14h12v-2H10v2zm0-6h12v-2H10v2z"/> </SvgIcon> ); EditorFormatLineSpacing = pure(EditorFormatLineSpacing); EditorFormatLineSpacing.displayName = 'EditorFormatLineSpacing'; EditorFormatLineSpacing.muiName = 'SvgIcon'; export default EditorFormatLineSpacing;
src/routes/dashboard/components/comments.js
hhj679/mybition-web
import React from 'react' import PropTypes from 'prop-types' import { Table, Tag } from 'antd' import styles from './comments.less' import { color } from '../../../utils' const status = { 1: { color: color.green, text: 'APPROVED', }, 2: { color: color.yellow, text: 'PENDING', }, 3: { color: color.red, text: 'REJECTED', }, } function Comments ({ data }) { const columns = [ { title: 'avatar', dataIndex: 'avatar', width: 48, className: styles.avatarcolumn, render: text => <span style={{ backgroundImage: `url(${text})` }} className={styles.avatar} />, }, { title: 'content', dataIndex: 'content', render: (text, it) => <div> <h5 className={styles.name}>{it.name}</h5> <p className={styles.content}>{it.content}</p> <div className={styles.daterow}> <Tag color={status[it.status].color}>{status[it.status].text}</Tag> <span className={styles.date}>{it.date}</span> </div> </div>, }, ] return ( <div className={styles.comments}> <Table pagination={false} showHeader={false} columns={columns} rowKey={(record, key) => key} dataSource={data.filter((item, key) => key < 3)} /> </div> ) } Comments.propTypes = { data: PropTypes.array, } export default Comments
src/pages/Uses.js
thibmaek/thibmaek.github.io
import React from 'react'; import { object } from 'prop-types'; import { PageHelmet } from '../components/helmet/'; const Publications = ({ data }) => { const { title, body } = data.contentfulPage; return ( <section> <PageHelmet title={title} /> <header> <h1>{title}</h1> </header> <article dangerouslySetInnerHTML={{ __html: body.childMarkdownRemark.html }} /> </section> ); }; Publications.propTypes = { data: object.isRequired, }; export const query = graphql` query UsesPageQuery { contentfulPage(slug: { eq: "uses" }) { title body { childMarkdownRemark { html } } } } `; export default Publications;
components/Layout/Header.js
rauchs-jewelry/rauchs-jewelry-website
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-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 Navigation from './Navigation'; import Link from '../Link'; import s from './Header.css'; class Header extends React.Component { componentDidMount() { window.componentHandler.upgradeElement(this.root); } componentWillUnmount() { window.componentHandler.downgradeElements(this.root); } render() { return ( <header className={`mdl-layout__header ${s.header}`} ref={node => (this.root = node)}> <div className={`mdl-layout__header-row ${s.row}`}> <Link className={`mdl-layout-title ${s.title}`} to="/"> React Static Boilerplate </Link> <div className="mdl-layout-spacer"></div> <Navigation /> </div> </header> ); } } export default Header;
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js
ksivam/react-router
/*globals COURSES:true */ import React from 'react' import { Link } from 'react-router' class AnnouncementsSidebar extends React.Component { render() { let { announcements } = COURSES[this.props.params.courseId] return ( <div> <h3>Sidebar Assignments</h3> <ul> {announcements.map(announcement => ( <li key={announcement.id}> <Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}> {announcement.title} </Link> </li> ))} </ul> </div> ) } } export default AnnouncementsSidebar
src/icons/CachedIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class CachedIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M38 16l-8 8h6c0 6.63-5.37 12-12 12-2.03 0-3.93-.51-5.61-1.39l-2.92 2.92C17.95 39.08 20.86 40 24 40c8.84 0 16-7.16 16-16h6l-8-8zm-26 8c0-6.63 5.37-12 12-12 2.03 0 3.93.51 5.61 1.39l2.92-2.92C30.05 8.92 27.14 8 24 8 15.16 8 8 15.16 8 24H2l8 8 8-8h-6z"/></svg>;} };
packages/bonde-admin/src/mobilizations/widgets/__plugins__/pressure/components/pressure-tell-a-friend.js
ourcities/rebu-client
import PropTypes from 'prop-types' import React from 'react' import { FormattedMessage } from 'react-intl' import { TellAFriend } from '@/components/share' const PressureTellAFriend = ({ preview, mobilization, widget }) => ( <TellAFriend preview={preview} mobilization={mobilization} widget={widget} message={ <FormattedMessage id='pressure-widget--tell-a-friend.message' defaultMessage='Pressão enviada' /> } /> ) PressureTellAFriend.propTypes = { preview: PropTypes.bool, mobilization: PropTypes.object.isRequired, widget: PropTypes.object.isRequired } export default PressureTellAFriend
src/Input/index.js
DuckyTeam/ducky-components
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import styles from './styles.css'; import WrapperStyles from '../Wrapper/styles.css'; import TypographyStyles from '../Typography/styles.css'; import Typography from '../Typography'; function Input(props) { const capitalizeFirstLetter = (string) => { return string.charAt(0).toUpperCase() + string.slice(1); }; return ( <div className={classNames(styles.wrapper, {[props.className]: props.className})}> <input autoFocus={props.autoFocus} className={classNames(styles.input, TypographyStyles.bodyTextNormal, WrapperStyles.short, { [styles.error]: props.errorMessage || props.error })} name={props.name} onBlur={props.onBlur} onChange={props.onChange} pattern={props.inputType === 'number' ? '\\d*' : null} placeholder={capitalizeFirstLetter(props.placeholder)} type={props.inputType} value={props.value} /> <Typography className={classNames(styles.errorMessage, { [styles.errorMessageActive]: props.errorMessage })} type="bodyTextNormal" > {props.errorMessage} </Typography> </div> ); } Input.propTypes = { autoFocus: PropTypes.bool, className: PropTypes.string, error: PropTypes.bool, errorMessage: PropTypes.node, inputType: PropTypes.string, name: PropTypes.string, onBlur: PropTypes.func, onChange: PropTypes.func, placeholder: PropTypes.string, value: PropTypes.string }; export default Input;
examples/huge-apps/app.js
KamilSzot/react-router
import React from 'react'; import createHistory from 'history/lib/createHashHistory'; import { Router } from 'react-router'; import AsyncProps from 'react-router/lib/experimental/AsyncProps'; import stubbedCourses from './stubs/COURSES'; var rootRoute = { component: AsyncProps, // iunno? renderInitialLoad() { return <div>loading...</div> }, childRoutes: [{ path: '/', component: require('./components/App'), childRoutes: [ require('./routes/Calendar'), require('./routes/Course'), require('./routes/Grades'), require('./routes/Messages'), require('./routes/Profile'), ]} ] }; var history = createHistory(); React.render(( <Router history={history} routes={rootRoute} createElement={AsyncProps.createElement} /> ), document.getElementById('example'));
src/Menus/PitcherSelection.js
kevinleclair1/pitch_fx_visualizer
import React from 'react'; import { createSelector } from 'reselect'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import DatePicker from 'material-ui/DatePicker'; import CircularProgress from 'material-ui/CircularProgress'; import moment from 'moment'; import createContainer from '../containers/GenericContainer.js'; import { actions, selectors as gameDataSelectors } from '../redux/gameData.js'; import { selectFieldCb } from './helpers.js'; const center = { padding: '0 16px' } const GameDatePicker = createContainer({ actions: { onChange: actions.setDate }, mapStateToProps: (state) => { return { hintText: "Choose a Game Date", style: center, value: gameDataSelectors.getGameDate(state), maxDate: moment().subtract(1, 'days').toDate() } }, Component: (props) => ( <DatePicker {...props} onChange={(ev, date) => props.onChange({ date })} /> ) }) const GameSelectionFieldComponent = (props) => ( <div style={center} > <SelectField value={props.value} disabled={props.disabled} floatingLabelText={props.floatingLabelText} onChange={selectFieldCb(props.onChange)} fullWidth={true} > {props.games.map((game) => ( <MenuItem key={game.gameday_link} value={game.gameday_link} primaryText={`${game.home_team_name} vs. ${game.away_team_name}`} /> ))} </SelectField> </div> ); const GameSelectionField = createContainer({ actions: { onChange: actions.setGame }, mapStateToProps: createSelector( gameDataSelectors.getSelectedGameId, gameDataSelectors.getGames, (gameId, games) => ({ value: gameId, floatingLabelText: 'Select a Game', disabled: !games.length, games: games }) ), Component: GameSelectionFieldComponent }); const PitcherSelectionFieldComponent = (props) => ( <div style={center} > <SelectField value={props.value} disabled={props.disabled} floatingLabelText={props.floatingLabelText} onChange={selectFieldCb(props.onChange)} fullWidth={true} > {props.pitchers.map((pitcher) => ( <MenuItem key={pitcher.id} value={pitcher.id} primaryText={`${pitcher.name_display_first_last} (${pitcher.teamName})`} /> ))} </SelectField> </div> ) const PitcherSelectionField = createContainer({ actions: { onChange: actions.setPitcher }, mapStateToProps: createSelector( gameDataSelectors.getSelectedPitcher, gameDataSelectors.getPitchers, (selectedPitcher, pitchers) => ({ value: selectedPitcher, floatingLabelText: 'Select a Pitcher', disabled: !pitchers.length, pitchers: pitchers }) ), Component: PitcherSelectionFieldComponent }); const getLoader = () => ( <div style={center} > <CircularProgress /> </div> ) const PitcherSelectionComponent = (props) => { return ( <div style={{ padding: '16px 0' }}> <GameDatePicker /> <GameSelectionField /> <PitcherSelectionField /> {props.loading ? getLoader() : null} </div> ) } export default createContainer({ mapStateToProps: createSelector( gameDataSelectors.getLoadingState, (loading) => ({ loading }) ), Component: PitcherSelectionComponent })
src/svg-icons/image/wb-incandescent.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageWbIncandescent = (props) => ( <SvgIcon {...props}> <path d="M3.55 18.54l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8zM11 22.45h2V19.5h-2v2.95zM4 10.5H1v2h3v-2zm11-4.19V1.5H9v4.81C7.21 7.35 6 9.28 6 11.5c0 3.31 2.69 6 6 6s6-2.69 6-6c0-2.22-1.21-4.15-3-5.19zm5 4.19v2h3v-2h-3zm-2.76 7.66l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4z"/> </SvgIcon> ); ImageWbIncandescent = pure(ImageWbIncandescent); ImageWbIncandescent.displayName = 'ImageWbIncandescent'; ImageWbIncandescent.muiName = 'SvgIcon'; export default ImageWbIncandescent;
src/components/ProjectTile/ProjectTile.js
OR13/car2go
import React from 'react' import { PropTypes } from 'prop-types'; import Paper from 'material-ui/Paper' import { isObject } from 'lodash' import IconButton from 'material-ui/IconButton' import DeleteIcon from 'material-ui/svg-icons/action/delete' import classes from './ProjectTile.scss' export const ProjectTile = ({ project, onSelect, onDelete, showDelete }) => ( <Paper className={classes.container}> <div className={classes.top}> <span className={classes.name} onClick={() => onSelect(project)}> {project.name} </span> { showDelete && onDelete ? <IconButton tooltip='delete' onClick={onDelete} > <DeleteIcon /> </IconButton> : null } </div> <span className={classes.owner}> { isObject(project.owner) ? project.owner.displayName : project.owner || 'No Owner' } </span> </Paper> ) ProjectTile.propTypes = { project: PropTypes.object.isRequired, onSelect: PropTypes.func.isRequired, onDelete: PropTypes.func.isRequired, showDelete: PropTypes.bool } export default ProjectTile
src/core/display/App/Navigation/Vertical/Search.js
JulienPradet/pigment-store
import React from 'react' const Search = ({search, onChange}) => { return <div> <input type='text' value={search} onChange={(e) => onChange(e.target.value)} placeholder='Search...' /> <button onClick={() => onChange('')}>reset</button> </div> } export default Search
src/javascript/shared/components/header/index.js
rahulharinkhede2013/xigro-dashboard
import React from 'react'; import { Button } from 'att-iot-ui/lib/button'; import { ListDivider } from 'att-iot-ui/lib/list'; import Icon from 'att-iot-ui/lib/icon'; import ProfileMenu from './profileMenu'; import classnames from 'classnames'; // style import styles from './style.scss'; import index from '../../../index.scss'; import app from '../../../app.scss'; export default (props) => ( <header className={classnames(styles.siteHead,app.siteHead)}> <div className={classnames(app.appWrapperContainer)}> <div className={classnames(index.dFlex, index.justifyContentStart)}> <div className={classnames(index.p2, index.mrAuto)}> <a href="/"><Icon name='att-logo' att width={36} height={36} /> </a> <i className={classnames(index.fa, index.faBars)} aria-hidden="true"></i> | IoT Marketplace </div> <div className={classnames(index.p2)}> <ProfileMenu /> </div> </div> </div> </header> );
examples/todomvc/index.js
ptkach/redux
import 'babel-polyfill' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import App from './containers/App' import configureStore from './store/configureStore' import 'todomvc-app-css/index.css' const store = configureStore() render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
src/parser/rogue/outlaw/CONFIG.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import { tsabo, Coywolf } from 'CONTRIBUTORS'; import SPECS from 'game/SPECS'; import Warning from 'interface/Alert/Warning'; import CHANGELOG from './CHANGELOG'; export default { // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion. contributors: [tsabo, Coywolf], // The WoW client patch this spec was last updated to be fully compatible with. patchCompatibility: '7.3', // If set to false`, the spec will show up as unsupported. isSupported: false, // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more. // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component. description: ( <> <Warning> Hey there! A good basis has been implemented for this spec, but it needs to be fleshed out more to provide all the feedback possible.<br /><br /> This spec needs a focused maintainer. If you want to give it a try, check <a href="https://github.com/WoWAnalyzer/WoWAnalyzer">GitHub</a> for more information. </Warning> <Warning> Hi <kbd>@Tsabo</kbd> here. Due to some incorrect data coming out of WarcraftLogs for Outlaw beta logs, combo points generated by Sinister Strike and Pistol Shot may be incorrect. I will verify this once PrePatch is live. </Warning> </> ), // A recent example report to see interesting parts of the spec. Will be shown on the homepage. exampleReport: '/report/wptPT3mfWavbj9KY/33-Heroic+Conclave+of+the+Chosen+-+Kill+(6:22)/13-Kuracz', // Don't change anything below this line; // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about. spec: SPECS.OUTLAW_ROGUE, // The contents of your changelog. changelog: CHANGELOG, // The CombatLogParser class for your spec. parser: () => import('./CombatLogParser' /* webpackChunkName: "OutlawRogue" */).then(exports => exports.default), // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code. path: __dirname, };
docusaurus/website/pages/en/index.js
hirviid/react-redux-fetch
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); const CompLibrary = require('../../core/CompLibrary.js'); // // const MarkdownBlock = CompLibrary.MarkdownBlock; /* Used to read markdown */ const Container = CompLibrary.Container; const GridBlock = CompLibrary.GridBlock; const siteConfig = require(`${process.cwd()}/siteConfig.js`); function imgUrl(img) { return `${siteConfig.baseUrl}img/${img}`; } function docUrl(doc, language) { return `${siteConfig.baseUrl}docs/${language ? `${language}/` : ''}${doc}`; } function pageUrl(page, language) { return siteConfig.baseUrl + (language ? `${language}/` : '') + page; } class Button extends React.Component { render() { return ( <div className="pluginWrapper buttonWrapper"> <a className="button" href={this.props.href} target={this.props.target}> {this.props.children} </a> </div> ); } } Button.defaultProps = { target: '_self', }; const SplashContainer = props => ( <div className="homeContainer"> <div className="homeSplashFade"> <div className="wrapper homeWrapper">{props.children}</div> </div> </div> ); const Logo = props => ( <div className="projectLogo"> <img src={props.img_src} alt="Project Logo" /> </div> ); const ProjectTitle = () => ( <h2 className="projectTitle"> {siteConfig.title} <small>{siteConfig.tagline}</small> </h2> ); const PromoSection = props => ( <div className="section promoSection"> <div className="promoRow"> <div className="pluginRowBlock">{props.children}</div> </div> </div> ); class HomeSplash extends React.Component { render() { const language = this.props.language || ''; return ( <SplashContainer> <Logo img_src={imgUrl('react-redux-fetch.svg')} /> <div className="inner"> <ProjectTitle /> <PromoSection> <Button href={docUrl('getting-started', language)}>Get started</Button> </PromoSection> </div> </SplashContainer> ); } } const Block = props => ( <Container padding={['bottom', 'top']} id={props.id} background={props.background}> <GridBlock align={props.align} contents={props.children} layout={props.layout} /> </Container> ); Block.defaultProps = { align: 'center', }; const Features = () => ( <Block layout="fourColumn"> {[ { content: 'No more creating actions, action types, reducers, middleware and selectors for every API call. React-redux-fetch removes this boilerplate without losing flexibility.', image: imgUrl('react-redux-fetch-blue.svg'), imageAlign: 'top', title: 'Remove boilerplate', }, { content: 'Almost every part of react-redux-fetch can be replaced with a custom implementation. Use the sensible defaults, or customize where needed.', image: imgUrl('feature-customize.svg'), imageAlign: 'top', title: 'Highly customizable', }, ]} </Block> ); const GetStarted = props => ( <Block layout="twoColumn" background="light" {...props}> {[ { content: `To download react-redux-fetch, run: \`\`\`sh npm install --save react-redux-fetch \`\`\` or \`\`\`sh yarn add react-redux-fetch \`\`\` `, title: 'Installation', }, { content: ` 1. Connect the react-redux-fetch middleware to the Store using applyMiddleware: \`\`\`js // configureStore.js import { middleware as fetchMiddleware } from 'react-redux-fetch'; import { applyMiddleware, createStore } from 'redux'; const configureStore = (initialState, rootReducer) => { const middleware = [fetchMiddleware, otherMiddleware]; const store = createStore( rootReducer, initialState, applyMiddleware(...middleware) ); return store; }; export default configureStore; \`\`\` 2. Mount react-redux-fetch reducer to the state at repository: \`\`\`js // rootReducer.js import { combineReducers } from 'redux'; import { reducer as fetchReducer } from 'react-redux-fetch'; const rootReducer = combineReducers({ // ... other reducers repository: fetchReducer }); export default rootReducer; \`\`\` `, title: 'Setup', }, ]} </Block> ); const Usage = props => ( <Block layout="twoColumn" {...props}> {[ { content: ` \`\`\`js import React from 'react'; import PropTypes from 'prop-types' import reduxFetch from 'react-redux-fetch'; class PokemonList extends React.Component { static propTypes = { dispatchAllPokemonGet: PropTypes.func.isRequired, allPokemonFetch: PropTypes.object }; componentDidMount() { this.props.dispatchAllPokemonGet(); } render() { const {allPokemonFetch} = this.props; if (allPokemonFetch.rejected) { return <div>Oops... Could not fetch Pokémon!</div>; } if (allPokemonFetch.fulfilled) { return ( <ul> {allPokemonFetch.value.results.map(pokemon => ( <li key={pokemon.name}>{pokemon.name}</li> ))} </ul> ); } return <div>Loading...</div>; } } // reduxFetch(): Declarative way to define the resource needed for this component export default reduxFetch([{ resource: 'allPokemon', method: 'get', // You can omit this, this is the default request: { url: 'http://pokeapi.co/api/v2/pokemon/' } }])(PokemonList); \`\`\` `, title: 'Usage: Higher order Component', }, { content: ` \`\`\`js import React from 'react'; import { ReduxFetch } from 'react-redux-fetch'; const fetchConfig = [{ resource: 'allPokemon', method: 'get', // You can omit this, this is the default request: { url: 'http://pokeapi.co/api/v2/pokemon/' } }]; const PokemonList = () => ( <ReduxFetch config={fetchConfig} fetchOnMount> {({ allPokemonFetch }) => { if (allPokemonFetch.rejected) { return <div>Oops... Could not fetch Pokémon!</div>; } if (allPokemonFetch.fulfilled) { return ( <ul> {allPokemonFetch.value.results.map(pokemon => ( <li key={pokemon.name}>{pokemon.name}</li> ))} </ul> ); } return <div>Loading...</div>; }} </ReduxFetch> ); export default PokemonList; \`\`\` `, title: 'Usage: Render props', }, ]} </Block> ); class Index extends React.Component { render() { const language = this.props.language || ''; return ( <div> <HomeSplash language={language} /> <div className="mainContainer"> <Features /> <GetStarted align="left" /> <Usage align="left" /> </div> </div> ); } } module.exports = Index;
packages/wix-style-react/src/MessageBox/docs/AlertExamples/EmptyState.js
wix/wix-style-react
/* eslint-disable react/prop-types */ import React from 'react'; import ImagePlaceholder from '../../../../stories/utils/ImagePlaceholder'; import { MessageBoxFunctionalLayout, EmptyState } from 'wix-style-react'; export default () => ( <MessageBoxFunctionalLayout title="Choose Your Favorites" confirmText="Select" cancelText="Cancel" theme="blue" disableConfirmation withEmptyState dataHook="alert-empty-state" > <EmptyState title="You don't have any favorites yet" subtitle="Go back and add some items to your favorites' list" image={<ImagePlaceholder />} /> </MessageBoxFunctionalLayout> );
webpack/containers/Application/Routes.js
adamruzicka/katello
import React from 'react'; import { Route } from 'react-router-dom'; import { links } from './config'; export default () => ( <div> {links.map(({ path, component }) => ( <Route exact key={path} path={`/${path}`} component={component} /> ))} </div> );
static/tables/strategy-table.js
joequant/sptrader
import React from 'react'; import {AgGridReact} from 'ag-grid-react'; import {Button} from 'react-bootstrap'; import {actionBoxWidth, StrategyControl, renderLog, pad, process_headers} from '../../static/utils'; export class StrategyTable extends React.Component { constructor(props) { super(props); this.state = { columnDefs: [], rowData: [], idList: new Set(), defaultData: {} }; this.onGridReady = this.onGridReady.bind(this); this.addRow = this.addRow.bind(this); this.removeRow = this.removeRow.bind(this); } addRow() { var r = Object.assign({}, this.state.defaultData); var c = this.state.idList; var rows = this.state.rowData; var i = 0; var id = undefined; do { i += 1; id = r.strategy + "-" + pad(i, 5); } while (c.has(id)); r.id = id; this.state.rowData.push(r); this.state.idList.add(id); this.api.setRowData(rows); } removeRow(props) { props.api.removeItems([props.node]); this.state.rowData.splice(props.rowIndex, 1); this.state.idList.delete(props.data.id); $.get("/strategy/remove-row/" + props.data.id); } // in onGridReady, store the api for later use componentWillReceiveProps(newprops) { var l = this; if (newprops.info != undefined) { var r = this.state.rowData; for(var i=0; i < r.length; i++) { var newr = newprops.info[r[i].id]; if (newr != undefined) { for (var attrname in newr){ r[i][attrname] = newr[attrname]; } } } this.setState({rowData: r}); this.api.setRowData(r); } if (newprops.header != undefined) { process_headers(l, [ {headerName: "Id", field: "id"}, {headerName: "Status", volatile: true, field: "status"}, {headerName: "Comment", volatile: true, field: "comment"}, {headerName: "Instrument", field: "dataname", editable: true, defaultData: ''} ], [ {headerName: "Log", field: "log", cellRenderer: renderLog}, {headerName: "Actions", field: "start", cellRendererFramework: StrategyControl, width: actionBoxWidth, parent: l }], newprops.header, {'status': 'stopped', 'strategy': l.props.strategy} ); } if (newprops.data != undefined) { var d = newprops.data; var idList = new Set(); for(var i=0; i < d.length; i++) { idList.add(d[i].id); } l.setState({rowData: d, idList: idList}); l.api.setRowData(d); } } onGridReady(params) { this.api = params.api; this.columnApi = params.columnApi; } render() { return ( <div> <Button onClick={this.addRow}>New Strategy</Button> <AgGridReact // column definitions and row data are immutable, the grid // will update when these lists change columnDefs={this.state.columnDefs} rowData={this.state.rowData} onGridReady={this.onGridReady} /></div> ) } }
src/root/Root.js
jorilindell/postit-react
// @flow import React from 'react' import {Provider} from 'react-redux' import {Router} from 'react-router' import routes from './routes' export type RootProps = { history: any, store: any, } const Root = ({history, store}: RootProps) => <Provider store={store}> <Router history={history} routes={routes} key={Math.random()}/> </Provider> export default Root
src/svg-icons/action/rounded-corner.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionRoundedCorner = (props) => ( <SvgIcon {...props}> <path d="M19 19h2v2h-2v-2zm0-2h2v-2h-2v2zM3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm0-4h2V3H3v2zm4 0h2V3H7v2zm8 16h2v-2h-2v2zm-4 0h2v-2h-2v2zm4 0h2v-2h-2v2zm-8 0h2v-2H7v2zm-4 0h2v-2H3v2zM21 8c0-2.76-2.24-5-5-5h-5v2h5c1.65 0 3 1.35 3 3v5h2V8z"/> </SvgIcon> ); ActionRoundedCorner = pure(ActionRoundedCorner); ActionRoundedCorner.displayName = 'ActionRoundedCorner'; ActionRoundedCorner.muiName = 'SvgIcon'; export default ActionRoundedCorner;
components/HomePage.js
jordancappy/jorder
import React from 'react'; class HomePage extends React.Component { render(){ return( <div> <div className="page-header text-center"> <h1>jorder</h1> <p className="lead">create html 5 forms with so much ease</p> <h1> <a className="btn btn-lg btn-success" href="/auth/google">log in with google</a> </h1> </div> </div> ); } } export default HomePage;
.storybook/Example/Example.story.js
metasfresh/metasfresh-webui-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Example from './'; // Defaults to <name>.story.js export const name = 'Example component'; export default story => { const states = { 'Regular state': () => ( <Example /> ), 'Inverted state': () => ( <Example inverted /> ), }; for (const [state, render] of Object.entries(states)) { story.add(state, render); } };
src/js/Components/Chapel.js
RoyalSix/Eagle-Connect
import React, { Component } from 'react'; import { Text, View, ListView, Image } from 'react-native'; import style from 'css'; import * as assets from 'assets'; export default class ChapelContainer extends Component { constructor(props) { super(props); this.renderSectionHeader = this.renderSectionHeader.bind(this); this.onLayout = this.onLayout.bind(this); this.renderRow = this.renderRow.bind(this) this.state = { numberOfLines:1 } } renderRow(data) { var date; try { date = data.date.split(',')[2].trim(); } catch (e) { } return ( <View style={{ padding: 10, backgroundColor: 'white', flexDirection: 'row' }}> <Image style={{ height: 80, width: 80, borderRadius: 40 }} source={assets[data.picture]} /> <View style={{ justifyContent: 'center', marginHorizontal: 10 }}> <Text style={{ fontSize: 20, color: 'black', width:250, fontFamily:'Arial', fontWeight:'bold' }}>{data.location.toUpperCase()}</Text> <View style={{ flexDirection: 'column', justifyContent: 'space-between', margin: 5 }}> <Text style={{ fontSize: 15, color: 'black' }}>Time: {date}</Text> {data.speaker ? <Text numberOfLines={this.state.numberOfLines} style={{ fontSize: 15, color: 'black', width: 200 }}>Speaker: {data.speaker}</Text> : null} <Text numberOfLines={this.state.numberOfLines} style={{ width:200, fontSize: 15, color: 'black' }}>{data.title}</Text> </View> </View> </View> ) } renderHeader() { return <Text style={style.chapelHeading}>chapels</Text>; } renderSeparator(sectionId, rowId) { return (<View key={`sep:${sectionId}:${rowId}`} style={style.chapelSeparator} />) } renderSectionHeader(sectionData, sectionId) { const _this = this; if (Object.keys(sectionData).length) return ( <Text ref={(sectionHeaderComponent) => { if (_this.props.day == sectionId) { _this[sectionId] = sectionHeaderComponent; } else if (_this.props.tomorrow == sectionId) { _this[sectionId] = sectionHeaderComponent; } }} style={{ fontWeight: "700", color: 'white', fontSize: 25, padding: 5, backgroundColor: 'black', flex: 1 }}> {sectionId} </Text>) else return (<View></View>) } onLayout() { const _this = this; if (this[this.props.day]) { this[this.props.day].measure((fx, fy, width, height, px, py) => { _this.refs.listView.scrollTo({y:fy}) }) } else if (this[this.props.tomorrow]) { this[this.props.tomorrow].measure((fx, fy, width, height, px, py) => { _this.refs.listView.scrollTo({y:fy}) }) } } render() { return ( <ListView ref="listView" enableEmptySections style={style.chapelContainer} dataSource={this.props.dataSource} renderRow={this.renderRow} renderSeparator={this.renderSeparator} renderSectionHeader={this.renderSectionHeader} onLayout={this.onLayout} /> ) } }
resource/js/app.js
kyonmm/crowi
import React from 'react'; import ReactDOM from 'react-dom'; import Crowi from './util/Crowi'; import CrowiRenderer from './util/CrowiRenderer'; import HeaderSearchBox from './components/HeaderSearchBox'; import SearchPage from './components/SearchPage'; import PageListSearch from './components/PageListSearch'; //import PageComment from './components/PageComment'; if (!window) { window = {}; } // FIXME const crowi = new Crowi({me: $('#content-main').data('current-username')}, window); window.crowi = crowi; crowi.fetchUsers(); const crowiRenderer = new CrowiRenderer(); window.crowiRenderer = crowiRenderer; const componentMappings = { 'search-top': <HeaderSearchBox />, 'search-page': <SearchPage />, 'page-list-search': <PageListSearch />, //'page-comment': <PageComment />, }; Object.keys(componentMappings).forEach((key) => { const elem = document.getElementById(key); if (elem) { ReactDOM.render(componentMappings[key], elem); } });
src/containers/TrustSupport.js
iris-dni/iris-frontend
import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import { fetchPetition } from 'actions/PetitionActions'; import settings from 'settings'; import Trust from 'components/Trust'; import getPetitionForm from 'selectors/petitionForm'; const TrustSupportContainer = (props) => ( <div> <Helmet title={settings.trustPage.support.title} /> <Trust {...props} action={'support'} /> </div> ); TrustSupportContainer.fetchData = ({ store, params }) => { return store.dispatch(fetchPetition(params.id)); }; export const mapStateToProps = ({ petition, trust, me }) => ({ petition: getPetitionForm(petition), isLoggedIn: me && !!me.id }); TrustSupportContainer.propTypes = { location: React.PropTypes.object.isRequired, petition: React.PropTypes.object.isRequired, isLoggedIn: React.PropTypes.bool.isRequired }; export default connect( mapStateToProps )(TrustSupportContainer);
project/src/scenes/Admin/Media/MediaManager/components/MediaForm/MediaForm.js
boldr/boldr
/* @flow */ import React from 'react'; import styled from 'styled-components'; import { Field, reduxForm } from 'redux-form'; // internal import Button from '@boldr/ui/Button'; import { Form, TextFormField } from '@boldr/ui/Form'; type Props = { handleSubmit?: Function, reset?: Function, submitting?: boolean, pristine?: boolean, }; const FormBottom = styled.div` justify-content: center; display: flex; width: 100%; font-size: 14px; text-align: center; `; const MediaForm = (props: Props) => { const { handleSubmit, reset, submitting, pristine } = props; return ( <Form onSubmit={handleSubmit} className="boldr-form__fileeditor"> <Field id="name" name="name" type="text" label="File name" component={TextFormField} /> <Field id="description" name="fileDescription" type="text" label="Description" component={TextFormField} /> <FormBottom> <Button htmlType="submit" kind="primary" disabled={submitting || pristine}> Save </Button> <Button onClick={reset} outline> Reset </Button> </FormBottom> </Form> ); }; export default reduxForm({ form: 'mediaForm', })(MediaForm);
src/app/core/atoms/icon/icons/calendar.js
blowsys/reservo
import React from 'react'; const Calendar = (props) => <svg {...props} x="0px" y="0px" viewBox="0 0 14.173 14.173"><g><path d="M12.253,2.593l-1.949,0l-0.001-1.194L8.822,1.399l0.001,1.194l-3.474,0L5.349,1.398L3.867,1.399 l0.001,1.194l-1.948,0c-0.398,0-0.721,0.323-0.721,0.721l0,1.94l11.776,0l0-1.94C12.974,2.915,12.652,2.593,12.253,2.593z"/><path d="M1.199,11.804c0,0.398,0.323,0.721,0.721,0.721l10.334,0c0.398,0,0.721-0.323,0.721-0.721l0-5.069 l-11.776,0L1.199,11.804z M7.192,7.968C7.41,7.986,7.627,8.054,7.787,8.213c0.16,0.159,0.248,0.371,0.248,0.597l0,2.114H6.554 l0-1.473L6.112,9.452L6.109,7.971L7.192,7.968z"/></g></svg>; export default Calendar;
example/pages/footer/index.js
n7best/react-weui
import React from 'react'; import { Footer, FooterText, FooterLinks, FooterLink } from '../../../build/packages'; import Page from '../../component/page'; const FooterDemo = (props) => ( <Page className="footer" title="Footer" subTitle="页脚" spacing> <Footer> <FooterText>Copyright &copy; 2008-2016 weui.io</FooterText> </Footer> <br/><br/> <Footer> <FooterLinks> <FooterLink href="javascript:void(0);">Link</FooterLink> </FooterLinks> <FooterText>Copyright &copy; 2008-2016 weui.io</FooterText> </Footer> <br/><br/> <Footer> <FooterLinks> <FooterLink href="javascript:void(0);">Link</FooterLink> <FooterLink href="javascript:void(0);">Link</FooterLink> </FooterLinks> <FooterText>Copyright &copy; 2008-2016 weui.io</FooterText> </Footer> </Page> ); export default FooterDemo;
packages/wix-style-react/src/Stepper/docs/index.story.js
wix/wix-style-react
import React from 'react'; import { header, tabs, tab, description, importExample, title, columns, divider, code, api, testkit, playground, } from 'wix-storybook-utils/Sections'; import { storySettings } from '../test/storySettings'; import Stepper from '..'; import { Type, StepType, FitMode } from '../constants'; import responsiveExample from '!raw-loader!./examples/responsive'; import stepTypesExample from '!raw-loader!./examples/stepTypes'; import fitModesExample from '!raw-loader!./examples/fitModes'; import stepperTypeExample from '!raw-loader!./examples/stepperTypes'; import cardExample from '!raw-loader!./examples/card'; import composerHeaderExample from '!raw-loader!./examples/composerHeader'; const steps = [ { text: 'First step', type: StepType.Completed }, { text: 'Second step' }, { text: 'Third step', type: StepType.Disabled }, ]; export default { category: storySettings.category, storyName: 'Stepper', component: Stepper, componentPath: '..', componentProps: setState => ({ steps, type: Type.Circle, fit: FitMode.Compact, activeStep: 1, onClick: activeStep => setState({ activeStep }), }), exampleProps: { steps: [{ label: '3 steps', value: steps }], onClick: stepIndex => `I was called with ${stepIndex}`, }, sections: [ header({ sourceUrl: 'https://github.com/wix/wix-style-react/tree/master/src/Stepper/', component: <Stepper steps={steps} activeStep={1} />, }), tabs([ tab({ title: 'Description', sections: [ columns([ description({ title: 'Description', text: 'Stepper displays the path a user needs to follow to complete the process. It breaks a large number of information into steps and indicates which step is active. It works best when split up to 7 steps.', }), ]), importExample("import { Stepper } from 'wix-style-react';"), divider(), title('Examples'), code({ title: 'Step types', description: 'Steps can have different types: completed, normal, error and disabled.', compact: true, source: stepTypesExample, }), code({ title: 'Stepper types', description: 'Using `type` prop stepper can appear in `circle` style or plain `text`. Text type is good for neutral and compact layouts.', compact: true, source: stepperTypeExample, }), code({ title: 'Fit modes', description: 'Using `fit` prop stepper can appear in `normal` or `stretched` fit mode. With `stretched` fit the component will grow and fill parent container width.', compact: true, source: fitModesExample, }), code({ title: 'Responsive', description: "When there is not enough space the active step's text is fully displayed and the rest of the steps are equally shortened.", compact: true, source: responsiveExample, }), divider(), title('Use Cases'), code({ title: 'Inside a Card', description: 'Stepper is used in a Card header to indicate the path a user needs to follow to complete the process.', compact: true, source: cardExample, }), code({ title: 'Inside a ComposerHeader', description: 'Stepper inside a ComposerHeader can appear in start or center positions and must use type `text`.', compact: true, source: composerHeaderExample, }), ], }), ...[ { title: 'API', sections: [api()] }, { title: 'Testkit', sections: [testkit()] }, { title: 'Playground', sections: [playground()] }, ].map(tab), ]), ], };
app/scripts/Account/createRoutes.js
igr-santos/bonde-client
import React from 'react' import { Route } from 'react-router' import { BackgroundContainer } from '../Dashboard/containers' import { EditUserPage, LoginPageWrapper, LogoutPage, RegisterPage } from './pages' import { AccountContainer } from './containers' export default (requiredLogin, redirectUrl) => [ <Route key="account" component={BackgroundContainer}> <Route path="/login" component={LoginPageWrapper(redirectUrl)} /> <Route path="/logout" component={LogoutPage} /> <Route path="/register" component={RegisterPage} /> </Route>, <Route key="account-logged" path="/account" component={AccountContainer} onEnter={requiredLogin}> <Route path="/edit" component={EditUserPage} /> </Route> ]
antd-dva/ant-design-pro-demo/test/src/components/Ellipsis/index.js
JianmingXia/StudyTest
import React, { Component } from 'react'; import { Tooltip } from 'antd'; import classNames from 'classnames'; import styles from './index.less'; /* eslint react/no-did-mount-set-state: 0 */ /* eslint no-param-reassign: 0 */ const isSupportLineClamp = document.body.style.webkitLineClamp !== undefined; const EllipsisText = ({ text, length, tooltip, ...other }) => { if (typeof text !== 'string') { throw new Error('Ellipsis children must be string.'); } if (text.length <= length || length < 0) { return <span {...other}>{text}</span>; } const tail = '...'; let displayText; if (length - tail.length <= 0) { displayText = ''; } else { displayText = text.slice(0, length - tail.length); } if (tooltip) { return ( <Tooltip overlayStyle={{ wordBreak: 'break-all' }} title={text}> <span> {displayText} {tail} </span> </Tooltip> ); } return ( <span {...other}> {displayText} {tail} </span> ); }; export default class Ellipsis extends Component { state = { text: '', targetCount: 0, }; componentDidMount() { if (this.node) { this.computeLine(); } } componentWillReceiveProps(nextProps) { if (this.props.lines !== nextProps.lines) { this.computeLine(); } } computeLine = () => { const { lines } = this.props; if (lines && !isSupportLineClamp) { const text = this.shadowChildren.innerText; const lineHeight = parseInt(getComputedStyle(this.root).lineHeight, 10); const targetHeight = lines * lineHeight; this.content.style.height = `${targetHeight}px`; const totalHeight = this.shadowChildren.offsetHeight; const shadowNode = this.shadow.firstChild; if (totalHeight <= targetHeight) { this.setState({ text, targetCount: text.length, }); return; } // bisection const len = text.length; const mid = Math.floor(len / 2); const count = this.bisection(targetHeight, mid, 0, len, text, shadowNode); this.setState({ text, targetCount: count, }); } }; bisection = (th, m, b, e, text, shadowNode) => { const suffix = '...'; let mid = m; let end = e; let begin = b; shadowNode.innerHTML = text.substring(0, mid) + suffix; let sh = shadowNode.offsetHeight; if (sh <= th) { shadowNode.innerHTML = text.substring(0, mid + 1) + suffix; sh = shadowNode.offsetHeight; if (sh > th) { return mid; } else { begin = mid; mid = Math.floor((end - begin) / 2) + begin; return this.bisection(th, mid, begin, end, text, shadowNode); } } else { if (mid - 1 < 0) { return mid; } shadowNode.innerHTML = text.substring(0, mid - 1) + suffix; sh = shadowNode.offsetHeight; if (sh <= th) { return mid - 1; } else { end = mid; mid = Math.floor((end - begin) / 2) + begin; return this.bisection(th, mid, begin, end, text, shadowNode); } } }; handleRoot = (n) => { this.root = n; }; handleContent = (n) => { this.content = n; }; handleNode = (n) => { this.node = n; }; handleShadow = (n) => { this.shadow = n; }; handleShadowChildren = (n) => { this.shadowChildren = n; }; render() { const { text, targetCount } = this.state; const { children, lines, length, className, tooltip, ...restProps } = this.props; const cls = classNames(styles.ellipsis, className, { [styles.lines]: lines && !isSupportLineClamp, [styles.lineClamp]: lines && isSupportLineClamp, }); if (!lines && !length) { return ( <span className={cls} {...restProps}> {children} </span> ); } // length if (!lines) { return ( <EllipsisText className={cls} length={length} text={children || ''} tooltip={tooltip} {...restProps} /> ); } const id = `antd-pro-ellipsis-${`${new Date().getTime()}${Math.floor(Math.random() * 100)}`}`; // support document.body.style.webkitLineClamp if (isSupportLineClamp) { const style = `#${id}{-webkit-line-clamp:${lines};-webkit-box-orient: vertical;}`; return ( <div id={id} className={cls} {...restProps}> <style>{style}</style> {tooltip ? ( <Tooltip overlayStyle={{ wordBreak: 'break-all' }} title={children}> {children} </Tooltip> ) : ( children )} </div> ); } const childNode = ( <span ref={this.handleNode}> {targetCount > 0 && text.substring(0, targetCount)} {targetCount > 0 && targetCount < text.length && '...'} </span> ); return ( <div {...restProps} ref={this.handleRoot} className={cls}> <div ref={this.handleContent}> {tooltip ? ( <Tooltip overlayStyle={{ wordBreak: 'break-all' }} title={text}> {childNode} </Tooltip> ) : ( childNode )} <div className={styles.shadow} ref={this.handleShadowChildren}> {children} </div> <div className={styles.shadow} ref={this.handleShadow}> <span>{text}</span> </div> </div> </div> ); } }
app/javascript/mastodon/features/compose/components/compose_form.js
theoria24/mastodon
import React from 'react'; import CharacterCounter from './character_counter'; import Button from '../../../components/button'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ReplyIndicatorContainer from '../containers/reply_indicator_container'; import AutosuggestTextarea from '../../../components/autosuggest_textarea'; import AutosuggestInput from '../../../components/autosuggest_input'; import PollButtonContainer from '../containers/poll_button_container'; import UploadButtonContainer from '../containers/upload_button_container'; import { defineMessages, injectIntl } from 'react-intl'; import SpoilerButtonContainer from '../containers/spoiler_button_container'; import PrivacyDropdownContainer from '../containers/privacy_dropdown_container'; import EmojiPickerDropdown from '../containers/emoji_picker_dropdown_container'; import PollFormContainer from '../containers/poll_form_container'; import UploadFormContainer from '../containers/upload_form_container'; import WarningContainer from '../containers/warning_container'; import { isMobile } from '../../../is_mobile'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { length } from 'stringz'; import { countableText } from '../util/counter'; import Icon from 'mastodon/components/icon'; const allowedAroundShortCode = '><\u0085\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\u0009\u000a\u000b\u000c\u000d'; const messages = defineMessages({ placeholder: { id: 'compose_form.placeholder', defaultMessage: 'What is on your mind?' }, spoiler_placeholder: { id: 'compose_form.spoiler_placeholder', defaultMessage: 'Write your warning here' }, publish: { id: 'compose_form.publish', defaultMessage: 'Toot' }, publishLoud: { id: 'compose_form.publish_loud', defaultMessage: '{publish}!' }, saveChanges: { id: 'compose_form.save_changes', defaultMessage: 'Save changes' }, }); export default @injectIntl class ComposeForm extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { intl: PropTypes.object.isRequired, text: PropTypes.string.isRequired, suggestions: ImmutablePropTypes.list, spoiler: PropTypes.bool, privacy: PropTypes.string, spoilerText: PropTypes.string, focusDate: PropTypes.instanceOf(Date), caretPosition: PropTypes.number, preselectDate: PropTypes.instanceOf(Date), isSubmitting: PropTypes.bool, isChangingUpload: PropTypes.bool, isEditing: PropTypes.bool, isUploading: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClearSuggestions: PropTypes.func.isRequired, onFetchSuggestions: PropTypes.func.isRequired, onSuggestionSelected: PropTypes.func.isRequired, onChangeSpoilerText: PropTypes.func.isRequired, onPaste: PropTypes.func.isRequired, onPickEmoji: PropTypes.func.isRequired, showSearch: PropTypes.bool, anyMedia: PropTypes.bool, isInReply: PropTypes.bool, singleColumn: PropTypes.bool, }; static defaultProps = { showSearch: false, }; handleChange = (e) => { this.props.onChange(e.target.value); } handleKeyDown = (e) => { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { this.handleSubmit(); } } getFulltextForCharacterCounting = () => { return [this.props.spoiler? this.props.spoilerText: '', countableText(this.props.text)].join(''); } canSubmit = () => { const { isSubmitting, isChangingUpload, isUploading, anyMedia } = this.props; const fulltext = this.getFulltextForCharacterCounting(); const isOnlyWhitespace = fulltext.length !== 0 && fulltext.trim().length === 0; return !(isSubmitting || isUploading || isChangingUpload || length(fulltext) > 500 || (isOnlyWhitespace && !anyMedia)); } handleSubmit = () => { if (this.props.text !== this.autosuggestTextarea.textarea.value) { // Something changed the text inside the textarea (e.g. browser extensions like Grammarly) // Update the state to match the current text this.props.onChange(this.autosuggestTextarea.textarea.value); } if (!this.canSubmit()) { return; } this.props.onSubmit(this.context.router ? this.context.router.history : null); } onSuggestionsClearRequested = () => { this.props.onClearSuggestions(); } onSuggestionsFetchRequested = (token) => { this.props.onFetchSuggestions(token); } onSuggestionSelected = (tokenStart, token, value) => { this.props.onSuggestionSelected(tokenStart, token, value, ['text']); } onSpoilerSuggestionSelected = (tokenStart, token, value) => { this.props.onSuggestionSelected(tokenStart, token, value, ['spoiler_text']); } handleChangeSpoilerText = (e) => { this.props.onChangeSpoilerText(e.target.value); } handleFocus = () => { if (this.composeForm && !this.props.singleColumn) { const { left, right } = this.composeForm.getBoundingClientRect(); if (left < 0 || right > (window.innerWidth || document.documentElement.clientWidth)) { this.composeForm.scrollIntoView(); } } } componentDidMount () { this._updateFocusAndSelection({ }); } componentDidUpdate (prevProps) { this._updateFocusAndSelection(prevProps); } _updateFocusAndSelection = (prevProps) => { // This statement does several things: // - If we're beginning a reply, and, // - Replying to zero or one users, places the cursor at the end of the textbox. // - Replying to more than one user, selects any usernames past the first; // this provides a convenient shortcut to drop everyone else from the conversation. if (this.props.focusDate !== prevProps.focusDate) { let selectionEnd, selectionStart; if (this.props.preselectDate !== prevProps.preselectDate && this.props.isInReply) { selectionEnd = this.props.text.length; selectionStart = this.props.text.search(/\s/) + 1; } else if (typeof this.props.caretPosition === 'number') { selectionStart = this.props.caretPosition; selectionEnd = this.props.caretPosition; } else { selectionEnd = this.props.text.length; selectionStart = selectionEnd; } // Because of the wicg-inert polyfill, the activeElement may not be // immediately selectable, we have to wait for observers to run, as // described in https://github.com/WICG/inert#performance-and-gotchas Promise.resolve().then(() => { this.autosuggestTextarea.textarea.setSelectionRange(selectionStart, selectionEnd); this.autosuggestTextarea.textarea.focus(); }).catch(console.error); } else if(prevProps.isSubmitting && !this.props.isSubmitting) { this.autosuggestTextarea.textarea.focus(); } else if (this.props.spoiler !== prevProps.spoiler) { if (this.props.spoiler) { this.spoilerText.input.focus(); } else { this.autosuggestTextarea.textarea.focus(); } } } setAutosuggestTextarea = (c) => { this.autosuggestTextarea = c; } setSpoilerText = (c) => { this.spoilerText = c; } setRef = c => { this.composeForm = c; }; handleEmojiPick = (data) => { const { text } = this.props; const position = this.autosuggestTextarea.textarea.selectionStart; const needsSpace = data.custom && position > 0 && !allowedAroundShortCode.includes(text[position - 1]); this.props.onPickEmoji(position, data, needsSpace); } render () { const { intl, onPaste, showSearch } = this.props; const disabled = this.props.isSubmitting; let publishText = ''; if (this.props.isEditing) { publishText = intl.formatMessage(messages.saveChanges); } else if (this.props.privacy === 'private' || this.props.privacy === 'direct') { publishText = <span className='compose-form__publish-private'><Icon id='lock' /> {intl.formatMessage(messages.publish)}</span>; } else { publishText = this.props.privacy !== 'unlisted' ? intl.formatMessage(messages.publishLoud, { publish: intl.formatMessage(messages.publish) }) : intl.formatMessage(messages.publish); } return ( <div className='compose-form'> <WarningContainer /> <ReplyIndicatorContainer /> <div className={`spoiler-input ${this.props.spoiler ? 'spoiler-input--visible' : ''}`} ref={this.setRef}> <AutosuggestInput placeholder={intl.formatMessage(messages.spoiler_placeholder)} value={this.props.spoilerText} onChange={this.handleChangeSpoilerText} onKeyDown={this.handleKeyDown} disabled={!this.props.spoiler} ref={this.setSpoilerText} suggestions={this.props.suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSpoilerSuggestionSelected} searchTokens={[':']} id='cw-spoiler-input' className='spoiler-input__input' /> </div> <AutosuggestTextarea ref={this.setAutosuggestTextarea} placeholder={intl.formatMessage(messages.placeholder)} disabled={disabled} value={this.props.text} onChange={this.handleChange} suggestions={this.props.suggestions} onFocus={this.handleFocus} onKeyDown={this.handleKeyDown} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} onPaste={onPaste} autoFocus={!showSearch && !isMobile(window.innerWidth)} > <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} /> <div className='compose-form__modifiers'> <UploadFormContainer /> <PollFormContainer /> </div> </AutosuggestTextarea> <div className='compose-form__buttons-wrapper'> <div className='compose-form__buttons'> <UploadButtonContainer /> <PollButtonContainer /> <PrivacyDropdownContainer disabled={this.props.isEditing} /> <SpoilerButtonContainer /> </div> <div className='character-counter__wrapper'><CharacterCounter max={500} text={this.getFulltextForCharacterCounting()} /></div> </div> <div className='compose-form__publish'> <div className='compose-form__publish-button-wrapper'><Button text={publishText} onClick={this.handleSubmit} disabled={!this.canSubmit()} block /></div> </div> </div> ); } }
app/containers/Root.js
sheldhur/Vector
// @flow import React from 'react'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'react-router-redux'; import Routes from '../routes'; type RootType = { store: {}, history: {} }; export default function Root({ store, history }: RootType) { return ( <Provider store={store}> <ConnectedRouter history={history}> <Routes /> </ConnectedRouter> </Provider> ); }
projeto/todo/src/components/App.js
frbaroni/curso_react
import React from 'react' import Footer from './Footer' import Todo from '../containers/add-todo' import Lista from '../containers/lista' const App = () => ( <div className="container"> <Todo /> <Lista /> <Footer /> </div> ) export default App
js/EditDictionaryDialog.js
dmitriykovalev/slovareg
import React from 'react'; import {Button, FormGroup, FormControl, Input, Modal} from 'react-bootstrap'; const EditDictionaryDialog = React.createClass({ propTypes: { show: React.PropTypes.bool.isRequired, onDone: React.PropTypes.func.isRequired, // f(name, words) onHide: React.PropTypes.func.isRequired, // f() title: React.PropTypes.string.isRequired, submitText: React.PropTypes.string.isRequired, name: React.PropTypes.string, words: React.PropTypes.string, }, getDefaultProps() { return { name: '', words: '' }; }, getInitialState() { return { name: '', words: '' }; }, componentWillReceiveProps(nextProps) { this.setState({ name: nextProps.name, words: nextProps.words }); }, handleSubmit(event) { event.preventDefault(); const {name, words} = this.state; if (name.trim()) { this.props.onDone(name, words); this.props.onHide(); } }, handleNameChange(event) { this.setState({name: event.target.value}); }, handleWordsChange(event) { this.setState({words: event.target.value}); }, render() { return ( <Modal bsSize='large' animation={false} onHide={this.props.onHide} show={this.props.show}> <form> <Modal.Header closeButton> <Modal.Title>{this.props.title}</Modal.Title> </Modal.Header> <Modal.Body> <FormGroup controlId='name'> <FormControl type='text' placeholder='Name' value={this.state.name} onChange={this.handleNameChange} autoFocus/> </FormGroup> <FormGroup controlId='words'> <FormControl componentClass='textarea' placeholder='Words' value={this.state.words} onChange={this.handleWordsChange}/> </FormGroup> </Modal.Body> <Modal.Footer> <Button onClick={this.props.onHide}>Cancel</Button> <Button bsStyle='primary' disabled={!this.state.name.trim()} onClick={this.handleSubmit}>{this.props.submitText}</Button> </Modal.Footer> </form> </Modal> ); } }); export default EditDictionaryDialog;
src/mui/field/DateField.js
RestUI/rest-ui
import React from 'react'; import PropTypes from 'prop-types'; import get from 'lodash.get'; import pure from 'recompose/pure'; const toLocaleStringSupportsLocales = (() => { // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString try { new Date().toLocaleString("i"); } catch (error) { return (error instanceof RangeError); } return false; })(); /** * Display a date value as a locale string. * * Uses Intl.DateTimeFormat() if available, passing the locales and options props as arguments. * If Intl is not available, it outputs date as is (and ignores the locales and options props). * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString * @example * <DateField source="published_at" /> * // renders the record { id: 1234, published_at: new Date('2012-11-07') } as * <span>07/11/2012</span> * * <DateField source="published_at" elStyle={{ color: 'red' }} /> * // renders the record { id: 1234, new Date('2012-11-07') } as * <span style="color:red;">07/11/2012</span> * * <DateField source="share" options={{ weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }} /> * // renders the record { id: 1234, new Date('2012-11-07') } as * <span>Wednesday, November 7, 2012</span> * * <DateField source="price" locales="fr-FR" options={{ weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }} /> * // renders the record { id: 1234, new Date('2012-11-07') } as * <span>mercredi 7 novembre 2012</span> */ export const DateField = ({ elStyle, locales, options, record, showTime = false, source }) => { if (!record) return null; const value = get(record, source); if (value == null) return null; const date = value instanceof Date ? value : new Date(value); const dateString = showTime ? (toLocaleStringSupportsLocales ? date.toLocaleString(locales, options) : date.toLocaleString()) : (toLocaleStringSupportsLocales ? date.toLocaleDateString(locales, options) : date.toLocaleDateString()); return <span style={elStyle}>{dateString}</span>; }; DateField.propTypes = { addLabel: PropTypes.bool, elStyle: PropTypes.object, label: PropTypes.string, locales: PropTypes.oneOfType([ PropTypes.string, PropTypes.arrayOf(PropTypes.string), ]), options: PropTypes.object, record: PropTypes.object, showTime: PropTypes.bool, source: PropTypes.string.isRequired, }; const PureDateField = pure(DateField); PureDateField.defaultProps = { addLabel: true, }; export default PureDateField;
app/components/Character.js
migueloop/1streaction
import React from 'react'; import CharacterStore from '../stores/CharacterStore'; import CharacterActions from '../actions/CharacterActions' class Character extends React.Component { constructor(props) { super(props); this.state = CharacterStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { CharacterStore.listen(this.onChange); CharacterActions.getCharacter(this.props.params.id); $('.magnific-popup').magnificPopup({ type: 'image', mainClass: 'mfp-zoom-in', closeOnContentClick: true, midClick: true, zoom: { enabled: true, duration: 300 } }); } componentWillUnmount() { CharacterStore.unlisten(this.onChange); $(document.body).removeClass(); } componentDidUpdate(prevProps) { if (prevProps.params.id !== this.props.params.id) { CharacterActions.getCharacter(this.props.params.id); } } onChange(state) { this.setState(state); } render() { return ( <div className='container'> <div className='profile-img'> <a ref='magnificPopup' className='magnific-popup' href={'https://image.eveonline.com/Character/' + this.state.characterId + '_1024.jpg'}> <img src={'https://image.eveonline.com/Character/' + this.state.characterId + '_256.jpg'} /> </a> </div> <div className='profile-info clearfix'> <h2><strong>{this.state.name}</strong></h2> <h4 className='lead'>Race: <strong>{this.state.race}</strong></h4> <h4 className='lead'>Bloodline: <strong>{this.state.bloodline}</strong></h4> <h4 className='lead'>Gender: <strong>{this.state.gender}</strong></h4> <button className='btn btn-transparent' onClick={CharacterActions.report.bind(this, this.state.characterId)} disabled={this.state.isReported}> {this.state.isReported ? 'Reported' : 'Report Character'} </button> </div> <div className='profile-stats clearfix'> <ul> <li><span className='stats-number'>{this.state.winLossRatio}</span>Winning Percentage</li> <li><span className='stats-number'>{this.state.wins}</span> Wins</li> <li><span className='stats-number'>{this.state.losses}</span> Losses</li> </ul> </div> </div> ); } } export default Character;
src/routes/error/index.js
vincentdd/crm
import React from 'react' import { Icon } from 'antd' import styles from './index.less' const Error = () => (<div className="content-inner"> <div className={styles.error}> <Icon type="frown-o" /> <h1>404 Not Found</h1> </div> </div>) export default Error
app/javascript/mastodon/features/compose/containers/sensitive_button_container.js
haleyashleypraesent/ProjectPrionosuchus
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import IconButton from '../../../components/icon_button'; import { changeComposeSensitivity } from '../../../actions/compose'; import Motion from 'react-motion/lib/Motion'; import spring from 'react-motion/lib/spring'; import { injectIntl, defineMessages } from 'react-intl'; const messages = defineMessages({ title: { id: 'compose_form.sensitive', defaultMessage: 'Mark media as sensitive' }, }); const mapStateToProps = state => ({ visible: state.getIn(['compose', 'media_attachments']).size > 0, active: state.getIn(['compose', 'sensitive']), }); const mapDispatchToProps = dispatch => ({ onClick () { dispatch(changeComposeSensitivity()); }, }); class SensitiveButton extends React.PureComponent { static propTypes = { visible: PropTypes.bool, active: PropTypes.bool, onClick: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { visible, active, onClick, intl } = this.props; return ( <Motion defaultStyle={{ scale: 0.87 }} style={{ scale: spring(visible ? 1 : 0.87, { stiffness: 200, damping: 3 }) }}> {({ scale }) => { const icon = active ? 'eye-slash' : 'eye'; const className = classNames('compose-form__sensitive-button', { 'compose-form__sensitive-button--visible': visible, }); return ( <div className={className} style={{ transform: `translateZ(0) scale(${scale})` }}> <IconButton className='compose-form__sensitive-button__icon' title={intl.formatMessage(messages.title)} icon={icon} onClick={onClick} size={18} active={active} style={{ lineHeight: null, height: null }} inverted /> </div> ); }} </Motion> ); } } export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(SensitiveButton));
src/components/ShareExperience/common/SuccessFeedback.js
WendellLiu/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import Checked from 'common/icons/Checked'; import Feedback from 'common/Feedback'; const SuccessFeedback = ({ buttonClick }) => ( <Feedback buttonClick={buttonClick} heading="上傳成功" buttonText="查看本篇" Icon={Checked} /> ); SuccessFeedback.propTypes = { buttonClick: PropTypes.func, }; export default SuccessFeedback;
frontend/src/components/eois/details/headerOptions/agencyOpenHeaderOptions.js
unicef/un-partner-portal
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { compose } from 'ramda'; import { withRouter } from 'react-router'; import { connect } from 'react-redux'; import { PROJECT_STATUSES } from '../../../../helpers/constants'; import { authorizedFileDownload } from '../../../../helpers/api/api'; import DropdownMenu from '../../../common/dropdownMenu'; import SpreadContent from '../../../common/spreadContent'; import EditButton from '../../buttons/editCfeiButton'; import DownloadButton from '../../buttons/downloadCfeiButton'; import InviteButton from '../../buttons/invitePartner'; import Reviewers from '../../buttons/manageReviewers'; import Complete from '../../buttons/completeCfeiButton'; import withMultipleDialogHandling from '../../../common/hoc/withMultipleDialogHandling'; import EditCfeiModal from '../../modals/editCfei/editCfeiModal'; import EditDateCfeiModal from '../../modals/editCfei/editDateCfeiModal'; import AddInformedPartners from '../../modals/callPartners/addInformedPartners'; import ManageReviewersModal from '../../modals/manageReviewers/manageReviewersModal'; import CompleteCfeiModal from '../../modals/completeCfei/completeCfeiModal'; import CancelCfeiModal from '../../modals/completeCfei/cancelCfeiModal'; import DeleteCfeiModal from '../../modals/completeCfei/deleteCfeiModal'; import SendCfeiButton from '../../buttons/sendCfeiButton'; import DeleteButton from '../../buttons/deleteCfeiButton'; import PublishCfeiButton from '../../buttons/publishCfeiButton'; import SendCfeiModal from '../../modals/completeCfei/sendCfeiModal'; import PublishCfeiModal from '../../modals/completeCfei/publishCfeiModal'; import { checkPermission, isRoleOffice, AGENCY_ROLES, AGENCY_PERMISSIONS, COMMON_PERMISSIONS } from '../../../../helpers/permissions'; import { selectCfeiStatus, isCfeiPublished, isCfeiDeadlinePassed, isCfeiCompleted, isUserAFocalPoint, isUserACreator, cfeiHasRecommendedPartner, isSendForDecision, isCfeiClarificationDeadlinePassed, } from '../../../../store'; import CancelCfeiButton from '../../buttons/cancelCfeiButton'; const messages = { updateDeadlineDate: 'Update Application Deadline date to publish this CFEI', updateClarificationDate: 'Update Application Clarificatin Deadline date to publish this CFEI', } const del = 'del'; const edit = 'edit'; const cancel = 'cancel'; const invite = 'invite'; const manage = 'manage'; const complete = 'complete'; const send = 'send'; const publish = 'publish'; const editDate = 'editDate'; const download = 'download'; class PartnerOpenHeaderOptions extends Component { constructor(props) { super(props); this.sendOptions = this.sendOptions.bind(this); this.isPuslishPermissionAllowed = this.isPuslishPermissionAllowed.bind(this); } isFinalizeAllowed(hasActionPermission) { const { isAdvEd, isPAM, isBasEd, isMFT, isCreator, isFocalPoint } = this.props; return ((hasActionPermission && isAdvEd && (isCreator || isFocalPoint)) || (hasActionPermission && isBasEd && isCreator) || (hasActionPermission && isMFT && isFocalPoint) || (hasActionPermission && isPAM && isCreator)); } isPuslishPermissionAllowed(hasActionPermission) { const { isAdvEd, isPAM, isBasEd, isCreator, isFocalPoint } = this.props; return ((hasActionPermission && isAdvEd && (isCreator || isFocalPoint)) || (hasActionPermission && isBasEd && isCreator) || (hasActionPermission && isPAM && isCreator)); } sendOptions() { const { params: { id }, handleDialogOpen, hasManageDraftPermission, hasInviteSentPermission, hasEditSentPermission, hasEditPublishedDatesPermission, hasInvitePublishPermission, hasCancelPublishPermission, hasManageReviewersPermission, hasRecommendedPartner, isSend, status, isPublished, isDeadlinePassed, isFocalPoint, isCreator } = this.props; const options = [ { name: download, content: <DownloadButton handleClick={() => { authorizedFileDownload({ uri: `/projects/${id}/?export=pdf` }); }} />, }, ]; if (((hasManageDraftPermission && isCreator && status === PROJECT_STATUSES.DRA) || (hasEditSentPermission && isFocalPoint)) && !isPublished) { options.push( { name: edit, content: <EditButton handleClick={() => handleDialogOpen(edit)} />, }); } if (this.isPuslishPermissionAllowed(hasEditPublishedDatesPermission) && isPublished) { options.push( { name: editDate, content: <EditButton handleClick={() => handleDialogOpen(editDate)} />, }); } if (((hasManageDraftPermission && isCreator && status === PROJECT_STATUSES.DRA) || (hasInviteSentPermission && isFocalPoint && status === PROJECT_STATUSES.SEN) || (isPublished && this.isPuslishPermissionAllowed(hasInvitePublishPermission))) && !isDeadlinePassed) { options.push( { name: invite, content: <InviteButton handleClick={() => handleDialogOpen(invite)} />, }); } if (!hasRecommendedPartner && !isSend && isPublished && this.isPuslishPermissionAllowed(hasManageReviewersPermission)) { options.push( { name: manage, content: <Reviewers handleClick={() => handleDialogOpen(manage)} />, }); } if (!isPublished && (hasManageDraftPermission && isCreator && status === PROJECT_STATUSES.DRA || (hasEditSentPermission && isFocalPoint))) { options.push( { name: del, content: <DeleteButton handleClick={() => handleDialogOpen(del)} />, }); } if (!isPublished && this.isPuslishPermissionAllowed(hasCancelPublishPermission)) { options.push( { name: cancel, content: <CancelCfeiButton handleClick={() => handleDialogOpen(cancel)} />, }); } return options; } render() { const { params: { id }, isCompleted, isCreator, isFocalPoint, isPublished, status, isDeadlinePassed, isClarificationRequestPassed, isAdvEd, isPAM, hasPublishPermission, hasSendPermission, hasFinalizePermission, dialogOpen, handleDialogClose, handleDialogOpen } = this.props; return ( <SpreadContent> {isPublished && this.isFinalizeAllowed(hasFinalizePermission) && <Complete handleClick={() => handleDialogOpen(complete)} />} {!isCompleted && status === PROJECT_STATUSES.DRA && isCreator && hasSendPermission && !isPAM && <SendCfeiButton handleClick={() => handleDialogOpen(send)} />} {!isPublished && !isCompleted && hasPublishPermission && (((isFocalPoint || isCreator) && isAdvEd) || (isCreator && isPAM)) && <PublishCfeiButton tooltipInfo={isDeadlinePassed && messages.updateDeadlineDate || isClarificationRequestPassed && messages.updateClarificationDate} disabled={isDeadlinePassed || isClarificationRequestPassed} handleClick={() => handleDialogOpen(publish)} />} <DropdownMenu options={this.sendOptions()} /> {dialogOpen[del] && <DeleteCfeiModal id={id} dialogOpen={dialogOpen[del]} handleDialogClose={handleDialogClose} />} {dialogOpen[cancel] && <CancelCfeiModal id={id} dialogOpen={dialogOpen[cancel]} handleDialogClose={handleDialogClose} />} {dialogOpen[publish] && <PublishCfeiModal id={id} type="open" dialogOpen={dialogOpen[publish]} handleDialogClose={handleDialogClose} />} {dialogOpen[send] && <SendCfeiModal id={id} type="open" dialogOpen={dialogOpen[send]} handleDialogClose={handleDialogClose} />} {dialogOpen[edit] && <EditCfeiModal id={id} type="open" dialogOpen={dialogOpen[edit]} handleDialogClose={handleDialogClose} />} {dialogOpen[editDate] && <EditDateCfeiModal id={id} type="open" dialogOpen={dialogOpen[editDate]} handleDialogClose={handleDialogClose} />} {dialogOpen[invite] && <AddInformedPartners id={id} dialogOpen={dialogOpen[invite]} handleDialogClose={handleDialogClose} />} {dialogOpen[manage] && <ManageReviewersModal id={id} dialogOpen={dialogOpen[manage]} handleDialogClose={handleDialogClose} />} {dialogOpen[complete] && <CompleteCfeiModal id={id} dialogOpen={dialogOpen[complete]} handleDialogClose={handleDialogClose} />} </SpreadContent> ); } } PartnerOpenHeaderOptions.propTypes = { params: PropTypes.object, dialogOpen: PropTypes.object, handleDialogClose: PropTypes.func, handleDialogOpen: PropTypes.func, isPublished: PropTypes.bool, isCreator: PropTypes.bool, isFocalPoint: PropTypes.bool, hasManageDraftPermission: PropTypes.bool, hasSendPermission: PropTypes.bool, hasInviteSentPermission: PropTypes.bool, hasEditSentPermission: PropTypes.bool, hasInvitePublishPermission: PropTypes.bool, hasCancelPublishPermission: PropTypes.bool, hasPublishPermission: PropTypes.bool, hasEditPublishedDatesPermission: PropTypes.bool, hasManageReviewersPermission: PropTypes.bool, hasFinalizePermission: PropTypes.bool, hasRecommendedPartner: PropTypes.bool, isDeadlinePassed: PropTypes.bool, isClarificationRequestPassed: PropTypes.bool, isCompleted: PropTypes.bool, isAdvEd: PropTypes.bool, isMFT: PropTypes.bool, isPAM: PropTypes.bool, isBasEd: PropTypes.bool, isSend: PropTypes.bool, status: PropTypes.string, }; const mapStateToProps = (state, ownProps) => ({ isCreator: isUserACreator(state, ownProps.id), isFocalPoint: isUserAFocalPoint(state, ownProps.id), isCompleted: isCfeiCompleted(state, ownProps.id), isPublished: isCfeiPublished(state, ownProps.id), isDeadlinePassed: isCfeiDeadlinePassed(state, ownProps.id), isClarificationRequestPassed: isCfeiClarificationDeadlinePassed(state, ownProps.id), hasRecommendedPartner: cfeiHasRecommendedPartner(state, ownProps.id), status: selectCfeiStatus(state, ownProps.id), hasManageDraftPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_DRAFT_MANAGE, state), hasSendPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_DRAFT_SEND_TO_FOCAL_POINT_TO_PUBLISH, state), hasInviteSentPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_SENT_INVITE_CSO, state), hasPublishPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_PUBLISH, state) || checkPermission(AGENCY_PERMISSIONS.CFEI_SENT_PUBLISH, state), hasEditSentPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_SENT_EDIT, state), hasInvitePublishPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_PUBLISHED_INVITE_CSO, state), hasCancelPublishPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_PUBLISHED_CANCEL, state), hasManageReviewersPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_MANAGE_REVIEWERS, state), hasFinalizePermission: checkPermission(COMMON_PERMISSIONS.CFEI_FINALIZE, state), hasEditPublishedDatesPermission: checkPermission(AGENCY_PERMISSIONS.CFEI_PUBLISHED_EDIT_DATES, state), isAdvEd: isRoleOffice(AGENCY_ROLES.EDITOR_ADVANCED, state), isMFT: isRoleOffice(AGENCY_ROLES.MFT_USER, state), isPAM: isRoleOffice(AGENCY_ROLES.PAM_USER, state), isBasEd: isRoleOffice(AGENCY_ROLES.EDITOR_BASIC, state), isSend: isSendForDecision(state, ownProps.id), }); export default compose( withMultipleDialogHandling, connect(mapStateToProps, null), withRouter, )(PartnerOpenHeaderOptions);
Inspector/js/app.js
qa-dev/WebDriverAgent
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React from 'react'; import ReactDOM from 'react-dom'; import HTTP from 'js/http'; import Screen from 'js/screen'; import ScreenshotFactory from 'js/screenshot_factory'; import Tree from 'js/tree'; import TreeNode from 'js/tree_node'; import TreeContext from 'js/tree_context'; import Inspector from 'js/inspector'; require('css/app.css'); const SCREENSHOT_ENDPOINT = 'screenshot'; const TREE_ENDPOINT = 'source?format=json'; const ORIENTATION_ENDPOINT = 'orientation'; class App extends React.Component { constructor(props) { super(props); this.state = {}; } refreshApp() { this.fetchScreenshot(); this.fetchTree(); } componentDidMount() { this.refreshApp(); } fetchScreenshot() { HTTP.get(ORIENTATION_ENDPOINT, (orientation) => { orientation = orientation.value; HTTP.get(SCREENSHOT_ENDPOINT, (base64EncodedImage) => { base64EncodedImage = base64EncodedImage.value; ScreenshotFactory.createScreenshot(orientation, base64EncodedImage, (screenshot) => { this.setState({ screenshot: screenshot, }); }); }); }); } fetchTree() { HTTP.get(TREE_ENDPOINT, (treeInfo) => { treeInfo = treeInfo.value; this.setState({ rootNode: TreeNode.buildNode(treeInfo, new TreeContext()), }); }); } render() { return ( <div id="app"> <Screen highlightedNode={this.state.highlightedNode} screenshot={this.state.screenshot} rootNode={this.state.rootNode} refreshApp={() => { this.refreshApp(); }} /> <Tree onHighlightedNodeChange={(node) => { this.setState({ highlightedNode: node, }); }} onSelectedNodeChange={(node) => { this.setState({ selectedNode: node, }); }} rootNode={this.state.rootNode} selectedNode={this.state.selectedNode} /> <Inspector selectedNode={this.state.selectedNode} refreshApp={() => { this.refreshApp(); }} /> </div> ); } } ReactDOM.render(<App />, document.body);
packages/retabulate-react/src/components/WrapRenderer.js
jasonphillips/retabulate
import React from 'react'; // converts cells to a collection to be used in charts, etc const WrapRenderer = ({data, renderer}) => { const cells = data.rows.map(r => r.cells).reduce((all,a) => all.concat(a), []) const collection = cells.map( c => ({ ...c.queries.reduce((combined, {key, values}) => ({...combined, [key]: values}), {}), value: JSON.parse(c.value), agg: c.agg, variable: c.variable, }) ); return React.createElement(renderer, {data: collection}); } export default WrapRenderer;
app/javascript/mastodon/components/avatar_overlay.js
Chronister/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { autoPlayGif } from '../initial_state'; export default class AvatarOverlay extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, friend: ImmutablePropTypes.map.isRequired, animate: PropTypes.bool, }; static defaultProps = { animate: autoPlayGif, }; render() { const { account, friend, animate } = this.props; const baseStyle = { backgroundImage: `url(${account.get(animate ? 'avatar' : 'avatar_static')})`, }; const overlayStyle = { backgroundImage: `url(${friend.get(animate ? 'avatar' : 'avatar_static')})`, }; return ( <div className='account__avatar-overlay'> <div className='account__avatar-overlay-base' style={baseStyle} /> <div className='account__avatar-overlay-overlay' style={overlayStyle} /> </div> ); } }
app/index.ios.js
stianjensen/shortsdag.no
import React, { Component } from 'react'; import { AppRegistry, AppState, StyleSheet, Text, View, Image, Modal, TouchableHighlight, } from 'react-native'; import Credits from './credits'; const apiURL = 'https://shortsdag.no'; export default class Shortsdag extends Component { constructor(props) { super(props); this.state = { appState: AppState.currentState, forecast: null, modalVisible: false, }; this.updateForecast(); } setModalVisible(visible) { this.setState({modalVisible: visible}); } updateForecast() { const success = async pos => { const url = '/api/forecast/' + pos.coords.latitude +'/' + pos.coords.longitude + '/'; const response = await fetch(apiURL + url); const data = await response.json(); this.setState({forecast: data}); }; const error = async err => { const url = '/api/forecast/'; const response = await fetch(apiURL + url); const data = await response.json(); this.setState({forecast: data}); }; const options = { timeout: 5000, maximumAge: 60000 }; navigator.geolocation.getCurrentPosition(success, error, options) } componentDidMount() { AppState.addEventListener('change', this._handleAppStateChange); } componentWillUnmount() { AppState.removeEventListener('change', this._handleAppStateChange); } _handleAppStateChange = nextAppState => { if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') { this.setState({forecast: null}); this.updateForecast(); } this.setState({appState: nextAppState}); }; render() { let forecastImage, forecastText; if (this.state.forecast) { const weather = this.state.forecast.weather; if (weather === 'shorts') { forecastImage = require('./images/bg_shorts.jpg'); forecastText = 'Det er shortsdag!'; } else if (weather === 'pants') { forecastImage = require('./images/bg_pants.jpg'); forecastText = 'Det er ikke shortsdag :(' } else if (weather === 'freezing') { forecastImage = require('./images/bg_cold.jpg'); forecastText = 'Det er ikke shortsdag :(' } else if (weather === 'snow') { forecastImage = require('./images/bg_snow.jpg'); forecastText = 'Det er ikke shortsdag :(' } else if (weather === 'rain') { forecastImage = require('./images/bg_rain.jpg'); forecastText = 'Det er ikke shortsdag :(' } } return ( <View style={styles.container}> { this.state.forecast ? <Image style={styles.background} source={forecastImage}> <Text style={styles.shortsdag}> {forecastText} </Text> </Image> : <Text style={styles.loading}> Kikker ut vinduet... </Text> } <TouchableHighlight onPress={() => { this.setModalVisible(true) }} style={styles.showModalButton} > <Text style={styles.showModalButtonText}>?</Text> </TouchableHighlight> <Modal animationType={"slide"} transparent={false} visible={this.state.modalVisible} onRequestClose={() => {alert("Modal has been closed.")}} > <Credits /> <TouchableHighlight onPress={() => {this.setModalVisible(!this.state.modalVisible)}} style={styles.showModalButton} > <Text style={styles.showModalButtonText}>X</Text> </TouchableHighlight> </Modal> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, background: { flex: 1, justifyContent: 'center', alignItems: 'center', resizeMode: 'contain', }, loading: { margin: 10, fontSize: 30, textAlign: 'center', }, shortsdag: { fontSize: 30, textAlign: 'center', color: '#ffffff', backgroundColor: 'transparent', }, notshortsdag: { fontSize: 30, textAlign: 'center', color: '#ffffff', backgroundColor: 'transparent', }, showModalButton: { position: 'absolute', top: 30, right: 20, backgroundColor: 'rgba(0, 0, 0, 0.5)', width: 40, height: 40, borderRadius: 20, }, showModalButtonText: { lineHeight: 40, textAlign: 'center', color: '#ffffff', }, }); AppRegistry.registerComponent('Shortsdag', () => Shortsdag);
test/integration/prerender/pages/blocking-fallback/[slug].js
azukaru/next.js
import React from 'react' import Link from 'next/link' import { useRouter } from 'next/router' export async function getStaticPaths() { return { paths: [], fallback: 'blocking', } } export async function getStaticProps({ params }) { await new Promise((resolve) => setTimeout(resolve, 1000)) return { props: { params, hello: 'world', post: params.slug, random: Math.random(), time: (await import('perf_hooks')).performance.now(), }, revalidate: 1, } } export default ({ post, time, params }) => { if (useRouter().isFallback) { return <p>hi fallback</p> } return ( <> <p>Post: {post}</p> <span>time: {time}</span> <div id="params">{JSON.stringify(params)}</div> <div id="query">{JSON.stringify(useRouter().query)}</div> <Link href="/"> <a id="home">to home</a> </Link> </> ) }
app/routes/user/CreateRoute.js
ryrudnev/dss-wm
import React from 'react'; import Helmet from 'react-helmet'; import { Route } from '../../core/router'; import { Model as User } from '../../entities/User'; import { Collection as Companies } from '../../entities/Company'; import { PageHeader, Row, Col, Panel } from 'react-bootstrap'; import UserForm from '../../components/UserForm'; import Progress from 'react-progress-2'; import radio from 'backbone.radio'; const router = radio.channel('router'); const session = radio.channel('session'); export default class CompanyCreateRoute extends Route { breadcrumb = 'Создать' authorize() { return session.request('currentUser').get('role') === 'admin'; } onCancel() { router.request('navigate', 'users'); } fetch() { this.companies = new Companies; return this.companies.fetch(); } onSubmit(values) { Progress.show(); (new User(values)).save({}, { success: model => { Progress.hide(); router.request('navigate', `users/${model.id}`); }, }); } render() { return ( <div> <Helmet title="Регистрация нового пользователя" /> <PageHeader>Регистрация нового пользователя</PageHeader> <Row> <Col md={8}> <Panel> <UserForm create onSubmit={this.onSubmit} onCancel={this.onCancel} companies={this.companies.toJSON()} /> </Panel> </Col> </Row> </div> ); } }
src/svg-icons/image/flash-auto.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFlashAuto = (props) => ( <SvgIcon {...props}> <path d="M3 2v12h3v9l7-12H9l4-9H3zm16 0h-2l-3.2 9h1.9l.7-2h3.2l.7 2h1.9L19 2zm-2.15 5.65L18 4l1.15 3.65h-2.3z"/> </SvgIcon> ); ImageFlashAuto = pure(ImageFlashAuto); ImageFlashAuto.displayName = 'ImageFlashAuto'; ImageFlashAuto.muiName = 'SvgIcon'; export default ImageFlashAuto;
actor-apps/app-web/src/app/components/sidebar/HeaderSection.react.js
shenhzou654321/actor-platform
import React from 'react'; import mixpanel from 'utils/Mixpanel'; import MyProfileActions from 'actions/MyProfileActions'; import LoginActionCreators from 'actions/LoginActionCreators'; import AvatarItem from 'components/common/AvatarItem.react'; import MyProfileModal from 'components/modals/MyProfile.react'; import ActorClient from 'utils/ActorClient'; import classNames from 'classnames'; var getStateFromStores = () => { return {dialogInfo: null}; }; class HeaderSection extends React.Component { componentWillMount() { ActorClient.bindUser(ActorClient.getUid(), this.setUser); } constructor() { super(); this.setUser = this.setUser.bind(this); this.toggleHeaderMenu = this.toggleHeaderMenu.bind(this); this.openMyProfile = this.openMyProfile.bind(this); this.setLogout = this.setLogout.bind(this); this.state = getStateFromStores(); } setUser(user) { this.setState({user: user}); } toggleHeaderMenu() { mixpanel.track('Open sidebar menu'); this.setState({isOpened: !this.state.isOpened}); } setLogout() { LoginActionCreators.setLoggedOut(); } render() { var user = this.state.user; if (user) { var headerClass = classNames('sidebar__header', 'sidebar__header--clickable', { 'sidebar__header--opened': this.state.isOpened }); return ( <header className={headerClass}> <div className="sidebar__header__user row" onClick={this.toggleHeaderMenu}> <AvatarItem image={user.avatar} placeholder={user.placeholder} size="small" title={user.name} /> <span className="sidebar__header__user__name col-xs">{user.name}</span> <span className="sidebar__header__user__expand"> <i className="material-icons">keyboard_arrow_down</i> </span> </div> <ul className="sidebar__header__menu"> <li className="sidebar__header__menu__item" onClick={this.openMyProfile}> <i className="material-icons">person</i> <span>Profile</span> </li> {/* <li className="sidebar__header__menu__item" onClick={this.openCreateGroup}> <i className="material-icons">group_add</i> <span>Create group</span> </li> */} <li className="sidebar__header__menu__item hide"> <i className="material-icons">cached</i> <span>Integrations</span> </li> <li className="sidebar__header__menu__item hide"> <i className="material-icons">settings</i> <span>Settings</span> </li> <li className="sidebar__header__menu__item hide"> <i className="material-icons">help</i> <span>Help</span> </li> <li className="sidebar__header__menu__item" onClick={this.setLogout}> <i className="material-icons">power_settings_new</i> <span>Log out</span> </li> </ul> <MyProfileModal/> </header> ); } else { return null; } } openMyProfile() { MyProfileActions.modalOpen(); mixpanel.track('My profile open'); this.setState({isOpened: false}); } } export default HeaderSection;
src/svg-icons/navigation/subdirectory-arrow-left.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationSubdirectoryArrowLeft = (props) => ( <SvgIcon {...props}> <path d="M11 9l1.42 1.42L8.83 14H18V4h2v12H8.83l3.59 3.58L11 21l-6-6 6-6z"/> </SvgIcon> ); NavigationSubdirectoryArrowLeft = pure(NavigationSubdirectoryArrowLeft); NavigationSubdirectoryArrowLeft.displayName = 'NavigationSubdirectoryArrowLeft'; NavigationSubdirectoryArrowLeft.muiName = 'SvgIcon'; export default NavigationSubdirectoryArrowLeft;
frontend/src/Noise.js
generalelectrix/color_organist
import React from 'react' import { Slider } from './Slider' const GAUSSIAN = 'gaussian' const UNIFORM = 'uniform' const Noise = ({name, initialCenter, bipolar, dispatch}) => { const [mode, setMode] = React.useState(GAUSSIAN) const [center, setCenter] = React.useState(initialCenter) const [width, setWidth] = React.useState(0.0) const updateAndSend = (parameter, value, stateUpdater) => { stateUpdater(value) dispatch(name, parameter, value) } const updateMode = e => { const v = e.target.value updateAndSend("mode", v, setMode) } return ( <div className="flexcol stretch"> <select value={mode} onChange={updateMode}> <option value={GAUSSIAN}>gaussian</option> <option value={UNIFORM}>uniform</option> </select> <div className="flexrow stretch"> <Slider label="center" value={center} min={bipolar ? -1.0 : 0.0} onChange={v => updateAndSend("center", v, setCenter)} /> <Slider label="width" value={width} onChange={v => updateAndSend("width", v, setWidth)} /> </div> </div> ) } export default Noise
node_modules/react-router-dom/node_modules/react-router/es/Redirect.js
pornvutp/tact
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; import warning from 'warning'; import invariant from 'invariant'; import { createLocation, locationsAreEqual } from 'history'; /** * The public API for updating the location programmatically * with a component. */ var Redirect = function (_React$Component) { _inherits(Redirect, _React$Component); function Redirect() { _classCallCheck(this, Redirect); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Redirect.prototype.isStatic = function isStatic() { return this.context.router && this.context.router.staticContext; }; Redirect.prototype.componentWillMount = function componentWillMount() { invariant(this.context.router, 'You should not use <Redirect> outside a <Router>'); if (this.isStatic()) this.perform(); }; Redirect.prototype.componentDidMount = function componentDidMount() { if (!this.isStatic()) this.perform(); }; Redirect.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { var prevTo = createLocation(prevProps.to); var nextTo = createLocation(this.props.to); if (locationsAreEqual(prevTo, nextTo)) { warning(false, 'You tried to redirect to the same route you\'re currently on: ' + ('"' + nextTo.pathname + nextTo.search + '"')); return; } this.perform(); }; Redirect.prototype.perform = function perform() { var history = this.context.router.history; var _props = this.props, push = _props.push, to = _props.to; if (push) { history.push(to); } else { history.replace(to); } }; Redirect.prototype.render = function render() { return null; }; return Redirect; }(React.Component); Redirect.propTypes = { push: PropTypes.bool, from: PropTypes.string, to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired }; Redirect.defaultProps = { push: false }; Redirect.contextTypes = { router: PropTypes.shape({ history: PropTypes.shape({ push: PropTypes.func.isRequired, replace: PropTypes.func.isRequired }).isRequired, staticContext: PropTypes.object }).isRequired }; export default Redirect;
packages/cf-component-card/src/CardToolbar.js
koddsson/cf-ui
import React from 'react'; import PropTypes from 'prop-types'; class CardToolbar extends React.Component { render() { return ( <div className="cf-card__toolbar"> <div className="cf-card__toolbar_controls"> {this.props.controls} </div> <div className="cf-card__toolbar_links" role="tablist"> {this.props.links} </div> </div> ); } } CardToolbar.propTypes = { controls: PropTypes.any, links: PropTypes.any }; export default CardToolbar;
docs-ui/components/emptyStateWarning.stories.js
mvaled/sentry
import React from 'react'; import {storiesOf} from '@storybook/react'; import {withInfo} from '@storybook/addon-info'; import EmptyStateWarning from 'app/components/emptyStateWarning'; storiesOf('UI|EmptyStateWarning', module).add( 'default', withInfo('Default')(() => ( <EmptyStateWarning data="https://example.org/foo/bar/"> <p>There are no events found!</p> </EmptyStateWarning> )) );
app/admin/actions/SkillListItem.js
ecellju/internship-portal
import React from 'react'; import { Label, Icon } from 'semantic-ui-react'; import PropTypes from 'prop-types'; const SkillListItem = props => ( <Label style={{ margin: 10 }}><Icon name="checkmark" /> {props.skill} </Label> ); export default SkillListItem; SkillListItem.propTypes = { skill: PropTypes.string.isRequired, };
js/jqwidgets/demos/react/app/splitter/loadingsplitpanelswithxhr/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxSplitter from '../../../jqwidgets-react/react_jqxsplitter.js'; class App extends React.Component { componentDidMount() { let loadPage = (url, tabIndex) => { let request = new XMLHttpRequest(); request.open('GET', url, false); request.setRequestHeader('Content-Type', 'text/json'); request.send(null); // Add 'setTimeout' to slow down the request otherwise cannot see 'ajax-loader.gif' setTimeout(() => { document.getElementById('content' + tabIndex).innerHTML = '<div style="overflow: auto; width: 100%; height: 100%;">' + request.response + '</div>'; }, (tabIndex * 400)); //document.getElementById('content' + tabIndex).innerHTML = '<div style="overflow: auto; width: 100%; height: 100%;">' + request.response + '</div>'; } loadPage('../app/splitter/loadingsplitpanelswithxhr/pages/ajax1.htm', 1); loadPage('../app/splitter/loadingsplitpanelswithxhr/pages/ajax2.htm', 2); } render() { return ( <JqxSplitter ref='mainSplitter' width={850} height={300} panels={[{ size: '50%' }, { size: '50%' }]} > <div id='content1'> <img src='../../images/ajax-loader.gif' /> </div> <div id='content2'> <img src='../../images/ajax-loader.gif' /> </div> </JqxSplitter> ) } } ReactDOM.render(<App />, document.getElementById('app'));