path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
examples/basic/forms/index.js
bluSCALE4/react-modal
import React, { Component } from 'react'; import Modal from 'react-modal'; const MODAL_A = 'modal_a'; const MODAL_B = 'modal_b'; const DEFAULT_TITLE = 'Default title'; class Forms extends Component { constructor(props) { super(props); this.state = { isOpen: false }; } toggleModal = event => { console.log(event); const { isOpen } = this.state; this.setState({ isOpen: !isOpen }); } render() { const { isOpen } = this.state; return ( <div> <button className="btn btn-primary" onClick={this.toggleModal}>Open Modal</button> <Modal id="modal_with_forms" isOpen={isOpen} closeTimeoutMS={150} contentLabel="modalB" shouldCloseOnOverlayClick={true} onRequestClose={this.toggleModal} aria={{ labelledby: "heading", describedby: "fulldescription" }}> <h1 id="heading">Forms!</h1> <div id="fulldescription" tabIndex="0" role="document"> <p>This is a description of what it does: nothing :)</p> <form> <fieldset> <input type="text" /> <input type="text" /> </fieldset> <fieldset> <legend>Radio buttons</legend> <label> <input id="radio-a" name="radios" type="radio" /> A </label> <label> <input id="radio-b" name="radios" type="radio" /> B </label> </fieldset> <fieldset> <legend>Checkbox buttons</legend> <label> <input id="checkbox-a" name="checkbox-a" type="checkbox" /> A </label> <label> <input id="checkbox-b" name="checkbox-b" type="checkbox" /> B </label> </fieldset> <input type="text" /> </form> </div> </Modal> </div> ); } } export default { label: "Modal with forms fields.", app: Forms };
test/helpers/shallowRenderHelper.js
SKoschnicke/react-test
/** * 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(); }
examples/real-world/index.js
eiriklv/redux
import 'babel-core/polyfill'; import React from 'react'; import Root from './containers/Root'; import BrowserHistory from 'react-router/lib/BrowserHistory'; React.render( <Root history={new BrowserHistory()} />, document.getElementById('root') );
charts/react-chartjs-3/example1/src/index.js
rob-blackbourn/scratch-js
import React from 'react' import ReactDOM from 'react-dom' import 'typeface-roboto' import App from './App' import * as serviceWorker from './serviceWorker' ReactDOM.render(<App />, document.getElementById('root')) serviceWorker.unregister()
app/components/EmployeeFormCreate/index.js
dreamweaver1231/frontend
/** * * EmployeeFormCreate * */ import React from 'react'; import { reduxForm, Field } from 'redux-form/immutable'; import MenuItem from 'material-ui/MenuItem'; import { RaisedButton, Divider } from 'material-ui'; import { SelectField, TextField, DatePicker } from 'redux-form-material-ui'; const EmployeeFormCreate = ({ handleSubmit, pristine, reset, submitting }) => { const required = (value) => value == null ? 'Required' : undefined; const style = { margin: 12, }; return ( <form onSubmit={handleSubmit}> <Field name="Enterprise_ID" component={TextField} hintText="Enterpise ID of Employee" /> <Field name="First_Name" component={TextField} hintText="First Name" /> <Field name="Last_Name" component={TextField} hintText="Last Name" /> <Field name="Supervisor_Name" component={TextField} hintText="Supervisor Name" /> <Field name="Supervisor_EnterpriseID" component={TextField} hintText="Supervisor Enterprise ID" /> <Field name="MyTE_Approver_Name" component={TextField} hintText="MYte Approver Name" /> <Field name="MyTE_Approver_ID" component={TextField} hintText="MYte Approver ID" /> <Field name="User_ID" component={TextField} hintText="User ID" /> <Field name="Contact_Number" component={TextField} hintText="Contact Number" /> <Field name="Cisco_Manager_Name" component={TextField} hintText="Cisco Manager Name" /> <Field name="Portfolio_Name" component={TextField} hintText="Portfolio Name" /> <Field name="Primary_Application" component={TextField} hintText="Primary Application" /> <Field name="Location" component={TextField} hintText="Location" /> <Field name="SOW_Number" component={TextField} hintText="SOW Number" /> <br /> <Field name="HL_Date" component={DatePicker} format={null} hintText="HL Date" validate={required} /> <Field name="Cisco_Start_Date" component={DatePicker} format={null} hintText="Cisco Start Date" validate={required} /> <Field name="Liquid" component={SelectField} hintText="Core / Shared" floatingLabelText="Liquid" floatingLabelFixed autoWidth={false} > <MenuItem value="Core" primaryText="Core" /> <MenuItem value="Shared" primaryText="Shared" /> </Field> <br /> <Field name="Career_Level" component={SelectField} hintText="Career Level" floatingLabelText="Career Level" floatingLabelFixed autoWidth={false} > <MenuItem value="08-Associate Manager" primaryText="Associate Manager" /> <MenuItem value="09-Team Lead" primaryText="Team Lead" /> <MenuItem value="10-Senior Software Engineer" primaryText="Senior Software Engineer" /> <MenuItem value="11-Software Engineer" primaryText="Software Engineer" /> <MenuItem value="12-Associate Software Engineer" primaryText="Associate Software Engineer" /> </Field> <br /> <Field name="Gender" component={SelectField} hintText="Gender" floatingLabelText="Gender" floatingLabelFixed autoWidth={false} > <MenuItem value="M" primaryText="Male" /> <MenuItem value="F" primaryText="Female" /> </Field> <div> <RaisedButton type="submit" label="Submit" primary style={style} disabled={submitting} /> <RaisedButton onClick={reset} label="Reset" secondary style={style} disabled={pristine || submitting} /> </div> <br /> <br /> <Divider /> </form> ); }; EmployeeFormCreate.propTypes = { handleSubmit: React.PropTypes.func, reset: React.PropTypes.func, pristine: React.PropTypes.bool, submitting: React.PropTypes.bool, }; // Decorate with redux-form export default reduxForm({ form: 'employeeForm', })(EmployeeFormCreate);
react/Hidden/Hidden.js
seekinternational/seek-asia-style-guide
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import styles from './Hidden.less'; const Hidden = ({ children, component, className, print, screen, mobile, aboveMobile, desktop, ...restprops }) => { const props = { ...restprops, className: classNames({ [className]: className, [styles.desktop]: desktop, [styles.mobile]: mobile, [styles.print]: print, [styles.screen]: screen, [styles.aboveMobile]: aboveMobile }) }; return React.createElement(component, props, children); }; Hidden.propTypes = { children: PropTypes.node, component: PropTypes.oneOfType([ PropTypes.func, PropTypes.string ]), className: PropTypes.string, desktop: PropTypes.bool, mobile: PropTypes.bool, print: PropTypes.bool, screen: PropTypes.bool, aboveMobile: PropTypes.bool }; Hidden.defaultProps = { className: '', component: 'span', desktop: false, mobile: false, print: false, screen: false, aboveMobile: false }; export default Hidden;
docs/app/Examples/elements/Button/Variations/ButtonExampleFloated.js
shengnian/shengnian-ui-react
import React from 'react' import { Button } from 'shengnian-ui-react' const ButtonExampleFloated = () => ( <div> <Button floated='right'>Right Floated</Button> <Button floated='left'>Left Floated</Button> </div> ) export default ButtonExampleFloated
packages/react-devtools-shell/src/app/InspectableElements/SimpleValues.js
Simek/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import React from 'react'; export default function SimpleValues() { return ( <ChildComponent string="abc" emptyString="" number={123} undefined={undefined} null={null} nan={NaN} infinity={Infinity} true={true} false={false} /> ); } function ChildComponent(props: any) { return null; }
js/components/pages/NotFound.react.js
Kielan/kielan-com
import React, { Component } from 'react'; import { Link } from 'react-router'; class NotFound extends Component { render() { return ( <article> <h1>Page not found.</h1> <Link to="/" className="btn">Home</Link> </article> ); } } export default NotFound;
src/js/components/filter__row/index.js
Arlefreak/arlefreakClient
import PropTypes from 'prop-types'; import React from 'react'; const FilterRow = ({ onClick, name, className}) => ( <li> <a className={ className } onClick={ onClick }> { name } </a> </li> ); FilterRow.propTypes = { onClick: PropTypes.func.isRequired, name: PropTypes.string.isRequired, className: PropTypes.string, }; export default FilterRow;
test/src/index.js
gnextia/gnextia
import React from 'react' import { render } from 'react-dom' import { createStore, applyMiddleware, compose } from 'redux' import createSagaMiddleware from 'redux-saga' import { Provider } from 'react-redux' const { name } = require('../package.json') import config from './config' import './theme/index.scss' import App from './app' import { default as reducers } from './reducers' import sagas from './sagas' // Devtool let devtoolsOrCompose = compose // Hot Module if (config.env != 'production') { if (module.hot) module.hot.accept() devtoolsOrCompose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ name }) : compose } // Saga and Store const sagaMiddleware = createSagaMiddleware() const store = createStore( reducers, devtoolsOrCompose(applyMiddleware(sagaMiddleware)) ) sagaMiddleware.run(sagas) render( <Provider store={store}> <App /> </Provider>, document.getElementById('index') )
code/schritte/2-hierarchy/src/GreetingController.js
st-he/react-workshop
import React from 'react'; import GreetingMaster from './GreetingMaster'; import GreetingDetail from './GreetingDetail'; let currentId = 0; const sampleGreetings = [{ id: currentId++, name: 'Olli', greeting: 'Huhu' }, { id: currentId++, name: 'Oma', greeting: 'Hallo' } ]; const MODE_MASTER = 'MODE_MASTER'; const MODE_DETAIL = 'MODE_DETAIL'; export default class GreetingController extends React.Component { render() { const {mode, greetings} = this.state; return ( <div> {mode === MODE_MASTER ? <GreetingMaster greetings={greetings} onAdd={() => this.setState({mode: MODE_DETAIL})} /> : <GreetingDetail onAdd={(greeting) => this.addGreeting(greeting)} /> } </div>); } constructor(props) { super(props); this.state = { greetings: sampleGreetings, mode: MODE_MASTER }; } addGreeting(greetingToBeAdded) { const {greetings} = this.state; greetingToBeAdded.id = currentId++; const newGreetings = [...greetings, greetingToBeAdded]; this.setState({ greetings: newGreetings, mode: MODE_MASTER }); } }
gui/react/src/components/Loading.js
williamparry/cloudRIG
import React, { Component } from 'react'; import { Dimmer, Loader } from 'semantic-ui-react' import 'semantic-ui-css/semantic.min.css'; class Loading extends Component { render() { return( <Dimmer active inverted> <Loader inverted>{this.props.message}</Loader> </Dimmer> ) } } export default Loading;
app/components/Basketball.js
RogerZZZZZ/widget_electron
import React from 'react' import { Component} from 'react' import { BasketballCrawler} from '../utils/crawler.js' import { Table, ButtonGroup, Button } from './BasketballComponent.js' let bCrawler = new BasketballCrawler(); class Basketball extends Component{ constructor(props){ super(props) let self = this; bCrawler.init('gameResult', (data) => { self.setState({gameResult: data}) }); bCrawler.init('teamRanking', (data) => { self.setState({teamRanking: data}) }); bCrawler.init('playerStatistics', (data) => { self.setState({playerStatistics: data}) }); this.state = { gameResult: [], teamRanking: [], playerStatistics: [], pageIndex: 0 //0:Schedule, 1:Ranking, 2: Player Statistics } } _naviButtonClick(val){ this.setState({ pageIndex: val }) } render(){ let self = this; let pageIndex = this.state.pageIndex; let gameResult = this.state.gameResult; let todayMatch = (gameResult.length === 0 ? []: gameResult.today), tomorrowMatch = (gameResult.length === 0 ? []: gameResult.tomorrow); let teamRanking = this.state.teamRanking; let eastRanking = (teamRanking.length === 0 ? []: teamRanking.east), westRanking = (teamRanking.length === 0 ? []: teamRanking.west); let ps = this.state.playerStatistics; let pts = [], blk = [], stl =[], fg = [], reb = [], ass = []; if(ps.length !== 0){ pts = ps.pts; blk = ps.blk; stl = ps.stl; fg = ps.fg; reb = ps.reb; ass = ps.ass; } return ( <div> <ButtonGroup> <Button name="Schedule" onClick={self._naviButtonClick.bind(self, 0)} status={pageIndex===0?false: true}/> <Button name="Ranking" onClick={self._naviButtonClick.bind(self, 1)} status={pageIndex===1?false: true}/> <Button name="Statistics" onClick={self._naviButtonClick.bind(self, 2)} status={pageIndex===2?false: true}/> </ButtonGroup> { pageIndex === 0? ( <div className="main-wrap"> <div className="title">Schedule</div> <Table data={todayMatch} type={0} /> <Table data={tomorrowMatch} type={1} /> </div> ): (pageIndex === 1? ( <div className="main-wrap"> <div className="title">NBA Standings</div> <Table data={eastRanking} type={2} /> <Table data={westRanking} type={2} /> <div className="glossary"> <div className="title">GLOSSARY</div> <div className="item"> <span className="lite">W:</span> <span>Wins</span> </div> <div className="item"> <span className="lite">L:</span> <span>Losses</span> </div> <div className="item"> <span className="lite">PCT:</span> <span>Winning Percentage</span> </div> <div className="item"> <span className="lite">GB:</span> <span>Games Back</span> </div> <div className="item"> <span className="lite">HOME:</span> <span>Home Record</span> </div> <div className="item"> <span className="lite">ROAD:</span> <span>Road Record</span> </div> <div className="item"> <span className="lite">PPG:</span> <span>Points Per Game</span> </div> <div className="item"> <span className="lite">OPP PPG:</span> <span>Opponent Points Per Game</span> </div> <div className="item"> <span className="lite">L10:</span> <span>Record last 10 games</span> </div> <div className="item"> <span className="lite">STRK:</span> <span>Current Streak</span> </div> <div className="item"> <span className="lite">X:</span> <span>Clinched Playoff berth</span> </div> <div className="item"> <span className="lite">Y:</span> <span>Clinched Dicision</span> </div> <div className="item"> <span className="lite">E:</span> <span>Eliminated From Playoff</span> </div> </div> </div> ): ( <div className="main-wrap"> <div className="title">Player Statistics</div> <div className="statistics-container"> <Table data={pts} type={3} header="POINTS"/> <Table data={blk} type={3} header="BLOCKS"/> <Table data={ass} type={3} header="ASSISTS"/> </div> <div className="statistics-container"> <Table data={reb} type={3} header="REBOUNDS"/> <Table data={stl} type={3} header="STEALS"/> <Table data={fg} type={3} header="FIELD GOAL %"/> </div> </div> )) } </div> ) } } export default Basketball
examples/npm-webpack/src/index.js
gorangajic/react-swipe-views
'use strict'; import React from 'react'; import { default as Router, Route, DefaultRoute, Redirect } from 'react-router'; import App from './components/App'; require('../../../lib/react-swipe-views.css'); require('./main.css'); require('babel-core/polyfill'); React.initializeTouchEvents(true); const routes = ( <Route name="app" path="/" handler={App}> <DefaultRoute name="root" handler={App} /> <Route name="intro" path="/intro" handler={App}/> <Route name="code" path="/code" handler={App}/> <Route name="thanks" path="/thanks" handler={App}/> </Route> ); Router.run(routes, Router.HistoryLocation, (Handler) => { React.render( <Handler />, document.getElementById('root') ); });
src/browser/app/components/Spinner.js
xiankai/triple-triad-solver
/* @flow */ import React from 'react'; import Image from './Image'; const Spinner = (props: Object) => ( <Image {...props} tagName="img" src={require('./ajax-loader.gif')} /> ); export default Spinner;
src/MenuItem.js
mmarcant/react-bootstrap
import classNames from 'classnames'; import React from 'react'; import all from 'react-prop-types/lib/all'; import SafeAnchor from './SafeAnchor'; import { bsClass, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; const propTypes = { /** * Highlight the menu item as active. */ active: React.PropTypes.bool, /** * Disable the menu item, making it unselectable. */ disabled: React.PropTypes.bool, /** * Styles the menu item as a horizontal rule, providing visual separation between * groups of menu items. */ divider: all( React.PropTypes.bool, ({ divider, children }) => ( divider && children ? new Error('Children will not be rendered for dividers') : null ), ), /** * Value passed to the `onSelect` handler, useful for identifying the selected menu item. */ eventKey: React.PropTypes.any, /** * Styles the menu item as a header label, useful for describing a group of menu items. */ header: React.PropTypes.bool, /** * HTML `href` attribute corresponding to `a.href`. */ href: React.PropTypes.string, /** * Callback fired when the menu item is clicked. */ onClick: React.PropTypes.func, /** * Callback fired when the menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: React.PropTypes.func, }; const defaultProps = { divider: false, disabled: false, header: false, }; class MenuItem extends React.Component { constructor(props, context) { super(props, context); this.handleClick = this.handleClick.bind(this); } handleClick(event) { const { href, disabled, onSelect, eventKey } = this.props; if (!href || disabled) { event.preventDefault(); } if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } } render() { const { active, disabled, divider, header, onClick, className, style, ...props } = this.props; const [bsProps, elementProps] = splitBsPropsAndOmit(props, [ 'eventKey', 'onSelect', ]); if (divider) { // Forcibly blank out the children; separators shouldn't render any. elementProps.children = undefined; return ( <li {...elementProps} role="separator" className={classNames(className, 'divider')} style={style} /> ); } if (header) { return ( <li {...elementProps} role="heading" className={classNames(className, prefix(bsProps, 'header'))} style={style} /> ); } return ( <li role="presentation" className={classNames(className, { active, disabled })} style={style} > <SafeAnchor {...elementProps} role="menuitem" tabIndex="-1" onClick={createChainedFunction(onClick, this.handleClick)} /> </li> ); } } MenuItem.propTypes = propTypes; MenuItem.defaultProps = defaultProps; export default bsClass('dropdown', MenuItem);
frontend/src/@crema/core/AppsContainer/AppsContent.js
edinnen/Thanksgiving_Intranet
import React from 'react'; import Scrollbar from '../Scrollbar'; import makeStyles from '@material-ui/core/styles/makeStyles'; const AppsContent = (props) => { const useStyles = makeStyles((theme) => ({ appsContentContainer: (props) => ({ height: `calc(100% - ${props.isDetailView ? 60 : 115}px)`, [theme.breakpoints.up('sm')]: { height: `calc(100% - ${props.fullView ? 0 : 60}px)`, }, [theme.breakpoints.up('xl')]: { height: `calc(100% - ${props.fullView ? 0 : 77}px)`, }, '& .scrum-absolute': { position: 'absolute', top: 0, left: 0, width: '100%', }, '& .scrum-row': { display: 'inline-flex', minWidth: '100%', height: '100%', marginLeft: '-10px', marginRight: '-10px', }, '& .scrum-col': { width: '280px', marginLeft: '10px', marginRight: '10px', borderRadius: theme.overrides.MuiCard.root.borderRadius, height: '100% !important', [theme.breakpoints.up('md')]: { width: '354px', }, }, '& .scroll-scrum-item': { height: 'auto !important', }, }), })); const classes = useStyles(props); return ( <Scrollbar className={classes.appsContentContainer}> {props.children} </Scrollbar> ); }; export default AppsContent; AppsContent.defaultProps = {isDetailView: false};
src/ui/form/checkbox/checkbox-story.js
josmardias/react-redux-boilerplate
import React from 'react' import { storiesOf } from '@kadira/storybook' import Checkbox from '.' storiesOf('ui.Form.Checkbox', module) .add('Default', () => ( <Checkbox label="Check it!" /> ))
src/routes/Home/components/HomeView.js
gohup/react_testcase
import React from 'react' import DuckImage from '../assets/Duck.jpg' import classes from './HomeView.scss' export const HomeView = () => ( <div> <h4>This is not a duck!</h4> <img alt='This is not a duck!' className={classes.duck} src={DuckImage} /> </div> ) export default HomeView
components/FunnelInputField/FunnelInputField.js
rdjpalmer/bloom
import PropTypes from 'prop-types'; import React from 'react'; import mergeObjectStrings from '../../utils/mergeObjectStrings/mergeObjectStrings'; import InputField from '../Form/InputField/InputField'; import css from './FunnelInputField.css'; const FunnelInputField = ({ classNames, ...rest }) => { const classes = mergeObjectStrings(css, classNames); return ( <InputField { ...rest } classNames={ classes } /> ); }; FunnelInputField.propTypes = { classNames: PropTypes.shape({ root: PropTypes.string, meta: PropTypes.string, label: PropTypes.string, valueReplay: PropTypes.string, placeholder: PropTypes.string, description: PropTypes.string, }), }; FunnelInputField.defaultProps = { classNames: {}, }; export default FunnelInputField;
src/components/Forms/TextArea.js
josedigital/koala-app
import React from 'react' const TextArea = (props) => { return ( <div className="form-element"> <label htmlFor={props.name}>{props.label}</label> <textarea name={props.name} id={props.name} value={props.content} onChange={props.controlFunction}> </textarea> </div> ) } TextArea.propTypes = { label: React.PropTypes.string.isRequired, name: React.PropTypes.string.isRequired, content: React.PropTypes.string.isRequired, controlFunction: React.PropTypes.func.isRequired } export default TextArea
src/collections/Menu/Menu.js
Semantic-Org/Semantic-UI-React
import cx from 'clsx' import _ from 'lodash' import PropTypes from 'prop-types' import React from 'react' import { ModernAutoControlledComponent as Component, childrenUtils, customPropTypes, createShorthandFactory, getElementType, getUnhandledProps, SUI, useKeyOnly, useKeyOrValueAndKey, useValueAndKey, useWidthProp, } from '../../lib' import MenuHeader from './MenuHeader' import MenuItem from './MenuItem' import MenuMenu from './MenuMenu' /** * A menu displays grouped navigation actions. * @see Dropdown */ class Menu extends Component { handleItemOverrides = (predefinedProps) => ({ onClick: (e, itemProps) => { const { index } = itemProps this.setState({ activeIndex: index }) _.invoke(predefinedProps, 'onClick', e, itemProps) _.invoke(this.props, 'onItemClick', e, itemProps) }, }) renderItems() { const { items } = this.props const { activeIndex } = this.state return _.map(items, (item, index) => MenuItem.create(item, { defaultProps: { active: parseInt(activeIndex, 10) === index, index, }, overrideProps: this.handleItemOverrides, }), ) } render() { const { attached, borderless, children, className, color, compact, fixed, floated, fluid, icon, inverted, pagination, pointing, secondary, size, stackable, tabular, text, vertical, widths, } = this.props const classes = cx( 'ui', color, size, useKeyOnly(borderless, 'borderless'), useKeyOnly(compact, 'compact'), useKeyOnly(fluid, 'fluid'), useKeyOnly(inverted, 'inverted'), useKeyOnly(pagination, 'pagination'), useKeyOnly(pointing, 'pointing'), useKeyOnly(secondary, 'secondary'), useKeyOnly(stackable, 'stackable'), useKeyOnly(text, 'text'), useKeyOnly(vertical, 'vertical'), useKeyOrValueAndKey(attached, 'attached'), useKeyOrValueAndKey(floated, 'floated'), useKeyOrValueAndKey(icon, 'icon'), useKeyOrValueAndKey(tabular, 'tabular'), useValueAndKey(fixed, 'fixed'), useWidthProp(widths, 'item'), className, 'menu', ) const rest = getUnhandledProps(Menu, this.props) const ElementType = getElementType(Menu, this.props) return ( <ElementType {...rest} className={classes}> {childrenUtils.isNil(children) ? this.renderItems() : children} </ElementType> ) } } Menu.propTypes = { /** An element type to render as (string or function). */ as: PropTypes.elementType, /** Index of the currently active item. */ activeIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** A menu may be attached to other content segments. */ attached: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['top', 'bottom'])]), /** A menu item or menu can have no borders. */ borderless: PropTypes.bool, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Additional colors can be specified. */ color: PropTypes.oneOf(SUI.COLORS), /** A menu can take up only the space necessary to fit its content. */ compact: PropTypes.bool, /** Initial activeIndex value. */ defaultActiveIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** A menu can be fixed to a side of its context. */ fixed: PropTypes.oneOf(['left', 'right', 'bottom', 'top']), /** A menu can be floated. */ floated: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['right'])]), /** A vertical menu may take the size of its container. */ fluid: PropTypes.bool, /** A menu may have just icons (bool) or labeled icons. */ icon: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['labeled'])]), /** A menu may have its colors inverted to show greater contrast. */ inverted: PropTypes.bool, /** Shorthand array of props for Menu. */ items: customPropTypes.collectionShorthand, /** * onClick handler for MenuItem. Mutually exclusive with children. * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All item props. */ onItemClick: customPropTypes.every([customPropTypes.disallow(['children']), PropTypes.func]), /** A pagination menu is specially formatted to present links to pages of content. */ pagination: PropTypes.bool, /** A menu can point to show its relationship to nearby content. */ pointing: PropTypes.bool, /** A menu can adjust its appearance to de-emphasize its contents. */ secondary: PropTypes.bool, /** A menu can vary in size. */ size: PropTypes.oneOf(_.without(SUI.SIZES, 'medium', 'big')), /** A menu can stack at mobile resolutions. */ stackable: PropTypes.bool, /** A menu can be formatted to show tabs of information. */ tabular: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['right'])]), /** A menu can be formatted for text content. */ text: PropTypes.bool, /** A vertical menu displays elements vertically. */ vertical: PropTypes.bool, /** A menu can have its items divided evenly. */ widths: PropTypes.oneOf(SUI.WIDTHS), } Menu.autoControlledProps = ['activeIndex'] Menu.Header = MenuHeader Menu.Item = MenuItem Menu.Menu = MenuMenu Menu.create = createShorthandFactory(Menu, (items) => ({ items })) export default Menu
src/pages/launchWindow/launchWindowPage.js
Synchro-TEC/site-apollo-11
import React from 'react'; import { LaunchWindow } from 'syntec-apollo-11'; import {PrismCode} from 'react-prism'; class LaunchWindowPage extends React.Component { constructor() { super(); } showLaunchWindow() { this.refs.modal.show(); } render() { return ( <div className='dm-content'> <LaunchWindow ref='modal'> Modal </LaunchWindow> <div className='sv-row'> <div className='sv-column'> <h3>Launch Window</h3> <h6 className='sv-vertical-marged'> Launch Window is a modal component. </h6> <p> <button className='sv-button small default' onClick={() => this.showLaunchWindow()}>Open</button> </p> </div> </div> <div className='dm-code-container'> <pre className='line-numbers' data-start='1'> <PrismCode className='language-js'> {require('!raw-loader!./laounchWindowExamples.js')} </PrismCode> </pre> </div> </div> ); } } LaunchWindowPage.displayName = 'LaunchWindowPage'; export default LaunchWindowPage;
blueocean-material-icons/src/js/components/svg-icons/device/battery-std.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const DeviceBatteryStd = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/> </SvgIcon> ); DeviceBatteryStd.displayName = 'DeviceBatteryStd'; DeviceBatteryStd.muiName = 'SvgIcon'; export default DeviceBatteryStd;
admin/client/App/screens/List/components/UpdateForm.js
creynders/keystone
import React from 'react'; import Select from 'react-select'; import { findDOMNode } from 'react-dom'; import assign from 'object-assign'; import { Fields } from 'FieldTypes'; import InvalidFieldType from '../../../shared/InvalidFieldType'; import { plural } from '../../../../utils/string'; import { BlankState, Button, Form, Modal } from 'elemental'; var UpdateForm = React.createClass({ displayName: 'UpdateForm', propTypes: { isOpen: React.PropTypes.bool, itemIds: React.PropTypes.array, list: React.PropTypes.object, onCancel: React.PropTypes.func, }, getDefaultProps () { return { isOpen: false, }; }, getInitialState () { return { fields: [], }; }, componentDidMount () { this.doFocus(); }, componentDidUpdate () { this.doFocus(); }, doFocus () { if (this.refs.focusTarget) { findDOMNode(this.refs.focusTarget).focus(); } }, getOptions () { const { fields } = this.props.list; return Object.keys(fields).map(key => ({ value: fields[key].path, label: fields[key].label })); }, getFieldProps (field) { var props = assign({}, field); props.value = this.state.fields[field.path]; props.values = this.state.fields; props.onChange = this.handleChange; props.mode = 'create'; props.key = field.path; return props; }, updateOptions (fields) { this.setState({ fields: fields, }, this.doFocus); }, handleChange (value) { console.log('handleChange:', value); }, handleClose () { this.setState({ fields: [], }); this.props.onCancel(); }, renderFields () { const { list } = this.props; const { fields } = this.state; const formFields = []; let focusRef; fields.forEach((fieldOption) => { const field = list.fields[fieldOption.value]; if (typeof Fields[field.type] !== 'function') { formFields.push(React.createElement(InvalidFieldType, { type: field.type, path: field.path, key: field.path })); return; } var fieldProps = this.getFieldProps(field); if (!focusRef) { fieldProps.ref = focusRef = 'focusTarget'; } formFields.push(React.createElement(Fields[field.type], fieldProps)); }); const fieldsUI = formFields.length ? formFields : ( <BlankState style={{ padding: '3em 2em' }}> <BlankState.Heading style={{ fontSize: '1.5em' }}>Choose a field above to begin</BlankState.Heading> </BlankState> ); return ( <div style={{ borderTop: '1px dashed rgba(0,0,0,0.1)', marginTop: 20, paddingTop: 20 }}> {fieldsUI} </div> ); }, renderForm () { const { itemIds, list } = this.props; const itemCount = plural(itemIds, ('* ' + list.singular), ('* ' + list.plural)); const formAction = `${Keystone.adminPath}/${list.path}`; return ( <Form type="horizontal" action={formAction} noValidate="true"> <Modal.Header text={'Update ' + itemCount} onClose={this.handleClose} showCloseButton /> <Modal.Body> <Select ref="initialFocusTarget" onChange={this.updateOptions} options={this.getOptions()} value={this.state.fields} key="field-select" multi /> {this.renderFields()} </Modal.Body> <Modal.Footer> <Button type="primary" submit>Update</Button> <Button type="link-cancel" onClick={this.handleClose}>Cancel</Button> </Modal.Footer> </Form> ); }, render () { return ( <Modal isOpen={this.props.isOpen} onCancel={this.handleClose} backdropClosesModal> {this.renderForm()} </Modal> ); }, }); module.exports = UpdateForm;
src/Collapse.js
yuche/react-bootstrap
import React from 'react'; import Transition from './Transition'; import domUtils from './utils/domUtils'; import createChainedFunction from './utils/createChainedFunction'; let capitalize = str => str[0].toUpperCase() + str.substr(1); // reading a dimension prop will cause the browser to recalculate, // which will let our animations work let triggerBrowserReflow = node => node.offsetHeight; //eslint-disable-line no-unused-expressions const MARGINS = { height: ['marginTop', 'marginBottom'], width: ['marginLeft', 'marginRight'] }; function getDimensionValue(dimension, elem){ let value = elem[`offset${capitalize(dimension)}`]; let computedStyles = domUtils.getComputedStyles(elem); let margins = MARGINS[dimension]; return (value + parseInt(computedStyles[margins[0]], 10) + parseInt(computedStyles[margins[1]], 10) ); } class Collapse extends React.Component { constructor(props, context){ super(props, context); this.onEnterListener = this.handleEnter.bind(this); this.onEnteringListener = this.handleEntering.bind(this); this.onEnteredListener = this.handleEntered.bind(this); this.onExitListener = this.handleExit.bind(this); this.onExitingListener = this.handleExiting.bind(this); } render() { let enter = createChainedFunction(this.onEnterListener, this.props.onEnter); let entering = createChainedFunction(this.onEnteringListener, this.props.onEntering); let entered = createChainedFunction(this.onEnteredListener, this.props.onEntered); let exit = createChainedFunction(this.onExitListener, this.props.onExit); let exiting = createChainedFunction(this.onExitingListener, this.props.onExiting); return ( <Transition ref='transition' {...this.props} aria-expanded={this.props.in} className={this._dimension() === 'width' ? 'width' : ''} exitedClassName='collapse' exitingClassName='collapsing' enteredClassName='collapse in' enteringClassName='collapsing' onEnter={enter} onEntering={entering} onEntered={entered} onExit={exit} onExiting={exiting} onExited={this.props.onExited} > { this.props.children } </Transition> ); } /* -- Expanding -- */ handleEnter(elem){ let dimension = this._dimension(); elem.style[dimension] = '0'; } handleEntering(elem){ let dimension = this._dimension(); elem.style[dimension] = this._getScrollDimensionValue(elem, dimension); } handleEntered(elem){ let dimension = this._dimension(); elem.style[dimension] = null; } /* -- Collapsing -- */ handleExit(elem){ let dimension = this._dimension(); elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px'; } handleExiting(elem){ let dimension = this._dimension(); triggerBrowserReflow(elem); elem.style[dimension] = '0'; } _dimension(){ return typeof this.props.dimension === 'function' ? this.props.dimension() : this.props.dimension; } //for testing _getTransitionInstance(){ return this.refs.transition; } _getScrollDimensionValue(elem, dimension){ return elem[`scroll${capitalize(dimension)}`] + 'px'; } } Collapse.propTypes = { /** * Collapse the Component in or out. */ in: React.PropTypes.bool, /** * Provide the duration of the animation in milliseconds, used to ensure that finishing callbacks are fired even if the * original browser transition end events are canceled. */ duration: React.PropTypes.number, /** * Specifies the dimension used when collapsing. * * _Note: Bootstrap only partially supports 'width'! * You will need to supply your own css animation for the `.width` css class._ */ dimension: React.PropTypes.oneOfType([ React.PropTypes.oneOf(['height', 'width']), React.PropTypes.func ]), /** * A function that returns the height or width of the animating DOM node. Allows for providing some custom logic how much * Collapse component should animate in its specified dimension. * * `getDimensionValue` is called with the current dimension prop value and the DOM node. */ getDimensionValue: React.PropTypes.func, /** * A Callback fired before the component starts to expand. */ onEnter: React.PropTypes.func, /** * A Callback fired immediately after the component starts to expand. */ onEntering: React.PropTypes.func, /** * A Callback fired after the component has expanded. */ onEntered: React.PropTypes.func, /** * A Callback fired before the component starts to collapse. */ onExit: React.PropTypes.func, /** * A Callback fired immediately after the component starts to collapse. */ onExiting: React.PropTypes.func, /** * A Callback fired after the component has collapsed. */ onExited: React.PropTypes.func, /** * Specify whether the transitioning component should be unmounted (removed from the DOM) once the exit animation finishes. */ unmountOnExit: React.PropTypes.bool, /** * Specify whether the component should collapse or expand when it mounts. */ transitionAppear: React.PropTypes.bool }; Collapse.defaultProps = { in: false, duration: 300, dimension: 'height', transitionAppear: false, unmountOnExit: false, getDimensionValue }; export default Collapse;
node_modules/antd/es/form/FormItem.js
yhx0634/foodshopfront
import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import PureRenderMixin from 'rc-util/es/PureRenderMixin'; import Row from '../grid/row'; import Col from '../grid/col'; import { FIELD_META_PROP } from './constants'; import warning from '../_util/warning'; var FormItem = function (_React$Component) { _inherits(FormItem, _React$Component); function FormItem() { _classCallCheck(this, FormItem); return _possibleConstructorReturn(this, (FormItem.__proto__ || Object.getPrototypeOf(FormItem)).apply(this, arguments)); } _createClass(FormItem, [{ key: 'componentDidMount', value: function componentDidMount() { warning(this.getControls(this.props.children, true).length <= 1, '`Form.Item` cannot generate `validateStatus` and `help` automatically, ' + 'while there are more than one `getFieldDecorator` in it.'); } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return PureRenderMixin.shouldComponentUpdate.apply(this, args); } }, { key: 'getHelpMsg', value: function getHelpMsg() { var context = this.context; var props = this.props; if (props.help === undefined && context.form) { return this.getId() ? (context.form.getFieldError(this.getId()) || []).join(', ') : ''; } return props.help; } }, { key: 'getControls', value: function getControls(children, recursively) { var controls = []; var childrenArray = React.Children.toArray(children); for (var i = 0; i < childrenArray.length; i++) { if (!recursively && controls.length > 0) { break; } var child = childrenArray[i]; if (child.type === FormItem) { continue; } if (!child.props) { continue; } if (FIELD_META_PROP in child.props) { controls.push(child); } else if (child.props.children) { controls = controls.concat(this.getControls(child.props.children, recursively)); } } return controls; } }, { key: 'getOnlyControl', value: function getOnlyControl() { var child = this.getControls(this.props.children, false)[0]; return child !== undefined ? child : null; } }, { key: 'getChildProp', value: function getChildProp(prop) { var child = this.getOnlyControl(); return child && child.props && child.props[prop]; } }, { key: 'getId', value: function getId() { return this.getChildProp('id'); } }, { key: 'getMeta', value: function getMeta() { return this.getChildProp(FIELD_META_PROP); } }, { key: 'renderHelp', value: function renderHelp() { var prefixCls = this.props.prefixCls; var help = this.getHelpMsg(); return help ? React.createElement( 'div', { className: prefixCls + '-explain', key: 'help' }, help ) : null; } }, { key: 'renderExtra', value: function renderExtra() { var _props = this.props, prefixCls = _props.prefixCls, extra = _props.extra; return extra ? React.createElement( 'div', { className: prefixCls + '-extra' }, extra ) : null; } }, { key: 'getValidateStatus', value: function getValidateStatus() { var _context$form = this.context.form, isFieldValidating = _context$form.isFieldValidating, getFieldError = _context$form.getFieldError, getFieldValue = _context$form.getFieldValue; var fieldId = this.getId(); if (!fieldId) { return ''; } if (isFieldValidating(fieldId)) { return 'validating'; } if (!!getFieldError(fieldId)) { return 'error'; } var fieldValue = getFieldValue(fieldId); if (fieldValue !== undefined && fieldValue !== null && fieldValue !== '') { return 'success'; } return ''; } }, { key: 'renderValidateWrapper', value: function renderValidateWrapper(c1, c2, c3) { var classes = ''; var form = this.context.form; var props = this.props; var validateStatus = props.validateStatus === undefined && form ? this.getValidateStatus() : props.validateStatus; if (validateStatus) { classes = classNames({ 'has-feedback': props.hasFeedback, 'has-success': validateStatus === 'success', 'has-warning': validateStatus === 'warning', 'has-error': validateStatus === 'error', 'is-validating': validateStatus === 'validating' }); } return React.createElement( 'div', { className: this.props.prefixCls + '-item-control ' + classes }, c1, c2, c3 ); } }, { key: 'renderWrapper', value: function renderWrapper(children) { var _props2 = this.props, prefixCls = _props2.prefixCls, wrapperCol = _props2.wrapperCol; var className = classNames(prefixCls + '-item-control-wrapper', wrapperCol && wrapperCol.className); return React.createElement( Col, _extends({}, wrapperCol, { className: className, key: 'wrapper' }), children ); } }, { key: 'isRequired', value: function isRequired() { var required = this.props.required; if (required !== undefined) { return required; } if (this.context.form) { var meta = this.getMeta() || {}; var validate = meta.validate || []; return validate.filter(function (item) { return !!item.rules; }).some(function (item) { return item.rules.some(function (rule) { return rule.required; }); }); } return false; } }, { key: 'renderLabel', value: function renderLabel() { var _props3 = this.props, prefixCls = _props3.prefixCls, label = _props3.label, labelCol = _props3.labelCol, colon = _props3.colon, id = _props3.id; var context = this.context; var required = this.isRequired(); var labelColClassName = classNames(prefixCls + '-item-label', labelCol && labelCol.className); var labelClassName = classNames(_defineProperty({}, prefixCls + '-item-required', required)); var labelChildren = label; // Keep label is original where there should have no colon var haveColon = colon && !context.vertical; // Remove duplicated user input colon if (haveColon && typeof label === 'string' && label.trim() !== '') { labelChildren = label.replace(/[:|:]\s*$/, ''); } return label ? React.createElement( Col, _extends({}, labelCol, { className: labelColClassName, key: 'label' }), React.createElement( 'label', { htmlFor: id || this.getId(), className: labelClassName, title: typeof label === 'string' ? label : '' }, labelChildren ) ) : null; } }, { key: 'renderChildren', value: function renderChildren() { var props = this.props; var children = React.Children.map(props.children, function (child) { if (child && typeof child.type === 'function' && !child.props.size) { return React.cloneElement(child, { size: 'large' }); } return child; }); return [this.renderLabel(), this.renderWrapper(this.renderValidateWrapper(children, this.renderHelp(), this.renderExtra()))]; } }, { key: 'renderFormItem', value: function renderFormItem(children) { var _itemClassName; var props = this.props; var prefixCls = props.prefixCls; var style = props.style; var itemClassName = (_itemClassName = {}, _defineProperty(_itemClassName, prefixCls + '-item', true), _defineProperty(_itemClassName, prefixCls + '-item-with-help', !!this.getHelpMsg()), _defineProperty(_itemClassName, prefixCls + '-item-no-colon', !props.colon), _defineProperty(_itemClassName, '' + props.className, !!props.className), _itemClassName); return React.createElement( Row, { className: classNames(itemClassName), style: style }, children ); } }, { key: 'render', value: function render() { var children = this.renderChildren(); return this.renderFormItem(children); } }]); return FormItem; }(React.Component); export default FormItem; FormItem.defaultProps = { hasFeedback: false, prefixCls: 'ant-form', colon: true }; FormItem.propTypes = { prefixCls: PropTypes.string, label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), labelCol: PropTypes.object, help: PropTypes.oneOfType([PropTypes.node, PropTypes.bool]), validateStatus: PropTypes.oneOf(['', 'success', 'warning', 'error', 'validating']), hasFeedback: PropTypes.bool, wrapperCol: PropTypes.object, className: PropTypes.string, id: PropTypes.string, children: PropTypes.node, colon: PropTypes.bool }; FormItem.contextTypes = { form: PropTypes.object, vertical: PropTypes.bool };
src/components/Map.js
TorinoMeteo/tm-realtime-map
import React from 'react' import PropTypes from 'prop-types' import Spinner from 'react-spinner' import LiveMap from 'components/LiveMap' import HistoryMap from 'components/HistoryMap' import ForecastMap from 'components/ForecastMap' import WebcamsMap from 'components/WebcamsMap' import AirQualityMap from 'components/AirQualityMap' import moment from 'moment' class Map extends React.Component { componentDidMount () { this.props.fetchRealtimeData() let now = moment() this.props.fetchLiveRadarImages(now.format('Y'), now.format('M'), now.format('D')) } componentWillReceiveProps (nextProps) { // fetch history data if needed if ( nextProps.map.view === 'history' && !this.props.history.loading && // avoid multiple requests ( this.props.map.view !== 'history' || !this.props.history.sync || nextProps.map.history.year !== this.props.map.history.year || nextProps.map.history.month !== this.props.map.history.month || nextProps.map.history.day !== this.props.map.history.day ) ) { this.props.fetchHistoricData( nextProps.map.history.year, nextProps.map.history.month, nextProps.map.history.day ) this.props.fetchHistoryRadarImages( nextProps.map.history.year, nextProps.map.history.month, nextProps.map.history.day ) } else if (nextProps.map.view === 'webcams' && !nextProps.webcams.data.length) { this.props.fetchWebcamsData() } else if (nextProps.map.view === 'airquality' && !nextProps.airquality.data.length) { this.props.fetchAirQualityData() } else if ( nextProps.map.view === 'forecast' && (nextProps.map.forecast.date.format('YMD') !== this.props.map.forecast.date.format('YMD') || !this.props.weatherForecast.sync)) { this.props.fetchWeatherForecastData(nextProps.map.forecast.date) } } render () { let loading = null if ( this.props.realtime.sync === false || this.props.realtime.loading || this.props.history.loading || this.props.webcams.loading || this.props.airquality.loading || this.props.weatherForecast.loading || this.props.radar.loading || (this.props.map.live.radar.active && this.props.map.live.radar.preloading) || (this.props.map.history.radar.active && this.props.map.history.radar.preloading) ) { loading = ( <div className='map-loading'> <Spinner style={{ height: 50, width: 50 }} /> </div> ) // if data are not yet loaded, fit bounds will be called with no markers // => viewport is set in the middle of the ocean, lol if (this.props.realtime.sync === false) { return loading } } let map = null if (this.props.map.view === 'live') { map = ( <LiveMap containerElement={<div className='map-container' />} mapElement={<div className='map-canvas' />} data={this.props.realtime.data.data} radarImages={this.props.radar.data.live} mapData={this.props.map} selectStation={this.props.selectLiveStation} changeLiveRadarPreloading={this.props.changeLiveRadarPreloading} changeMapViewport={this.props.changeMapViewport} setInitBoundFit={this.props.setInitBoundFit} /> ) } else if (this.props.map.view === 'history') { map = ( <HistoryMap containerElement={<div className='map-container' />} mapElement={<div className='map-canvas' />} data={this.props.history.data} mapData={this.props.map} selectStation={this.props.selectHistoryStation} changeMapViewport={this.props.changeMapViewport} /> ) } else if (this.props.map.view === 'forecast') { map = ( <ForecastMap containerElement={<div className='map-container' />} mapElement={<div className='map-canvas' />} data={this.props.weatherForecast.data} mapData={this.props.map} changeMapViewport={this.props.changeMapViewport} /> ) } else if (this.props.map.view === 'webcams') { map = ( <WebcamsMap containerElement={<div className='map-container' />} mapElement={<div className='map-canvas' />} data={this.props.webcams.data} mapData={this.props.map} selectWebcam={this.props.selectWebcam} changeMapViewport={this.props.changeMapViewport} /> ) } else if (this.props.map.view === 'airquality') { map = ( <AirQualityMap containerElement={<div className='map-container' />} mapElement={<div className='map-canvas' />} data={this.props.airquality.data} mapData={this.props.map} selectAirQualityStation={this.props.selectAirQualityStation} changeMapViewport={this.props.changeMapViewport} /> ) } return ( <div> {loading} {map} </div> ) } } Map.propTypes = { fetchRealtimeData: PropTypes.func.isRequired, fetchLiveRadarImages: PropTypes.func.isRequired, fetchHistoryRadarImages: PropTypes.func.isRequired, fetchHistoricData: PropTypes.func.isRequired, fetchWeatherForecastData: PropTypes.func.isRequired, fetchWebcamsData: PropTypes.func.isRequired, fetchAirQualityData: PropTypes.func.isRequired, selectWebcam: PropTypes.func.isRequired, selectAirQualityStation: PropTypes.func.isRequired, selectLiveStation: PropTypes.func.isRequired, selectHistoryStation: PropTypes.func.isRequired, changeLiveRadarPreloading: PropTypes.func.isRequired, changeMapViewport: PropTypes.func.isRequired, setInitBoundFit: PropTypes.func.isRequired, realtime: PropTypes.shape({ sync: PropTypes.bool, syncing: PropTypes.bool, loading: PropTypes.bool, data: PropTypes.shape({ data: PropTypes.array, stations: PropTypes.array }) }), history: PropTypes.shape({ sync: PropTypes.bool, syncing: PropTypes.bool, loading: PropTypes.bool, data: PropTypes.array }), weatherForecast: PropTypes.shape({ sync: PropTypes.bool, syncing: PropTypes.bool, loading: PropTypes.bool, data: PropTypes.array }), webcams: PropTypes.shape({ sync: PropTypes.bool, syncing: PropTypes.bool, loading: PropTypes.bool, data: PropTypes.array }), airquality: PropTypes.shape({ sync: PropTypes.bool, syncing: PropTypes.bool, loading: PropTypes.bool, data: PropTypes.array }), radar: PropTypes.shape({ sync: PropTypes.bool, syncing: PropTypes.bool, loading: PropTypes.bool, data: PropTypes.shape({ live: PropTypes.array.isRequired, history: PropTypes.array.isRequired }) }), map: PropTypes.shape({ live: PropTypes.shape({ quantity: PropTypes.string, radar: PropTypes.shape({ active: PropTypes.bool, preloading: PropTypes.bool }) }), history: PropTypes.shape({ quantity: PropTypes.string, year: PropTypes.number | PropTypes.string, month: PropTypes.number | PropTypes.string, day: PropTypes.number | PropTypes.string, radar: PropTypes.shape({ active: PropTypes.bool, preloading: PropTypes.bool }) }), forecast: PropTypes.shape({ date: PropTypes.object.isRequired }), webcams: PropTypes.shape({ selected: PropTypes.object }), airquality: PropTypes.shape({ selected: PropTypes.object }), view: PropTypes.string }) } export default Map
dispatch/static/manager/src/js/components/ZoneEditor/WidgetField.js
ubyssey/dispatch
import React from 'react' import * as fields from '../fields' import * as Form from '../Form' export default function WidgetField(props) { const Field = fields[props.field.type] let fieldError = '' let childErrors = null if (props.field.type == 'widget' && props.error) { try { childErrors = JSON.parse(props.error) fieldError = childErrors.self } catch (e) { fieldError = props.error } } else { fieldError = props.error } return ( <Form.Input error={fieldError} label={props.field.label}> <Field errors={childErrors} field={props.field} data={props.data} onChange={props.onChange} /> </Form.Input> ) }
client/src/research/BackgroundColor.js
mit-teaching-systems-lab/threeflows
import React, { Component } from 'react'; //Teacher Moments sets background color based on users' screen size (see: public/index.html) //This component sets the background color of Teacher Moments to white for all of the research related pages. class BackgroundColor extends Component { componentWillMount() { document.body.style.backgroundColor = "white"; } componentWillUnmount() { document.body.style.backgroundColor = null; } render() { return ( <div></div> ); } } export default BackgroundColor;
examples/async/index.js
morgante/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; const store = configureStore(); React.render( <Provider store={store}> {() => <App />} </Provider>, document.getElementById('root') );
test/test-controller-without-model.js
mxc/cauldron
"use strict"; import React from 'react'; import ReactDOM from 'react-dom'; import TestComp from './test-comp'; import TestModel from './test-model'; import BaseController from '../src/base-controller' class TestControllerWithoutModel extends BaseController { constructor(props,context){ super(props,context); } render(){ return (<TestComp />); } } export default TestControllerWithoutModel;
webapp/app/components/Users/Button/index.js
EIP-SAM/SAM-Solution-Server
// // List buttons page users // import React from 'react'; import { ButtonToolbar } from 'react-bootstrap'; import LinkContainerButton from 'components/Button'; import styles from './styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class UsersButton extends React.Component { render() { return ( <ButtonToolbar className={styles.toolbar}> <LinkContainerButton buttonBsStyle="info" buttonText="Create user" link="/create-user" /> </ButtonToolbar> ); } }
src/components/Schemes/ColorPicker/index.js
nobus/weaver
import React, { Component } from 'react'; import { SketchPicker } from 'react-color'; import { Modal, Button } from 'react-bootstrap'; class ColorPicker extends Component { render() { return ( <Modal show={this.props.showModal} onHide={this.props.close}> <Modal.Header> <Modal.Title>Color picker</Modal.Title> </Modal.Header> <Modal.Body> <SketchPicker /> </Modal.Body> <Modal.Footer> <Button onClick={this.props.close}>Close</Button> <Button bsStyle="primary" onClick={this.props.saveChanges}> Save changes </Button> </Modal.Footer> </Modal> ) } } export default ColorPicker;
docs/src/pages/components/lists/CheckboxListSecondary.js
lgollut/material-ui
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import Checkbox from '@material-ui/core/Checkbox'; import Avatar from '@material-ui/core/Avatar'; const useStyles = makeStyles((theme) => ({ root: { width: '100%', maxWidth: 360, backgroundColor: theme.palette.background.paper, }, })); export default function CheckboxListSecondary() { const classes = useStyles(); const [checked, setChecked] = React.useState([1]); const handleToggle = (value) => () => { const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } setChecked(newChecked); }; return ( <List dense className={classes.root}> {[0, 1, 2, 3].map((value) => { const labelId = `checkbox-list-secondary-label-${value}`; return ( <ListItem key={value} button> <ListItemAvatar> <Avatar alt={`Avatar n°${value + 1}`} src={`/static/images/avatar/${value + 1}.jpg`} /> </ListItemAvatar> <ListItemText id={labelId} primary={`Line item ${value + 1}`} /> <ListItemSecondaryAction> <Checkbox edge="end" onChange={handleToggle(value)} checked={checked.indexOf(value) !== -1} inputProps={{ 'aria-labelledby': labelId }} /> </ListItemSecondaryAction> </ListItem> ); })} </List> ); }
src/components/header/Description.js
jckfa/img.silly.graphics
import React from 'react' import styled from 'styled-components' import Gutters from '../utils/Gutters' import { site } from '../config/vars' import media from '../utils/media' const Container = styled.ul` padding: 1.25em 0 2em; & li { display: block; } & li + li { padding-top: 0.5em; } ${media.m` display: flex; justify-content: space-between; & li + li { padding-top: 0; } `} ` const Description = () => ( <Gutters> <Container> <li> PUB DOM or DIE </li> <li> <i> Use, Copy, Modify, Distribute • Any Purpose • No Attribution </i> </li> <li> Inspired by <a href="http://img.modem.studio" target="_blank" rel="noopener noreferrer"> this site </a> </li> <li> <a href={site.submit_url} target="_blank" rel="noopener noreferrer"> Submit </a> </li> </Container> </Gutters> ) export default Description
examples/counter/containers/App.js
blackxored/redux-devtools
import React, { Component } from 'react'; import CounterApp from './CounterApp'; import { createStore, applyMiddleware, combineReducers, compose } from 'redux'; import { devTools, persistState } from 'redux-devtools'; import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react'; import thunk from 'redux-thunk'; import { Provider } from 'react-redux'; import * as reducers from '../reducers'; const finalCreateStore = compose( applyMiddleware(thunk), devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)), createStore ); const reducer = combineReducers(reducers); const store = finalCreateStore(reducer); export default class App extends Component { render() { return ( <div> <Provider store={store}> {() => <CounterApp />} </Provider> <DebugPanel top right bottom> <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> </div> ); } }
src/components/ItemCard.js
nikolay-radkov/EBudgie
import React from 'react'; import { Text, StyleSheet, View, TouchableHighlight, } from 'react-native'; import { Icon } from 'react-native-elements'; import colors from '../themes/Colors'; import metrics from '../themes/Metrics'; const styles = StyleSheet.create({ items: { flexDirection: 'column', backgroundColor: colors.silver, borderWidth: metrics.borderWidth, borderColor: colors.snow, margin: 2, elevation: 1, borderRadius: metrics.buttonRadius, }, category: { flexDirection: 'row', backgroundColor: colors.snow, }, itemsContainer: { flexDirection: 'row', padding: 2, }, full: { flex: 1, justifyContent: 'center', }, itemContainer: { borderRadius: metrics.buttonRadius, padding: 10, borderWidth: metrics.borderWidth, margin: 2, borderColor: colors.snow, }, item: { fontSize: 14, textAlign: 'center', color: colors.snow }, column: { flex: 1, }, }); const ItemCard = ({ color, icon, size, title, oddItems, evenItems, onPress, }) => { const mappedEvenItems = evenItems.map((i, index) => { return ( <TouchableHighlight key={index} onPress={() => onPress(i.id)} style={[styles.itemContainer, { backgroundColor: color }]} > <Text style={styles.item}>{i.name}</Text> </TouchableHighlight> ); }); const mappedOddItems = oddItems.map((i, index) => { return ( <TouchableHighlight key={index} onPress={() => onPress(i.id)} style={[styles.itemContainer, { backgroundColor: color }]} > <Text style={styles.item}>{i.name}</Text> </TouchableHighlight> ); }); return ( <View style={styles.items}> <View style={styles.category}> <Icon color={color} name={icon} reverse size={size} /> <View style={styles.full}> <Text>{title}</Text> </View> </View> <View style={styles.itemsContainer}> <View style={styles.column}>{mappedEvenItems}</View> <View style={styles.column}>{mappedOddItems}</View> </View> </View> ); }; ItemCard.propTypes = { onPress: React.PropTypes.func, color: React.PropTypes.string, icon: React.PropTypes.string, size: React.PropTypes.number, title: React.PropTypes.string, oddItems: React.PropTypes.array, evenItems: React.PropTypes.array, }; export default ItemCard;
react/features/calendar-sync/components/ConferenceNotification.native.js
gpolitis/jitsi-meet
// @flow import React, { Component } from 'react'; import { Text, TouchableOpacity, View } from 'react-native'; import { appNavigate } from '../../app/actions'; import { getURLWithoutParamsNormalized } from '../../base/connection'; import { getLocalizedDateFormatter, translate } from '../../base/i18n'; import { Icon, IconNotificationJoin } from '../../base/icons'; import { connect } from '../../base/redux'; import { ASPECT_RATIO_NARROW } from '../../base/responsive-ui'; import styles from './styles'; const ALERT_MILLISECONDS = 5 * 60 * 1000; /** * The type of the React {@code Component} props of * {@link ConferenceNotification}. */ type Props = { /** * The current aspect ratio of the screen. */ _aspectRatio: Symbol, /** * The URL of the current conference without params. */ _currentConferenceURL: string, /** * The calendar event list. */ _eventList: Array<Object>, /** * The Redux dispatch function. */ dispatch: Function, /** * The translate function. */ t: Function }; /** * The type of the React {@code Component} state of * {@link ConferenceNotification}. */ type State = { /** * The event object to display the notification for. */ event?: Object }; /** * Component to display a permanent badge-like notification on the conference * screen when another meeting is about to start. */ class ConferenceNotification extends Component<Props, State> { updateIntervalId: IntervalID; /** * Constructor of the ConferenceNotification component. * * @inheritdoc */ constructor(props: Props) { super(props); this.state = { event: undefined }; // Bind event handlers so they are only bound once per instance. this._getNotificationContentStyle = this._getNotificationContentStyle.bind(this); this._getNotificationPosition = this._getNotificationPosition.bind(this); this._maybeDisplayNotification = this._maybeDisplayNotification.bind(this); this._onGoToNext = this._onGoToNext.bind(this); } /** * Implements React Component's componentDidMount. * * @inheritdoc */ componentDidMount() { this.updateIntervalId = setInterval( this._maybeDisplayNotification, 10 * 1000 ); } /** * Implements React Component's componentWillUnmount. * * @inheritdoc */ componentWillUnmount() { clearInterval(this.updateIntervalId); } /** * Implements the React Components's render. * * @inheritdoc */ render() { const { event } = this.state; const { t } = this.props; if (event) { const now = Date.now(); const label = event.startDate < now && event.endDate > now ? 'calendarSync.ongoingMeeting' : 'calendarSync.nextMeeting'; return ( <View style = { [ styles.notificationContainer, this._getNotificationPosition() ] } > <View style = { this._getNotificationContentStyle() }> <TouchableOpacity onPress = { this._onGoToNext } > <View style = { styles.touchableView }> <View style = { styles.notificationTextContainer }> <Text style = { styles.notificationText }> { t(label) } </Text> <Text style = { styles.notificationText }> { getLocalizedDateFormatter( event.startDate ).fromNow() } </Text> </View> <View style = { styles.notificationIconContainer }> <Icon src = { IconNotificationJoin } style = { styles.notificationIcon } /> </View> </View> </TouchableOpacity> </View> </View> ); } return null; } _getNotificationContentStyle: () => Array<Object>; /** * Decides the color of the notification and some additional * styles based on notificationPosition. * * @private * @returns {Array<Object>} */ _getNotificationContentStyle() { const { event } = this.state; const { _aspectRatio } = this.props; const now = Date.now(); const style = [ styles.notificationContent ]; if (event && event.startDate < now && event.endDate > now) { style.push(styles.notificationContentPast); } else { style.push(styles.notificationContentNext); } if (_aspectRatio === ASPECT_RATIO_NARROW) { style.push(styles.notificationContentSide); } else { style.push(styles.notificationContentTop); } return style; } _getNotificationPosition: () => Object; /** * Decides the position of the notification. * * @private * @returns {Object} */ _getNotificationPosition() { const { _aspectRatio } = this.props; if (_aspectRatio === ASPECT_RATIO_NARROW) { return styles.notificationContainerSide; } return styles.notificationContainerTop; } _maybeDisplayNotification: () => void; /** * Periodically checks if there is an event in the calendar for which we * need to show a notification. * * @private * @returns {void} */ _maybeDisplayNotification() { const { _currentConferenceURL, _eventList } = this.props; let eventToShow; if (_eventList && _eventList.length) { const now = Date.now(); for (const event of _eventList) { const eventUrl = event.url && getURLWithoutParamsNormalized(new URL(event.url)); if (eventUrl && eventUrl !== _currentConferenceURL) { if ((!eventToShow && event.startDate > now && event.startDate < now + ALERT_MILLISECONDS) || (event.startDate < now && event.endDate > now)) { eventToShow = event; } } } } this.setState({ event: eventToShow }); } _onGoToNext: () => void; /** * Opens the meeting URL that the notification shows. * * @private * @returns {void} */ _onGoToNext() { const { event } = this.state; if (event && event.url) { this.props.dispatch(appNavigate(event.url)); } } } /** * Maps redux state to component props. * * @param {Object} state - The redux state. * @returns {{ * _aspectRatio: Symbol, * _currentConferenceURL: string, * _eventList: Array * }} */ function _mapStateToProps(state: Object) { const { locationURL } = state['features/base/connection']; return { _aspectRatio: state['features/base/responsive-ui'].aspectRatio, _currentConferenceURL: locationURL ? getURLWithoutParamsNormalized(locationURL) : '', _eventList: state['features/calendar-sync'].events }; } export default translate(connect(_mapStateToProps)(ConferenceNotification));
src/List.js
kiloe/ui
import React from 'react'; import View from './View'; import CSS from './utils/css'; CSS.register({ }); export default class List extends View { static defaultProps = { ...View.defaultProps, scroll: true, row: false, } getClassNames(){ let cs = super.getClassNames(); cs.list = true; return cs; } getStyle(){ let style = super.getStyle(); // style.paddingTop = '8px'; return style; } }
frontend/src/Album/EpisodeStatusConnector.js
lidarr/Lidarr
import _ from 'lodash'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import createAlbumSelector from 'Store/Selectors/createAlbumSelector'; import createQueueItemSelector from 'Store/Selectors/createQueueItemSelector'; import createTrackFileSelector from 'Store/Selectors/createTrackFileSelector'; import EpisodeStatus from './EpisodeStatus'; function createMapStateToProps() { return createSelector( createAlbumSelector(), createQueueItemSelector(), createTrackFileSelector(), (album, queueItem, trackFile) => { const result = _.pick(album, [ 'airDateUtc', 'monitored', 'grabbed' ]); result.queueItem = queueItem; result.trackFile = trackFile; return result; } ); } const mapDispatchToProps = { }; class EpisodeStatusConnector extends Component { // // Render render() { return ( <EpisodeStatus {...this.props} /> ); } } EpisodeStatusConnector.propTypes = { albumId: PropTypes.number.isRequired, trackFileId: PropTypes.number.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(EpisodeStatusConnector);
es/components/sidebar/panel-element-editor/attributes-editor/item-attributes-editor.js
cvdlab/react-planner
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React, { Component } from 'react'; import PropTypes from 'prop-types'; import FormNumberInput from '../../../style/form-number-input'; import FormTextInput from '../../../style/form-text-input'; var tableStyle = { width: '100%' }; var firstTdStyle = { width: '6em' }; var inputStyle = { textAlign: 'left' }; export default function ItemAttributesEditor(_ref, _ref2) { var element = _ref.element, onUpdate = _ref.onUpdate, attributeFormData = _ref.attributeFormData, state = _ref.state, rest = _objectWithoutProperties(_ref, ['element', 'onUpdate', 'attributeFormData', 'state']); var translator = _ref2.translator; var name = attributeFormData.has('name') ? attributeFormData.get('name') : element.name; var renderedX = attributeFormData.has('x') ? attributeFormData.get('x') : element.x; var renderedY = attributeFormData.has('y') ? attributeFormData.get('y') : element.y; var renderedR = attributeFormData.has('rotation') ? attributeFormData.get('rotation') : element.rotation; return React.createElement( 'table', { style: tableStyle }, React.createElement( 'tbody', null, React.createElement( 'tr', null, React.createElement( 'td', { style: firstTdStyle }, translator.t('Name') ), React.createElement( 'td', null, React.createElement(FormTextInput, { value: name, onChange: function onChange(event) { return onUpdate('name', event.target.value); }, style: inputStyle }) ) ), React.createElement( 'tr', null, React.createElement( 'td', { style: firstTdStyle }, 'X' ), React.createElement( 'td', null, React.createElement(FormNumberInput, _extends({ value: renderedX, onChange: function onChange(event) { return onUpdate('x', event.target.value); }, style: inputStyle, state: state, precision: 2 }, rest)) ) ), React.createElement( 'tr', null, React.createElement( 'td', { style: firstTdStyle }, 'Y' ), React.createElement( 'td', null, React.createElement(FormNumberInput, _extends({ value: renderedY, onChange: function onChange(event) { return onUpdate('y', event.target.value); }, style: inputStyle, state: state, precision: 2 }, rest)) ) ), React.createElement( 'tr', null, React.createElement( 'td', { style: firstTdStyle }, translator.t('Rotation') ), React.createElement( 'td', null, React.createElement(FormNumberInput, _extends({ value: renderedR, onChange: function onChange(event) { return onUpdate('rotation', event.target.value); }, style: inputStyle, state: state, precision: 2 }, rest)) ) ) ) ); } ItemAttributesEditor.propTypes = { element: PropTypes.object.isRequired, onUpdate: PropTypes.func.isRequired, attributeFormData: PropTypes.object.isRequired, state: PropTypes.object.isRequired }; ItemAttributesEditor.contextTypes = { translator: PropTypes.object.isRequired };
webpack/components/PermissionDenied.js
mmoll/foreman_templates
import React from 'react'; import PropTypes from 'prop-types'; import { EmptyStatePattern as EmptyState } from 'foremanReact/components/common/EmptyState'; const PermissionDenied = props => { const description = ( <span> {__('You are not authorized to perform this action.')} <br /> {__( 'Please request one of the required permissions listed below from a Foreman administrator:' )} <br /> </span> ); return ( <EmptyState iconType="fa" icon="lock" header={__('Permission Denied')} description={description} documentation={props.doc} /> ); }; PermissionDenied.propTypes = { doc: PropTypes.node.isRequired, }; export default PermissionDenied;
src/svg-icons/content/create.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentCreate = (props) => ( <SvgIcon {...props}> <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/> </SvgIcon> ); ContentCreate = pure(ContentCreate); ContentCreate.displayName = 'ContentCreate'; ContentCreate.muiName = 'SvgIcon'; export default ContentCreate;
src/components/ArticleListItem/ArticleListItem.js
bingomanatee/wonderworld
import React from 'react'; import './articleListItem.scss'; import {FolderLabel} from '../FolderLabel/FolderLabel'; export const ArticleListItem = (props) => ( <div className='article-list-item' onClick={() => props.visitArticle(props.article)} key={'article-list-item-' + props.article}> <div className='article-list-item-inner'> <div className='article-list-item-title-group'> <FolderLabel className='article-list-item-folder' article={props.article} /> <div className='article-list-item-title'> <h2 className='article-list-item-title__inner'> {props.article.title}</h2> </div> </div> <div className='article-list-item-description-group'> <div className='article-list-item-intro'> <p className='article-list-item-intro__inner'>{props.article.intro || ' '} </p> </div> <div className='article-list-item-time'> <span className='article-list-item-time__inner'>{props.article.revisedMoment.fromNow() }</span> </div> </div> </div> </div> ); ArticleListItem.propTypes = { article: React.PropTypes.object.isRequired, visitArticle: React.PropTypes.func.isRequired }; export default ArticleListItem;
services/ui/src/pages/index.js
amazeeio/lagoon
import React from 'react'; import Router from 'next/router'; import { queryStringToObject } from 'lib/util'; export default class IndexPage extends React.Component { static async getInitialProps({ req, res }) { if (res) { const currentUrl = new URL(req.url, `https://${req.headers.host}`); res.writeHead(302, { Location: `/projects${currentUrl.search}` }); res.end(); } else { Router.push({ pathname: '/projects', query: queryStringToObject(location.search), }); } return {}; } }
app/javascript/flavours/glitch/components/status_list.js
im-in-space/mastodon
import { debounce } from 'lodash'; import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import StatusContainer from 'flavours/glitch/containers/status_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; import LoadGap from './load_gap'; import ScrollableList from './scrollable_list'; import RegenerationIndicator from 'flavours/glitch/components/regeneration_indicator'; export default class StatusList extends ImmutablePureComponent { static propTypes = { scrollKey: PropTypes.string.isRequired, statusIds: ImmutablePropTypes.list.isRequired, featuredStatusIds: ImmutablePropTypes.list, onLoadMore: PropTypes.func, onScrollToTop: PropTypes.func, onScroll: PropTypes.func, trackScroll: PropTypes.bool, isLoading: PropTypes.bool, isPartial: PropTypes.bool, hasMore: PropTypes.bool, prepend: PropTypes.node, alwaysPrepend: PropTypes.bool, emptyMessage: PropTypes.node, timelineId: PropTypes.string.isRequired, }; static defaultProps = { trackScroll: true, }; getFeaturedStatusCount = () => { return this.props.featuredStatusIds ? this.props.featuredStatusIds.size : 0; } getCurrentStatusIndex = (id, featured) => { if (featured) { return this.props.featuredStatusIds.indexOf(id); } else { return this.props.statusIds.indexOf(id) + this.getFeaturedStatusCount(); } } handleMoveUp = (id, featured) => { const elementIndex = this.getCurrentStatusIndex(id, featured) - 1; this._selectChild(elementIndex, true); } handleMoveDown = (id, featured) => { const elementIndex = this.getCurrentStatusIndex(id, featured) + 1; this._selectChild(elementIndex, false); } handleLoadOlder = debounce(() => { this.props.onLoadMore(this.props.statusIds.size > 0 ? this.props.statusIds.last() : undefined); }, 300, { leading: true }) _selectChild (index, align_top) { const container = this.node.node; const element = container.querySelector(`article:nth-of-type(${index + 1}) .focusable`); if (element) { if (align_top && container.scrollTop > element.offsetTop) { element.scrollIntoView(true); } else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) { element.scrollIntoView(false); } element.focus(); } } setRef = c => { this.node = c; } render () { const { statusIds, featuredStatusIds, onLoadMore, timelineId, ...other } = this.props; const { isLoading, isPartial } = other; if (isPartial) { return <RegenerationIndicator />; } let scrollableContent = (isLoading || statusIds.size > 0) ? ( statusIds.map((statusId, index) => statusId === null ? ( <LoadGap key={'gap:' + statusIds.get(index + 1)} disabled={isLoading} maxId={index > 0 ? statusIds.get(index - 1) : null} onClick={onLoadMore} /> ) : ( <StatusContainer key={statusId} id={statusId} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} contextType={timelineId} scrollKey={this.props.scrollKey} /> )) ) : null; if (scrollableContent && featuredStatusIds) { scrollableContent = featuredStatusIds.map(statusId => ( <StatusContainer key={`f-${statusId}`} id={statusId} featured onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} contextType={timelineId} scrollKey={this.props.scrollKey} /> )).concat(scrollableContent); } return ( <ScrollableList {...other} showLoading={isLoading && statusIds.size === 0} onLoadMore={onLoadMore && this.handleLoadOlder} ref={this.setRef}> {scrollableContent} </ScrollableList> ); } }
src/components/SettingsController/index.js
michaltakac/mathworldvr
import React from 'react' import PropTypes from 'prop-types' import { Entity } from 'aframe-react' const propTypes = { initialState: PropTypes.any.isRequired, actionToTrigger: PropTypes.func, min: PropTypes.number, max: PropTypes.number, step: PropTypes.number, type: PropTypes.string, name: PropTypes.string.isRequired, options: PropTypes.array, } const defaultProps = { type: 'slider', options: [], step: 0.01, min: 1, max: 10, } const SettingsController = ({ actionToTrigger, initialState, min, max, name, options, step, type, }) => { return ( <Entity datguicontroller={{ actionToTrigger, initialState, min, name, max, options, step, type, }} /> ) } SettingsController.propTypes = propTypes SettingsController.defaultProps = defaultProps export default SettingsController
src/routes/Apply/components/Apply.js
techcoop/techcoop.group
import React from 'react' import ReactDOM from 'react-dom' import './Apply.scss' const formDomain = 'https://docs.google.com/forms/' const formUrl = formDomain + 'd/e/1FAIpQLSccXBwqFccJ-g_n9545FEomK0v8wXI0KNfgqnCgiI0LLtnYHg/viewform?embedded=true' export class Apply extends React.Component { constructor (props) { super(props) this.updateDimensions = this.updateDimensions.bind(this) } updateDimensions () { let $this = ReactDOM.findDOMNode(this) $this.height = window.document.documentElement.clientHeight - 70 } componentDidMount () { this.updateDimensions() window.addEventListener('resize', this.updateDimensions) } componentWillUnmount () { window.removeEventListener('resize', this.updateDimensions) } render () { return ( <iframe src={formUrl} width='100%' frameBorder='0' marginHeight='0' marginWidth='0' > Loading... </iframe> ) } } Apply.propTypes = { apply : React.PropTypes.number.isRequired, doubleAsync : React.PropTypes.func.isRequired, increment : React.PropTypes.func.isRequired } export default Apply
client/acp/src/view/display/avatar.js
NicolasSiver/nodebb-plugin-ns-awards
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; export default class Avatar extends React.Component { render() { let avatarClass = classNames('aws-avatar', 'aws-avatar--' + this.props.size); let iconClass = classNames('aws-avatar__icon', 'aws-avatar__icon--' + this.props.size); let content; if (this.props.user.picture) { content = <img className="aws-avatar__image img-responsive" src={this.props.user.picture}/>; } else { content = <div className={iconClass} style={{backgroundColor: this.props.user['icon:bgColor']}}> {this.props.user['icon:text']} </div>; } return ( <div className={avatarClass}> {content} </div> ); } } Avatar.defaultProps = { size: 'normal' }; Avatar.propTypes = { size: PropTypes.string, user: PropTypes.object.isRequired };
src/components/app.js
martezconner/react_vidhub
import _ from 'lodash'; import React, { Component } from 'react'; import YTSearch from 'youtube-api-search'; // import SideBar from './nav/side_bar'; import Footer from './footer/footer'; import SearchBar from './search_bar'; import VideoList from './video_list'; import VideoDetail from './video_detail'; const API_KEY = 'AIzaSyBEIw0KXm-3tennZlyek9zStz07th6SiOw'; class App extends Component { constructor(props) { super(props); this.state = { videos: [], selectedVideo: null }; this.videoSearch('coding tech'); } videoSearch(term) { YTSearch({key: API_KEY, term: term}, (videos) => { this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render() { const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 400); return ( <div> <SearchBar onSearchTermChange={videoSearch} /> <VideoDetail video={this.state.selectedVideo} /> <VideoList onVideoSelect={selectedVideo => this.setState({selectedVideo}) } videos={this.state.videos} /> <Footer /> </div> ); } }; export default App;
src/scenes/home/404/fourOhFour.js
NestorSegura/operationcode_frontend
import React from 'react'; import styles from './fourOhFour.css'; const FourOhFour = () => ( <div className={styles.FourOhFour}> <div className={styles.bg}> <h1 className={styles.title}>404!</h1> <p className={styles.paragraph}>You definitely weren&apos;t supposed to see this...</p> </div> </div> ); export default FourOhFour;
app/javascript/mastodon/features/notifications/components/notification.js
NS-Kazuki/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import StatusContainer from '../../../containers/status_container'; import AccountContainer from '../../../containers/account_container'; import { injectIntl, FormattedMessage } from 'react-intl'; import Permalink from '../../../components/permalink'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { HotKeys } from 'react-hotkeys'; const notificationForScreenReader = (intl, message, timestamp) => { const output = [message]; output.push(intl.formatDate(timestamp, { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' })); return output.join(', '); }; export default @injectIntl class Notification extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { notification: ImmutablePropTypes.map.isRequired, hidden: PropTypes.bool, onMoveUp: PropTypes.func.isRequired, onMoveDown: PropTypes.func.isRequired, onMention: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleMoveUp = () => { const { notification, onMoveUp } = this.props; onMoveUp(notification.get('id')); } handleMoveDown = () => { const { notification, onMoveDown } = this.props; onMoveDown(notification.get('id')); } handleOpen = () => { const { notification } = this.props; if (notification.get('status')) { this.context.router.history.push(`/statuses/${notification.get('status')}`); } else { this.handleOpenProfile(); } } handleOpenProfile = () => { const { notification } = this.props; this.context.router.history.push(`/accounts/${notification.getIn(['account', 'id'])}`); } handleMention = e => { e.preventDefault(); const { notification, onMention } = this.props; onMention(notification.get('account'), this.context.router.history); } getHandlers () { return { moveUp: this.handleMoveUp, moveDown: this.handleMoveDown, open: this.handleOpen, openProfile: this.handleOpenProfile, mention: this.handleMention, reply: this.handleMention, }; } renderFollow (notification, account, link) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-follow focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.follow', defaultMessage: '{name} followed you' }, { name: account.get('acct') }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-user-plus' /> </div> <span title={notification.get('created_at')}> <FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} /> </span> </div> <AccountContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} /> </div> </HotKeys> ); } renderMention (notification) { return ( <StatusContainer id={notification.get('status')} withDismiss hidden={this.props.hidden} onMoveDown={this.handleMoveDown} onMoveUp={this.handleMoveUp} contextType='notifications' /> ); } renderFavourite (notification, link) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-favourite focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.favourite', defaultMessage: '{name} favourited your status' }, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-star star-icon' /> </div> <FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} /> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={!!this.props.hidden} /> </div> </HotKeys> ); } renderReblog (notification, link) { const { intl } = this.props; return ( <HotKeys handlers={this.getHandlers()}> <div className='notification notification-reblog focusable' tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.reblog', defaultMessage: '{name} boosted your status' }, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-retweet' /> </div> <FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} /> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} /> </div> </HotKeys> ); } render () { const { notification } = this.props; const account = notification.get('account'); const displayNameHtml = { __html: account.get('display_name_html') }; const link = <bdi><Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} /></bdi>; switch(notification.get('type')) { case 'follow': return this.renderFollow(notification, account, link); case 'mention': return this.renderMention(notification); case 'favourite': return this.renderFavourite(notification, link); case 'reblog': return this.renderReblog(notification, link); } return null; } }
app/Translator.js
steemit-intl/steemit.com
import React from 'react'; import isString from 'lodash/isString'; import isObject from 'lodash/isObject'; import isUndefined from 'lodash/isUndefined'; import { IntlProvider, addLocaleData, injectIntl } from 'react-intl'; // most of this code creates a wrapper for i18n API. // this is needed to make i18n future proof /* module exports two functions: translate and translateHtml usage example: translate('reply_to_user', {username: 'undeadlol1') == 'Reply to undeadlol1' translateHtml works the same, expcept it renders string with html tags in it */ // locale data is needed for various messages, ie 'N minutes ago' import enLocaleData from 'react-intl/locale-data/en'; import ruLocaleData from 'react-intl/locale-data/ru'; import frLocaleData from 'react-intl/locale-data/fr'; import esLocaleData from 'react-intl/locale-data/es'; import itLocaleData from 'react-intl/locale-data/it'; addLocaleData([...enLocaleData, ...ruLocaleData, ...frLocaleData, ...esLocaleData, ...itLocaleData]); // Our translated strings import { en } from './locales/en'; import { ru } from './locales/ru'; import { fr } from './locales/fr'; import { es } from './locales/es'; import { it } from './locales/it'; const translations = { en: en, ru: ru, fr: fr, es: es, it: it } // exported function placeholders // this is needed for proper export before react-intl functions with locale data, // will be properly created (they depend on react props and context, // which is not available until component is being created) let translate = () => {}; let translateHtml = () => {}; let translatePlural = () => {}; // react-intl's formatMessage and formatHTMLMessage functions depend on context(this is where strings are stored) // thats why we: // 1) create instance of <IntlProvider /> which wraps our application and creates react context (see "Translator" component below) // 2) create <DummyComponentToExportProps /> inside <IntlProvider /> (the "Translator" component) // 3) now we have proper context which we use to export translate() and translateHtml() to be used anywhere // all of this shenanigans are needed because many times translations are needed outside of components(in reducers and redux "connect" functions) // but since react-intl functions depends on components context it would be not possible @injectIntl // inject translation functions through 'intl' prop class DummyComponentToExportProps extends React.Component { render() { // render hidden placeholder return <span hidden>{' '}</span> } // IMPORTANT // use 'componentWillMount' instead of 'componentDidMount', // or there will be all sorts of partially renddered components componentWillMount() { // assign functions after component is created (context is picked up) translate = (...params) => this.translateHandler('string', ...params) translateHtml = (...params) => this.translateHandler('html', ...params) translatePlural = (...params) => this.translateHandler('plural', ...params) } translateHandler(translateType, id, values, options) { const { formatMessage, formatHTMLMessage, formatPlural } = this.props.intl // choose which method of rendering to choose: normal string or string with html // handler = translateType === 'string' ? formatMessage : formatHTMLMessage let handler switch (translateType) { case 'string': handler = formatMessage; break case 'html': handler = formatHTMLMessage; break case 'plural': handler = formatPlural; break default: throw new Error('unknown translate handler type') } // check if right parameters were used before running function if (isString(id)) { if (!isUndefined(values) && !isObject(values)) throw new Error('translating function second parameter must be an object!'); // map parameters for react-intl, // which uses formatMessage({id: 'stringId', values: {some: 'values'}, options: {}}) structure else return handler({id}, values, options) } else throw new Error('translating function first parameter must be a string!'); } } // actual wrapper for application class Translator extends React.Component { render() { /* LANGUAGE PICKER */ // Define user's language. Different browsers have the user locale defined // on different fields on the `navigator` object, so we make sure to account // for these different by checking all of them let language = 'en'; // while Server Side Rendering is in process, 'navigator' is undefined if (process.env.BROWSER) { language = navigator ? (navigator.languages && navigator.languages[0]) || navigator.language || navigator.userLanguage : 'en'; } //Split locales with a region code (ie. 'en-EN' to 'en') const languageWithoutRegionCode = language.toLowerCase().split(/[_-]+/)[0]; // TODO: don't forget to add Safari polyfill // to ensure dynamic language change, "key" property with same "locale" info must be added // see: https://github.com/yahoo/react-intl/wiki/Components#multiple-intl-contexts let messages = translations[languageWithoutRegionCode] return <IntlProvider locale={languageWithoutRegionCode} key={languageWithoutRegionCode} messages={messages}> <div> <DummyComponentToExportProps /> {this.props.children} </div> </IntlProvider> } } export { translate, translateHtml, translatePlural } export default Translator
app/ui/Container.js
spleenboy/pallium
import React, { Component } from 'react'; import styles from './Container.css'; export default class Container extends Component { render() { return ( <div className={styles.container}> {this.props.children} </div> ); } }
node_modules/react-dimensions/index.js
SpatialMap/SpatialMapDev
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var React = require('react'); var onElementResize = require('element-resize-event'); var defaultContainerStyle = { width: '100%', height: '100%', padding: 0, border: 0 }; function defaultGetWidth(element) { return element.clientWidth; } function defaultGetHeight(element) { return element.clientHeight; } /** * Wraps a react component and adds properties `containerHeight` and * `containerWidth`. Useful for responsive design. Properties update on * window resize. **Note** that the parent element must have either a * height or a width, or nothing will be rendered * * Can be used as a * [higher-order component](http://babeljs.io/blog/2015/06/07/react-on-es6-plus/#property-initializers) * or as an [ES7 class decorator](https://github.com/wycats/javascript-decorators) * (see examples) * * @param {object} [options] * @param {function} [options.getHeight] A function that is passed an element and returns element * height, where element is the wrapper div. Defaults to `(element) => element.clientHeight` * @param {function} [options.getWidth] A function that is passed an element and returns element * width, where element is the wrapper div. Defaults to `(element) => element.clientWidth` * @param {object} [options.containerStyle] A style object for the `<div>` that will wrap your component. * The dimensions of this `div` are what are passed as props to your component. The default style is * `{ width: '100%', height: '100%', padding: 0, border: 0 }` which will cause the `div` to fill its * parent in most cases. If you are using a flexbox layout you will want to change this default style. * @param {string} [options.className] Control the class name set on the wrapper `<div>` * @param {boolean} [options.elementResize=false] Set true to watch the wrapper `div` for changes in * size which are not a result of window resizing - e.g. changes to the flexbox and other layout. * @return {function} A higher-order component that can be * used to enhance a react component `Dimensions()(MyComponent)` * * @example * // ES2015 * import React from 'react' * import Dimensions from 'react-dimensions' * * class MyComponent extends React.Component { * render() ( * <div * containerWidth={this.props.containerWidth} * containerHeight={this.props.containerHeight} * > * </div> * ) * } * * export default Dimensions()(MyComponent) // Enhanced component * * @example * // ES5 * var React = require('react') * var Dimensions = require('react-dimensions') * * var MyComponent = React.createClass({ * render: function() {( * <div * containerWidth={this.props.containerWidth} * containerHeight={this.props.containerHeight} * > * </div> * )} * } * * module.exports = Dimensions()(MyComponent) // Enhanced component * */ module.exports = function Dimensions() { var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _ref$getHeight = _ref.getHeight; var getHeight = _ref$getHeight === undefined ? defaultGetHeight : _ref$getHeight; var _ref$getWidth = _ref.getWidth; var getWidth = _ref$getWidth === undefined ? defaultGetWidth : _ref$getWidth; var _ref$containerStyle = _ref.containerStyle; var containerStyle = _ref$containerStyle === undefined ? defaultContainerStyle : _ref$containerStyle; var _ref$className = _ref.className; var className = _ref$className === undefined ? null : _ref$className; var _ref$elementResize = _ref.elementResize; var elementResize = _ref$elementResize === undefined ? false : _ref$elementResize; return function (ComposedComponent) { return function (_React$Component) { _inherits(DimensionsHOC, _React$Component); function DimensionsHOC() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, DimensionsHOC); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(DimensionsHOC)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = {}, _this.updateDimensions = function () { var container = _this.refs.container; var containerWidth = getWidth(container); var containerHeight = getHeight(container); if (containerWidth !== _this.state.containerWidth || containerHeight !== _this.state.containerHeight) { _this.setState({ containerWidth: containerWidth, containerHeight: containerHeight }); } }, _this.onResize = function () { if (_this.rqf) return; _this.rqf = _this.getWindow().requestAnimationFrame(function () { _this.rqf = null; _this.updateDimensions(); }); }, _temp), _possibleConstructorReturn(_this, _ret); } // ES7 Class properties // http://babeljs.io/blog/2015/06/07/react-on-es6-plus/#property-initializers // Using arrow functions and ES7 Class properties to autobind // http://babeljs.io/blog/2015/06/07/react-on-es6-plus/#arrow-functions _createClass(DimensionsHOC, [{ key: 'getWindow', // If the component is mounted in a different window to the javascript // context, as with https://github.com/JakeGinnivan/react-popout // then the `window` global will be different from the `window` that // contains the component. // Depends on `defaultView` which is not supported <IE9 value: function getWindow() { return this.refs.container ? this.refs.container.ownerDocument.defaultView || window : window; } }, { key: 'componentDidMount', value: function componentDidMount() { if (!this.refs.container) { throw new Error('Cannot find container div'); } this.updateDimensions(); if (elementResize) { // Experimental: `element-resize-event` fires when an element resizes. // It attaches its own window resize listener and also uses // requestAnimationFrame, so we can just call `this.updateDimensions`. onElementResize(this.refs.container, this.updateDimensions); } else { this.getWindow().addEventListener('resize', this.onResize, false); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.getWindow().removeEventListener('resize', this.onResize); } /** * Returns the underlying wrapped component instance. * Useful if you need to access a method or property of the component * passed to react-dimensions. * * @return {object} The rendered React component **/ }, { key: 'getWrappedInstance', value: function getWrappedInstance() { this.refs.wrappedInstance; } }, { key: 'render', value: function render() { var _state = this.state; var containerWidth = _state.containerWidth; var containerHeight = _state.containerHeight; if (!containerWidth && !containerHeight) { console.warn('Wrapper div has no height or width, try overriding style with `containerStyle` option'); } return React.createElement( 'div', { className: className, style: containerStyle, ref: 'container' }, (containerWidth || containerHeight) && React.createElement(ComposedComponent, _extends({}, this.state, this.props, { updateDimensions: this.updateDimensions, ref: 'wrappedInstance' })) ); } }]); return DimensionsHOC; }(React.Component); }; };
packages/ringcentral-widgets-docs/src/app/pages/Components/Spinner/Demo.js
u9520107/ringcentral-js-widget
import React from 'react'; // eslint-disable-next-line import Spinner from 'ringcentral-widgets/components/Spinner'; const props = {}; /** * A example of `Spinner` */ const SpinnerDemo = () => ( <div style={{ position: 'relative', height: '50px', width: '50px', }}> <Spinner {...props} /> </div> ); export default SpinnerDemo;
src/labels/IndividuLabel.js
dezede/dezede
import React from 'react'; import PropTypes from 'prop-types'; import {computed} from "mobx"; import {observer} from "mobx-react"; import Individu from "../models/Individu"; @observer class IndividuLabel extends React.Component { static propTypes = { id: PropTypes.number.isRequired, }; @computed get individu() { return Individu.getById(this.props.id); } render() { if (this.individu === null || !this.individu.loaded) { return null; } return ( <span dangerouslySetInnerHTML={{__html: this.individu.html}} /> ); } } export default IndividuLabel;
docs/app/Examples/elements/Header/Variations/HeaderExampleInverted.js
vageeshb/Semantic-UI-React
import React from 'react' import { Header, Segment } from 'semantic-ui-react' const HeaderExampleInverted = () => ( <Segment inverted> <Header as='h4' inverted color='red'>Red</Header> <Header as='h4' inverted color='orange'>Orange</Header> <Header as='h4' inverted color='yellow'>Yellow</Header> <Header as='h4' inverted color='olive'>Olive</Header> <Header as='h4' inverted color='green'>Green</Header> <Header as='h4' inverted color='teal'>Teal</Header> <Header as='h4' inverted color='blue'>Blue</Header> <Header as='h4' inverted color='purple'>Purple</Header> <Header as='h4' inverted color='violet'>Violet</Header> <Header as='h4' inverted color='pink'>Pink</Header> <Header as='h4' inverted color='brown'>Brown</Header> <Header as='h4' inverted color='grey'>Grey</Header> </Segment> ) export default HeaderExampleInverted
src/svg-icons/action/three-d-rotation.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionThreeDRotation = (props) => ( <SvgIcon {...props}> <path d="M7.52 21.48C4.25 19.94 1.91 16.76 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32zm.89-6.52c-.19 0-.37-.03-.52-.08-.16-.06-.29-.13-.4-.24-.11-.1-.2-.22-.26-.37-.06-.14-.09-.3-.09-.47h-1.3c0 .36.07.68.21.95.14.27.33.5.56.69.24.18.51.32.82.41.3.1.62.15.96.15.37 0 .72-.05 1.03-.15.32-.1.6-.25.83-.44s.42-.43.55-.72c.13-.29.2-.61.2-.97 0-.19-.02-.38-.07-.56-.05-.18-.12-.35-.23-.51-.1-.16-.24-.3-.4-.43-.17-.13-.37-.23-.61-.31.2-.09.37-.2.52-.33.15-.13.27-.27.37-.42.1-.15.17-.3.22-.46.05-.16.07-.32.07-.48 0-.36-.06-.68-.18-.96-.12-.28-.29-.51-.51-.69-.2-.19-.47-.33-.77-.43C9.1 8.05 8.76 8 8.39 8c-.36 0-.69.05-1 .16-.3.11-.57.26-.79.45-.21.19-.38.41-.51.67-.12.26-.18.54-.18.85h1.3c0-.17.03-.32.09-.45s.14-.25.25-.34c.11-.09.23-.17.38-.22.15-.05.3-.08.48-.08.4 0 .7.1.89.31.19.2.29.49.29.86 0 .18-.03.34-.08.49-.05.15-.14.27-.25.37-.11.1-.25.18-.41.24-.16.06-.36.09-.58.09H7.5v1.03h.77c.22 0 .42.02.6.07s.33.13.45.23c.12.11.22.24.29.4.07.16.1.35.1.57 0 .41-.12.72-.35.93-.23.23-.55.33-.95.33zm8.55-5.92c-.32-.33-.7-.59-1.14-.77-.43-.18-.92-.27-1.46-.27H12v8h2.3c.55 0 1.06-.09 1.51-.27.45-.18.84-.43 1.16-.76.32-.33.57-.73.74-1.19.17-.47.26-.99.26-1.57v-.4c0-.58-.09-1.1-.26-1.57-.18-.47-.43-.87-.75-1.2zm-.39 3.16c0 .42-.05.79-.14 1.13-.1.33-.24.62-.43.85-.19.23-.43.41-.71.53-.29.12-.62.18-.99.18h-.91V9.12h.97c.72 0 1.27.23 1.64.69.38.46.57 1.12.57 1.99v.4zM12 0l-.66.03 3.81 3.81 1.33-1.33c3.27 1.55 5.61 4.72 5.96 8.48h1.5C23.44 4.84 18.29 0 12 0z"/> </SvgIcon> ); ActionThreeDRotation = pure(ActionThreeDRotation); ActionThreeDRotation.displayName = 'ActionThreeDRotation'; ActionThreeDRotation.muiName = 'SvgIcon'; export default ActionThreeDRotation;
test/integration/client-navigation/pages/nav/head-2.js
BlancheXu/test
import React from 'react' import Head from 'next/head' import Link from 'next/link' export default props => ( <div id='head-2'> <Head> <meta name='description' content='Head Two' /> <title>this is head-2</title> </Head> <Link href='/nav/head-1'> <a id='to-head-1'>to head 1</a> </Link> </div> )
app/Images.js
SKatiyar/LetterTrack
'use strict'; import React, { Component } from 'react'; import { Modal, Image, StyleSheet, View, Text, TouchableWithoutFeedback, } from 'react-native'; import { Button, Icon, Toast, } from 'native-base'; export default class ImageList extends Component { constructor(props) { super(props); this.showModal = this.showModal.bind(this); this.removeImage = this.removeImage.bind(this); this.state = { images: props.images ? props.images.split(',') : [], modalVisible: false, previewImage: '', }; }; componentWillReceiveProps(nextProps) { this.setState({ images: nextProps.images ? nextProps.images.split(',') : [] }); }; showModal(img) { if (img) { this.setState({ modalVisible: true, previewImage: img, }); } else { this.setState({ modalVisible: false, previewImage: '', }); } }; removeImage() { this.props.removeImage(this.state.previewImage); this.showModal(); }; render() { let imagesEles = this.state.images.map(function(ele) { return ( <TouchableWithoutFeedback onPress={() => {this.showModal(ele)}} key={ele}> <Image source={{uri: ele}} style={styles.imagePreview} /> </TouchableWithoutFeedback> ); }.bind(this)); return ( <View> <View style={styles.imagesContainer}> {imagesEles} <TouchableWithoutFeedback onPress={() => {this.props.showCamera(true)}}> <View style={styles.addLetterImage}> <Text>Add Image</Text> <Icon name='md-camera' /> </View> </TouchableWithoutFeedback> </View> <Modal animationType={'fade'} transparent={false} visible={this.state.modalVisible} onRequestClose={() => {this.showModal()}}> <Image source={{uri: this.state.previewImage}} style={styles.modalPreview}/> <Button style={styles.deleteButton} onPress={this.removeImage}> <Icon name="md-trash" style={styles.deleteLabel}/> </Button> </Modal> </View> ); }; }; const styles = StyleSheet.create({ addLetterImage: { height: 150, width: 100, justifyContent: 'center', alignItems: 'center', backgroundColor: '#DDD', }, imagePreview: { height: 150, width: 100, marginRight: 5, borderWidth: 1, borderColor: '#00000011', }, imagesContainer: { flex: 1, flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'flex-start' }, deleteButton: { position: 'absolute', bottom: 5, width: 100, backgroundColor: '#E74C3C', marginRight: 5, marginLeft: 5, justifyContent: 'center' }, modalPreview: { flex: 1, resizeMode: 'contain', }, deleteLabel: { color: '#FFFFFF' }, });
src/svg-icons/action/motorcycle.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionMotorcycle = (props) => ( <SvgIcon {...props}> <path d="M19.44 9.03L15.41 5H11v2h3.59l2 2H5c-2.8 0-5 2.2-5 5s2.2 5 5 5c2.46 0 4.45-1.69 4.9-4h1.65l2.77-2.77c-.21.54-.32 1.14-.32 1.77 0 2.8 2.2 5 5 5s5-2.2 5-5c0-2.65-1.97-4.77-4.56-4.97zM7.82 15C7.4 16.15 6.28 17 5 17c-1.63 0-3-1.37-3-3s1.37-3 3-3c1.28 0 2.4.85 2.82 2H5v2h2.82zM19 17c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z"/> </SvgIcon> ); ActionMotorcycle = pure(ActionMotorcycle); ActionMotorcycle.displayName = 'ActionMotorcycle'; ActionMotorcycle.muiName = 'SvgIcon'; export default ActionMotorcycle;
app/js/app.js
benekex2/smart_mirror
import React from 'react' import ReactDOM from 'react-dom' import '../css/app.css' import '../css/weather-icons.css' import { Weather } from "./components/weather.js" import { Clock } from "./components/clock.js" import { News } from "./components/news.js" import { WeatherInside } from "./components/weatherInside.js" import bbcLogo from '../images/bbc-logo.png' import cnnLogo from '../images/cnn-logo.png' import twpLogo from '../images/twp-logo.png' import twsjLogo from '../images/twsj-logo.png' export class App extends React.Component { render() { return ( <div className="container"> <header> <div className="clock component"> <Clock name="CityRow" UTCOffset="1"/> <WeatherInside /> </div> <div className="weather component"> <Weather /> </div> </header> <footer> <div className="news component"> <News source="bbc-news" image={bbcLogo} /> <News source="the-washington-post" image={twpLogo} /> </div> <div className="news component"> <News source="cnn" image={cnnLogo} /> <News source="the-wall-street-journal" image={twsjLogo} /> </div> </footer> </div> ); } } ReactDOM.render( <App />, document.getElementById('root') );
app/components/tab-icon.js
7kfpun/BitcoinReactNative
import React from 'react'; import { Text, View, } from 'react-native'; import { ifIphoneX } from 'react-native-iphone-x-helper'; export default class TabIcon extends React.PureComponent { render() { return ( <View style={{ alignItems: 'center', ...ifIphoneX({ paddingBottom: 60, }, {}), }} > <Text style={{ color: this.props.selected ? '#00B9EA' : 'gray', fontSize: 15 }} >{this.props.title}</Text> </View> ); } } TabIcon.propTypes = { title: React.PropTypes.string, selected: React.PropTypes.bool, }; TabIcon.defaultProps = { title: '', selected: false, };
src/components/comment_list.js
vndeguzman/redux-exercise
import React from 'react' import { connect } from 'react-redux'; const CommentList = (props) => { const list = props.comments.map(comment => <li key={comment}>{comment}</li>); return ( <ul className="comment-list"> {list} </ul> ) }; function mapStateToProps(state) { return { comments: state.comments } } export default connect(mapStateToProps)(CommentList);
app/javascript/mastodon/components/poll.js
abcang/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import Motion from 'mastodon/features/ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import escapeTextContentForBrowser from 'escape-html'; import emojify from 'mastodon/features/emoji/emoji'; import RelativeTimestamp from './relative_timestamp'; import Icon from 'mastodon/components/icon'; const messages = defineMessages({ closed: { id: 'poll.closed', defaultMessage: 'Closed', }, voted: { id: 'poll.voted', defaultMessage: 'You voted for this answer', }, votes: { id: 'poll.votes', defaultMessage: '{votes, plural, one {# vote} other {# votes}}', }, }); const makeEmojiMap = record => record.get('emojis').reduce((obj, emoji) => { obj[`:${emoji.get('shortcode')}:`] = emoji.toJS(); return obj; }, {}); export default @injectIntl class Poll extends ImmutablePureComponent { static propTypes = { poll: ImmutablePropTypes.map, intl: PropTypes.object.isRequired, disabled: PropTypes.bool, refresh: PropTypes.func, onVote: PropTypes.func, }; state = { selected: {}, expired: null, }; static getDerivedStateFromProps (props, state) { const { poll, intl } = props; const expires_at = poll.get('expires_at'); const expired = poll.get('expired') || expires_at !== null && (new Date(expires_at)).getTime() < intl.now(); return (expired === state.expired) ? null : { expired }; } componentDidMount () { this._setupTimer(); } componentDidUpdate () { this._setupTimer(); } componentWillUnmount () { clearTimeout(this._timer); } _setupTimer () { const { poll, intl } = this.props; clearTimeout(this._timer); if (!this.state.expired) { const delay = (new Date(poll.get('expires_at'))).getTime() - intl.now(); this._timer = setTimeout(() => { this.setState({ expired: true }); }, delay); } } _toggleOption = value => { if (this.props.poll.get('multiple')) { const tmp = { ...this.state.selected }; if (tmp[value]) { delete tmp[value]; } else { tmp[value] = true; } this.setState({ selected: tmp }); } else { const tmp = {}; tmp[value] = true; this.setState({ selected: tmp }); } } handleOptionChange = ({ target: { value } }) => { this._toggleOption(value); }; handleOptionKeyPress = (e) => { if (e.key === 'Enter' || e.key === ' ') { this._toggleOption(e.target.getAttribute('data-index')); e.stopPropagation(); e.preventDefault(); } } handleVote = () => { if (this.props.disabled) { return; } this.props.onVote(Object.keys(this.state.selected)); }; handleRefresh = () => { if (this.props.disabled) { return; } this.props.refresh(); }; renderOption (option, optionIndex, showResults) { const { poll, disabled, intl } = this.props; const pollVotesCount = poll.get('voters_count') || poll.get('votes_count'); const percent = pollVotesCount === 0 ? 0 : (option.get('votes_count') / pollVotesCount) * 100; const leading = poll.get('options').filterNot(other => other.get('title') === option.get('title')).every(other => option.get('votes_count') >= other.get('votes_count')); const active = !!this.state.selected[`${optionIndex}`]; const voted = option.get('voted') || (poll.get('own_votes') && poll.get('own_votes').includes(optionIndex)); let titleEmojified = option.get('title_emojified'); if (!titleEmojified) { const emojiMap = makeEmojiMap(poll); titleEmojified = emojify(escapeTextContentForBrowser(option.get('title')), emojiMap); } return ( <li key={option.get('title')}> <label className={classNames('poll__option', { selectable: !showResults })}> <input name='vote-options' type={poll.get('multiple') ? 'checkbox' : 'radio'} value={optionIndex} checked={active} onChange={this.handleOptionChange} disabled={disabled} /> {!showResults && ( <span className={classNames('poll__input', { checkbox: poll.get('multiple'), active })} tabIndex='0' role={poll.get('multiple') ? 'checkbox' : 'radio'} onKeyPress={this.handleOptionKeyPress} aria-checked={active} aria-label={option.get('title')} data-index={optionIndex} /> )} {showResults && ( <span className='poll__number' title={intl.formatMessage(messages.votes, { votes: option.get('votes_count'), })} > {Math.round(percent)}% </span> )} <span className='poll__option__text translate' dangerouslySetInnerHTML={{ __html: titleEmojified }} /> {!!voted && <span className='poll__voted'> <Icon id='check' className='poll__voted__mark' title={intl.formatMessage(messages.voted)} /> </span>} </label> {showResults && ( <Motion defaultStyle={{ width: 0 }} style={{ width: spring(percent, { stiffness: 180, damping: 12 }) }}> {({ width }) => <span className={classNames('poll__chart', { leading })} style={{ width: `${width}%` }} /> } </Motion> )} </li> ); } render () { const { poll, intl } = this.props; const { expired } = this.state; if (!poll) { return null; } const timeRemaining = expired ? intl.formatMessage(messages.closed) : <RelativeTimestamp timestamp={poll.get('expires_at')} futureDate />; const showResults = poll.get('voted') || expired; const disabled = this.props.disabled || Object.entries(this.state.selected).every(item => !item); let votesCount = null; if (poll.get('voters_count') !== null && poll.get('voters_count') !== undefined) { votesCount = <FormattedMessage id='poll.total_people' defaultMessage='{count, plural, one {# person} other {# people}}' values={{ count: poll.get('voters_count') }} />; } else { votesCount = <FormattedMessage id='poll.total_votes' defaultMessage='{count, plural, one {# vote} other {# votes}}' values={{ count: poll.get('votes_count') }} />; } return ( <div className='poll'> <ul> {poll.get('options').map((option, i) => this.renderOption(option, i, showResults))} </ul> <div className='poll__footer'> {!showResults && <button className='button button-secondary' disabled={disabled} onClick={this.handleVote}><FormattedMessage id='poll.vote' defaultMessage='Vote' /></button>} {showResults && !this.props.disabled && <span><button className='poll__link' onClick={this.handleRefresh}><FormattedMessage id='poll.refresh' defaultMessage='Refresh' /></button> · </span>} {votesCount} {poll.get('expires_at') && <span> · {timeRemaining}</span>} </div> </div> ); } }
src/js/components/Tag.js
davrodpin/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Anchor from './Anchor'; import Props from '../utils/Props'; import CSSClassnames from '../utils/CSSClassnames'; const CLASS_ROOT = CSSClassnames.TAG; export default class Tag extends Component { render () { let classes = [CLASS_ROOT]; if (this.props.className) { classes.push(this.props.className); } var other = Props.pick(this.props, Object.keys(Anchor.propTypes)); return ( <div className={classes.join(' ')} onClick={this.props.onClick}> {this.props.children} <Anchor {...other} className={`${CLASS_ROOT}--label`}> <span>{this.props.label}</span> </Anchor> </div> ); } } Tag.propTypes = { label: React.PropTypes.string, ...Anchor.propTypes };
frontend/src/lib/ResponsiveTable.js
GAumala/Facturacion
import React, { Component } from 'react'; import { Table } from 'fixed-data-table'; import ContainerDimensions from 'react-container-dimensions'; /** * This component draws a Table efficiently using all the space available. It expects the parent to have all the height available, so that the table fits the size of the window. If this condition is not met, the table may not render at all. */ export default class ResponsiveTable extends Component { render() { return ( <ContainerDimensions> {({ width, height }) => <Table rowHeight={this.props.rowHeight || 50} rowsCount={this.props.rowsCount} width={width} height={height} headerHeight={this.props.headerHeight || 50} > {this.props.children} </Table>} </ContainerDimensions> ); } }
app/javascript/mastodon/features/compose/components/compose_form.js
imas/mastodon
import React from 'react'; import CharacterCounter from './character_counter'; import Button from '../../../components/button'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ReplyIndicatorContainer from '../containers/reply_indicator_container'; import AutosuggestTextarea from '../../../components/autosuggest_textarea'; import AutosuggestInput from '../../../components/autosuggest_input'; import UploadButtonContainer from '../containers/upload_button_container'; import { defineMessages, injectIntl } from 'react-intl'; import SpoilerButtonContainer from '../containers/spoiler_button_container'; import PrivacyDropdownContainer from '../containers/privacy_dropdown_container'; import EmojiPickerDropdown from '../containers/emoji_picker_dropdown_container'; import UploadFormContainer from '../containers/upload_form_container'; import WarningContainer from '../containers/warning_container'; import { isMobile } from '../../../is_mobile'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { length } from 'stringz'; import { countableText } from '../util/counter'; import Icon from 'mastodon/components/icon'; const allowedAroundShortCode = '><\u0085\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\u0009\u000a\u000b\u000c\u000d'; const messages = defineMessages({ placeholder: { id: 'compose_form.placeholder', defaultMessage: 'What is on your mind?' }, spoiler_placeholder: { id: 'compose_form.spoiler_placeholder', defaultMessage: 'Write your warning here' }, publish: { id: 'compose_form.publish', defaultMessage: 'Toot' }, publishLoud: { id: 'compose_form.publish_loud', defaultMessage: '{publish}!' }, }); export default @injectIntl class ComposeForm extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { intl: PropTypes.object.isRequired, text: PropTypes.string.isRequired, suggestions: ImmutablePropTypes.list, spoiler: PropTypes.bool, privacy: PropTypes.string, spoilerText: PropTypes.string, focusDate: PropTypes.instanceOf(Date), caretPosition: PropTypes.number, preselectDate: PropTypes.instanceOf(Date), isSubmitting: PropTypes.bool, isChangingUpload: PropTypes.bool, isUploading: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClearSuggestions: PropTypes.func.isRequired, onFetchSuggestions: PropTypes.func.isRequired, onSuggestionSelected: PropTypes.func.isRequired, onChangeSpoilerText: PropTypes.func.isRequired, onPaste: PropTypes.func.isRequired, onPickEmoji: PropTypes.func.isRequired, showSearch: PropTypes.bool, anyMedia: PropTypes.bool, singleColumn: PropTypes.bool, }; static defaultProps = { showSearch: false, }; handleChange = (e) => { this.props.onChange(e.target.value); } handleKeyDown = (e) => { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { this.handleSubmit(); } } getFulltextForCharacterCounting = () => { return [this.props.spoiler? this.props.spoilerText: '', countableText(this.props.text)].join(''); } canSubmit = () => { const { isSubmitting, isChangingUpload, isUploading, anyMedia } = this.props; const fulltext = this.getFulltextForCharacterCounting(); const isOnlyWhitespace = fulltext.length !== 0 && fulltext.trim().length === 0; return !(isSubmitting || isUploading || isChangingUpload || length(fulltext) > 500 || (isOnlyWhitespace && !anyMedia)); } handleSubmit = () => { if (this.props.text !== this.autosuggestTextarea.textarea.value) { // Something changed the text inside the textarea (e.g. browser extensions like Grammarly) // Update the state to match the current text this.props.onChange(this.autosuggestTextarea.textarea.value); } if (!this.canSubmit()) { return; } this.props.onSubmit(this.context.router ? this.context.router.history : null); } onSuggestionsClearRequested = () => { this.props.onClearSuggestions(); } onSuggestionsFetchRequested = (token) => { this.props.onFetchSuggestions(token); } onSuggestionSelected = (tokenStart, token, value) => { this.props.onSuggestionSelected(tokenStart, token, value, ['text']); } onSpoilerSuggestionSelected = (tokenStart, token, value) => { this.props.onSuggestionSelected(tokenStart, token, value, ['spoiler_text']); } handleChangeSpoilerText = (e) => { this.props.onChangeSpoilerText(e.target.value); } handleFocus = () => { if (this.composeForm && !this.props.singleColumn) { const { left, right } = this.composeForm.getBoundingClientRect(); if (left < 0 || right > (window.innerWidth || document.documentElement.clientWidth)) { this.composeForm.scrollIntoView(); } } } componentDidMount () { this._updateFocusAndSelection({ }); } componentDidUpdate (prevProps) { this._updateFocusAndSelection(prevProps); } _updateFocusAndSelection = (prevProps) => { // This statement does several things: // - If we're beginning a reply, and, // - Replying to zero or one users, places the cursor at the end of the textbox. // - Replying to more than one user, selects any usernames past the first; // this provides a convenient shortcut to drop everyone else from the conversation. if (this.props.focusDate !== prevProps.focusDate) { let selectionEnd, selectionStart; if (this.props.preselectDate !== prevProps.preselectDate) { selectionEnd = this.props.text.length; selectionStart = this.props.text.search(/\s/) + 1; } else if (typeof this.props.caretPosition === 'number') { selectionStart = this.props.caretPosition; selectionEnd = this.props.caretPosition; } else { selectionEnd = this.props.text.length; selectionStart = selectionEnd; } this.autosuggestTextarea.textarea.setSelectionRange(selectionStart, selectionEnd); this.autosuggestTextarea.textarea.focus(); } else if(prevProps.isSubmitting && !this.props.isSubmitting) { this.autosuggestTextarea.textarea.setSelectionRange(0, 0) this.autosuggestTextarea.textarea.focus(); } else if (this.props.spoiler !== prevProps.spoiler) { if (this.props.spoiler) { this.spoilerText.input.focus(); } else { this.autosuggestTextarea.textarea.focus(); } } } setAutosuggestTextarea = (c) => { this.autosuggestTextarea = c; } setSpoilerText = (c) => { this.spoilerText = c; } setRef = c => { this.composeForm = c; }; handleEmojiPick = (data) => { const { text } = this.props; const position = this.autosuggestTextarea.textarea.selectionStart; const needsSpace = data.custom && position > 0 && !allowedAroundShortCode.includes(text[position - 1]); this.props.onPickEmoji(position, data, needsSpace); } render () { const { intl, onPaste, showSearch } = this.props; const disabled = this.props.isSubmitting; let publishText = ''; if (this.props.privacy === 'private' || this.props.privacy === 'direct') { publishText = <span className='compose-form__publish-private'><Icon id='lock' /> {intl.formatMessage(messages.publish)}</span>; } else { publishText = this.props.privacy !== 'unlisted' ? intl.formatMessage(messages.publishLoud, { publish: intl.formatMessage(messages.publish) }) : intl.formatMessage(messages.publish); } return ( <div className='compose-form'> <WarningContainer /> <ReplyIndicatorContainer /> <div className={`spoiler-input ${this.props.spoiler ? 'spoiler-input--visible' : ''}`} ref={this.setRef}> <AutosuggestInput placeholder={intl.formatMessage(messages.spoiler_placeholder)} value={this.props.spoilerText} onChange={this.handleChangeSpoilerText} onKeyDown={this.handleKeyDown} disabled={!this.props.spoiler} ref={this.setSpoilerText} suggestions={this.props.suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSpoilerSuggestionSelected} searchTokens={[':']} id='cw-spoiler-input' className='spoiler-input__input' /> </div> <AutosuggestTextarea ref={this.setAutosuggestTextarea} placeholder={intl.formatMessage(messages.placeholder)} disabled={disabled} value={this.props.text} onChange={this.handleChange} suggestions={this.props.suggestions} onFocus={this.handleFocus} onKeyDown={this.handleKeyDown} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} onPaste={onPaste} autoFocus={!showSearch && !isMobile(window.innerWidth)} > <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} /> <div className='compose-form__modifiers'> <UploadFormContainer /> </div> </AutosuggestTextarea> <div className='compose-form__buttons-wrapper'> <div className='compose-form__buttons'> <UploadButtonContainer /> <PrivacyDropdownContainer /> <SpoilerButtonContainer /> </div> <div className='character-counter__wrapper'><CharacterCounter max={500} text={this.getFulltextForCharacterCounting()} /></div> </div> <div className='compose-form__publish'> <div className='compose-form__publish-button-wrapper'><Button text={publishText} onClick={this.handleSubmit} disabled={!this.canSubmit()} block /></div> </div> </div> ); } }
src/client.js
Nek/react-redux-universal-hot-example
/* global __DEVTOOLS__ */ import React from 'react'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import Location from 'react-router/lib/Location'; import createStore from './redux/create'; import ApiClient from './ApiClient'; import universalRouter from './universalRouter'; const history = new BrowserHistory(); const client = new ApiClient(); const dest = document.getElementById('content'); const store = createStore(client, window.__data); const location = new Location(document.location.pathname, document.location.search); universalRouter(location, history, store) .then((component) => { if (__DEVTOOLS__) { const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react'); console.info('You will see a "Warning: React attempted to reuse markup in a container but the checksum was' + ' invalid." message. That\'s because the redux-devtools are enabled.'); React.render(<div> {component} <DebugPanel top right bottom key="debugPanel"> <DevTools store={store} monitor={LogMonitor}/> </DebugPanel> </div>, dest); } else { React.render(component, dest); } }, (error) => { console.error(error); }); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger const reactRoot = window.document.getElementById('content'); if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } }
app/containers/Preschool/EditPreschool.js
klpdotorg/tada-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Formsy from 'formsy-react'; import FRC from 'formsy-react-components'; import get from 'lodash.get'; import isEmpty from 'lodash.isempty'; import { deleteInstitution, modifyInstitution, enableSubmitForm, disableSubmitForm, openDeleteBoundaryModal, } from '../../actions'; import { Confirm } from '../Modal'; import { hasChildren } from '../../utils'; const { Input, Textarea, Select } = FRC; class EditPreschoolForm extends Component { constructor() { super(); this.saveInsti = this.saveInsti.bind(this); this.deleteInstitution = this.deleteInstitution.bind(this); } saveInsti() { const myform = this.myform.getModel(); const institution = { dise_code: myform.institutionDise_code, institution_gender: myform.institutionGender, name: myform.institutionName, address: myform.institutionAddress, area: myform.institutionArea, landmark: myform.institutionLandmark, pincode: myform.institutionPincode, cat: myform.institutionCat, languages: myform.institutionLang, mgmt: myform.institutionMgmt, id: this.props.institution.id, }; this.props.save(this.props.institution.id, institution); } deleteInstitution() { const { institution, circleNodeId, institutionNodeId } = this.props; const params = { boundaryNodeId: institutionNodeId, boundaryId: institution.id, parentId: circleNodeId, }; this.props.deleteInstitution(params); } render() { const selectOptions = [ { value: 'co-ed', label: 'Co-Ed' }, { value: 'boys', label: 'Boys' }, { value: 'girls', label: 'Girls' }, ]; const singleSelectOptions = [{ value: '', label: 'Please select…' }, ...selectOptions]; const { institution, canSubmit, canDelete, languages, institutionCategories, managements, error, } = this.props; return ( <Formsy.Form onValidSubmit={this.saveInsti} onValid={this.props.enableSubmitForm} onInvalid={this.props.disableSubmitForm} ref={(ref) => { this.myform = ref; }} > {!isEmpty(error) ? ( <div className="alert alert-danger"> {Object.keys(error).map((key) => { const value = error[key]; return ( <p key={key}> <strong>{key}:</strong> {value[0]} </p> ); })} </div> ) : ( <span /> )} <div className="form-group"> <div className="col-sm-12"> <Input name="institutionName" id="institutionName" value={institution.name} label="Institution :" type="text" className="form-control" required validations="minLength:1" /> </div> </div> <div className="form-group"> <div className="col-sm-12"> <Textarea rows={3} cols={40} name="institutionAddress" label="Address :" value={institution.address} required validations="minLength:1" /> </div> </div> <div className="form-group"> <div className="col-sm-12"> <Input name="institutionArea" id="institutionArea" value={institution.area} label="Area:" type="text" className="form-control" /> </div> </div> <div className="form-group"> <div className="col-sm-12"> <Input name="institutionLandmark" id="institutionLandmark" value={institution.landmark} label="Landmark:" type="text" className="form-control" /> </div> </div> <div className="form-group"> <div className="col-sm-12"> <Input name="institutionPincode" id="institutionPincode" value={institution.pincode} label="Pincode:" type="text" className="form-control" /> </div> </div> <div className="form-group"> <div className="col-sm-12"> <Select name="institutionCat" label="Category:" value={institution.category} options={institutionCategories} /> </div> </div> <div className="form-group"> <div className="col-sm-12"> <Select multiple name="institutionLang" label="Medium:" value={institution.languages} options={languages} required /> </div> </div> <div className="form-group"> <div className="col-sm-12"> <Select name="institutionGender" label="Gender:" value={institution.institution_gender} options={singleSelectOptions} required /> </div> </div> <div className="form-group"> <div className="col-sm-12"> <Select name="institutionMgmt" label="Management:" value={institution.mgmt} options={managements} required /> </div> </div> <div className="form-group"> <div className="col-sm-12"> <Input name="institutionDise_code" id="institutionDise_code" value={institution.dise} label="DISE Code:" type="text" className="form-control" /> </div> </div> <div className="col-md-12"> <button type="submit" className="btn btn-primary padded-btn" disabled={!canSubmit}> Save </button> <button type="button" className="btn btn-primary padded-btn" disabled={!canDelete} onClick={() => { this.props.showConfirmModal(institution.name); }} > Delete </button> <Confirm onYes={this.deleteInstitution} /> </div> </Formsy.Form> ); } } EditPreschoolForm.propTypes = { error: PropTypes.object, canSubmit: PropTypes.bool, circleNodeId: PropTypes.string, institutionNodeId: PropTypes.string, institution: PropTypes.object, canDelete: PropTypes.bool, languages: PropTypes.array, managements: PropTypes.array, institutionCategories: PropTypes.array, save: PropTypes.func, deleteInstitution: PropTypes.func, showConfirmModal: PropTypes.func, enableSubmitForm: PropTypes.func, disableSubmitForm: PropTypes.func, }; const mapStateToProps = (state, ownProps) => { const { isAdmin } = state.profile; const { institutionNodeId } = ownProps; const { boundaries } = state; return { canDelete: isAdmin && hasChildren(institutionNodeId, boundaries), openConfirmModal: state.appstate.confirmModal, institution: get(boundaries.boundaryDetails, institutionNodeId, {}), canSubmit: state.appstate.enableSubmitForm, languages: state.languages.languages, managements: state.institution.managements, institutionCategories: state.institution.institutionCats, error: boundaries.editError, }; }; const EditPreschool = connect(mapStateToProps, { save: modifyInstitution, deleteInstitution, enableSubmitForm, disableSubmitForm, showConfirmModal: openDeleteBoundaryModal, })(EditPreschoolForm); export { EditPreschool };
src/components/mention-area.component.js
dyesseyumba/git-point
import React, { Component } from 'react'; import fuzzysort from 'fuzzysort'; import styled from 'styled-components'; import { TouchableOpacity, Animated, ScrollView } from 'react-native'; import { animations, fonts, normalize } from 'config'; const StyledAnimatedView = styled(Animated.View)` ${({ style }) => style}; `; const SuggestionsRowContainer = styled.View` flex-direction: row; padding: 5px 15px; `; const UserDetailsBox = styled.View` flex: 1; margin: 5px; `; const DisplayNameText = styled.Text` font-size: ${normalize(12)}; ${fonts.fontPrimary}; `; export class MentionArea extends Component { props: { users: Array, trigger: string, text: string, updateText: Function, height: number, style: Object, }; state: { height: number, tracking: boolean, }; constructor() { super(); this.state = { height: new Animated.Value(0), tracking: false, }; } componentDidUpdate() { const { text, trigger } = this.props; if ( !this.state.tracking && text[text.length - 1] === trigger && (text[text.length - 2] === ' ' || text.length === 1) ) { this.startTracking(); } if (this.state.tracking && (text[text.length - 1] === ' ' || text === '')) { this.stopTracking(); } } onSuggestionTap(user, close) { const { text, trigger } = this.props; if (text.slice(0, text.lastIndexOf(trigger)) === '') { this.props.updateText(`@${user} `); } else { this.props.updateText( `${text.slice(0, text.lastIndexOf(trigger) - 1)} @${user} ` ); } if (close) { this.stopTracking(); } } getSearchedUsers() { const { users, text, trigger = '@' } = this.props; const searchableText = text.slice(text.lastIndexOf(trigger) + 1); const results = fuzzysort .go(searchableText, users, { highlightMatches: false, threshold: -200, }) .map(user => user.target); return results; } startTracking() { this.openSuggestionsPanel(); this.setState({ tracking: true }); } stopTracking() { this.closeSuggestionsPanel(); this.setState({ tracking: false }); } openSuggestionsPanel() { Animated.spring(this.state.height, { duration: animations.duration, toValue: this.props.height, friction: animations.friction, }).start(); } closeSuggestionsPanel() { Animated.timing(this.state.height, { duration: animations.duration, toValue: 0, }).start(); } updateHeight(num) { const newValue = num * 50; if (newValue < this.props.height) { Animated.timing(this.state.height, { duration: animations.speed, toValue: newValue, }).start(); } else { Animated.spring(this.state.height, { duration: animations.duration, toValue: this.props.height, friction: animations.friction, }).start(); } } renderSuggestionsRow(users) { return users.map(user => ( <TouchableOpacity key={user} onPress={() => this.onSuggestionTap(user, true)} > <SuggestionsRowContainer> <UserDetailsBox> <DisplayNameText>@{user}</DisplayNameText> </UserDetailsBox> </SuggestionsRowContainer> </TouchableOpacity> )); } render() { let searched = []; if (this.state.tracking) { searched = this.getSearchedUsers(); this.updateHeight(searched.length); } return ( <StyledAnimatedView style={{ ...this.props.style, height: this.state.height }} > <ScrollView keyboardShouldPersistTaps="always"> {this.state.tracking && this.renderSuggestionsRow(searched)} </ScrollView> </StyledAnimatedView> ); } }
src/components/team/EloHistory.js
tervay/AutoScout
import React from 'react'; import ResponsiveLine from 'nivo/lib/components/charts/line/ResponsiveLine'; export default class EloHistory extends React.Component { constructor(props) { super(props); this.state = { show: true, }; this.toggleGraph = this.toggleGraph.bind(this); } componentDidMount() { const tabs = Array.prototype.slice.call(document.querySelectorAll('.tabs > ul > li')); tabs.forEach((tab) => { tab.addEventListener('click', () => { tabs.forEach((tab_) => { tab_.classList.remove('is-active'); }); tab.classList.add('is-active'); }); }); } componentWillUnmount() { window.removeEventListener('resize', this.handleWindowSizeChange); } toggleGraph() { this.setState({ show: !this.state.show }); const div = document.getElementById('eloHideShow'); div.classList.toggle('fa-angle-down'); div.classList.toggle('fa-angle-up'); } render() { let graph = <div />; if (this.props.elos !== undefined && this.state.show) { const dataList = []; let min = Infinity; let max = -Infinity; this.props.elos.forEach((e) => { dataList.push({ x: e.event.key, y: e.elo.toFixed(2), }); if (e.elo < min) { min = e.elo; } if (e.elo > max) { max = e.elo; } }); const dataObj = { id: 'elo', data: dataList, }; graph = ( <div style={{ height: '250px' }}> <ResponsiveLine data={[dataObj]} margin={{ top: 0, right: 25, bottom: 25, left: 65, }} minY={min > 0 ? 0.975 * min : 1.025 * min} maxY={max > 0 ? 1.025 * max : 0.975 * max} stacked curve={'natural'} axisBottom={{ orient: 'bottom', tickSize: 0, tickPadding: 7, tickRotation: 0, legend: 'Event', legendOffset: 50, legendPosition: 'center', }} axisLeft={{ orient: 'left', tickSize: 0, tickPadding: 10, tickRotation: 0, legend: 'Elo', legendOffset: -50, legendPosition: 'center', }} enableGridX enableGridY colors="d320c" colorBy="id" lineWidth={2} enableDots dotSize={10} dotColor="inherit:darker(0.3)" dotBorderWidth={2} dotBorderColor="#ffffff" // enableDotLabel dotLabel="x" dotLabelYOffset={-12} animate motionStiffness={300} motionDamping={60} isInteractive enableStackTooltip /> </div>); } return ( <div> {graph} </div> ); } }
showcase/showcase-components/showcase-utils.js
Apercu/react-vis
import React from 'react'; export function mapSection(section, index) { const SectionComponent = section.component; return ( <section key={`${section.name}-index`}> <h3>{section.name}</h3> <div className="flex"> {section.sourceLink && <a className="docs-link" href={section.sourceLink}>> Source</a>} {section.docsLink && <a className="docs-link" href={section.docsLink}>> Docs</a>} {section.comment && <p className="docs-comment">{section.comment}</p>} </div> <SectionComponent /> </section> ); }
docs-ui/components/contextData.stories.js
mvaled/sentry
import React from 'react'; import {storiesOf} from '@storybook/react'; // import {action} from '@storybook/addon-actions'; import {withInfo} from '@storybook/addon-info'; import ContextData from 'app/components/contextData'; storiesOf('UI|ContextData', module).add( 'strings', withInfo('Default')(() => <ContextData data="https://example.org/foo/bar/" />) );
src/components/SideBar/Nav.js
chaitanya1375/Myprojects
import React, { Component } from 'react'; import { Link, withRouter } from 'react-router-dom'; import { Collapse } from 'react-bootstrap'; class Nav extends Component { state = {}; render() { let { location } = this.props; return ( <ul className="nav"> <li className={location.pathname === '/' ? 'active' : null}> <Link to="/"> <i className="pe-7s-graph"></i> <p>Dashboard</p> </Link> </li> <li className={this.isPathActive('/charts') ? 'active' : null}> <Link to="/charts"> <i className="pe-7s-graph"></i> <p>Charts</p> </Link> </li> </ul> ); } isPathActive(path) { return this.props.location.pathname.startsWith(path); } } export default withRouter(Nav);
components/reports/RangeCalendar.js
hutsi/bookkeeping
import React, { Component } from 'react'; import { DateRangePicker } from 'react-dates'; import Button from '@material-ui/core/Button'; import moment from 'moment'; import { withStyles } from '@material-ui/core/styles'; import 'react-dates/initialize'; import 'react-dates/lib/css/_datepicker.css'; const styles = theme => ({ wrapper: { display: 'flex', alignItems: 'center' }, calendar: { } }); class RangeCalendar extends Component { state = { focusedInput: null }; handleChange = ({ startDate, endDate }) => { this.props.onChange({ startDate, endDate }) }; render() { const { startDate, endDate, classes } = this.props const { focusedInput } = this.state; return ( <div className={classes.wrapper}> <div className={classes.calendar}> <DateRangePicker small startDateId='startDate' endDateId='endDate' startDate={startDate} endDate={endDate} focusedInput={focusedInput} onFocusChange={focusedInput => this.setState({ focusedInput })} onDatesChange={this.handleChange} isOutsideRange={() => false} noBorder /> </div> <div> <Button mini onClick={() => this.handleChange({ startDate: moment().subtract(1, 'week'), endDate: moment() })} > 1 week </Button> <Button mini onClick={() => this.handleChange({ startDate: moment().subtract(1, 'month'), endDate: moment() })} > 1 month </Button> <Button mini onClick={() =>this.handleChange({ startDate: moment().subtract(3, 'month'), endDate: moment() })} > 3 months </Button> <Button mini onClick={() => this.handleChange({ startDate: moment().subtract(6, 'month'), endDate: moment() })} > 6 months </Button> <Button mini onClick={() => this.handleChange({ startDate: moment().subtract(1, 'year'), endDate: moment() })} > 1 year </Button> </div> </div> ); } } export default withStyles(styles)(RangeCalendar);
src/components/HiddenInput/HiddenInput.js
eliaslopezgt/ps-react-eli
import React from 'react'; import PropTypes from 'prop-types'; /** Hidden Input with name and value */ function HiddenInput({name, value, ...props}) { return ( <input name={name} value={value} type="hidden" {...props}/> ); } HiddenInput.propTypes = { /** Input name. Recommend setting this to match object's property so a single change handler can be used. */ name: PropTypes.string, /** Value */ value: PropTypes.any, }; export default HiddenInput;
themes/frontend/assets/reactjs/process/js/Car/Filter/DesktopFilters.js
fonea/velon
import React from 'react'; export default class DesktopFilters extends React.Component { render() { return(<div>juice</div>); } }
docs/src/app/components/pages/components/AppBar/ExampleIconButton.js
ngbrown/material-ui
import React from 'react'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; import FlatButton from 'material-ui/FlatButton'; function handleTouchTap() { alert('onTouchTap triggered on the title component'); } const styles = { title: { cursor: 'pointer', }, }; const AppBarExampleIconButton = () => ( <AppBar title={<span style={styles.title}>Title</span>} onTitleTouchTap={handleTouchTap} iconElementLeft={<IconButton><NavigationClose /></IconButton>} iconElementRight={<FlatButton label="Save" />} /> ); export default AppBarExampleIconButton;
components/companies/CompanyList.js
Justbit-site/justbit-mobile
import React from 'react'; import { StyleSheet, View, ListView, } from 'react-native'; import { createRouter } from '@expo/ex-navigation'; import Ripple from 'react-native-material-ripple'; import Router from '../../navigation/Router'; import CompanyBox from './companyBox'; import CompanyDetails from '../../screens/CompanyDetails'; export default class CompanyList extends React.Component { constructor(props) { super(props); const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => { r1 !== r2 }}) this.state = { dataSource: ds } } componentDidMount(){ this.updateDataSource(this.props.companies) } componentWillReceiveProps(newProps){ if(newProps.companies !== this.props.companies){ this.updateDataSource(newProps.companies) } } updateDataSource = data => { this.setState({ dataSource: this.state.dataSource.cloneWithRows(data) }) } static route = { navigationBar: { title: 'Aliados estrategicos' }, }; handlePress(company){ this.props.navigator.push(Router.getRoute('companyDetails', {company})); } render() { return ( <ListView enableEmptySections={true} style={styles.container} dataSource={this.state.dataSource} renderRow={(company) => { return( <Ripple style={styles.companyBox} onPress={() => this.handlePress(company)}> <CompanyBox company={company} /> </Ripple> ) }} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#eeeeee' }, companyBox: { margin: 5, backgroundColor: '#ffffff', flexDirection: 'row', // Shadow in iOs shadowColor: '#000000', shadowOpacity: .2, shadowOffset: { height: 1, width: -2 }, // Shadow in android elevation: 2 }, });
src/donations/index.js
dyegolara/sismo-frontend
import React from 'react' const SOURCE = [ { link: 'http://www.topos.mx/', label: 'Topos – Brigada de Rescate Topos Tlaltelolco, A.C. (Earthquake help team)' }, { link: 'https://www.amazon.com.mx/b?ie=UTF8&node=17290014011', label: 'Cruz Roja Mexico (Red Cross Mexico) - Amazon Wishlist ' }, { link: 'https://www.donaunicef.org.mx/landing-terremoto/?utm_source=mpr_redes&utm_campaign=tw-terremoto&utm_medium=tw&utm_content=tw-org&utm_term=tw-org', label: 'UNICEF Mexico ' }, { link: 'https://www.globalgiving.org/projects/mexico-earthquake-and-hurricane-relief-fund/', label: 'Mexico Earthquake Relief Fund' }, { link: 'http://www.elfinanciero.com.mx/nacional/quieres-ayudar-aqui-se-instalaran-los-centros-de-acopio.html', label: 'Centros de Acopio en DF/Local Support Center in Mexico City ' }, { link: 'http://www.projectpaz.org/', label: 'Support Mexico Earthquake Relief by Project Paz (New York based non-profit)' }, { link: 'https://www.youcaring.com/mexicorecoveryeffort-955816', label: 'Unión del Barrio (CA) México Recovery Effort Donation Page' }, { link: 'http://comoayudar.mx/', label: 'Collection of different donation options/Collecion de varias opcionés para donar a Mx' }, { link: 'https://www.gofundme.com/b7uj4b-supporting-mexico', label: 'Supporting Mexico' } ] export default () => { let donations = SOURCE.map((don, index) => { return ( <li key={index} > <a target='_blank' href={don.link} > {don.label} </a> </li> ) }) return ( <div className='section'> <div className='content'> <h2 className='title'>Donaciones</h2> <ul> {donations} </ul> </div> </div> ) }
es/components/Chat/ChatMessages.js
welovekpop/uwave-web-welovekpop.club
import _extends from "@babel/runtime/helpers/builtin/extends"; import _jsx from "@babel/runtime/helpers/builtin/jsx"; import _assertThisInitialized from "@babel/runtime/helpers/builtin/assertThisInitialized"; import _inheritsLoose from "@babel/runtime/helpers/builtin/inheritsLoose"; import React from 'react'; import PropTypes from 'prop-types'; import Message from './Message'; import Motd from './Motd'; import ScrollDownNotice from './ScrollDownNotice'; import specialMessages from './specialMessages'; var ChatMessages = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(ChatMessages, _React$Component); function ChatMessages() { var _temp, _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return (_temp = _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this, _this.state = { isScrolledToBottom: true }, _this.onExternalScroll = function (direction) { var el = _this.container; if (direction === 'start') { el.scrollTop = 0; } else if (direction === 'end') { el.scrollTop = el.scrollHeight; } else { el.scrollTop += direction * 250; } }, _this.handleResize = function () { if (_this.state.isScrolledToBottom) { _this.scrollToBottom(); } }, _this.handleScroll = function () { _this.setState({ isScrolledToBottom: _this.isScrolledToBottom() }); }, _this.handleScrollToBottom = function (event) { event.preventDefault(); _this.scrollToBottom(); }, _this.refContainer = function (container) { _this.container = container; }, _temp) || _assertThisInitialized(_this); } var _proto = ChatMessages.prototype; _proto.componentDidMount = function componentDidMount() { var bus = this.props.bus; this.scrollToBottom(); this.shouldScrollToBottom = false; bus.on('chat:scroll', this.onExternalScroll); // A window resize may affect the available space. if (typeof window !== 'undefined') { window.addEventListener('resize', this.handleResize); } }; // This usually means that new messages came in; // either way it does not hurt to run this multiple times // so it is safe to use. // eslint-disable-next-line camelcase, react/sort-comp _proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps() { this.shouldScrollToBottom = this.isScrolledToBottom(); }; _proto.componentDidUpdate = function componentDidUpdate() { // Keep the chat scrolled to the bottom after a new message is addded. if (this.shouldScrollToBottom) { this.scrollToBottom(); this.shouldScrollToBottom = false; } }; _proto.componentWillUnmount = function componentWillUnmount() { var bus = this.props.bus; bus.off('chat:scroll', this.onExternalScroll); if (typeof window !== 'undefined') { window.removeEventListener('resize', this.handleResize); } }; _proto.scrollToBottom = function scrollToBottom() { var el = this.container; el.scrollTop = el.scrollHeight; }; _proto.isScrolledToBottom = function isScrolledToBottom() { var el = this.container; var lastMessage = el.lastElementChild; if (lastMessage) { var neededSize = el.scrollTop + el.offsetHeight + lastMessage.offsetHeight; return neededSize >= el.scrollHeight - 20; } return true; }; _proto.renderMotd = function renderMotd() { if (!this.props.motd) { return null; } return _jsx(Motd, { compileOptions: this.props.compileOptions }, void 0, this.props.motd); }; _proto.renderMessage = function renderMessage(msg) { var SpecialMessage = specialMessages[msg.type]; if (SpecialMessage) { return React.createElement(SpecialMessage, _extends({ key: msg._id }, msg)); } return React.createElement(Message, _extends({ key: msg._id, compileOptions: this.props.compileOptions, deletable: this.props.canDeleteMessages, onDelete: this.props.onDeleteMessage }, msg)); }; _proto.render = function render() { var isScrolledToBottom = this.state.isScrolledToBottom; return React.createElement("div", { ref: this.refContainer, className: "ChatMessages", onScroll: this.handleScroll }, _jsx(ScrollDownNotice, { show: !isScrolledToBottom, onClick: this.handleScrollToBottom }), this.renderMotd(), this.props.messages.map(this.renderMessage, this)); }; return ChatMessages; }(React.Component); export { ChatMessages as default }; ChatMessages.propTypes = process.env.NODE_ENV !== "production" ? { bus: PropTypes.object.isRequired, messages: PropTypes.array, motd: PropTypes.array, canDeleteMessages: PropTypes.bool, onDeleteMessage: PropTypes.func, compileOptions: PropTypes.shape({ availableEmoji: PropTypes.array, emojiImages: PropTypes.object }) } : {}; //# sourceMappingURL=ChatMessages.js.map
src/svg-icons/action/play-for-work.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPlayForWork = (props) => ( <SvgIcon {...props}> <path d="M11 5v5.59H7.5l4.5 4.5 4.5-4.5H13V5h-2zm-5 9c0 3.31 2.69 6 6 6s6-2.69 6-6h-2c0 2.21-1.79 4-4 4s-4-1.79-4-4H6z"/> </SvgIcon> ); ActionPlayForWork = pure(ActionPlayForWork); ActionPlayForWork.displayName = 'ActionPlayForWork'; ActionPlayForWork.muiName = 'SvgIcon'; export default ActionPlayForWork;
clients/libs/slate-editor-font-family-plugin/src/FontFamilyMark.js
nossas/bonde-client
/* eslint-disable react/prop-types */ import React from 'react' import FontFamilyList from './FontFamilyList' const FontFamilyMark = ({ children, mark: { data } }) => ( <span style={{ fontFamily: FontFamilyList[data.get('fontFamilyIndex')].name }}> {children} </span> ) export default FontFamilyMark
node_modules/semantic-ui-react/dist/es/views/Item/ItemHeader.js
mowbell/clickdelivery-fed-test
import _extends from 'babel-runtime/helpers/extends'; import _isNil from 'lodash/isNil'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META } from '../../lib'; /** * An item can contain a header. */ function ItemHeader(props) { var children = props.children, className = props.className, content = props.content; var classes = cx('header', className); var rest = getUnhandledProps(ItemHeader, props); var ElementType = getElementType(ItemHeader, props); return React.createElement( ElementType, _extends({}, rest, { className: classes }), _isNil(children) ? content : children ); } ItemHeader.handledProps = ['as', 'children', 'className', 'content']; ItemHeader._meta = { name: 'ItemHeader', parent: 'Item', type: META.TYPES.VIEW }; process.env.NODE_ENV !== "production" ? ItemHeader.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand } : void 0; ItemHeader.create = createShorthandFactory(ItemHeader, function (content) { return { content: content }; }); export default ItemHeader;
src/svg-icons/toggle/check-box-outline-blank.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleCheckBoxOutlineBlank = (props) => ( <SvgIcon {...props}> <path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ToggleCheckBoxOutlineBlank = pure(ToggleCheckBoxOutlineBlank); ToggleCheckBoxOutlineBlank.displayName = 'ToggleCheckBoxOutlineBlank'; ToggleCheckBoxOutlineBlank.muiName = 'SvgIcon'; export default ToggleCheckBoxOutlineBlank;
webpack/scenes/ContentViews/Details/Filters/index.js
Katello/katello
import React from 'react'; import { Route } from 'react-router-dom'; import { number, shape } from 'prop-types'; import ContentViewFilters from './ContentViewFilters'; import ContentViewFilterDetails from './ContentViewFilterDetails'; const ContentViewFiltersRoutes = ({ cvId, details }) => ( <> <Route exact path="/filters"> <ContentViewFilters cvId={cvId} details={details} /> </Route> <Route path="/filters/:filterId([0-9]+)"> <ContentViewFilterDetails cvId={cvId} details={details} /> </Route> </> ); ContentViewFiltersRoutes.propTypes = { cvId: number.isRequired, details: shape({ permissions: shape({}), }).isRequired, }; export default ContentViewFiltersRoutes;
examples/customised/src/components/RandomButton/RandomButton.js
styleguidist/react-styleguidist
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import sample from 'lodash/sample'; import s from './RandomButton.css'; /** * Button that changes label on every click. */ export default class RandomButton extends Component { static propTypes = { /** * List of possible labels. */ variants: PropTypes.array.isRequired, }; constructor(props) { super(); this.state = { label: sample(props.variants), }; } handleClick = () => { this.setState({ label: sample(this.props.variants), }); }; render() { return ( <button className={s.root} onClick={this.handleClick}> {this.state.label} </button> ); } }
src/components/Layoutx/Menux/index.js
wz-one-piece/Antd-Demo
import React from 'react' import PropTypes from 'prop-types' import styles from './index.less' import { Menu, Icon } from 'antd'; import { Link } from 'dva/router' import { arrayToTree, queryArray, config } from 'utils' const Menux = ({menu, handleClickNavMenu}) => { // 生成树状 const menuTree = arrayToTree(menu.filter(_ => _.mpid !== '-1'), 'id', 'mpid') const levelMap = {} // 递归生成菜单 const getMenus = (menuTreeN) => { return menuTreeN.map(item => { if (item.children) { if (item.mpid) { levelMap[item.id] = item.mpid } return ( <Menu.SubMenu key={item.id} title={<span> {item.icon && <Icon type={item.icon} />} <span>{item.name}</span> </span>} > {getMenus(item.children)} </Menu.SubMenu> ) } return ( <Menu.Item key={item.id}> <Link to={item.route}> {item.icon && <Icon type={item.icon} />} <span>{item.name}</span> </Link> </Menu.Item> ) }) } const menuItems = getMenus(menuTree) return ( <div> <div className={styles.sider_logo}> <Link to="/" ><img alt={'logo'} src={config.logo} /></Link> </div> <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']} onClick={handleClickNavMenu}> {menuItems} </Menu> </div> ) } Menux.propTypes = { menu: PropTypes.array, handleClickNavMenu: PropTypes.func, } export default Menux
src/icons/StrokeDecentralization.js
ipfs/webui
import React from 'react' const StrokeDecentralization = props => ( <svg viewBox='0 0 100 100' {...props}> <path d='M90 39.9a4.75 4.75 0 0 0-5.4-3.9 4.66 4.66 0 0 0-2.18 1l-8.25-5.41a4.59 4.59 0 0 0 .11-2 4.81 4.81 0 0 0-.25-.94l5.3-4.33a1.22 1.22 0 0 0 .17.15 4.67 4.67 0 0 0 2.78.91 4.79 4.79 0 0 0 3.85-2 4.75 4.75 0 0 0-4.58-7.48 4.74 4.74 0 0 0-4 5.43c0 .13.07.26.1.39l-5.59 4.57a4.69 4.69 0 0 0-3.26-.69 4.85 4.85 0 0 0-.63.16L58.16 11.6c.06-.07.12-.12.17-.19a4.68 4.68 0 0 0 .85-3.53 4.76 4.76 0 1 0-4 5.43c.14 0 .26-.07.4-.1L65.77 27.5a4.73 4.73 0 0 0-.86 3.5c0 .15.07.29.1.43L50 41.13l-.17-.13a4.73 4.73 0 0 0-3.53-.84 4.75 4.75 0 0 0-.7 9.21l.4 25.88a4.73 4.73 0 0 0-2.14 1.53L19.4 67.92a6.35 6.35 0 0 0 0-.87 4.73 4.73 0 0 0-1.9-3.1 4.75 4.75 0 1 0-2.79 8.59 4.73 4.73 0 0 0 3.71-1.81L42.8 79.6a5 5 0 0 0 .05.86c0 .16.08.31.12.46l-10.3 6.75-.14-.13a4.73 4.73 0 0 0-3.53-.85 4.75 4.75 0 0 0 .73 9.44 4.84 4.84 0 0 0 .75-.06 4.73 4.73 0 0 0 3.94-5.43 3.43 3.43 0 0 0-.11-.46l10.3-6.75a4.64 4.64 0 0 0 3.67 1 4.75 4.75 0 0 0 3.61-2.82l12 1a4.73 4.73 0 1 0 .24-3l-12-1A4.73 4.73 0 0 0 49 75.22l-.4-25.93a4.72 4.72 0 0 0 3.13-5.22c0-.14-.08-.28-.11-.42l15-9.66c.06 0 .11.11.17.15a4.7 4.7 0 0 0 3.53.85 4.8 4.8 0 0 0 2.19-1l8.24 5.41a4.74 4.74 0 1 0 9.25.5zM16.88 69.41A2.75 2.75 0 0 1 12 68.22a2.75 2.75 0 0 1 2.28-3.14 3.25 3.25 0 0 1 .44 0 2.73 2.73 0 0 1 1.6.52 2.69 2.69 0 0 1 1.1 1.79 2.73 2.73 0 0 1-.54 2.02zm51.2 9.34a3.11 3.11 0 0 1 .43 0 2.74 2.74 0 0 1 1.61.52 2.69 2.69 0 0 1 1.1 1.73 2.75 2.75 0 1 1-3.14-2.28zM80.07 19A2.74 2.74 0 0 1 85 20.18a2.7 2.7 0 0 1-.49 2 2.75 2.75 0 0 1-3.84.61A2.74 2.74 0 0 1 79.58 21a2.7 2.7 0 0 1 .49-2zm-27.19-8.16a2.74 2.74 0 0 1 1.18-4.93 3.27 3.27 0 0 1 .44 0 2.75 2.75 0 1 1-1.62 5zM32 93a2.75 2.75 0 0 1-3.84.61 2.77 2.77 0 0 1-1.16-1.8 2.73 2.73 0 0 1 .5-2 2.69 2.69 0 0 1 1.79-1.09 2.09 2.09 0 0 1 .43 0 2.68 2.68 0 0 1 1.61.53A2.74 2.74 0 0 1 32 93zm18.29-13.7a2.74 2.74 0 1 1-3.18-2.3 3.13 3.13 0 0 1 .43 0 2.75 2.75 0 0 1 2.71 2.29zm-1-32.86a2.77 2.77 0 0 1-1.8 1.1 2.71 2.71 0 0 1-2-.5 2.74 2.74 0 0 1-1.1-1.79 2.71 2.71 0 0 1 .5-2 2.74 2.74 0 0 1 1.79-1.1 3.11 3.11 0 0 1 .43 0 2.74 2.74 0 0 1 1.61.52 2.69 2.69 0 0 1 1.1 1.8 2.75 2.75 0 0 1-.56 1.96zM70 33a2.75 2.75 0 1 1 2.29-3.14A2.75 2.75 0 0 1 70 33zm15.77 10.35a2.75 2.75 0 0 1-3.14-2.28 2.74 2.74 0 1 1 3.14 2.28z' /> </svg> ) export default StrokeDecentralization
app/app.js
easingthemes/berlinmap
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ import 'babel-polyfill'; /* eslint-disable import/no-unresolved, import/extensions */ // Load the manifest.json file and the .htaccess file import '!file?name=[name].[ext]!./manifest.json'; import 'file?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import LanguageProvider from 'containers/LanguageProvider'; import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder import 'sanitize.css/sanitize.css'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state import { selectLocationState } from 'containers/App/selectors'; const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: selectLocationState(), }); // Set up the router, wrapping all Routes in the App component import App from 'containers/App'; import createRoutes from './routes'; const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (translatedMessages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={translatedMessages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(System.import('intl')); })) .then(() => Promise.all([ System.import('intl/locale-data/jsonp/de.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed import { install } from 'offline-plugin/runtime'; install();
pootle/static/js/admin/components/Language/LanguageEdit.js
evernote/zing
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; import LanguageForm from './LanguageForm'; const LanguageEdit = React.createClass({ propTypes: { collection: React.PropTypes.object.isRequired, model: React.PropTypes.object, onAdd: React.PropTypes.func.isRequired, onDelete: React.PropTypes.func.isRequired, onSuccess: React.PropTypes.func.isRequired, }, render() { return ( <div className="item-edit"> <div className="hd"> <h2>{gettext('Edit Language')}</h2> <button onClick={this.props.onAdd} className="btn btn-primary"> {gettext('Add Language')} </button> </div> <div className="bd"> {!this.props.model ? ( <p> {gettext( 'Use the search form to find the language, ' + 'then click on a language to edit.' )} </p> ) : ( <LanguageForm key={this.props.model.id} model={this.props.model} collection={this.props.collection} onSuccess={this.props.onSuccess} onDelete={this.props.onDelete} /> )} </div> </div> ); }, }); export default LanguageEdit;
TestDemos/examples/LessonExamples/IIID-News/Components/Finder.js
AzenXu/ReactNativeTest
/** * Created by Azen on 16/9/4. */ import React, { Component } from 'react'; import { View, Image, Text, TabBarIOS, StyleSheet } from 'react-native' var Finder = React.createClass({ render() { return( <View style={styles.container}> <Text>发现</Text> </View> ) } }); const styles = StyleSheet.create({ container:{ flex: 1, backgroundColor: 'pink', justifyContent:'center', alignItems:'center' } }); module.exports = Finder;
components/react-draft-wysiwyg/util/TextArea.js
andresin87/wysiwyg
/** * Created by alucas on 6/12/16. */ import React, { Component } from 'react'; class TextArea extends Component { constructor() { super(); this.setValue = this.setValue.bind(this); this.onChange = this.onChange.bind(this); } onChange(event) { this.setState({ value: event.target.value }); if (this.props && this.props.onChange) { this.props.onChange(); } } setValue(value) { this.setState({ value }); } componentWillmount() { // this.state.value = this.props.value ? this.props.value : ''; } render() { const { className, disabled } = this.props; const value = (this.state && this.state.value) ? this.state.value : ''; return ( <textarea style={{ minHeight: 200, width: '100%', }} className={className} disabled={disabled} onChange={this.onChange} value={value} > {value} </textarea> ); } } TextArea.propTypes = { className: React.PropTypes.string, disabled: React.PropTypes.bool, value: React.PropTypes.string, onChange: React.PropTypes.func, }; TextArea.defaultProps = { disabled: false, }; export { TextArea };
src/components/Welcome/Welcome.js
ihenvyr/react-app
import React from 'react'; import styles from './Welcome.scss'; class Welcome extends React.Component { static propTypes = {}; static defaultProps = {}; state = { checked: false }; checkboxToggle = () => { this.setState({ checked: !this.state.checked }) }; render() { return ( <div className={styles.container}> <h2>Welcome to React App</h2> <p> A <span className="bold-green-text">simple</span> react application boilerplate! {' '} <label>checkbox<input type="checkbox" checked={this.state.checked} onChange={this.checkboxToggle} /></label> </p> </div> ); } } export default Welcome;
src/index.js
znewton/myxx-client
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import fapp from 'firebase/app'; import registerServiceWorker from './registerServiceWorker'; import './sass/index.scss'; const config = { apiKey: "AIzaSyCcCJOhAOAXQIUR17x2Uy_Gbo5W1kWHrWk", authDomain: "myxx-6b351.firebaseapp.com", databaseURL: "https://myxx-6b351.firebaseio.com", projectId: "myxx-6b351", storageBucket: "myxx-6b351.appspot.com", messagingSenderId: "587045094258" }; fapp.initializeApp(config); ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
resources/js/react/MissingPage.js
chekun/spore
import React from 'react'; var Router = require('react-router'); var Link = Router.Link; class MissingPage extends React.Component { constructor(props) { super(props) } render() { return ( <div className="container landing-container"> <h2>404 Not Found!</h2> <div> <Link to="/search" className="btn btn-info .btn-lg">孢子大搜索</Link> <Link to="/rank" className="btn btn-info .btn-lg">孢子风云榜</Link> </div> </div> ); } } export default MissingPage