path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
examples/huge-apps/components/GlobalNav.js
rkaneriya/react-router
import React from 'react' import { Link } from 'react-router' const dark = 'hsl(200, 20%, 20%)' const light = '#fff' const styles = {} styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: dark, color: light } styles.link = { padding: 11, color: light, fontWeight: 200 } styles.activeLink = { ...styles.link, background: light, color: dark } class GlobalNav extends React.Component { static defaultProps = { user: { id: 1, name: 'Ryan Florence' } } constructor(props, context) { super(props, context) this.logOut = this.logOut.bind(this) } logOut() { alert('log out') } render() { var { user } = this.props return ( <div style={styles.wrapper}> <div style={{ float: 'left' }}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '} <Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '} <Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '} </div> <div style={{ float: 'right' }}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ) } } export default GlobalNav
cms/react-static/src/containers/404.js
fishjar/gabe-study-notes
import React from 'react' // export default () => ( <div> <h1>404 - Oh no's! We couldn't find that page :(</h1> </div> )
packages/mineral-ui-icons/src/IconDialerSip.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconDialerSip(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M17 3h-1v5h1V3zm-2 2h-2V4h2V3h-3v3h2v1h-2v1h3V5zm3-2v5h1V6h2V3h-3zm2 2h-1V4h1v1zm0 10.5c-1.25 0-2.45-.2-3.57-.57a.998.998 0 0 0-1.01.24l-2.2 2.2a15.045 15.045 0 0 1-6.59-6.59l2.2-2.21c.27-.26.35-.65.24-1A11.36 11.36 0 0 1 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1z"/> </g> </Icon> ); } IconDialerSip.displayName = 'IconDialerSip'; IconDialerSip.category = 'communication';
client/modules/App/__tests__/App.spec.js
mraq1234/mod11
import React from 'react'; import test from 'ava'; import sinon from 'sinon'; import { shallow, mount } from 'enzyme'; import { App } from '../App'; import styles from '../App.css'; import { intlShape } from 'react-intl'; import { intl } from '../../../util/react-intl-test-helper'; import { toggleAddPost } from '../AppActions'; const intlProp = { ...intl, enabledLanguages: ['en', 'fr'] }; const children = <h1>Test</h1>; const dispatch = sinon.spy(); const props = { children, dispatch, intl: intlProp, }; test('renders properly', t => { const wrapper = shallow( <App {...props} /> ); // t.is(wrapper.find('Helmet').length, 1); t.is(wrapper.find('Header').length, 1); t.is(wrapper.find('Footer').length, 1); t.is(wrapper.find('Header').prop('toggleAddPost'), wrapper.instance().toggleAddPostSection); t.truthy(wrapper.find('Header + div').hasClass(styles.container)); t.truthy(wrapper.find('Header + div').children(), children); }); test('calls componentDidMount', t => { sinon.spy(App.prototype, 'componentDidMount'); mount( <App {...props} />, { context: { router: { isActive: sinon.stub().returns(true), push: sinon.stub(), replace: sinon.stub(), go: sinon.stub(), goBack: sinon.stub(), goForward: sinon.stub(), setRouteLeaveHook: sinon.stub(), createHref: sinon.stub(), }, intl, }, childContextTypes: { router: React.PropTypes.object, intl: intlShape, }, }, ); t.truthy(App.prototype.componentDidMount.calledOnce); App.prototype.componentDidMount.restore(); }); test('calling toggleAddPostSection dispatches toggleAddPost', t => { const wrapper = shallow( <App {...props} /> ); wrapper.instance().toggleAddPostSection(); t.truthy(dispatch.calledOnce); t.truthy(dispatch.calledWith(toggleAddPost())); });
examples/universal/client/index.js
nacyot/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import configureStore from '../common/store/configureStore'; import App from '../common/containers/App'; const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('app'); React.render( <Provider store={store}> {() => <App/>} </Provider>, rootElement );
app/javascript/mastodon/features/notifications/components/clear_column_button.js
glitch-soc/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Icon from 'mastodon/components/icon'; export default class ClearColumnButton extends React.PureComponent { static propTypes = { onClick: PropTypes.func.isRequired, }; render () { return ( <button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.props.onClick}><Icon id='eraser' /> <FormattedMessage id='notifications.clear' defaultMessage='Clear notifications' /></button> ); } }
public/components/tehtPage/tabsComponents/kuvatvideot/Valvontakamerat.js
City-of-Vantaa-SmartLab/kupela
import React from 'react'; import Basic from '../reusables/templates/Basic'; const Valvontakamerat = (props) => <div className="valvontakamerat"> <p><b>Valvontakamerat:</b></p> {props.securitycams.map((cam) => <a onClick={props.selectItem(cam.nameId, 'GET_kuvatvideot', cam)}> <Basic src={cam.url} title={cam.name} {...props}/> </a> )} </div>; export default Valvontakamerat;
SSBW/Tareas/Tarea9/restaurantes2/node_modules/react-bootstrap/es/Row.js
jmanday/Master
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var Row = function (_React$Component) { _inherits(Row, _React$Component); function Row() { _classCallCheck(this, Row); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Row.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Row; }(React.Component); Row.propTypes = propTypes; Row.defaultProps = defaultProps; export default bsClass('row', Row);
src/app/components/team/Rules/RulesComponent.js
meedan/check-web
import React from 'react'; import PropTypes from 'prop-types'; import { injectIntl, intlShape, defineMessages, FormattedMessage } from 'react-intl'; import { graphql, commitMutation } from 'react-relay/compat'; import { Store } from 'react-relay/classic'; import { makeStyles } from '@material-ui/core/styles'; import Paper from '@material-ui/core/Paper'; import Rule from './Rule'; import RulesTable from './RulesTable'; import { ContentColumn } from '../../../styles/js/shared'; import { safelyParseJSON } from '../../../helpers'; import { withSetFlashMessage } from '../../FlashMessage'; const useStyles = makeStyles(theme => ({ paper: { padding: theme.spacing(2), margin: '0 auto', boxShadow: 'none', }, })); const messages = defineMessages({ copyOf: { id: 'rule.copyOf', defaultMessage: 'Copy of {ruleName}', }, }); const RulesComponent = (props) => { const classes = useStyles(); const propRules = props.team.get_rules ? props.team.get_rules.slice(0) : []; const [rules, setRules] = React.useState(JSON.parse(JSON.stringify(propRules))); const [currentRuleIndex, setCurrentRuleIndex] = React.useState(null); const rule = currentRuleIndex !== null ? rules[currentRuleIndex] : null; const [savedRule, setSavedRule] = React.useState(null); const handleError = (error) => { let errorMessage = <FormattedMessage id="rulesComponent.defaultErrorMessage" defaultMessage="Could not save rules" />; const json = safelyParseJSON(error.source); if (json && json.errors && json.errors[0] && json.errors[0].message) { errorMessage = json.errors[0].message; } props.setFlashMessage(errorMessage, 'error'); }; const handleSuccess = () => { props.setFlashMessage(<FormattedMessage id="rulesComponent.savedSuccessfully" defaultMessage="Rules saved successfully" />, 'success'); }; const handleUpdateRules = (newRules, commit) => { setRules(newRules); if (commit) { commitMutation(Store, { mutation: graphql` mutation RulesComponentUpdateTeamMutation($input: UpdateTeamInput!) { updateTeam(input: $input) { team { id get_rules } } } `, variables: { input: { id: props.team.id, rules: JSON.stringify(newRules), }, }, onCompleted: (response, error) => { if (error) { handleError(error); } else { handleSuccess(); } }, onError: (error) => { handleError(error); }, }); } }; const handleGoBack = () => { const updatedRules = rules.slice(0); if (!savedRule) { updatedRules.splice(currentRuleIndex, 1); } else { updatedRules[currentRuleIndex] = JSON.parse(JSON.stringify(savedRule)); } setSavedRule(null); setCurrentRuleIndex(null); handleUpdateRules(updatedRules, false); }; const handleClickRule = (index) => { setSavedRule(JSON.parse(JSON.stringify(rules[index]))); setCurrentRuleIndex(index); }; const handleDuplicateRule = () => { const updatedRules = rules.slice(0); const dupRule = JSON.parse(JSON.stringify(rule)); dupRule.name = props.intl.formatMessage(messages.copyOf, { ruleName: rule.name }); dupRule.updated_at = parseInt(new Date().getTime() / 1000, 10); updatedRules.push(dupRule); setCurrentRuleIndex(updatedRules.length - 1); handleUpdateRules(updatedRules, true); setSavedRule(dupRule); }; const handleDeleteRule = () => { const updatedRules = rules.slice(0); updatedRules.splice(currentRuleIndex, 1); handleUpdateRules(updatedRules, true); setCurrentRuleIndex(null); }; const handleAddRule = () => { const updatedRules = rules.slice(0); const newRule = { name: '', updated_at: null, rules: { operator: 'and', groups: [ { operator: 'and', conditions: [ { rule_definition: '', rule_value: '', }, ], }, ], }, actions: [ { action_definition: '', action_value: '', }, ], }; setSavedRule(null); updatedRules.push(newRule); handleUpdateRules(updatedRules, false); setCurrentRuleIndex(updatedRules.length - 1); }; const handleDeleteRules = (indexes) => { const updatedRules = rules.slice(0); indexes.forEach((index) => { updatedRules.splice(index, 1); }); handleUpdateRules(updatedRules, true); }; const handleSaveRule = () => { const updatedRule = JSON.parse(JSON.stringify(rule)); updatedRule.updated_at = parseInt(new Date().getTime() / 1000, 10); const updatedRules = rules.slice(0); updatedRules[currentRuleIndex] = updatedRule; handleUpdateRules(updatedRules, true); setCurrentRuleIndex(null); }; const handleChangeRule = (updatedRule) => { const updatedRules = rules.slice(0); updatedRules[currentRuleIndex] = updatedRule; handleUpdateRules(updatedRules, false); }; if (currentRuleIndex !== null && rule !== null) { return ( <ContentColumn large> <Paper className={classes.paper}> <Rule rule={rule} schema={JSON.parse(props.team.rules_json_schema)} unsavedChanges={JSON.stringify(rule) !== JSON.stringify(savedRule)} onGoBack={handleGoBack} onDeleteRule={handleDeleteRule} onSaveRule={handleSaveRule} onDuplicateRule={handleDuplicateRule} onChangeRule={handleChangeRule} /> </Paper> </ContentColumn> ); } return ( <ContentColumn large> <RulesTable rules={rules} onClickRule={handleClickRule} onAddRule={handleAddRule} onDeleteRules={handleDeleteRules} /> </ContentColumn> ); }; RulesComponent.propTypes = { team: PropTypes.object.isRequired, setFlashMessage: PropTypes.func.isRequired, // https://github.com/yannickcr/eslint-plugin-react/issues/1389 // eslint-disable-next-line react/no-typos intl: intlShape.isRequired, }; export default injectIntl(withSetFlashMessage(RulesComponent));
docs/src/Routes.js
tigerandgirl/ssc-refer
import React from 'react'; import {IndexRoute, Route} from 'react-router'; import ComponentsPage from './ComponentsPage'; import ValidationPage from './ValidationPage'; // import GettingStartedPage from './GettingStartedPage'; import HomePage from './HomePage'; // import IntroductionPage from './IntroductionPage'; import NotFoundPage from './NotFoundPage'; import Root from './Root'; // import SupportPage from './SupportPage'; export default ( <Route path="/" component={Root}> <IndexRoute component={HomePage} /> {/* <Route path="introduction.html" component={IntroductionPage} /> */} {/* <Route path="getting-started.html" component={GettingStartedPage} /> */} <Route path="components.html" component={ComponentsPage} /> <Route path="validation.html" component={ValidationPage} /> {/* <Route path="support.html" component={SupportPage} /> */} <Route path="*" component={NotFoundPage} /> </Route> );
test/js/release_test/ViroButtonTest.js
viromedia/viro
/** * Sample React Native App * https://github.com/facebook/react-native *//** * Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import { ViroSceneNavigator, ViroScene, ViroBox, ViroMaterials, ViroNode, ViroOrbitCamera, ViroCamera, ViroAmbientLight, ViroOmniLight, ViroSpotLight, ViroDirectionalLight, ViroButton, ViroImage, ViroVideo, Viro360Image, Viro360Video, ViroFlexView, ViroUtils, ViroText, ViroAnimations, ViroQuad, ViroSkyBox, ViroSphere, Viro3DObject, } from 'react-viro'; var createReactClass = require('create-react-class'); var button_local = require("../res/card_main.png"); var buttonHover_local = require("../res/card_petite_ansu.png"); var buttonClick_local = require("../res/card_main.png"); var button_uri = {uri:"https://s3-us-west-2.amazonaws.com/viro/Explorer/360_horseshoe.jpg"}; var buttonHover_uri = {uri:"http://storage.googleapis.com/ix_choosemuse/uploads/2016/02/Muse%20Android.jpeg"}; var buttonClick_uri = {uri:"https://s3-us-west-2.amazonaws.com/viro/Explorer/360_horseshoe.jpg"}; var ReleaseMenu = require("./ReleaseMenu.js"); var ViroButtonTest = createReactClass({ getInitialState() { return { widthAndHeight:1, format:"RGBA8", showUrlImage:false }; }, render: function() { var buttonSource = this.state.showUrlImage ? button_uri : button_local; var buttonHover = this.state.showUrlImage ? buttonHover_uri : buttonHover_local; var buttonClick = this.state.showUrlImage ? buttonClick_uri : buttonClick_local; return ( <ViroScene> <ReleaseMenu sceneNavigator={this.props.sceneNavigator}/> <ViroButton width={this.state.widthAndHeight} height={this.state.widthAndHeight} position={[0,0.5,-4]} scale={[0.5, 0.5, 0.5]} source={buttonSource} hoverSource={buttonHover} clickSource={buttonClick} onClick={this._onHover} onHover={this._onHover}/> {this._getTestControls()} </ViroScene> ); }, _getTestControls(){ return( <ViroNode position={[0,-0.5,-2]}> <ViroText style={styles.baseTextTwo} position={[-1,0, 0]} width={1} height={2} text={"Toggle ImageSource isUrlIamge: " + this.state.showUrlImage} onClick={this._toggleImageSource}/> <ViroText style={styles.baseTextTwo} position={[0,0, 0]} width={1} height={2} text={"Toggle ImageSize: " + this.state.widthAndHeight} onClick={this._toggleSize}/> <ViroText style={styles.baseTextTwo} position={[1,0, 0]} width={1} height={2} text={"Toggle Format " + this.state.format} onClick={this._toggleFormat}/> <ViroImage source={require('./res/poi_dot.png')} position={[0, -3, -2]} transformBehaviors={["billboard"]} onClick={this._showNext} /> </ViroNode> ); }, _showNext() { this.props.sceneNavigator.replace({scene:require('./ViroQuadFlexViewTest')}); }, _onHover(source, isHovering){ console.log("onHover"); }, _toggleImageSource() { var newShowUrlImageFlag = !this.state.showUrlImage; this.setState({ showUrlImage:newShowUrlImageFlag, }); }, _toggleSize() { var size = this.state.widthAndHeight; size = size + 0.5; if (size > 4){ size = 0.5; } this.setState({ widthAndHeight:size }); }, }); var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, elementText: { fontFamily: 'HelveticaNeue-Medium', fontSize: 30, color: '#ffffff', textAlign: 'center', }, baseTextTwo: { fontFamily: 'Arial', fontSize: 10, color: '#ffffff', flex: 1, textAlignVertical: 'center', textAlign: 'center', }, }); module.exports = ViroButtonTest;
examples/server-rendering/shared/components/App.js
amazeui/amazeui-react
'use strict'; import React from 'react' import { Link, } from 'react-router'; import { Topbar, Nav, NavItem, CollapsibleNav, Container, GoTop, } from './AMUIReact'; import {SiteFooter} from './index'; import * as demos from './demos'; export class App extends React.Component { constructor(props, context) { super(props); } renderDemoNav() { return ( <Nav className="demo-nav" pills > { Object.keys(demos).map((demo, index) => { return ( <NavItem key={index} linkComponent={Link} linkProps={{to: `/${demo}`}} active = {this.context.router.isActive(`/${demo}`)} > {demo.charAt(0).toUpperCase() + demo.substring(1)} </NavItem> ) }) } </Nav> ) } render() { return ( <div className="ask-page"> <Topbar className="ask-header" brand="Amaze UI React Server Rendering" brandLink="/" inverse > <CollapsibleNav> <Nav topbar> </Nav> </CollapsibleNav> </Topbar> <Container className="ask-main"> <p className="am-margin-top-lg"> Amaze UI React 组件后端渲染测试 </p> {this.renderDemoNav()} <div className="demo-content"> {this.props.children} </div> </Container> <SiteFooter /> <GoTop theme="fixed" autoHide icon="arrow-up" /> </div> ); } } App.contextTypes = { router: React.PropTypes.object.isRequired };
client/components/EditCaption.js
RobinClowers/photo-album
import React from 'react' import { withStyles } from '@material-ui/core/styles' import TextField from '@material-ui/core/TextField' import FormControl from '@material-ui/core/FormControl' import FormHelperText from '@material-ui/core/FormHelperText' import Button from '@material-ui/core/Button' import { updatePhoto } from 'client/src/api' const styles = theme => ({ container: { alignItems: 'flex-end', display: 'flex', flexDirection: 'column', width: '100%', }, textField: { width: '100%', }, }) class EditCaption extends React.Component { constructor(props) { super(props) this.state = { caption: props.initalValue, errors: [], } } handleChange(fieldName) { return event => { this.setState({ ...this.state, [fieldName]: event.target.value }) } } handleSubmit = async _event => { const response = await updatePhoto(this.props.photoId, { caption: this.state.caption, }) if (response.ok) { this.setState({ errors: [], caption: '' }) this.props.handleCaptionUpdated() } else { const body = await response.json() this.setState({ ...this.state, errors: body.errors }) } } handleKeyPress = async event => { if (event.which == 13 && event.shiftKey) { this.handleSubmit(event) } } render() { const { classes } = this.props return ( <div className={classes.container}> <FormControl fullWidth error aria-describedby="component-error-text"> <TextField autoFocus error={this.state.errors.length > 0} label="Add a caption" multiline rowsMax="4" value={this.state.caption} onChange={this.handleChange('caption')} onKeyPress={this.handleKeyPress} className={classes.textField} margin="normal" variant="outlined" /> <FormHelperText id="component-error-text" error style={{ margin: 8 }}> {this.state.errors} </FormHelperText> </FormControl> <Button variant="contained" color="primary" onClick={this.handleSubmit}> Update </Button> </div> ) } } export default withStyles(styles)(EditCaption)
src/routes/index.js
MaayanLab/L1000
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import CoreLayout from 'layouts/CoreLayout'; import HomeView from 'views/HomeView'; import RegisterView from 'views/RegisterView'; import LoginView from 'views/LoginView'; import ProfileView from 'views/ProfileView'; import CartView from 'views/CartView'; import CheckoutView from 'views/CheckoutView'; import AddNewCompoundView from 'views/AddNewCompoundView'; import NotFoundView from 'views/NotFoundView'; export default (/* store */) => ( <Route path="/" component={CoreLayout}> <IndexRoute component={HomeView} /> <Route path="/register" component={RegisterView} /> <Route path="/login" component={LoginView} /> <Route path="/user/profile" component={ProfileView} /> <Route path="/user/cart" component={CartView} /> <Route path="/user/checkout" component={CheckoutView} /> <Route path="/experiments/:experimentId/compounds/add" component={AddNewCompoundView} /> <Route path="*" component={NotFoundView} /> </Route> );
docs/src/app/components/pages/components/Drawer/ExampleUndocked.js
hwo411/material-ui
import React from 'react'; import Drawer from 'material-ui/Drawer'; import MenuItem from 'material-ui/MenuItem'; import RaisedButton from 'material-ui/RaisedButton'; export default class DrawerUndockedExample extends React.Component { constructor(props) { super(props); this.state = {open: false}; } handleToggle = () => this.setState({open: !this.state.open}); handleClose = () => this.setState({open: false}); render() { return ( <div> <RaisedButton label="Open Drawer" onTouchTap={this.handleToggle} /> <Drawer docked={false} width={200} open={this.state.open} onRequestChange={(open) => this.setState({open})} > <MenuItem onTouchTap={this.handleClose}>Menu Item</MenuItem> <MenuItem onTouchTap={this.handleClose}>Menu Item 2</MenuItem> </Drawer> </div> ); } }
docs/stories/method.js
react-native-web-community/react-native-web-webview
import React from 'react'; import { WebView } from 'react-native-webview'; import { text } from '@storybook/addon-knobs'; export const basic = () => ( <WebView source={{ uri: text('URI', 'https://react-native-web-community.github.io/react-native-web-webview/'), method: text('Method', 'GET'), }} /> );
app/javascript/mastodon/features/picture_in_picture/components/header.js
tootcafe/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from 'mastodon/components/icon_button'; import { Link } from 'react-router-dom'; import Avatar from 'mastodon/components/avatar'; import DisplayName from 'mastodon/components/display_name'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, }); const mapStateToProps = (state, { accountId }) => ({ account: state.getIn(['accounts', accountId]), }); export default @connect(mapStateToProps) @injectIntl class Header extends ImmutablePureComponent { static propTypes = { accountId: PropTypes.string.isRequired, statusId: PropTypes.string.isRequired, account: ImmutablePropTypes.map.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { account, statusId, onClose, intl } = this.props; return ( <div className='picture-in-picture__header'> <Link to={`/statuses/${statusId}`} className='picture-in-picture__header__account'> <Avatar account={account} size={36} /> <DisplayName account={account} /> </Link> <IconButton icon='times' onClick={onClose} title={intl.formatMessage(messages.close)} /> </div> ); } }
src/ui/LabelValue.js
touchstonejs/touchstonejs
import classnames from 'classnames'; import FieldControl from './FieldControl'; import Item from './Item'; import ItemInner from './ItemInner'; import React from 'react'; module.exports = React.createClass({ displayName: 'LabelValue', propTypes: { alignTop: React.PropTypes.bool, className: React.PropTypes.string, label: React.PropTypes.string, placeholder: React.PropTypes.string, value: React.PropTypes.string }, render () { return ( <Item alignTop={this.props.alignTop} className={this.props.className} component="label"> <ItemInner> <div className="FieldLabel">{this.props.label}</div> <FieldControl> <div className={classnames('field', this.props.value ? 'u-selectable' : 'field-placeholder')}> {this.props.value || this.props.placeholder} </div> </FieldControl> </ItemInner> </Item> ); } });
src/server.js
NogsMPLS/react-redux-universal-hot-example
import Express from 'express'; import React from 'react'; import Location from 'react-router/lib/Location'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import api from './api/api'; import ApiClient from './ApiClient'; import universalRouter from './universalRouter'; import Html from './Html'; import PrettyError from 'pretty-error'; const pretty = new PrettyError(); const app = new Express(); const proxy = httpProxy.createProxyServer({ target: 'http://localhost:' + config.apiPort }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); let webpackStats; if (!__DEVELOPMENT__) { webpackStats = require('../webpack-stats.json'); } app.use(require('serve-static')(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res); }); app.use((req, res) => { if (__DEVELOPMENT__) { webpackStats = require('../webpack-stats.json'); // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env delete require.cache[require.resolve('../webpack-stats.json')]; } const client = new ApiClient(req); const store = createStore(client); const location = new Location(req.path, req.query); if (__DISABLE_SSR__) { res.send('<!doctype html>\n' + React.renderToString(<Html webpackStats={webpackStats} component={<div/>} store={store}/>)); } else { universalRouter(location, undefined, store) .then(({component, transition, isRedirect}) => { if (isRedirect) { res.redirect(transition.redirectInfo.pathname); return; } res.send('<!doctype html>\n' + React.renderToString(<Html webpackStats={webpackStats} component={component} store={store}/>)); }) .catch((error) => { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500).send({error: error.stack}); }); } }); if (config.port) { app.listen(config.port, (err) => { if (err) { console.error(err); } else { api().then(() => { console.info('==> ✅ Server is listening'); console.info('==> 🌎 %s running on port %s, API on port %s', config.app.name, config.port, config.apiPort); console.info('----------\n==> 💻 Open http://localhost:%s in a browser to view the app.', config.port); }); } }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
src/graph/render.js
kbeloborodko/webpack-deep-dive
import React from 'react' import ReactDOM from 'react-dom' import {PieChart} from 'rd3' import {chain} from 'lodash' export default updateGraph function updateGraph(node, store) { store.findAll(todos => { ReactDOM.render( <Graph todos={todos} />, node, ) }) } function Graph({todos}) { const data = chain(todos) .groupBy('completed') .map((group, complete) => ({ label: complete === 'true' ? 'Complete' : 'Incomplete', value: Math.round(group.length / todos.length * 10000) / 100 })) .value() return ( <div> There are {todos.length} total todos <div> <PieChart data={data} width={450} height={310} radius={110} innerRadius={20} sectorBorderColor="white" title="Todo Data" /> </div> </div> ) } Graph.propTypes = { todos: React.PropTypes.array, }
src/app/components/SignIn.js
omarglz/rgvelite
import React from 'react'; import * as firebase from 'firebase'; export class SignIn extends React.Component { componentWillMount() { this.authListener = this.authListener.bind(this); this.authListener(); } loginWithPass(email,password) { firebase.auth().signInWithEmailAndPassword(email, password).catch((error) => { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; if (errorCode === 'auth/wrong-password') { alert('Wrong password.'); } else if (errorCode === 'auth/invalid-email' || errorCode === 'auth/user-not-found') { alert('Wrong email.'); } else { alert(errorMessage); } console.log(error); }); } authListener() { this.fireBaseListener = firebase.auth().onAuthStateChanged((user) => { if (user) { // this.setState({ // User: { id: user.uid } // }); window.location.href = "../admin"; } else { // No user is signed in. } }); } componentWillUnmount() { this.fireBaseListener && this.fireBaseListener(); this.authListener = undefined; } render() { return ( <main className="pa4 black-80"> <form className="measure center"> <fieldset id="sign_up" className="ba b--transparent ph0 mh0"> <legend className="f4 fw6 ph0 mh0">Sign In</legend> <div className="mt3"> <label className="db fw6 lh-copy f6" for="email-address">Email</label> <input className="pa2 input-reset ba bg-transparent w-100" type="email" name="email-address" id="email-address" /> </div> <div className="mv3"> <label className="db fw6 lh-copy f6" for="password">Password</label> <input className="b pa2 input-reset ba bg-transparent w-100" type="password" name="password" id="password" /> </div> </fieldset> <div className=""> <input className="b ph3 pv2 ba b--black bg-transparent grow pointer f6 dib" value="Sign in" onClick={() => this.loginWithPass(document.getElementById("email-address").value, document.getElementById("password").value)} /> </div> </form> </main> ); } }
src/core/containers/TapProvisioningSearch.js
getfilament/Distil
import React from 'react'; import { connect } from 'react-redux'; import _ from 'lodash'; import { bindActionCreators } from 'redux'; import * as hqActionCreators from '../actions/hqActionCreators'; import { List, ListItem, FontIcon, LinearProgress } from 'material-ui'; import Section from '../components/Section'; let TapProvisioning = React.createClass({ componentWillMount() { this.interval = setInterval(() => { this.props.hqActions.fetchTaps(); }, 5000); }, componentWillUnmount() { clearInterval(this.interval); }, render() { let { taps } = this.props; let foundTaps = taps.length > 0; if (!foundTaps) { return ( <Section zDepth={1}> <h1>Plug in a tap</h1> <h2>Searching</h2> <LinearProgress mode="indeterminate" /> </Section> ); } return ( <Section zDepth={1}> <h1>Choose a tap to provision</h1> <List> {taps.map(tap => ( <ListItem href={`/taps/${tap.id}/provision`} primaryText={tap.id} rightIcon={ <FontIcon className='material-icons'>keyboard_arrow_right</FontIcon> } /> ))} </List> </Section> ); } }); function mapStateToProps(state) { return { taps: _.values(state.taps).filter(t => !t.provisioned) }; } function mapDispatchToProps(dispatch) { return { hqActions: bindActionCreators(hqActionCreators, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(TapProvisioning);
app/components/Counter/Counter.js
taggun/app-benchmark
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import styles from './Counter.css'; class Counter extends Component { props: { increment: () => void, incrementIfOdd: () => void, incrementAsync: () => void, decrement: () => void, counter: number }; render() { const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props; return ( <div> <div className={styles.backButton} data-tid="backButton"> <Link to="/"> <i className="fa fa-arrow-left fa-3x" /> </Link> </div> <div className={`counter ${styles.counter}`} data-tid="counter"> {counter} </div> <div className={styles.btnGroup}> <button className={styles.btn} onClick={increment} data-tclass="btn"> <i className="fa fa-plus" /> </button> <button className={styles.btn} onClick={decrement} data-tclass="btn"> <i className="fa fa-minus" /> </button> <button className={styles.btn} onClick={incrementIfOdd} data-tclass="btn">odd</button> <button className={styles.btn} onClick={() => incrementAsync()} data-tclass="btn">async</button> </div> </div> ); } } export default Counter;
src/components/details/commentsBox/CommentsBox.js
yakovlevyuri/inloop-application-test
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import CommentsItem from './CommentsItem'; export default class CommentsBox extends Component { static propTypes = { comments: PropTypes.array, detailsId: PropTypes.string, removeComment: PropTypes.func.isRequired, }; render() { const { comments, detailsId, removeComment, } = this.props; return ( <div> { comments.map((comment, id) => { return ( <CommentsItem comment={comment} detailsId={detailsId} removeComment={removeComment} key={id} /> ) }) } </div> ); } }
src/components/vagrant/original/VagrantOriginal.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './VagrantOriginal.svg' /** VagrantOriginal */ function VagrantOriginal({ width, height, className }) { return ( <SVGDeviconInline className={'VagrantOriginal' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } VagrantOriginal.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default VagrantOriginal
components/pages/HomePage.js
Garnel/electron-react
import React from 'react'; class HomePage extends React.Component { render() { return ( <div>Home Page</div> ); } } export default HomePage;
packages/material-ui-icons/src/Pets.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Pets = props => <SvgIcon {...props}> <circle cx="4.5" cy="9.5" r="2.5" /><circle cx="9" cy="5.5" r="2.5" /><circle cx="15" cy="5.5" r="2.5" /><circle cx="19.5" cy="9.5" r="2.5" /><path d="M17.34 14.86c-.87-1.02-1.6-1.89-2.48-2.91-.46-.54-1.05-1.08-1.75-1.32-.11-.04-.22-.07-.33-.09-.25-.04-.52-.04-.78-.04s-.53 0-.79.05c-.11.02-.22.05-.33.09-.7.24-1.28.78-1.75 1.32-.87 1.02-1.6 1.89-2.48 2.91-1.31 1.31-2.92 2.76-2.62 4.79.29 1.02 1.02 2.03 2.33 2.32.73.15 3.06-.44 5.54-.44h.18c2.48 0 4.81.58 5.54.44 1.31-.29 2.04-1.31 2.33-2.32.31-2.04-1.3-3.49-2.61-4.8z" /> </SvgIcon>; Pets = pure(Pets); Pets.muiName = 'SvgIcon'; export default Pets;
components/MealToggler.js
PaRb/Extend
import React, { Component } from 'react'; import { View, Text, TouchableOpacity, StyleSheet, Modal } from 'react-native'; export default class MealToggler extends Component { render() { return <Text>TODO! MealToggler</Text>; } } MealToggler.propTypes = {};
src/components/commentBoard.js
melissa-c/Comms
'use strict' import React from 'react' import ReactDOM from 'react-dom' import ImgGallery from './imgGallery' import VerbGallery from './verbGallery' module.exports = class CommentBoard extends React.Component { constructor(props){ super(props) } render (){ return ( <div className="commentBoard"> <div>I can</div> <div> <img className='chosenVerb' src={this.props.verb}></img> </div> <div> <img className='chosenPic' src={this.props.image}></img> </div> </div> ) } }
react-universal-web-apps-simple/app/components/main/Header.js
joekraken/react-demos
import React from 'react'; import {IndexLink} from 'react-router'; export default class Header extends React.Component { render() { return ( <header className="app-header"> <h1 className="title"> <IndexLink to={this.props.root}>App</IndexLink> </h1> </header> ); } }
examples/with-external-scoped-css/pages/_document.js
nahue/next.js
import React from 'react' import Document, { Head, Main, NextScript } from 'next/document' export default class MyDocument extends Document { static getInitialProps ({ renderPage }) { const {html, head} = renderPage() return { html, head } } render () { return ( <html> <Head> <link rel='stylesheet' href='/static/css/bundle.css' /> </Head> <body> {this.props.customValue} <Main /> <NextScript /> </body> </html> ) } }
actor-apps/app-web/src/app/components/modals/InviteUser.react.js
vanloswang/actor-platform
import _ from 'lodash'; import React from 'react'; import Modal from 'react-modal'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import { Styles, FlatButton } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import ActorClient from 'utils/ActorClient'; import { KeyCodes } from 'constants/ActorAppConstants'; import InviteUserActions from 'actions/InviteUserActions'; import InviteUserByLinkActions from 'actions/InviteUserByLinkActions'; import ContactStore from 'stores/ContactStore'; import InviteUserStore from 'stores/InviteUserStore'; import ContactItem from './invite-user/ContactItem.react'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return ({ contacts: ContactStore.getContacts(), group: InviteUserStore.getGroup(), isOpen: InviteUserStore.isModalOpen() }); }; const hasMember = (group, userId) => undefined !== _.find(group.members, (c) => c.peerInfo.peer.id === userId); @ReactMixin.decorate(IntlMixin) class InviteUser extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); this.state = _.assign({ search: '' }, getStateFromStores()); ThemeManager.setTheme(ActorTheme); ThemeManager.setComponentThemes({ button: { minWidth: 60 } }); InviteUserStore.addChangeListener(this.onChange); ContactStore.addChangeListener(this.onChange); document.addEventListener('keydown', this.onKeyDown, false); } componentWillUnmount() { InviteUserStore.removeChangeListener(this.onChange); ContactStore.removeChangeListener(this.onChange); document.removeEventListener('keydown', this.onKeyDown, false); } onChange = () => { this.setState(getStateFromStores()); }; onClose = () => { InviteUserActions.hide(); }; onContactSelect = (contact) => { ActorClient.inviteMember(this.state.group.id, contact.uid); }; onInviteUrlByClick = () => { InviteUserByLinkActions.show(this.state.group); InviteUserActions.hide(); }; onKeyDown = (event) => { if (event.keyCode === KeyCodes.ESC) { event.preventDefault(); this.onClose(); } }; onSearchChange = (event) => { this.setState({search: event.target.value}); }; render() { const contacts = this.state.contacts; const isOpen = this.state.isOpen; let contactList = []; if (isOpen) { _.forEach(contacts, (contact, i) => { const name = contact.name.toLowerCase(); if (name.includes(this.state.search.toLowerCase())) { if (!hasMember(this.state.group, contact.uid)) { contactList.push( <ContactItem contact={contact} key={i} onSelect={this.onContactSelect}/> ); } else { contactList.push( <ContactItem contact={contact} key={i} member/> ); } } }, this); } if (contactList.length === 0) { contactList.push( <li className="contacts__list__item contacts__list__item--empty text-center"> <FormattedMessage message={this.getIntlMessage('inviteModalNotFound')}/> </li> ); } return ( <Modal className="modal-new modal-new--invite contacts" closeTimeoutMS={150} isOpen={isOpen} style={{width: 400}}> <header className="modal-new__header"> <a className="modal-new__header__icon material-icons">person_add</a> <h4 className="modal-new__header__title"> <FormattedMessage message={this.getIntlMessage('inviteModalTitle')}/> </h4> <div className="pull-right"> <FlatButton hoverColor="rgba(74,144,226,.12)" label="Done" labelStyle={{padding: '0 8px'}} onClick={this.onClose} secondary={true} style={{marginTop: -6}}/> </div> </header> <div className="modal-new__body"> <div className="modal-new__search"> <i className="material-icons">search</i> <input className="input input--search" onChange={this.onSearchChange} placeholder={this.getIntlMessage('inviteModalSearch')} type="search" value={this.state.search}/> </div> <a className="link link--blue" onClick={this.onInviteUrlByClick}> <i className="material-icons">link</i> {this.getIntlMessage('inviteByLink')} </a> </div> <div className="contacts__body"> <ul className="contacts__list"> {contactList} </ul> </div> </Modal> ); } } export default InviteUser;
app/components/app.js
ForbesLindesay/chat-example
'use strict'; import React from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import ChannelSelector from './channel-selector'; import LogIn from './log-in'; @connect(state => ({user: state.user})) export default class App { render() { if (!this.props.user) { return <LogIn onLogIn={name => this.props.dispatch({type: 'LOG_IN', name: name})} />; } return ( <div className="container"> <div className="row"> <div className="col-md-2"> <ul> <li><Link to="/">New Channel</Link></li> </ul> <ChannelSelector /> </div> <div className="col-md-10"> {this.props.children} </div> </div> </div> ); } };
src/containers/App.js
yyssc/sanhu
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import Top from '../components/Top'; import Footer from '../components/Footer'; import Sidebar from '../components/Sidebar'; class App extends React.Component { render() { let styles = { marginLeft: '200px', marginTop: '70px', WebkitTransition: 'all .3s ease-in-out', MozTransition: 'all .3s ease-in-out', OTransition: 'all .3s ease-in-out', transition: 'all .3s ease-in-out', height: '100%' }; return ( <div className="app-container"> <Sidebar /> <div style={ styles }> {/*<Top />*/} { this.props.children } {/*<Footer />*/} </div> </div> ); } } export default App;
frontend/react-stack/react/cdc-admin/src/components/BookTable.js
wesleyegberto/courses-projects
import React, { Component } from 'react'; export default class BookTable extends Component { render() { return ( <table className="pure-table"> <thead> <tr> <th>Author</th> <th>Title</th> <th>Price</th> </tr> </thead> <tbody> {this.props.books.map(book => <tr key={book.id}> <td>{book.autor.nome}</td> <td>{book.titulo}</td> <td>{book.preco}</td> </tr> )} </tbody> </table> ); } }
client/modules/users/components/teachersList.js
johngonzalez/abcdapp
import React from 'react'; import {ListGroup, ListGroupItem} from 'react-bootstrap'; const TeachersList = ({teachers}) => ( <div> <ListGroup> { teachers && teachers.length > 0 ? teachers.map((t) => ( <ListGroupItem key={t._id}> {t.emails[0].address} </ListGroupItem> )) : <p>No hay profesores en la lista</p> } </ListGroup> </div> ); TeachersList.propTypes = { teachers: React.PropTypes.array, }; export default TeachersList;
src/svg-icons/action/g-translate.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGTranslate = (props) => ( <SvgIcon {...props}> <path d="M20 5h-9.12L10 2H4c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h7l1 3h8c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zM7.17 14.59c-2.25 0-4.09-1.83-4.09-4.09s1.83-4.09 4.09-4.09c1.04 0 1.99.37 2.74 1.07l.07.06-1.23 1.18-.06-.05c-.29-.27-.78-.59-1.52-.59-1.31 0-2.38 1.09-2.38 2.42s1.07 2.42 2.38 2.42c1.37 0 1.96-.87 2.12-1.46H7.08V9.91h3.95l.01.07c.04.21.05.4.05.61 0 2.35-1.61 4-3.92 4zm6.03-1.71c.33.6.74 1.18 1.19 1.7l-.54.53-.65-2.23zm.77-.76h-.99l-.31-1.04h3.99s-.34 1.31-1.56 2.74c-.52-.62-.89-1.23-1.13-1.7zM21 20c0 .55-.45 1-1 1h-7l2-2-.81-2.77.92-.92L17.79 18l.73-.73-2.71-2.68c.9-1.03 1.6-2.25 1.92-3.51H19v-1.04h-3.64V9h-1.04v1.04h-1.96L11.18 6H20c.55 0 1 .45 1 1v13z"/> </SvgIcon> ); ActionGTranslate = pure(ActionGTranslate); ActionGTranslate.displayName = 'ActionGTranslate'; ActionGTranslate.muiName = 'SvgIcon'; export default ActionGTranslate;
src/components/App.js
edgarallanglez/foxacademia_frontend
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import injectTapEventPlugin from 'react-tap-event-plugin'; const ContextType = { // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader insertCss: PropTypes.func.isRequired, // Universal HTTP client fetch: PropTypes.func.isRequired, }; /** * The top-level React component setting context (global) variables * that can be accessed from all the child components. * * https://facebook.github.io/react/docs/context.html * * Usage example: * * const context = { * history: createBrowserHistory(), * store: createStore(), * }; * * ReactDOM.render( * <App context={context}> * <Layout> * <LandingPage /> * </Layout> * </App>, * container, * ); */ class App extends React.PureComponent { static propTypes = { context: PropTypes.shape(ContextType).isRequired, children: PropTypes.element.isRequired, }; static childContextTypes = ContextType; getChildContext() { return this.props.context; } componentWillMount() { injectTapEventPlugin(); } render() { // NOTE: If you need to add or modify header, footer etc. of the app, // please do that inside the Layout component. return React.Children.only(this.props.children); } } export default App;
.history/src/containers/GKM/ItemsContainer_20170624100126.js
oded-soffrin/gkm_viewer
import React from 'react'; import { connect } from 'react-redux'; import { addItem, addCategory, updateItem, deleteItem, resetDb } from '../../actions/itemActions' import ItemsPage from '../../components/GKM/ItemsPage.js'; import { getItems, getCategories } from '../../reducers/item' export const ItemsContainer = (props) => { return ( <div> <h1>Items Container</h1> <ItemsPage {...props} /> </div> ); }; ItemsContainer.propTypes = { }; function mapStateToProps(state) { return { items: getItems(state), categories: getCategories(state) }; } export default connect( mapStateToProps, { addItem, addCategory, updateItem, deleteItem, resetDb } )(ItemsContainer);
src/routes.js
cyberid41/simple-blog-react
import React from 'react'; import { IndexRoute, Route } from 'react-router'; import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth'; import { App, About, Register, Login, LoginSuccess, NotFound, Blogs, Blog, BlogEdit, BlogCreate } from 'containers'; export default store => { const loadAuthIfNeeded = cb => { if (!isAuthLoaded(store.getState())) { return store.dispatch(loadAuth()).then(() => cb()); } return cb(); }; const checkUser = (cond, replace, cb) => { const { auth: { user } } = store.getState(); if (!cond(user)) replace('/'); cb(); }; const requireNotLogged = (nextState, replace, cb) => { const cond = user => !user; loadAuthIfNeeded(() => checkUser(cond, replace, cb)); }; const requireLogin = (nextState, replace, cb) => { const cond = user => !!user; loadAuthIfNeeded(() => checkUser(cond, replace, cb)); }; /** * Please keep routes in alphabetical order */ return ( <Route path="/" component={App}> {/* Home (main) route */} <IndexRoute component={Blogs} /> {/* Routes requiring login */} <Route onEnter={requireLogin}> <Route path="loginSuccess" component={LoginSuccess} /> <Route path="blog/:_id/edit" component={BlogEdit} /> <Route path="blog/create" component={BlogCreate} /> </Route> {/* Routes disallow login */} <Route onEnter={requireNotLogged}> <Route path="register" component={Register} /> </Route> {/* Routes */} <Route path="login" component={Login} /> <Route path="about" component={About} /> <Route path="blog" component={Blogs} /> <Route path="blog/:slug" component={Blog} /> {/* Catch all route */} <Route path="*" component={NotFound} status={404} /> </Route> ); };
examples/sections/src/components/WrappedButton/WrappedButton.js
styleguidist/react-styleguidist
import React from 'react'; import Button from '../Button'; const dummyWrapper = (WrappedComponent) => (props) => <WrappedComponent {...props} />; /** * A button wrapped by a Decorator/Enhancer */ const WrappedButton = dummyWrapper(Button); export default WrappedButton;
client/src/login/root.js
andris9/mailtrain
'use strict'; import React from 'react'; import Login from './Login'; import Reset from './Forgot'; import ResetLink from './Reset'; import mailtrainConfig from 'mailtrainConfig'; function getMenus(t) { const subPaths = {} if (mailtrainConfig.isAuthMethodLocal) { subPaths.forgot = { title: t('passwordReset-1'), extraParams: [':username?'], link: '/login/forgot', panelComponent: Reset }; subPaths.reset = { title: t('passwordReset-1'), extraParams: [':username', ':resetToken'], link: '/login/reset', panelComponent: ResetLink }; } return { 'login': { title: t('signIn'), link: '/login', panelComponent: Login, children: subPaths } }; } export default { getMenus }
CompositeUi/src/views/form/TaskEdit.js
kreta/kreta
/* * This file is part of the Kreta package. * * (c) Beñat Espiña <benatespina@gmail.com> * (c) Gorka Laucirica <gorka.lauzirika@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import React from 'react'; import {connect} from 'react-redux'; import {Field, reduxForm} from 'redux-form'; import Form from './../component/Form'; import FormActions from './../component/FormActions'; import FormInput from './../component/FormInput'; import FormInputWysiwyg from './../component/FormInputWysiwyg'; import Button from './../component/Button'; import PageHeader from './../component/PageHeader'; import {Row, RowColumn} from './../component/Grid'; import Selector from './../component/Selector'; import SelectorOption from './../component/SelectorOption'; import Thumbnail from './../component/Thumbnail'; import UserThumbnail from './../component/UserThumbnail'; const validate = values => { const errors = {}, requiredFields = ['title', 'description', 'assignee', 'priority']; requiredFields.forEach(field => { if (!values[field] || values[field] === '') { errors[field] = 'Required'; } }); return errors; }; @connect(state => ({ initialValues: { project: state.currentProject.project.id, title: state.currentProject.selectedTask.title, description: state.currentProject.selectedTask.description, priority: state.currentProject.selectedTask.priority, assignee: state.currentProject.selectedTask.assignee.id, }, project: state.currentProject.project, updating: state.currentProject.updating, })) @reduxForm({form: 'TaskEdit', validate}) class TaskEdit extends React.Component { assigneeSelector() { const {project} = this.props, options = [], users = project.organization.organization_members.concat( project.organization.owners, ); users.forEach(member => { options.push( <SelectorOption key={member.id} text={member.user_name} thumbnail={<UserThumbnail user={member} />} value={member.id} />, ); }); return options; } render() { const {project, handleSubmit, updating} = this.props; return ( <Form onSubmit={handleSubmit}> <Row collapse> <RowColumn> <PageHeader thumbnail={<Thumbnail image={null} text={project.name} />} title={project.name} /> </RowColumn> <RowColumn> <Field autoFocus component={FormInput} label="Title" name="title" tabIndex={1} /> <div className="task-new__description"> <Field component={FormInputWysiwyg} label="Description" name="description" tabIndex={2} /> </div> </RowColumn> <RowColumn large={4} medium={6}> <Field component={Selector} name="assignee" tabIndex={3}> {this.assigneeSelector()} </Field> </RowColumn> <RowColumn large={4} medium={6}> <Field component={Selector} name="priority" tabIndex={4}> <SelectorOption text="Select priority..." value="" /> <SelectorOption text="High" value="HIGH" /> <SelectorOption text="Medium" value="MEDIUM" /> <SelectorOption text="Low" value="LOW" /> </Field> </RowColumn> <RowColumn> <FormActions> <Button color="green" disabled={updating} tabIndex={5} type="submit" > Done </Button> </FormActions> </RowColumn> </Row> </Form> ); } } export default TaskEdit;
RNTester/js/ActivityIndicatorExample.js
farazs/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @providesModule ActivityIndicatorExample */ 'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, StyleSheet, View } from 'react-native'; /** * Optional Flowtype state and timer types definition */ type State = { animating: boolean; }; type Timer = number; class ToggleAnimatingActivityIndicator extends Component { /** * Optional Flowtype state and timer types */ state: State; _timer: Timer; constructor(props) { super(props); this.state = { animating: true, }; } componentDidMount() { this.setToggleTimeout(); } componentWillUnmount() { clearTimeout(this._timer); } setToggleTimeout() { this._timer = setTimeout(() => { this.setState({animating: !this.state.animating}); this.setToggleTimeout(); }, 2000); } render() { return ( <ActivityIndicator animating={this.state.animating} style={[styles.centering, {height: 80}]} size="large" /> ); } } exports.displayName = (undefined: ?string); exports.framework = 'React'; exports.title = '<ActivityIndicator>'; exports.description = 'Animated loading indicators.'; exports.examples = [ { title: 'Default (small, white)', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} color="white" /> ); } }, { title: 'Gray', render() { return ( <View> <ActivityIndicator style={[styles.centering]} /> <ActivityIndicator style={[styles.centering, {backgroundColor: '#eeeeee'}]} /> </View> ); } }, { title: 'Custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator color="#0000ff" /> <ActivityIndicator color="#aa00aa" /> <ActivityIndicator color="#aa3300" /> <ActivityIndicator color="#00aa00" /> </View> ); } }, { title: 'Large', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} size="large" color="white" /> ); } }, { title: 'Large, custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator size="large" color="#0000ff" /> <ActivityIndicator size="large" color="#aa00aa" /> <ActivityIndicator size="large" color="#aa3300" /> <ActivityIndicator size="large" color="#00aa00" /> </View> ); } }, { title: 'Start/stop', render() { return <ToggleAnimatingActivityIndicator />; } }, { title: 'Custom size', render() { return ( <ActivityIndicator style={[styles.centering, {transform: [{scale: 1.5}]}]} size="large" /> ); } }, { platform: 'android', title: 'Custom size (size: 75)', render() { return ( <ActivityIndicator style={styles.centering} size={75} /> ); } }, ]; const styles = StyleSheet.create({ centering: { alignItems: 'center', justifyContent: 'center', padding: 8, }, gray: { backgroundColor: '#cccccc', }, horizontal: { flexDirection: 'row', justifyContent: 'space-around', padding: 8, }, });
app/Containers/MeContainer.js
TBoyLi/BookBall
import React from 'react'; import {connect} from 'react-redux'; import Me from '../Components/Me'; export default class MeContainer extends React.Component { render() { return ( <Me {...this.props} /> ) } } // export default connect((state) => { // const {MeContainer} = state; // return { // MeReducer // } // })(MeContainer);
assets/javascripts/kitten/components/graphics/icons/visa-icon/index.js
KissKissBankBank/kitten
import React from 'react' import classNames from 'classnames' export const VisaIcon = ({ className, ...props }) => ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 732 224.43" width="36" className={classNames('k-ColorSvg', className)} {...props} > <title>Visa</title> <path fill="#004686" d="M257.87 221.21L294.93 3.77h59.26l-37.08 217.44h-59.24zM532.06 9.13A152.88 152.88 0 0 0 478.94 0c-58.56 0-99.81 29.49-100.16 71.72-.33 31.24 29.45 48.67 51.93 59.07 23.07 10.65 30.82 17.45 30.71 27-.15 14.57-18.42 21.23-35.46 21.23-23.72 0-36.32-3.29-55.79-11.41l-7.64-3.46-8.32 48.67c13.84 6.07 39.44 11.33 66 11.61 62.3 0 102.74-29.15 103.2-74.28.22-24.74-15.57-43.56-49.76-59.08-20.71-10.06-33.4-16.77-33.27-27 0-9 10.74-18.7 33.94-18.7a109.19 109.19 0 0 1 44.39 8.35l5.31 2.5 8-47.12zM684 3.98h-45.8c-14.19 0-24.8 3.88-31 18l-88 199.25h62.23s10.18-26.79 12.48-32.67c6.8 0 67.26.09 75.9.09 1.78 7.61 7.21 32.58 7.21 32.58h55L684 3.98m-73 140.15c4.9-12.53 23.61-60.78 23.61-60.78-.35.57 4.86-12.59 7.86-20.75l4 18.74s11.34 51.91 13.72 62.79H611zM208.17 3.93l-58 148.27-6.17-30.12c-10.84-34.74-44.49-72.36-82.12-91.21l53.06 190.15 62.7-.07 93.3-217h-62.77z" /> <path d="M96.32 3.8H.76L0 8.33c74.35 18 123.54 61.49 144 113.75l-20.82-99.92c-3.59-13.77-14-17.87-26.86-18.36z" fill="#ef9b11" /> </svg> )
src/components/recording/MouseDrawingHandler.js
zebras-filming-videos/streamr-web
import React from 'react' import throttle from 'lodash/throttle' import cx from 'classnames' import Measure from 'react-measure' export default class MouseDrawingHandler extends React.Component { constructor (props) { super(props) this.state = { drawing: false } } componentDidMount () { this.throttledPointCreate = throttle(this.props.onPointCreate, 20, { leading: true, trailing: true }) this.throttledCursorMove = throttle(this.props.onCursorMove, 50, { leading: true, trailing: true }) this.measurer = setTimeout(() => this.refs.measure.measure(), 400) } componentWillUnmount () { clearTimeout(this.measurer) } mouseDownCallback (event, measurements) { if (!this.props.recording) return this.props.onLineStart(this.getRelativePosition(event, measurements)) this.setState({ drawing: true }) } mouseUpCallback (event, measurements) { if (!this.props.recording) return if (this.state.drawing) { this.throttledPointCreate.cancel() this.props.onLineEnd(this.getRelativePosition(event, measurements)) } this.setState({ drawing: false }) } mouseMoveCallback (event, measurements) { if (!this.props.recording) return if (this.state.drawing) { this.throttledPointCreate(this.getRelativePosition(event, measurements)) } else { this.throttledCursorMove(this.getRelativePosition(event, measurements)) } } mouseLeaveCallback (event, measurement) { if (!this.props.recording) return this.setState({ drawing: false }) if (this.state.drawing) { this.props.onPointCreate(this.getRelativePosition(event, measurement)) this.props.onLineEnd(this.getRelativePosition(event, measurement)) } } getRelativePosition (event, measurements) { const x = (event.pageX - measurements.left) / measurements.width const y = (event.pageY - measurements.top) / measurements.height return { x: this.round(x, 5), y: this.round(y, 5) } } round (number, precision) { return Math.round(number * Math.pow(10, precision)) / Math.pow(10, precision) } render () { const { children } = this.props return ( <div className={cx('mouse-drawing-handler')}> <Measure ref='measure' whitelist={['width', 'height', 'top', 'right', 'bottom', 'left']}> {(measurements) => ( <div className='click-zone' onMouseDown={(event) => this.mouseDownCallback(event, measurements)} onMouseMove={(event) => this.mouseMoveCallback(event, measurements)} onMouseUp={(event) => this.mouseUpCallback(event, measurements)} onMouseLeave={(event) => this.mouseLeaveCallback(event, measurements)}> {children} </div> )} </Measure> </div> ) } }
app/javascript/mastodon/features/ui/components/compare_history_modal.js
glitch-soc/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import { FormattedMessage } from 'react-intl'; import { closeModal } from 'mastodon/actions/modal'; import emojify from 'mastodon/features/emoji/emoji'; import escapeTextContentForBrowser from 'escape-html'; import InlineAccount from 'mastodon/components/inline_account'; import IconButton from 'mastodon/components/icon_button'; import RelativeTimestamp from 'mastodon/components/relative_timestamp'; import MediaAttachments from 'mastodon/components/media_attachments'; const mapStateToProps = (state, { statusId }) => ({ versions: state.getIn(['history', statusId, 'items']), }); const mapDispatchToProps = dispatch => ({ onClose() { dispatch(closeModal()); }, }); export default @connect(mapStateToProps, mapDispatchToProps) class CompareHistoryModal extends React.PureComponent { static propTypes = { onClose: PropTypes.func.isRequired, index: PropTypes.number.isRequired, statusId: PropTypes.string.isRequired, versions: ImmutablePropTypes.list.isRequired, }; render () { const { index, versions, onClose } = this.props; const currentVersion = versions.get(index); const emojiMap = currentVersion.get('emojis').reduce((obj, emoji) => { obj[`:${emoji.get('shortcode')}:`] = emoji.toJS(); return obj; }, {}); const content = { __html: emojify(currentVersion.get('content'), emojiMap) }; const spoilerContent = { __html: emojify(escapeTextContentForBrowser(currentVersion.get('spoiler_text')), emojiMap) }; const formattedDate = <RelativeTimestamp timestamp={currentVersion.get('created_at')} short={false} />; const formattedName = <InlineAccount accountId={currentVersion.get('account')} />; const label = currentVersion.get('original') ? ( <FormattedMessage id='status.history.created' defaultMessage='{name} created {date}' values={{ name: formattedName, date: formattedDate }} /> ) : ( <FormattedMessage id='status.history.edited' defaultMessage='{name} edited {date}' values={{ name: formattedName, date: formattedDate }} /> ); return ( <div className='modal-root__modal compare-history-modal'> <div className='report-modal__target'> <IconButton className='report-modal__close' icon='times' onClick={onClose} size={20} /> {label} </div> <div className='compare-history-modal__container'> <div className='status__content'> {currentVersion.get('spoiler_text').length > 0 && ( <React.Fragment> <div className='translate' dangerouslySetInnerHTML={spoilerContent} /> <hr /> </React.Fragment> )} <div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} /> {!!currentVersion.get('poll') && ( <div className='poll'> <ul> {currentVersion.getIn(['poll', 'options']).map(option => ( <li key={option.get('title')}> <span className='poll__input disabled' /> <span className='poll__option__text translate' dangerouslySetInnerHTML={{ __html: emojify(escapeTextContentForBrowser(option.get('title')), emojiMap) }} /> </li> ))} </ul> </div> )} <MediaAttachments status={currentVersion} /> </div> </div> </div> ); } }
src/svg-icons/av/queue-play-next.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvQueuePlayNext = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h2v-2H3V5h18v8h2V5c0-1.11-.9-2-2-2zm-8 7V7h-2v3H8v2h3v3h2v-3h3v-2h-3zm11 8l-4.5 4.5L18 21l3-3-3-3 1.5-1.5L24 18z"/> </SvgIcon> ); AvQueuePlayNext = pure(AvQueuePlayNext); AvQueuePlayNext.displayName = 'AvQueuePlayNext'; AvQueuePlayNext.muiName = 'SvgIcon'; export default AvQueuePlayNext;
app/static/src/performer/TestTypeResultForm_modules/NewWindingResistanceTestForm.js
SnowBeaver/Vision
import React from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; import FormGroup from 'react-bootstrap/lib/FormGroup'; import Button from 'react-bootstrap/lib/Button'; import Radio from 'react-bootstrap/lib/Radio'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; import {findDOMNode} from 'react-dom'; import {hashHistory} from 'react-router'; import {Link} from 'react-router'; import {NotificationContainer, NotificationManager} from 'react-notifications'; const TextField = React.createClass({ render: function() { var label = (this.props.label != null) ? this.props.label: ""; var name = (this.props.name != null) ? this.props.name: ""; var value = (this.props.value != null) ? this.props.value: ""; return ( <FormGroup> <FormControl type="text" placeholder={label} name={name} value={value} onChange={this.props.onChange} /> <FormControl.Feedback /> </FormGroup> ); } }); var NewWindingResistanceTestForm = React.createClass({ getInitialState: function () { return { loading: false, maxRowId: 0, deleteOnSubmit: [], showPrimaryWindingTestPanel: true, showSecondaryWindingTestPanel: false, showTertiaryWindingTestPanel: false, tests: [], errors: {}, fields: [ 'temp1', 'corr1', 'mesure1', 'temp2', 'corr2', 'mesure2', 'temp3', 'corr3', 'mesure3', 'winding', 'tap_position', 'id' ] } }, getUniqueKey: function() { var maxRowId = this.state.maxRowId + 1; this.state.maxRowId += 1; return "key-" + maxRowId; }, addResultToState: function (result) { var res = (result['result']); var fields = this.state.fields; var tests = []; for ( var i = 0; i < res.length; i++ ) { var test = { uniqueKey: this.getUniqueKey() }; var data = res[i]; for (var j = 0; j < fields.length; j++) { var key = fields[j]; if (data.hasOwnProperty(key)) { test[key] = data[key]; } } tests[i] = test; } this.setState({tests: tests}); }, componentDidMount: function () { var source = '/api/v1.0/' + this.props.tableName + '/?test_result_id=' + this.props.testResultId; this.serverRequest = $.authorizedGet(source, this.addResultToState, 'json'); }, _create: function () { var fields = this.state.fields; var tests = this.state.tests; var data = []; for (var i = 0; i < tests.length; i++) { var test = {test_result_id: this.props.testResultId}; var tap = tests[i]; for (var j = 0; j < fields.length; j++) { var key = fields[j]; if (tap.hasOwnProperty(key)) { test[key] = tap[key]; } } data.push(test) } return $.authorizedAjax({ url: '/api/v1.0/test_result/multi/' + this.props.tableName, type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify(data), beforeSend: function () { this.setState({loading: true}); }.bind(this) }) }, _delete: function (id) { return $.authorizedAjax({ url: '/api/v1.0/' + this.props.tableName + '/' + id, type: 'DELETE', }) }, _onSubmit: function (e) { e.preventDefault(); // Do not propagate the submit event of the main form e.stopPropagation(); if (!this.is_valid()){ NotificationManager.error('Please correct the errors'); e.stopPropagation(); return false; } this.state.tests = this.refs.table.state.data; var xhr = this._create(); xhr.done(this._onSuccess) .fail(this._onError) .always(this.hideLoading); for (var i = 0; i < this.state.deleteOnSubmit.length; i++) { var xhr_del = this._delete(this.state.deleteOnSubmit[i]); xhr_del.done(this._onDeleteSuccess) .fail(this._onError) } this.state.deleteOnSubmit = []; }, hideLoading: function () { this.setState({loading: false}); }, _onSuccess: function (data) { // this.setState(this.getInitialState()); this.addResultToState(data); NotificationManager.success('Test values have been saved successfully.'); }, _onDeleteSuccess: function (data) { NotificationManager.success('Test values have been deleted successfully.'); }, _onError: function (data) { var message = "Failed"; var res = data.responseJSON; if (res.message) { message = data.responseJSON.message; } if (res.error) { this.setState({ errors: res.error }); } NotificationManager.error(message); }, _onFilterChange: function (e) { var state = { showPrimaryWindingTestPanel: false, showSecondaryWindingTestPanel: false, showTertiaryWindingTestPanel: false }; if (e.target.id === 'primary') { state['showPrimaryWindingTestPanel'] = true; } else if (e.target.id === 'secondary') { state['showSecondaryWindingTestPanel'] = true; } else if (e.target.id === 'tertiary') { state['showTertiaryWindingTestPanel'] = true; } this.setState(state); }, _formGroupClass: function (field) { var className = "form-group "; if (field) { className += " has-error" } return className; }, addToDeleteOnSubmit: function(el) { if (el.hasOwnProperty('id')) { this.state.deleteOnSubmit.push(el.id); } }, addNewStringToTable: function() { var newRow = { uniqueKey: this.getUniqueKey() }; this.refs.table.handleAddRow(newRow); }, deleteStringsFromTable: function() { var selectedRowKeys = this.refs.table.state.selectedRowKeys; var table = this.refs.table.state.data; var selectedRows = table.filter(function(el){ return selectedRowKeys.indexOf(el.uniqueKey) !== -1; }); selectedRows.map(this.addToDeleteOnSubmit); var result = this.refs.table.handleDropRow(selectedRowKeys); }, dataFormatPosition: function(cell, row, formatExtraData, rowIdx){ return rowIdx + 1; }, _validateDict: { mesure1: {data_type: "float", label: "H1-H2"}, temp1: {data_type: "float", label: "Temp(3d column)"}, corr1: {data_type: "float", label: "Corr (4th column)"}, mesure2: {data_type: "float", label: "H2-H3"}, temp2: {data_type: "float", label: "Temp(6th column)"}, corr2: {data_type: "float", label: "Corr(7th column)"}, mesure3: {data_type: "float", label: "H3-H1"}, temp3: {data_type: "float", label: "Temp(9th column)"}, corr3: {data_type: "float", label: "Corr(10th column)"}, winding: {data_type: "int", label: "Winding"}, tap_position: {data_type: "int", label: "Tap position"}, }, _validateFieldType: function (value, type){ var error = ""; if (type != undefined && value){ var typePatterns = { "float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/, "int": /^(-|\+)?(0|[1-9]\d*)$/, }; if (!typePatterns[type].test(value)){ error = "Invalid " + type + " value"; } } return error; }, is_valid: function () { if (Object.keys(this.state.errors).length > 0) { return false; } var fields = this.state.fields.slice(); var index = fields.indexOf("id"); if (index >= 0) { fields.splice( index, 1 ); } var tests = this.state.tests; var is_valid = true; var msg = ''; for (var i = 0; i < tests.length; i++) { var tap = tests[i]; for (var j = 0; j < fields.length; j++) { var field_name = fields[j]; if (tap.hasOwnProperty(field_name)) { var value = tap[field_name]; if (value) { var data_type = this._validateDict[field_name]['data_type']; var label = this._validateDict[field_name]['label']; var error = this._validateFieldType(value, data_type); msg = 'Value of (' + label + ') in row N' + ( i + 1 ) + ' must be of type ' + data_type + ' \n\n'; if (error) { is_valid = false; NotificationManager.error(msg, 'Validation error', 20000); } } } } } return is_valid; }, beforeSaveCell: function(row, name, value) { var data_type = this._validateDict[name]['data_type']; var label = this._validateDict[name]['label']; var error = this._validateFieldType(value, data_type); if (error) { NotificationManager.error('Value of (' + label + ') must by of type ' + data_type); } return true; }, render: function () { return ( <div className="form-container"> <form method="post" action="#" onSubmit={this._onSubmit} > <BootstrapTable data={this.state.tests} striped={true} hover={true} condensed={true} ignoreSinglePage={true} selectRow={{mode: "checkbox", clickToSelect: true, bgColor: "rgb(238, 193, 213)",}} cellEdit={{mode: "click", blurToSave:true, beforeSaveCell:this.beforeSaveCell}} ref="table" > <TableHeaderColumn dataField="id" hidden>ID</TableHeaderColumn> <TableHeaderColumn dataField="uniqueKey" isKey hidden>Key</TableHeaderColumn> <TableHeaderColumn dataField="position" dataFormat={this.dataFormatPosition} >N</TableHeaderColumn> <TableHeaderColumn dataField="mesure1">H1-H2</TableHeaderColumn> <TableHeaderColumn dataField="temp1">Temp(C)</TableHeaderColumn> <TableHeaderColumn dataField="corr1">Corr.75C</TableHeaderColumn> <TableHeaderColumn dataField="mesure2">H2-H3</TableHeaderColumn> <TableHeaderColumn dataField="temp2">Temp(C)</TableHeaderColumn> <TableHeaderColumn dataField="corr2">Corr.75C</TableHeaderColumn> <TableHeaderColumn dataField="mesure3">H3-H1</TableHeaderColumn> <TableHeaderColumn dataField="temp3">Temp</TableHeaderColumn> <TableHeaderColumn dataField="corr3">Corr.75C</TableHeaderColumn> <TableHeaderColumn dataField="winding">Winding</TableHeaderColumn> <TableHeaderColumn dataField="tap_position">Tap pos</TableHeaderColumn> {/*<TableHeaderColumn dataField="tap_position"*/} {/*editable={{ validator: this.tap_positionValidator}}*/} {/*>Tap pos</TableHeaderColumn>*/} </BootstrapTable> <div className="row"> <div className="col-md-2"> <a href="javascript:void(0)" className="glyphicon glyphicon-plus" onClick={this.addNewStringToTable} aria-hidden="true" >Add new</a> </div> <div className="row"> <div className="col-md-2"> <a href="javascript:void(0)" className="glyphicon glyphicon-minus" onClick={this.deleteStringsFromTable} aria-hidden="true" >Delete selected</a> </div> </div> </div> <div className="row"> <div className="col-md-offset-7"> <div className="col-md-3" > <Radio name="filter" id="primary" onClick={this._onFilterChange}>Primary(H)</Radio> </div> <div className="col-md-3" > <Radio name="filter" id="secondary" onClick={this._onFilterChange} >Secondary(X)</Radio> </div> <div className="col-md-3" > <Radio name="filter" id="tertiary" onClick={this._onFilterChange} >Tertiary(T)</Radio> </div> </div> </div> <div className="row"> <div className="col-md-12 "> <Button bsStyle="success" className="pull-right" type="submit">Save</Button> &nbsp; <Button bsStyle="danger" className="pull-right margin-right-xs" onClick={this.props.handleClose} >Cancel</Button> </div> </div> </form> </div> ); } }); export default NewWindingResistanceTestForm;
dungeon-maker/src/components/AddPowers.js
sgottreu/dungeoneering
import React from 'react'; import PowersForm from './PowersForm'; function AddPowers( {existingPowers, current_power, power, boundPowerAC, entitiesState, powersState, boundEntityAC} ) { return ( <div className="AddPowers"> <PowersForm entityType='character' existingPowers={existingPowers} boundPowerAC={boundPowerAC} entitiesState={entitiesState} powersState={powersState} boundEntityAC={boundEntityAC} /> </div> ); } export default AddPowers;
client/components/SecondaryNav.js
steveliles/react-ssr-codesplit
import React from 'react' import Link from 'redux-first-router-link' import styles from './SecondaryNav.css' const SecondaryNav = ({ tabs }) => ( <ol className={styles.bar}> {tabs.map(t => ( <li key={t.name}><Link href={t.href || t.name}>{t.name}</Link></li> ))} </ol> ) export default SecondaryNav
src/client/components/ApplicationFormComponent.js
aaronpanch/hercules
import React from 'react'; import PropTypes from 'prop-types'; import Input from './InputComponent'; import FormRow from './FormRowComponent'; require('../styles/card.scss'); require('../styles/button.scss'); class ApplicationForm extends React.Component { constructor(props) { super(props); this.state = { appName: this.props.name || '', desc: this.props.description || '', owner: this.props.owner || '', repo: this.props.repo || '', }; this.cancel = this.cancel.bind(this); this.create = this.create.bind(this); } cancel() { this.props.cancelAdding(); } create(e) { this.props.createApp({ name: this.state.appName, description: this.state.desc, owner: this.state.owner, repo: this.state.repo, }); } render() { return ( <section className="card"> <div className="card__padded"> <h1 className="card__title">Add Application</h1> <FormRow hint="Choose a unique name as an identifier for your app"> <Input label="name" disabled={this.props.disabled} value={this.state.appName} onChange={e => { this.setState({ appName: e.target.value }); }} /> </FormRow> <FormRow> <Input label="description" disabled={this.props.disabled} value={this.state.desc} onChange={e => { this.setState({ desc: e.target.value }); }} /> </FormRow> <FormRow hint="Enter the GitHub repository details"> <div className="grid"> <div className="grid-1"> <Input label="owner" disabled={this.props.disabled} value={this.state.owner} onChange={e => { this.setState({ owner: e.target.value }); }} /> </div> <p className="grid-0 u-margin-an" style={{ display: 'flex', alignItems: 'center' }} > / </p> <div className="grid-1"> <Input label="repo" disabled={this.props.disabled} value={this.state.repo} onChange={e => { this.setState({ repo: e.target.value }); }} /> </div> </div> </FormRow> </div> <div className="card__buttons"> <button onClick={this.cancel} className="button button--cancel"> cancel </button> <button className="button button--primary" onClick={this.create}> save </button> </div> </section> ); } } ApplicationForm.propTypes = { cancelAdding: PropTypes.func.isRequired, }; export default ApplicationForm;
src/index.js
vgrigoriu/learn-to-read
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import 'bootstrap/dist/css/bootstrap.css'; import 'bootstrap/dist/css/bootstrap-theme.css'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
client/src/screens/groups.screen.js
srtucker22/chatty
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { FlatList, ActivityIndicator, Button, Image, StyleSheet, Text, TouchableHighlight, View, } from 'react-native'; import { graphql, compose } from 'react-apollo'; import moment from 'moment'; import Icon from 'react-native-vector-icons/FontAwesome'; import { connect } from 'react-redux'; import { USER_QUERY } from '../graphql/user.query'; const styles = StyleSheet.create({ container: { backgroundColor: 'white', flex: 1, }, loading: { justifyContent: 'center', flex: 1, }, groupContainer: { flex: 1, flexDirection: 'row', alignItems: 'center', backgroundColor: 'white', borderBottomColor: '#eee', borderBottomWidth: 1, paddingHorizontal: 12, paddingVertical: 8, }, groupName: { fontWeight: 'bold', flex: 0.7, }, groupTextContainer: { flex: 1, flexDirection: 'column', paddingLeft: 6, }, groupText: { color: '#8c8c8c', }, groupImage: { width: 54, height: 54, borderRadius: 27, }, groupTitleContainer: { flexDirection: 'row', }, groupLastUpdated: { flex: 0.3, color: '#8c8c8c', fontSize: 11, textAlign: 'right', }, groupUsername: { paddingVertical: 4, }, header: { alignItems: 'flex-end', padding: 6, borderColor: '#eee', borderBottomWidth: 1, }, warning: { textAlign: 'center', padding: 12, }, }); // format createdAt with moment const formatCreatedAt = createdAt => moment(createdAt).calendar(null, { sameDay: '[Today]', nextDay: '[Tomorrow]', nextWeek: 'dddd', lastDay: '[Yesterday]', lastWeek: 'dddd', sameElse: 'DD/MM/YYYY', }); const Header = ({ onPress }) => ( <View style={styles.header}> <Button title={'New Group'} onPress={onPress} /> </View> ); Header.propTypes = { onPress: PropTypes.func.isRequired, }; class Group extends Component { constructor(props) { super(props); this.goToMessages = this.props.goToMessages.bind(this, this.props.group); } render() { const { id, name, messages } = this.props.group; return ( <TouchableHighlight key={id} onPress={this.goToMessages} > <View style={styles.groupContainer}> <Image style={styles.groupImage} source={{ uri: 'https://reactjs.org/logo-og.png', }} /> <View style={styles.groupTextContainer}> <View style={styles.groupTitleContainer}> <Text style={styles.groupName}>{`${name}`}</Text> <Text style={styles.groupLastUpdated}> {messages.edges.length ? formatCreatedAt(messages.edges[0].node.createdAt) : ''} </Text> </View> <Text style={styles.groupUsername}> {messages.edges.length ? `${messages.edges[0].node.from.username}:` : ''} </Text> <Text style={styles.groupText} numberOfLines={1}> {messages.edges.length ? messages.edges[0].node.text : ''} </Text> </View> <Icon name="angle-right" size={24} color={'#8c8c8c'} /> </View> </TouchableHighlight> ); } } Group.propTypes = { goToMessages: PropTypes.func.isRequired, group: PropTypes.shape({ id: PropTypes.number, name: PropTypes.string, messages: PropTypes.shape({ edges: PropTypes.arrayOf(PropTypes.shape({ cursor: PropTypes.string, node: PropTypes.object, })), }), }), }; class Groups extends Component { static navigationOptions = { title: 'Chats', }; constructor(props) { super(props); this.goToMessages = this.goToMessages.bind(this); this.goToNewGroup = this.goToNewGroup.bind(this); this.onRefresh = this.onRefresh.bind(this); } onRefresh() { this.props.refetch(); // faking unauthorized status } keyExtractor = item => item.id.toString(); goToMessages(group) { const { navigate } = this.props.navigation; navigate('Messages', { groupId: group.id, title: group.name }); } goToNewGroup() { const { navigate } = this.props.navigation; navigate('NewGroup'); } renderItem = ({ item }) => <Group group={item} goToMessages={this.goToMessages} />; render() { const { loading, user, networkStatus } = this.props; // render loading placeholder while we fetch messages if (loading || !user) { return ( <View style={[styles.loading, styles.container]}> <ActivityIndicator /> </View> ); } if (user && !user.groups.length) { return ( <View style={styles.container}> <Header onPress={this.goToNewGroup} /> <Text style={styles.warning}>{'You do not have any groups.'}</Text> </View> ); } // render list of groups for user return ( <View style={styles.container}> <FlatList data={user.groups} keyExtractor={this.keyExtractor} renderItem={this.renderItem} ListHeaderComponent={() => <Header onPress={this.goToNewGroup} />} onRefresh={this.onRefresh} refreshing={networkStatus === 4} /> </View> ); } } Groups.propTypes = { navigation: PropTypes.shape({ navigate: PropTypes.func, }), loading: PropTypes.bool, networkStatus: PropTypes.number, refetch: PropTypes.func, user: PropTypes.shape({ id: PropTypes.number.isRequired, email: PropTypes.string.isRequired, groups: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, }), ), }), }; const userQuery = graphql(USER_QUERY, { skip: ownProps => !ownProps.auth || !ownProps.auth.jwt, options: ownProps => ({ variables: { id: ownProps.auth.id } }), props: ({ data: { loading, networkStatus, refetch, user } }) => ({ loading, networkStatus, refetch, user, }), }); const mapStateToProps = ({ auth }) => ({ auth, }); export default compose( connect(mapStateToProps), userQuery, )(Groups);
src/svg-icons/editor/format-indent-increase.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatIndentIncrease = (props) => ( <SvgIcon {...props}> <path d="M3 21h18v-2H3v2zM3 8v8l4-4-4-4zm8 9h10v-2H11v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z"/> </SvgIcon> ); EditorFormatIndentIncrease = pure(EditorFormatIndentIncrease); EditorFormatIndentIncrease.displayName = 'EditorFormatIndentIncrease'; EditorFormatIndentIncrease.muiName = 'SvgIcon'; export default EditorFormatIndentIncrease;
packages/reactor-kitchensink/src/examples/Grid/ReduxGrid/ReduxGrid.js
sencha/extjs-reactor
import React, { Component } from 'react'; import { Grid, Toolbar, Container, Button } from '@extjs/ext-react'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import Employees from './Employees'; import { reducer } from './reducer'; const store = createStore(reducer); export default class ReduxGridExample extends Component { render() { return ( <Provider store={store}> <Container layout="fit" padding="10"> <Employees/> </Container> </Provider> ) } }
blueprints/form/files/__root__/forms/__name__Form/__name__Form.js
danieljwest/ExamGenerator
import React from 'react' import { reduxForm } from 'redux-form' export const fields = [] const validate = (values) => { const errors = {} return errors } type Props = { handleSubmit: Function, fields: Object, } export class <%= pascalEntityName %> extends React.Component { props: Props; defaultProps = { fields: {}, } render() { const { fields, handleSubmit } = this.props return ( <form onSubmit={handleSubmit}> </form> ) } } <%= pascalEntityName %> = reduxForm({ form: '<%= pascalEntityName %>', fields, validate })(<%= pascalEntityName %>) export default <%= pascalEntityName %>
js/pages/logframe/components/title.js
mercycorps/TolaActivity
import React from 'react'; import { inject } from 'mobx-react'; const ExcelButton = inject('filterStore')( ({ filterStore }) => { const clickHandler = filterStore.excelUrl ? () => { window.open(filterStore.excelUrl, '_blank') } : (e) => { e.preventDefault(); }; return ( <button type="button" className="btn btn-sm btn-secondary" onClick={ clickHandler } disabled={ !filterStore.excelUrl }> <i className="fas fa-download"></i> Excel </button> ); } ); const TitleBar = inject('dataStore')( ({ dataStore }) => { return ( <React.Fragment> <div className="logframe--header"> <h1 className="page-title h2"> <a href={ dataStore.program_page_url }>{ dataStore.name }:</a> &nbsp; <span className="font-weight-normal text-muted text-nowrap"> { // # Translators: short for "Logistical Framework" gettext('Logframe') } &nbsp; <small><i className="fas fa-table"></i></small> </span> </h1> </div> <ExcelButton /> </React.Fragment> ); } ) export default TitleBar;
client/app/routes.js
vulcan-estudios/pwa-examples
import React from 'react'; import { Route, IndexRoute, Redirect } from 'react-router'; import App from 'client/app/containers/App'; import Fridge from 'client/app/containers/Fridge'; import Recipes from 'client/app/containers/Recipes'; import Blending from 'client/app/containers/Blending'; export default ( <Route path='/' component={App}> <IndexRoute component={Fridge} /> <Route path='/recipes' component={Recipes} /> <Route path='/blender/:recipeId' component={Blending} /> <Redirect from='*' to='/' /> </Route> );
frontend/src/Organize/OrganizePreviewRow.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import CheckInput from 'Components/Form/CheckInput'; import Icon from 'Components/Icon'; import { icons, kinds } from 'Helpers/Props'; import styles from './OrganizePreviewRow.css'; class OrganizePreviewRow extends Component { // // Lifecycle componentDidMount() { const { id, onSelectedChange } = this.props; onSelectedChange({ id, value: true }); } // // Listeners onSelectedChange = ({ value, shiftKey }) => { const { id, onSelectedChange } = this.props; onSelectedChange({ id, value, shiftKey }); }; // // Render render() { const { id, existingPath, newPath, isSelected } = this.props; return ( <div className={styles.row}> <CheckInput containerClassName={styles.selectedContainer} name={id.toString()} value={isSelected} onChange={this.onSelectedChange} /> <div> <div> <Icon name={icons.SUBTRACT} kind={kinds.DANGER} /> <span className={styles.path}> {existingPath} </span> </div> <div> <Icon name={icons.ADD} kind={kinds.SUCCESS} /> <span className={styles.path}> {newPath} </span> </div> </div> </div> ); } } OrganizePreviewRow.propTypes = { id: PropTypes.number.isRequired, existingPath: PropTypes.string.isRequired, newPath: PropTypes.string.isRequired, isSelected: PropTypes.bool, onSelectedChange: PropTypes.func.isRequired }; export default OrganizePreviewRow;
packages/xo-web/src/xo-app/vm-import/index.js
vatesfr/xo-web
import * as FormGrid from 'form-grid' import _ from 'intl' import ActionButton from 'action-button' import Button from 'button' import Component from 'base-component' import Dropzone from 'dropzone' import isEmpty from 'lodash/isEmpty' import map from 'lodash/map' import orderBy from 'lodash/orderBy' import PropTypes from 'prop-types' import React from 'react' import { Container, Col, Row } from 'grid' import { importVms, isSrWritable } from 'xo' import { SizeInput } from 'form' import { createFinder, createGetObject, createGetObjectsOfType, createSelector } from 'selectors' import { connectStore, formatSize, mapPlus, noop } from 'utils' import { SelectNetwork, SelectPool, SelectSr } from 'select-objects' import parseOvaFile from './ova' import styles from './index.css' // =================================================================== const FORMAT_TO_HANDLER = { ova: parseOvaFile, xva: noop, } // =================================================================== @connectStore( () => { const getHostMaster = createGetObject((_, props) => props.pool.master) const getPifs = createGetObjectsOfType('PIF').pick((state, props) => getHostMaster(state, props).$PIFs) const getDefaultNetworkId = createSelector(createFinder(getPifs, [pif => pif.management]), pif => pif.$network) return { defaultNetwork: getDefaultNetworkId, } }, { withRef: true } ) class VmData extends Component { static propTypes = { descriptionLabel: PropTypes.string, disks: PropTypes.objectOf( PropTypes.shape({ capacity: PropTypes.number.isRequired, descriptionLabel: PropTypes.string.isRequired, nameLabel: PropTypes.string.isRequired, path: PropTypes.string.isRequired, compression: PropTypes.string, }) ), memory: PropTypes.number, nameLabel: PropTypes.string, nCpus: PropTypes.number, networks: PropTypes.array, pool: PropTypes.object.isRequired, } get value() { const { props, refs } = this return { descriptionLabel: refs.descriptionLabel.value, disks: map(props.disks, ({ capacity, path, compression, position }, diskId) => ({ capacity, descriptionLabel: refs[`disk-description-${diskId}`].value, nameLabel: refs[`disk-name-${diskId}`].value, path, position, compression, })), memory: +refs.memory.value, nameLabel: refs.nameLabel.value, networks: map(props.networks, (_, networkId) => { const network = refs[`network-${networkId}`].value return network.id ? network.id : network }), nCpus: +refs.nCpus.value, tables: props.tables, } } _getNetworkPredicate = createSelector( () => this.props.pool.id, id => network => network.$pool === id ) render() { const { descriptionLabel, defaultNetwork, disks, memory, nameLabel, nCpus, networks } = this.props return ( <div> <Row> <Col mediumSize={6}> <div className='form-group'> <label>{_('vmNameLabel')}</label> <input className='form-control' ref='nameLabel' defaultValue={nameLabel} type='text' required /> </div> <div className='form-group'> <label>{_('vmNameDescription')}</label> <input className='form-control' ref='descriptionLabel' defaultValue={descriptionLabel} type='text' /> </div> </Col> <Col mediumSize={6}> <div className='form-group'> <label>{_('nCpus')}</label> <input className='form-control' ref='nCpus' defaultValue={nCpus} type='number' required /> </div> <div className='form-group'> <label>{_('vmMemory')}</label> <SizeInput defaultValue={memory} ref='memory' required /> </div> </Col> </Row> <Row> <Col mediumSize={6}> {!isEmpty(disks) ? map(disks, (disk, diskId) => ( <Row key={diskId}> <Col mediumSize={6}> <div className='form-group'> <label> {_('diskInfo', { position: `${disk.position}`, capacity: formatSize(disk.capacity), })} </label> <input className='form-control' ref={`disk-name-${diskId}`} defaultValue={disk.nameLabel} type='text' required /> </div> </Col> <Col mediumSize={6}> <div className='form-group'> <label>{_('diskDescription')}</label> <input className='form-control' ref={`disk-description-${diskId}`} defaultValue={disk.descriptionLabel} type='text' required /> </div> </Col> </Row> )) : _('noDisks')} </Col> <Col mediumSize={6}> {networks.length > 0 ? map(networks, (name, networkId) => ( <div className='form-group' key={networkId}> <label>{_('networkInfo', { name })}</label> <SelectNetwork defaultValue={defaultNetwork} ref={`network-${networkId}`} predicate={this._getNetworkPredicate()} /> </div> )) : _('noNetworks')} </Col> </Row> </div> ) } } // =================================================================== const parseFile = async (file, type, func) => { try { return { data: await func(file), file, type, } } catch (error) { console.error(error) return { error, file, type } } } const getRedirectionUrl = vms => vms.length === 0 ? undefined // no redirect : vms.length === 1 ? `/vms/${vms[0]}` : `/home?s=${encodeURIComponent(`id:|(${vms.join(' ')})`)}&t=VM` export default class Import extends Component { constructor(props) { super(props) this.state.vms = [] } _import = () => { const { state } = this return importVms( mapPlus(state.vms, (vm, push, vmIndex) => { if (!vm.error) { const ref = this.refs[`vm-data-${vmIndex}`] push({ ...vm, data: ref && ref.value, }) } }), state.sr ) } _handleDrop = async files => { this.setState({ vms: [], }) const vms = await Promise.all( mapPlus(files, (file, push) => { const { name } = file const extIndex = name.lastIndexOf('.') let func let type if (extIndex >= 0 && (type = name.slice(extIndex + 1).toLowerCase()) && (func = FORMAT_TO_HANDLER[type])) { push(parseFile(file, type, func)) } }) ) this.setState({ vms: orderBy(vms, vm => [vm.error != null, vm.type, vm.file.name]), }) } _handleCleanSelectedVms = () => { this.setState({ vms: [], }) } _handleSelectedPool = pool => { if (pool === '') { this.setState({ pool: undefined, sr: undefined, srPredicate: undefined, }) } else { this.setState({ pool, sr: pool.default_SR, srPredicate: sr => sr.$pool === this.state.pool.id && isSrWritable(sr), }) } } _handleSelectedSr = sr => { this.setState({ sr: sr === '' ? undefined : sr, }) } render() { const { pool, sr, srPredicate, vms } = this.state return ( <Container> <form id='import-form'> <FormGrid.Row> <FormGrid.LabelCol>{_('vmImportToPool')}</FormGrid.LabelCol> <FormGrid.InputCol> <SelectPool value={pool} onChange={this._handleSelectedPool} required /> </FormGrid.InputCol> </FormGrid.Row> <FormGrid.Row> <FormGrid.LabelCol>{_('vmImportToSr')}</FormGrid.LabelCol> <FormGrid.InputCol> <SelectSr disabled={!pool} onChange={this._handleSelectedSr} predicate={srPredicate} required value={sr} /> </FormGrid.InputCol> </FormGrid.Row> {sr && ( <div> <Dropzone onDrop={this._handleDrop} message={_('importVmsList')} /> <hr /> <h5>{_('vmsToImport')}</h5> {vms.length > 0 ? ( <div> {map(vms, ({ data, error, file, type }, vmIndex) => ( <div key={file.preview} className={styles.vmContainer}> <strong>{file.name}</strong> <span className='pull-right'> <strong>{`(${formatSize(file.size)})`}</strong> </span> {!error ? ( data && ( <div> <hr /> <div className='alert alert-info' role='alert'> <strong>{_('vmImportFileType', { type })}</strong> {_('vmImportConfigAlert')} </div> <VmData {...data} ref={`vm-data-${vmIndex}`} pool={pool} /> </div> ) ) : ( <div> <hr /> <div className='alert alert-danger' role='alert'> <strong>{_('vmImportError')}</strong>{' '} {(error && error.message) || _('noVmImportErrorDescription')} </div> </div> )} </div> ))} </div> ) : ( <p>{_('noSelectedVms')}</p> )} <hr /> <div className='form-group pull-right'> <ActionButton btnStyle='primary' disabled={!vms.length} className='mr-1' form='import-form' handler={this._import} icon='import' redirectOnSuccess={getRedirectionUrl} type='submit' > {_('newImport')} </ActionButton> <Button onClick={this._handleCleanSelectedVms}>{_('importVmsCleanList')}</Button> </div> </div> )} </form> </Container> ) } }
src/components/common/UploadBtn.js
macpie/Gif-Chrome-Extension
import React from 'react'; import IconButton from 'material-ui/IconButton'; import UploadIcon from 'material-ui/svg-icons/file/cloud-upload'; class UploadBtn extends React.Component { render() { return ( <IconButton iconStyle={{color: "rgb(255, 64, 129)"}} tooltipPosition="bottom-center" tooltip="Upload to Giphy" children={<UploadIcon />} onClick={this.props.onClick} /> ); } }; export default UploadBtn;
app/containers/SignUp/SignUpForm.js
danielmoraes/invoices-web-client
import React from 'react' import { Form } from 'components' import { User } from 'api/entity-schema' const formLayout = [ [ 'name' ], [ 'email' ], [ 'password' ], [ 'confirmPassword' ] ] const formOptions = { focus: 'name', hideLabels: true, fieldOptions: { name: {}, email: {}, password: { inputType: 'password' }, confirmPassword: { label: 'Confirm Password', inputType: 'password' } } } // inject schema to field options Object.keys(formOptions.fieldOptions).forEach((field) => { formOptions.fieldOptions[field].schema = User[field] }) const SignUpForm = (props) => ( <Form layout={formLayout} options={formOptions} {...props} /> ) export default SignUpForm
src/layouts/index.js
omahajs/omahajs.github.io
import React from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import './index.css'; const Layout = ({children, data}) => ( <div> <Helmet title={data.site.siteMetadata.title} meta={[ {name: 'description', content: 'Sample'}, {name: 'keywords', content: 'sample, something'} ]} /> <div> {children()} </div> </div> ); Layout.propTypes = { children: PropTypes.func, data: PropTypes.object }; export default Layout; export const query = graphql` query SiteTitleQuery { site { siteMetadata { title } } } `;
src/icons/NaturePeopleIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class NaturePeopleIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M44.34 18.34c0-7.73-6.27-14-14-14s-14 6.27-14 14c0 6.93 5.04 12.67 11.66 13.79V40H12v-6h2v-8c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v8h2v10h32v-4h-6v-7.76c6.95-.82 12.34-6.73 12.34-13.9zM9 22c1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3 1.34 3 3 3z"/></svg>;} };
js/react/codemirror.js
nCoda/julius
// -*- coding: utf-8 -*- // ------------------------------------------------------------------------------------------------ // Program Name: Julius // Program Description: User interface for the nCoda music notation editor. // // Filename: js/react/codemirror.js // Purpose: React wrapper for the CodeMirror text editor widget. // // Copyright (C) 2016 Christopher Antila // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // ------------------------------------------------------------------------------------------------ // // This React component is inspired by Jed Watson's MIT-licensed "react-codemirror," which is // available on GitHub: https://github.com/JedWatson/react-codemirror/ // import React from 'react'; import CodeMirror from 'codemirror'; // TODO: figure out how to do this without cheating like this import '../../node_modules/codemirror/mode/python/python.js'; // import diff_match_patch from 'diff-match-patch'; // TODO: make this import here properly, instead of index.html import '../../node_modules/codemirror/addon/merge/merge.js'; // IMPORTANT: This component is not being used for CodeScoreView, but is still being used for RevisionsView /** CodeMirrorReactWrapper: React wrapper for the CodeMirror text editor widget. * * React Props: * ------------ * @param {str} className - The "class" attribute for the <div> that will contain CodeMirror. * @param {func} onChange - When the CodeMirror text is changed, this function is called with * the text editor's new value. * * CodeMirror Props: * ------------ * @param {bool} autoFocus - Whether to focus CodeMirror after it's initialized (defaults to false). * @param {bool} electricChars - Something fancy with the indentation (defaults to true). * @param {int} indentUnit - Indent by this many tabs/spaces (defaults to 4). * @param {bool} indentWithTabs - Indent by indentUnit tabs instead of indentUnit spaces (defaults to false). * @param {bool} lineNumbers - Whether to show line numbers (defaults to true). * @param {bool} lineWrapping - Whether to use wraparound for long lines of text (defaults to false). * @param {str} mode - Text editor's highlighting/folding mode (defaults to "python"). * @param {bool} smartIndent - I guess this avoids stupid indentation? (defaults to true). * @param {str} text - The initial text to show in the editor. * @param {str} theme - The text editor's visual theme (defaults to "codemirror-ncoda light"). * * DiffView Props: * --------------- * @param {str} connect - Either "align" or an unknown value, dictating how to align the texts. * @param {bool} diff - When true, use the "MergeView" plugin to display a textual diff between * two text passages. Defaults to false. Provide the texts to "leftText" and "rightText." * @param {str} leftText - The text to show on the left side of a diff. * @param {str} rightText - The text to show on the right side of a diff. * * State: * ------ * @param {object} codemirror - The CodeMirror instance rendered inside this component. * */ const CodeMirrorReactWrapper = React.createClass({ propTypes: { // React props className: React.PropTypes.string, onChange: React.PropTypes.func, // CodeMirror props autofocus: React.PropTypes.bool, electricChars: React.PropTypes.bool, indentUnit: React.PropTypes.number, indentWithTabs: React.PropTypes.bool, lineNumbers: React.PropTypes.bool, lineWrapping: React.PropTypes.bool, mode: React.PropTypes.string, smartIndent: React.PropTypes.bool, text: React.PropTypes.string, // becomes "value" for CodeMirror theme: React.PropTypes.string, // DiffView props connect: React.PropTypes.string, diff: React.PropTypes.bool, leftText: React.PropTypes.string, // becomes "origLeft" for CodeMirror rightText: React.PropTypes.string, // becomes "value" for CodeMirror }, getDefaultProps() { return { // React props className: '', // CodeMirror props autofocus: false, electricChars: true, indentUnit: 4, indentWithTabs: false, lineNumbers: true, lineWrapping: false, mode: 'python', smartIndent: true, text: '', theme: 'codemirror-ncoda light', // DiffView props connect: 'align', diff: false, leftText: '', rightText: '', }; }, getInitialState() { return {codemirror: null}; }, /** Format a set of "props" so they can be given to CodeMirror as "options." */ propsToOptions(props) { const options = { // CodeMirror props autofocus: props.autofocus, electricChars: props.electricChars, indentUnit: props.indentUnit, indentWithTabs: props.indentWithTabs, lineNumbers: props.lineNumbers, lineWrapping: props.lineWrapping, mode: props.mode, smartIndent: props.smartIndent, value: props.text, theme: props.theme, }; if (this.props.diff) { // DiffView props options.connect = props.connect; origLeft = props.leftText; value = props.rightText; } // set hardwired options options['revertButtons'] = false; // for DiffView/MergeView options['readOnly'] = this.props.diff; // no editing in DiffView options['scrollbarStyle'] = 'native'; options['inputStyle'] = 'contenteditable'; return options; }, componentDidMount() { let codemirror; let editor; const options = this.propsToOptions(this.props); // initialize the text editor; different for DiffView and regular text editor if (this.props.diff) { codemirror = CodeMirror.MergeView(this.refs.codemirror, options); editor = codemirror.edit; } else { codemirror = CodeMirror(this.refs.codemirror, options); editor = codemirror; } // connect an "onChange"-like callback if requested if (this.props.onChange) { editor.on('change', this.onChange); // call the "props" function indirectly } this.setState({codemirror: editor}); }, componentWillReceiveProps(nextProps) { // As much as possible, we want to allow props to take effect in render(). Unfortunately, // it's not possible for much! if (nextProps !== this.props) { // 1.) onChange // TODO // 2.) diff // TODO: allow changing "this.props.diff" if (nextProps.diff !== this.props.diff) { console.error("You can't change the 'diff' of the CodeMirror component; ignoring"); } // 3.) options if (this.state.codemirror) { // idk why CodeMirror wouldn't be rendered yet, but now we know for sure const options = this.propsToOptions(nextProps); for (const key in options) { // only update if it's different if (options[key] !== this.state.codemirror.options[key]) { if (key === 'origLeft') { // simply setting "origLeft" again doesn't work this.state.codemirror.state.diffViews[0].orig.setOption('value', options[key]); } else if (key === 'value') { // TODO: temporary for T50? // NOTE: aside from T50, we shouldn't be receiving a new "value"... ? // ... if we are, it moves the cursor, so that's not good for typing if (this.state.codemirror.getOption(key) === '') { this.state.codemirror.setOption(key, options[key]); } } else { this.state.codemirror.setOption(key, options[key]); } } } } } }, shouldComponentUpdate(nextProps) { if (nextProps.className !== this.props.className) { return true; } return false; }, componentWillUnmount() { delete this.state.codemirror; }, onChange(doc) { if (this.props.onChange) { this.props.onChange(doc.getValue()); } }, render() { return <div className={this.props.className} ref="codemirror"/>; }, }); export {CodeMirrorReactWrapper as CodeMirror}; export default CodeMirrorReactWrapper;
lib/PaneHeaderIconButton/PaneHeaderIconButton.js
folio-org/stripes-components
/** * PaneHeaderIconButton */ import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import IconButton from '../IconButton'; import css from './PaneHeaderIconButton.css'; import paneHeaderCss from '../PaneHeader/PaneHeader.css'; const PaneHeaderIconButton = React.forwardRef(({ className, innerClassName, ...rest }, ref) => ( <IconButton ref={ref} className={classnames(className, css.PaneHeaderIconButton, paneHeaderCss.paneHeaderIconButton)} innerClassName={classnames(css.PaneHeaderIconButton__inner, innerClassName)} {...rest} /> )); PaneHeaderIconButton.propTypes = { className: PropTypes.string, innerClassName: PropTypes.string, }; export default PaneHeaderIconButton;
nCoda-win32-x64/resources/app/js/react/pdf_viewer.js
nCoda/Windows
// -*- coding: utf-8 -*- // ------------------------------------------------------------------------------------------------ // Program Name: Julius // Program Description: User interface for the nCoda music notation editor. // // Filename: js/react/pdf_viewer.js // Purpose: React wrapper for PDF display with PDF.js. // // Copyright (C) 2016, 2017 Sienna M. Wood // // The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // ------------------------------------------------------------------------------------------------ // // This React component is inspired by javascriptiscoolpl's MIT-licensed "npm-simple-react-pdf," // which is available on GitHub: https://github.com/javascriptiscoolpl/npm-simple-react-pdf // import React from 'react'; import PDFJS from 'pdfjs-dist'; import { ButtonGroup, Button } from 'amazeui-react'; export default class PDFViewer extends React.Component { constructor(props) { super(props); this.downloadPDF = this.downloadPDF.bind(this); this.refresh = this.refresh.bind(this); this.loadPDF = this.loadPDF.bind(this); } componentWillMount() { window.PDFJS.workerSrc = this.props.workerSrc; } componentDidMount() { this.loadPDF(); } shouldComponentUpdate(nextProps) { return this.props.file !== nextProps.file; } componentDidUpdate() { this.loadPDF(); } downloadPDF() { let uri = ''; if (this.props.file.startsWith('http')) { // if an absolute URL, no changes needed uri = this.props.file; } else { // prefix with base uri if needed uri = document.baseURI; uri = uri.slice(0, uri.lastIndexOf('.')); // slice off '.html#/...' uri = uri.slice(0, uri.lastIndexOf('/') + 1); // slice off anything after final / uri = `${uri}${this.props.file}`; } const tempLink = document.createElement('a'); tempLink.href = uri; tempLink.setAttribute('download', 'ncoda-pdf.pdf'); tempLink.click(); } refresh() { this.forceUpdate(); // console.log("PDF display reloaded."); } loadPDF() { const node = this.node.getElementsByClassName(this.props.pdfContainerClass)[0]; node.innerHTML = 'PDF loading...'; PDFJS.getDocument(this.props.file) .then((pdf) => { node.innerHTML = ''; let id = 1; for (let i = 1; i <= pdf.numPages; i += 1) { pdf.getPage(i).then((page) => { const canvas = document.createElement('canvas'); canvas.id = `page-${id}`; id += 1; const scale = 3; // for greater resolution, actual display size controlled by styles const viewport = page.getViewport(scale); canvas.width = viewport.width; canvas.height = viewport.height; node.appendChild(canvas); const canvasContext = canvas.getContext('2d'); const renderContext = { canvasContext, viewport }; page.render(renderContext); }); } }) .catch((error) => { // console.error('PDF could not be displayed.', error); node.innerHTML = 'Sorry, there was an error and the PDF could not be displayed.'; }); } render() { let classes = this.props.pdfContainerClass; if (classes !== 'nc-pdf') { classes = `${classes} nc-pdf`; } return ( <div className="nc-pdfviewer" ref={node => this.node = node}> <div className="nc-pdfviewer-toolbar nc-toolbar"> <ButtonGroup className="nc-pdfviewer-btns"> <Button amSize="sm" amStyle="link" title="Download PDF" className="nc-pdf-download-btn" onClick={() => this.downloadPDF()} > <i className="am-icon-download" /> Download PDF </Button> <Button amSize="sm" amStyle="link" title="Refresh PDF" className="nc-pdf-refresh-btn" onClick={() => this.refresh()} > <i className="am-icon-refresh" /> Refresh PDF </Button> </ButtonGroup> </div> <div className="nc-content-wrap"> <div className={classes} /> </div> </div> ); } } PDFViewer.propTypes = { file: React.PropTypes.string.isRequired, pdfContainerClass: React.PropTypes.string, workerSrc: React.PropTypes.string.isRequired, }; PDFViewer.defaultProps = { pdfContainerClass: 'nc-pdf', workerSrc: './js/lib/pdf.worker.js', };
fields/types/geopoint/GeoPointField.js
matthewstyers/keystone
import Field from '../Field'; import React from 'react'; import { FormInput, Grid, } from '../../../admin/client/App/elemental'; module.exports = Field.create({ displayName: 'GeopointField', statics: { type: 'Geopoint', }, focusTargetRef: 'lat', handleLat (event) { const { value = [], path, onChange } = this.props; const newVal = event.target.value; onChange({ path, value: [value[0], newVal], }); }, handleLong (event) { const { value = [], path, onChange } = this.props; const newVal = event.target.value; onChange({ path, value: [newVal, value[1]], }); }, renderValue () { const { value } = this.props; if (value && value[1] && value[0]) { return <FormInput noedit>{value[1]}, {value[0]}</FormInput>; // eslint-disable-line comma-spacing } return <FormInput noedit>(not set)</FormInput>; }, renderField () { const { value = [], path } = this.props; return ( <Grid.Row xsmall="one-half" gutter={10}> <Grid.Col> <FormInput autoComplete="off" name={this.getInputName(path + '[1]')} onChange={this.handleLat} placeholder="Latitude" ref="lat" value={value[1]} /> </Grid.Col> <Grid.Col width="one-half"> <FormInput autoComplete="off" name={this.getInputName(path + '[0]')} onChange={this.handleLong} placeholder="Longitude" ref="lng" value={value[0]} /> </Grid.Col> </Grid.Row> ); }, });
dist/components/page8.js
LongStoryMedia/Compass
import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; const Page8 = () => { return ( <div> <h1>Page 8</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque ultricies, metus a euismod dictum, ex ligula congue arcu, non rutrum dolor sem mattis ligula. In quis quam ut libero sollicitudin tempus. Phasellus quis leo tempus, tempus quam quis, fringilla libero. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum vitae magna eu lectus pharetra ultricies sit amet quis sem. Donec sed efficitur massa. Duis sit amet commodo nibh, eget porta risus. Integer a mi ligula. </p> <p> Donec venenatis, ante vel gravida eleifend, nisl magna lobortis massa, nec cursus tortor sapien nec neque. Nulla ac nunc sit amet justo pharetra dictum. Curabitur faucibus nec turpis et elementum. Vestibulum congue ligula ut odio dictum elementum. Ut feugiat congue turpis. Etiam consequat lectus eu est iaculis, eget tristique justo aliquam. Proin sit amet vehicula nulla. Integer et eleifend nulla, non scelerisque felis. </p> <p> Duis faucibus turpis sit amet purus malesuada pulvinar. Sed vitae auctor ante. Curabitur nunc nisl, efficitur nec metus ac, condimentum luctus mi. Donec sit amet sapien sit amet lorem sagittis faucibus. Pellentesque vulputate mi eget nulla rhoncus, at tincidunt nisl tincidunt. Ut in quam ac nibh gravida eleifend non vel ex. Sed quis enim quis massa commodo tristique. </p> <p> Phasellus vehicula ex nulla, non sodales arcu vulputate viverra. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla enim lectus, semper a tellus ac, ultricies varius odio. Etiam dictum lorem diam, sed accumsan mauris fringilla quis. Proin in lectus tristique, fringilla elit et, lobortis purus. Phasellus efficitur mauris ante. Aliquam luctus aliquet sem vitae maximus. Aliquam in lorem pharetra, eleifend nunc non, porta mauris. Donec sit amet tellus lacinia, elementum erat ut, dapibus ipsum. Duis ut urna ex. </p> <p> Morbi consequat quis ligula at consectetur. Nulla facilisi. Etiam maximus orci id cursus venenatis. Vestibulum suscipit mauris a est congue, malesuada imperdiet augue faucibus. Vestibulum sagittis nisl et erat aliquam, non porta mauris eleifend. Morbi elementum mollis dui a condimentum. Nam semper mauris nulla, a varius tellus scelerisque quis. Nunc libero arcu, lobortis id ante ut, efficitur iaculis neque. Nunc egestas pulvinar libero, et aliquam nisl ornare quis. Proin iaculis in elit ac posuere. </p> </div> ) } export default Page8;
examples/huge-apps/components/Dashboard.js
Dodelkin/react-router
import React from 'react' import { Link } from 'react-router' class Dashboard extends React.Component { render() { const { courses } = this.props return ( <div> <h2>Super Scalable Apps</h2> <p> Open the network tab as you navigate. Notice that only the amount of your app that is required is actually downloaded as you navigate around. Even the route configuration objects are loaded on the fly. This way, a new route added deep in your app will not affect the initial bundle of your application. </p> <h2>Courses</h2>{' '} <ul> {courses.map(course => ( <li key={course.id}> <Link to={`/course/${course.id}`}>{course.name}</Link> </li> ))} </ul> </div> ) } } export default Dashboard
docs/app/Examples/collections/Message/Variations/MessageCompactExample.js
jcarbo/stardust
import React from 'react' import { Message } from 'stardust' const MessageCompactExample = () => ( <Message compact> Get all the best inventions in your e-mail every day. Sign up now! </Message> ) export default MessageCompactExample
docs/src/app/components/pages/components/Stepper/GranularControlStepper.js
hai-cea/material-ui
import React from 'react'; import { Step, Stepper, StepButton, } from 'material-ui/Stepper'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; const getStyles = () => { return { root: { width: '100%', maxWidth: 700, margin: 'auto', }, content: { margin: '0 16px', }, actions: { marginTop: 12, }, backButton: { marginRight: 12, }, }; }; /** * This is similar to the horizontal non-linear example, except the * `<Step>` components are being controlled manually via individual props. * * An enhancement made possible by this functionality (shown below), * is to permanently mark steps as complete once the user has satisfied the * application's required conditions (in this case, once it has visited the step). * */ class GranularControlStepper extends React.Component { state = { stepIndex: null, visited: [], }; componentWillMount() { const {stepIndex, visited} = this.state; this.setState({visited: visited.concat(stepIndex)}); } componentWillUpdate(nextProps, nextState) { const {stepIndex, visited} = nextState; if (visited.indexOf(stepIndex) === -1) { this.setState({visited: visited.concat(stepIndex)}); } } handleNext = () => { const {stepIndex} = this.state; if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } }; handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } }; getStepContent(stepIndex) { switch (stepIndex) { case 0: return 'Select campaign settings...'; case 1: return 'What is an ad group anyways?'; case 2: return 'This is the bit I really care about!'; default: return 'Click a step to get started.'; } } render() { const {stepIndex, visited} = this.state; const styles = getStyles(); return ( <div style={styles.root}> <p> <a href="#" onClick={(event) => { event.preventDefault(); this.setState({stepIndex: null, visited: []}); }} > Click here </a> to reset the example. </p> <Stepper linear={false}> <Step completed={visited.indexOf(0) !== -1} active={stepIndex === 0}> <StepButton onClick={() => this.setState({stepIndex: 0})}> Select campaign settings </StepButton> </Step> <Step completed={visited.indexOf(1) !== -1} active={stepIndex === 1}> <StepButton onClick={() => this.setState({stepIndex: 1})}> Create an ad group </StepButton> </Step> <Step completed={visited.indexOf(2) !== -1} active={stepIndex === 2}> <StepButton onClick={() => this.setState({stepIndex: 2})}> Create an ad </StepButton> </Step> </Stepper> <div style={styles.content}> <p>{this.getStepContent(stepIndex)}</p> {stepIndex !== null && ( <div style={styles.actions}> <FlatButton label="Back" disabled={stepIndex === 0} onClick={this.handlePrev} style={styles.backButton} /> <RaisedButton label="Next" primary={true} onClick={this.handleNext} /> </div> )} </div> </div> ); } } export default GranularControlStepper;
src/components/callout.js
nordsoftware/react-foundation
import React from 'react'; import PropTypes from 'prop-types'; import { CalloutColors, CalloutSizes } from '../enums'; import { GeneralPropTypes, FlexboxPropTypes, createClassName, generalClassNames, removeProps, objectKeys, objectValues } from '../utils'; /** * Callout component. * http://foundation.zurb.com/sites/docs/callout.html * * @param {Object} props * @returns {Object} */ export const Callout = props => { const className = createClassName( props.noDefaultClassName ? null : 'callout', props.className, props.color, props.size, generalClassNames(props) ); const passProps = removeProps(props, objectKeys(Callout.propTypes)); return <div {...passProps} className={className}/>; }; Callout.propTypes = { ...GeneralPropTypes, ...FlexboxPropTypes, color: PropTypes.oneOf(objectValues(CalloutColors)), size: PropTypes.oneOf(objectValues(CalloutSizes)) };
app/addons/documents/routes-index-editor.js
apache/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the 'License'); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import React from 'react'; import FauxtonAPI from "../../core/api"; import BaseRoute from "./shared-routes"; import ActionsIndexEditor from "./index-editor/actions"; import DatabaseActions from '../databases/actions'; import Databases from "../databases/base"; import SidebarActions from './sidebar/actions'; import {SidebarItemSelection} from './sidebar/helpers'; import {DocsTabsSidebarLayout, ViewsTabsSidebarLayout} from './layouts'; const IndexEditorAndResults = BaseRoute.extend({ routes: { 'database/:database/_partition/:partitionkey/new_view': { route: 'createView', roles: ['fx_loggedIn'] }, 'database/:database/_partition/:partitionkey/new_view/:designDoc': { route: 'createView', roles: ['fx_loggedIn'] }, 'database/:database/new_view': { route: 'createViewNoPartition', roles: ['fx_loggedIn'] }, 'database/:database/new_view/:designDoc': { route: 'createViewNoPartition', roles: ['fx_loggedIn'] }, 'database/:database/_partition/:partitionkey/_design/:ddoc/_view/:view': { route: 'showPartitionedView', roles: ['fx_loggedIn'] }, 'database/:database/_design/:ddoc/_view/:view': { route: 'showGlobalView', roles: ['fx_loggedIn'] }, 'database/:database/_partition/:partitionkey/_design/:ddoc/_view/:view/edit': { route: 'editView', roles: ['fx_loggedIn'] }, 'database/:database/_design/:ddoc/_view/:view/edit': { route: 'editViewNoPartition', roles: ['fx_loggedIn'] } }, initialize (route, options) { var databaseName = options[0]; this.databaseName = databaseName; this.database = new Databases.Model({id: databaseName}); this.createDesignDocsCollection(); this.addSidebar(); }, showGlobalView: function (databaseName, ddoc, viewName) { return this.showView(databaseName, '', ddoc, viewName); }, showPartitionedView: function (databaseName, partitionKey, ddoc, viewName) { return this.showView(databaseName, partitionKey, ddoc, viewName); }, showView: function (databaseName, partitionKey, ddoc, viewName) { viewName = viewName.replace(/\?.*$/, ''); ActionsIndexEditor.dispatchClearIndex(); ActionsIndexEditor.dispatchFetchDesignDocsBeforeEdit({ viewName: viewName, isNewView: false, database: this.database, designDocs: this.designDocs, designDocId: '_design/' + ddoc }); DatabaseActions.fetchSelectedDatabaseInfo(databaseName); const selectedNavItem = new SidebarItemSelection('designDoc', { designDocName: ddoc, designDocSection: 'Views', indexName: viewName }); SidebarActions.dispatchExpandSelectedItem(selectedNavItem); const encodedPartKey = partitionKey ? encodeURIComponent(partitionKey) : ''; const url = FauxtonAPI.urls('view', 'server', encodeURIComponent(databaseName), encodedPartKey, encodeURIComponent(ddoc), encodeURIComponent(viewName)); const endpoint = FauxtonAPI.urls('view', 'apiurl', encodeURIComponent(databaseName), encodedPartKey, encodeURIComponent(ddoc), encodeURIComponent(viewName)); const docURL = FauxtonAPI.constants.DOC_URLS.GENERAL; const navigateToPartitionedView = (partKey) => { const baseUrl = FauxtonAPI.urls('partitioned_view', 'app', encodeURIComponent(databaseName), encodeURIComponent(partKey), encodeURIComponent(ddoc)); FauxtonAPI.navigate('#/' + baseUrl + encodeURIComponent(viewName)); }; const navigateToGlobalView = () => { const baseUrl = FauxtonAPI.urls('view', 'app', encodeURIComponent(databaseName), encodeURIComponent(ddoc)); FauxtonAPI.navigate('#/' + baseUrl + encodeURIComponent(viewName)); }; const dropDownLinks = this.getCrumbs(this.database); return <DocsTabsSidebarLayout docURL={docURL} endpoint={endpoint} dbName={this.database.id} dropDownLinks={dropDownLinks} database={this.database} fetchUrl={url} ddocsOnly={false} deleteEnabled={false} selectedNavItem={selectedNavItem} partitionKey={partitionKey} onPartitionKeySelected={navigateToPartitionedView} onGlobalModeSelected={navigateToGlobalView} globalMode={partitionKey === ''} />; }, createViewNoPartition: function (databaseName, _designDoc) { return this.createView(databaseName, '', _designDoc); }, createView: function (database, partitionKey, _designDoc) { let isNewDesignDoc = true; let designDoc = 'new-doc'; if (_designDoc) { designDoc = '_design/' + _designDoc; isNewDesignDoc = false; } ActionsIndexEditor.dispatchFetchDesignDocsBeforeEdit({ viewName: 'new-view', isNewView: true, database: this.database, designDocs: this.designDocs, designDocId: designDoc, isNewDesignDoc: isNewDesignDoc }); DatabaseActions.fetchSelectedDatabaseInfo(database); const selectedNavItem = new SidebarItemSelection(''); const dropDownLinks = this.getCrumbs(this.database); return <ViewsTabsSidebarLayout showIncludeAllDocs={true} docURL={FauxtonAPI.constants.DOC_URLS.GENERAL} dbName={this.database.id} dropDownLinks={dropDownLinks} database={this.database} selectedNavItem={selectedNavItem} partitionKey={partitionKey} />; }, editViewNoPartition: function (databaseName, ddocName, viewName) { return this.editView(databaseName, '', ddocName, viewName); }, editView: function (databaseName, partitionKey, ddocName, viewName) { ActionsIndexEditor.dispatchFetchDesignDocsBeforeEdit({ viewName: viewName, isNewView: false, database: this.database, designDocs: this.designDocs, designDocId: '_design/' + ddocName }); DatabaseActions.fetchSelectedDatabaseInfo(databaseName); const selectedNavItem = new SidebarItemSelection('designDoc', { designDocName: ddocName, designDocSection: 'Views', indexName: viewName }); SidebarActions.dispatchExpandSelectedItem(selectedNavItem); const docURL = FauxtonAPI.constants.DOC_URLS.GENERAL; const endpoint = FauxtonAPI.urls('view', 'apiurl', databaseName, ddocName, viewName); const dropDownLinks = this.getCrumbs(this.database); return <ViewsTabsSidebarLayout showIncludeAllDocs={true} docURL={docURL} endpoint={endpoint} dbName={this.database.id} dropDownLinks={dropDownLinks} database={this.database} selectedNavItem={selectedNavItem} partitionKey={partitionKey} />; } }); export default IndexEditorAndResults;
packages/react/src/components/ToggleSmall/ToggleSmall.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import { settings } from 'carbon-components'; import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { keys, match } from '../../internal/keyboard'; import { warning } from '../../internal/warning'; const { prefix } = settings; let didWarnAboutDeprecation = false; const ToggleSmall = ({ className, defaultToggled, toggled, onChange, onToggle, id, labelText, labelA, labelB, ...other }) => { if (__DEV__) { warning( didWarnAboutDeprecation, '`<ToggleSmall>` has been deprecated in favor of `<Toggle size="sm" />` and will be removed in the next major release of `carbon-components-react`' ); didWarnAboutDeprecation = true; } let input; const wrapperClasses = classNames(`${prefix}--form-item`, { [className]: className, }); const checkedProps = {}; if (typeof toggled !== 'undefined') { checkedProps.checked = toggled; } else { checkedProps.defaultChecked = defaultToggled; } const ariaLabel = (typeof labelText === 'string' && labelText) || other['aria-label'] || other.ariaLabel || null; return ( <div className={wrapperClasses}> <input {...other} {...checkedProps} aria-label={null} type="checkbox" id={id} className={`${prefix}--toggle-input ${prefix}--toggle-input--small`} onChange={(evt) => { onChange && onChange(evt); onToggle(input.checked, id, evt); }} ref={(el) => { input = el; }} onKeyUp={(evt) => { if (match(evt, keys.Enter)) { input.checked = !input.checked; onChange && onChange(evt); onToggle(input.checked, id, evt); } }} /> <label className={`${prefix}--toggle-input__label`} htmlFor={id} aria-label={ariaLabel}> {labelText} <span className={`${prefix}--toggle__switch`}> <svg className={`${prefix}--toggle__check`} width="6px" height="5px" viewBox="0 0 6 5"> <path d="M2.2 2.7L5 0 6 1 2.2 5 0 2.7 1 1.5z" /> </svg> <span className={`${prefix}--toggle__text--off`} aria-hidden="true"> {labelA} </span> <span className={`${prefix}--toggle__text--on`} aria-hidden="true"> {labelB} </span> </span> </label> </div> ); }; ToggleSmall.propTypes = { ['aria-label']: PropTypes.string.isRequired, /** * The CSS class for the toggle */ className: PropTypes.string, /** * `true` to make it toggled on by default. */ defaultToggled: PropTypes.bool, /** * The `id` attribute for the toggle */ id: PropTypes.string.isRequired, /** * Specify the label for the "off" position */ labelA: PropTypes.node.isRequired, /** * Specify the label for the "on" position */ labelB: PropTypes.node.isRequired, /** * The `aria-label` attribute for the toggle */ labelText: PropTypes.node, /** * Provide an optional hook that is called when the control is changed */ onChange: PropTypes.func, /** * The event handler for the `onChange` event. */ onToggle: PropTypes.func, /** * `true` to make it toggled on */ toggled: PropTypes.bool, }; ToggleSmall.defaultProps = { defaultToggled: false, onToggle: () => {}, labelA: 'Off', labelB: 'On', }; export default ToggleSmall;
docs/app/Examples/elements/Input/Types/InputExampleInput.js
ben174/Semantic-UI-React
import React from 'react' import { Input } from 'semantic-ui-react' const InputExampleInput = () => ( <Input placeholder='Search...' /> ) export default InputExampleInput
src/parser/rogue/assassination/modules/talents/Subterfuge.js
fyruna/WoWAnalyzer
import React from 'react'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import GarroteSnapshot from '../features/GarroteSnapshot'; import StealthCasts from './StealthCasts'; class Subterfuge extends StealthCasts { static dependencies = { garroteSnapshot: GarroteSnapshot, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.SUBTERFUGE_TALENT.id); } get bonusDamage() { return this.garroteSnapshot.bonusDamage; } get stealthsWithAtleastOneGarrote() { let stealthsWithGarrote = 0; this.stealthSequences.forEach(sequence => { const firstGarroteCast = sequence.find(e => e.ability.guid === SPELLS.GARROTE.id); if (firstGarroteCast) { stealthsWithGarrote += 1; } }); return stealthsWithGarrote; } get stealthCasts() { return this.stealthSequences.length; } get percentGoodStealthCasts() { return (this.stealthsWithAtleastOneGarrote / this.stealthCasts) || 0; } get suggestionThresholds() { return { actual: this.percentGoodStealthCasts, isLessThan: { minor: 0.95, average: 0.9, major: 0.8, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest(<>Your failed to cast atleast one <SpellLink id={SPELLS.GARROTE.id} /> during <SpellLink id={SPELLS.SUBTERFUGE_BUFF.id} /> {this.stealthCasts - this.stealthsWithAtleastOneGarrote} time(s). Make sure to prioritize snapshotting <SpellLink id={SPELLS.GARROTE.id} /> during <SpellLink id={SPELLS.SUBTERFUGE_BUFF.id} />.</>) .icon(SPELLS.GARROTE.icon) .actual(`${formatPercentage(actual)}% of Subterfuges with atleast one Garrote cast`) .recommended(`>${formatPercentage(recommended)}% is recommended`); }); } statistic() { return ( <TalentStatisticBox talent={SPELLS.SUBTERFUGE_TALENT.id} position={STATISTIC_ORDER.OPTIONAL(2)} value={<ItemDamageDone amount={this.bonusDamage} />} tooltip={`You casted atleast one Garrote during Subterfuge ${this.stealthsWithAtleastOneGarrote} times out of ${this.stealthCasts}.`} /> ); } } export default Subterfuge;
fields/types/password/PasswordColumn.js
geminiyellow/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/src/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/src/components/ItemsTableValue'; var PasswordColumn = React.createClass({ displayName: 'PasswordColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { let value = this.props.data.fields[this.props.col.path]; return value ? '********' : ''; }, render () { return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); } }); module.exports = PasswordColumn;
packages/material-ui-icons/src/ClearAll.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let ClearAll = props => <SvgIcon {...props}> <path d="M5 13h14v-2H5v2zm-2 4h14v-2H3v2zM7 7v2h14V7H7z" /> </SvgIcon>; ClearAll = pure(ClearAll); ClearAll.muiName = 'SvgIcon'; export default ClearAll;
Libraries/Components/Button.js
hoangpham95/react-native
/** * 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. * * @format * @flow * @generate-docs */ 'use strict'; const Platform = require('../Utilities/Platform'); const React = require('react'); const StyleSheet = require('../StyleSheet/StyleSheet'); const Text = require('../Text/Text'); const TouchableNativeFeedback = require('./Touchable/TouchableNativeFeedback'); const TouchableOpacity = require('./Touchable/TouchableOpacity'); const View = require('./View/View'); const invariant = require('invariant'); import type {PressEvent} from '../Types/CoreEventTypes'; import type {ColorValue} from '../StyleSheet/StyleSheet'; type ButtonProps = $ReadOnly<{| /** Text to display inside the button. On Android the given title will be converted to the uppercased form. */ title: string, /** Handler to be called when the user taps the button. The first function argument is an event in form of [PressEvent](pressevent). */ onPress: (event?: PressEvent) => mixed, /** If `true`, doesn't play system sound on touch. @platform android @default false */ touchSoundDisabled?: ?boolean, /** Color of the text (iOS), or background color of the button (Android). @default {@platform android} '#2196F3' @default {@platform ios} '#007AFF' */ color?: ?ColorValue, /** TV preferred focus. @platform tv @default false */ hasTVPreferredFocus?: ?boolean, /** Designates the next view to receive focus when the user navigates down. See the [Android documentation][android:nextFocusDown]. [android:nextFocusDown]: https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusDown @platform android, tv */ nextFocusDown?: ?number, /** Designates the next view to receive focus when the user navigates forward. See the [Android documentation][android:nextFocusForward]. [android:nextFocusForward]: https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusForward @platform android, tv */ nextFocusForward?: ?number, /** Designates the next view to receive focus when the user navigates left. See the [Android documentation][android:nextFocusLeft]. [android:nextFocusLeft]: https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusLeft @platform android, tv */ nextFocusLeft?: ?number, /** Designates the next view to receive focus when the user navigates right. See the [Android documentation][android:nextFocusRight]. [android:nextFocusRight]: https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusRight @platform android, tv */ nextFocusRight?: ?number, /** Designates the next view to receive focus when the user navigates up. See the [Android documentation][android:nextFocusUp]. [android:nextFocusUp]: https://developer.android.com/reference/android/view/View.html#attr_android:nextFocusUp @platform android, tv */ nextFocusUp?: ?number, /** Text to display for blindness accessibility features. */ accessibilityLabel?: ?string, /** If `true`, disable all interactions for this component. @default false */ disabled?: ?boolean, /** Used to locate this view in end-to-end tests. */ testID?: ?string, |}>; /** A basic button component that should render nicely on any platform. Supports a minimal level of customization. If this button doesn't look right for your app, you can build your own button using [TouchableOpacity](touchableopacity) or [TouchableWithoutFeedback](touchablewithoutfeedback). For inspiration, look at the [source code for this button component][button:source]. Or, take a look at the [wide variety of button components built by the community] [button:examples]. [button:source]: https://github.com/facebook/react-native/blob/master/Libraries/Components/Button.js [button:examples]: https://js.coach/?menu%5Bcollections%5D=React%20Native&page=1&query=button ```jsx <Button onPress={onPressLearnMore} title="Learn More" color="#841584" accessibilityLabel="Learn more about this purple button" /> ``` ```SnackPlayer name=Button%20Example import React from 'react'; import { StyleSheet, Button, View, SafeAreaView, Text, Alert } from 'react-native'; const Separator = () => ( <View style={styles.separator} /> ); const App = () => ( <SafeAreaView style={styles.container}> <View> <Text style={styles.title}> The title and onPress handler are required. It is recommended to set accessibilityLabel to help make your app usable by everyone. </Text> <Button title="Press me" onPress={() => Alert.alert('Simple Button pressed')} /> </View> <Separator /> <View> <Text style={styles.title}> Adjust the color in a way that looks standard on each platform. On iOS, the color prop controls the color of the text. On Android, the color adjusts the background color of the button. </Text> <Button title="Press me" color="#f194ff" onPress={() => Alert.alert('Button with adjusted color pressed')} /> </View> <Separator /> <View> <Text style={styles.title}> All interaction for the component are disabled. </Text> <Button title="Press me" disabled onPress={() => Alert.alert('Cannot press this one')} /> </View> <Separator /> <View> <Text style={styles.title}> This layout strategy lets the title define the width of the button. </Text> <View style={styles.fixToText}> <Button title="Left button" onPress={() => Alert.alert('Left button pressed')} /> <Button title="Right button" onPress={() => Alert.alert('Right button pressed')} /> </View> </View> </SafeAreaView> ); const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', marginHorizontal: 16, }, title: { textAlign: 'center', marginVertical: 8, }, fixToText: { flexDirection: 'row', justifyContent: 'space-between', }, separator: { marginVertical: 8, borderBottomColor: '#737373', borderBottomWidth: StyleSheet.hairlineWidth, }, }); export default App; ``` */ class Button extends React.Component<ButtonProps> { render(): React.Node { const { accessibilityLabel, color, onPress, touchSoundDisabled, title, hasTVPreferredFocus, nextFocusDown, nextFocusForward, nextFocusLeft, nextFocusRight, nextFocusUp, disabled, testID, } = this.props; const buttonStyles = [styles.button]; const textStyles = [styles.text]; if (color) { if (Platform.OS === 'ios') { textStyles.push({color: color}); } else { buttonStyles.push({backgroundColor: color}); } } const accessibilityState = {}; if (disabled) { buttonStyles.push(styles.buttonDisabled); textStyles.push(styles.textDisabled); accessibilityState.disabled = true; } invariant( typeof title === 'string', 'The title prop of a Button must be a string', ); const formattedTitle = Platform.OS === 'android' ? title.toUpperCase() : title; const Touchable = Platform.OS === 'android' ? TouchableNativeFeedback : TouchableOpacity; return ( <Touchable accessibilityLabel={accessibilityLabel} accessibilityRole="button" accessibilityState={accessibilityState} hasTVPreferredFocus={hasTVPreferredFocus} nextFocusDown={nextFocusDown} nextFocusForward={nextFocusForward} nextFocusLeft={nextFocusLeft} nextFocusRight={nextFocusRight} nextFocusUp={nextFocusUp} testID={testID} disabled={disabled} onPress={onPress} touchSoundDisabled={touchSoundDisabled}> <View style={buttonStyles}> <Text style={textStyles} disabled={disabled}> {formattedTitle} </Text> </View> </Touchable> ); } } const styles = StyleSheet.create({ button: Platform.select({ ios: {}, android: { elevation: 4, // Material design blue from https://material.google.com/style/color.html#color-color-palette backgroundColor: '#2196F3', borderRadius: 2, }, }), text: { textAlign: 'center', margin: 8, ...Platform.select({ ios: { // iOS blue from https://developer.apple.com/ios/human-interface-guidelines/visual-design/color/ color: '#007AFF', fontSize: 18, }, android: { color: 'white', fontWeight: '500', }, }), }, buttonDisabled: Platform.select({ ios: {}, android: { elevation: 0, backgroundColor: '#dfdfdf', }, }), textDisabled: Platform.select({ ios: { color: '#cdcdcd', }, android: { color: '#a1a1a1', }, }), }); module.exports = Button;
node_modules/react-native/local-cli/generator/templates/index.android.js
Right-Men/Ironman
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class <%= name %> extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('<%= name %>', () => <%= name %>);
app/components/Admin/Routes/ListCategoriesRoute/index.js
VineRelay/VineRelayStore
import React from 'react'; import PropTypes from 'prop-types'; import { QueryRenderer, graphql } from 'react-relay'; import relayEnvironment from 'app/config/relay'; import PageError from 'app/components/Common/PageError'; import PageLoader from 'app/components/Common/PageLoader'; import DashboardLayout from 'app/components/Admin/Main/DashboardLayout'; import ListCategories from 'app/components/Admin/Category/ListCategories'; import Paper from 'app/components/Admin/Main/Paper'; import Snackbar from 'material-ui/Snackbar'; import { getErrorMessage } from 'app/utils/error'; import FloatingCreateButton from 'app/components/Admin/Main/FloatingCreateButton'; import removeCategoryMutation from './removeCategoryMutation'; class ListCategoriesRoute extends React.Component { static propTypes = { viewer: PropTypes.object.isRequired, history: PropTypes.object.isRequired, categories: PropTypes.object.isRequired, }; componentWillMount() { // Not an admin so change to login if (!this.props.viewer.isAdmin) { this.props.history.replace('/admin/login'); } this.setState({ snackbarMessage: '', }); } onRemoveSuccess = () => { this.setState({ snackbarMessage: 'Category has been deleted', }); } onRemoveError = (error) => { this.setState({ snackbarMessage: getErrorMessage(error), }); } onRemoveComplete = (mutation, errors) => { if (errors) { this.onRemoveError(errors[0]); } else { this.onRemoveSuccess(); } } gotoEditCategory = (id) => this.props.history.push(`/admin/category/${id}`); render() { const { viewer, categories, history, } = this.props; const { snackbarMessage, } = this.state; return ( <DashboardLayout viewer={viewer}> <Paper> <ListCategories categories={categories} onEditCategory={this.gotoEditCategory} onRemoveCategory={(nodeId) => removeCategoryMutation(nodeId, this.onRemoveComplete)} /> </Paper> <Snackbar open={!!snackbarMessage} message={snackbarMessage || ''} autoHideDuration={4000} onRequestClose={() => this.setState({ snackbarMessage: '' })} /> <FloatingCreateButton onClick={() => history.push('/admin/category/create')} /> </DashboardLayout> ); } } export default (props) => ( <QueryRenderer environment={relayEnvironment} query={graphql` query ListCategoriesRouteQuery { viewer { isAdmin ...DashboardLayout_viewer } categories { ...ListCategories_categories } } `} render={({ error, props: relayProps }) => { if (error) { return <PageError error={error} />; } if (relayProps) { return <ListCategoriesRoute {...relayProps} {...props} />; } return <PageLoader />; }} /> );
src/components/Navigation/Navigation.js
grahamplata/grahamplata-gatsbyJS
import React from 'react' import Link from 'gatsby-link' import './Navigation.scss' class Navigation extends React.Component { render() { return ( <div> <header className="nav"> <div className="container"> <div className="nav-left"> <Link className="nav-item" to="/"> <strong>Graham Plata</strong> </Link> </div> <span className="nav-toggle "> <span /> <span /> <span /> </span> <div className="nav-right nav-menu"> <Link className="nav-item" to="/" activeClassName="is-active" activeStyle={{ color: '#00d1b2' }} > Home </Link> <Link className="nav-item" to="/about" activeClassName="is-active" activeStyle={{ color: '#00d1b2' }} > About </Link> <Link className="nav-item" to="/blog" activeClassName="is-active" activeStyle={{ color: '#00d1b2' }} > Blog </Link> <Link className="nav-item" to="/projects" activeClassName="is-active" activeStyle={{ color: '#00d1b2' }} > Projects </Link> <Link className="nav-item" to="/portfolio" activeClassName="is-active" activeStyle={{ color: '#00d1b2' }} > Portfolio </Link> <a className="navbar-item is-hidden-desktop-only" href="https://twitter.com/grahamplata" > <span className="icon"> <i className="fa fa-twitter" /> </span> </a> <a className="navbar-item is-hidden-desktop-only" href="https://github.com/grahamplata" > <span className="icon"> <i className="fa fa-github" /> </span> </a> </div> </div> </header> </div> ) } } export default Navigation
examples/auth-with-shared-root/components/User.js
stshort/react-router
import React from 'react' const User = React.createClass({ render() { return <h1>User: {this.props.params.id}</h1> } }) module.exports = User
fluxible-router/components/Nav.js
devypt/flux-examples
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ import React from 'react'; import {NavLink} from 'fluxible-router'; class Nav extends React.Component { render() { return ( <ul className="pure-menu pure-menu-open pure-menu-horizontal"> <li><NavLink routeName="home" activeStyle={{backgroundColor: '#ccc'}}>Home</NavLink></li> <li><NavLink routeName="about" activeStyle={{backgroundColor: '#ccc'}}>About</NavLink></li> </ul> ); } } export default Nav;
src/components/SpiritViewer/stats.js
aaron-edwards/Spirit-Guide
import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import calc from '../../utils/calc'; export default class Stats extends Component { calculate(formula) { if(this.props.force && this.props.force !== 'formula') { return Math.max(1, Math.ceil(calc(formula, this.props.force))); } else { return formula; } } render() { return ( <View style={styles.container}> <View style={styles.row} > <View style={styles.box}> <Text style={styles.title}>Body</Text> <Text>{this.calculate(this.props.body)}</Text> </View> <View style={styles.box}> <Text style={styles.title}>Agility</Text> <Text>{this.calculate(this.props.agility)}</Text> </View> <View style={styles.box}> <Text style={styles.title}>Reaction</Text> <Text>{this.calculate(this.props.reaction)}</Text> </View> <View style={styles.box}> <Text style={styles.title}>Strength</Text> <Text>{this.calculate(this.props.strength)}</Text> </View> </View> <View style={styles.row} > <View style={styles.box}> <Text style={styles.title}>Willpower</Text> <Text>{this.calculate(this.props.willpower)}</Text> </View> <View style={styles.box}> <Text style={styles.title}>Logic</Text> <Text>{this.calculate(this.props.logic)}</Text> </View> <View style={styles.box}> <Text style={styles.title}>Intuition</Text> <Text>{this.calculate(this.props.intuition)}</Text> </View> <View style={styles.box}> <Text style={styles.title}>Charisma</Text> <Text>{this.calculate(this.props.charisma)}</Text> </View> </View> <View style={styles.row} > <View style={styles.box}> <Text style={styles.title}>Edge</Text> <Text>{this.calculate(this.props.edge)}</Text> </View> <View style={styles.box}> <Text style={styles.title}>Essence</Text> <Text>{this.calculate(this.props.essence)}</Text> </View> <View style={styles.box}> <Text style={styles.title}>Magic</Text> <Text>{this.calculate(this.props.magic)}</Text> </View> </View> </View>) } } const styles = StyleSheet.create({ container: { alignItems: 'center', flexDirection: 'column', }, row: { flexDirection: 'row', justifyContent: 'center', }, title: { fontWeight: 'bold', }, box: { width: 75, margin: 2, alignItems: 'center', borderRadius: 4, borderWidth: 0.5, borderColor: '#d6d7da', } });
examples/es6/config/react.js
lore/lore
/** * Configuration file for React * * This file is where you define overrides for the default mounting behavior. */ // import React from 'react'; // import ReactDOM from 'react-dom'; // import { Provider } from 'react-redux'; // import { Router } from 'react-router'; export default { /** * ID of DOM Element the application will be mounted to */ // domElementId: 'root', /** * Generate the root component that will be mounted to the DOM. This * function will be invoked by lore after all hooks have been loaded. */ // getRootComponent: function(lore) { // const store = lore.store; // const routes = lore.router.routes; // const history = lore.router.history; // // return ( // <Provider store={store}> // <Router history={history}> // {routes} // </Router> // </Provider> // ); // }, /** * Mount the root component to the DOM */ // mount: function(Root, lore) { // const config = lore.config.react; // ReactDOM.render(Root, document.getElementById(config.domElementId), cb); // } }
es/_wlk/icons/Instagram.js
welovekpop/uwave-web-welovekpop.club
import _jsx from "@babel/runtime/helpers/builtin/jsx"; import _extends from "@babel/runtime/helpers/builtin/extends"; import React from 'react'; import SvgIcon from "@material-ui/core/es/SvgIcon"; // Instagram icon from the Font-Awesome icon font by Dave Gandy: // http://fontawesome.io/icon/instagram/ // https://github.com/FortAwesome/Font-Awesome /* eslint-disable max-len */ var _ref = /*#__PURE__*/ _jsx("path", { d: "M1490 1426v-648h-135q20 63 20 131 0 126-64 232.5t-174 168.5-240 62q-197 0-337-135.5t-140-327.5q0-68 20-131h-141v648q0 26 17.5 43.5t43.5 17.5h1069q25 0 43-17.5t18-43.5zm-284-533q0-124-90.5-211.5t-218.5-87.5q-127 0-217.5 87.5t-90.5 211.5 90.5 211.5 217.5 87.5q128 0 218.5-87.5t90.5-211.5zm284-360v-165q0-28-20-48.5t-49-20.5h-174q-29 0-49 20.5t-20 48.5v165q0 29 20 49t49 20h174q29 0 49-20t20-49zm174-208v1142q0 81-58 139t-139 58h-1142q-81 0-139-58t-58-139v-1142q0-81 58-139t139-58h1142q81 0 139 58t58 139z" }); var InstagramIcon = function InstagramIcon(props) { return React.createElement(SvgIcon, _extends({ viewBox: "0 0 1792 1792" }, props), _ref); }; /* eslint-enable max-len */ export default InstagramIcon; //# sourceMappingURL=Instagram.js.map
frontend/src/components/controls/StandaloneRecorderUI/index.js
webrecorder/webrecorder
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Collapsible from 'react-collapsible'; import { Button, Col, Form, Row } from 'react-bootstrap'; import { appHost, defaultRecDesc } from 'config'; import { addTrailingSlash, apiFetch, fixMalformedUrls } from 'helpers/utils'; import { AppContext } from 'store/contexts'; import { CollectionDropdown, ExtractWidget, RemoteBrowserSelect } from 'containers'; import './style.scss'; const ipcRenderer = __DESKTOP__ ? window.require('electron').ipcRenderer : null; class StandaloneRecorderUI extends Component { static contextType = AppContext; static propTypes = { activeCollection: PropTypes.object, extractable: PropTypes.object, history: PropTypes.object, selectedBrowser: PropTypes.string, spaceUtilization: PropTypes.object, toggleLogin: PropTypes.func, username: PropTypes.string }; constructor(props) { super(props); const hasRB = Boolean(props.selectedBrowser); this.state = { advOpen: hasRB, initialOpen: hasRB, sessionNotes: '', setColl: false, url: '', validation: null }; } handleFocus = (evt) => { if (!this.state.highlight) { this.textarea.setSelectionRange(0, this.state.sessionNotes.length); this.setState({ highlight: true }); } } handleInput = (evt) => { evt.preventDefault(); this.setState({ [evt.target.name]: evt.target.value }); } startPreview = (evt) => { evt.preventDefault(); const { history, username, activeCollection } = this.props; const { url } = this.state; if (!url) { return this.setState({ validation: 'error' }); } if (!this.context.isAnon && !activeCollection.id) { this.setState({ setColl: true }); return false; } this.setState({ validation: null }); const cleanUrl = addTrailingSlash(fixMalformedUrls(url)); history.push(`/${username}/${activeCollection.id}/live/${cleanUrl}`); } startRecording = (evt) => { evt.preventDefault(); const { activeCollection, extractable, history, selectedBrowser, username } = this.props; const { sessionNotes, url } = this.state; if (!url) { return false; } if (!this.context.isAnon && !activeCollection.id) { this.setState({ setColl: true }); return false; } const cleanUrl = addTrailingSlash(fixMalformedUrls(url)); // data to create new recording const data = { url: cleanUrl, coll: activeCollection.id, desc: sessionNotes }; // add remote browser if (selectedBrowser) { data.browser = selectedBrowser; } if (extractable) { const mode = extractable.get('allSources') ? 'extract' : 'extract_only'; data.url = extractable.get('targetUrl'); data.mode = `${mode}:${extractable.get('id')}`; data.timestamp = extractable.get('timestamp'); } else { data.mode = 'record'; } // generate recording url apiFetch('/new', data, { method: 'POST' }) .then(res => res.json()) .then(({ url }) => history.push(url.replace(appHost, ''))) .catch(err => console.log('error', err)); } closeAdvance = () => this.setState({ advOpen: false }) openAdvance = () => this.setState({ advOpen: true }) triggerLogin = () => this.props.toggleLogin(true, '/'); render() { const { isAnon } = this.context; const { activeCollection, extractable, spaceUtilization } = this.props; const { advOpen, initialOpen, url } = this.state; const isOutOfSpace = spaceUtilization ? spaceUtilization.get('available') <= 0 : false; const advOptions = ( <div><span className={classNames('caret', { 'caret-flip': advOpen })} /> Session settings</div> ); return ( <Form className="start-recording-homepage" onSubmit={this.startRecording}> <Row> <Col> <Form.Group className={classNames({ 'input-group': extractable })}> <Form.Label htmlFor="url" aria-label="url" srOnly>Url</Form.Label> <Form.Control id="url" aria-label="url" type="text" name="url" onChange={this.handleInput} style={{ height: '33px' }} value={url} placeholder="URL to capture" title={isOutOfSpace ? 'Out of space' : 'Enter URL to capture'} required disabled={isOutOfSpace} /> <ExtractWidget toCollection={activeCollection.title} url={url} /> </Form.Group> </Col> </Row> <Row className="top-buffer"> <Col xs={12} md={2}> <p className="standalone-dropdown-label">Add to collection </p> </Col> <Col xs={12} md={10}> { isAnon ? <Button size="lg" block onClick={this.triggerLogin} variant="outline-secondary" className="anon-button"><span>Login to add to Collection...</span></Button> : <CollectionDropdown size="lg" label={false} /> } { this.state.setColl && <Form.Text style={{ color: 'red' }}> Choose a collection </Form.Text> } </Col> </Row> { !__DESKTOP__ && <Row className="top-buffer rb-dropdown"> <Col xs={12} md={2}> <p className="standalone-dropdown-label">Select browser</p> </Col> <Col xs={12} md={10}> <RemoteBrowserSelect size="lg" /> </Col> </Row> } <Col xs={12} className="top-buffer"> <Collapsible easing="ease-in-out" lazyRender onClose={this.closeAdvance} onOpen={this.openAdvance} open={initialOpen} overflowWhenOpen="visible" transitionTime={300} trigger={advOptions}> <div className="session-settings"> <div> <h4>Session Notes</h4> <textarea rows={5} ref={(o) => { this.textarea = o; }} onFocus={this.handleFocus} name="sessionNotes" placeholder={defaultRecDesc} value={this.state.sessionNotes} onChange={this.handleInput} /> </div> </div> </Collapsible> <div className="actions"> { __DESKTOP__ && <Button variant="outline-secondary" onClick={this.startPreview} aria-label="start preview">Preview</Button> } <Button size="lg" type="submit" variant="primary" aria-label="start recording" disabled={isOutOfSpace}> Start Capture </Button> </div> </Col> </Form> ); } } export default StandaloneRecorderUI;
widgets/src/button/button.js
joshferrell/hapi-maily
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Button extends Component { static contextTypes = { styles: PropTypes.shape({ colors: PropTypes.object.isRequired }).isRequired }; static propTypes = { children: PropTypes.node.isRequired, url: PropTypes.string.isRequired, buttonType: PropTypes.string, squared: PropTypes.bool }; static defaultProps = { buttonType: 'primary', squared: false }; render = () => { const { colors } = this.context.styles; const { children, url, buttonType, squared } = this.props; const buttonProps = { 'background-color': colors[buttonType], color: '#FFFFFF', 'border-radius': squared ? '0' : '25', 'font-size': '18', 'font-weight': 'bold', 'text-transform': 'uppercase', 'inner-padding': '15 30', href: url, rel: 'noreferrer' }; return ( <mj-button {...buttonProps}>{children}</mj-button> ); } } export default Button;
assets/jqwidgets/demos/react/app/kanban/disablecollapse/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxKanban from '../../../jqwidgets-react/react_jqxkanban.js'; class App extends React.Component { render() { let fields = [ { name: 'id', type: 'string' }, { name: 'status', map: 'state', type: 'string' }, { name: 'text', map: 'label', type: 'string' }, { name: 'tags', type: 'string' }, { name: 'color', map: 'hex', type: 'string' }, { name: 'resourceId', type: 'number' } ]; let source = { localData: [ { id: '1161', state: 'new', label: 'Make a new Dashboard', tags: 'dashboard', hex: '#36c7d0', resourceId: 3 }, { id: '1645', state: 'work', label: 'Prepare new release', tags: 'release', hex: '#ff7878', resourceId: 1 }, { id: '9213', state: 'new', label: 'One item added to the cart', tags: 'cart', hex: '#96c443', resourceId: 3 }, { id: '6546', state: 'done', label: 'Edit Item Price', tags: 'price, edit', hex: '#ff7878', resourceId: 4 }, { id: '9034', state: 'new', label: 'Login 404 issue', tags: 'issue, login', hex: '#96c443' } ], dataType: 'array', dataFields: fields }; let dataAdapter = new $.jqx.dataAdapter(source); let resourcesAdapterFunc = () => { let resourcesSource = { localData: [ { id: 0, name: 'No name', image: '../../jqwidgets/styles/images/common.png', common: true }, { id: 1, name: 'Andrew Fuller', image: '../../images/andrew.png' }, { id: 2, name: 'Janet Leverling', image: '../../images/janet.png' }, { id: 3, name: 'Steven Buchanan', image: '../../images/steven.png' }, { id: 4, name: 'Nancy Davolio', image: '../../images/nancy.png' }, { id: 5, name: 'Michael Buchanan', image: '../../images/Michael.png' }, { id: 6, name: 'Margaret Buchanan', image: '../../images/margaret.png' }, { id: 7, name: 'Robert Buchanan', image: '../../images/robert.png' }, { id: 8, name: 'Laura Buchanan', image: '../../images/Laura.png' }, { id: 9, name: 'Laura Buchanan', image: '../../images/Anne.png' } ], dataType: 'array', dataFields: [ { name: 'id', type: 'number' }, { name: 'name', type: 'string' }, { name: 'image', type: 'string' }, { name: 'common', type: 'boolean' } ] }; let resourcesDataAdapter = new $.jqx.dataAdapter(resourcesSource); return resourcesDataAdapter; } let columns = [ { text: 'Backlog', dataField: 'new', maxItems: 4 }, { text: 'In Progress', dataField: 'work', maxItems: 2 }, { text: 'Done', dataField: 'done', collapsible: false, maxItems: 5 } ]; let columnRenderer = (element, collapsedElement, column) => { setTimeout(() => { let columnItems = this.refs.myKanban.getColumnItems(column.dataField).length; // update header's status. element.find('.jqx-kanban-column-header-status').html(' (' + columnItems + '/' + column.maxItems + ')'); // update collapsed header's status. collapsedElement.find('.jqx-kanban-column-header-status').html(' (' + columnItems + '/' + column.maxItems + ')'); }); }; return ( <JqxKanban ref='myKanban' resources={resourcesAdapterFunc()} source={dataAdapter} columns={columns} columnRenderer={columnRenderer} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
examples/todo/js/components/TodoApp.js
tmitchel2/relay
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import AddTodoMutation from '../mutations/AddTodoMutation'; import TodoListFooter from './TodoListFooter'; import TodoTextInput from './TodoTextInput'; import React from 'react'; import Relay from 'react-relay'; class TodoApp extends React.Component { _handleTextInputSave = (text) => { Relay.Store.update( new AddTodoMutation({text, viewer: this.props.viewer}) ); } render() { var hasTodos = this.props.viewer.totalCount > 0; return ( <div> <section className="todoapp"> <header className="header"> <h1> todos </h1> <TodoTextInput autoFocus={true} className="new-todo" onSave={this._handleTextInputSave} placeholder="What needs to be done?" /> </header> {this.props.children} {hasTodos && <TodoListFooter todos={this.props.viewer.todos} viewer={this.props.viewer} /> } </section> <footer className="info"> <p> Double-click to edit a todo </p> <p> Created by the <a href="https://facebook.github.io/relay/"> Relay team </a> </p> <p> Part of <a href="http://todomvc.com">TodoMVC</a> </p> </footer> </div> ); } } export default Relay.createContainer(TodoApp, { fragments: { viewer: () => Relay.QL` fragment on User { totalCount, ${AddTodoMutation.getFragment('viewer')}, ${TodoListFooter.getFragment('viewer')}, } `, }, });
eventkit_cloud/ui/static/ui/app/components/MapTools/SearchAOIButton.js
venicegeo/eventkit-cloud
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { withTheme } from '@material-ui/core/styles'; import ActionSearch from '@material-ui/icons/Search'; import ContentClear from '@material-ui/icons/Clear'; export class SearchAOIButton extends Component { constructor(props) { super(props); this.handleOnClick = this.handleOnClick.bind(this); } handleOnClick() { if (this.props.buttonState === 'SELECTED') { this.props.handleCancel(); this.props.setAllButtonsDefault(); } } render() { const { colors } = this.props.theme.eventkit; const state = this.props.buttonState; const styles = { buttonName: { color: colors.primary, bottom: '0px', fontSize: '8px', width: '55px', height: '12px', }, buttonGeneral: { height: '50px', width: '55px', borderRight: '1px solid #e6e6e6', borderLeft: 'none', borderBottom: 'none', borderTop: 'none', margin: '0px', padding: '0px', backgroundColor: colors.white, outline: 'none', borderRadius: '5px 0px 0px 5px', boxShadow: '0px 3px gba(0, 0, 0, 0.2)', }, }; const DEFAULT_ICON = (( <div id="default_icon"> <ActionSearch className="qa-SearchAOIButton-ActionSearch-default" color="primary" /> <div className="qa-SearchAOIButton-div-default" style={styles.buttonName}>SEARCH</div> </div> )); const INACTIVE_ICON = (( <div id="inactive_icon"> <ActionSearch className="qa-SearchAOIButton-ActionSearch-inactive" style={{ opacity: 0.4 }} color="primary" /> <div className="qa-SearchAOIButton-div-default" style={{ ...styles.buttonName, opacity: 0.4 }}>SEARCH</div> </div> )); const SELECTED_ICON = (( <div id="selected_icon"> <ContentClear className="qa-SearchAOIButton-ContentClear" color="primary" /> <div className="qa-SearchAOIButton-div" style={styles.buttonName}>SEARCH</div> </div> )); let icon = SELECTED_ICON; if (state === 'DEFAULT') { icon = DEFAULT_ICON; } else if (state === 'INACTIVE') { icon = INACTIVE_ICON; } return ( <button type="button" className="qa-SearchAOIButton-button" style={styles.buttonGeneral} onClick={this.handleOnClick}> {icon} </button> ); } } SearchAOIButton.propTypes = { buttonState: PropTypes.string.isRequired, handleCancel: PropTypes.func.isRequired, setAllButtonsDefault: PropTypes.func.isRequired, theme: PropTypes.object.isRequired, }; export default withTheme(SearchAOIButton);
src/parser/shared/modules/items/bfa/pvp/DreadGladiatorsBadge.js
fyruna/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS/index'; import ITEMS from 'common/ITEMS/index'; import Analyzer from 'parser/core/Analyzer'; import UptimeIcon from 'interface/icons/Uptime'; import PrimaryStatIcon from 'interface/icons/PrimaryStat'; import ItemStatistic from 'interface/statistics/ItemStatistic'; import BoringItemValueText from 'interface/statistics/components/BoringItemValueText'; import { formatPercentage, formatNumber } from 'common/format'; import { calculatePrimaryStat } from 'common/stats'; import Abilities from 'parser/core/modules/Abilities'; /** * Dread Gladiator's Badge - * Increases primary stat by 657 for 15 sec. (2 Min Cooldown) */ class DreadGladiatorsBadge extends Analyzer { static dependencies = { abilities: Abilities, }; statBuff = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrinket(ITEMS.DREAD_GLADIATORS_BADGE.id); if (this.active) { this.statBuff = calculatePrimaryStat(385, 1746, this.selectedCombatant.getItem(ITEMS.DREAD_GLADIATORS_BADGE.id).itemLevel); this.abilities.add({ spell: SPELLS.DIG_DEEP, buffSpellId: SPELLS.DIG_DEEP.id, name: ITEMS.DREAD_GLADIATORS_BADGE.name, category: Abilities.SPELL_CATEGORIES.ITEMS, cooldown: 120, castEfficiency: { suggestion: true, }, }); } } get totalBuffUptime() { return this.selectedCombatant.getBuffUptime(SPELLS.DIG_DEEP.id) / this.owner.fightDuration; } statistic() { console.log(this.selectedCombatant.spec.primaryStat); return ( <ItemStatistic size="flexible" > <BoringItemValueText item={ITEMS.DREAD_GLADIATORS_BADGE}> <UptimeIcon /> {formatPercentage(this.totalBuffUptime)}% uptime<br /> <PrimaryStatIcon stat={this.selectedCombatant.spec.primaryStat} /> {formatNumber(this.totalBuffUptime * this.statBuff)} <small>average {this.selectedCombatant.spec.primaryStat} gained</small> </BoringItemValueText> </ItemStatistic> ); } } export default DreadGladiatorsBadge;
app/javascript/mastodon/features/hashtag_timeline/index.js
yi0713/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import ColumnSettingsContainer from './containers/column_settings_container'; import { expandHashtagTimeline, clearTimeline } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { FormattedMessage } from 'react-intl'; import { connectHashtagStream } from '../../actions/streaming'; import { isEqual } from 'lodash'; const mapStateToProps = (state, props) => ({ hasUnread: state.getIn(['timelines', `hashtag:${props.params.id}${props.params.local ? ':local' : ''}`, 'unread']) > 0, }); export default @connect(mapStateToProps) class HashtagTimeline extends React.PureComponent { disconnects = []; static propTypes = { params: PropTypes.object.isRequired, columnId: PropTypes.string, dispatch: PropTypes.func.isRequired, hasUnread: PropTypes.bool, multiColumn: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('HASHTAG', { id: this.props.params.id })); } } title = () => { let title = [this.props.params.id]; if (this.additionalFor('any')) { title.push(' ', <FormattedMessage key='any' id='hashtag.column_header.tag_mode.any' values={{ additional: this.additionalFor('any') }} defaultMessage='or {additional}' />); } if (this.additionalFor('all')) { title.push(' ', <FormattedMessage key='all' id='hashtag.column_header.tag_mode.all' values={{ additional: this.additionalFor('all') }} defaultMessage='and {additional}' />); } if (this.additionalFor('none')) { title.push(' ', <FormattedMessage key='none' id='hashtag.column_header.tag_mode.none' values={{ additional: this.additionalFor('none') }} defaultMessage='without {additional}' />); } return title; } additionalFor = (mode) => { const { tags } = this.props.params; if (tags && (tags[mode] || []).length > 0) { return tags[mode].map(tag => tag.value).join('/'); } else { return ''; } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } _subscribe (dispatch, id, tags = {}, local) { let any = (tags.any || []).map(tag => tag.value); let all = (tags.all || []).map(tag => tag.value); let none = (tags.none || []).map(tag => tag.value); [id, ...any].map(tag => { this.disconnects.push(dispatch(connectHashtagStream(id, tag, local, status => { let tags = status.tags.map(tag => tag.name); return all.filter(tag => tags.includes(tag)).length === all.length && none.filter(tag => tags.includes(tag)).length === 0; }))); }); } _unsubscribe () { this.disconnects.map(disconnect => disconnect()); this.disconnects = []; } componentDidMount () { const { dispatch } = this.props; const { id, tags, local } = this.props.params; this._subscribe(dispatch, id, tags, local); dispatch(expandHashtagTimeline(id, { tags, local })); } componentWillReceiveProps (nextProps) { const { dispatch, params } = this.props; const { id, tags, local } = nextProps.params; if (id !== params.id || !isEqual(tags, params.tags) || !isEqual(local, params.local)) { this._unsubscribe(); this._subscribe(dispatch, id, tags, local); dispatch(clearTimeline(`hashtag:${id}${local ? ':local' : ''}`)); dispatch(expandHashtagTimeline(id, { tags, local })); } } componentWillUnmount () { this._unsubscribe(); } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { id, tags, local } = this.props.params; this.props.dispatch(expandHashtagTimeline(id, { maxId, tags, local })); } render () { const { hasUnread, columnId, multiColumn } = this.props; const { id, local } = this.props.params; const pinned = !!columnId; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={`#${id}`}> <ColumnHeader icon='hashtag' active={hasUnread} title={this.title()} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} showBackButton > {columnId && <ColumnSettingsContainer columnId={columnId} />} </ColumnHeader> <StatusListContainer trackScroll={!pinned} scrollKey={`hashtag_timeline-${columnId}`} timelineId={`hashtag:${id}${local ? ':local' : ''}`} onLoadMore={this.handleLoadMore} emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />} bindToDocument={!multiColumn} /> </Column> ); } }
src/App.js
atyenoria/chat-server-client
import React, { Component } from 'react'; import { NICE, SUPER_NICE } from './colors'; class Counter extends Component { constructor(props) { super(props); this.state = { counter: 0 }; this.interval = setInterval(() => this.tick(), 1000); } tick() { this.setState({ counter: this.state.counter + this.props.increment }); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <h1 style={{ color: this.props.color }}> Counter ({this.props.increment}): {this.state.counter} </h1> ); } } export class App extends Component { render() { return ( <div> <Counter increment={1} color={NICE} /> <Counter increment={5} color={SUPER_NICE} /> </div> ); } }
docs/src/app/components/pages/components/DropDownMenu/ExampleLongMenu.js
IsenrichO/mui-with-arrows
import React from 'react'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; const items = []; for (let i = 0; i < 100; i++ ) { items.push(<MenuItem value={i} key={i} primaryText={`Item ${i}`} />); } export default class DropDownMenuLongMenuExample extends React.Component { constructor(props) { super(props); this.state = {value: 10}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <DropDownMenu maxHeight={300} value={this.state.value} onChange={this.handleChange}> {items} </DropDownMenu> ); } }
packages/react/src/components/forms/InputNumber/InputNumber.stories.js
massgov/mayflower
import React from 'react'; import { StoryPage } from 'StorybookConfig/preview'; import { action } from '@storybook/addon-actions'; import InputNumber from './index'; import InputNumberDocs from './InputNumber.md'; export const InputNumberExample = (args) => { const storyProps = { style: (args.inline) ? { width: '400px' } : { width: '200px' } }; if (args.width > 0) { storyProps.style = { width: `${args.width}px` }; } return( <div {...storyProps}> <InputNumber {...args} /> </div> ); }; InputNumberExample.storyName = 'Default'; InputNumberExample.args = { hiddenLabel: false, labelText: 'Number Input', required: false, inline: false, disabled: false, id: 'number-input', name: 'number-input', width: 0, maxlength: 20, placeholder: '0', errorMsg: 'you did not type something', max: 100, min: 0, step: 1, onChange: () => action('onChange'), onBlur: () => action('onBlur'), showButtons: true }; InputNumberExample.argTypes = { unit: { control: { type: 'text' } } }; export default { title: 'forms/atoms/InputNumber', component: InputNumber, parameters: { docs: { page: () => <StoryPage Description={InputNumberDocs} /> } } };