path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
demo/prism-async-light.js
conorhastings/react-syntax-highlighter
import React from 'react'; import { render } from 'react-dom'; import SyntaxHighlighter from '../src/prism-async-light'; import prismStyles from './styles/prism'; import ExamplesLinks from './examples-links'; import clike from '../src/languages/prism/clike'; import javascript from '../src/languages/prism/javascript'; import jsx from '../src/languages/prism/jsx'; import markup from '../src/languages/prism/markup'; import markupTemplating from '../src/languages/prism/markup-templating'; SyntaxHighlighter.registerLanguage('clike', clike); SyntaxHighlighter.registerLanguage('javascript', javascript); SyntaxHighlighter.registerLanguage('jsx', jsx); SyntaxHighlighter.registerLanguage('markup', markup); SyntaxHighlighter.registerLanguage('markup-templating', markupTemplating); const availableStyles = prismStyles; const availableLanguages = [ 'clike', 'javascript', 'jsx', 'markup', 'markup-templating' ]; class Component extends React.Component { constructor() { super(); const initialCodeString = `function createStyleObject(classNames, style) { return classNames.reduce((styleObject, className) => { return {...styleObject, ...style[className]}; }, {}); } function createClassNameString(classNames) { return classNames.join(' '); } // this comment is here to demonstrate an extremely long line length, well beyond what you should probably allow in your own code, though sometimes you'll be highlighting code you can't refactor, which is unfortunate but should be handled gracefully function createChildren(style, useInlineStyles) { let childrenCount = 0; return children => { childrenCount += 1; return children.map((child, i) => createElement({ node: child, style, useInlineStyles, key:\`code-segment-$\{childrenCount}-$\{i}\` })); } } function createElement({ node, style, useInlineStyles, key }) { const { properties, type, tagName, value } = node; if (type === "text") { return value; } else if (tagName) { const TagName = tagName; const childrenCreator = createChildren(style, useInlineStyles); const props = ( useInlineStyles ? { style: createStyleObject(properties.className, style) } : { className: createClassNameString(properties.className) } ); const children = childrenCreator(node.children); return <TagName key={key} {...props}>{children}</TagName>; } } `; this.state = { code: initialCodeString, showLineNumbers: false, wrapLongLines: false, style: 'atom-dark', styleSrc: require('../src/styles/prism/atom-dark').default, language: 'jsx', languageSrc: require(`../src/languages/prism/jsx`).default }; } render() { return ( <div className="demo__root demo__root--prism-async-light"> <header> <h1>React Syntax Highlighter Demo</h1> <ExamplesLinks /> </header> <main> <aside className="options__container"> <div className="options__option options__option--language"> <select className="select" value={this.state.language} onChange={e => this.setState({ languageSrc: require(`../src/languages/prism/${ e.target.value }`).default, language: e.target.value }) } > {availableLanguages.map(l => ( <option key={l} value={l}> {l} </option> ))} </select> </div> <div className="options__option options__option--theme"> <select className="select" value={this.state.selectedStyle} onChange={e => this.setState({ styleSrc: require(`../src/styles/prism/${e.target.value}`) .default, style: e.target.value }) } > {availableStyles.map(s => ( <option key={s} value={s}> {s} </option> ))} </select> </div> <div className="options__option options__option--line-numbers"> <label htmlFor="showLineNumbers" className="option__label"> <input type="checkbox" className="option__checkbox" checked={this.state.showLineNumbers} onChange={() => this.setState({ showLineNumbers: !this.state.showLineNumbers }) } id="showLineNumbers" /> <span className="label__text">Show line numbers</span> </label> </div> <div className="options__option options__option--wrap-long-lines"> <label htmlFor="wrapLongLines" className="option__label"> <input type="checkbox" className="option__checkbox" checked={this.state.wrapLongLines} onChange={() => this.setState({ wrapLongLines: !this.state.wrapLongLines }) } id="wrapLongLines" /> <span className="label__text">Wrap long lines</span> </label> </div> </aside> <article className="example__container"> <div className="textarea__wrapper"> <textarea style={{ flex: 1, marginTop: 11 }} rows={40} value={this.state.code} onChange={e => this.setState({ code: e.target.value })} /> </div> <SyntaxHighlighter style={this.state.styleSrc} showLineNumbers={this.state.showLineNumbers} wrapLines={true} wrapLongLines={this.state.wrapLongLines} lineProps={lineNumber => ({ style: { display: 'block', cursor: 'pointer' }, onClick() { alert(`Line Number Clicked: ${lineNumber}`); } })} language={this.state.language} > {this.state.code} </SyntaxHighlighter> </article> </main> </div> ); } } render(<Component />, document.getElementById('app'));
src/components/common/svg-icons/places/rv-hookup.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesRvHookup = (props) => ( <SvgIcon {...props}> <path d="M20 17v-6c0-1.1-.9-2-2-2H7V7l-3 3 3 3v-2h4v3H4v3c0 1.1.9 2 2 2h2c0 1.66 1.34 3 3 3s3-1.34 3-3h8v-2h-2zm-9 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm7-6h-4v-3h4v3zM17 2v2H9v2h8v2l3-3z"/> </SvgIcon> ); PlacesRvHookup = pure(PlacesRvHookup); PlacesRvHookup.displayName = 'PlacesRvHookup'; PlacesRvHookup.muiName = 'SvgIcon'; export default PlacesRvHookup;
src/components/App.js
HackArdennes2017/Project06
import React from 'react' import { Switch, Route } from 'react-router' import { Provider } from 'react-redux' import routes from 'routes' export default (store, Router, routerProps) => <Provider store={store}> <Router {...routerProps}> <Switch> {routes.map(route => <Route key={route.path} {...route} />)} </Switch> </Router> </Provider>
docs/src/CodeExample.js
JimiHFord/react-bootstrap
import React from 'react'; export default class CodeExample extends React.Component { render() { return ( <pre className="cm-s-solarized cm-s-light"> <code> {this.props.codeText} </code> </pre> ); } componentDidMount() { if (CodeMirror === undefined) { return; } CodeMirror.runMode( this.props.codeText, this.props.mode, React.findDOMNode(this).children[0] ); } }
examples/huge-apps/routes/Course/components/Dashboard.js
ryardley/react-router
import React from 'react'; class Dashboard extends React.Component { render () { return ( <div> <h3>Course Dashboard</h3> </div> ); } } export default Dashboard;
client/modules/core/components/.stories/new_poll_form.js
thancock20/voting-app
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import { withKnobs, text, boolean, number, object } from '@kadira/storybook-addon-knobs'; import { setComposerStub } from 'react-komposer'; import NewPollForm from '../new_poll_form.jsx'; storiesOf('core.NewPollForm', module) .addDecorator(withKnobs) .add('default view', () => { return ( <NewPollForm createPoll={action('createPoll')}/> ); });
src/svg-icons/editor/monetization-on.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorMonetizationOn = (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 2zm1.41 16.09V20h-2.67v-1.93c-1.71-.36-3.16-1.46-3.27-3.4h1.96c.1 1.05.82 1.87 2.65 1.87 1.96 0 2.4-.98 2.4-1.59 0-.83-.44-1.61-2.67-2.14-2.48-.6-4.18-1.62-4.18-3.67 0-1.72 1.39-2.84 3.11-3.21V4h2.67v1.95c1.86.45 2.79 1.86 2.85 3.39H14.3c-.05-1.11-.64-1.87-2.22-1.87-1.5 0-2.4.68-2.4 1.64 0 .84.65 1.39 2.67 1.91s4.18 1.39 4.18 3.91c-.01 1.83-1.38 2.83-3.12 3.16z"/> </SvgIcon> ); EditorMonetizationOn = pure(EditorMonetizationOn); EditorMonetizationOn.displayName = 'EditorMonetizationOn'; EditorMonetizationOn.muiName = 'SvgIcon'; export default EditorMonetizationOn;
client/modules/App/components/DevTools.js
GTDev87/stylizer
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w" > <LogMonitor /> </DockMonitor> );
src/components/internal/ConfirmationOverlay.js
GetAmbassador/react-ions
import React from 'react' import PropTypes from 'prop-types' import optclass from './OptClass' import Button from '../Button' import colors from '../internal/colors' const ConfirmationOverlay = ({ prompt, handleConfirmation }) => { const getTextStyle = () => { return { fontSize: '14px', fontWeight: '600', color: colors.primary4, margin: '0 0 24px', display: 'block' } } const getButtonWrapperStyle = () => { return { display: 'flex', justifyContent: 'flex-end', marginRight: '-12px' } } return ( <div> <span style={getTextStyle()}>{prompt || 'Are you sure?'}</span> <div style={getButtonWrapperStyle()}> <Button onClick={handleConfirmation.bind(this, false)} optClass='danger-alt'>Cancel</Button> <Button onClick={handleConfirmation.bind(this, true)}>Yes</Button> </div> </div> ) } ConfirmationOverlay.propTypes = { prompt: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), handleConfirmation: PropTypes.func.isRequired } export default ConfirmationOverlay
app/containers/AlgorithmContainer.js
omeryagmurlu/algoriv
import React, { Component } from 'react'; import _pickBy from 'lodash.pickby'; import _mapValues from 'lodash.mapvalues'; import { makeCancelable, cancelCatch, AlgorithmError } from 'app/utils'; import AnimatorContainer from 'app/containers/AnimatorContainer'; import LoadingView from 'app/views/LoadingView'; const snapshot = (payload, object) => { payload.push(JSON.parse(JSON.stringify(object))); // get rid of reference }; const snapProxy = (frames, fn) => (...params) => snapshot(frames, fn(...params)); // params passed to frame are passed to snap const filterObjectByKeys = (obj, arr) => _pickBy(obj, (v, k) => (typeof arr[k] !== 'undefined')); export const framer = (logic, snap) => (input) => { const frames = []; return Promise.resolve(logic(input, snapProxy(frames, snap))) .then((optEndInput) => { if (frames.length === 0) { throw AlgorithmError('Algorithm must frame at least once'); } return [frames, optEndInput]; }); }; const AlgorithmFactory = ({ logic: algLogic, input: algInput, initInputs: algInitInput, snap: algSnap, modules: algModules, modulesInputProps: algModulesInputProps, info: algInfo, }) => ((() => class AlgorithmPrototype extends Component { logic = (input) => framer(algLogic, algSnap)(input).then(([frames, optEndInput]) => { this.setState({ callback: () => { this.lastLogicEndInput = typeof optEndInput === 'object' ? optEndInput : {}; } }); return frames; }) constructor(props) { super(props); this.state = { input: { ...algInput }, // BUGFIX: multiple instances, deepCopy needed frames: null, callback: null, updating: true }; this.cancellables = []; this.lastLogicEndInput = {}; } componentDidMount() { this.cancellable(this.logic(algInput)) .then(frames => { this.setState({ frames, updating: false }); }).catch(cancelCatch); // .catch(err => { // throw new Error(`Algorithm can't init, ${err}`); // }); } componentWillUnmount() { this.lastLogicEndInput = {}; this.cancelRunning(); } cancellable = prom => { const cancellable = makeCancelable(prom); this.cancellables.push(cancellable); return cancellable.promise; } cancelRunning = () => { while (this.cancellables.length > 0) { this.cancellables.pop().cancel(); } } inputHandler(inputObj, cb) { const overridedNewInput = { ...inputObj, ...this.lastLogicEndInput }; this.lastLogicEndInput = {}; this.setState({ updating: true }); const currentNewInput = { ...this.state.input, ...overridedNewInput }; this.cancellable(this.logic( filterObjectByKeys(currentNewInput, algInput) )).then(frames => { this.setState(prev => { prev.input = { ...prev.input, ...overridedNewInput, }; prev.frames = frames; prev.updating = false; return prev; }, cb); }).catch(cancelCatch).catch(err => { throw new Error(`Input is faulty, ${err}`); }); } getInput = () => _mapValues(filterObjectByKeys(this.state.input, algInput), (v, k) => ({ value: v, update: (newInput, cb = () => {}) => this.inputHandler({ [k]: newInput }, cb) })) render() { const inputProps = algModulesInputProps(this.getInput()); return ( <LoadingView {...this.props} overlay={this.state.frames ? (<AnimatorContainer {...this.props} frames={this.state.frames} callback={this.state.callback} algorithmInfo={algInfo} algorithmStatic={_mapValues((typeof algModules === 'function' ? algModules(this.props.app.settings) : algModules), (v, k) => ({ ...v, input: inputProps[k] }))} algorithmInitInput={algInitInput(this.getInput())} />) : null} disabled={!this.state.updating} message={!this.state.frames ? 'Loading Algorithm' : 'Evaluating'} tooLongTime={3000} tooLongMessage="Algorithm logic is taking too long to compute" tooLongEscape={() => { this.cancelRunning(); if (!this.state.frames) { return this.props.app.goBack(); } return this.setState({ updating: false }); }} /> ); } })({})); export default AlgorithmFactory;
new-lamassu-admin/src/components/tables/Stripes.js
naconner/lamassu-server
import React from 'react' import { Td } from 'src/components/fake-table/Table' import { ReactComponent as StripesSvg } from 'src/styling/icons/stripes.svg' const Stripes = ({ width }) => ( <Td width={width}> <StripesSvg /> </Td> ) export default Stripes
test/integration/jsconfig-paths/pages/resolve-order.js
flybayer/next.js
import React from 'react' import api from '@lib/api' export default function ResolveOrder() { return <div>{api()}</div> }
docs/src/app/components/pages/components/TextField/ExampleCustomize.js
kittyjumbalaya/material-components-web
import React from 'react'; import TextField from 'material-ui/TextField'; import {orange500, blue500} from 'material-ui/styles/colors'; const styles = { errorStyle: { color: orange500, }, underlineStyle: { borderColor: orange500, }, floatingLabelStyle: { color: orange500, }, floatingLabelFocusStyle: { color: blue500, }, }; const TextFieldExampleCustomize = () => ( <div> <TextField hintText="Styled Hint Text" hintStyle={styles.errorStyle} /><br /> <TextField hintText="Custom error color" errorText="This field is required." errorStyle={styles.errorStyle} /><br /> <TextField hintText="Custom Underline Color" underlineStyle={styles.underlineStyle} /><br /> <TextField hintText="Custom Underline Focus Color" underlineFocusStyle={styles.underlineStyle} /><br /> <TextField floatingLabelText="Styled Floating Label Text" floatingLabelStyle={styles.floatingLabelStyle} floatingLabelFocusStyle={styles.floatingLabelFocusStyle} /> </div> ); export default TextFieldExampleCustomize;
test/js/AR/onPinchRotateTest.js
viromedia/viro
/** * Copyright (c) 2017-present, Viro Media, 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, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import { ViroScene, ViroARScene, ViroARPlane, ViroARPlaneSelector, ViroBox, ViroMaterials, ViroNode, ViroOrbitCamera, ViroImage, ViroVideo, ViroSkyBox, Viro360Video, ViroText, ViroQuad } from 'react-viro'; import TimerMixin from 'react-timer-mixin'; var createReactClass = require('create-react-class'); var testARScene = createReactClass({ mixins: [TimerMixin], getInitialState: function() { return { surfaceSize : [0,0,0], center : [0,0,0], rotation : [0,0,0], scale : [1,1,1], } }, render: function() { return ( <ViroARScene ref="arscene" > <ViroARPlane onAnchorUpdated={this._onPlaneUpdate}> <ViroQuad materials={"transparent"} scale={this.state.surfaceSize} position={this.state.center} rotation={[-90, 0, 0]} onClick={this._onSurfaceClickUsingPosition}/> </ViroARPlane> {this._getBox()} </ViroARScene> ); }, _getBox() { if (this.state.boxLocation != undefined) { return ( <ViroNode ref={(component)=>{this.boxRef = component}} position={this.state.boxLocation} onDrag={()=>{}} scale={this.state.scale} rotation={this.state.rotation} dragType={"FixedToWorld"} > <ViroBox position={[0,.075,0]} scale={[.15, .15,.15]} onPinch={this._onPinch} onRotate={this._onRotate}/> </ViroNode> ) } }, _onPlaneUpdate(updateDict) { this.setState({ surfaceSize : [updateDict.width, updateDict.height, 1], center : updateDict.center, }) }, _onSurfaceClickCameraForward() { this.refs["arscene"].getCameraOrientationAsync().then((orientation) => { this.refs["arscene"].performARHitTestWithRay(orientation.forward).then((results)=>{ if (results.length > 0) { for (var i = 0; i < results.length; i++) { let result = results[i]; if (result.type == "ExistingPlaneUsingExtent") { this.setState({ boxLocation : result.transform.position }); return; } } } }) }); }, _onSurfaceClickUsingPosition(position) { console.log(position); this.refs["arscene"].performARHitTestWithPosition(position).then((results)=>{ if (results.length > 0) { for (var i = 0; i < results.length; i++) { let result = results[i]; if (result.type == "ExistingPlaneUsingExtent") { this.setState({ boxLocation : result.transform.position }); return; } } } }) }, _onRotate(rotateState, rotationFactor, source) { if (rotateState == 3) { this.setState({ rotation : [this.state.rotation[0], this.state.rotation[1] - rotationFactor, this.state.rotation[2]] }); return; } this.boxRef.setNativeProps({rotation:[this.state.rotation[0], this.state.rotation[1] - rotationFactor, this.state.rotation[2]]}); }, /* Pinch scaling should be relative to its last value *not* the absolute value of the scale factor. So while the pinching is ongoing set scale through setNativeProps and multiply the state by that factor. At the end of a pinch event, set the state to the final value and store it in state. */ _onPinch(pinchState, scaleFactor, source) { var newScale = this.state.scale.map((x)=>{return x * scaleFactor}) if (pinchState == 3) { this.setState({ scale : newScale }); return; } this.boxRef.setNativeProps({scale:newScale}); }, }); ViroMaterials.createMaterials({ transparent: { shininess: 2.0, lightingModel: "Constant", diffuseColor: "#0000cc55" }, }); module.exports = testARScene;
frontend/src/Components/NotFound.js
geogolem/Radarr
import PropTypes from 'prop-types'; import React from 'react'; import PageContent from 'Components/Page/PageContent'; import translate from 'Utilities/String/translate'; import styles from './NotFound.css'; function NotFound({ message }) { return ( <PageContent title={translate('MIA')}> <div className={styles.container}> <div className={styles.message}> {message} </div> <img className={styles.image} src={`${window.Radarr.urlBase}/Content/Images/404.png`} /> </div> </PageContent> ); } NotFound.propTypes = { message: PropTypes.string.isRequired }; NotFound.defaultProps = { message: 'You must be lost, nothing to see here.' }; export default NotFound;
src/SideBar/__tests__/SideBar.js
Detaysoft/react-chat-elements
import React, { Component } from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import SideBar from '../SideBar'; describe('SideBar component', () => { it('should render without issues', () => { const component = shallow(<SideBar />); expect(component.length).toBe(1); expect(toJson(component)).toMatchSnapshot(); }); });
node_modules/react-router/es/IndexRoute.js
soniacq/LearningReact
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils'; import { component, components, falsy } from './InternalPropTypes'; var func = React.PropTypes.func; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ /* eslint-disable react/require-render-return */ var IndexRoute = React.createClass({ displayName: 'IndexRoute', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = _createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0; } } }, propTypes: { path: falsy, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRoute;
frontend/test/app/components/NewsletterFooter-test.js
mathjazz/testpilot
import React from 'react'; import { expect } from 'chai'; import sinon from 'sinon'; import { shallow } from 'enzyme'; import NewsletterFooter from '../../../src/app/components/NewsletterFooter'; describe('app/components/NewsletterFooter', () => { const _subject = (form) => { const props = { newsletterForm: { subscribe: sinon.spy(), setEmail: sinon.spy(), setPrivacy: sinon.spy(), ...form } }; return shallow(<NewsletterFooter {...props} />); }; describe('error notification', () => { it('should not show when failed=false', () => { const subject = _subject({ failed: false }); expect(subject.find('.error')).to.have.length(0); }); it('should show when failed=true', () => { const subject = _subject({ failed: true }); expect(subject.find('.error')).to.have.length(1); }); }); describe('header', () => { it('should render when succeeded=false', () => { const subject = _subject({ succeeded: false }).find('header'); expect(subject.hasClass('success-header')).to.equal(false); }); it('should be replaced with a success message when succeeded=true', () => { const subject = _subject({ succeeded: true }).find('header'); expect(subject.hasClass('success-header')).to.equal(true); }); }); it('should not have the `correct` class by default', () => { const subject = _subject({ succeeded: false }); expect(subject.hasClass('success')).to.equal(false); }); it('should have `correct` class when succeeded=true', () => { const subject = _subject({ succeeded: true }); expect(subject.hasClass('success')).to.equal(true); }); it('should pass props to the child NewsletterForm', () => { const subject = _subject({ foo: 'bar' }); expect(subject.find('NewsletterForm').prop('foo')).to.equal('bar'); }); });
src/routes/Counter/components/Counter.js
Dylan1312/pool-elo
import React from 'react' import Match from './Match' class Counter extends React.Component { constructor(props) { super(props); this.state = { playerOne: "", playerTwo: "", result: "" } this.baseState = this.state } resetState(){ this.state = this.baseState } render() { let self = this; let props = this.props function submitMatch() { if(self.state.playerOne != "" && self.state.playerTwo != "" && self.state.result != "" && self.state.playerOne != self.state.playerTwo) { props.submitMatch( self.state.playerOne, self.state.playerTwo, self.state.result ) self.resetState() } } function handleChange(event) { self.setState({ [event.target.name]: event.target.value }); } return ( <div style={{margin: '0 auto'}}> <h2>Add a match</h2> <div className='form form-inline'> <div className='form-group'> <label >Player One</label> <select name="playerOne" className='form-control' onChange={handleChange} value={this.state.playerOne}> <option value="">Choose</option> {props.players.filter((player) => player.name != this.state.playerTwo).map( player => <option key={player.name} value={player.name}>{player.name}</option> )} </select> </div> <div className='form-group'> <label>Player Two</label> <select name="playerTwo" className='form-control' onChange={handleChange} value={this.state.playerTwo}> <option value="">Choose</option> {props.players.filter((player) => player.name != this.state.playerOne).map( player => <option key={player.name} value={player.name}>{player.name}</option> )} </select> </div> <div className='form-group'> <label>Winner</label> <select name="result" className='form-control'onChange={handleChange} value={this.state.result}> <option value=""></option> <option value={self.state.playerOne}>{self.state.playerOne}</option> <option value={self.state.playerTwo}>{self.state.playerTwo}</option> </select> <button className='btn btn-default' onClick={submitMatch}>Submit </button> </div> </div> <h2>The League</h2> <table className='table table-striped table-bordered'> <tbody> {props.players.sort(function(a, b) { return b.elo - a.elo; }).filter( function(player){ return props.matches.map(function(match){ return match.playerOne}).includes(player.name) || props.matches.map(function(match){ return match.playerTwo}).includes(player.name) } ).map( (player, index) => <tr key={index}><th>{index+1}</th><td>{player.name}</td><td>{player.elo}</td></tr> )} </tbody> </table> <h2>Past Matches</h2> <ul style={{listStyle: "none"}}> {props.matches.map( (match) => <Match match={match}></Match> )} </ul> </div> ) } } Counter.propTypes = { submitMatch: React.PropTypes.func.isRequired, players: React.PropTypes.array, match: React.PropTypes.object } export default Counter
src/app/components/public/Details.js
cherishstand/OA-react
import React, { Component } from 'react'; import Header from './Header'; // require('es6-promise').polyfill(); import {Link} from 'react-router' import Subheader from 'material-ui/Subheader'; import AppBar from 'material-ui/AppBar'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import ArrowBaclIcon from 'material-ui/svg-icons/navigation/arrow-back'; import Template from './template'; import IconButton from 'material-ui/IconButton'; import ChevronRight from 'material-ui/svg-icons/navigation/chevron-right'; import ExitToApp from 'material-ui/svg-icons/action/exit-to-app'; import { BASIC_URL } from '../../constants/Config'; import Picklist from './Picklist'; import DatePick from './DatePick'; import Alert from './Alert'; import Loading from './Loading'; const styles = { sub: { lineHeight: '30px', paddingLeft: 0 }, head: { textAlign: 'center', height: 45, lineHeight: '45px', backgroundColor:'rgb(255, 255, 255)' }, title:{ height: 45, lineHeight: '45px', overflow: 'initial', color: 'rgb(33, 33, 33)', fontSize: 18 }, edit: { height: 45, lineHeight: '45px', color: 'rgb(94, 149, 201)', width: 48, fontSize: 14 }, disable: { color: 'rgba(0, 0, 0, 0.5)' }, chevron: { margin: '10px 0', width: 20, height: 20 } } class Head extends Component { constructor(props, context){ super(props, context) } render() { return( <AppBar style={styles.head} titleStyle={styles.title} title='客户详情' iconStyleRight={{marginTop: 0}} iconStyleLeft={{marginTop: 0, marginRight: 0}} iconElementLeft={this.context.disable ? <div onTouchTap={this.props.handleCancel} style={styles.edit}>取消</div> : <IconButton onTouchTap={this.context.router.goBack}><ArrowBaclIcon color="#5e95c9"/></IconButton> } iconElementRight={this.context.disable ? <div onTouchTap={this.props.handleSave} style={styles.edit}>保存</div> : <IconButton onTouchTap={this.props.toogleEdit}><ExitToApp color="#5e95c9"/></IconButton> } /> ) } } Head.contextTypes = { disable: React.PropTypes.bool.isRequired, router: React.PropTypes.object, handleSave: React.PropTypes.any } const changeTopic = {}; class Details extends Component { constructor(props, context){ super(props, context); this.props.fetchPost(this.props.location.query.url, this.props.params.id, this.props.location.query.mode) this.state = { data: {}, disable: false, typeList: {}, open: false, } this.handleChange = (event, idx, v) => { const name = event.target.name; const value = event.target.value; changeTopic[name] = value; this.setState({data: Object.assign({}, this.state.data, changeTopic)}) } this.toogleEdit = () => { this.setState({disable: !this.state.disable}) } this.handleSave = () => { this.setState({open: true}) } this.handleCancel = () => { this.setState({open: true}) } this.handleClose = () => { this.setState({open: false}) } this.handleSubmit = (event) => { event.preventDefault(); let form = document.querySelector('form') let path = this.props.location.pathname fetch(`${BASIC_URL}${path}`, { method: 'PUT', body: new FormData(form) }) this.setState({open: false,disable: false}) } } componentWillUpdate(){ return false } componentWillReceiveProps(nextProps){ this.state.data = nextProps.state.data.topic; this.state.typeList = nextProps.state.data.replies; } getChildContext() { return { disable: this.state.disable, handleSave: this.handleSave } } render() { let layout = []; const {data, typeList, disable, open} = this.state; for(let key in typeList){ if(key !== 'pick_list'){ layout.push ( <div key={key}> <Subheader style={styles.sub}>{typeList[key].blocklabel}</Subheader> <div className='basic-msg'> {typeList[key].fields&&typeList[key].fields.map((field, index) => { if(field.uitype === '15'){ return <div key={index} className='list-item'> <label>{field.fieldlabel}:</label> { disable ? <div> {data.pick_list.hasOwnProperty(field.fieldname) ? <Picklist list={data.pick_list[field.fieldname]} {...field} value={data[field.fieldname]}/> : <span name={field.fieldname} data-type={field.fieldtype}></span>} {<ChevronRight color='#6d6c6c' style={styles.chevron}/>} </div> : <span>{data[field.fieldname]}</span> } </div> } else if(field.uitype === '51'){ return <div key={index} className='list-item'> <label>{field.fieldlabel}:</label> <span>{data[field.fieldname]}{disable ? <ChevronRight color='#6d6c6c' style={styles.chevron}/> : null}</span> </div> } else if (field.uitype === '5'){ return <div key={index} className='list-item'> <label>{field.fieldlabel}:</label> <div> <DatePick date={data.hasOwnProperty(field.fieldname) ? new Date(data[field.fieldname]) : null} name={field.fieldname} /> {disable ? <ChevronRight color='#6d6c6c' style={{width: 20, height: 20}}/> : null} </div> </div> } else if(field.uitype === '19' || field.uitype === '21'){ return <div key={index} className='list-item'> <label>{field.fieldlabel}:</label> <textarea rows={5} value={data.hasOwnProperty(field.fieldname) ? data[field.fieldname] : ' '} onChange={this.handleChange} name={field.fieldname} data-type={field.fieldtype} /> </div> } else { return <div key={index} className='list-item'> <label>{field.fieldlabel}:</label> <input type='text' value={data.hasOwnProperty(field.fieldname) ? data[field.fieldname] : ' '} onChange={this.handleChange} name={field.fieldname} data-type={field.fieldtype} disabled={disable ? false : 'disabled'} /> </div> } })} </div> </div> ) } } return ( <div> <div className="fiexded"> <Head toogleEdit={this.toogleEdit} handleSave={this.handleSave} handleCancel={this.handleCancel}/> </div> { this.props.state.isFetching ? <Loading /> : <div style={{padding: '45px 6px 0 6px'}} > <form onSubmit={this.handleSubmit}> {layout} </form> </div> } <Alert open={open} handleClose={this.handleClose} handleSave={this.handleSave} onSubmit={this.handleSubmit} toogleEdit={this.toogleEdit}/> </div> ) } } Details.childContextTypes = { disable: React.PropTypes.bool.isRequired, handleSave: React.PropTypes.any } export default Template({ component: Details, })
src/components/PendingChallengeDetail.js
jrzimmerman/bestrida-rn
import React from 'react'; import { Dimensions, View, StatusBar, Text, TouchableOpacity } from 'react-native'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import SegmentMap from './SegmentMap'; import styles from '../styles/styles'; import pendingStyles from '../styles/pendingStyles'; import * as challengeActions from '../actions/challenges'; import * as segmentActions from '../actions/segments'; export class PendingChallengeDetail extends React.Component { constructor(props) { super(props); this.handleAccept = this.handleAccept.bind(this); this.handleDecline = this.handleDecline.bind(this); } componentDidMount() { const { dispatch } = this.props; const { challenge } = this.props.navigation.state.params; dispatch(segmentActions.getSegment(challenge.segment.id)); } componentWillUnmount() { this.props.dispatch(segmentActions.clearSegment()); } handleAccept(challengeId, userId) { const { dispatch, navigation } = this.props; dispatch(challengeActions.acceptChallenge(challengeId, userId)); dispatch(challengeActions.pendingChallenges(userId)); navigation.goBack(); } handleDecline(challengeId, userId) { const { dispatch, navigation } = this.props; dispatch(challengeActions.declineChallenge(challengeId, userId)); dispatch(challengeActions.pendingChallenges(userId)); navigation.goBack(); } render() { const { segments } = this.props; const { challenge, userId } = this.props.navigation.state.params; const { height, width } = Dimensions.get('window'); let segmentMap; if (segments && segments.segment && segments.segment.map) { segmentMap = ( <View style={styles.challengeMapView}> <SegmentMap height={height * 0.275} width={width * 0.9} map={segments.segment.map} /> </View> ); } let challengeFooter; if (userId && challenge.challengee.id === userId) { challengeFooter = ( <View style={pendingStyles.challengeOptions}> <TouchableOpacity onPress={() => this.handleDecline(challenge.id, userId)} style={pendingStyles.challengeOptionsDecline} > <Text style={pendingStyles.challengeOptionsDeclineText}> Decline </Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.handleAccept(challenge.id, userId)} style={pendingStyles.challengeOptionsAccept} > <Text style={pendingStyles.challengeOptionsAcceptText}>Accept</Text> </TouchableOpacity> </View> ); } else if (userId && challenge.challenger.id === userId) { challengeFooter = ( <TouchableOpacity onPress={() => this.handleDecline(challenge.id, userId)} style={styles.button} > <Text style={styles.buttonText}>Cancel Challenge</Text> </TouchableOpacity> ); } return ( <View style={styles.container}> <StatusBar barStyle="light-content" /> <View style={styles.challengeTitleView}> <Text style={styles.challengeTitleText}> {challenge.segment.name} </Text> </View> <View style={styles.challengeDetailView}> <View style={styles.detailRowView}> <Text style={styles.challengeDetailTitle}>Start Date</Text> <Text style={styles.challengeDetailText}> {new Date(challenge.created).toDateString()} </Text> </View> <View style={styles.detailRowView}> <Text style={styles.challengeDetailTitle}>End Date</Text> <Text style={styles.challengeDetailText}> {new Date(challenge.expires).toDateString()} </Text> </View> <View style={styles.detailRowView}> <Text style={styles.challengeDetailTitle}>Distance</Text> <Text style={styles.challengeDetailText}> {`${(challenge.segment.distance / 1609.34).toFixed(2)} Miles` || '0'} </Text> </View> <View style={styles.detailRowView}> <Text style={styles.challengeDetailTitle}>Location</Text> <Text style={styles.challengeDetailText}> {`${challenge.segment.city ? `${challenge.segment.city},` : ''} ${challenge.segment.state}`} </Text> </View> <View style={styles.detailRowView}> <Text style={styles.challengeDetailTitle}>Activity Type</Text> <Text style={styles.challengeDetailText}> {challenge.segment.activityType || 'Not Available'} </Text> </View> <View style={styles.detailRowView}> <Text style={styles.challengeDetailTitle}>Average Grade</Text> <Text style={styles.challengeDetailText}>{`${challenge.segment .averageGrade} %`}</Text> </View> <View style={styles.detailRowView}> <Text style={styles.challengeDetailTitle}>Climb Category</Text> <Text style={styles.challengeDetailText}> {challenge.segment.climbCategory || 'Not Available'} </Text> </View> <View style={styles.detailRowView}> <Text style={styles.challengeDetailTitle}>Elevation Gain</Text> <Text style={styles.challengeDetailText}> {`${challenge.segment.totalElevationGain} meters`} </Text> </View> </View> {segmentMap} <View style={styles.challengeFooterView}>{challengeFooter}</View> </View> ); } } const { func, number, shape } = PropTypes; PendingChallengeDetail.propTypes = { dispatch: func, challenge: shape({}), userId: number, navigation: shape({}), segments: shape({}) }; const mapStateToProps = state => ({ userId: state.user.auth.userId, segments: state.segments }); export default connect(mapStateToProps)(PendingChallengeDetail);
examples/styled-components/src/containers/Home.js
calvinrbnspiess/react-static
import React from 'react' import { getSiteProps } from 'react-static' // import logoImg from '../logo.png' export default getSiteProps(() => ( <div> <h1 style={{ textAlign: 'center' }}>Welcome to</h1> <img src={logoImg} alt="" /> </div> ))
app/containers/NotFoundPage/index.js
thuy616/react-d3-charts
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
packages/core/admin/admin/src/pages/AuthPage/components/Oops/index.js
wistityhq/strapi
import React from 'react'; import { useIntl } from 'react-intl'; import { useQuery } from '@strapi/helper-plugin'; import { Box } from '@strapi/design-system/Box'; import { Main } from '@strapi/design-system/Main'; import { Flex } from '@strapi/design-system/Flex'; import { Link } from '@strapi/design-system/Link'; import { Typography } from '@strapi/design-system/Typography'; import UnauthenticatedLayout, { Column, LayoutContent, } from '../../../../layouts/UnauthenticatedLayout'; import Logo from '../../../../components/UnauthenticatedLogo'; const Oops = () => { const { formatMessage } = useIntl(); const query = useQuery(); const message = query.get('info') || formatMessage({ id: 'Auth.components.Oops.text', defaultMessage: 'Your account has been suspended.', }); return ( <UnauthenticatedLayout> <Main> <LayoutContent> <Column> <Logo /> <Box paddingTop={6} paddingBottom={7}> <Typography as="h1" variant="alpha"> {formatMessage({ id: 'Auth.components.Oops.title', defaultMessage: 'Oops...' })} </Typography> </Box> <Typography>{message}</Typography> <Box paddingTop={4}> <Typography> {formatMessage({ id: 'Auth.components.Oops.text.admin', defaultMessage: 'If this is a mistake, please contact your administrator.', })} </Typography> </Box> </Column> </LayoutContent> <Flex justifyContent="center"> <Box paddingTop={4}> <Link to="/auth/login"> {formatMessage({ id: 'Auth.link.signin', defaultMessage: 'Sign in' })} </Link> </Box> </Flex> </Main> </UnauthenticatedLayout> ); }; export default Oops;
client/modules/Search/components/SearchForm/SearchForm.js
XuHaoJun/tiamat
import React from 'react'; class SearchForm extends React.Component { render() { return 'test'; } } export default SearchForm;
src/js/components/Retail/Login/partial/LoginFormOTP.js
ajainsyn/project
import React from 'react'; import { Link } from 'react-router-dom'; const LoginFormOTP = ({...props}) => { return ( <div className="retail-login"> <div className="retail-login-header"> <h3> Enter your One Time Password (OTP) <span className="info-otp">Please check your registred mobile number 85xxxxxx25 for OTP</span> </h3> </div> <form className="form-default"> <div className="form-box"> <label htmlFor="otp" className="form-label">One Time Passowrd (OTP)</label> <input id="otp" name="otp" className="form-input" type="text" /> </div> <div className="buttons"> <button className="btn btn-primary" onClick={props.backToLogin} >Back to login</button> <Link to="/my-account" className="btn btn-default">Login to SYN Bank</Link> </div> </form> </div> )}; export default LoginFormOTP;
src/parser/monk/brewmaster/CHANGELOG.js
sMteX/WoWAnalyzer
import React from 'react'; import { emallson, Zerotorescue } from 'CONTRIBUTORS'; import ITEMS from 'common/ITEMS'; import ItemLink from 'common/ItemLink'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; export default [ { date: new Date('2019-04-11'), changes: <>Fixed a bug in the Mitigation Values tab that caused Mastery's base 8% to be counted towards contribution by Mastery Rating.</>, contributors: [emallson], }, { date: new Date('2019-03-10'), changes: <>Fixed a bug in the <SpellLink id={SPELLS.IRONSKIN_BREW.id} /> normalizer that led to a crash in the new timeline.</>, contributors: [Zerotorescue], }, { date: new Date('2019-02-16'), changes: <>Removed <SpellLink id={SPELLS.BREATH_OF_FIRE.id} /> from the checklist.</>, contributors: [emallson], }, { date: new Date('2019-01-31'), changes: <>Added Mitigation Values tab showing estimated stat values for damage mitigation.</>, contributors: [emallson], }, { date: new Date('2018-12-30'), changes: <>Added <SpellLink id={SPELLS.STRAIGHT_NO_CHASER.id} /> module.</>, contributors: [emallson], }, { date: new Date('2018-12-29'), changes: <>Added <SpellLink id={SPELLS.GIFT_OF_THE_OX_1.id} /> healing statistic.</>, contributors: [emallson], }, { date: new Date('2018-10-26'), changes: <>Added <SpellLink id={SPELLS.CELESTIAL_FORTUNE_HEAL.id} /> healing statistic and table.</>, contributors: [emallson], }, { date: new Date('2018-10-22'), changes: <>The <SpellLink id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} /> module now loads on-demand, improving load times for lower-end devices.</>, contributors: [emallson], }, { date: new Date('2018-10-15'), changes: <>Added <SpellLink id={SPELLS.PURIFYING_BREW.id} /> checklist item.</>, contributors: [emallson], }, { date: new Date('2018-10-02'), changes: <>Re-enabled the <SpellLink id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} /> module and added additional distribution information to it.</>, contributors: [emallson], }, { date: new Date('2018-09-27'), changes: 'Updated Stagger plot to show very quick purifies more accurately.', contributors: [emallson], }, { date: new Date('2018-09-22'), changes: <>Updated <SpellLink id={SPELLS.IRONSKIN_BREW.id} /> and <SpellLink id={SPELLS.BREATH_OF_FIRE.id} /> suggestions to use hits mitigated instead of uptime.</>, contributors: [emallson], }, { date: new Date('2018-09-22'), changes: <>Added support for <SpellLink id={SPELLS.FIT_TO_BURST.id} />.</>, contributors: [emallson], }, { date: new Date('2018-09-13'), changes: <>Added support for <SpellLink id={SPELLS.ELUSIVE_FOOTWORK.id} />.</>, contributors: [emallson], }, { date: new Date('2018-08-11'), changes: <>Added support for <SpellLink id={SPELLS.STAGGERING_STRIKES.id} />.</>, contributors: [emallson], }, { date: new Date('2018-07-22'), changes: <>Updated support for <ItemLink id={ITEMS.SOUL_OF_THE_GRANDMASTER.id} /> and temporarily disabled the <SpellLink id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} /> module pending new formula coefficients.</>, contributors: [emallson], }, { date: new Date('2018-07-18'), changes: <>Added support for <SpellLink id={SPELLS.LIGHT_BREWING_TALENT.id} />.</>, contributors: [emallson], }, { date: new Date('2018-07-15'), changes: <>Added <SpellLink id={SPELLS.TRAINING_OF_NIUZAO.id} /> support.</>, contributors: [emallson], }, { date: new Date('2018-06-16'), changes: <>Updated <SpellLink id={SPELLS.IRONSKIN_BREW.id} /> cooldown and duration and added <SpellLink id={SPELLS.GUARD_TALENT.id} />, along with other changes in beta build 26812.</>, contributors: [emallson], }, ];
app/containers/ThemeProvider/index.js
juanda99/arasaac-frontend
/* * * ThemeProvider * * this component connects the redux state theme to the * */ import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import { makeSelectDirection } from 'containers/LanguageProvider/selectors'; import customTheme from './customTheme' export class ThemeProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { const theme = customTheme(this.props.theme, this.props.direction) return ( <MuiThemeProvider muiTheme={theme}> {React.Children.only(this.props.children)} </MuiThemeProvider> ) } } ThemeProvider.propTypes = { theme: PropTypes.string, children: PropTypes.element.isRequired, direction: PropTypes.string.isRequired, } const mapStateToProps = (state) => { const theme = state.get('theme') const direction = makeSelectDirection()(state) return ({ theme, direction }) } function mapDispatchToProps(dispatch) { return { dispatch } } export default connect(mapStateToProps, mapDispatchToProps)(ThemeProvider)
src/components/Link/Link.js
AaronHartigan/DudeTruck
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import history from '../../history'; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } class Link extends React.Component { static propTypes = { to: PropTypes.string.isRequired, children: PropTypes.node.isRequired, onClick: PropTypes.func, }; static defaultProps = { onClick: null, }; handleClick = event => { if (this.props.onClick) { this.props.onClick(event); } if (isModifiedEvent(event) || !isLeftClickEvent(event)) { return; } if (event.defaultPrevented === true) { return; } event.preventDefault(); history.push(this.props.to); }; render() { const { to, children, ...props } = this.props; return ( <a href={to} {...props} onClick={this.handleClick}> {children} </a> ); } } export default Link; export { Link as LinkTest };
src/components/Navigation/SideNavbar.js
strongharris/Dashboard
import React from 'react'; import { Link } from 'react-router-dom'; const SideNavbar = () => { return ( <div id="menubar" className="menubar-inverse "> <div className="menubar-fixed-panel"> <div> <a className="btn btn-icon-toggle btn-default menubar-toggle" data-toggle="menubar" href="javascript:void(0);"> <i className="fa fa-bars"></i> </a> </div> <div className="expanded"> <a href="/"> <span className="text-lg text-bold text-primary ">MATERIAL&nbsp;ADMIN</span> </a> </div> </div> <div className="menubar-scroll-panel"> <ul id="main-menu" className="gui-controls"> <li> <a href="/" className="active"> <div className="gui-icon"><i className="md md-home"></i></div> <span className="title">Home</span> </a> </li> <li> <a href="#/management/survey" > <div className="gui-icon"><i className="md md-web"></i></div> <span className="title">Survey</span> </a> </li> <li> <a href="javascript:void(0)" > <div className="gui-icon"><i className="md md-account-child"></i></div> <span className="title">Account</span> </a> </li> <li className="gui-folder"> <a> <div className="gui-icon"><i className="md md-insert-chart"></i></div> <span className="title">Analytic</span> </a> <ul> <li><a href="#/analytic/background"><span className="title">Community Field Study</span></a></li> </ul> </li> <li className="gui-folder"> <a> <div className="gui-icon"><i className="fa fa-folder-open fa-fw"></i></div> <span className="title">Data</span> </a> <ul> <li><a href="#/data/background"><span className="title">Community Field Study</span></a></li> </ul> </li> </ul> <div className="menubar-foot-panel"> <small className="no-linebreak hidden-folded"> <span className="opacity-75">Copyright &copy; SZC</span> <strong>Impact Learning</strong> </small> </div> </div> </div> ); } export default SideNavbar;
src/fit-items-popover/index.js
SodhanaLibrary/react-examples
import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import App from './app'; render( <AppContainer><App/></AppContainer>, document.querySelector("#app")); if (module.hot) { module.hot.accept('./app.js', () => { const App = require('./app.js').default; render( <AppContainer> <App/> </AppContainer>, document.querySelector("#app") ); }); }
src/components/Popup/Popup.js
Barylskyigb/simple-debts-react-native
import React from 'react'; import { View, KeyboardAvoidingView, Platform, Text, ViewPropTypes } from 'react-native'; import PropTypes from 'prop-types'; import Modal from 'react-native-modal'; import styles from './Popup.styles'; import KeyboardDismissingView from '../KeyboardDismissingView/KeyboardDismissingView'; import ButtonDeprecated from '../Button/ButtonDeprecated'; const Popup = ({ onBackdropPress, style, containerStyle, children, title, noMargin, cancelBtnProps, confirmBtnProps, ...rest }) => ( <Modal onBackdropPress={onBackdropPress} onBackButtonPress={onBackdropPress} backdropOpacity={0.5} animationIn="fadeIn" animationOut="fadeOut" avoidKeyboard style={noMargin && { margin: 0 }} useNativeDriver hideModalContentWhileAnimating {...rest} > <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={-50} style={[styles.container, containerStyle]} > <KeyboardDismissingView style={styles.popup}> {title && <Text style={styles.title}>{title}</Text>} {title && <View style={styles.divider} />} <View style={[styles.body, style]}>{children}</View> {(cancelBtnProps || confirmBtnProps) && ( <View style={styles.btnsContainer}> {cancelBtnProps && ( <ButtonDeprecated title="CANCEL" {...cancelBtnProps} style={[styles.btn, cancelBtnProps.style]} textStyle={styles.btnText} /> )} {confirmBtnProps && ( <ButtonDeprecated title="OK" {...confirmBtnProps} style={[styles.btn, confirmBtnProps.style]} textStyle={styles.btnText} /> )} </View> )} </KeyboardDismissingView> </KeyboardAvoidingView> </Modal> ); Popup.propTypes = { onBackdropPress: PropTypes.func.isRequired, style: ViewPropTypes.style, containerStyle: ViewPropTypes.style, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node ]).isRequired, title: PropTypes.string, noMargin: PropTypes.bool, cancelBtnProps: PropTypes.object, confirmBtnProps: PropTypes.object }; Popup.defaultProps = { style: null, title: null, noMargin: false, cancelBtnProps: null, confirmBtnProps: null }; export default Popup;
src/botPage/view/react-components/HeaderWidgets.js
binary-com/binary-bot
import React from 'react'; const ServerTime = ({ api }) => { const [hasApiResponse, setHasApiResponse] = React.useState(false); const [date, setDate] = React.useState(); const [dateString, setDateString] = React.useState(); const updateTime = () => { if (!date) return; date.setSeconds(date.getSeconds() + 1); const year = date.getUTCFullYear(); const month = `0${date.getMonth() + 1}`.slice(-2); const day = `0${date.getUTCDate()}`.slice(-2); const hours = `0${date.getUTCHours()}`.slice(-2); const minutes = `0${date.getUTCMinutes()}`.slice(-2); const seconds = `0${date.getUTCSeconds()}`.slice(-2); setDateString(`${year}-${month}-${day} ${hours}:${minutes}:${seconds} GMT`); }; const getServerTime = () => { api.send({ time: 1 }).then(response => { const newDate = new Date(response.time * 1000); setDate(newDate); setHasApiResponse(true); }); }; React.useEffect(() => { getServerTime(); const updateTimeInterval = setInterval(updateTime, 1000); const serverTimeInterval = setInterval(getServerTime, 30000); return () => { clearInterval(updateTimeInterval); clearInterval(serverTimeInterval); }; }, [hasApiResponse]); React.useEffect(() => updateTime(), [date]); return <b>{dateString}</b>; }; export default ServerTime;
src/v2/stories/Buttons.stories.js
aredotna/ervell
import React from 'react' import { storiesOf } from '@storybook/react' import theme from 'v2/styles/theme' import Specimen from 'v2/stories/__components__/Specimen' import States from 'v2/stories/__components__/States' import GenericButton from 'v2/components/UI/GenericButton' import { DividerButton, FilledButton } from 'v2/components/UI/Buttons' storiesOf('Button', module) .add('GenericButton', () => ( <States states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <GenericButton>Button</GenericButton> </States> )) .add('GenericButton - colors', () => ( <Specimen> {theme.meta.colorNames.map(color => ( <States key={color} states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <GenericButton color={color}>{color}</GenericButton> </States> ))} </Specimen> )) .add('GenericButton - sizes', () => ( <Specimen> {theme.fontSizes.map((size, i) => ( <States key={size} states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <GenericButton f={i}>{`f={${i}}`}</GenericButton> </States> ))} </Specimen> )) .add('GenericButton - minWidth', () => ( <Specimen> <GenericButton minWidth="7em">Yes</GenericButton>{' '} <GenericButton minWidth="7em">No</GenericButton>{' '} <GenericButton minWidth="7em">Maybe</GenericButton> </Specimen> )) .add('GenericButton - dark backgrounds', () => ( <Specimen> <States bg="white" states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <GenericButton>Submit</GenericButton> </States> <States bg="state.premium" states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <GenericButton color="white">Submit</GenericButton> </States> </Specimen> )) .add('DividerButton', () => ( <States states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <DividerButton>Submit</DividerButton> </States> )) .add('DividerButton - colors', () => ( <Specimen> {theme.meta.colorNames.map(color => ( <States key={color} states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <DividerButton color={color}>{color}</DividerButton> </States> ))} </Specimen> )) .add('DividerButton - sizes', () => ( <Specimen> {theme.fontSizes.map((size, i) => ( <States key={size} states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <DividerButton f={i}>{`f={${i}}`}</DividerButton> </States> ))} </Specimen> )) .add('FilledButton', () => ( <States bg="gray.regular" states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <FilledButton>Button</FilledButton> </States> )) .add('FilledButton - colors', () => ( <Specimen> {theme.meta.colorNames.map(color => ( <States key={color} states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <FilledButton color={color}>{color}</FilledButton> </States> ))} </Specimen> )) .add('FilledButton - sizes', () => ( <Specimen> {theme.fontSizes.map((size, i) => ( <States bg="gray.regular" key={size} states={[{}, { disabled: true }, { hover: true }, { active: true }]} > <FilledButton f={i}>{`f={${i}}`}</FilledButton> </States> ))} </Specimen> ))
node_modules/react-element-to-jsx-string/AnonymousStatelessComponent.js
Snatch-M/fesCalendar
import React from 'react'; export default function(props) { const {children} = props; // eslint-disable-line react/prop-types return <div>{children}</div>; }
src/components/experience.js
DoWhileGeek/resume
import React from 'react' const PageBreak = () => <div className="page-break" /> export default ({ company, title, dateRange, children, pageBreak = false }) => { return ( <> <div className="experience-container"> <div className="experience-header"> <span> <b>{title}</b> at {company} </span> {dateRange} </div> <ul className="duties-list">{children}</ul> </div> {pageBreak && <PageBreak />} </> ) }
frontend/tests/components/Header.spec.js
Svjard/sagedesk
import expect from 'expect'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import { Header } from 'components/Header'; describe('Header', () => { it('should should show the correct user name', () => { const renderedComponent = TestUtils.renderIntoDocument( <Header /> ); expect(renderedComponent).toExist(); }); });
packages/material-ui-icons/src/LibraryAdd.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let LibraryAdd = props => <SvgIcon {...props}> <path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z" /> </SvgIcon>; LibraryAdd = pure(LibraryAdd); LibraryAdd.muiName = 'SvgIcon'; export default LibraryAdd;
src/Parser/Core/Modules/Items/Legion/AntorusTheBurningThrone/TarratusKeystone.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import ITEMS from 'common/ITEMS'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import ItemHealingDone from 'Main/ItemHealingDone'; /* * Tarratus Keystone - * Use: Open a portal at an ally's location that releases brilliant light, restoring 1633313 health split amongst injured allies within 20 yds. (1 Min, 30 Sec Cooldown) */ class TarratusKeystone extends Analyzer { static dependencies = { combatants: Combatants, }; healing = 0; on_initialized() { this.active = this.combatants.selected.hasTrinket(ITEMS.TARRATUS_KEYSTONE.id); } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (spellId === SPELLS.TARRATUS_KEYSTONE.id) { this.healing += (event.amount || 0) + (event.absorbed || 0); } } item() { return { item: ITEMS.TARRATUS_KEYSTONE, result: <ItemHealingDone amount={this.healing} />, }; } } export default TarratusKeystone;
modules/RoutingContext.js
Nedomas/react-router
import React from 'react' import invariant from 'invariant' import getRouteParams from './getRouteParams' const { array, func, object } = React.PropTypes /** * A <RoutingContext> renders the component tree for a given router state * and sets the history object and the current location in context. */ const RoutingContext = React.createClass({ propTypes: { history: object.isRequired, createElement: func.isRequired, location: object.isRequired, routes: array.isRequired, params: object.isRequired, components: array.isRequired }, getDefaultProps() { return { createElement: React.createElement } }, childContextTypes: { history: object.isRequired, location: object.isRequired }, getChildContext() { return { history: this.props.history, location: this.props.location } }, createElement(component, props) { return component == null ? null : this.props.createElement(component, props) }, render() { const { history, location, routes, params, components } = this.props let element = null if (components) { element = components.reduceRight((element, components, index) => { if (components == null) return element // Don't create new children use the grandchildren. const route = routes[index] const routeParams = getRouteParams(route, params) const props = { history, location, params, route, routeParams, routes } if (element) props.children = element if (typeof components === 'object') { const elements = {} for (const key in components) if (components.hasOwnProperty(key)) elements[key] = this.createElement(components[key], props) return elements } return this.createElement(components, props) }, element) } invariant( element === null || element === false || React.isValidElement(element), 'The root route must render a single element' ) return element } }) export default RoutingContext
client/extensions/woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal/rates-step/index.js
Automattic/woocommerce-services
/** @format */ /** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { localize } from 'i18n-calypso'; import { find, forEach, isEmpty, mapValues, some } from 'lodash'; import formatCurrency from '@automattic/format-currency'; import Gridicon from 'gridicons'; /** * Internal dependencies */ import ShippingRates from './list'; import StepContainer from '../step-container'; import { hasNonEmptyLeaves } from 'woocommerce/woocommerce-services/lib/utils/tree'; import { toggleStep, updateRate, } from 'woocommerce/woocommerce-services/state/shipping-label/actions'; import { getShippingLabel, isLoaded, getFormErrors, getTotalPriceBreakdown, } from 'woocommerce/woocommerce-services/state/shipping-label/selectors'; import { getAllPackageDefinitions } from 'woocommerce/woocommerce-services/state/packages/selectors'; import { getOrderShippingTotal } from 'woocommerce/lib/order-values/totals'; import { getOrderShippingMethod, getOrderCurrency } from 'woocommerce/lib/order-values'; import { getOrder } from 'woocommerce/state/sites/orders/selectors'; const ratesSummary = ( selectedRates, availableRates, total, packagesSaved, translate ) => { if ( ! packagesSaved ) { return translate( 'Unsaved changes made to packages' ); } if ( some( mapValues( availableRates, rateObject => isEmpty( rateObject.default.rates ) ) ) ) { return translate( 'No rates found' ); } if ( ! total ) { return ''; } const packageIds = Object.keys( selectedRates ); // Show the service name and cost when only one service/package exists if ( 1 === packageIds.length ) { const packageId = packageIds[ 0 ]; const selectedRate = selectedRates[ packageId ]; const packageRates = availableRates[ packageId ].default.rates; const rateInfo = find( packageRates, [ 'service_id', selectedRate ] ); if ( rateInfo ) { return translate( '%(serviceName)s: %(rate)s', { args: { serviceName: rateInfo.title, rate: formatCurrency( rateInfo.rate, 'USD' ), }, } ); } return ''; } // Otherwise, just show the total return translate( 'Total rate: %(total)s', { args: { total: formatCurrency( total, 'USD' ), }, } ); }; const getRatesStatus = ( { retrievalInProgress, errors, available, form } ) => { if ( retrievalInProgress ) { return { isProgress: true }; } if ( hasNonEmptyLeaves( errors ) ) { return { isError: true }; } if ( isEmpty( available ) ) { return {}; } if ( ! form.packages.saved ) { return { isWarning: true }; } return { isSuccess: true }; }; const showCheckoutShippingInfo = props => { const { shippingMethod, shippingCost, translate, currency } = props; // Use a temporary HTML element in order to let the DOM API convert HTML entities into text const shippingMethodDiv = document.createElement( 'div' ); shippingMethodDiv.innerHTML = shippingMethod; const decodedShippingMethod = shippingMethodDiv.textContent; // Add suffix for non USD. const shippingCostSuffix = ( typeof currency != 'undefined' && 'USD' !== currency ) ? currency : ''; if ( shippingMethod ) { let shippingInfo; if ( 0 < shippingCost ) { shippingInfo = translate( 'Customer paid a {{shippingMethod/}} of {{shippingCost/}} for shipping', { components: { shippingMethod: ( <span>{ decodedShippingMethod }</span> ), shippingCost: ( <span className="rates-step__shipping-info-cost"> { formatCurrency( shippingCost, currency ) } { shippingCostSuffix } </span> ), }, } ); } else { shippingInfo = translate( 'Your customer selected {{shippingMethod/}}', { components: { shippingMethod: ( <span className="rates-step__shipping-info-method">{ decodedShippingMethod }</span> ), }, } ); } return ( <div className="rates-step__shipping-info"> <Gridicon icon="info-outline" /> <div >{ shippingInfo }</div> </div> ); } }; const RatesStep = props => { const { siteId, orderId, form, allPackages, values, available, errors, ratesTotal, translate, currency, } = props; const summary = ratesSummary( values, available, ratesTotal, form.packages.saved, translate ); const toggleStepHandler = () => props.toggleStep( orderId, siteId, 'rates' ); const updateRateHandler = ( packageId, serviceId, carrierId, signatureRequired ) => props.updateRate( orderId, siteId, packageId, serviceId, carrierId, signatureRequired ); // Preselect rates for packages that have only one rate available. forEach( form.packages.selected, ( selectedRate, pckgId ) => { // Skip preselection for already selected values. if( "" !== values[ pckgId ] ) { return; } if ( ( ! isEmpty( available ) ) && ( pckgId in available ) && ( 1 === available[ pckgId ].default.rates.length ) ) { const signatureRequired = false; // Don't preselect signature. const { service_id } = available[ pckgId ].default.rates[ 0 ]; updateRateHandler( pckgId, service_id, signatureRequired ); } } ); return ( <StepContainer title={ translate( 'Shipping rates' ) } summary={ summary } expanded={ ! isEmpty( available ) } toggleStep={ toggleStepHandler } { ...getRatesStatus( props ) } > { ! isEmpty( available ) && showCheckoutShippingInfo( props ) } <ShippingRates id="rates" orderId={ orderId } siteId={ siteId } currency={ currency } showRateNotice={ false } selectedPackages={ form.packages.selected } allPackages={ allPackages } selectedRates={ values } availableRates={ available } updateRate={ updateRateHandler } errors={ errors } /> </StepContainer> ); }; RatesStep.propTypes = { siteId: PropTypes.number.isRequired, orderId: PropTypes.number.isRequired, form: PropTypes.object.isRequired, values: PropTypes.object.isRequired, available: PropTypes.object.isRequired, errors: PropTypes.object.isRequired, toggleStep: PropTypes.func.isRequired, updateRate: PropTypes.func.isRequired, }; const mapStateToProps = ( state, { orderId, siteId } ) => { const loaded = isLoaded( state, orderId, siteId ); const shippingLabelState = getShippingLabel( state, orderId, siteId ); const priceBreakdown = getTotalPriceBreakdown( state, orderId, siteId ); const order = getOrder( state, orderId, siteId ); return { ...shippingLabelState.form.rates, form: shippingLabelState.form, errors: loaded && getFormErrors( state, orderId, siteId ).rates, ratesTotal: priceBreakdown ? priceBreakdown.total : 0, allPackages: getAllPackageDefinitions( state, siteId ), shippingCost: getOrderShippingTotal( order ), shippingMethod: getOrderShippingMethod( order ), currency: getOrderCurrency( order ), }; }; const mapDispatchToProps = dispatch => { return bindActionCreators( { toggleStep, updateRate }, dispatch ); }; export default connect( mapStateToProps, mapDispatchToProps )( localize( RatesStep ) );
packages/react/src/components/UIShell/__tests__/HeaderName-test.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import { mount } from 'enzyme'; import { HeaderName } from '../'; describe('HeaderName', () => { let mockProps; beforeEach(() => { mockProps = { className: 'custom-class', children: 'Name', prefix: 'IBM', href: '/', }; }); it('should render', () => { const wrapper = mount(<HeaderName {...mockProps} />); expect(wrapper).toMatchSnapshot(); }); });
app/jsx/navigation_header/trays/GroupsTray.js
djbender/canvas-lms
/* * Copyright (C) 2015 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import I18n from 'i18n!GroupsTray' import React from 'react' import {bool, arrayOf, shape, string} from 'prop-types' import {View} from '@instructure/ui-layout' import {Heading, List, Spinner} from '@instructure/ui-elements' import {Link} from '@instructure/ui-link' export default function GroupsTray({groups, hasLoaded}) { return ( <View as="div" padding="medium"> <Heading level="h3" as="h2"> {I18n.t('Groups')} </Heading> <hr role="presentation" /> <List variant="unstyled" margin="small 0" itemSpacing="small"> {hasLoaded ? ( groups .map(group => ( <List.Item key={group.id}> <Link isWithinText={false} href={`/groups/${group.id}`}> {group.name} </Link> </List.Item> )) .concat([ <List.Item key="hr"> <hr role="presentation" /> </List.Item>, <List.Item key="all"> <Link isWithinText={false} href="/groups"> {I18n.t('All Groups')} </Link> </List.Item> ]) ) : ( <List.Item> <Spinner size="small" renderTitle={I18n.t('Loading')} /> </List.Item> )} </List> </View> ) } GroupsTray.propTypes = { groups: arrayOf( shape({ id: string.isRequired, name: string.isRequired }) ).isRequired, hasLoaded: bool.isRequired } GroupsTray.defaultProps = { groups: [] }
test/integration/image-component/custom-resolver/pages/client-side.js
zeit/next.js
import React from 'react' import Image from 'next/image' const myLoader = ({ src, width, quality }) => { return `https://customresolver.com/${src}?w~~${width},q~~${quality}` } const MyImage = (props) => { return <Image loader={myLoader} {...props}></Image> } const Page = () => { return ( <div> <p id="client-side">Image Client Side Test</p> <MyImage id="basic-image" src="foo.jpg" loading="eager" width={300} height={400} quality={60} /> <Image id="unoptimized-image" unoptimized src="https://arbitraryurl.com/foo.jpg" loading="eager" width={300} height={400} /> </div> ) } export default Page
internals/templates/containers/HomePage/index.js
VeloCloud/website-ui
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
src/tags/size.js
JimLiu/bbcode-to-react
// https://github.com/vishnevskiy/bbcodejs/blob/master/src/coffee/tags.coffee import React from 'react'; import Tag from '../tag'; export default class SizeTag extends Tag { toHTML() { const size = this.params.size; if (isNaN(size)) { return this.getContent(); } return [`<span style="font-size:${size}px">`, this.getContent(), '</span>']; } toReact() { const size = this.params.size; if (isNaN(size)) { return this.getComponents(); } return ( <span style={{ fontSize: `${size}px` }}>{this.getComponents()}</span> ); } }
demo/components/Head.js
flybears/component-react
/** * Created by flybear on 15/11/18. */ import React from 'react' export default class Head extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(){ console.log("---") } render() { return ( <header> <nav className="navbar navbar-default"> <div className="container-fluid"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <a className="navbar-brand" href="javascript:">Brand</a> </div> <div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul className="nav navbar-nav"> <li className="active"><a href="javascript:">Link <span className="sr-only">(current)</span></a></li> <li><a href="javascript:">Link</a></li> <li className="dropdown"> <a href="javascript:" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span className="caret"></span></a> <ul className="dropdown-menu"> <li><a href="javascript:">Action</a></li> <li><a href="javascript:">Another action</a></li> <li><a href="javascript:">Something else here</a></li> <li role="separator" className="divider"></li> <li><a href="javascript:">Separated link</a></li> <li role="separator" className="divider"></li> <li><a href="javascript:">One more separated link</a></li> </ul> </li> </ul> <div className="nav navbar-nav navbar-right lh50"> <button className="btn btn-primary m-r-sm" onClick={this.handleClick} >登陆</button> <button className="btn btn-default" href="javascript:">注册</button> </div> </div> </div> </nav> </header> ) } }
opentech/static_src/src/app/src/components/MessagesList/index.js
OpenTechFund/WebApp
import React from 'react' import PropTypes from 'prop-types' import MessageBar from '@components/MessageBar' const MessagesList = ({ children }) => { return ( <ul className="messages"> { children } </ul> ) } MessagesList.propTypes = { children: PropTypes.oneOfType([PropTypes.arrayOf(MessageBar), MessageBar]) } export default MessagesList
server/sonar-web/src/main/js/apps/overview/gate/gate-condition.js
vamsirajendra/sonarqube
import React from 'react'; import { getPeriodLabel, getPeriodDate } from '../helpers/periods'; import { DrilldownLink } from '../../../components/shared/drilldown-link'; import { formatMeasure } from '../../../helpers/measures'; const Measure = React.createClass({ render() { if (this.props.value == null || isNaN(this.props.value)) { return null; } let formatted = formatMeasure(this.props.value, this.props.type); return <span>{formatted}</span>; } }); export default React.createClass({ render() { let metricName = window.t('metric', this.props.condition.metric.name, 'name'); let threshold = this.props.condition.level === 'ERROR' ? this.props.condition.error : this.props.condition.warning; let period = this.props.condition.period ? getPeriodLabel(this.props.component.periods, this.props.condition.period) : null; let periodDate = getPeriodDate(this.props.component.periods, this.props.condition.period); let classes = 'alert_' + this.props.condition.level.toUpperCase(); return ( <li className="overview-gate-condition"> <div className="little-spacer-bottom">{period}</div> <div style={{ display: 'flex', alignItems: 'center' }}> <div className="overview-gate-condition-value"> <DrilldownLink component={this.props.component.key} metric={this.props.condition.metric.name} period={this.props.condition.period} periodDate={periodDate}> <span className={classes}> <Measure value={this.props.condition.actual} type={this.props.condition.metric.type}/> </span> </DrilldownLink>&nbsp; </div> <div className="overview-gate-condition-metric"> <div>{metricName}</div> <div> {window.t('quality_gates.operator', this.props.condition.op, 'short')} {' '} <Measure value={threshold} type={this.props.condition.metric.type}/> </div> </div> </div> </li> ); } });
examples/simple/src/App.js
treyhoover/react-greedy-text
import React, { Component } from 'react'; import GreedyText from 'react-greedy-text'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <header> <GreedyText> Greedy Text! </GreedyText> </header> <main style={{ flex: 1, display: 'flex' }}> <div style={{ flex: 1 }}> <GreedyText> Greedy Text does a binary search to quickly maximize the font-size that will fill its parent container without overflowing. </GreedyText> </div> <div style={{ flex: 1, padding: '0px 40px' }}> <GreedyText> “I mean I guess if you had no other option...” </GreedyText> </div> </main> </div> ); } } export default App;
components/User/UserProfile/PrivatePublicUserProfile/PrivatePublicUserProfile.js
slidewiki/slidewiki-platform
import PropTypes from 'prop-types'; import React from 'react'; import { List, Segment, Checkbox, Header } from 'semantic-ui-react'; import PublicUserData from '../PublicUserData'; import UserDecks from './UserDecks'; import UserCollections from '../../../DeckCollection/UserCollections'; import UserMenu from './UserMenu'; import UserRecommendations from '../UserRecommendations'; import classNames from 'classnames/bind'; import { FormattedMessage, defineMessages } from 'react-intl'; import fetchUserDecks from '../../../../actions/user/userprofile/fetchUserDecks'; class PrivatePublicUserProfile extends React.Component { constructor(props) { super(props); } showUserDecks() { return <UserDecks decks={this.props.decks} decksMeta={this.props.decksMeta} deckListType={this.props.categoryItem} loadMoreLoading={this.props.loadMoreLoading} loadMoreError={this.props.loadMoreError} user={this.props.user} loggedinuser={this.props.loggedinuser} />; } showUserCollections() { return <UserCollections user={this.props.user} loggedinuser={this.props.loggedinuser} loggedinUserId={this.props.loggedinUserId} />; } showUserRecommendactions() { return <UserRecommendations loggedinuser={this.props.loggedinuser} loggedinUserId={this.props.loggedinUserId} />; } chooseView() { switch (this.props.category) { case 'playlists': return this.showUserCollections(); case 'recommendations': return this.showUserRecommendactions(); case 'deck': default: return this.showUserDecks(); } } handleFilterChange(event, { value }) { this.context.executeAction(fetchUserDecks, { deckListType: this.props.categoryItem, params: { username: this.props.user.uname, sort: this.props.decksMeta.sort, status: value, } }); } render() { let meta = this.props.decksMeta; let profileClasses = classNames({ 'tablet': this.props.loggedinuser && this.props.user.uname === this.props.loggedinuser, 'computer': this.props.loggedinuser && this.props.user.uname === this.props.loggedinuser, 'only': this.props.loggedinuser && this.props.user.uname === this.props.loggedinuser, 'sixteen': true, 'wide': true, 'column': true }); let messages = defineMessages({ anyText: { id: 'user.userProfile.privatePublicProfile.allStatus', defaultMessage: 'All' }, publicText: { id: 'user.userProfile.privatePublicProfile.publicStatus', defaultMessage: 'Published' }, hiddenText: { id: 'user.userProfile.privatePublicProfile.hiddenStatus', defaultMessage: 'Unlisted' } }); return ( <div className="ui vertically padded stackable grid container" > <div className="four wide column" > <div className="ui stackable grid "> <div className={profileClasses}> <PublicUserData user={this.props.user} loggedinuser={this.props.loggedinuser} /> </div> <div className="sixteen wide column"> <UserMenu user={this.props.user} loggedinuser={this.props.loggedinuser} choice={this.props.category} /> {this.props.user.uname === this.props.loggedinuser && this.props.category !== 'playlists' && this.props.category !== 'recommendations' && <Segment> <Header size='small' dividing ><FormattedMessage id='user.userProfile.privatePublicProfile.publicationStatus' defaultMessage='Publication status' /></Header> <List>{ [ { value: 'any', text: this.context.intl.formatMessage(messages.anyText) }, { value: 'public', text: this.context.intl.formatMessage(messages.publicText) }, { value: 'hidden', text: this.context.intl.formatMessage(messages.hiddenText) }, ].map((opt, index) => ( <List.Item key={index}> <Checkbox radio name='published_status' value={opt.value} disabled={!meta.status} aria-labelledby={`published_${opt.value}_label`} label={<label id={`published_${opt.value}_label`}>{opt.text}</label>} checked={meta.status === opt.value} onChange={this.handleFilterChange.bind(this)} /> </List.Item> )) } </List> </Segment> } </div> </div> </div> <div className="twelve wide column" > {this.chooseView()} </div> <div className="ui tab" data-tab="activity"></div> </div> ); } } PrivatePublicUserProfile.contextTypes = { executeAction: PropTypes.func.isRequired, intl: PropTypes.object.isRequired }; export default PrivatePublicUserProfile;
packages/react/src/internal/__tests__/useDelayedState-test.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import { cleanup, render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import { act } from 'react-dom/test-utils'; import { useDelayedState } from '../useDelayedState'; jest.useFakeTimers(); describe('useDelayedState', () => { afterEach(cleanup); it('should update the state after the given delayMs', () => { function TestComponent() { const [count, setCount] = useDelayedState(0); return ( <> <span data-testid="count">{count}</span> <button type="button" onClick={() => { setCount((c) => c + 1, 1000); }}> increment </button> </> ); } render(<TestComponent />); expect(screen.getByTestId('count').textContent).toBe('0'); act(() => { userEvent.click(screen.getByText('increment')); jest.runOnlyPendingTimers(); }); expect(screen.getByTestId('count').textContent).toBe('1'); }); it('should cancel any pending state updates if called before delayMs has passed', () => { function TestComponent() { const [count, setCount] = useDelayedState(0); return ( <> <span data-testid="count">{count}</span> <button type="button" onClick={() => { setCount((c) => c + 1, 1000); }}> increment </button> </> ); } render(<TestComponent />); act(() => { userEvent.click(screen.getByText('increment')); jest.advanceTimersByTime(500); userEvent.click(screen.getByText('increment')); jest.runOnlyPendingTimers(); }); expect(screen.getByTestId('count').textContent).toBe('1'); }); it('should immediately call setState if no delay is given', () => { function TestComponent() { const [count, setCount] = useDelayedState(0); return ( <> <span data-testid="count">{count}</span> <button type="button" onClick={() => { setCount(count + 1); }}> increment </button> </> ); } render(<TestComponent />); expect(screen.getByTestId('count').textContent).toBe('0'); userEvent.click(screen.getByText('increment')); expect(screen.getByTestId('count').textContent).toBe('1'); }); });
packages/core/upload/admin/src/components/EditAssetDialog/RemoveAssetDialog.js
wistityhq/strapi
import React from 'react'; import PropTypes from 'prop-types'; import { ConfirmDialog } from '@strapi/helper-plugin'; import { useRemoveAsset } from '../../hooks/useRemoveAsset'; export const RemoveAssetDialog = ({ onClose, asset }) => { const { isLoading, removeAsset } = useRemoveAsset(onClose); const handleConfirm = () => { removeAsset(asset.id); }; return ( <ConfirmDialog isConfirmButtonLoading={isLoading} isOpen onToggleDialog={onClose} onConfirm={handleConfirm} /> ); }; RemoveAssetDialog.propTypes = { onClose: PropTypes.func.isRequired, asset: PropTypes.shape({ id: PropTypes.number, height: PropTypes.number, width: PropTypes.number, size: PropTypes.number, createdAt: PropTypes.string, ext: PropTypes.string, name: PropTypes.string, url: PropTypes.string, }).isRequired, };
src/parser/shaman/restoration/modules/spells/HealingRain.js
fyruna/WoWAnalyzer
import React from 'react'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import SPELLS from 'common/SPELLS'; import { TooltipElement } from 'common/Tooltip'; import Analyzer from 'parser/core/Analyzer'; import Combatants from 'parser/shared/modules/Combatants'; // 50 was too low, 100 was too high // had no issues with 85ms const BUFFER_MS = 85; class HealingRain extends Analyzer { static dependencies = { combatants: Combatants, }; healingRainTicks = []; get averageHitsPerTick() { const totalHits = this.healingRainTicks.reduce((total, tick) => total + tick.hits, 0); return totalHits / this.healingRainTicks.length; } suggestions(when) { const suggestionThreshold = this.suggestionThreshold; when(suggestionThreshold.actual).isLessThan(suggestionThreshold.isLessThan.minor) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>Try to always cast <SpellLink id={SPELLS.HEALING_RAIN_CAST.id} /> in areas where players stack. This allows the spell to consitantly hit all 6 possible targets.</span>) .icon(SPELLS.HEALING_RAIN_CAST.icon) .actual(`${suggestionThreshold.actual.toFixed(2)} average targets healed`) .recommended(`${suggestionThreshold.isLessThan.minor} average targets healed`) .regular(suggestionThreshold.isLessThan.average).major(suggestionThreshold.isLessThan.average); }); } get suggestionThreshold() { return { actual: this.averageHitsPerTick, isLessThan: { minor: 5, average: 3, major: 2, }, style: 'number', }; } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.HEALING_RAIN_HEAL.id) { return; } // Filter out pets, but only if it fully overhealed as Rain will prioritize injured pets over non-injured players // fully overhealing guarantees that there are not enough players in the healing rain const combatant = this.combatants.players[event.targetID]; if (!combatant && event.overheal && event.amount === 0) { return; } const healingRainTick = this.healingRainTicks.find(tick => event.timestamp - BUFFER_MS <= tick.timestamp); if (!healingRainTick) { this.healingRainTicks.push({ timestamp: event.timestamp, hits: 1, }); } else { // dirty fix for partial ticks happening at the same time as a real tick healingRainTick.hits = healingRainTick.hits + 1 > 6 ? healingRainTick.hits = 6 : healingRainTick.hits + 1; } } statistic() { if (isNaN(this.averageHitsPerTick)) { return false; } return ( <StatisticBox icon={<SpellIcon id={SPELLS.HEALING_RAIN_HEAL.id} />} value={`${this.averageHitsPerTick.toFixed(2)}`} position={STATISTIC_ORDER.OPTIONAL()} label={( <TooltipElement content="The average number of targets healed by Healing Rain out of the maximum amount of 6 targets."> Average Healing Rain Targets </TooltipElement> )} /> ); } } export default HealingRain;
WebApp/wwwroot/ReactApp/src/components/codecamp/speakers/SpeakerListItem.js
pkellner/svcc-react4
import React from 'react'; import PropTypes from 'prop-types'; export default function SpeakerListItem(props) { const { id, firstName, lastName, company, imageUrl } = props; const img = () => { if (process.env.NODE_ENV === 'development') { return ( <img src={`assets/images/speakers/Speaker-${id}.jpg`} alt="{this.props.firstName} {this.props.lastName}" /> ); } return ( <img src={imageUrl} alt="{this.props.firstName} {this.props.lastName}" /> ); }; return ( <div className="col-12 col-sm-6 speakers-list-item"> <div className="events-speaker d-flex align-items-center"> <div className="events-speaker-photo">{img()}</div> <div className="events-speaker-description"> <div className="name"> {firstName} {lastName} </div> <div className="profession">{company}</div> </div> </div> </div> ); } SpeakerListItem.propTypes = { id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), firstName: PropTypes.string, lastName: PropTypes.string, company: PropTypes.string, imageUrl: PropTypes.string, };
docs/src/pages/landing/Sponsors.js
lgollut/material-ui
import React from 'react'; import * as PropTypes from 'prop-types'; import { useSelector } from 'react-redux'; import { makeStyles } from '@material-ui/core/styles'; import NoSsr from '@material-ui/core/NoSsr'; import MarkdownElement from 'docs/src/modules/components/MarkdownElement'; import Container from '@material-ui/core/Container'; import Divider from '@material-ui/core/Divider'; import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown'; const useStyles = makeStyles( (theme) => ({ '@global': { '.anchor-link-style': { position: 'absolute', top: -9999, left: -9999, }, }, root: { minHeight: 600, textAlign: 'center', }, markdownElement: { padding: theme.spacing(4, 0), }, }), { name: 'Sponsors' }, ); export default function Sponsors({ docs }) { const classes = useStyles(); const userLanguage = useSelector((state) => state.options.userLanguage); const { rendered } = docs[userLanguage]; return ( <div className={classes.root}> <NoSsr defer> <Container maxWidth="md"> <Divider /> {rendered.map((renderedMarkdown, index) => { return ( <MarkdownElement key={index} className={classes.markdownElement} renderedMarkdown={renderedMarkdown} /> ); })} </Container> </NoSsr> </div> ); } Sponsors.propTypes = { docs: PropTypes.object.isRequired, }; const requireRaw = require.context('./', false, /\.md$/); export async function getInitialProps() { const { docs } = prepareMarkdown({ pageFilename: '/', requireRaw }); return { docs }; }
app/components/Home.js
albertmejia/empire_room
import React from 'react'; import {home} from '../styles/home.scss'; import Carousel from './Carousel'; import UpcomingEvents from './UpcomingEvents'; import axios from 'axios'; import { WP_DOMAIN } from '../../wp.config'; class Home extends React.Component { constructor(props) { super(props); this.state = { eventsList: [], carouselImages: [] }; } componentWillMount() { axios.get(`${WP_DOMAIN}/wp-json/wp/v2/events`) .then((res) => { this.setState({eventsList: res.data}); }) .catch((err) => { console.log(err, 'there was an error'); }); axios.get(`${WP_DOMAIN}/wp-json/wp/v2/carousel_images`) .then((res) => { const carouselImagesArray = res.data.map((image) => { return image.acf.carousel_image; }); this.setState({carouselImages: carouselImagesArray}); }) .catch((err) => { console.log(err, 'there was an error'); }); } componentDidMount() { window.scrollTo(0, 0); } render() { return ( <div className={home}> <Carousel carouselImages={this.state.carouselImages}/> <UpcomingEvents eventsList={this.state.eventsList} isHomepage={true}/> </div> ); } } export default Home;
todo-list/src/List.js
Nodewarrior/react-examples
import React, { Component } from 'react'; const List = props => ( <ul> {props.items.map((item, index) => <li key={index}>{item}</li>)} </ul> ); export default List;
src/components/App.js
tanykim/julie-and-julia
import React, { Component } from 'react'; import Script from './../data/data.json'; import SearchForm from './SearchForm'; import Visualization from './Visualization'; import SecretStory from './SecretStory'; import TextLineList from './TextLineList'; class App extends Component { constructor(props) { super(props); this.state = { data: Script, searchedLines: [], highlighted: [], lineNo: null, story: '' }; this.handleScroll = this.handleScroll.bind(this); this.onHighlight = this.onHighlight.bind(this); this.onReceiveResult = this.onReceiveResult.bind(this); this.onResetResult = this.onResetResult.bind(this); this.showSecretStory = this.showSecretStory.bind(this); this.textHovered = this.textHovered.bind(this); } //scroll componentDidMount() { window.addEventListener('scroll', this.handleScroll); } handleScroll(event) { const scrollTop = event.srcElement.body.scrollTop; const resultH = document.getElementById('result-container').clientHeight; //220 is roughly the height of the bottom part, with some buffer //show the default when scoll is over if (scrollTop > 220 && window.innerHeight - resultH < -scrollTop) { this.setState({isHidden: true}); } else { this.setState({isHidden: false}); } } //highlight lines in sync with text enter onHighlight(tempResult) { this.setState({highlighted: tempResult}); } //when text input submitted (return key pressed) onReceiveResult(result, searchStr) { let searchedLines = result.map((id) => [id, this.state.data[id]]); this.setState({ searchedLines: searchedLines, searchStr: searchStr, story: '' }); } //secret message showSecretStory(story) { this.setState({story: story}); } //when Backspace is pressed after results are shown onResetResult() { this.setState({ searchedLines: [] }) } textHovered(lineNo) { this.setState({linkedLineNo: lineNo}); } render() { return ( <div className="container-fluid"> {/* visualization */} <div className="row vis-container" id="vis-width"> <div className="col-xs-12 hidden-xs hidden-sm vis"> <Visualization data={this.state.data} highlighted={this.state.highlighted} linkedLineNo={this.state.linkedLineNo} searchedLines={this.state.searchedLines} /> </div> </div> {/* result */} <div className="row result-container" id="result-container"> <div className="col-xs-12 col-md-6 col-md-offset-3 story"> <SecretStory story={this.state.story} /> </div> <div className="col-xs-12 col-md-10 col-md-offset-1 col-lg-6 col-lg-offset-3 result"> <TextLineList searchedLines={this.state.searchedLines} searchStr={this.state.searchStr} onHovered={this.textHovered} /> </div> </div> {/* default bottom */} <div className="default-container"> <div className="row"> <div className={this.state.isHidden ? 'col-xs-12 title small' : 'col-xs-12 title'}> Julie <span className="amp">&amp;</span> Julia </div> </div> <div className={this.state.isHidden ? 'hide' : 'show'}> <SearchForm data={this.state.data} onHighlight={this.onHighlight} onReceiveResult={this.onReceiveResult} onResetResult={this.onResetResult} onSecretStory={this.showSecretStory} /> <div className="row"> <div className="col-xs-12 footer"> <ul> <li>Inspired by <a href="https://twitter.com/pencilpenbrush/status/803756815225909248" target="_blacnk">@pencilpenbrush</a></li> <li>View on <a href="https://github.com/tanykim/julie-and-julia" target="_blacnk">GitHub</a></li> <li><a href="http://www.script-o-rama.com/movie_scripts/j/julie-and-julia-script-transcript.html" target="_blacnk">Original Script</a></li> </ul> </div> </div> </div> </div> </div> ); } } export default App;
src/backward/Widgets/Container.js
sampsasaarela/NativeBase
/* @flow */ import React from 'react'; import { View, Image, ScrollView } from 'react-native'; import { connectStyle } from 'native-base-shoutem-theme'; import { Footer } from '../../basic/Footer'; import { Fab } from '../../basic/Fab'; import _ from 'lodash'; import mapPropsToStyleNames from '../../Utils/mapPropsToStyleNames'; import { ViewNB } from './View'; import { Header } from './Header'; import { Content } from './Content'; import NativeBaseComponent from '../Base/NativeBaseComponent'; import computeProps from '../../Utils/computeProps'; class Container extends NativeBaseComponent { propTypes: { style : React.PropTypes.object } renderHeader() { if (Array.isArray(this.props.children)) { return _.find(this.props.children, (item) => { if (item && (item.type.displayName === 'Styled(Header)' || item.type.displayName === 'Styled(SHeader)')) { return true; } }); } else if (this.props.children && (this.props.children.type.displayName === 'Styled(Header)' || this.props.children.type.displayName === 'Styled(SHeader)')) { return this.props.children; } } renderContent() { if (Array.isArray(this.props.children)) { return _.filter(this.props.children, (item) => { if (item && (item.type.displayName === 'Styled(ViewNB)' || item.type.displayName === 'Styled(Content)' || item.type === Image || item.type === View || item.type === ScrollView || item.type.displayName === 'Styled(Fab)')) { return true; } }); } else if (this.props.children && (this.props.children.type.displayName === 'Styled(Content)' || this.props.children.type.displayName === 'Styled(ViewNB)' || this.props.children.type === View || this.props.children.type === Image || this.props.children.type === ScrollView)) { return this.props.children; } } renderFooter() { if (Array.isArray(this.props.children)) { return _.find(this.props.children, (item) => { if (item && item.type.displayName === 'Styled(Footer)') { return true; } }); } else if (this.props.children && this.props.children.type.displayName === 'Styled(Footer)') { return this.props.children; } } prepareRootProps() { const type = { flex: 1, }; const defaultProps = { style: type, }; return computeProps(this.props, defaultProps); } render() { return ( <View ref={c => this._root = c} {...this.prepareRootProps()}> {this.renderHeader()} {this.renderContent()} {this.renderFooter()} </View> ); } } Container.propTypes = { ...View.propTypes, style: React.PropTypes.object, }; const StyledContainer = connectStyle('NativeBase.Container', {}, mapPropsToStyleNames)(Container); export { StyledContainer as Container, };
index.js
toubou91/react-lorem
import React from 'react'; import { render } from 'react-dom'; import Lorem from './Lorem'; render( <div> <Lorem /> <Lorem reps={{ times: 4, lineBreak: true }} color={'yellow'} fontSize={'medium'} /> <Lorem color={'blue'} fontSize={30} /> <Lorem color={'rgb(154,67,123)'} fontSize={'large'} /> </div>, document.getElementById('root') );
client/app/components/IssueIcon/index.js
Kielan/onDemanager
import React from 'react'; class IssueIcon extends React.Component { render() { return ( <svg height="1em" width="0.875em" className={ this.props.className } > <path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" /> </svg> ); } } export default IssueIcon;
test/specs/shape/PolygonSpec.js
recharts/recharts
import React from 'react'; import { expect } from 'chai'; import { Surface, Polygon } from 'recharts'; import { mount, render } from 'enzyme'; describe('<Polygon />', () => { const points = [ { x: 100, y: 300 }, { x: 300, y: 300 }, { x: 200, y: 50 }, ]; it('Render 1 path in simple Polygon', () => { const wrapper = render( <Surface width={400} height={400}> <Polygon points={points} fill="#ff7300" /> </Surface> ); expect(wrapper.find('.recharts-polygon').length).to.equal(1); }); it('Dno\'t render any path when points is empty or null', () => { const wrapper = render( <Surface width={400} height={400}> <Polygon points={[]} fill="#ff7300" /> <Polygon fill="#ff7300" /> </Surface> ); expect(wrapper.find('.recharts-polygon').length).to.equal(0); }); });
test/helpers/shallowRenderHelper.js
jc784999074/study-react
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
app/javascript/mastodon/components/button.js
rekif/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class Button extends React.PureComponent { static propTypes = { text: PropTypes.node, onClick: PropTypes.func, disabled: PropTypes.bool, block: PropTypes.bool, secondary: PropTypes.bool, size: PropTypes.number, className: PropTypes.string, style: PropTypes.object, children: PropTypes.node, }; static defaultProps = { size: 36, }; handleClick = (e) => { if (!this.props.disabled) { this.props.onClick(e); } } setRef = (c) => { this.node = c; } focus() { this.node.focus(); } render () { const style = { padding: `0 ${this.props.size / 2.25}px`, height: `${this.props.size}px`, lineHeight: `${this.props.size}px`, ...this.props.style, }; const className = classNames('button', this.props.className, { 'button-secondary': this.props.secondary, 'button--block': this.props.block, }); return ( <button className={className} disabled={this.props.disabled} onClick={this.handleClick} ref={this.setRef} style={style} > {this.props.text || this.props.children} </button> ); } }
app/index.js
AidanNichol/stedwards-booking-system
import 'babel-polyfill'; import React from 'react'; import { render } from 'react-dom'; import { browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { AppContainer } from 'react-hot-loader'; import {configureStore} from 'store'; import Root from 'containers/Root'; // import './styles/main.scss'; const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById('root') ); if (module.hot) { module.hot.accept('containers/Root', () => { const NewRoot = require('containers/Root').default; render( <AppContainer> <NewRoot store={store} history={history} /> </AppContainer>, document.getElementById('root') ); }); }
src/product.js
slx-dev/react-testing
import React from 'react'; import {Row,Col} from 'reactstrap'; import PRODUCTS from './products.json'; // import Gallery from './gallery'; var $ = require ('jquery'); export default class Product extends React.Component { render() { var getProductData = id => $.grep(PRODUCTS, function(e){ return e.id === id }); var productData = getProductData(this.props.params.id)[0]; return ( <div> <Row> <Col className="col-md-7"> <Row id="icon"> <Col className="col-md-3 app-title"> <img alt="{productData.name}" src={productData.iconUrl} /> </Col> <Col className="col-md-9"> <h3 className="applicationName"> {productData.name} </h3> <p>{productData.shortDescription}</p> </Col> </Row> <div id="product-box"> <img alt="{productData.name}" src={"../" + productData.imageUrl} className="modal-content" id="img01"/> </div> <p/> {productData.description} <p/><h5 className="lead">Support</h5> <hr/> We provide support for this product without any charges. If you have any problems just submit a <a href="">ticket</a>. <p/> <h5 className="lead">Release notes</h5> <hr/> <b>VER. {productData.versionNo} ({productData.releaseDate.substring(0,10)})</b><br/> <p/><pre>Important bug fixes and interface improvements</pre> </Col> <Col className="col-md-4 sidebar-l sidebar-right hentry"> <div className="sidebar-right-box small"> <div className="price"> <b><span className="lead pull-left">Regular License</span></b> <span className=" amount lead">€180</span> </div> <p/> &#10003; Quality control <br/> &#10003; Future updates <br/>&#10003; 6 months support from HausTech <br /><a href=""><span className="small">What does support include?</span></a> <form action=""> <p/><input type="checkbox" name="extend-support" value="extend-yes"/> Extend support to 12 months <p/> <a role="button" className="btn btn-info btn-md btn-block btn-success" href={"/dl/" + productData.name + ".application"}>Launch</a> <button className="btn btn-info btn-md btn-block btn-primary"><span className="glyphicon glyphicon-shopping-cart"/> Buy Now</button> </form> </div> <div> <hr/> <table className="small"> <tbody> <tr> <td><b>Last Update</b></td> <td>23 August, 2016</td> </tr> <tr> <td><b>Created</b></td> <td>{productData.releaseDate.substring(0,10)}</td> </tr> <tr> <td><b>Compatible Platforms</b></td> <td>Microsoft Windows 9, 10<br/>OSX 10.10+</td> </tr> </tbody> </table> </div> </Col> </Row> </div> ); } }
analysis/demonhuntervengeance/src/modules/talents/SpiritBombSoulsConsume.js
anom0ly/WoWAnalyzer
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import BoringSpellValueText from 'parser/ui/BoringSpellValueText'; import Statistic from 'parser/ui/Statistic'; import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY'; import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER'; import React from 'react'; const MS_BUFFER = 100; class SpiritBombSoulsConsume extends Analyzer { get totalGoodCasts() { return this.soulsConsumedByAmount[4] + this.soulsConsumedByAmount[5]; } get totalCasts() { return Object.values(this.soulsConsumedByAmount).reduce((total, casts) => total + casts, 0); } get percentGoodCasts() { return this.totalGoodCasts / this.totalCasts; } get suggestionThresholdsEfficiency() { return { actual: this.percentGoodCasts, isLessThan: { minor: 0.9, average: 0.85, major: 0.8, }, style: 'percentage', }; } castTimestamp = 0; castSoulsConsumed = 0; cast = 0; soulsConsumedByAmount = Array.from({ length: 6 }, (x) => 0); /* Feed The Demon talent is taken in defensive builds. In those cases you want to generate and consume souls as quickly as possible. So how you consume your souls down matter. If you dont take that talent your taking a more balanced build meaning you want to consume souls in a way that boosts your dps. That means feeding the souls into spirit bomb as efficiently as possible (cast at 4+ souls) for a dps boost and have soul cleave absorb souls as little as possible since it provides no extra dps. */ constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.SPIRIT_BOMB_TALENT.id) && !this.selectedCombatant.hasTalent(SPELLS.FEED_THE_DEMON_TALENT.id); this.addEventListener( Events.cast.by(SELECTED_PLAYER).spell(SPELLS.SPIRIT_BOMB_TALENT), this.onCast, ); this.addEventListener( Events.changebuffstack.by(SELECTED_PLAYER).spell(SPELLS.SOUL_FRAGMENT_STACK), this.onChangeBuffStack, ); this.addEventListener(Events.fightend, this.onFightend); } onCast(event) { if (this.cast > 0) { this.countHits(); } this.castTimestamp = event.timestamp; this.cast += 1; } onChangeBuffStack(event) { if (event.oldStacks < event.newStacks) { return; } if (event.timestamp - this.castTimestamp < MS_BUFFER) { const soulsConsumed = event.oldStacks - event.newStacks; this.castSoulsConsumed += soulsConsumed; } } countHits() { if (!this.soulsConsumedByAmount[this.castSoulsConsumed]) { this.soulsConsumedByAmount[this.castSoulsConsumed] = 1; this.castSoulsConsumed = 0; return; } this.soulsConsumedByAmount[this.castSoulsConsumed] += 1; this.castSoulsConsumed = 0; } onFightend() { this.countHits(); } suggestions(when) { when(this.suggestionThresholdsEfficiency).addSuggestion((suggest, actual, recommended) => suggest( <> Try to cast <SpellLink id={SPELLS.SPIRIT_BOMB_TALENT.id} /> at 4 or 5 souls. </>, ) .icon(SPELLS.SPIRIT_BOMB_TALENT.icon) .actual( t({ id: 'demonhunter.vengeance.suggestions.spiritBomb.soulsConsumed', message: `${formatPercentage(this.percentGoodCasts)}% of casts at 4+ souls.`, }), ) .recommended(`>${formatPercentage(recommended)}% is recommended`), ); } statistic() { return ( <Statistic position={STATISTIC_ORDER.CORE(6)} category={STATISTIC_CATEGORY.TALENTS} size="flexible" dropdown={ <> <table className="table table-condensed"> <thead> <tr> <th>Stacks</th> <th>Casts</th> </tr> </thead> <tbody> {Object.values(this.soulsConsumedByAmount).map((castAmount, stackAmount) => ( <tr key={stackAmount}> <th>{stackAmount}</th> <td>{castAmount}</td> </tr> ))} </tbody> </table> </> } > <BoringSpellValueText spell={SPELLS.SPIRIT_BOMB_TALENT}> <> {formatPercentage(this.percentGoodCasts)}% <small>good casts</small> </> </BoringSpellValueText> </Statistic> ); } } export default SpiritBombSoulsConsume;
docs/src/Routes.js
wjb12/react-bootstrap
import React from 'react'; import Root from './Root'; import HomePage from './HomePage'; import IntroductionPage from './IntroductionPage'; import GettingStartedPage from './GettingStartedPage'; import ComponentsPage from './ComponentsPage'; import SupportPage from './SupportPage'; import NotFoundPage from './NotFoundPage'; import {Route, DefaultRoute, NotFoundRoute} from 'react-router'; export default ( <Route name="home" path="/" handler={Root}> <DefaultRoute handler={HomePage}/> <NotFoundRoute handler={NotFoundPage} /> <Route name="introduction" path="introduction.html" handler={IntroductionPage} /> <Route name="getting-started" path="getting-started.html" handler={GettingStartedPage} /> <Route name="components" path="components.html" handler={ComponentsPage} /> <Route name="support" path="support.html" handler={SupportPage} /> </Route> );
src/routes/Recover/components/EmailForm/EmailForm.js
ronihcohen/magic-vote
import React from 'react' import PropTypes from 'prop-types' import { Field, reduxForm } from 'redux-form' import { TextField } from 'redux-form-material-ui' import RaisedButton from 'material-ui/RaisedButton' import { required, email } from 'utils/forms' import { RECOVER_EMAIL_FORM_NAME } from 'constants' import classes from './EmailForm.scss' export const EmailForm = ({ account, handleSubmit, submitting, pristine, valid }) => ( <form className={classes.container} onSubmit={handleSubmit}> <h4>Send Recovery Code To Email</h4> <Field name="email" component={TextField} label="Email" validate={[required, email]} /> <div className={classes.submit}> <RaisedButton label="Send" primary type="submit" disabled={submitting} /> </div> </form> ) EmailForm.propTypes = { account: PropTypes.shape({ providerData: PropTypes.array }), pristine: PropTypes.bool, // added by redux-form valid: PropTypes.bool, // added by redux-form handleSubmit: PropTypes.func.isRequired, // added by redux-form submitting: PropTypes.bool // added by redux-form } export default reduxForm({ form: RECOVER_EMAIL_FORM_NAME })(EmailForm)
node_modules/react-navigation/src/routers/__tests__/StackRouter-test.js
aksharora/ReactNativeDemoBasic
/* @flow */ import React from 'react'; import StackRouter from '../StackRouter'; import TabRouter from '../TabRouter'; import NavigationActions from '../../NavigationActions'; const ListScreen = () => <div />; const ProfileNavigator = () => <div />; ProfileNavigator.router = StackRouter({ list: { path: 'list/:id', screen: ListScreen, }, }); const MainNavigator = () => <div />; MainNavigator.router = StackRouter({ profile: { path: 'p/:id', screen: ProfileNavigator, }, }); const LoginScreen = () => <div />; const AuthNavigator = () => <div />; AuthNavigator.router = StackRouter({ login: { screen: LoginScreen, }, }); const BarScreen = () => <div />; class FooNavigator extends React.Component { static router = StackRouter({ bar: { path: 'b/:barThing', screen: BarScreen, }, }); render() { return <div />; } } const PersonScreen = () => <div />; const TestStackRouter = StackRouter({ main: { screen: MainNavigator, }, auth: { screen: AuthNavigator, }, person: { path: 'people/:id', screen: PersonScreen, }, foo: { path: 'fo/:fooThing', screen: FooNavigator, }, }); describe('StackRouter', () => { test('Gets the active screen for a given state', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ foo: { screen: FooScreen, }, bar: { screen: BarScreen, }, }); expect(router.getComponentForState({ index: 0, routes: [ { key: 'a', routeName: 'foo' }, { key: 'b', routeName: 'bar' }, { key: 'c', routeName: 'foo' }, ], })).toBe(FooScreen); expect(router.getComponentForState({ index: 1, routes: [ { key: 'a', routeName: 'foo' }, { key: 'b', routeName: 'bar' }, ], })).toBe(BarScreen); }); test('Handles getScreen in getComponentForState', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ foo: { getScreen: () => FooScreen, }, bar: { getScreen: () => BarScreen, }, }); expect(router.getComponentForState({ index: 0, routes: [ { key: 'a', routeName: 'foo' }, { key: 'b', routeName: 'bar' }, { key: 'c', routeName: 'foo' }, ], })).toBe(FooScreen); expect(router.getComponentForState({ index: 1, routes: [ { key: 'a', routeName: 'foo' }, { key: 'b', routeName: 'bar' }, ], })).toBe(BarScreen); }); test('Gets the screen for given route', () => { const FooScreen = () => <div />; const BarScreen = class extends React.Component { render() { return <div />; } }; const BazScreen = React.createClass({ render() { return <div />; } }); const router = StackRouter({ foo: { screen: FooScreen, }, bar: { screen: BarScreen, }, baz: { screen: BazScreen, }, }); expect(router.getComponentForRouteName('foo')).toBe(FooScreen); expect(router.getComponentForRouteName('bar')).toBe(BarScreen); expect(router.getComponentForRouteName('baz')).toBe(BazScreen); }); test('Handles getScreen in getComponent', () => { const FooScreen = () => <div />; const BarScreen = class extends React.Component { render() { return <div />; } }; const BazScreen = React.createClass({ render() { return <div />; } }); const router = StackRouter({ foo: { getScreen: () => FooScreen, }, bar: { getScreen: () => BarScreen, }, baz: { getScreen: () => BazScreen, }, }); expect(router.getComponentForRouteName('foo')).toBe(FooScreen); expect(router.getComponentForRouteName('bar')).toBe(BarScreen); expect(router.getComponentForRouteName('baz')).toBe(BazScreen); }); test('Parses simple paths', () => { expect(AuthNavigator.router.getActionForPathAndParams('login')).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'login', }); }); test('Parses paths with a param', () => { expect(TestStackRouter.getActionForPathAndParams('people/foo')).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'person', params: { id: 'foo', }, }); }); test('Correctly parses a path without arguments into an action chain', () => { const uri = 'auth/login'; const action = TestStackRouter.getActionForPathAndParams(uri); expect(action).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'auth', action: { type: NavigationActions.NAVIGATE, routeName: 'login', }, }); }); test('Correctly parses a path with arguments into an action chain', () => { const uri = 'main/p/4/list/10259959195'; const action = TestStackRouter.getActionForPathAndParams(uri); expect(action).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'main', action: { type: NavigationActions.NAVIGATE, routeName: 'profile', params: { id: '4', }, action: { type: NavigationActions.NAVIGATE, routeName: 'list', params: { id: '10259959195', }, }, }, }); }); test('Correctly returns null action for non-existent path', () => { const uri = 'asdf/1234'; const action = TestStackRouter.getActionForPathAndParams(uri); expect(action).toEqual(null); }); test('Correctly returns action chain for partially matched path', () => { const uri = 'auth/login/2'; const action = TestStackRouter.getActionForPathAndParams(uri); expect(action).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'auth', action: { type: NavigationActions.NAVIGATE, routeName: 'login', }, }); }); test('Correctly returns action for path with multiple parameters', () => { const path = 'fo/22/b/hello'; const action = TestStackRouter.getActionForPathAndParams(path); expect(action).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'foo', params: { fooThing: '22', }, action: { type: NavigationActions.NAVIGATE, routeName: 'bar', params: { barThing: 'hello', }, }, }); }); test('Handle basic stack logic for plain components', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ Foo: { screen: FooScreen, }, Bar: { screen: BarScreen, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); expect(state).toEqual({ index: 0, routes: [ { key: 'Init', routeName: 'Foo', }, ], }); const state2 = router.getStateForAction({ type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { name: 'Zoom' } }, state); expect(state2 && state2.index).toEqual(1); expect(state2 && state2.routes[1].routeName).toEqual('Bar'); expect(state2 && state2.routes[1].params).toEqual({ name: 'Zoom' }); expect(state2 && state2.routes.length).toEqual(2); const state3 = router.getStateForAction({ type: NavigationActions.BACK }, state2); expect(state3).toEqual({ index: 0, routes: [ { key: 'Init', routeName: 'Foo', }, ], }); }); test('Handle basic stack logic for components with router', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; BarScreen.router = StackRouter({ Xyz: { screen: () => null, }, }); const router = StackRouter({ Foo: { screen: FooScreen, }, Bar: { screen: BarScreen, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); expect(state).toEqual({ index: 0, routes: [ { key: 'Init', routeName: 'Foo', }, ], }); const state2 = router.getStateForAction({ type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { name: 'Zoom' } }, state); expect(state2 && state2.index).toEqual(1); expect(state2 && state2.routes[1].routeName).toEqual('Bar'); expect(state2 && state2.routes[1].params).toEqual({ name: 'Zoom' }); expect(state2 && state2.routes.length).toEqual(2); const state3 = router.getStateForAction({ type: NavigationActions.BACK }, state2); expect(state3).toEqual({ index: 0, routes: [ { key: 'Init', routeName: 'Foo', }, ], }); }); test('Handle goBack identified by key', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ Foo: { screen: FooScreen, }, Bar: { screen: BarScreen, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction({ type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { name: 'Zoom' } }, state); const state3 = router.getStateForAction({ type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { name: 'Foo' } }, state2); const state4 = router.getStateForAction({ type: NavigationActions.BACK, key: 'wrongKey' }, state3); expect(state3).toEqual(state4); const state5 = router.getStateForAction({ type: NavigationActions.BACK, key: state3 && state3.routes[1].key }, state4); expect(state5).toEqual(state); }); test('Handle initial route navigation', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ Foo: { screen: FooScreen, }, Bar: { screen: BarScreen, }, }, { initialRouteName: 'Bar' }); const state = router.getStateForAction({ type: NavigationActions.INIT }); expect(state).toEqual({ index: 0, routes: [ { key: 'Init', routeName: 'Bar', }, ], }); }); test('Initial route params appear in nav state', () => { const FooScreen = () => <div />; const router = StackRouter({ Foo: { screen: FooScreen, }, }, { initialRouteName: 'Bar', initialRouteParams: { foo: 'bar' } }); const state = router.getStateForAction({ type: NavigationActions.INIT }); expect(state).toEqual({ index: 0, routes: [ { key: 'Init', routeName: 'Bar', params: { foo: 'bar' }, }, ], }); }); test('Action params appear in nav state', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ Foo: { screen: FooScreen, }, Bar: { screen: BarScreen, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction({ type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { bar: '42' } }, state); expect(state2).not.toBeNull(); expect(state2 && state2.index).toEqual(1); expect(state2 && state2.routes[1].params).toEqual({ bar: '42' }); }); test('Handles the SetParams action', () => { const router = StackRouter({ Foo: { screen: () => <div />, }, Bar: { screen: () => <div />, }, }, { initialRouteName: 'Bar', initialRouteParams: { name: 'Zoo' }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction({ type: NavigationActions.SET_PARAMS, params: { name: 'Qux' }, key: 'Init', }, state); expect(state2 && state2.index).toEqual(0); expect(state2 && state2.routes[0].params).toEqual({ name: 'Qux' }); }); test('Handles the reset action', () => { const router = StackRouter({ Foo: { screen: () => <div />, }, Bar: { screen: () => <div />, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction({ type: NavigationActions.RESET, actions: [{ type: NavigationActions.NAVIGATE, routeName: 'Foo', params: { bar: '42' } }, { type: NavigationActions.NAVIGATE, routeName: 'Bar' }], index: 1 }, state); expect(state2 && state2.index).toEqual(1); expect(state2 && state2.routes[0].params).toEqual({ bar: '42' }); expect(state2 && state2.routes[0].routeName).toEqual('Foo'); expect(state2 && state2.routes[1].routeName).toEqual('Bar'); }); test('Handles the reset action with nested Router', () => { const ChildRouter = TabRouter({ baz: { screen: () => <div />, }, }); const ChildNavigator = () => <div />; ChildNavigator.router = ChildRouter; const router = StackRouter({ Foo: { screen: ChildNavigator, }, Bar: { screen: () => <div />, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction({ type: NavigationActions.RESET, actions: [{ type: NavigationActions.NAVIGATE, routeName: 'Foo' }], index: 0 }, state); expect(state2 && state2.index).toEqual(0); expect(state2 && state2.routes[0].routeName).toEqual('Foo'); /* $FlowFixMe */ expect(state2 && state2.routes[0].routes[0].routeName).toEqual('baz'); }); test('Handles the navigate action with params and nested StackRouter', () => { const ChildNavigator = () => <div />; ChildNavigator.router = StackRouter({ Baz: { screen: () => <div /> } }); const router = StackRouter({ Foo: { screen: () => <div />, }, Bar: { screen: ChildNavigator, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction({ type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { foo: '42' } }, state); expect(state2 && state2.routes[1].params).toEqual({ foo: '42' }); /* $FlowFixMe */ expect(state2 && state2.routes[1].routes).toEqual([ { key: 'Init', routeName: 'Baz', params: { foo: '42' }, }, ]); }); test('Handles the navigate action with params and nested TabRouter', () => { const ChildNavigator = () => <div />; ChildNavigator.router = TabRouter({ Baz: { screen: () => <div /> }, Boo: { screen: () => <div /> }, }); const router = StackRouter({ Foo: { screen: () => <div />, }, Bar: { screen: ChildNavigator, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction({ type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { foo: '42' } }, state); expect(state2 && state2.routes[1].params).toEqual({ foo: '42' }); /* $FlowFixMe */ expect(state2 && state2.routes[1].routes).toEqual([ { key: 'Baz', routeName: 'Baz', params: { foo: '42' }, }, { key: 'Boo', routeName: 'Boo', params: { foo: '42' }, }, ]); }); test('Handles empty URIs', () => { const router = StackRouter({ Foo: { screen: () => <div />, }, Bar: { screen: () => <div />, }, }, { initialRouteName: 'Bar' }); const action = router.getActionForPathAndParams(''); expect(action).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'Bar' }); let state = null; if (action) { state = router.getStateForAction(action); } expect(state && state.index).toEqual(0); expect(state && state.routes[0]).toEqual({ key: 'Init', routeName: 'Bar' }); }); test('Maps old actions (uses "Handles the reset action" test)', () => { const router = StackRouter({ Foo: { screen: () => <div />, }, Bar: { screen: () => <div />, }, }); /* $FlowFixMe: these are for deprecated action names */ const state = router.getStateForAction({ type: 'Init' }); /* $FlowFixMe: these are for deprecated action names */ const state2 = router.getStateForAction({ type: 'Reset', actions: [{ type: 'Navigate', routeName: 'Foo', params: { bar: '42' } }, { type: 'Navigate', routeName: 'Bar' }], index: 1 }, state); expect(state2 && state2.index).toEqual(1); expect(state2 && state2.routes[0].params).toEqual({ bar: '42' }); expect(state2 && state2.routes[0].routeName).toEqual('Foo'); expect(state2 && state2.routes[1].routeName).toEqual('Bar'); }); });
src/articles/Single.js
NewSpring/Apollos
import React from 'react'; import { ScrollView } from 'react-native'; import { compose, mapProps, pure } from 'recompose'; import withArticle from '@data/withArticle'; import withCachedContent from '@data/withCachedContent'; import BackgroundView from '@ui/BackgroundView'; import Header from '@ui/Header'; import ContentView, { Title, ByLine, HTMLView } from '@ui/ContentView'; import RelatedContent from '@ui/RelatedContent'; import SecondaryNav, { Like, Share } from '@ui/SecondaryNav'; const enhance = compose( pure, mapProps(({ match: { params: { id } } }) => ({ id })), withArticle, withCachedContent, ); const ShareLink = withArticle(Share); const ArticleSingle = enhance( ({ content: { authors = [], title = '', content: { isLiked, body, tags, ...otherContentProps } = {}, } = {}, id, isLoading, }) => ( <BackgroundView> <Header titleText="Article" backButton /> <ScrollView> <ContentView isLoading={isLoading} {...otherContentProps}> <Title>{title}</Title> <ByLine authors={authors} /> <HTMLView>{body}</HTMLView> </ContentView> {// Don't render till data is ready. // Consider adding placeholder views for the content above. !isLoading && <RelatedContent tags={tags} excludedIds={[id]} />} </ScrollView> <SecondaryNav isLoading={isLoading} fullWidth> <ShareLink id={id} /> <Like id={id} isLiked={isLiked} /> </SecondaryNav> </BackgroundView> ), ); export default ArticleSingle;
frontend/app/js/components/settings/plugins/index.js
serverboards/serverboards
import React from 'react' import rpc from 'app/rpc' import Flash from 'app/flash' import PluginDetails from './details' import plugin from 'app/utils/plugin' import {merge, object_list_to_map} from 'app/utils' import event from 'app/utils/event' import i18n from 'app/utils/i18n' import {set_modal, goto} from 'app/utils/store' import store from 'app/utils/store' import cache from 'app/utils/cache' import PropTypes from 'prop-types' import {SectionMenu} from 'app/components' require('sass/cards.sass') import PluginCard from './card' class Plugins extends React.Component{ constructor(props){ super(props) this.state = { plugins: [], updates: {}, settings: {} } this.reload_plugin_list = this.reload_plugin_list.bind(this) } componentDidMount(){ event.on("plugins.reloaded", this.reload_plugin_list) this.load_plugin_list() } load_plugin_list(){ cache.plugins().then( pluginsd => { let plugins = Object.values(pluginsd) plugins = plugins.sort( (a,b) => (a.name || "").localeCompare(b.name || "") ) this.setState({plugins}) }).catch((e) => { Flash.error(`Could not load plugin list.\n ${e}`) }) plugin.call("serverboards.core.update/marketplace", "check_updates", []) .then( orig => { let updates = {} for (let o of orig){ updates[o.id] = o.updated } this.setState({updates}) }) rpc.call("plugin.component.catalog", {type: "settings"}) .then( formlist => { let settings = {} for (let f of formlist){ settings[f.plugin]=(settings[f.plugin] || []).concat(f) } this.setState({settings}) }) } reload_plugin_list(){ cache.invalidate("plugins") // ensure invalidated. May happen later too. Needed at the cache side too. this.load_plugin_list() } componentWillUnmount(){ event.off("plugins.reloaded", this.reload_plugin_list) } handleUpdate(id){ let updates = {...this.state.updates} updates[id] = "updating" this.setState({updates}) rpc.call("action.trigger", ["serverboards.core.update/update_plugin", {"plugin_id": id}]) .then( () => { this.reload_plugin_list.bind(this) Flash.success(i18n("Plugin updated successfully.")) }) .catch( Flash.error ) } render(){ const {plugins, settings, updates} = this.state return ( <div className="expand with scroll and padding"> <div className="ui container"> <div className="ui cards"> {plugins.map((p) => ( <PluginCard key={p.id} plugin={{...p, updated: updates[p.id]}} onUpdate={() => this.handleUpdate(p.id)} onOpenDetails={() => {set_modal('plugin.details',{plugin: p})}} onOpenSettings={settings[p.id] ? ( () => set_modal('plugin.settings',{plugin: p, settings: settings[p.id] }) ) : null } /> ))} </div> </div> </div> ) } } Plugins.contextTypes = { router: PropTypes.object } export default Plugins
test/CategorizedTagInput_spec.js
mvader/react-categorized-tag-input
import expect from 'expect'; import React from 'react'; import TestUtils from 'react-addons-test-utils'; import jsdomReact from './jsdomReact'; import CategorizedTagInput from '../src/CategorizedTagInput.jsx'; describe('CategorizedTagInput', () => { jsdomReact(); });
modules/__tests__/transitionHooks-test.js
dmitrigrabov/react-router
/*eslint-env mocha */ /*eslint react/prop-types: 0*/ import expect, { spyOn } from 'expect' import React from 'react' import createHistory from 'history/lib/createMemoryHistory' import execSteps from './execSteps' import Router from '../Router' describe('When a router enters a branch', function () { let node, Dashboard, NewsFeed, Inbox, DashboardRoute, NewsFeedRoute, InboxRoute, RedirectToInboxRoute, MessageRoute, routes beforeEach(function () { node = document.createElement('div') Dashboard = React.createClass({ render() { return ( <div className="Dashboard"> <h1>The Dashboard</h1> {this.props.children} </div> ) } }) NewsFeed = React.createClass({ render() { return <div>News</div> } }) Inbox = React.createClass({ render() { return <div>Inbox</div> } }) NewsFeedRoute = { path: 'news', component: NewsFeed, onEnter(nextState, replaceState) { expect(this).toBe(NewsFeedRoute) expect(nextState.routes).toContain(NewsFeedRoute) expect(replaceState).toBeA('function') }, onLeave() { expect(this).toBe(NewsFeedRoute) } } InboxRoute = { path: 'inbox', component: Inbox, onEnter(nextState, replaceState) { expect(this).toBe(InboxRoute) expect(nextState.routes).toContain(InboxRoute) expect(replaceState).toBeA('function') }, onLeave() { expect(this).toBe(InboxRoute) } } RedirectToInboxRoute = { path: 'redirect-to-inbox', onEnter(nextState, replaceState) { expect(this).toBe(RedirectToInboxRoute) expect(nextState.routes).toContain(RedirectToInboxRoute) expect(replaceState).toBeA('function') replaceState(null, '/inbox') }, onLeave() { expect(this).toBe(RedirectToInboxRoute) } } MessageRoute = { path: 'messages/:messageID', onEnter(nextState, replaceState) { expect(this).toBe(MessageRoute) expect(nextState.routes).toContain(MessageRoute) expect(replaceState).toBeA('function') }, onLeave() { expect(this).toBe(MessageRoute) } } DashboardRoute = { component: Dashboard, onEnter(nextState, replaceState) { expect(this).toBe(DashboardRoute) expect(nextState.routes).toContain(DashboardRoute) expect(replaceState).toBeA('function') }, onLeave() { expect(this).toBe(DashboardRoute) }, childRoutes: [ NewsFeedRoute, InboxRoute, RedirectToInboxRoute, MessageRoute ] } routes = [ DashboardRoute ] }) afterEach(function () { React.unmountComponentAtNode(node) }) it('calls the onEnter hooks of all routes in that branch', function (done) { const dashboardRouteEnterSpy = spyOn(DashboardRoute, 'onEnter').andCallThrough() const newsFeedRouteEnterSpy = spyOn(NewsFeedRoute, 'onEnter').andCallThrough() React.render(<Router history={createHistory('/news')} routes={routes}/>, node, function () { expect(dashboardRouteEnterSpy).toHaveBeenCalled() expect(newsFeedRouteEnterSpy).toHaveBeenCalled() done() }) }) describe('and one of the transition hooks navigates to another route', function () { it('immediately transitions to the new route', function (done) { const redirectRouteEnterSpy = spyOn(RedirectToInboxRoute, 'onEnter').andCallThrough() const redirectRouteLeaveSpy = spyOn(RedirectToInboxRoute, 'onLeave').andCallThrough() const inboxEnterSpy = spyOn(InboxRoute, 'onEnter').andCallThrough() React.render(<Router history={createHistory('/redirect-to-inbox')} routes={routes}/>, node, function () { expect(this.state.location.pathname).toEqual('/inbox') expect(redirectRouteEnterSpy).toHaveBeenCalled() expect(redirectRouteLeaveSpy.calls.length).toEqual(0) expect(inboxEnterSpy).toHaveBeenCalled() done() }) }) }) describe('and then navigates to another branch', function () { it('calls the onLeave hooks of all routes in the previous branch that are not in the next branch', function (done) { const dashboardRouteLeaveSpy = spyOn(DashboardRoute, 'onLeave').andCallThrough() const inboxRouteEnterSpy = spyOn(InboxRoute, 'onEnter').andCallThrough() const inboxRouteLeaveSpy = spyOn(InboxRoute, 'onLeave').andCallThrough() const steps = [ function () { expect(inboxRouteEnterSpy).toHaveBeenCalled('InboxRoute.onEnter was not called') this.history.pushState(null, '/news') }, function () { expect(inboxRouteLeaveSpy).toHaveBeenCalled('InboxRoute.onLeave was not called') expect(dashboardRouteLeaveSpy.calls.length).toEqual(0, 'DashboardRoute.onLeave was called') } ] const execNextStep = execSteps(steps, done) React.render( <Router history={createHistory('/inbox')} routes={routes} onUpdate={execNextStep} />, node, execNextStep) }) }) describe('and then navigates to the same branch, but with different params', function () { it('calls the onLeave and onEnter hooks of all routes whose params have changed', function (done) { const dashboardRouteLeaveSpy = spyOn(DashboardRoute, 'onLeave').andCallThrough() const dashboardRouteEnterSpy = spyOn(DashboardRoute, 'onEnter').andCallThrough() const messageRouteLeaveSpy = spyOn(MessageRoute, 'onLeave').andCallThrough() const messageRouteEnterSpy = spyOn(MessageRoute, 'onEnter').andCallThrough() const steps = [ function () { expect(dashboardRouteEnterSpy).toHaveBeenCalled('DashboardRoute.onEnter was not called') expect(messageRouteEnterSpy).toHaveBeenCalled('InboxRoute.onEnter was not called') this.history.pushState(null, '/messages/456') }, function () { expect(messageRouteLeaveSpy).toHaveBeenCalled('MessageRoute.onLeave was not called') expect(messageRouteEnterSpy).toHaveBeenCalled('MessageRoute.onEnter was not called') expect(dashboardRouteLeaveSpy.calls.length).toEqual(0, 'DashboardRoute.onLeave was called') } ] const execNextStep = execSteps(steps, done) React.render( <Router history={createHistory('/messages/123')} routes={routes} onUpdate={execNextStep} />, node, execNextStep) }) }) })
1m_Redux_Lynda/Ex_Files_Learning_Redux/Exercise Files/Ch05/05_03/finished/src/index.js
yevheniyc/C
import C from './constants' import React from 'react' import { render } from 'react-dom' import routes from './routes' import sampleData from './initialState' import storeFactory from './store' import { Provider } from 'react-redux' import { addError } from './actions' const initialState = (localStorage["redux-store"]) ? JSON.parse(localStorage["redux-store"]) : sampleData const saveState = () => localStorage["redux-store"] = JSON.stringify(store.getState()) const handleError = error => { store.dispatch( addError(error.message) ) } const store = storeFactory(initialState) store.subscribe(saveState) window.React = React window.store = store window.addEventListener("error", handleError) render( <Provider store={store}> {routes} </Provider>, document.getElementById('react-container') )
src/react.js
joshblack/redux
import React from 'react'; import createAll from './components/createAll'; export const { Provider, Connector, provide, connect } = createAll(React);
src/__tests__/Popup.js
snario/react-mapbox-gl
import React from 'react'; jest.dontMock('../BaseTileLayer'); jest.dontMock('../MapComponent'); jest.dontMock('../MapLayer'); jest.dontMock('../PopupContainer'); jest.dontMock('../Map'); jest.dontMock('../Marker'); jest.dontMock('../Popup'); jest.dontMock('../TileLayer'); jest.dontMock('../index'); const {Map, Marker, Popup, TileLayer} = require('../'); describe('Popup', () => { it('adds the popup to the map', () => { const position = [0, 0]; const component = <Map center={position} zoom={10}> <TileLayer url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' /> <Popup position={position}> <span>Test Popup</span> </Popup> </Map>; document.body.innerHTML = '<div id="test"></div>'; React.render(component, document.getElementById('test')); expect(document.querySelector('#test .leaflet-popup-content span').textContent).toBe('Test Popup'); }); it('adds and removes the popup on the map', () => { const getNode = () => { return document.querySelector('#test .leaflet-popup-content span'); }; class Component extends React.Component { constructor() { super(); this.state = { show: false, test: true }; } componentDidMount() { expect(getNode()).toBe(null); this.setState({show: true}); } componentDidUpdate() { if (this.state.test) { expect(getNode()).toBeDefined(); this.setState({ show: false, test: false }); } else { expect(getNode()).toBe(null); } } render() { const position = [0, 0]; const popup = this.state.show ? <Popup position={position}> <span>Test Popup</span> </Popup> : null; return ( <Map ref='map' center={position} zoom={10}> <TileLayer url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' /> {popup} </Map> ); } } document.body.innerHTML = '<div id="test"></div>'; React.render(<Component />, document.getElementById('test')); }); });
src/components/about.js
MichaelMansourati/earCamera
import React from 'react' import { Helmet } from 'react-helmet' import '../styles/about.css' const About = () => ( <div className="page-goes-here" id="about"> <Helmet> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous" /> </Helmet> <div className="textArea"> <p> Ear Camera is a collective of bodies creating cochlear art. We are a capillary community, a neural network, an ear that listens, a camerata of peers. Our concerts are a living snapshot of our inner chambers developed in dark rooms and focused onto vibrating membranes. We are a lens that reflects the society in which we live. We believe that all human experience, rendered in photorealistic detail, is worthy of amplification. </p> <p> <span>Ear Camera is: </span> <a target="_blank" href="http://www.tommysaxophone.com"> Tommy Davis </a> <span> // </span> <a target="_blank" href="https://www.indiayeshe.com"> India Gailey </a> <span> // </span> <a target="_blank" href="http://www.jglasermusic.com"> Joseph Glaser </a> <span> // </span> <a target="_blank" href="https://soundcloud.com/noa-haran"> Noa Haran </a> <span> // </span> <a target="_blank" href="https://soundcloud.com/justin-jaramillo-7"> Justin Jaramillo </a> <span> // </span> <a target="_blank" href="https://soundcloud.com/michaelkimsheng"> Michael Kim-Sheng </a> <span> // </span> <a target="_blank" href="http://michaelmansourati.com"> Michael Mansourati </a> <span> // </span> <a target="_blank" href="http://www.jamesrubinomusic.com"> James Rubino </a> <span> // </span> <a target="_blank" href="https://www.soundcloud.com/keithstratton"> Keith Stratton </a> </p> <p> <a target="_blank" href="https://www.facebook.com/EarCamera/"> <i className="fa fa-facebook-official" aria-hidden="true" /> </a> <span className="faSlash"> // </span> <a target="_blank" href="https://www.instagram.com/ear_camera"> <i className="fa fa-instagram" aria-hidden="true" /> </a> <span className="faSlash"> // </span> <a target="_blank" href="https://twitter.com/earCamera"> <i className="fa fa-twitter" aria-hidden="true" /> </a> <span className="faSlash"> // </span> <a href="mailto:mail@ear.camera"> <i className="fa fa-envelope-o" aria-hidden="true" /> </a> </p> <p> Logo by <a href="https://www.kasiasuro.com">Kasia Suro</a>. </p> </div> <div className="yt-container"> <iframe className="youtube" id="about-yt" width="560px" height="315px" src="https://www.youtube.com/embed/65dl6LzR1ec" frameBorder="0" allowFullScreen /> </div> </div> ) export default About
fixtures/kitchensink/src/features/webpack/UnknownExtInclusion.js
saschatimme/reason-react-scripts
/** * 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 aFileWithExtUnknown from './assets/aFileWithExt.unknown' const text = aFileWithExtUnknown.includes('base64') ? atob(aFileWithExtUnknown.split('base64,')[1]).trim() : aFileWithExtUnknown export default () => ( <p id="feature-unknown-ext-inclusion">{text}.</p> )
frontend/sections/timeline/explore/explore.js
apostolidhs/wiregoose
import isEmpty from 'lodash/isEmpty'; import React from 'react'; import PropTypes from 'prop-types'; import CSSModules from 'react-css-modules'; import { LinkContainer } from 'react-router-bootstrap'; import Nav from 'react-bootstrap/lib/Nav'; import NavItem from 'react-bootstrap/lib/NavItem'; import Panel from 'react-bootstrap/lib/Panel'; import Row from 'react-bootstrap/lib/Row'; import Col from 'react-bootstrap/lib/Col'; import FontAwesome from 'react-fontawesome'; import { Link } from 'react-router'; import styles from '../timeline.less'; import { publish } from '../../../components/events/events.js'; import Header from '../../../components/timeline/header.js'; import Timeline from '../../../components/timeline/timeline.js'; import TimelinePage from '../../../components/timeline/page.js'; import InfiniteScrollPage from '../../../components/infinite-scroll/page.js'; import * as WiregooseApi from '../../../components/services/wiregoose-api.js'; import {createResponseHandler, composeCachedResponse} from '../../../components/offline-mode/cached-explore-timeline.js'; import BrowserLanguageDetection from '../../../components/utilities/browser-language-detection.js'; import tr from '../../../components/localization/localization.js'; @CSSModules(styles, { allowMultiple: true, }) export default class Explore extends InfiniteScrollPage { static page = new TimelinePage(); state = {} timeline = undefined // ref componentDidMount() { this.cachedResponseHandler = createResponseHandler(); Explore.page.componentDidMount(this); super.componentDidMount(); } componentWillUnmount() { super.componentWillUnmount(); Explore.page.componentWillUnmount(); if (this.state.cachedResponsePromise) { Explore.page.invalidateCache(); } } retrieveTimeline = () => { if (this.state.cachedResponsePromise) { return Promise.resolve({data: { data: {} }});; } return WiregooseApi.timeline.explore( Explore.page.lastFeeds, BrowserLanguageDetection(), { onOffline: () => { if (isEmpty(Explore.page.virtualList)) { const cachedResp = composeCachedResponse(); const cachedResponsePromise = cachedResp && Promise.resolve(cachedResp); this.setState({cachedResponsePromise}); return cachedResponsePromise; } } } ) .then(resp => this.cachedResponseHandler(resp)); } handleMetaData = () => { publish('page-ready', { title: tr.timelineExploreTitle, keywords: tr.timelineExploreKeywords, description: tr.timelineExploreDescription // image: // time: // lang: }); } onScroll = () => { Explore.page.onScroll(this); } renderCachedContentNotification() { return ( <Panel> <Row> <Col sm={1}> <h1 className="text-center w-m-0"> <FontAwesome name="wifi" className="text-warning" /> </h1> </Col> <Col sm={11}> <strong>{tr.offlineModeTitle}</strong> <p> {tr.offlineModeDescription} {' '} {tr.or} {' '} <a href="#" title={tr.refresh} onClick={evt => {evt.preventDefault(); location.reload()}}> {tr.refresh} </a> </p> </Col> </Row> </Panel> ); } render() { return ( <div> <Header> <Nav bsStyle="pills" activeKey={1}> <LinkContainer to="/"> <NavItem eventKey={1}>{tr.explore}</NavItem> </LinkContainer> </Nav> </Header> {this.state.cachedResponsePromise && this.renderCachedContentNotification() } <Timeline ref={(ref) => this.timeline = ref} /> </div> ); } }
docs/src/sections/ReferListSection.js
tigerandgirl/ssc-refer
import React from 'react'; import PropTable from '../PropTable'; import Anchor from '../Anchor'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function ReferListSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="referlist">参照组件(列表参照组件)</Anchor> <small><code>&lt;ReferList&gt;</code></small> </h2> <h3><Anchor id="refer-list">列表参照组件</Anchor></h3> <p>使用<code>referDataUrl</code>设置数据源地地。</p> <p>使用<code>referConditions</code>设置数据请求的参数,详见属性说明</p> <p>使用<code>defaultSelected</code>设置默认值,值为一个json数组,当是单选时只有一个item,设置为多选时为多个</p> <p>需要引用本模块样式,如<code>import 'ssc-refer/css/referStyle.css';</code></p> <ReactPlayground codeText={Samples.ReferList} /> </div> ); }
src/containers/search_result_list.js
etchoi/theTenSpot
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import axios from 'axios'; import { showItem } from '../actions'; class SearchResultList extends Component { formatPrice(str) { let price = parseInt(str); return (price/100).toFixed(2); } renderResult(resultData) { return _.map(resultData, data => { const id = data.ASIN[0]; return ( <li key={data.ASIN[0]} onClick={this.showItem.bind(this, id)} className="search-list-item"> <div className="row"> <img className="col s3" src={data.SmallImage[0].URL[0]} /> <h6 className="col s9">{data.ItemAttributes[0].Title[0]}</h6> { data.ItemAttributes[0].ListPrice[0].Amount[0] ? ( <p>{'$'+this.formatPrice(data.ItemAttributes[0].ListPrice[0].Amount[0])}</p> ) : ( <p>No Price</p> )} <p>{data.SalesRank}</p> </div> </li> ); }) } render() { return ( <ul className="search-list col s4"> {this.renderResult(this.props.search_result)} </ul> ) } showItem(id) { this.props.dispatch(showItem(id)) } renderImage() { // HERE HERE HERE } } function mapStateToProps({ search_result }) { return { search_result }; } export default connect(mapStateToProps)(SearchResultList);
webpack/scenes/Subscriptions/components/SubscriptionsToolbar/SubscriptionsToolbar.js
mccun934/katello
import React from 'react'; import PropTypes from 'prop-types'; import { Row, Col, Form, FormGroup, Button } from 'patternfly-react'; import { LinkContainer } from 'react-router-bootstrap'; import { noop } from 'foremanReact/common/helpers'; import { translate as __ } from 'foremanReact/common/I18n'; import Search from '../../../../components/Search/index'; import TooltipButton from '../../../../move_to_pf/TooltipButton'; import OptionTooltip from '../../../../move_to_pf/OptionTooltip'; const SubscriptionsToolbar = ({ canManageSubscriptionAllocations, disableManifestActions, disableManifestReason, disableDeleteButton, disableDeleteReason, disableAddButton, getAutoCompleteParams, updateSearchQuery, onDeleteButtonClick, onSearch, onManageManifestButtonClick, onExportCsvButtonClick, tableColumns, toolTipOnChange, toolTipOnclose, }) => ( <Row className="toolbar-pf table-view-pf-toolbar-external"> <Col sm={12}> <Form className="toolbar-pf-actions"> <FormGroup className="toolbar-pf-filter"> <Search onSearch={onSearch} getAutoCompleteParams={getAutoCompleteParams} updateSearchQuery={updateSearchQuery} /> </FormGroup> <div className="option-tooltip-container"> <OptionTooltip options={tableColumns} icon="fa-columns" id="subscriptionTableTooltip" onChange={toolTipOnChange} onClose={toolTipOnclose} /> </div> <div className="toolbar-pf-action-right"> <FormGroup> {canManageSubscriptionAllocations && <LinkContainer to="subscriptions/add" disabled={disableManifestActions || disableAddButton} > <TooltipButton tooltipId="add-subscriptions-button-tooltip" tooltipText={disableManifestReason} tooltipPlacement="top" title={__('Add Subscriptions')} disabled={disableManifestActions} bsStyle="primary" /> </LinkContainer> } <Button onClick={onManageManifestButtonClick}> {__('Manage Manifest')} </Button> <Button onClick={onExportCsvButtonClick} > {__('Export CSV')} </Button> {canManageSubscriptionAllocations && <TooltipButton bsStyle="danger" onClick={onDeleteButtonClick} tooltipId="delete-subscriptions-button-tooltip" tooltipText={disableDeleteReason} tooltipPlacement="top" title={__('Delete')} disabled={disableManifestActions || disableDeleteButton} /> } </FormGroup> </div> </Form> </Col> </Row> ); SubscriptionsToolbar.propTypes = { ...Search.propTypes, tableColumns: OptionTooltip.propTypes.options, canManageSubscriptionAllocations: PropTypes.bool, disableManifestActions: PropTypes.bool, disableManifestReason: PropTypes.string, disableDeleteButton: PropTypes.bool, disableDeleteReason: PropTypes.string, disableAddButton: PropTypes.bool, onDeleteButtonClick: PropTypes.func, onManageManifestButtonClick: PropTypes.func, onExportCsvButtonClick: PropTypes.func, toolTipOnChange: PropTypes.func, toolTipOnclose: PropTypes.func, }; SubscriptionsToolbar.defaultProps = { ...Search.defaultProps, tableColumns: [], disableManifestActions: false, disableManifestReason: '', disableDeleteButton: false, disableDeleteReason: '', disableAddButton: false, onDeleteButtonClick: noop, onManageManifestButtonClick: noop, onExportCsvButtonClick: noop, toolTipOnChange: noop, toolTipOnclose: noop, }; export default SubscriptionsToolbar;
src/components/Home/break.js
pritchardtw/ReactPersonalSite
import React, { Component } from 'react'; export default class Break extends Component { render() { return ( <div className="break"> </div> ); } }
frontend/src/clue.js
wadobo/socializa
import React from 'react'; import { withRouter } from 'react-router'; import Purifier from 'html-purify'; import { user, getIcon } from './auth'; import Bucket from './bucket'; import Loading from './loading'; import API from './api'; import { EventSolveOpt } from './eventsolve'; import { ResolvableComponent } from './eventsolve'; import { translate } from 'react-i18next'; class ClueItemB extends ResolvableComponent { state = { clue: null, state: 'normal', solution: null, step: 0, } clueChange = (e) => { this.setState({solution: e.target.value}); } componentDidMount() { var clue = this.props.clue; this.setState({ clue: clue }); } solve = (solution) => { const { t } = this.props; var self = this; this.setState({ state: 'solving' }); API.solve_clue(this.state.clue.pk, solution) .then(function(resp) { if (resp.status == 'correct') { var c = self.state.clue; alert(t('events::Conglatulations!')); if (resp.clues.length) { self.props.newClues(resp.clues); } else { c.status = 'solved'; c.solution = solution; self.setState({ clue: c, state: 'normal' }); } } else { self.setState({ state: 'normal' }); alert(t('events::Wrong answer. Try again')); } }).catch(function(err) { self.setState({ state: 'normal' }); alert(t('common::Unknown error')); }); } getField = () => { return this.state.clue; } render() { const { t } = this.props; var self = this; function createMarkup() { var purifier = new Purifier(); var input = self.state.clue.challenge.desc; var result = purifier.purify(input); return {__html: result }; } return ( <div> { this.state.clue ? <div className="clue"> <h1>{ this.state.clue.challenge.name }</h1> <div dangerouslySetInnerHTML={ createMarkup() } /> { this.state.clue.status == 'solved' ? <p className="text-success">{ this.state.clue.solution }</p> : <div> { this.state.clue.solution ? this.renderState() : <span></span> } { this.state.state == 'solving' ? <Loading /> : <span></span> } </div> } </div> : <Loading /> } </div> ); } } export let ClueItem = translate(['event', 'clue'], { wait: true })(withRouter(ClueItemB)); class Clue extends React.Component { state = { clues: [], } componentDidMount() { this.setState({clues: Bucket.clues}); } goBack = () => { this.props.history.push('/map'); } viewEvent = () => { this.props.history.push('/event/' + user.activeEvent.pk); } newClues = (clues) => { this.setState({'clues': clues}); } render() { const { t } = this.props; var self = this; return ( <div id="clue" className="container mbottom"> { this.state.clues.map(function(c, i) { return <ClueItem key={c.pk} clue={c} newClues={self.newClues.bind(self)}/>; }) } <button className="btn btn-primary btn-fixed-bottom-left" onClick={ this.goBack }>{t('clue::Map')}</button> <button className="btn btn-success btn-fixed-bottom-right" onClick={ this.viewEvent }>{t('clue::Event')}</button> </div> ); } } export default Clue = translate(['event', 'clue'], { wait: true })(withRouter(Clue));
src/index.js
spirosikmd/reflow
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; const root = document.getElementById('root'); ReactDOM.render(<App />, root); if (module.hot) { module.hot.accept('./App', () => { const NextApp = require('./App').default; ReactDOM.render(<NextApp />, root); }); }
src/give/AddAccount/Failure.js
NewSpring/Apollos
import React from 'react'; import PropTypes from 'prop-types'; import styled from '@ui/styled'; import PaddedView from '@ui/PaddedView'; import Icon from '@ui/Icon'; import { H3, H4, BodyText } from '@ui/typography'; import { withTheme } from '@ui/theme'; import Button, { ButtonLink } from '@ui/Button'; import WebBrowser from '@ui/WebBrowser'; import Paragraph from '@ui/Paragraph'; import { Link } from '@ui/NativeWebRouter'; const contact = () => WebBrowser.openBrowserAsync('https://rock.newspring.cc/workflows/152?Topic=Stewardship'); const BackgroundView = styled(({ theme }) => ({ backgroundColor: theme.colors.background.paper, justifyContent: 'center', alignItems: 'center', paddingTop: theme.sizing.baseUnit * 3, }))(PaddedView); const ThemedIcon = withTheme(({ theme }) => ({ size: theme.sizing.baseUnit * 3, fill: theme.colors.alert, }))(Icon); const Heading = styled(({ theme }) => ({ color: theme.colors.alert, paddingTop: theme.sizing.baseUnit, }))(H3); const SubHeading = styled(({ theme }) => ({ color: theme.colors.text.secondary, paddingBottom: theme.sizing.baseUnit, textAlign: 'center', }))(H4); const Failure = ({ paymentFailedMessage }) => ( <BackgroundView> <ThemedIcon name="circle-outline-x-mark" /> <Heading>Uh Oh!</Heading> <SubHeading>Looks like there was a problem adding your payment method.</SubHeading> {paymentFailedMessage ? ( <Paragraph><BodyText>{paymentFailedMessage}</BodyText></Paragraph> ) : null} <Paragraph> <Link pop> <Button title="Try Again" /> </Link> </Paragraph> <Paragraph> <BodyText italic> If you would like a member of our customer support team to follow up with you regarding this error, please{' '} <ButtonLink onPress={contact}>contact us</ButtonLink> {' '}and someone will be happy to assist you. </BodyText> </Paragraph> </BackgroundView> ); Failure.propTypes = { paymentFailedMessage: PropTypes.string, }; export default Failure;
server/sonar-web/src/main/js/apps/overview/main/main.js
vamsirajendra/sonarqube
import _ from 'underscore'; import moment from 'moment'; import React from 'react'; import { GeneralDebt } from './debt'; import { GeneralCoverage } from './coverage'; import { GeneralDuplications } from './duplications'; import { GeneralStructure } from './structure'; import { CoverageSelectionMixin } from '../components/coverage-selection-mixin'; import { getPeriodLabel, getPeriodDate } from './../helpers/periods'; import { getMeasuresAndVariations } from '../../../api/measures'; import { getIssuesCount } from '../../../api/issues'; import { getTimeMachineData } from '../../../api/time-machine'; const METRICS_LIST = [ 'sqale_rating', 'overall_coverage', 'new_overall_coverage', 'coverage', 'new_coverage', 'it_coverage', 'new_it_coverage', 'tests', 'duplicated_lines_density', 'duplicated_blocks', 'ncloc', 'ncloc_language_distribution' ]; const HISTORY_METRICS_LIST = [ 'sqale_index', 'duplicated_lines_density', 'ncloc' ]; export default React.createClass({ propTypes: { leakPeriodIndex: React.PropTypes.string.isRequired }, mixins: [CoverageSelectionMixin], getInitialState() { return { ready: false, history: {}, leakPeriodLabel: getPeriodLabel(this.props.component.periods, this.props.leakPeriodIndex), leakPeriodDate: getPeriodDate(this.props.component.periods, this.props.leakPeriodIndex) }; }, componentDidMount() { Promise.all([ this.requestMeasures(), this.requestIssuesAndDebt(), this.requestLeakIssuesAndDebt() ]).then(responses => { let measures = this.getMeasuresValues(responses[0], 'value'); measures.issues = responses[1].issues; measures.debt = responses[1].debt; let leak; if (this.state.leakPeriodDate) { leak = this.getMeasuresValues(responses[0], 'var' + this.props.leakPeriodIndex); leak.issues = responses[2].issues; leak.debt = responses[2].debt; } this.setState({ ready: true, measures: measures, leak: leak, coverageMetricPrefix: this.getCoverageMetricPrefix(measures) }, this.requestHistory); }); }, requestMeasures () { return getMeasuresAndVariations(this.props.component.key, METRICS_LIST); }, getMeasuresValues (measures, fieldKey) { let values = {}; Object.keys(measures).forEach(measureKey => { values[measureKey] = measures[measureKey][fieldKey]; }); return values; }, requestIssuesAndDebt() { // FIXME requesting severities facet only to get debtTotal return getIssuesCount({ componentUuids: this.props.component.id, resolved: 'false', facets: 'severities' }); }, requestLeakIssuesAndDebt() { if (!this.state.leakPeriodDate) { return Promise.resolve(); } let createdAfter = moment(this.state.leakPeriodDate).format('YYYY-MM-DDTHH:mm:ssZZ'); // FIXME requesting severities facet only to get debtTotal return getIssuesCount({ componentUuids: this.props.component.id, createdAfter: createdAfter, resolved: 'false', facets: 'severities' }); }, requestHistory () { let coverageMetric = this.state.coverageMetricPrefix + 'coverage'; let metrics = [].concat(HISTORY_METRICS_LIST, coverageMetric).join(','); return getTimeMachineData(this.props.component.key, metrics).then(r => { let history = {}; r[0].cols.forEach((col, index) => { history[col.metric] = r[0].cells.map(cell => { let date = moment(cell.d).toDate(); let value = cell.v[index] || 0; return { date, value }; }); }); let historyStartDate = history[HISTORY_METRICS_LIST[0]][0].date; this.setState({ history, historyStartDate }); }); }, renderLoading () { return <div className="text-center"> <i className="spinner spinner-margin"/> </div>; }, render() { if (!this.state.ready) { return this.renderLoading(); } let coverageMetric = this.state.coverageMetricPrefix + 'coverage'; let props = _.extend({}, this.props, this.state); return <div className="overview-domains-list"> <GeneralDebt {...props} history={this.state.history['sqale_index']}/> <GeneralCoverage {...props} coverageMetricPrefix={this.state.coverageMetricPrefix} history={this.state.history[coverageMetric]}/> <GeneralDuplications {...props} history={this.state.history['duplicated_lines_density']}/> <GeneralStructure {...props} history={this.state.history['ncloc']}/> </div>; } });
src/routes/contact/Contact.js
stanxii/laiico
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Contact.css'; class Contact extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>{this.props.title}</h1> <p>...</p> </div> </div> ); } } export default withStyles(s)(Contact);
src/main.js
EragonJ/Kaku
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import Electron, { ipcRenderer as IpcRenderer, shell as Shell, remote as Remote, } from 'electron'; const Dialog = Remote.dialog; const App = Remote.app; import ReactTooltip from 'react-tooltip'; // general modules import ErrorMonitor from './modules/ErrorMonitor'; ErrorMonitor.init(); import PreferenceManager from './modules/PreferenceManager'; import TrackInfoFetcher from 'kaku-core/modules/TrackInfoFetcher'; import PlaylistManager from './modules/PlaylistManager'; import L10nManager from './modules/L10nManager'; import TopRanking from 'kaku-core/modules/TopRanking'; import AppCore from './modules/AppCore'; import Searcher from './modules/Searcher'; import AutoUpdater from './modules/AutoUpdater'; import Tracker from './modules/Tracker'; const _ = L10nManager.get.bind(L10nManager); // views > components import ToolbarComponent from './views/components/toolbar'; import TopRankingComponent from './views/components/topranking'; import NewsComponent from './views/components/news'; import AllTracksComponent from './views/components/alltracks'; import PlayerComponent from './views/components/player'; import MenusComponent from './views/components/menus'; import HistoryComponent from './views/components/history'; import PlayQueueComponent from './views/components/play-queue'; import PlaylistComponent from './views/components/playlist'; import SettingsComponent from './views/components/settings'; import OnlineDJComponent from './views/components/online-dj'; import AboutComponent from './views/components/about'; import ChatroomComponent from './views/components/chatroom'; import ConnectionCheckComponent from './views/components/connection-check'; // views > modules import TabManager from './views/modules/TabManager'; import RemotePlayer from './views/modules/RemotePlayer'; import CastingManager from './views/modules/CastingManager'; import KonamiCodeManager from './views/modules/KonamiCodeManager'; import EasterEggs from './views/modules/EasterEggs'; import AppTouchBar from './views/modules/AppTouchBar'; import AppMenus from './views/modules/AppMenus'; import AppTray from './views/modules/AppTray'; import Player from './views/modules/Player'; import Notifier from './views/modules/Notifier'; const loadingPageDOM = document.querySelector('.loading-page'); const contentPageDOM = document.querySelector('.content-page'); class KakuApp extends Component { componentWillMount() { AppMenus.build(); AppTray.build(); AppTouchBar.build(); window.addEventListener('beforeunload', () => { AppTray.destroy(); AppTouchBar.destroy(); }); // this should be run first this._initializeDefaultTopRanking(); // TODO // Need to figure out why `Loading` showing up so slowly setTimeout(() => { this._hideLoadingPage(); this._triggerAutoUpdater(); }, 3000); } componentDidMount() { this._bindShortcutEvents(); this._bindTrayEvents(); this._bindPlayerEvents(); this._initializeAppTitle(); this._initializeDefaultAlwaysOnTop(); this._initializeDefaultChatroom(); this._initializeDefaultLanguage(); this._initializeDefaultSearcher(); this._initializeDefaultTrackFormat(); this._initializeDefaultVolume(); this._initializeKonamiCode(); // Initialize these after Player.js has been setup CastingManager.init(); RemotePlayer.init(); // Say hi :) Tracker.pageview('/').send(); } _bindShortcutEvents() { IpcRenderer.on('key-MediaNextTrack', () => { Player.playNextTrack(); }); IpcRenderer.on('key-MediaPreviousTrack', () => { Player.playPreviousTrack(); }); IpcRenderer.on('key-MediaPlayPause', () => { Player.playOrPause(); }); IpcRenderer.on('key-Escape', () => { Player.exitFullscreen(); }); } _bindTrayEvents() { IpcRenderer.on('tray-MediaPreviousTrack', () => { Player.playPreviousTrack(); }); IpcRenderer.on('tray-MediaNextTrack', () => { Player.playNextTrack(); }); IpcRenderer.on('tray-MediaPlayPause', () => { Player.playOrPause(); }); } _bindPlayerEvents() { Player.on('play', () => { let playingTrack = Player.playingTrack; if (playingTrack) { let title = playingTrack.title; let maxLength = 40; let translatedTitle = _('app_title_playing', { name: title }); if (translatedTitle.length > maxLength) { translatedTitle = translatedTitle.substr(0, maxLength) + ' ...'; } AppCore.title = translatedTitle; } }); Player.on('ended', () => { AppCore.title = _('app_title_normal'); }); } _initializeDefaultTopRanking() { var defaultCountryCode = PreferenceManager.getPreference('default.topRanking.countryCode'); if (defaultCountryCode) { TopRanking.changeCountry(defaultCountryCode); } } _initializeAppTitle() { AppCore.title = _('app_title_normal'); } _initializeDefaultAlwaysOnTop() { var defaultAlwaysOnTop = PreferenceManager.getPreference('default.alwaysOnTop.enabled'); if (defaultAlwaysOnTop) { Remote.getCurrentWindow().setAlwaysOnTop(defaultAlwaysOnTop); } } _initializeDefaultChatroom() { var defaultChatroom = PreferenceManager.getPreference('default.chatroom.enabled'); if (typeof defaultChatroom === 'undefined') { PreferenceManager.setPreference('default.chatroom.enabled', true); } } _initializeDefaultLanguage() { var defaultLanguage = PreferenceManager.getPreference('default.language'); // For new users, there is no `defaultLanguage` in DB yet. if (defaultLanguage) { L10nManager.changeLanguage(defaultLanguage); } } _initializeDefaultSearcher() { var defaultSearcher = PreferenceManager.getPreference('default.searcher'); if (defaultSearcher) { Searcher.changeSearcher(defaultSearcher); } } _initializeDefaultTrackFormat() { var defaultFormat = PreferenceManager.getPreference('default.track.format') || 'best'; TrackInfoFetcher.changeFormat(defaultFormat); } _initializeDefaultVolume() { var defaultVolume = PreferenceManager.getPreference('default.volume') || 'default'; Player.setVolume(defaultVolume); } _initializeKonamiCode() { KonamiCodeManager.attach(document.body, () => { EasterEggs.show(); }); } _triggerAutoUpdater() { AutoUpdater.updateApp(); Notifier.alert(_('main_autoupdate_ytdl')); AutoUpdater.updateYoutubeDl().then(() => { Notifier.alert(_('main_autoupdate_ytdl_success')); console.log('updated youtube-dl successfully'); }).catch(() => { Notifier.alert(_('main_autoupdate_ytdl_error')); console.log('failed to update youtube-dl'); }); } _hideLoadingPage() { loadingPageDOM.hidden = true; } render() { return ( <div className="root"> <ConnectionCheckComponent/> <ChatroomComponent/> <div className="row row-no-padding top-row"> <div className="col-md-12"> <div className="toolbar-slot"> <ToolbarComponent/> </div> </div> </div> <div className="row row-no-padding bottom-row"> <div className="left"> <div className="sidebar"> <MenusComponent/> <PlayerComponent/> </div> </div> <div className="right"> <div className="tab-content"> <div role="tabpanel" className="tab-pane active" id="tab-home"> <TopRankingComponent/> </div> <div role="tabpanel" className="tab-pane" id="tab-news"> <NewsComponent/> </div> <div role="tabpanel" className="tab-pane" id="tab-search"> <AllTracksComponent/> </div> <div role="tabpanel" className="tab-pane" id="tab-settings"> <SettingsComponent/> </div> <div role="tabpanel" className="tab-pane" id="tab-online-dj"> <OnlineDJComponent/> </div> <div role="tabpanel" className="tab-pane" id="tab-about"> <AboutComponent/> </div> <div role="tabpanel" className="tab-pane" id="tab-history"> <HistoryComponent/> </div> <div role="tabpanel" className="tab-pane" id="tab-play-queue"> <PlayQueueComponent/> </div> <div role="tabpanel" className="tab-pane" id="tab-playlist"> <PlaylistComponent/> </div> </div> </div> </div> <ReactTooltip/> </div> ); } } ReactDOM.render(<KakuApp/>, contentPageDOM);
src/components/MinimapZoom/Minimap.js
vogelino/design-timeline
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { createScaleFunction, getLanes } from '../../helpers/timelineHelper'; import { SIDEBAR_WIDTH, TOPICS_LIST_WIDTH, MINIMAP_MARGIN } from '../../redux/constants/uiConstants'; import EventsLane from '../EventsLane/EventsLane'; export const MinimapComponent = ({ events, categories, ui: { windowWidth }, mainTimeline: { minDate, maxDate }, }) => { const totalWidth = windowWidth - SIDEBAR_WIDTH - TOPICS_LIST_WIDTH - (2 * MINIMAP_MARGIN); const scaleFunc = createScaleFunction({ totalWidth, minDate, maxDate }); const lanes = getLanes({ categories, events, scaleFunc }); const getFutureZone = (date, classPrefix) => ( <div className={`events-lanes_${classPrefix}`} style={{ width: windowWidth - SIDEBAR_WIDTH - scaleFunc(date) - TOPICS_LIST_WIDTH - MINIMAP_MARGIN, }} /> ); return ( <div className="minimap"> {getFutureZone(new Date('2017-06-28'), 'publication')} {getFutureZone(new Date(), 'future')} {lanes.map(({ laneSlug, laneEvents }) => ( <EventsLane key={laneSlug} classNamePrefix="minimap" className={laneSlug} events={laneEvents} width={totalWidth} /> ))} </div> ); }; MinimapComponent.propTypes = { events: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, data: PropTypes.shape({ title: PropTypes.string.isRequired, }).isRequired, state: PropTypes.shape({ selected: PropTypes.bool.isRequired, hovered: PropTypes.bool.isRequired, }).isRequired, }), ).isRequired, categories: PropTypes.arrayOf( PropTypes.shape({ slug: PropTypes.string.isRequired, title: PropTypes.string.isRequired, color: PropTypes.string.isRequired, }), ).isRequired, ui: PropTypes.shape({ windowWidth: PropTypes.number.isRequired, }), mainTimeline: PropTypes.shape({ minDate: PropTypes.instanceOf(Date).isRequired, maxDate: PropTypes.instanceOf(Date).isRequired, }), }; const mapStateToProps = ({ events, categories, ui, mainTimeline }) => ({ events, categories, ui, mainTimeline }); export default connect(mapStateToProps)(MinimapComponent);
js/jqwidgets/demos/react/app/tabs/defaultfunctionality/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxTabs from '../../../jqwidgets-react/react_jqxtabs.js'; import JqxCheckBox from '../../../jqwidgets-react/react_jqxcheckbox.js'; class App extends React.Component { componentDidMount() { this.refs.animation.on('change', (event) => { let checked = event.args.checked; this.refs.myTabs.selectionTracker(checked); }); this.refs.contentAnimation.on('change', (event) => { let checked = event.args.checked; if (checked) { this.refs.myTabs.animationType('fade'); } else { this.refs.myTabs.animationType('none'); } }); } render () { let tabsHTML = ` <ul> <li style="margin-left: 30px;">Node.js</li> <li>JavaServer Pages</li> <li>Active Server Pages</li> <li>Python</li> <li>Perl</li> </ul> <div> Node.js is an event-driven I/O server-side JavaScript environment based on V8. It is intended for writing scalable network programs such as web servers. It was created by Ryan Dahl in 2009, and its growth is sponsored by Joyent, which employs Dahl. Similar environments written in other programming languages include Twisted for Python, Perl Object Environment for Perl, libevent for C and EventMachine for Ruby. Unlike most JavaScript, it is not executed in a web browser, but is instead a form of server-side JavaScript. Node.js implements some CommonJS specifications. Node.js includes a REPL environment for interactive testing. </div> <div> JavaServer Pages (JSP) is a Java technology that helps software developers serve dynamically generated web pages based on HTML, XML, or other document types. Released in 1999 as Sun's answer to ASP and PHP,[citation needed] JSP was designed to address the perception that the Java programming environment didn't provide developers with enough support for the Web. To deploy and run, a compatible web server with servlet container is required. The Java Servlet and the JavaServer Pages (JSP) specifications from Sun Microsystems and the JCP (Java Community Process) must both be met by the container. </div> <div> ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET language. The ASP.NET SOAP extension framework allows ASP.NET components to process SOAP messages. </div> <div> Python is a general-purpose, high-level programming language[5] whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax",[7] and its standard library is large and comprehensive. Its use of indentation for block delimiters is unique among popular programming languages. Python supports multiple programming paradigms, primarily but not limited to object-oriented, imperative and, to a lesser extent, functional programming styles. It features a fully dynamic type system and automatic memory management, similar to that of Scheme, Ruby, Perl, and Tcl. Like other dynamic languages, Python is often used as a scripting language, but is also used in a wide range of non-scripting contexts. </div> <div> Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular amongst programmers. Larry Wall continues to oversee development of the core language, and its upcoming version, Perl 6. Perl borrows features from other programming languages including C, shell scripting (sh), AWK, and sed.[5] The language provides powerful text processing facilities without the arbitrary data length limits of many contemporary Unix tools, facilitating easy manipulation of text files. </div> `; return ( <div> <JqxTabs ref='myTabs' template={tabsHTML} width={'90%'} height={200} position={'top'} /> <div id='settings' style={{ marginTop: 5 }}> <JqxCheckBox ref='animation' style={{ marginTop: 10 }} value='Enable Select Animation'/> <JqxCheckBox ref='contentAnimation' style={{ marginTop: 10 }} value='Enable Content Animation'/> </div> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/components/counts/ShortCountVol.js
availabs/avail_app_bootstrap
import React from 'react'; import StackedBarGraph from '../graphs/StackedBarGraph'; import directionCodes from '../utils/directionCodes'; class ShortCountVol extends React.Component { render() { var data = this.props.data; var countDate = `${data.month}/${data.dayOfFirstData}/${data.year}`; var infoTable = ( <table style={{ width: '100%' }}> <tr> <th>Count Id</th> <td>{data.countId}</td> <th>Date</th> <td>{countDate}</td> </tr> <tr> <th>Functional Class</th> <td>{data.functionalClass}</td> <th>Factor Group</th> <td>{data.factorGroup}</td> </tr> <tr> <th>Recorder Placement</th> <td colSpan={7}>{data.specificRecorderPlacement}</td> </tr> </table> ); var chartData = Object.keys(data.counts).map(countDate => { return Object.keys(data.counts[countDate]).map(dir => { return data.counts[countDate][dir].data.map((value, index) => { var xValue = data.counts[countDate][dir].data.length > 24 ? (index / 4).toFixed(2) : index + 1; return { name: dir, x: +xValue, y: value }; }); }); }); // let aadtData = Object.keys(data.federalDirection) // .sort((a, b) => b - a) // .map(dir => { // return ( // <div className="col-4"> // <div className="el-tablo highlight"> // <div className="label">{directionCodes[dir]} AADT</div> // <div className="value"> // {data.federalDirection[dir].aadt.toLocaleString()} // </div> // </div> // </div> // ); // }); // let legendData = Object.keys(data.federalDirection) // .filter(dir => dir !== '0' && dir !== '9') // .map(dir => { // return { name: directionCodes[dir] }; // }); return ( <div> <div className="element-box"> {chartData.map((currentData, i) => { const currentCount = data.counts[Object.keys(data.counts)[i]]; const legendData = Object.keys(currentCount).map(dir => { return { name: directionCodes[dir] }; }); const countInfo = currentCount[Object.keys(currentCount)[0]]; return ( <div className="row"> <div className="project-info"> <div className="row align-items-center"> <div className="col-sm-12"> <div className="project-title"> <h5> Short Count&nbsp; <span style={{ fontWeight: 100 }}> {countInfo.dayOfWeek} {countInfo.date} </span> </h5> </div> </div> </div> </div> <div className="col-md-12 col-xl-12"> <StackedBarGraph data={currentData} legendData={legendData} /> </div> </div> ); })} <div className="row"> <div className="col-md-12 col-xl-12"> <div className="padded b-l b-r"> <div className="element-info-with-icon smaller"> <div className="element-info-icon"> <div className="os-icon os-icon-bar-chart-stats-up" /> </div> <div className="element-info-text"> <h5 className="element-inner-header">Metadata</h5> <div className="element-inner-desc" /> </div> </div> {infoTable} </div> </div> </div> </div> </div> ); } } export default ShortCountVol;
test/fixtures/stateless-assignment/expected.js
layershifter/babel-plugin-transform-react-handled-props
import PropTypes from 'prop-types'; import React from 'react'; const Example = function () { return <div />; }; Example.handledProps = ["active", "children", "className"]; Example.defaultProps = { active: true }; Example.propTypes = { children: PropTypes.node, className: PropTypes.string }; export default Example;
node_modules/semantic-ui-react/src/modules/Popup/PopupContent.js
mowbell/clickdelivery-fed-test
import cx from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META, } from '../../lib' /** * A PopupContent displays the content body of a Popover. */ export default function PopupContent(props) { const { children, className } = props const classes = cx('content', className) const rest = getUnhandledProps(PopupContent, props) const ElementType = getElementType(PopupContent, props) return <ElementType {...rest} className={classes}>{children}</ElementType> } PopupContent.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** The content of the Popup */ children: PropTypes.node, /** Classes to add to the Popup content className. */ className: PropTypes.string, } PopupContent._meta = { name: 'PopupContent', type: META.TYPES.MODULE, parent: 'Popup', } PopupContent.create = createShorthandFactory(PopupContent, children => ({ children }))
src/client/index.js
playnogames/stacks
import React from 'react'; import ReactDom from 'react-dom'; import App from './components/App'; import './scss/index.scss'; ReactDom.render( <App />, document.getElementById('app') );
client/components/requestUApproved.js
marhyorh/booktrade
import React from 'react'; export default (props) => { const onRemove = (book, event) => { event.preventDefault(); Meteor.call('book.unApprove', book); } const reqApproved = () => { return props.books.map(book => { return ( <li className="list-group-item" key={book._id}> {book.title} <i className="glyphicon glyphicon-remove" onClick={onRemove.bind(this, book)} /> </li> ); }); } return ( <div className="requestUApproved"> {props.books.length >= 1 && <h3>Requests you approved:</h3>} <ul className="list-group"> { reqApproved() } </ul> </div> ) };
src/components/VenueList.js
mgaebler/kicknow-client-web
import React from 'react' export default class VenueList extends React.Component { render () { function generateVenueButton (venue){ return ( <a className="list-group-item" href={`/location/add/${venue.id}`} key={venue.id} > <h4 className="list-group-item-heading"> {venue.name} </h4> <p className="list-group-item-text"> {venue.location.address} </p> </a> ) } return ( <div className="list-group"> {this.props.venues.map(generateVenueButton)} </div> ) } }
node_modules/react-bootstrap/es/MediaHeading.js
soniacq/LearningReact
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'h4' }; var MediaHeading = function (_React$Component) { _inherits(MediaHeading, _React$Component); function MediaHeading() { _classCallCheck(this, MediaHeading); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaHeading.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return MediaHeading; }(React.Component); MediaHeading.propTypes = propTypes; MediaHeading.defaultProps = defaultProps; export default bsClass('media-heading', MediaHeading);