path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
examples/digger-tree-sections/frontend/src/booking/index.js
binocarlos/templatestack
import React from 'react' import { render } from 'react-dom' import { routerForBrowser } from 'redux-little-router' import RootFactory from 'template-ui/lib/containers/Root' import configureStore from 'template-ui/lib/store/configureStore' import rootSaga from './sagas' import { routeConfig, routes } from './routes' import reducers from './reducers' const router = routerForBrowser({ routes: routeConfig }) const Root = RootFactory(routes) const store = configureStore({ router, reducers, initialState: window.__INITIAL_STATE__ }) store.runSaga(rootSaga) render( <Root store={ store } />, document.getElementById('mount') )
frontend/src/Components/Link/SpinnerButton.js
Radarr/Radarr
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import Icon from 'Components/Icon'; import { icons } from 'Helpers/Props'; import Button from './Button'; import styles from './SpinnerButton.css'; function SpinnerButton(props) { const { className, isSpinning, isDisabled, spinnerIcon, children, ...otherProps } = props; return ( <Button className={classNames( className, styles.button, isSpinning && styles.isSpinning )} isDisabled={isDisabled || isSpinning} {...otherProps} > <span className={styles.spinnerContainer}> <Icon className={styles.spinner} name={spinnerIcon} isSpinning={true} /> </span> <span className={styles.label}> {children} </span> </Button> ); } SpinnerButton.propTypes = { className: PropTypes.string.isRequired, isSpinning: PropTypes.bool.isRequired, isDisabled: PropTypes.bool, spinnerIcon: PropTypes.object.isRequired, children: PropTypes.node }; SpinnerButton.defaultProps = { className: styles.button, spinnerIcon: icons.SPINNER }; export default SpinnerButton;
definitions/npm/react-navigation_v1.x.x/test_react-navigation.js
doberkofler/flow-typed
// @flow import type { NavigationScreenProp, } from 'react-navigation'; import { TabNavigator, StackNavigator, DrawerNavigator, } from 'react-navigation'; import React from 'react'; /** * Screens */ const FunctionalScreenComponent = ( { navigation }: { navigation: NavigationScreenProp<*> }, ) => { return "Test"; }; TabNavigator({ Test1: { screen: FunctionalScreenComponent }, }); class ClassScreenComponent extends React.Component<*> { render() { return "Test"; } } StackNavigator({ Test1: { screen: ClassScreenComponent }, }); // $ExpectError numbers can never be components StackNavigator({ Test1: { screen: 5 }, }); // $ExpectError you need a screen! TabNavigator({ Test1: { blah: "test" }, }); DrawerNavigator({ Test1: { getScreen: () => FunctionalScreenComponent }, }); /** * Configs */ StackNavigator( { Test1: { screen: FunctionalScreenComponent }, }, { mode: "card", initialRouteName: "Test1", }, ); StackNavigator( { Test1: { screen: FunctionalScreenComponent }, }, // $ExpectError stack not drawer! { initialRouteName: "Test1", drawerBackgroundColor: "green", }, ); TabNavigator( { Test1: { screen: FunctionalScreenComponent }, }, // $ExpectError tab not drawer! { drawerBackgroundColor: "green", }, ); TabNavigator( { Test1: { screen: FunctionalScreenComponent }, }, { initialRouteName: "Test1", }, ); DrawerNavigator( { Test1: { screen: FunctionalScreenComponent }, }, { drawerBackgroundColor: "green", }, ); DrawerNavigator( { Test1: { screen: FunctionalScreenComponent }, }, // $ExpectError drawer not tab! { tabBarPosition: "top", }, ); /** * Nav options */ StackNavigator({ Test1: { screen: FunctionalScreenComponent, navigationOptions: { headerTitle: 'Home', }, }, }); class ComponentWithNavOptions extends React.Component<*> { static navigationOptions = { headerTitle: "Home", }; render() { return "Test"; } } StackNavigator({ Test1: { screen: ComponentWithNavOptions }, }); class ComponentWithFunctionalNavOptions extends React.Component<*> { static navigationOptions = ( { navigation }: { navigation: NavigationScreenProp<*> }, ) => ({ headerTitle: navigation.state.routeName, }); render() { return "Test"; } } /** * Nested */ const nestedNavigator = TabNavigator({ Test1: { screen: FunctionalScreenComponent }, }); StackNavigator({ Test2: { screen: nestedNavigator }, Test3: { screen: ClassScreenComponent }, });
src/svg-icons/editor/border-all.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderAll = (props) => ( <SvgIcon {...props}> <path d="M3 3v18h18V3H3zm8 16H5v-6h6v6zm0-8H5V5h6v6zm8 8h-6v-6h6v6zm0-8h-6V5h6v6z"/> </SvgIcon> ); EditorBorderAll = pure(EditorBorderAll); EditorBorderAll.displayName = 'EditorBorderAll'; EditorBorderAll.muiName = 'SvgIcon'; export default EditorBorderAll;
examples/builder/FormBuilder.js
davidkpiano/react-redux-form
import React from 'react'; import { Field, Control, Form, actions, track, } from 'react-redux-form'; import { connect } from 'react-redux'; import uniqueId from 'lodash/uniqueId'; import get from 'lodash/get'; const controlMap = { text: <input type="text" /> }; const createField = () => ({ id: uniqueId(), model: 'user.name', label: '', controls: [], }); class FormBuilder extends React.Component { handleAddField() { const { dispatch } = this.props; const newField = createField(); dispatch(actions.push('fields', newField)); dispatch(actions.change('currentField', newField.id)); } render() { const { fields, currentField, dispatch } = this.props; const editingField = fields.find((field) => field.id === currentField); return ( <Form model="user"> <button type="button" onClick={() => this.handleAddField()} > Add Field </button> {fields.map((field) => <Field model={field.model} key={field.id} onClick={() => dispatch(actions.change('currentField', field.id))} > <label>{field.label}</label> {controlMap[field.type] || <input />} </Field> )} {currentField && <fieldset> <strong>Editing {editingField.model} {currentField}</strong> <Field model={track('fields[].label', {id: currentField})} dynamic> <label>Label for {editingField.model} {currentField}</label> <input type="text" /> </Field> </fieldset> } </Form> ) } } export default connect(s => s)(FormBuilder);
fields/types/text/TextColumn.js
rafmsou/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var TextColumn = React.createClass({ displayName: 'TextColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, linkTo: React.PropTypes.string, }, getValue () { // cropping text is important for textarea, which uses this column const value = this.props.data.fields[this.props.col.path]; return value ? value.substr(0, 100) : null; }, render () { const value = this.getValue(); const empty = !value && this.props.linkTo ? true : false; const className = this.props.col.field.monospace ? 'ItemList__value--monospace' : undefined; return ( <ItemsTableCell> <ItemsTableValue className={className} to={this.props.linkTo} empty={empty} padded interior field={this.props.col.type}> {value} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = TextColumn;
admin/client/App/screens/List/components/ListColumnsForm.js
dryna/keystone-twoje-urodziny
import React from 'react'; import assign from 'object-assign'; import Popout from '../../../shared/Popout'; import PopoutList from '../../../shared/Popout/PopoutList'; import { FormInput } from '../../../elemental'; import ListHeaderButton from './ListHeaderButton'; import { setActiveColumns } from '../actions'; var ListColumnsForm = React.createClass({ displayName: 'ListColumnsForm', getInitialState () { return { selectedColumns: {}, searchString: '', }; }, getSelectedColumnsFromStore () { var selectedColumns = {}; this.props.activeColumns.forEach(col => { selectedColumns[col.path] = true; }); return selectedColumns; }, togglePopout (visible) { this.setState({ selectedColumns: this.getSelectedColumnsFromStore(), isOpen: visible, searchString: '', }); }, toggleColumn (path, value) { const newColumns = assign({}, this.state.selectedColumns); if (value) { newColumns[path] = value; } else { delete newColumns[path]; } this.setState({ selectedColumns: newColumns, }); }, applyColumns () { this.props.dispatch(setActiveColumns(Object.keys(this.state.selectedColumns))); this.togglePopout(false); }, updateSearch (e) { this.setState({ searchString: e.target.value }); }, renderColumns () { const availableColumns = this.props.availableColumns; const { searchString } = this.state; let filteredColumns = availableColumns; if (searchString) { filteredColumns = filteredColumns .filter(column => column.type !== 'heading') .filter(column => new RegExp(searchString).test(column.field.label.toLowerCase())); } return filteredColumns.map((el, i) => { if (el.type === 'heading') { return <PopoutList.Heading key={'heading_' + i}>{el.content}</PopoutList.Heading>; } const path = el.field.path; const selected = this.state.selectedColumns[path]; return ( <PopoutList.Item key={'column_' + el.field.path} icon={selected ? 'check' : 'dash'} iconHover={selected ? 'dash' : 'check'} isSelected={!!selected} label={el.field.label} onClick={() => { this.toggleColumn(path, !selected); }} /> ); }); }, render () { const formFieldStyles = { borderBottom: '1px dashed rgba(0,0,0,0.1)', marginBottom: '1em', paddingBottom: '1em', }; return ( <div> <ListHeaderButton active={this.state.isOpen} id="listHeaderColumnButton" glyph="list-unordered" label="Columns" onClick={() => this.togglePopout(!this.state.isOpen)} /> <Popout isOpen={this.state.isOpen} onCancel={() => this.togglePopout(false)} relativeToID="listHeaderColumnButton"> <Popout.Header title="Columns" /> <Popout.Body scrollable> <div style={formFieldStyles}> <FormInput autoFocus onChange={this.updateSearch} placeholder="Find a column..." value={this.state.searchString} /> </div> <PopoutList> {this.renderColumns()} </PopoutList> </Popout.Body> <Popout.Footer primaryButtonAction={this.applyColumns} primaryButtonLabel="Apply" secondaryButtonAction={() => this.togglePopout(false)} secondaryButtonLabel="Cancel" /> </Popout> </div> ); }, }); module.exports = ListColumnsForm;
src/scripts/GroupViewer.js
lixmal/keepass4web
import React from 'react' import Classnames from 'classnames' export default class GroupViewer extends React.Component { constructor(props) { super(props) } getIcon(element) { var icon = null if (element.custom_icon_uuid) icon = <img className="kp-icon" src={'img/icon/' + encodeURIComponent(element.custom_icon_uuid.replace(/\//g, '_'))} /> else if (element.icon) icon = <img className="kp-icon" src={'img/icons/' + encodeURIComponent(element.icon) + '.png'} /> return icon } render() { var classes = Classnames({ 'panel': true, 'panel-default': true, 'loading-mask': this.props.mask, }) if (!this.props.group) return (<div className={classes}></div>) var group = this.props.group var entries = [] for (var i in group.entries) { let entry = group.entries[i] entries.push( <tr key={i} onClick={this.props.onSelect.bind(this, entry)}> <td className="kp-wrap"> {this.getIcon(entry)} {entry.title} </td> <td className="kp-wrap"> {entry.username} </td> </tr> ) } return ( <div className={classes}> <div className="panel-heading"> {this.getIcon(group)} {group.title} </div> <div className="panel-body"> <table className="table table-hover table-condensed kp-table"> <thead> <tr> <th> Entry Name </th> <th> Username </th> </tr> </thead> <tbody className="groupview-body"> {entries} </tbody> </table> </div> </div> ) } }
blueprints/route/files/src/routes/__name__/components/__name__.js
ksevezich/DayOfBlueprint
import React from 'react' import classes from './<%= pascalEntityName %>.scss' export const <%= pascalEntityName %> = () => ( <div className={classes['<%= pascalEntityName %>']}> <h4><%= pascalEntityName %></h4> </div> ) export default <%= pascalEntityName %>
pages/about.js
ieugen/reactjs-universal-demo
"use strict"; import React from 'react' import Layout from './layout' export default class IndexPage extends React.Component { render() { return ( <Layout title={this.props.title} > <h1> Despre mine </h1> <p> Sunt consultant IT, trainer pe tehnologie (Java, Linux, Node.js în curând ) </p> </Layout> ) } }
app/containers/DetailPanel.js
transparantnederland/relationizer
import React from 'react'; import { connect } from 'react-redux'; import api from '../utils/api'; import admin from '../utils/admin'; import ConceptDropTarget from '../components/ConceptDropTarget'; import Detail from '../components/Detail'; function loadData(props) { const { id } = props; if (id) { props.dispatch(api.actions.concept({ id })); props.dispatch(admin.actions.flags()); } } const DetailPanel = React.createClass({ componentWillMount() { loadData(this.props); }, componentWillReceiveProps(nextProps) { const { id, concept } = nextProps; if (this.props.id !== id) { loadData(nextProps); } if ((this.props.concept && this.props.concept.id) !== (concept && concept.id)) { if (concept.type === 'tnl:Person') { this.props.dispatch(api.actions.orgsFromPerson({ id: concept.id })); this.props.dispatch(api.actions.peopleFromOrgsFromPerson({ id: concept.id })); } else { this.props.dispatch(api.actions.peopleFromOrg({ id: concept.id })); } } }, render() { const { concept, conceptRelations, conceptNetwork, dispatch, flags } = this.props; if (!concept) { return null; } return ( <div style={{ display: 'flex', flex: 1 }}> <ConceptDropTarget concept={concept}> <Detail concept={concept} conceptRelations={conceptRelations} conceptNetwork={conceptNetwork} flags={flags} dispatch={dispatch} /> </ConceptDropTarget> </div> ); }, }); export default connect( (state) => { const { router: { location }, data: { concept, orgsFromPerson, peopleFromOrg, peopleFromOrgsFromPerson, flags }, } = state; // Fetch #hash id from location.state OR fall back on location.hash (on initial pageload) const id = (location.state && location.state.hash) || (!!location.hash && location.hash.substring(1)); const conceptRelations = (concept.data && concept.data.type) === 'tnl:Person' ? orgsFromPerson : peopleFromOrg; const conceptNetwork = (concept.data && concept.data.type) === 'tnl:Person' ? peopleFromOrgsFromPerson.data : null; const conceptFlags = flags.data.filter((item) => { return item.originId === id || item.targetId === id; }); return { id, flags: conceptFlags, concept: concept.data, conceptRelations: conceptRelations.data, conceptNetwork, }; } )(DetailPanel);
pnpm-cached/.pnpm-store/1/registry.npmjs.org/react-bootstrap/0.31.0/es/MenuItem.js
Akkuma/npm-cache-benchmark
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 PropTypes from 'prop-types'; import all from 'react-prop-types/lib/all'; import SafeAnchor from './SafeAnchor'; import { bsClass, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { /** * Highlight the menu item as active. */ active: PropTypes.bool, /** * Disable the menu item, making it unselectable. */ disabled: PropTypes.bool, /** * Styles the menu item as a horizontal rule, providing visual separation between * groups of menu items. */ divider: all(PropTypes.bool, function (_ref) { var divider = _ref.divider, children = _ref.children; return divider && children ? new Error('Children will not be rendered for dividers') : null; }), /** * Value passed to the `onSelect` handler, useful for identifying the selected menu item. */ eventKey: PropTypes.any, /** * Styles the menu item as a header label, useful for describing a group of menu items. */ header: PropTypes.bool, /** * HTML `href` attribute corresponding to `a.href`. */ href: PropTypes.string, /** * Callback fired when the menu item is clicked. */ onClick: PropTypes.func, /** * Callback fired when the menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: PropTypes.func }; var defaultProps = { divider: false, disabled: false, header: false }; var MenuItem = function (_React$Component) { _inherits(MenuItem, _React$Component); function MenuItem(props, context) { _classCallCheck(this, MenuItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } MenuItem.prototype.handleClick = function handleClick(event) { var _props = this.props, href = _props.href, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (!href || disabled) { event.preventDefault(); } if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; MenuItem.prototype.render = function render() { var _props2 = this.props, active = _props2.active, disabled = _props2.disabled, divider = _props2.divider, header = _props2.header, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = _objectWithoutProperties(_props2, ['active', 'disabled', 'divider', 'header', 'onClick', 'className', 'style']); var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['eventKey', 'onSelect']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; if (divider) { // Forcibly blank out the children; separators shouldn't render any. elementProps.children = undefined; return React.createElement('li', _extends({}, elementProps, { role: 'separator', className: classNames(className, 'divider'), style: style })); } if (header) { return React.createElement('li', _extends({}, elementProps, { role: 'heading', className: classNames(className, prefix(bsProps, 'header')), style: style })); } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, elementProps, { role: 'menuitem', tabIndex: '-1', onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return MenuItem; }(React.Component); MenuItem.propTypes = propTypes; MenuItem.defaultProps = defaultProps; export default bsClass('dropdown', MenuItem);
frontend/app/site/pages/Styles/BlockQuote.js
briancappello/flask-react-spa
import React from 'react' import { DocComponent } from 'components' export default class BlockQuote extends DocComponent { title = 'Block Quotes' html = `\ <blockquote> Success consists of going from failure to failure without loosing enthusiasm. <cite>Winston Churchill</cite> </blockquote> ` }
src/components/UIShell/SideNavDetails.js
carbon-design-system/carbon-components-react
/** * 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 cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; const { prefix } = settings; const SideNavDetails = ({ children, className: customClassName, title }) => { const className = cx(`${prefix}--side-nav__details`, customClassName); return ( <div className={className}> <h2 className={`${prefix}--side-nav__title`} title={title}> {title} </h2> {children} </div> ); }; SideNavDetails.propTypes = { /** * Optionally provide a custom class to apply to the underlying <li> node */ className: PropTypes.string, /** * Provide optional children to render in `SideNavDetails`. Useful for * rendering the `SideNavSwitcher` component. */ children: PropTypes.node, /** * Provide the text that will be rendered as the title in the component */ title: PropTypes.string.isRequired, }; export default SideNavDetails;
react-simple-starter/src/components/app.js
majalcmaj/ReactJSCourse
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <div>React simple starter</div> ); } }
Tutorial/js/project/2.MeiTuan/Component/Mine/XMGMineMiddleView.js
onezens/react-native-repo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native'; /**-------导入外部的json数据-------***/ var MiddleData = require('./MiddleData.json'); var MineMiddleView = React.createClass({ render() { return ( <View style={styles.container}> {this.renderAllItem()} </View> ); }, renderAllItem(){ // 定义组件数组 var itemArr = []; // 遍历 for(var i=0; i<MiddleData.length; i++){ // 取出单独的数据 var data = MiddleData[i]; // 创建组件装入数组 itemArr.push( <InnerView key={i} iconName={data.iconName} title={data.title}/> ); } // 返回 return itemArr; } }); // 里面的组件类 var InnerView = React.createClass({ getDefaultProps(){ return{ iconName: '', title:'' } }, render(){ return( <TouchableOpacity activeOpacity={0.5} onPress={()=>{alert('0')}}> <View style={styles.innerViewStyle}> <Image source={{uri: this.props.iconName}} style={{width:40, height:30, marginBottom:3}}/> <Text style={{color:'gray'}}>{this.props.title}</Text> </View> </TouchableOpacity> ); } }); const styles = StyleSheet.create({ container: { // 设置主轴的方向 flexDirection:'row', alignItems: 'center', backgroundColor: 'white', // 设置主轴的对齐方式 justifyContent:'space-around' }, innerViewStyle:{ width:70, height:70, // 水平和垂直居中 justifyContent:'center', alignItems:'center' } }); // 输出组件类 module.exports = MineMiddleView;
react/features/base/react/components/native/ForwardButton.js
gpolitis/jitsi-meet
// @flow import React, { Component } from 'react'; import { Text, TouchableOpacity } from 'react-native'; import { ColorSchemeRegistry } from '../../../color-scheme'; import { translate } from '../../../i18n'; import { connect } from '../../../redux'; /** * The type of the React {@code Component} props of {@link ForwardButton}. */ type Props = { /** * True if the nutton should be disabled. */ disabled: boolean; /** * The i18n label key of the button. */ labelKey: string, /** * The action to be performed when the button is pressed. */ onPress: Function, /** * An external style object passed to the component. */ style?: Object, /** * The function to be used to translate i18n labels. */ t: Function, /** * The color schemed style of the Header component. */ _headerStyles: Object }; /** * A component rendering a forward/next/action button. */ class ForwardButton extends Component<Props> { /** * Implements React's {@link Component#render()}, renders the button. * * @inheritdoc * @returns {ReactElement} */ render() { const { _headerStyles } = this.props; return ( <TouchableOpacity accessibilityLabel = { 'Forward' } disabled = { this.props.disabled } onPress = { this.props.onPress } > <Text style = { [ _headerStyles.headerButtonText, this.props.disabled && _headerStyles.disabledButtonText, this.props.style ] }> { this.props.t(this.props.labelKey) } </Text> </TouchableOpacity> ); } } /** * Maps part of the Redux state to the props of the component. * * @param {Object} state - The Redux state. * @returns {{ * _headerStyles: Object * }} */ function _mapStateToProps(state) { return { _headerStyles: ColorSchemeRegistry.get(state, 'Header') }; } export default translate(connect(_mapStateToProps)(ForwardButton));
app/js/pages/joinPage.js
Dennetix/Motwo
import React from 'react'; import autobind from 'autobind-decorator'; import { observer } from 'mobx-react'; import chat from '../utils/chat'; import utils from '../utils/utils'; import locale from '../utils/locale'; import { setSettingsProp } from '../utils/settings' import FormMessage from '../components/ui/formMessage' import FormTextInput from '../components/ui/formTextInput'; import FormSubmitButton from '../components/ui/formSubmitButton'; import AppStore from '../stores/appStore'; @locale @observer export default class JoinPage extends React.Component { getStyle() { return { container: { width: '100%' }, form: { width: '22rem', position: 'absolute', left: '50%', top: '50%', transform: 'translateX(-50%)' } }; } @autobind onSubmit(e) { e.preventDefault(); AppStore.errorMessage = ''; let channel = e.target[0].value; if(!utils.isStringAndNotEmpty(channel)) { AppStore.errorMessage = this.props.getLocalizedTranslation('formNotFilled'); return false; } AppStore.isLoading = true; chat.join(channel) .then(() => { setSettingsProp({login: {channel}}, false); AppStore.isLoading = false; }) .catch(err => { setSettingsProp({login: {channel: undefined}}, false); AppStore.errorMessage = err; AppStore.isLoading = false; }) } render() { let style = this.getStyle(); return ( <div style={style.container}> <form style={style.form} onSubmit={this.onSubmit}> { AppStore.errorMessage ? <FormMessage error>{AppStore.errorMessage}</FormMessage> : <FormMessage>{this.props.getLocalizedTranslation('joinNotice')}</FormMessage> } <FormTextInput placeholder={this.props.getLocalizedTranslation('channel')} /> <FormSubmitButton value={this.props.getLocalizedTranslation('joinButton')} /> </form> </div> ); } }
archimate-frontend/src/main/javascript/components/view/edges/view/viewConnection.js
zhuj/mentha-web-archimate
import React from 'react' import { ViewLinkWidget } from '../BaseLinkWidget' export const TYPE='viewConnection'; export class ViewConnectionWidget extends ViewLinkWidget { getClassName(link) { return 'viewConnection'; } }
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Generators.js
picter/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function* load(limit) { let i = 1; while (i <= limit) { yield { id: i, name: i }; i++; } } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } componentDidMount() { const users = []; for (let user of load(4)) { users.push(user); } this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-generators"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
src/components/movies/MoviePoster.js
santhoshthepro/redux-movies-app
import React, { Component } from 'react'; import { Link } from 'react-router'; import MovieBox from '../movies/MovieBox'; export default class MoviePoster extends Component{ constructor(props){ super(props); //Here is where you initialize state this.state ={ movies: [ {key:'1', title: 'Kabali',desc:'Sample Movies',pic:'http://bit.do/movie-pic1'}, {key:'2', title: 'Kabali 2',desc:'Sample Movies',pic:'http://bit.do/movie-pic1'}, {key:'3', title: 'Kabali 3',desc:'Sample Movies',pic:'http://bit.do/movie-pic1'} ] } this.handleBooking = this.handleBooking.bind(this); this.handleReadMore = this.handleReadMore.bind(this); } handleBooking(e){ console.log("Booking Received!"); console.log("Title: "+ e.movieTitle); } handleReadMore(){ console.log("Read More..."); } render(){ var movieItems = this.state.movies.map(function(movie){ return <MovieBox ItemKey={movie.key} desc={movie.desc} title={movie.title} pic={movie.pic} handleBooking={this.handleBooking} handleReadMore={this.handleReadMore}/> }.bind(this)); return (<div> <h2>Now Showing...</h2> {movieItems} </div>); } }
docs/app/Examples/elements/Button/GroupVariations/ButtonExampleGroupColored.js
ben174/Semantic-UI-React
import React from 'react' import { Button } from 'semantic-ui-react' const ButtonExampleGroupColored = () => ( <Button.Group color='blue'> <Button>One</Button> <Button>Two</Button> <Button>Three</Button> </Button.Group> ) export default ButtonExampleGroupColored
src/components/root/Root.js
Syferpan/adams
import React from 'react' import PropTypes from 'prop-types' import { Provider } from 'react-redux' import createBrowserHistory from '../../services/history/history' import { Router, Route } from 'react-router-dom' import App from '../app/App' const Root = ({ store }) => ( <Provider store={store}> <Router history={createBrowserHistory}> <Route path="/" component={App} /> </Router> </Provider> ) Root.propTypes = { store: PropTypes.object.isRequired } export default Root
actor-apps/app-web/src/app/components/dialog/MessagesSection.react.js
damoguyan8844/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; import { MessageContentTypes } from 'constants/ActorAppConstants'; import MessageActionCreators from 'actions/MessageActionCreators'; import VisibilityStore from 'stores/VisibilityStore'; import MessageItem from './messages/MessageItem.react'; const {addons: { PureRenderMixin }} = addons; let _delayed = []; let flushDelayed = () => { _.forEach(_delayed, (p) => { MessageActionCreators.setMessageShown(p.peer, p.message); }); _delayed = []; }; let flushDelayedDebounced = _.debounce(flushDelayed, 30, 100); let lastMessageDate = null, lastMessageSenderId = null; @ReactMixin.decorate(PureRenderMixin) class MessagesSection extends React.Component { static propTypes = { messages: React.PropTypes.array.isRequired, peer: React.PropTypes.object.isRequired }; constructor(props) { super(props); VisibilityStore.addChangeListener(this.onAppVisibilityChange); } componentWillUnmount() { VisibilityStore.removeChangeListener(this.onAppVisibilityChange); } getMessagesListItem = (message, index) => { let date = new Date(message.fullDate); const month = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; if (lastMessageDate === null) { lastMessageDate = new Date(message.fullDate); } const isFirstMessage = index === 0; const isNewDay = date.getDate() !== lastMessageDate.getDate(); const dateDivider = isNewDay ? <li className="date-divider">{month[date.getMonth()]} {date.getDate()}</li> : null; const isSameSender = message.sender.peer.id === lastMessageSenderId && !isFirstMessage && !isNewDay; const messageItem = ( <MessageItem key={message.sortKey} message={message} isNewDay={isNewDay} isSameSender={isSameSender} onVisibilityChange={this.onMessageVisibilityChange} peer={this.props.peer}/> ); lastMessageDate = new Date(message.fullDate); lastMessageSenderId = message.sender.peer.id; return [dateDivider, messageItem]; }; onAppVisibilityChange = () => { if (VisibilityStore.isVisible) { flushDelayed(); } }; onMessageVisibilityChange = (message, isVisible) => { if (isVisible) { _delayed.push({peer: this.props.peer, message: message}); if (VisibilityStore.isVisible) { flushDelayedDebounced(); } } }; render() { const messages = _.map(this.props.messages, this.getMessagesListItem); return ( <ul className="messages__list"> {messages} </ul> ); } } export default MessagesSection;
src/Explorer.js
BenjaminCosman/alchemistsSolver
import {worldWeight, partitionWeight} from './Logic.js' import {toPercentageString} from './Misc.js' import React from 'react' import _ from 'lodash' import Button from 'antd/lib/button' function countWorlds(worlds) { return _.sumBy(worlds, world => world.golemMaps.length) } function updatePartitions(partitions, world, studiedIngredients) { const fingerprint = _.filter(world.ingAlcMap, (alc, ing) => studiedIngredients.has(ing)).join("") if (fingerprint in partitions) { partitions[fingerprint].push(world) } else { partitions[fingerprint] = [world] } } function seekWorld(worlds, exploreIndex) { let skippedWeight = 0 for (let i = 0; i < worlds.length; i++) { let world = worlds[i] let weight = worldWeight(world) if (skippedWeight + weight <= exploreIndex) { skippedWeight += weight } else { if (weight > 1) { world = _.clone(world) world.golemMaps = [world.golemMaps[exploreIndex - skippedWeight]] } return world } } throw new Error("seekWorld: should be unreachable") } function Explorer({worlds, golem, studiedIngredients, publishViews}) { const [summary, setSummary] = React.useState(true) const [exploreIndex, setExploreIndex] = React.useState(0) const [worldsCount, setWorldsCount] = React.useState(0) const newCount = countWorlds(worlds) if (newCount !== worldsCount) { setExploreIndex(0) setWorldsCount(newCount) return null //shortcircuit and re-render since we changed state } let worldTracker let worldsOfInterest = worlds if (summary) { //TODO this seems fragile... const disableExplore = (!golem && partitionWeight(worlds) === 40320) || (golem && partitionWeight(worlds) === 967680) worldTracker = <div> Remaining worlds: {countWorlds(worlds)} <Button size="small" onClick={() => setSummary(false)} key="explore" disabled={disableExplore}>Explore</Button> </div> } else { let total let trackerText if (!golem) { let partitions = {} _.forEach(worlds, world => { updatePartitions(partitions, world, studiedIngredients) }) partitions = _.sortBy(partitions, p => -(partitionWeight(p))) total = partitions.length // Defensively moding by total here and below in case a props change has put it out of bounds, // though getDerivedStateFromProps should prevent that from happening worldsOfInterest = partitions[exploreIndex % total] trackerText = "Partition " } else { total = countWorlds(worlds) worldsOfInterest = [seekWorld(worlds, exploreIndex % total)] trackerText = "World " } const probability = toPercentageString(partitionWeight(worldsOfInterest)/partitionWeight(worlds)) worldTracker = <div> {trackerText + (1+(exploreIndex % total)) + " of " + total + " (probability " + probability + "%)"} <Button size="small" onClick={() => setSummary(true)} key="summary">Summary</Button> <Button size="small" onClick={() => setExploreIndex((exploreIndex - 1 + total) % total)} key="+">-</Button> <Button size="small" onClick={() => setExploreIndex((exploreIndex + 1) % total)} key="-">+</Button> </div> } return <> {worldTracker} {publishViews.map(f => f(worldsOfInterest))} </> } export {Explorer}
fields/types/color/ColorColumn.js
vokal/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var ColorColumn = React.createClass({ displayName: 'ColorColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value) return null; const colorBoxStyle = { backgroundColor: value, borderRadius: 3, display: 'inline-block', height: 18, marginRight: 10, verticalAlign: 'middle', width: 18, }; return ( <ItemsTableValue truncate={false} field={this.props.col.type}> <div style={{ lineHeight: '18px' }}> <span style={colorBoxStyle} /> <span style={{ display: 'inline-block', verticalAlign: 'middle' }}>{value}</span> </div> </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = ColorColumn;
src/components/misc/loader-segment.js
scholtzm/arnold
import React from 'react'; import { Segment, Loader, Image } from 'semantic-ui-react'; import shortParagraph from '../../static/image/short-paragraph.png'; import longParagraph from '../../static/image/long-paragraph.png'; const LoaderSegment = (props) => { const { size } = props; let image; switch(size) { case 'mini': case 'tiny': case 'small': case 'medium': image = shortParagraph; break; default: image = longParagraph; break; } return ( <Segment> <div className='ui dimmer inverted active'> <Loader size={props.size}>Loading</Loader> </div> <Image src={image} /> </Segment> ); }; LoaderSegment.defaultProps = { size: 'massive' }; export default LoaderSegment;
actor-apps/app-web/src/app/components/modals/InviteUser.react.js
winiceo/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/index.js
hisaksen/weather-app
import React from 'react'; import { render } from 'react-dom'; import ReactDOM from 'react-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Routers from './config/router'; //Material-ui requires muiThemeProvider wrapped around the components(inside routers) const App = () => ( <MuiThemeProvider> <Routers /> </MuiThemeProvider> ); ReactDOM.render( <App />, document.getElementById('app') );
console-ui/src/components/BatchHandle/BatchHandle.js
alibaba/nacos
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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 PropTypes from 'prop-types'; import { Dialog, Pagination, Transfer } from '@alifd/next'; import { request } from '../../globalLib'; import './index.scss'; class BatchHandle extends React.Component { static propTypes = { valueList: PropTypes.array, dataSource: PropTypes.array, onSubmit: PropTypes.func, }; constructor(props) { super(props); this.state = { visible: false, valueList: props.valueList || [], dataSourceList: props.dataSource || [], currentPage: 1, total: 0, pageSize: 10, dataSource: {}, }; } componentDidMount() {} openDialog(dataSource) { this.setState( { visible: true, dataSource, pageSize: dataSource.pageSize, }, () => { this.getData(); this.transfer._instance.filterCheckedValue = function(left, right, dataSource) { const result = { left, right, }; return result; }; } ); } closeDialog() { this.setState({ visible: false, }); } getData() { const { dataSource } = this.state; request({ url: `/diamond-ops/configList/serverId/${dataSource.serverId}?dataId=${ dataSource.dataId }&group=${dataSource.group}&appName=${ dataSource.appName }&config_tags=${dataSource.config_tags || ''}&pageNo=${this.state.currentPage}&pageSize=${ dataSource.pageSize }`, success: res => { if (res.code === 200) { this.setState({ dataSourceList: res.data.map(obj => ({ label: obj.dataId, value: obj.dataId, })) || [], total: res.total, }); } }, }); } changePage(currentPage) { this.setState( { currentPage, }, () => { this.getData(); } ); } onChange(valueList, data, extra) { this.setState({ valueList, }); } onSubmit() { this.props.onSubmit && this.props.onSubmit(this.state.valueList); } render() { // console.log("valueList: ", this.state.valueList, this.transfer); return ( <Dialog visible={this.state.visible} style={{ width: '500px' }} onCancel={this.closeDialog.bind(this)} onClose={this.closeDialog.bind(this)} onOk={this.onSubmit.bind(this)} title={'批量操作'} > <div> <Transfer ref={ref => (this.transfer = ref)} listStyle={{ height: 350 }} dataSource={this.state.dataSourceList || []} value={this.state.valueList} onChange={this.onChange.bind(this)} /> <Pagination style={{ marginTop: 10 }} current={this.state.currentPage} total={this.state.total} pageSize={this.state.pageSize} onChange={this.changePage.bind(this)} type="simple" /> </div> </Dialog> ); } } export default BatchHandle;
app/components/MenuBar/index.js
Coding/WebIDE-Frontend
import React from 'react' import { observer } from 'mobx-react' import MenuBar from './MenuBar' import menuBarItems from './menuBarItems' import state from './state' const MenuBarContainer = observer((() => <MenuBar items={state.items} />)) export default MenuBarContainer export { menuBarItems }
app/javascript/mastodon/features/compose/components/search_results.js
rekif/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage, defineMessages, injectIntl } from 'react-intl'; import AccountContainer from '../../../containers/account_container'; import StatusContainer from '../../../containers/status_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Hashtag from '../../../components/hashtag'; const messages = defineMessages({ dismissSuggestion: { id: 'suggestions.dismiss', defaultMessage: 'Dismiss suggestion' }, }); export default @injectIntl class SearchResults extends ImmutablePureComponent { static propTypes = { results: ImmutablePropTypes.map.isRequired, suggestions: ImmutablePropTypes.list.isRequired, fetchSuggestions: PropTypes.func.isRequired, dismissSuggestion: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; componentDidMount () { this.props.fetchSuggestions(); } render () { const { intl, results, suggestions, dismissSuggestion } = this.props; if (results.isEmpty() && !suggestions.isEmpty()) { return ( <div className='search-results'> <div className='trends'> <div className='trends__header'> <i className='fa fa-user-plus fa-fw' /> <FormattedMessage id='suggestions.header' defaultMessage='You might be interested in…' /> </div> {suggestions && suggestions.map(accountId => ( <AccountContainer key={accountId} id={accountId} actionIcon='times' actionTitle={intl.formatMessage(messages.dismissSuggestion)} onActionClick={dismissSuggestion} /> ))} </div> </div> ); } let accounts, statuses, hashtags; let count = 0; if (results.get('accounts') && results.get('accounts').size > 0) { count += results.get('accounts').size; accounts = ( <div className='search-results__section'> <h5><i className='fa fa-fw fa-users' /><FormattedMessage id='search_results.accounts' defaultMessage='People' /></h5> {results.get('accounts').map(accountId => <AccountContainer key={accountId} id={accountId} />)} </div> ); } if (results.get('statuses') && results.get('statuses').size > 0) { count += results.get('statuses').size; statuses = ( <div className='search-results__section'> <h5><i className='fa fa-fw fa-quote-right' /><FormattedMessage id='search_results.statuses' defaultMessage='Toots' /></h5> {results.get('statuses').map(statusId => <StatusContainer key={statusId} id={statusId} />)} </div> ); } if (results.get('hashtags') && results.get('hashtags').size > 0) { count += results.get('hashtags').size; hashtags = ( <div className='search-results__section'> <h5><i className='fa fa-fw fa-hashtag' /><FormattedMessage id='search_results.hashtags' defaultMessage='Hashtags' /></h5> {results.get('hashtags').map(hashtag => <Hashtag key={hashtag.get('name')} hashtag={hashtag} />)} </div> ); } return ( <div className='search-results'> <div className='search-results__header'> <i className='fa fa-search fa-fw' /> <FormattedMessage id='search_results.total' defaultMessage='{count, number} {count, plural, one {result} other {results}}' values={{ count }} /> </div> {accounts} {statuses} {hashtags} </div> ); } }
src/components/custom-components/TrackList/TrackItem.js
ArtyomVolkov/music-search
import React from 'react'; import { connect } from 'react-redux'; // M-UI components import { IconMenu, MenuItem, IconButton, CircularProgress, Divider } from 'material-ui'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; import { ListItem } from 'material-ui/List'; // Services import TRACK_ACTION_SERVICE from '../../../services/TrackActionService/TrackActionService'; // Style import './TrackItem.scss'; @connect( state => ({ player: state.player }), dispatch => ({}) ) class TrackItem extends React.Component { constructor (props) { super(props); this.state = { openActions: false }; } onPlaySong (index) { const { track, onAction } = this.props; if (onAction) { onAction('on-play', track, index); } } onToggleActions = () => { this.setState({ openActions: !this.state.openActions }); }; onDownloadTrack = () => { const { track } = this.props; TRACK_ACTION_SERVICE.onDownload(track); this.onToggleActions(); }; toPlayList = () => { const { track } = this.props; TRACK_ACTION_SERVICE.toPlayList(track); this.onToggleActions(); }; toFavorite = () => { const { track } = this.props; TRACK_ACTION_SERVICE.toFavorite(track); this.onToggleActions(); }; onSelectTrackAction (actionName) { const { track, onAction } = this.props; switch (actionName) { case 'to-playlist': this.toPlayList(); break; case 'to-favorite': this.toFavorite(); break; case 'on-download': this.onDownloadTrack(); break; default: if (onAction) { onAction(actionName, track); } break; } this.onToggleActions(); } render () { const { player, track, indexItem, showActions, actionItems } = this.props; const active = player.songData && player.songData.mbid === track.mbid ? 'active' : ''; const error = track.mbid === player.trackIdError ? 'error' : ''; return ( <div className={`track-item ${active} ${error}`}> <ListItem disabled={false} onTouchTap={this.onPlaySong.bind(this, indexItem)} secondaryText={track.albumName} primaryText={ <div className="song-info"> <span className="singer">{track.artistName}</span> <span className="divider">-</span> <span className="song-name">{track.name}</span> </div> } rightIconButton={ showActions && <IconMenu onRequestChange={this.onToggleActions} open={this.state.openActions} iconButtonElement={ <IconButton touch={true} tooltipPosition="bottom-left"> <MoreVertIcon color={'#607D8B'}/> </IconButton> }> <div className="track-item-action-icons"> <MenuItem leftIcon={<i className="fa fa-list-alt"/>} onTouchTap={this.onSelectTrackAction.bind(this, 'to-playlist')} >Add to playlist</MenuItem> <MenuItem leftIcon={<i className="fa fa-star"/>} onTouchTap={this.onSelectTrackAction.bind(this, 'to-favorite')} >Add to favorite</MenuItem> <Divider/> <MenuItem leftIcon={<i className="fa fa-download"/>} disabled={!!error || !active} onTouchTap={this.onSelectTrackAction.bind(this, 'on-download')} >Download</MenuItem> { actionItems && actionItems.map((item, index) => { return ( <div key={index}> {item.divider && <Divider/>} <MenuItem leftIcon={item.iconClass && <i className={item.iconClass}/>} onTouchTap={this.onSelectTrackAction.bind(this, item.action)} >{item.label}</MenuItem> </div> ); }) } </div> </IconMenu> } leftAvatar={<i className={`fa ${player.play && active ? 'fa-pause-circle' : 'fa-play-circle'}`}/>} /> { player.streamLoading && player.streamId === track.mbid && <div className="spinner-wrapper"> <CircularProgress size={45} thickness={4} color="#FF9800" style={{ left: 10 }} /> </div> } </div> ) } } export default TrackItem;
file-browser-ui/dev/js/components/profile/profile.js
CloudBoost/cloudboost
import React from 'react'; import {connect} from 'react-redux'; import {saveUserImage, deleteUserImage, showAlert, updateUser} from '../../actions'; import ChangeField from './ChangeField'; import FlatButton from 'material-ui/FlatButton'; import ReactTooltip from 'react-tooltip'; import Dialog from 'material-ui/Dialog'; import { Table, TableBody, TableRow, TableRowColumn } from 'material-ui/Table'; const profileStyle = { dialogStyle: {width: 400}, profileLabel: { fontWeight: 400, fontSize: 16, color: 'rgba(0,0,0,.5)', lineHeight: '24px', textAlign: 'left', letterSpacing: .03, paddingRight: 0, paddingLeft: 0, width: 140 }, profileLabelOutput: { fontWeight: 400, fontSize: 16, color: '#222', lineHeight: '24px', textAlign: 'left', letterSpacing: .03, paddingRight: 0, paddingLeft: 10 }, cutPadding: { paddingLeft: 0, paddingRight: 0 } }; export class Profile extends React.Component { constructor(props) { super(props); this.state = { oldPassword: '', newPassword: '', confirmPassword: '', name: this.props.currentUser.user ? this.props.currentUser.user.name : '', progress: false } } static get contextTypes() { return {router: React.PropTypes.object.isRequired} } changeFile(e) { if (e.target.files[0]) this.props.saveUserImage(e.target.files[0]) } openChangeFile() { document.getElementById("fileBox").click() } deleteFile(fileId) { if (fileId) this.props.deleteUserImage(fileId) } changeUserData() { if ((this.state.oldPassword && this.state.newPassword) || this.state.name) { if (this.state.newPassword === this.state.confirmPassword) { this.setState({progress: true}); updateUser(this.state.name, this.state.oldPassword, this.state.newPassword) .then(() => this.setState({oldPassword: '', newPassword: '', confirmPassword: '', progress: false})) .catch(err => { if (err.response) { let error = 'User Update Error' showAlert('error', error) } this.setState({oldPassword: '', newPassword: '', confirmPassword: '', progress: false}) }); } else { showAlert('error', 'New passwords does not match.') } } else { showAlert('error', 'Please fill all the fields.') } } changeHandler(which, e) { this.state[which] = e.target.value; this.setState(this.state) } keyUpHandler() { this.changeUserData(); } render() { let userImage = "src/assets/user_image.png"; let fileId = null; if (this.props.currentUser.file) { userImage = this.props.currentUser.file.document.url; fileId = this.props.currentUser.file.document.id } const actionsBtn = (<FlatButton label="Save" primary={true} disabled={this.state.progress} onTouchTap={this.changeUserData.bind(this)}/>); let profilepicobj = ( <div className="edit-profile-photo"> <div className="user-icon medium" style={{backgroundImage: `url('${userImage}')`}} onClick={this.openChangeFile.bind(this)}> { this.props.loading && <div className="profileimageloader"> <img src="src/assets/images/rolling.svg" alt=""/> </div> } <input type="file" style={{visibility: "collapse", width: "0"}} onChange={this.changeFile.bind(this)} id="fileBox" accept="image/*"/> </div> <span onClick={this.openChangeFile.bind(this)}>Click to Edit</span> </div> ); return ( <Dialog title="Edit Profile" modal={false} open={this.props.open} onRequestClose={this.props.close} contentStyle={profileStyle.dialogStyle} titleStyle={{padding: '21px 24px 14px'}} actionsContainerStyle={{padding: '0 16px 15px 8px'}} actions={actionsBtn}> <Table selectable={false}> <TableBody displayRowCheckbox={false} showRowHover={false} className="profile-body"> <TableRow className="profile-row"> <TableRowColumn style={profileStyle.profileLabel}>Profile Pic</TableRowColumn> <TableRowColumn children={profilepicobj} style={profileStyle.cutPadding}/> </TableRow> <TableRow className="profile-row"> <TableRowColumn style={profileStyle.profileLabel}>Name</TableRowColumn> <TableRowColumn style={profileStyle.cutPadding}> <ChangeField field="name" value={this.state.name} changeHandler={this.changeHandler.bind(this)} keyUpHandler={this.keyUpHandler.bind(this)}/> </TableRowColumn> </TableRow> <TableRow className="profile-row"> <TableRowColumn style={profileStyle.profileLabel}>Email</TableRowColumn> <TableRowColumn style={profileStyle.profileLabelOutput} data-tip={this.props.currentUser.user.email}> {this.props.currentUser.user ? this.props.currentUser.user.email : ''} </TableRowColumn> </TableRow> <TableRow className="profile-row"> <TableRowColumn style={profileStyle.profileLabel}>Old Password</TableRowColumn> <TableRowColumn style={profileStyle.cutPadding}> <ChangeField field="oldPassword" value={this.state.oldPassword} changeHandler={this.changeHandler.bind(this)} keyUpHandler={this.keyUpHandler.bind(this)}/> </TableRowColumn> </TableRow> <TableRow className="profile-row"> <TableRowColumn style={profileStyle.profileLabel}>New Password</TableRowColumn> <TableRowColumn style={profileStyle.cutPadding}> <ChangeField field="newPassword" value={this.state.newPassword} changeHandler={this.changeHandler.bind(this)} keyUpHandler={this.keyUpHandler.bind(this)}/> </TableRowColumn> </TableRow> <TableRow className="profile-row" style={{borderBottom: '1px solid rgb(224, 224, 224)'}}> <TableRowColumn style={profileStyle.profileLabel}>Confirm Password</TableRowColumn> <TableRowColumn style={profileStyle.cutPadding}> <ChangeField field="confirmPassword" value={this.state.confirmPassword} changeHandler={this.changeHandler.bind(this)} keyUpHandler={this.keyUpHandler.bind(this)}/> </TableRowColumn> </TableRow> </TableBody> </Table> <ReactTooltip place="bottom" type="dark" delayShow={100}/> </Dialog> ); } } const mapStateToProps = (state) => { return {currentUser: state.user, loading: state.loader.loading} }; const mapDispatchToProps = (dispatch) => { return { saveUserImage: (file) => dispatch(saveUserImage(file)), deleteUserImage: (fileId) => dispatch(deleteUserImage(fileId)) } }; export default connect(mapStateToProps, mapDispatchToProps)(Profile);
src/components/place-component.js
havok2905/react-night-entry
import React from 'react'; import Map from './map-component'; class Place extends React.Component { constructor() { super(); } cover() { return `http://quiet-thicket-99975.herokuapp.com/assets/${this.props.place.cover}`; } render() { return ( <div> <img src={ this.cover() } alt={ this.props.place.name }/> <div class='place-list__content'> <p><strong>{ this.props.place.name }</strong></p> <p>{ this.props.place.description }</p> <p><strong>{ this.props.place.street }, { this.props.place.city } { this.props.place.state }, { this.props.place.zip }</strong></p> <p><a href={ this.props.place.website } target='_blank'>Website</a></p> </div> </div> ); } } // Export dependencies like this: export default Place;
assets/node_modules/react-router/es6/RoutingContext.js
janta-devs/janta
import React from 'react'; import RouterContext from './RouterContext'; import warning from './routerWarning'; var RoutingContext = React.createClass({ displayName: 'RoutingContext', componentWillMount: function componentWillMount() { process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0; }, render: function render() { return React.createElement(RouterContext, this.props); } }); export default RoutingContext;
src/components/pages/NotFoundPage/index.js
SIB-Colombia/dataportal_v2_frontend
import React from 'react' import { PageTemplate, Header, Footer, Heading } from 'components' const NotFoundPage = () => { return ( <PageTemplate header={<Header />} footer={<Footer />}> <Heading>404 Not Found</Heading> </PageTemplate> ) } export default NotFoundPage
app/component/game-cell.js
dazorni/9tac
import React from 'react'; class GameCell extends React.Component { render() { return ( <div onClick={this._onClick.bind(this)} className={this._getClassName()} data-position={this.props.position}> <div className="content"></div> </div> ) } _getClassName() { let className = 'game-cell'; if (this.props.marked) { let playerClass = '-pone'; if (! this.props.isStartingPlayer) { playerClass = '-ptwo'; } if (this.props.isLastTurn) { playerClass = playerClass + ' game-cell-last-turn'; } className = className + ' game-cell-marked game-cell-marked' + playerClass; } return className } _onClick() { this.props.onTurn(this.props.position, this.props.field); } } GameCell.propTypes = { isLastTurn: React.PropTypes.bool.isRequired, position: React.PropTypes.any.isRequired, onTurn: React.PropTypes.func.isRequired } export default GameCell;
docs/app/Examples/elements/Icon/Variations/IconExampleRotated.js
clemensw/stardust
import React from 'react' import { Icon } from 'semantic-ui-react' const IconExampleRotated = () => ( <div> <Icon rotated='clockwise' name='cloud' /> <Icon rotated='counterclockwise' name='cloud' /> </div> ) export default IconExampleRotated
app/share/containers/ShareAppPage/HongbaoTitle.js
Princess310/antd-demo
import React from 'react'; import { getHongbaoInfo } from 'utils/utils'; import FlexCenter from 'components/FlexCenter'; import img from 'assets/images/share-hongbao.png'; function HongbaoTitle(props) { const hongbaoInfo = getHongbaoInfo(); return ( <FlexCenter style={{ height: '1.4rem' }}> <img src={img} style={{ width: '0.55rem', height: '0.65rem' }} /> <section style={{ marginLeft: '0.2rem',width: '5.15rem', fontSize: '0.3rem', fontWeight: 'bold' }}> {`${props.name}下载健康商信APP获得${hongbaoInfo.newer_money}元现金红包,邀请健康行业的朋友也来下载`} </section> </FlexCenter> ); } HongbaoTitle.propTypes = { }; export default HongbaoTitle;
app/components/distance-number.js
sirbrillig/voyageur-js-client
import React from 'react'; import AnimateOnChange from 'react-animate-on-change'; const DistanceNumber = ( props ) => { const meters = props.meters; if ( meters === null ) return <span>Loading...</span>; const miles = ( meters * 0.000621371192 ).toFixed( 1 ); const km = ( meters / 1000 ).toFixed( 1 ); const number = props.useMiles ? miles : km; const units = props.useMiles ? 'miles' : 'km'; return <AnimateOnChange baseClassName="distance__number" animationClassName="animated slideInDown" animate={ true }>{ number } { units }</AnimateOnChange>; }; DistanceNumber.propTypes = { useMiles: React.PropTypes.bool.isRequired, meters: React.PropTypes.number, }; export default DistanceNumber;
examples/with-overmind/components/Items.js
flybayer/next.js
import React from 'react' import { useOvermind } from '../overmind' function Items() { const { state } = useOvermind() return ( <ul> {state.items.map((item) => ( <li key={item.id}>{item.title}</li> ))} </ul> ) } export default Items
game-of-life-react-parcel/src/App.js
LandRover/kata
import React, { Component } from 'react'; import GameOfLife from './GameOfLife'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <h1>Conway's Game of Life</h1> <GameOfLife /> </div> ); } } export default App;
app/react-native/index.ios.js
sping/abcd-epic-fussball
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import App from './app/app'; AppRegistry.registerComponent('MeetupReactNative', () => App);
src/Toolbar/ToolbarRow.js
kradio3/react-mdc-web
import PropTypes from 'prop-types'; import React from 'react'; import classnames from 'classnames'; const ROOT = 'mdc-toolbar__row'; class ToolbarRow extends React.PureComponent { static propTypes = { className: PropTypes.string, children: PropTypes.node, onHeight: PropTypes.func, }; render() { const { className, children, onHeight, ...otherProps } = this.props; return ( <div className={classnames(ROOT, className)} {...otherProps} ref={(native) => { if (native && onHeight) { onHeight(native.offsetHeight); } }} > {children} </div> ); } } export default ToolbarRow;
packages/vulcan-i18n/lib/modules/provider.js
acidsound/Telescope
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { getSetting, Strings } from 'meteor/vulcan:lib'; import { intlShape } from './shape.js'; export default class IntlProvider extends Component{ constructor(){ super(); this.formatMessage = this.formatMessage.bind(this); } formatMessage({ id, defaultMessage }, values) { const messages = Strings[getSetting('locale', 'en')] || {}; let message = messages[id] || defaultMessage; if (values) { _.forEach(values, (value, key) => { message = message.replace(`{${key}}`, value); }); } return message; } formatStuff(something) { return something; } getChildContext() { return { intl: { formatDate: this.formatStuff, formatTime: this.formatStuff, formatRelative: this.formatStuff, formatNumber: this.formatStuff, formatPlural: this.formatStuff, formatMessage: this.formatMessage, formatHTMLMessage: this.formatStuff, now: this.formatStuff, } }; } render(){ return this.props.children; } } IntlProvider.childContextTypes = { intl: intlShape }
MobileApp/node_modules/react-native-elements/example/src/drawer/home.js
VowelWeb/CoinTradePros.com
import Expo from 'expo'; import React from 'react'; import { TabNavigator } from 'react-navigation'; import { Icon } from 'react-native-elements'; import ButtonsTab from '../tabs/buttons'; import ListsTab from '../tabs/lists'; import FormsTab from '../tabs/forms'; import FontsTab from '../tabs/fonts'; const Home = TabNavigator( { ButtonsTab: { screen: ButtonsTab, path: '/buttons', navigationOptions: { tabBarLabel: 'Buttons', tabBarIcon: ({ tintColor, focused }) => ( <Icon name={focused ? 'emoticon-cool' : 'emoticon-neutral'} size={30} type="material-community" color={tintColor} /> ), }, }, ListsTab: { screen: ListsTab, path: '/lists', navigationOptions: { tabBarLabel: 'Lists', tabBarIcon: ({ tintColor, focused }) => ( <Icon name="list" size={30} type="entypo" color={tintColor} /> ), }, }, FormsTab: { screen: FormsTab, path: '/forms', navigationOptions: { tabBarLabel: 'Forms', tabBarIcon: ({ tintColor, focused }) => ( <Icon name="wpforms" size={30} type="font-awesome" color={tintColor} /> ), }, }, FontsTab: { screen: FontsTab, path: '/fonts', navigationOptions: { tabBarLabel: 'Fonts', tabBarIcon: ({ tintColor, focused }) => ( <Icon name={focused ? 'font' : 'font'} size={30} type="font-awesome" color={tintColor} /> ), }, }, }, { initialRouteName: 'ButtonsTab', animationEnabled: false, swipeEnabled: false, tabBarOptions: { activeTintColor: '#e91e63', }, } ); Home.navigationOptions = { drawerLabel: 'Home', drawerIcon: ({ tintColor }) => ( <Icon name="home" size={30} style={{ width: 50, height: 50, alignItems: 'center', justifyContent: 'center', }} type="material-commnity" color={tintColor} /> ), }; export default Home;
stories/components/quoteBanner/index.js
NestorSegura/operationcode_frontend
import React from 'react'; import { storiesOf } from '@storybook/react'; import QuoteBanner from 'shared/components/quoteBanner/quoteBanner'; storiesOf('shared/components/quoteBanner', module) .add('Default', () => ( <QuoteBanner author="James bond" quote="I always enjoyed learning a new tongue" /> ));
lib/components/atoms/button.js
adjohnston/redux-counter-example
import React from 'react'; class Button extends React.Component { render() { const { onClick, text } = this.props; return ( <button onClick={onClick}> {text} </button> ) } } export default Button;
ui/src/components/EditableCell.js
untoldwind/eightyish
import React from 'react' import shallowEqual from '../util/shallowEqual' export default class EditableCell extends React.Component { static propTypes = { activeClassName: React.PropTypes.string, className: React.PropTypes.string, id: React.PropTypes.string, onChange: React.PropTypes.func, rowSpan: React.PropTypes.number, style: React.PropTypes.object, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]).isRequired } constructor(props) { super(props) this.state = { editing: false } } startEditing() { this.setState({editing: true, text: this.props.value}) } finishEditing() { if (this.props.value !== this.state.text) { this.commitEditing() } else if (this.props.value === this.state.text) { this.cancelEditing() } } commitEditing() { if (this.props.onChange) { this.props.onChange(this.state.text) } this.setState({editing: false}) } cancelEditing() { this.setState({editing: false}) } textChanged(event) { this.setState({ text: event.target.value.trim() }) } keyDown(event) { if (event.keyCode === 13) { this.finishEditing() } else if (event.keyCode === 27) { this.cancelEditing() } } componentDidUpdate(prevProps, prevState) { const inputElem = React.findDOMNode(this.refs.input) if (this.state.editing && !prevState.editing) { inputElem.focus() inputElem.setSelectionRange(0, inputElem.value.length) } else if (this.state.editing && prevProps.value !== this.props.value) { this.finishEditing() } } shouldComponentUpdate(nextProps, nextState) { return !shallowEqual(this.props, nextProps, true) || !shallowEqual(this.state, nextState) } render() { if (!this.state.editing) { return ( <td className={this.props.className} id={this.props.id} onClick={this.startEditing.bind(this)} rowSpan={this.props.rowSpan} style={this.props.style}> {this.props.value} </td> ) } return ( <td className={this.props.className} id={this.props.id} onClick={this.startEditing.bind(this)} rowSpan={this.props.rowSpan} style={this.props.style}> <input className={this.props.activeClassName} defaultValue={this.state.text} onBlur={this.finishEditing.bind(this)} onChange={this.textChanged.bind(this)} onKeyDown={this.keyDown.bind(this)} onReturn={this.finishEditing.bind(this)} ref="input" size={this.props.value.toString().length}/> </td> ) } }
src/components/utils/decorators/SubscriptDecorator.js
tsaiDavid/react-rich-text-editor
import React from 'react'; export const Subscript = (props) => { return ( <span> <sub> {props.children} </sub> </span> ); };
src/index.js
flucivja/meteostation
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
src/svg-icons/editor/format-indent-increase.js
spiermar/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;
components/drawer/Drawer.js
react-toolbox/react-toolbox
import React from 'react'; import PropTypes from 'prop-types'; import { themr } from 'react-css-themr'; import classnames from 'classnames'; import Portal from '../hoc/Portal'; import { DRAWER } from '../identifiers'; import ActivableRenderer from '../hoc/ActivableRenderer'; import InjectOverlay from '../overlay/Overlay'; const factory = (Overlay) => { const Drawer = ({ active, children, className, insideTree, onOverlayClick, onEscKeyDown, theme, type, withOverlay, }) => { const _className = classnames([theme.drawer, theme[type]], { [theme.active]: active, }, className); const content = ( <aside data-react-toolbox="drawer" className={_className}> {children} </aside> ); return React.createElement( insideTree ? 'div' : Portal, { className: theme.wrapper }, withOverlay && ( <Overlay active={active} onClick={onOverlayClick} onEscKeyDown={onEscKeyDown} theme={theme} themeNamespace="overlay" /> ), content, ); }; Drawer.propTypes = { active: PropTypes.bool, children: PropTypes.node, className: PropTypes.string, insideTree: PropTypes.bool, onEscKeyDown: PropTypes.func, onOverlayClick: PropTypes.func, theme: PropTypes.shape({ active: PropTypes.string, drawer: PropTypes.string, left: PropTypes.string, right: PropTypes.string, }), type: PropTypes.oneOf([ 'left', 'right', ]), withOverlay: PropTypes.bool, }; Drawer.defaultProps = { active: false, className: '', insideTree: false, type: 'left', withOverlay: true, }; return ActivableRenderer()(Drawer); }; const Drawer = factory(InjectOverlay); export default themr(DRAWER)(Drawer); export { factory as drawerFactory }; export { Drawer };
web/src/js/components/Settings/Widgets/WidgetSettingsComponent.js
gladly-team/tab
import React from 'react' import PropTypes from 'prop-types' import Toggle from 'material-ui/Toggle' import WidgetConfig from 'js/components/Settings/Widgets/WidgetConfigComponent' import { Card, CardHeader, CardText } from 'material-ui/Card' import { cardHeaderTitleStyle } from 'js/theme/default' import { getWidgetIconFromWidgetType } from 'js/components/Widget/widget-utils' import { YAHOO_USER_ID } from 'js/constants' import UpdateWidgetEnabledMutation from 'js/mutations/UpdateWidgetEnabledMutation' import UpdateWidgetConfigMutation from 'js/mutations/UpdateWidgetConfigMutation' class WidgetSettings extends React.Component { constructor(props) { super(props) this.state = { settings: [], } } componentDidMount() { const { appWidget, widget, user } = this.props var config if (widget && widget.config) { config = JSON.parse(widget.config) } let settings = this.getConfig(JSON.parse(appWidget.settings), config) // Quick fix: add Yahoo as an option for the Yahoo demo if (user.id === YAHOO_USER_ID) { settings = settings.map(setting => { if (setting.field === 'engine') { setting.choices.unshift('Yahoo') } return setting }) } this.setState({ settings: settings, }) } getConfig(settings, config) { if (!settings.length) { return [] } var value for (var i = 0; i < settings.length; i++) { if (!config || !(settings[i].field in config)) { value = settings[i].defaultValue } else { value = config[settings[i].field] } settings[i].value = value } return settings } onSettingsSave() {} onSaveError() { this.props.showError( 'Oops, we are having trouble saving your settings right now :(' ) } onWidgetEnableChange(event, checked) { // Call mutation to update widget enabled status. const { appWidget, user } = this.props UpdateWidgetEnabledMutation.commit( this.props.relay.environment, user, appWidget, checked, this.onSettingsSave.bind(this), this.onSaveError.bind(this) ) } onWidgetConfigUpdated(field, value) { const { widget, user, appWidget } = this.props var widgetConfig = {} if (widget) { widgetConfig = JSON.parse(widget.config) } widgetConfig[field] = value const strConfig = JSON.stringify(widgetConfig) // Call mutation to update widget config. UpdateWidgetConfigMutation.commit( this.props.relay.environment, user, appWidget, strConfig, this.onSettingsSave.bind(this), this.onSaveError.bind(this) ) } render() { const { appWidget, widget, user } = this.props const enabled = widget && widget.enabled const settings = this.state.settings || [] const cardStyle = { marginBottom: 10, } const enableToggleStyle = { width: 'initial', marginRight: 10, } const cardHeaderStyle = { display: 'flex', alignItems: 'center', justifyContent: 'space-between', } const cardTitleStyle = Object.assign({}, cardHeaderTitleStyle, { fontSize: 16, }) const settingsContainerStyle = { display: 'flex', flexDirection: 'column', } var settingsComponent if (settings && settings.length) { settingsComponent = ( <CardText> <div style={settingsContainerStyle}> {settings.map((setting, index) => { return ( <WidgetConfig key={index} setting={setting} onConfigUpdated={this.onWidgetConfigUpdated.bind(this)} /> ) })} </div> </CardText> ) } const WidgetIcon = getWidgetIconFromWidgetType(appWidget.type) // Quick fix: hide the search toggle for Yahoo demo const hideToggle = user.id === YAHOO_USER_ID && appWidget.name === 'Search' return ( <Card style={cardStyle}> <CardHeader style={cardHeaderStyle} title={ <span style={{ display: 'flex', alignItems: 'center', }} > <WidgetIcon style={{ height: 18, width: 18, marginRight: 8, }} /> {appWidget.name} </span> } titleStyle={cardTitleStyle} actAsExpander={false} showExpandableButton={false} > {hideToggle ? null : ( <Toggle style={enableToggleStyle} defaultToggled={enabled} onToggle={this.onWidgetEnableChange.bind(this)} /> )} </CardHeader> {settingsComponent} </Card> ) } } WidgetSettings.propTypes = { widget: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, enabled: PropTypes.bool.isRequired, config: PropTypes.string, settings: PropTypes.string, }), appWidget: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, type: PropTypes.string.isRequired, settings: PropTypes.string, }), user: PropTypes.shape({ id: PropTypes.string.isRequired, }), showError: PropTypes.func.isRequired, } export default WidgetSettings
src/documentation/Accessibility-story.js
wfp/ui
/* eslint-disable no-console */ import React from 'react'; import { storiesOf } from '@storybook/react'; import Link from '../components/Link'; import Page from './Page'; storiesOf('Getting started|Getting started', module) .addParameters({ options: { showPanel: false, isToolshown: false, sort: 'zz' }, }) .add('Accessibility', () => ( <Page title="Accessibility standards" subTitle="UX Standards"> <p> Accessible design not only helps users with disabilities; it provides better user experiences for everyone. All components follow the{' '} <b>WCAG AA standards</b>. </p> <p> All patterns are perceivable, operable, and understandable to users, even when using a screen reader or other assistive technology. However, how you use these elements also affects the accessibility of a product. </p> <p> Please find additional information about accessibility in the links below. </p> <p> <Link href="https://next.carbondesignsystem.com/guidelines/accessibility/overview#carbon-and-accessibility" target="_blank"> Accessibility standards of the Carbon Design System </Link> </p> </Page> ));
src/neuralNetwork/infoButtons/OutputLayerInfo.js
csenn/nn-visualizer
import React from 'react'; import InfoButtonTemplate from './InfoButtonTemplate'; export default class InfoButtons extends React.Component { _renderContent() { return ( <div> <p> The output layer is the last layer in a neural network. When a network is being used for classification, the output layer is designed to represent the possible output values. In this example, the possible outcomes are the digits 0-9. </p> <p> When the visualization is blue, the percentage on the node represents the accuracy of the network for that digit. When the visualization is yellow, the number is the activation of the node. The network "guesses" the digit with the highest activation. </p> </div> ) } render() { return ( <InfoButtonTemplate {...this.props} buttonLabel="Output Layer" modalTitle="The Output Layer" renderContent={this._renderContent} /> ); } }
src/give/RecentArticles.js
NewSpring/Apollos
import React from 'react'; import TaggedContent from '@ui/TaggedContent'; const RecentArticles = () => ( <TaggedContent tagName="giving" sectionTitle="Recent articles about giving" /> ); export default RecentArticles;
frontend/src/components/courses/lessons/LessonsList.js
technoboom/it-academy
import React from 'react'; class LessonsList extends React.Component { render() { return ( <div>lessons list should be here</div> ) } } export default LessonsList;
src/components/Home/Banner/index.js
LifeSourceUA/lifesource.ua
/** * [IL] * Library Import */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; /** * [IV] * View Import */ import Mobile from './Views/Mobile'; import Desktop from './Views/Desktop'; /** * [IBP] * Breakpoints */ import BP from 'lib/breakpoints'; /** * [ICONF] * Config Import */ import config from './config'; /** * [IRDX] * Redux connect (optional) */ @connect((state) => { return { mediaType: state.browser.mediaType }; }) class Contacts extends Component { /** * [CPT] * Component prop types */ static propTypes = { mediaType: PropTypes.string.isRequired, items: PropTypes.array.isRequired }; state = { dotIndex: 0 }; /** * [CDN] * Component display name */ static displayName = config.id; nextIndex = () => { this.setState({ dotIndex: this.state.dotIndex + 1 }); }; prevIndex = () => { if (this.state.dotIndex < 0) { return; } this.setState({ dotIndex: this.state.dotIndex - 1 }); }; /** * [CR] * Render function */ render = () => { /** * [RPD] * Props destructuring */ const { mediaType, items } = this.props; /** * [RV] * View */ let view; if (BP.isMobile(mediaType)) { view = ( <Mobile mediaType={ mediaType } items={ items } /> ); } else { view = ( <Desktop mediaType={ mediaType } items={ items } dotIndex={ this.state.dotIndex } nextIndex={ this.nextIndex } prevIndex={ this.prevIndex } /> ); } /** * [RR] * Return Component */ return view; } } /** * [IE] * Export */ export default Contacts;
web/src/components/loadingoverlay.js
corradio/electricitymap
import React from 'react'; import styled from 'styled-components'; import { CSSTransition } from 'react-transition-group'; const Overlay = styled.div` background-image: url(${resolvePath('images/loading/loading64_FA.gif')}), url(${resolvePath('images/loading/electricitymap-text.svg')}); background-position: calc(50% - 64px) center , center center; background-repeat: no-repeat, no-repeat; background-size: 36px , 10rem; background-color: #fafafa; transition: opacity ${props => props.fadeTimeout}ms ease-in-out; z-index: 500; flex: 1 1 0; `; export default ({ fadeTimeout = 500, visible }) => ( <CSSTransition in={visible} timeout={fadeTimeout} classNames="fade"> <Overlay id="loading" fadeTimeout={fadeTimeout} /> </CSSTransition> );
src/components/awesome-ones/app-bar.js
stefanosKarantin/stefanos-react-prj
import React from 'react' import AppBar from 'material-ui/AppBar' import MenuItem from 'material-ui/MenuItem/MenuItem'; import DropDownMenu from 'material-ui/DropDownMenu'; export class AppBarExample extends React.Component{ constructor(props) { super(props); this.state = {value: 0}; } handleChange = (event, index, value) => this.setState({value}); render (){ return( <AppBar title="My poker game" iconElementRight={ <DropDownMenu value={this.state.value} onChange={this.handleChange}> <MenuItem value={0} primaryText="Select Number of Players"/> <MenuItem value={1} primaryText="1 Player"/> <MenuItem value={2} primaryText="2 Players"/> <MenuItem value={3} primaryText="3 Players"/> <MenuItem value={4} primaryText="4 Players"/> <MenuItem value={5} primaryText="5 Players"/> <MenuItem value={6} primaryText="6 Players"/> </DropDownMenu> } /> ); } }
src/components/AthletePreview.js
Arunvirat/Logi-heroes
'use strict'; import React from 'react'; import { Link } from 'react-router'; export default class AthletePreview extends React.Component { calculateTotalPoints() { var totalpoints =0; var myGameRows =this.props.medals; if(myGameRows.length>0) { for(var s=0;s<myGameRows.length; s++) { totalpoints = totalpoints + parseInt(myGameRows[s].category); } } return totalpoints; } render() { return ( <Link to={`/athlete/${this.props.id}`}> <div className="athlete-preview"> <img src={`img/${this.props.image}`}/> <h2 className="name">{this.props.name}</h2> <span className="medals-count"><img src="/img/medal.png"/> {this.calculateTotalPoints()}</span> </div> </Link> ); } }
app/routes.js
thereactleague/galaxy
import React from 'react'; import {Router, Route, hashHistory, IndexRoute} from 'react-router' import App from './components/App'; import LoginContainer from './containers/LoginContainer'; import HomeContainer from './containers/HomeContainer'; const First = () => ( <div>{"First"}</div> ); const Second = () => ( <div>{"Second"}</div> ); // const routes = ( // <Router history={hashHistory}> // <Route name="app" path="/" component={App}> // <IndexRoute name="login" component={LoginContainer}/> // <Route name = "home" path='/home' component={HomeContainer}> // <Route path='/first' component={First}/> // <Route path='/second' component={Second}/> // </Route> // </Route> // </Router> // ); const LoginContainerWrapper = function () { return ( <LoginContainer refs="login" /> ); } const routes = ( <Router history={hashHistory}> <Route name="app" path="/" component={App}> <IndexRoute name="login" component={LoginContainerWrapper}/> <Route name = "home" path='/home' component={HomeContainer}/> </Route> </Router> ); export default routes;
src/svg-icons/action/grade.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGrade = (props) => ( <SvgIcon {...props}> <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/> </SvgIcon> ); ActionGrade = pure(ActionGrade); ActionGrade.displayName = 'ActionGrade'; ActionGrade.muiName = 'SvgIcon'; export default ActionGrade;
frontend/components/SignalPicker.js
heekzz/PowerHour
/** * Created by Fredrik on 2017-06-08. */ import React from 'react'; import {Grid, Row, Col, Button, Panel} from 'react-bootstrap'; import sounds from '../data/drinkSounds'; import { Howl } from 'howler' export default class SignalPicker extends React.Component { constructor(props) { super(props); this.state = { signal: '', }; this.chooseSignal = this.chooseSignal.bind(this); } componentDidMount() { } chooseSignal(sound) { this.setState({ signal: sound.id, }); this.props.chooseSignal(sound); } playSignal(signal) { new Howl({ src: [signal.url] }).play(); } getSounds() { let size = 12 / (sounds.length > 3 ? 4 : sounds.length % 4); return ( sounds.map((sound, key) => ( <Col xs={12} sm={12} md={12} key={sound.id} > <Panel> <Row> <Col md={8} xs={12}> <p><b>Name: </b>{sound.name}</p> <b>Length: </b>{sound.length/1000} seconds </Col> <Col xs={12} md={2}> <Button bsClass="button-black signal-button" onClick={() => this.playSignal(sound)} >Play</Button> </Col> <Col xs={12} md={2}> <Button bsClass="button-green signal-button" onClick={() => this.chooseSignal(sound)} >Choose signal</Button> </Col> </Row> </Panel> </Col> ) ) ) } render () { return ( <Row className="show-grid" > <Col md={12}> <h1>Choose signal</h1> <p>Choose a signal that will play when it's time to drink!</p> </Col> {this.getSounds()} </Row> ) } }
src/components/CreateResetPassword/components/PasswordValidationField/PasswordValidationField.js
folio-org/stripes-core
/* eslint-disable consistent-return */ import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Field } from 'redux-form'; import isEmpty from 'lodash/isEmpty'; import { TextField } from '@folio/stripes-components'; import omitProps from '@folio/stripes-components/util/omitProps'; const defaultValidationHandler = (errors) => { if (!isEmpty(errors)) { return ( <FormattedMessage id={`stripes-smart-components.${errors.pop()}`} /> ); } }; class PasswordValidationField extends React.Component { static manifest = Object.freeze({ validators: { type: 'okapi', path: 'tenant/rules?query=(type==RegExp and state==Enabled)', throwErrors: false, fetch: false, accumulate: true, }, }); static propTypes = { mutator: PropTypes.shape({ validators: PropTypes.shape({ GET: PropTypes.func.isRequired, }).isRequired, }).isRequired, token: PropTypes.string, username: PropTypes.string.isRequired, validate: PropTypes.arrayOf(PropTypes.func), validationHandler: PropTypes.func, }; static defaultProps = { validate: [], validationHandler: defaultValidationHandler, token: '', }; constructor(props) { super(props); this.noUserNameRuleName = 'no_user_name'; this.userNamePlaceholder = '<USER_NAME>'; } async componentDidMount() { this.rules = await this.getRules(); } async getRules() { const { mutator, token, } = this.props; const headers = token ? { headers: { 'x-okapi-token': token } } : {}; const { rules } = await mutator.validators.GET(headers); return rules; } validatePassword = value => { if (!this.rules) { return; } const { username, validationHandler, } = this.props; return validationHandler(this.getErrors(value, username)); }; getErrors(value, username) { return this.rules.filter(({ expression }) => expression) .reduce((errors, rule) => { const { errMessageId, expression, name, } = rule; const parsedExpression = (name === this.noUserNameRuleName) ? expression.replace(this.userNamePlaceholder, username) : expression; const regex = new RegExp(parsedExpression); if (!regex.test(value)) { errors.push(errMessageId); } return errors; }, []); } render() { const { validate, // should not be passed further // eslint-disable-next-line no-unused-vars validationHandler, ...props } = this.props; const fieldProps = omitProps(props, ['dataKey', 'refreshRemote']); return ( <Field type="password" component={TextField} validate={[...validate, this.validatePassword]} {...fieldProps} /> ); } } export default PasswordValidationField;
packages/stockflux-container/src/index.js
owennw/OpenFinD3FC
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
Realization/frontend/czechidm-core/src/redux/flash/FlashMessagesManager.js
bcvsolutions/CzechIdMng
import React from 'react'; import _ from 'lodash'; import { push } from 'connected-react-router'; import sha256 from 'js-sha256'; // api import { LocalizationService, AuthenticateService } from '../../services'; /* * action types */ export const ADD_MESSAGE = 'ADD_MESSAGE'; export const HIDE_MESSAGE = 'HIDE_MESSAGE'; export const HIDE_ALL_MESSAGES = 'HIDE_ALL_MESSAGES'; export const REMOVE_MESSAGE = 'REMOVE_MESSAGE'; export const REMOVE_ALL_MESSAGES = 'REMOVE_ALL_MESSAGES'; // export const DEFAULT_SERVER_UNAVAILABLE_TIMEOUT = 3000; const _DEFAULT_MESSAGE = { id: null, // internal id key: null, // key for unique checking title: null, message: null, level: 'success', // React.PropTypes.oneOf(['success', 'info', 'warning', 'error']), position: 'tr', // React.PropTypes.oneOf(['tr', 'tc', 'bl']), autoDismiss: 5, dismissible: true, action: null, hidden: false, date: new Date() }; /** * Flash messages * * @author Radek Tomiška */ export default class FlashMessagesManager { constructor() { this.serverUnavailableTimeout = DEFAULT_SERVER_UNAVAILABLE_TIMEOUT; } getServerUnavailableTimeout() { return this.serverUnavailableTimeout; } setServerUnavailableTimeout(serverUnavailableTimeout) { this.serverUnavailableTimeout = serverUnavailableTimeout; } addMessage(message) { return dispatch => { if (message.key) { dispatch(this.hideMessage(message.key)); } dispatch({ type: ADD_MESSAGE, message: _.merge({}, message, { date: new Date() }) }); }; } addError(error, context = null) { return this.addErrorMessage({}, error, context); } /** * Transforms options to message and adds default props */ createMessage(options) { if (!options) { return null; } let message = options; if (message == null) { message = LocalizationService.i18n('message.success.common', { defaultValue: 'The operation was successfully completed' }); } if (typeof message === 'string') { message = _.merge({}, _DEFAULT_MESSAGE, { message }); } // if (message.level) { message.level = message.level.toLowerCase(); } // errors are shown centered by default if (message.level && (message.level === 'error' /* || message.level === 'warning' */) && !message.position) { message.position = 'tc'; } // add default message = _.merge({}, _DEFAULT_MESSAGE, message); if (!message.title && !message.message) { message.message = LocalizationService.i18n('message.success.common', { defaultValue: 'The operation was successfully completed' }); } if (message.title && typeof message.title === 'object') { message.title = JSON.stringify(message.title); } if (message.message && typeof message.message === 'object') { message.message = JSON.stringify(message.message); } return message; } /** * Converts result model to flash message * * @param {ResultModel} resultModel * @return {FlashMessage} */ convertFromResultModel(resultModel) { if (!resultModel) { return null; } // automatic localization const messageTitle = LocalizationService.i18n( `${ resultModel.module }:error.${ resultModel.statusEnum }.title`, this._prepareParams(resultModel.parameters, `${ resultModel.statusEnum } (${ resultModel.statusCode }:${ resultModel.id })`) ); let defaultMessage = resultModel.message; if (!_.isEmpty(resultModel.parameters)) { defaultMessage += ' ('; let first = true; for (const parameterKey in resultModel.parameters) { if (!first) { defaultMessage += ', '; } else { first = false; } defaultMessage += `${parameterKey}:${resultModel.parameters[parameterKey]}`; } defaultMessage += ')'; } const messageText = LocalizationService.i18n( `${ resultModel.module }:error.${ resultModel.statusEnum }.message`, this._prepareParams(resultModel.parameters, defaultMessage) ); // const levelStatusCode = parseInt(resultModel.statusCode, 10); let level; // 4xx - warning message, 5xx - error message if (resultModel.level) { level = resultModel.level.toLowerCase(); } else if (levelStatusCode >= 500) { level = 'error'; } else if (levelStatusCode >= 200 && levelStatusCode < 300) { if (levelStatusCode === 202) { // accepted - info level = 'info'; } else { level = 'success'; } } else { level = 'warning'; // TODO: info level? } // return this.createMessage({ key: resultModel.statusEnum, level, title: messageTitle, message: messageText, }); } convertFromError(error) { if (this.isServerUnavailableError(error)) { return { key: 'error-app-load', level: 'error', title: LocalizationService.i18n('content.error.503.description'), message: LocalizationService.i18n('content.error.503.note'), dismissible: true/* , action: { label: 'Odeslat na podporu', callback: () => { alert('Comming soon.') } }*/ }; } if (this.isSyntaxError(error)) { return { key: 'syntax-error', level: 'warning', message: LocalizationService.i18n('content.error.syntax-error.message') }; } // let errorMessage; if (error.statusEnum) { // our error message errorMessage = this.convertFromResultModel(error); } else { // system error - only contain message errorMessage = { level: error.level || 'error', title: error.title, message: error.message }; } return errorMessage; } /** * Converts message from BE message * * @param {IdmMessage} notificationMessage * @return {FlashMessage} */ convertFromWebsocketMessage(notificationMessage) { if (!notificationMessage.model) { return notificationMessage; } // const message = this.convertFromResultModel(notificationMessage.model); // TODO: registrable message converters if (notificationMessage.key === 'core:event' && notificationMessage.model && notificationMessage.model.parameters && notificationMessage.model.parameters.processors) { message.children = ( <div> <ol style={{ listStylePosition: 'inside' }}> { [...notificationMessage.model.parameters.processors.map(processor => { return ( <li>{ LocalizationService.i18n(`${processor.module}:processor.${processor.name}.title`, { defaultValue: processor.id }) } </li> ); }).values()] } </ol> </div> ); } if (notificationMessage.position) { message.position = notificationMessage.position; } if (notificationMessage.level) { message.level = notificationMessage.level; } return message; } addErrorMessage(message, error) { return (dispatch, getState) => { if (DEBUG) { getState().logger.error(message, error); } const errorMessage = _.merge({}, this.convertFromError(error), message); // error redirect handler if (this.isServerUnavailableError(error)) { // timeout to prevent showing message on ajax call interuption setTimeout( () => { dispatch(this.addMessage(errorMessage)); dispatch(this._clearConfiguations()); }, this.getServerUnavailableTimeout() ); // TODO: module defined exception handlers } else if (this._isLoginError(error)) { // If authorities changed exception occurred, but token in the exception is // different then tokne in userContext, then we donť want make a logout (user // could be different (logout/login)). From same reason we will not show exception (maybe is current user different). if (error.statusEnum === 'AUTHORITIES_CHANGED') { if (error.parameters && error.parameters.token) { const currentToken = AuthenticateService.getTokenCIDMST(); // Make SHA1 hash from token const currentTokenHash = sha256(currentToken); const tokenFromErrorHash = error.parameters.token; if (tokenFromErrorHash !== currentTokenHash) { return; } } } this._logoutImmediatelly(); // we dont want to propagate LOGOUT dispatch event ... we want propagate new event: if (error.statusEnum && error.statusEnum === 'TWO_FACTOR_AUTH_REQIURED') { dispatch({ type: 'RECEIVE_LOGIN_EXPIRED', twoFactorToken: error.parameters.token }); } else { dispatch({ type: 'RECEIVE_LOGIN_EXPIRED' }); } } else { dispatch(this.addMessage(errorMessage)); } }; } // TODO: cyclic dependency in security manager _logoutImmediatelly() { const authenticateService = new AuthenticateService(); authenticateService.clearStorage(); } // TODO: cyclic dependency in configuration manager - refactor action constants to separate file _clearConfiguations() { return { type: 'APP_UNAVAILABLE' }; } /** * Returns true, if new login is needed */ _isLoginError(error) { if (!error.statusEnum) { return false; } if (error.statusEnum === 'XSRF' || error.statusEnum === 'LOG_IN' || error.statusEnum === 'AUTH_EXPIRED' || error.statusEnum === 'AUTHORITIES_CHANGED' || error.statusEnum === 'TOKEN_NOT_FOUND' || error.statusEnum === 'TWO_FACTOR_AUTH_REQIURED') { return true; } return false; } /** * Returns true, if BE is not available */ isServerUnavailableError(error) { if (error && error.message && (error.message.indexOf('NetworkError') > -1 || error.message.indexOf('Failed to fetch') > -1 || (error.statusCode && (error.statusCode === '400' || error.statusCode === '503')))) { return true; } return false; } /** * Returns true, if SyntaxError */ isSyntaxError(error) { if (error && error.message && (error.name === 'SyntaxError' && error.message.indexOf('JSON.parse') === 0)) { return true; } if (error && error.stack && error.stack.indexOf('SyntaxError') === 0) { return true; } return false; } _prepareParams(params, defaultMessage) { let results = {}; if (params) { // iterate over all params do necessary converts // TODO converter for date // for (const key in params) { // if (params.hasOwnProperty(key)) { // console.log(params[key], 111); // if (!isNaN(Number(params[key]))) { // // nothing, just number // } else if (params[key] instanceof Date && !isNaN(new Date(params[key])) && params) { // // convert to date // const date = moment(new Date(params[key])); // params[key] = date.format(LocalizationService.i18n('format.date')); // } // } // } results = _.merge({}, params); } if (defaultMessage) { results.defaultValue = defaultMessage; } return results; } hideMessage(id) { return { type: HIDE_MESSAGE, id }; } removeMessage(id) { return { type: REMOVE_MESSAGE, id }; } hideAllMessages() { return { type: HIDE_ALL_MESSAGES }; } removeAllMessages() { return { type: REMOVE_ALL_MESSAGES }; } redirect() { return dispatch => { dispatch(push(`/error/403`)); }; } }
webapp/components/PortalPopover/OverlayTrigger.js
raksuns/universal-iraks
import React from 'react'; import { uniqueId } from './utils'; class OverlayTrigger extends React.Component { constructor(props) { super(props); this.state = { open: false, id: uniqueId(), }; this.toggleOverlay = this.toggleOverlay.bind(this); this.onClose = this.onClose.bind(this); this.addCloseHandler = this.addCloseHandler.bind(this); this.removeCloseHandler = this.removeCloseHandler.bind(this); this.onClickOutside = this.onClickOutside.bind(this); this.accessibleLabel = this.accessibleLabel.bind(this); this.onScroll = this.onScroll.bind(this); } addCloseHandler() { document.addEventListener('click', this.onClickOutside); window.addEventListener('resize', this.onClickOutside); if (this.props.closeOnScroll) { // Use capture for scroll events window.addEventListener('scroll', this.onScroll, true); } } removeCloseHandler() { document.removeEventListener('click', this.onClickOutside); window.removeEventListener('resize', this.onClickOutside); window.removeEventListener('scroll', this.onScroll, true); } componentDidMount() { this.isNodeMounted = true; } componentDidUpdate() { } componentWillUnmount() { this.isNodeMounted = false; this.removeCloseHandler(); } toggleOverlay() { this.setState({ open: !this.state.open, }, () => { if (this.state.open) { this.addCloseHandler(); } else { this.removeCloseHandler(); } }); } onClose() { setTimeout(() => { if (this.isNodeMounted) { this.setState({ open: false, }); this.removeCloseHandler(); } }, 0); } onScroll() { this.setState({ open: false, }); } onClickOutside() { this.removeCloseHandler(); this.setState({ open: false, }); } accessibleLabel(children) { if (this.props.showLabel && this.props.hideLabel) { const label = (<span className="u-accessible">{this.state.open ? this.props.hideLabel : this.props.showLabel}</span>); return [label, children]; } return children; } render() { const { children } = this.props; if (!children || !this.props.overlay) { return <span />; } const triggerId = children.id || `trigger_${this.state.id}`; const trigger = React.cloneElement(children, { onClick: this.toggleOverlay, 'aria-controls': this.state.id, 'aria-owns': this.state.id, 'aria-expanded': this.state.open, 'aria-haspopup': true, id: triggerId, children: this.accessibleLabel(children.props.children), ref: (ref) => { this.trigger = ref; }, }); const overlay = React.cloneElement(this.props.overlay, { trigger: this.trigger || null, isOpened: this.state.open, onClose: this.onClose, id: this.state.id, label: this.props.label || '', }); return ( <span> {trigger} {overlay} </span> ); } } OverlayTrigger.propTypes = { closeOnScroll: React.PropTypes.bool, children: React.PropTypes.element.isRequired, overlay: React.PropTypes.object.isRequired, hideLabel: React.PropTypes.string, showLabel: React.PropTypes.string, label: React.PropTypes.string, }; export default OverlayTrigger;
src/ButtonToolbar.js
RichardLitt/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const ButtonToolbar = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'button-toolbar' }; }, render() { let classes = this.getBsClassSet(); return ( <div {...this.props} role="toolbar" className={classNames(this.props.className, classes)}> {this.props.children} </div> ); } }); export default ButtonToolbar;
client/src/app/components/ui/RFFileUpload.js
zraees/sms-project
import React from 'react' import classNames from 'classnames' import Msg from '../i18n/Msg' import LanguageStore from '../i18n/LanguageStore' import Dropzone from 'react-dropzone'; const RFFileUpload = (field) => { const files = field.input.value; const phrase = LanguageStore.getData().phrases["image preview"] || "image preview"; return ( <div> <Dropzone name={field.name} multiple={false} disablePreview={false} className='react-dropzone' activeClassName='active-react-dropzone' onDrop={( filesToUpload, e ) => field.input.onChange(filesToUpload)} > <center className="padding2px"><Msg phrase="DropPicText"/></center> </Dropzone> {field.meta.touched && field.meta.error && <span className="error">{field.meta.error}</span>} {files && Array.isArray(files) && ( <center> <img className="studentImgAdd" src={ files[0].preview } alt={phrase} /> </center> )} </div> ); }; export default RFFileUpload
admin/client/App/elemental/DropdownButton/index.js
matthewstyers/keystone
/* eslint quote-props: ["error", "as-needed"] */ import React from 'react'; import { css, StyleSheet } from 'aphrodite/no-important'; import Button from '../Button'; function DropdownButton ({ children, ...props }) { return ( <Button {...props}> {children} <span className={css(classes.arrow)} /> </Button> ); }; // NOTE // 1: take advantage of `currentColor` by leaving border top color undefined // 2: even though the arrow is vertically centered, visually it appears too low // because of lowercase characters beside it const classes = StyleSheet.create({ arrow: { borderLeft: '0.3em solid transparent', borderRight: '0.3em solid transparent', borderTop: '0.3em solid', // 1 display: 'inline-block', height: 0, marginTop: '-0.125em', // 2 verticalAlign: 'middle', width: 0, // add spacing ':first-child': { marginRight: '0.5em', }, ':last-child': { marginLeft: '0.5em', }, }, }); module.exports = DropdownButton;
components/input/Input.js
jasonleibowitz/react-toolbox
import React from 'react'; import classnames from 'classnames'; import { themr } from 'react-css-themr'; import { INPUT } from '../identifiers.js'; import InjectedFontIcon from '../font_icon/FontIcon.js'; const factory = (FontIcon) => { class Input extends React.Component { static propTypes = { children: React.PropTypes.any, className: React.PropTypes.string, disabled: React.PropTypes.bool, error: React.PropTypes.string, floating: React.PropTypes.bool, hint: React.PropTypes.string, icon: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.element ]), label: React.PropTypes.string, maxLength: React.PropTypes.number, multiline: React.PropTypes.bool, name: React.PropTypes.string, onBlur: React.PropTypes.func, onChange: React.PropTypes.func, onFocus: React.PropTypes.func, onKeyPress: React.PropTypes.func, required: React.PropTypes.bool, rows: React.PropTypes.number, theme: React.PropTypes.shape({ bar: React.PropTypes.string, counter: React.PropTypes.string, disabled: React.PropTypes.string, error: React.PropTypes.string, errored: React.PropTypes.string, hidden: React.PropTypes.string, hint: React.PropTypes.string, icon: React.PropTypes.string, input: React.PropTypes.string, inputElement: React.PropTypes.string, required: React.PropTypes.string, withIcon: React.PropTypes.string }), type: React.PropTypes.string, value: React.PropTypes.any }; static defaultProps = { className: '', hint: '', disabled: false, floating: true, multiline: false, required: false, type: 'text' }; componentDidMount () { if (this.props.multiline) { window.addEventListener('resize', this.handleAutoresize); this.handleAutoresize(); } } componentWillReceiveProps (nextProps) { if (!this.props.multiline && nextProps.multiline) { window.addEventListener('resize', this.handleAutoresize); } else if (this.props.multiline && !nextProps.multiline) { window.removeEventListener('resize', this.handleAutoresize); } } componentDidUpdate () { // resize the textarea, if nessesary if (this.props.multiline) this.handleAutoresize(); } componentWillUnmount () { if (this.props.multiline) window.removeEventListener('resize', this.handleAutoresize); } handleChange = (event) => { const { onChange, multiline, maxLength } = this.props; const valueFromEvent = event.target.value; // Trim value to maxLength if that exists (only on multiline inputs). // Note that this is still required even tho we have the onKeyPress filter // because the user could paste smt in the textarea. const haveToTrim = (multiline && maxLength && event.target.value.length > maxLength); const value = haveToTrim ? valueFromEvent.substr(0, maxLength) : valueFromEvent; // propagate to to store and therefore to the input if (onChange) onChange(value, event); }; handleAutoresize = () => { const element = this.refs.input; const rows = this.props.rows; if (typeof rows === 'number' && !isNaN(rows)) { element.style.height = null; } else { // compute the height difference between inner height and outer height const style = getComputedStyle(element, null); const heightOffset = style.boxSizing === 'content-box' ? -(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom)) : parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth); // resize the input to its content size element.style.height = 'auto'; element.style.height = `${element.scrollHeight + heightOffset}px`; } } handleKeyPress = (event) => { // prevent insertion of more characters if we're a multiline input // and maxLength exists const { multiline, maxLength, onKeyPress } = this.props; if (multiline && maxLength) { // check if smt is selected, in which case the newly added charcter would // replace the selected characters, so the length of value doesn't actually // increase. const isReplacing = event.target.selectionEnd - event.target.selectionStart; const value = event.target.value; if (!isReplacing && value.length === maxLength) { event.preventDefault(); event.stopPropagation(); return; } } if (onKeyPress) onKeyPress(event); }; blur () { this.refs.input.blur(); } focus () { this.refs.input.focus(); } render () { const { children, disabled, error, floating, hint, icon, name, label: labelText, maxLength, multiline, required, theme, type, value, onKeyPress, rows = 1, ...others} = this.props; const length = maxLength && value ? value.length : 0; const labelClassName = classnames(theme.label, {[theme.fixed]: !floating}); const className = classnames(theme.input, { [theme.disabled]: disabled, [theme.errored]: error, [theme.hidden]: type === 'hidden', [theme.withIcon]: icon }, this.props.className); const valuePresent = value !== null && value !== undefined && value !== '' && !(typeof value === Number && isNaN(value)); const inputElementProps = { ...others, className: classnames(theme.inputElement, {[theme.filled]: valuePresent}), onChange: this.handleChange, ref: 'input', role: 'input', name, disabled, required, type, value }; if (!multiline) { inputElementProps.maxLength = maxLength; inputElementProps.onKeyPress = onKeyPress; } else { inputElementProps.rows = rows; inputElementProps.onKeyPress = this.handleKeyPress; } return ( <div data-react-toolbox='input' className={className}> {React.createElement(multiline ? 'textarea' : 'input', inputElementProps)} {icon ? <FontIcon className={theme.icon} value={icon} /> : null} <span className={theme.bar} /> {labelText ? <label className={labelClassName}> {labelText} {required ? <span className={theme.required}> * </span> : null} </label> : null} {hint ? <span hidden={labelText} className={theme.hint}>{hint}</span> : null} {error ? <span className={theme.error}>{error}</span> : null} {maxLength ? <span className={theme.counter}>{length}/{maxLength}</span> : null} {children} </div> ); } } return Input; }; const Input = factory(InjectedFontIcon); export default themr(INPUT, null, { withRef: true })(Input); export { factory as inputFactory }; export { Input };
src/components/navigation_item.js
tmcw/docbox
import React from 'react'; import PropTypes from 'prop-types'; export default class NavigationItem extends React.PureComponent { static propTypes = { sectionName: PropTypes.string.isRequired, active: PropTypes.bool.isRequired, onClick: PropTypes.func.isRequired, href: PropTypes.string.isRequired } onClick = () => { this.props.onClick(this.props.sectionName); } render() { var {sectionName, href, active} = this.props; return (<a href={href} onClick={this.onClick} className={`line-height15 pad0x pad00y quiet block ${active ? 'fill-lighten0 round' : ''}`}> {sectionName} </a>); } }
src/components/Feedback/Feedback.js
pandoraui/react-starter
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
src/common/components/popover/index.js
canonical-websites/build.snapcraft.io
import PropTypes from 'prop-types'; import React from 'react'; import styles from './popover.css'; const Popover = (props) => { return ( <div className={styles.popover} style={{ top: `${props.top}px`, left:`${props.left}px` }} onClick={props.onClick} > {props.children} </div> ); }; Popover.propTypes = { left: PropTypes.number, top: PropTypes.number, children: PropTypes.node, onClick: PropTypes.func }; export default Popover;
examples/fluxible-router/app.js
pablolmiranda/fluxible
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ import React from 'react'; import Fluxible from 'fluxible'; import Application from './components/Application'; import RouteStore from './stores/RouteStore'; import ApplicationStore from './stores/ApplicationStore'; import TimeStore from './stores/TimeStore'; import PageStore from './stores/PageStore'; let app = new Fluxible({ component: Application, stores: [ RouteStore, ApplicationStore, TimeStore, PageStore ] }); export default app;
src/App.js
loftywaif002/folder-explorer
import React, { Component } from 'react'; import FolderComponent from './Components/FolderComponent'; import FileComponent from './Components/FileComponent'; import FolderTree from './Components/FolderTree'; import styles from './Components/folderTreeCSS.css'; const testData = { "id": 1, "filename": "All Categories", "children": [ { "id": 2, "filename": "Main Folder", "children": [ { "id": 3, "filename": "Nested Folder", "children": [ { "id": 4, "filename": "Super Nested Folder", "children": [ { "id": 5, "filename": "Deep File", }, { "id": 6, "filename": "Deep File 2", }, { "id": 7, "filename": "empty", } ] } ] }, ] }, { "id": 18, "filename": "Folder Two", "children": [ { "id": 19, "filename": "empty1", }, { "id": 20, "filename": "empty2", }, { "id": 21, "filename": "empty3", } ] }, { "id": 22, "filename": "Folder Three", "children": [ { "id": 23, "filename": "empty1", }, { "id": 24, "filename": "empty2", } ] }, { "id": 25, "filename": "Private Folder", "children": [ { "id": 26, "filename": "empty1", }, { "id": 27, "filename": "empty2", } ] } ] } export default class Sandbox extends Component { state = { data: 1, testData: testData, } render() { return ( <div style={{padding: '50px 20px', width: '50%'}}> <FolderTree data={this.state.testData} fileComponent={FileComponent} folderComponent={FolderComponent} /> </div> ); } }
app/components/IssueIcon/index.js
dbrelovsky/react-boilerplate
import React from 'react' function IssueIcon (props) { return ( <svg height='1em' width='0.875em' className={props.className} > <path d='M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z' /> </svg> ) } IssueIcon.propTypes = { className: React.PropTypes.string } export default IssueIcon
app/components/HomeNav.js
Strive22/Hunt
import React from 'react'; import { Grid, Row, Col, Button } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; import EnterJob from './EnterJob'; import SearchNewJobs from './SearchNewJobs' export default (props) => { return ( <Grid> <Row> <Col md={4}> <div className="selectbox dash"> <h2>View Your<br/>Dashboard</h2> <LinkContainer to={'/dashboard'}> <Button bsSize="large" className="search-btn">Go!</Button> </LinkContainer> </div> </Col> <Col md={4}> <SearchNewJobs search={props.searchForJobs}/> </Col> <Col md={4}> <EnterJob addJob={props.addJob}/> </Col> </Row> </Grid> ) }
Paths/React/05.Building Scalable React Apps/7-react-boilerplate-building-scalable-apps-m7-exercise-files/After/app/components/Link/index.js
phiratio/Pluralsight-materials
/** * * Link * */ import React from 'react'; import styles from './styles.css'; function Link({ link }) { return ( <div className={styles.link}> <div className={styles.votingContainer} > <div className={styles.votingCount} > {link.voteCount} </div> </div> <div className={styles.detailsContainer} > <div> <a href={link.url} className={styles.linkAnchor} > {link.url} </a> </div> <div className={styles.description} > {link.description} </div> </div> </div> ); } Link.propTypes = { link: React.PropTypes.shape({ voteCount: React.PropTypes.number.isRequired, description: React.PropTypes.string.isRequired, url: React.PropTypes.string.isRequired, id: React.PropTypes.string.isRequired, }), }; export default Link;
app/src/components/Chat/Message.js
RekkyRek/tic
import '../../assets/css/Chat/Message.sass'; import React, { Component } from 'react'; import twemoji from 'twemoji'; import emoji from 'node-emoji'; import * as Helpers from '../Utils/Helpers'; const fs = require('fs'); const mime = require('mime'); class Message extends React.Component { constructor(props) { super(props) this.state = { impath: '', innerHTML: '', msgImage: '', msgVideo: '', msgYoutube: '', imbak: '', loaded: false, shouldLoad: false, } } unescape(s){ var r = String(s); r = r.replace(/\\s/g, " "); // Whitespace r = r.replace(/\\p/g, "|"); // Pipe r = r.replace(/\\n/g, "\n"); // Newline r = r.replace(/\\f/g, "\f"); // Formfeed r = r.replace(/\\r/g, "\r"); // Carriage Return r = r.replace(/\\t/g, "\t"); // Tab r = r.replace(/\\v/g, "\v"); // Vertical Tab r = r.replace(/\\\//g, "\/"); // Slash r = r.replace(/\\\\/g, "\\"); // Backslash if(r.match(/\[URL\](.*?|\n)\[\/URL\]/g) != null) { r.match(/\[URL\](.*?|\n)\[\/URL\]/g).forEach(function(url) { let urll = url.length-6; r = r.replace(url, `<a alt="${url.substring(5, urll)}" href="${url.substring(5, urll)}">${url.substring(5, urll)}</a>`); let images = ['png', 'jpg', 'peg', 'gif']; let isurl = url.split("?")[0].substring(5, urll); if(images.indexOf(isurl.substring(isurl.length-3, isurl.length).toLowerCase()) > -1 && this.state.msgImage == '') { this.setState({ msgImage: url.substring(5, urll) }); return; } let videos = ['mp4', 'ifv', 'ebm']; if(videos.indexOf(url.substring(url.length-9, urll).toLowerCase()) > -1 && this.state.msgVideo == '') { if(url.indexOf('imgur') > -1) { let nurl = url.substring(5, urll).split('.'); nurl.pop(); url = '[URL]' + nurl.join('.') + '.mp4'; } this.setState({ msgVideo: url.substring(5, urll) }); return; } if(url.toLowerCase().indexOf('youtube') > -1 && url.toLowerCase().indexOf('?v=') > -1 && this.state.msgYoutube == '') { var video_id = url.split('v=')[1]; var ampersandPosition = video_id.indexOf('&'); if(ampersandPosition != -1) { video_id = video_id.substring(0, ampersandPosition); } else { video_id = video_id.substring(0, video_id.length - 6); } this.setState({ msgYoutube: video_id + '?autoplay=1' }); return; } if(url.toLowerCase().indexOf('youtu.be') > -1 && this.state.msgYoutube == '') { var video_id = url.substring(0, url.length-6).split('/').pop(); var ampersandPosition = video_id.indexOf('?'); if(ampersandPosition > -1) { video_id += '&playsinline=0&autoplay=1' } else { video_id += '?playsinline=0&autoplay=1' } this.setState({ msgYoutube: video_id }); return; } }, this); } return r; } componentDidMount() { let unesc = this.unescape(this.props.msg.msg); unesc = emoji.emojify(unesc); unesc = twemoji.parse(unesc); let impath = `${this.props.cacheDir}/clients/avatar_${Helpers.ts3_base16(this.props.msg.invokeruid)}`; let imseed = Math.floor(Math.random() * 360) let imbak = `linear-gradient(19deg, hsl(${imseed}, 98%, 56%) 0%, hsl(${imseed+15}, 100%, 56%) 100%)` if(!fs.existsSync(impath)) { impath = ""; this.setState({ innerHTML: unesc, imbak: imbak }) } else if(this.state.impath == ''){ fs.readFile(impath, (err, data) => { if (err) throw err; this.setState({ innerHTML: unesc, impath: `data:${mime.lookup(impath)};base64,${data.toString('base64')}`, imbak: imbak }) }); } } shouldComponentUpdate(nprops,nstate) { return nstate != this.state; } render() { let name = this.props.msg.invokername; let ytvid; if(this.state.msgYoutube != '') { if(!this.state.shouldLoad) { ytvid = ( <div className="msgMedia"> <img className="ytPreview" src={`https://ytimg.googleusercontent.com/vi/${this.state.msgYoutube.split('?')[0]}/hqdefault.jpg`} /> <div onClick={()=>{this.setState({ shouldLoad: true })}} className="ytPlayBtn"/> </div> ) } else { ytvid = ( <div className="msgMedia"> <iframe src={"https://www.youtube.com/embed/"+this.state.msgYoutube} onLoad={()=>{this.setState({ loaded: true })}} /> </div> ) } } if(this.state.innerHTML == '') { return (<div className="chatMessage" />); } return ( <div className="chatMessage"> <div className="chatImage" style={{ background: this.state.imbak }}> <div style={{ background: `url(${this.state.impath}) no-repeat center center` }}></div> </div> <div className="chatText"> <p><b>{name}</b></p> <span dangerouslySetInnerHTML={{ __html: this.state.innerHTML }} /> {this.state.msgImage != '' && <div className="msgMedia"> <img src={this.state.msgImage} onLoad={()=>{this.setState({ loaded: true })}}/> </div> } {this.state.msgVideo != '' && <div className="msgMedia"> <video src={this.state.msgVideo} onClick={(e)=>{ e.target.paused ? (e.target.play()) : (e.target.pause()); }} preload="auto" autoPlay="autoplay" muted="muted" loop="loop" onLoad={()=>{this.setState({ loaded: true })}} /> </div> } {this.state.msgYoutube != '' && this.state.msgYoutube != undefined && ytvid} </div> </div> ); } } export default Message;
packages/icons/src/dv/Windows.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function DvWindows(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M20.4 23.133H5.467v-12.8L20.4 8.2v14.933zm22.133 0H22.401V7.936L42.533 5v18.133zM20.4 24.867V39.8L5.467 37.667v-12.8H20.4zm22.133 0V43l-20.132-2.936V24.867h20.132z" /> </IconBase> ); } export default DvWindows;
src/Posts/Standardization/standardization.js
jasongforbes/jforbes.io
import React from 'react'; import PropTypes from 'prop-types'; import { InlineMath, BlockMath } from 'react-katex'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import { withStyles } from '@material-ui/core/styles'; import Highlight from '../../Highlight'; import styles from '../style'; import { getHelmet } from '../utilities'; import TimeSeries from './timeSeries'; import CustomizablePlot from './customizablePlot'; import AnimatedPlot from './animatedPlot'; import 'highlight.js/styles/ocean.css'; const Post = ({ classes, match }) => { const { helmet, title, date } = getHelmet(match.url); return ( <React.Fragment> {helmet} <React.Fragment> <Typography variant="h3">{title}</Typography> <Typography variant="subtitle1">{date}</Typography> <Typography variant="body1"> A common preprocessing step when operating on data is <em>standardization</em>. This is the procedure of making two data-sets comparable by removing any bias and normalizing the variance. This definition may seem arbitrary but the effect is quite easy to understand. </Typography> <Typography variant="body1"> Imagine you are working on speech recognition for home automation. The prototype device works while the production units have significant issues. The only difference between the units is the quality of the microphones. An expensive, but high quality, sensor is in the prototype. A more cost-effective sensor is in the production units. The specs are different and the training-set is exclusively generated by the expensive sensor. Can the change of sensor cause the issue? </Typography> <Typography variant="body1"> This is the kind of issue standardization solves. Visualizing the time series helps with conceptualizing the problem. </Typography> <Grid container spacing={0} className={classes.padding}> <Grid item xs={12} sm={5} md={6} xl={7}> <TimeSeries title="Prototype" /> </Grid> <Grid item xs={12} sm={7} md={6} xl={5}> <TimeSeries title="Production" bias={0.03} standardDeviation={0.4} /> </Grid> </Grid> <Typography variant="body1"> First notice that the low-cost sensor has an offset. The time-series recorded is non-zero, even at points of silence. This is an example of bias in the low-cost sensor, the effect of which is raising the value of each sample. In our speech-recognition example, bias is due to a flaw in the low-end sensor. For instance, there could be an added voltage between the reference ground and the sampling point. We can remove the bias by subtracting the average signal strength from the data. </Typography> <div className={classes.math}> <BlockMath math={ '\\begin{aligned}\ \\bar y &= \\bar x - {1 \\over N} \\sum_{i}^{N} x_i \\\\\ \\\\\ \\ &= \\bar x - \\mathrm{E}\\big[\\bar x\\big] \\\\\ \\end{aligned}' } /> </div> <Typography variant="body1"> The second effect is more subtle. The signal generated by the low-end sensor varies less than the original. This is due to the sensitivity of the sensor. In speech recognition, it means the speaker will need to be louder to generate a comparable signal. The data recorded by the high-end sensor has a higher variance. One way to correct for this is to divide both signals by their standard-deviation. </Typography> <div className={classes.math}> <BlockMath math={ '\\begin{aligned}\ \\bar y &= {\\bar x \\over \\sqrt{ {1 \\over N} \\sum_i^N(\\bar x - \\mathrm{E}\\big[\\bar x\\big])^2}} \\\\\ \\\\\ &= {\\bar x \\over \\sqrt{ \\mathrm{E}\\bigg[\\bar x - \\mathrm{E}\\big[\\bar x\\big]\\bigg]^2}} \\\\\ \\\\\ &= {\\bar x \\over \\sqrt{ \\mathrm{E}\\big[\\bar x^2\\big] - \\mathrm{E}\\big[\\bar x\\big]^2}} \\\\\ \\end{aligned}' } /> </div> <Typography variant="body1"> See how a change of bias or variance effects the signal. </Typography> <CustomizablePlot> <TimeSeries /> </CustomizablePlot> <Typography variant="body1"> All code in this post can be found on{' '} <a href="https://github.com/jasongforbes/jforbes.io/tree/master/src/Posts/Standardization"> GitHub </a> . </Typography> <Typography variant="h4">Environmental Causes</Typography> <Typography variant="body1"> The above example focuses on flaws in the sensor as a way to make this problem concrete. But a change in sensor is not the only reason a data-set requires normalization. For audio recordings, variance could be a symptom of a change in the environment. For instance, the addition of unwanted noise will create a change in signal variance. Similarly, as the speaker walks towards the sensor, the signal strength increases. </Typography> <Typography variant="body1"> As for bias, the electrical characteristics of a circuit change based on temporal factors. The electrical bias of a circuit could be dependent on the ambient temperature. This means the bias changes as the room heats and cools. It also means as the sensor&apos;s electronics generate heat, the bias will change. </Typography> <Typography variant="body1"> The end result is that the data requires continuous standardization. This is typically done in batches of <InlineMath math="M" /> samples. The application determines the window size <InlineMath math="M" />. </Typography> <Typography variant="body1"> Performing this running standardization will reduce the effect of environmental changes. As a result, this increases the effectiveness of machine-learning algorithms. </Typography> <AnimatedPlot /> <Typography variant="h4">A Naive Approach</Typography> <Typography variant="body1"> Below is a direct, yet inefficient, algorithm for windowed standardization. </Typography> <Highlight language="python"> def standardize(x, M):{'\n'} {' '}N = x.size{'\n'} {' '}out = np.zeros(N - M){'\n'} {' '}for i in range(0, N - M):{'\n'} {' '}out[i] = x[i] - np.mean(x[i:i + M]){'\n'} {' '}out[i] = out[i] / np.std(x[i:i + M]){'\n'} {' '}return out </Highlight> <Typography variant="body1"> This function is verbose and quite easy to understand. Unfortunately, this comes at the cost of efficiency. This naive approach has a complexity of <InlineMath math="O(NM)" />, where <InlineMath math="N" /> is the input data size and <InlineMath math="M" /> is the window size. When approaching a problem such as this, one of the first things to try is vectorization. Vectorization, in this case, can reduce the complexity to{' '} <InlineMath math="O(N)" /> and confers a host of other benefits. </Typography> <Typography variant="h4">Why Choose a Vectorized Implementation?</Typography> <Typography variant="body1"> Vectorizing an algorithm refers to operating uniformly across arrays. In other words, vectorizing an algorithm replaces <em>for loops</em> with optimized vector operations. These vectorized operations rely on the underlying linear-algebra library, such as BLAS. Optimized linear-algebra libraries provide the following benefits. </Typography> <Typography variant="h5">SIMD Instructions</Typography> <Typography variant="body1"> Modern processors have{' '} <a href="https://en.wikipedia.org/wiki/SIMD">Single Instruction, Multiple Data</a> (SIMD) instructions. These specialized instructions perform computations on a vector of data. A SIMD instruction loads a single operation (instruction) and a vector of data into an array of{' '} <a href="https://en.wikipedia.org/wiki/Arithmetic_logic_unit">Arithmetic Logic Units</a>{' '} (ALUs). SIMD allows for data-level parallelism that can provide enormous efficiency gains. This is in contrast to a traditional Single Instruction, Single Data (SISD) architectures. </Typography> <Typography variant="h5">Parallel Execution</Typography> <Typography variant="body1"> Vectorized operations can often exploit parallelism. Take, for instance, a vector dot-product. </Typography> <div className={classes.math}> <BlockMath math={'x = \\bar u^T \\bar v'} /> </div> <Typography variant="body1"> This is easily mapped into to two identical sub-problems. </Typography> <div className={classes.math}> <BlockMath math={ '\\begin{aligned}\ \\bar u &= \\begin{bmatrix} \ \\bar u_1 \\\\\ \\bar u_2 \\\\\ \\end{bmatrix} \\\\\ \\\\\ \\bar v &= \\begin{bmatrix} \ \\bar v_1 \\\\\ \\bar v_2 \\\\\ \\end{bmatrix}\\\\\ \\\\\ x_1 &= \\bar u_1^T \\bar v_1 \\\\\ \\\\\ x_2 &= \\bar u_2^T \\bar v_2 \\\\\ \\end{aligned}' } /> </div> <Typography variant="body1"> Combining the results of the sub problems gives the answer to the original query. </Typography> <div className={classes.math}> <BlockMath math="x = x_1 + x_2" /> </div> <Typography variant="body1"> The two sub-problems can be further divided to achieve the desired level or parallelism. This method, <a href="https://en.wikipedia.org/wiki/MapReduce">MapReduce</a>, is commonly exploited in vectorized operations. </Typography> <Typography variant="h5">Minimizing Cache Misses</Typography> <Typography variant="body1"> Fetching data from memory is a slow process. For this reason, processors cache data for fast access. This is common for operations that exhibit{' '} <a href="https://en.wikipedia.org/wiki/Locality_of_reference">sequential locality</a>. When accessing data at sequential addresses, the processor loads the entire block into the cache. This avoids repeating costly IO operations. </Typography> <Typography variant="body1"> Vectorized operations take advantage of sequential locality. For instance, take multiplying a{' '} <a href="https://en.wikipedia.org/wiki/Row-_and_column-major_order"> column-major matrix </a>{' '} by a scalar. A column-major matrix has each column stored in contiguous memory. To minimize cache misses, this function will iterate sequentially along the major axis. </Typography> <div className={classes.math}> <BlockMath math={ 'A = \\begin{bmatrix} \ a_{1,1} \\ a_{1,2} \\ a_{1,3} \\\\\ a_{2,1} \\ a_{2,2} \\ a_{2,3} \\\\\ a_{3,1} \\ a_{3,2} \\ a_{3,3} \\\\\ \\ldots \\\\\ \\end{bmatrix}' } /> </div> <Typography variant="body1"> For instance, if <InlineMath math="A" /> is a column-major matrix, then{' '} <InlineMath math="a_{2,1}" /> and <InlineMath math="a_{3,1}" /> are adjacent in memory. If the matrix <InlineMath math="A" /> has many rows, then <InlineMath math="a_{1,1}" /> and{' '} <InlineMath math="a_{1,2}" /> could be in different memory blocks. Iterating along the major axis minimizes the number of memory fetches. </Typography> <Typography variant="h4">A Vectorized Approach</Typography> <Typography variant="body1"> The first step of standardization is determining the mean of the vector. In the{' '} <em>windowed</em> approach, this is a{' '} <a href="https://en.wikipedia.org/wiki/Moving_average">moving average filter</a>. </Typography> <div className={classes.math}> <BlockMath math={ '\\begin{aligned} \ u_j &= {1 \\over M} \\sum_{i = j}^{M + j - 1} x_i \\\\\ \\\\\ &= {1 \\over M} \\bigg[ \\sum_{i}^{M + j - 1} x_i - \\sum_{i}^{j-1} x_i \\bigg] \\\\\ \\end{aligned}' } /> </div> <Typography variant="body1"> Note the similarity to the vectorized operation <em>cumulative-summation</em>. </Typography> <div className={classes.math}> <BlockMath math={'cumsum(\\bar x)_j = \\sum_{i}^{j} x_{i}'} /> </div> <Typography variant="body1"> Below is a vectorized implementation of the moving average filter. This implementation uses the cumulative-summation. </Typography> <Highlight language="python"> def moving_average(x, M):{'\n'} {' '}x_sum = np.cumsum(x){'\n'} {' '}return (x_sum[M:] - x_sum[:-M]) / float(M) </Highlight> <Typography variant="body1">A similar trick vectorizes the standard deviation.</Typography> <Highlight language="python"> def standard_deviation(x, M):{'\n'} {' '}x_sum = np.cumsum(x){'\n'} {' '}x_sq_sum = np.cumsum(np.square(x)){'\n'} {'\n'} {' '}mean = (x_sum[M:] - x_sum[:-M]) / float(M){'\n'} {' '}sq_mean = (x_sq_sum[M:] - x_sq_sum[:-M]) / float(M){'\n'} {' '}return np.sqrt(sq_mean - np.square(mean)) </Highlight> <Typography variant="body1"> Combine both definitions for our vectorized windowed standardization algorithm. </Typography> <Highlight language="python"> def standardize_vec(x, M):{'\n'} {' '}x_sum = np.cumsum(x){'\n'} {' '}x_sq_sum = np.cumsum(np.square(x)){'\n'} {'\n'} {' '}mean = (x_sum[M:] - x_sum[:-M]) / float(M){'\n'} {' '}sq_mean = (x_sq_sum[M:] - x_sq_sum[:-M]) / float(M){'\n'} {' '}std = np.sqrt(sq_mean - np.square(mean)){'\n'} {' '}return (x[:-M] - mean) / std </Highlight> <Typography variant="h4">Wrapping Up</Typography> <Typography variant="body1"> Below is the results from running the naive and vectorized algorithms on a vector of size 10000. In both cases, the window-size is 2048. The result is the average execution time from 50 iterations. </Typography> <Highlight language="bash"> 50 loops, best of 5: 11.53 sec per loop{' '}# standardize{'\n'} 50 loops, best of 5: 17.58 msec per loop # standardize_vec </Highlight> <Typography variant="body1"> There is a pitfall with the vectorized approach, and that is numerical error. The cumulative sum will sum together the entire vector, only to later get a subset of that summation. If the data has a wide range of values, the summation of large values may reduce the precision of the results. 32-bit floats can encode around 7 decimal digits of information. If the difference in values is near 7 decimal places, there will be numerical error. One solution is to use a larger floating point encoding (doubles / quads). That often comes with a significant slowdown in execution speed. </Typography> </React.Fragment> </React.Fragment> ); }; Post.propTypes = { classes: PropTypes.objectOf(PropTypes.string).isRequired, match: PropTypes.shape({ isExact: PropTypes.bool, path: PropTypes.string, url: PropTypes.string, }).isRequired, }; Post.defaultProps = {}; export default withStyles(styles)(Post);
services/client/public/js/auth/login.js
cpg1111/demo-maestro-app
'use strict'; import React from 'react' import Redux from 'redux' export class Login extends React.Component { constructor(props){ super(props); this.state = {}; } render(){ return ( <div> <form> <input type="email" name="email" placeholder="email"/> <input type="password" name="password" placeholder="password"/> <input type="submit" name="submit" value="submit"/> </form> </div> ); } }
src/components/common/icons/Company.js
chejen/GoodJobShare
import React from 'react'; /* eslint-disable */ const Company = (props) => ( <svg {...props} width="148" height="148" viewBox="0 0 148 148"> <g transform="translate(5)"> <path d="M48.4044336 147.763501L80.0395603 147.763501 80.0395603 114.790382 99.0548489 114.790382 99.0548489 147.763501 130.689976 147.763501 130.689976.137832061 48.4044336.137832061 48.4044336 147.763501zM95.3195511 17.5355522L114.33447 17.5355522 114.33447 36.9175267 95.3195511 36.9175267 95.3195511 17.5355522zM95.3195511 48.6852214L114.33447 48.6852214 114.33447 68.0671959 95.3195511 68.0671959 95.3195511 48.6852214zM95.3195511 79.8341374L114.33447 79.8341374 114.33447 99.216112 95.3195511 99.216112 95.3195511 79.8341374zM64.7595695 17.5355522L83.7744885 17.5355522 83.7744885 36.9175267 64.7595695 36.9175267 64.7595695 17.5355522zM64.7595695 48.6852214L83.7744885 48.6852214 83.7744885 68.0671959 64.7595695 68.0671959 64.7595695 48.6852214zM64.7595695 79.8341374L83.7744885 79.8341374 83.7744885 99.216112 64.7595695 99.216112 64.7595695 79.8341374zM0 147.763501L28.8013252 147.763501 28.8013252 117.744733 41.0177069 117.744733 41.0177069 13.3621781 0 13.3621781 0 147.763501zM14.8902046 29.201944L32.201887 29.201944 32.201887 46.847084 14.8902046 46.847084 14.8902046 29.201944zM14.8902046 57.5610789L32.201887 57.5610789 32.201887 75.2062188 14.8902046 75.2062188 14.8902046 57.5610789zM14.8902046 85.9194606L32.201887 85.9194606 32.201887 103.564601 14.8902046 103.564601 14.8902046 85.9194606z"/> </g> </svg> ); /* eslint-enable */ export default Company;
tools/kevoree-scripts/browser-tester/src/index.js
kevoree/kevoree-js
import React from 'react'; import ReactDOM from 'react-dom'; import ErrorUI from './components/Error'; import App from './components/App'; const params = decodeURI(window.location.search.substr(1)) .split('&') .reduce((params, value) => { const array = value.split('='); params[array[0]] = array[1]; return params; }, { model: 'kevlib.json', script: 'kevs/main.kevs' }); const root = document.getElementById('root'); fetch(`http://localhost:8080/app/${params.model}`) .then((res) => { return res.json(); }, () => { throw new Error(`Kevoree Browser Tester needs "${params.model}". Build your project with <pre><code>npm run build</code></pre> and refresh the page.`); }) .then((model) => { return fetch(`http://localhost:8080/app/${params.script}`) .then((res) => { if (res.status === 200) { return res.text(); } throw new Error(`Unable to find the KevScript file at "${params.script}"`); }, () => { throw new Error(`Kevoree Browser Tester needs a KevScript at "${params.script}". Create one and refresh the page.`); }) .then((script) => ({ model, script })); }) .then((params) => { ReactDOM.render(( <ErrorUI> <App {...params} /> </ErrorUI> ), root); }) .catch((err) => { ReactDOM.render(( <div className="container"> <div className="header"> <h2>Kevoree Browser Tester</h2> </div> <ErrorUI error={err} /> </div> ), root); });
src/interface/icons/Twitter.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; const Icon = ({ colored, ...other }) => ( <svg viewBox="0 0 300.00006 244.18703" className="icon" {...other}> <g transform="translate(-539.18 -568.86)"> <path d="m633.9 812.04c112.46 0 173.96-93.168 173.96-173.96 0-2.6463-0.0539-5.2806-0.1726-7.903 11.938-8.6302 22.314-19.4 30.498-31.66-10.955 4.8694-22.744 8.1474-35.111 9.6255 12.623-7.5693 22.314-19.543 26.886-33.817-11.813 7.0031-24.895 12.093-38.824 14.841-11.157-11.884-27.041-19.317-44.629-19.317-33.764 0-61.144 27.381-61.144 61.132 0 4.7978 0.5364 9.4646 1.5854 13.941-50.815-2.5569-95.874-26.886-126.03-63.88-5.2508 9.0354-8.2785 19.531-8.2785 30.73 0 21.212 10.794 39.938 27.208 50.893-10.031-0.30992-19.454-3.0635-27.69-7.6468-0.009 0.25652-0.009 0.50661-0.009 0.78077 0 29.61 21.075 54.332 49.051 59.934-5.1376 1.4006-10.543 2.1516-16.122 2.1516-3.9336 0-7.766-0.38716-11.491-1.1026 7.7838 24.293 30.355 41.971 57.115 42.465-20.926 16.402-47.287 26.171-75.937 26.171-4.929 0-9.7983-0.28036-14.584-0.84634 27.059 17.344 59.189 27.464 93.722 27.464" fill={colored ? '#1da1f2' : undefined} /> </g> </svg> ); Icon.propTypes = { colored: PropTypes.bool, }; Icon.defaultProps = { colored: false, }; export default Icon;
src/decorators/withViewport.js
JeffJin/jigsaw-puzzle
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 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, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = { width: 1366, height: 768 }; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = { width: window.innerWidth, height: window.innerHeight }; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? { width: window.innerWidth, height: window.innerHeight } : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({ viewport: value }); // eslint-disable-line react/no-set-state } }; } export default withViewport;
src/utils/ReactHelper.js
sk1981/react-header
import React from 'react'; import ObjectHelper from './ObjectHelper' export default { /** * Gets a lit of react children and appends the given properties * to each of them one by one * * Additionally takes addIndex attribute to add an index field * which denotes the index of the given child in the children array * * @param children * @param props * @param addIndex * @returns {*} */ addPropsToChildren(children, props, addIndex = false) { return React.Children.map(children, (child, index) => { const finalProps = addIndex ? ObjectHelper.assignProperties({}, props, {index: index}) : props; return React.cloneElement(child, finalProps) }); }, /** * Gets the main navigation object by appending isMainMenu Property * * @param navigationChild * @param originalProps * @returns {XML} */ getMainNav(navigationChild, originalProps) { const navListProps = ObjectHelper.assignProperties({}, originalProps, {isMainMenu: true}); return ( <nav role="navigation" key="nav" className="site-navigation"> {React.cloneElement(navigationChild, navListProps)} </nav> ); } }
docs/src/IntroductionPage.js
wjb12/react-bootstrap
import React from 'react'; import CodeExample from './CodeExample'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; const IntroductionPage = React.createClass({ render() { return ( <div> <NavMain activePage="introduction" /> <PageHeader title="Introduction" subTitle="The most popular front-end framework, rebuilt for React."/> <div className="container bs-docs-container"> <div className="row"> <div className="col-md-9" role="main"> <div className="bs-docs-section"> <p className="lead"> React-Bootstrap is a library of reuseable front-end components. You'll get the look-and-feel of Twitter Bootstrap, but with much cleaner code, via Facebook's React.js framework. </p> <p> Let's say you want a small button that says "Something", to trigger the function someCallback. If you were writing a native application, you might write something like: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `button(size=SMALL, color=GREEN, text="Something", onClick=someCallback)` } /> </div> <p> With the most popular web front-end framework, Twitter Bootstrap, you'd write this in your HTML: </p> <div className="highlight"> <CodeExample mode="htmlmixed" codeText={ `<button id="something-btn" type="button" class="btn btn-success btn-sm"> Something </button>` } /> </div> <p> And something like <code className="js"> $('#something-btn').click(someCallback); </code> in your Javascript. </p> <p> By web standards this is quite nice, but it's still quite nasty. React-Bootstrap lets you write this: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `<Button bsStyle="success" bsSize="small" onClick={someCallback}> Something </Button>` } /> </div> <p> The HTML/CSS implementation details are abstracted away, leaving you with an interface that more closely resembles what you would expect to write in other programming languages. </p> <h2>A better Bootstrap API using React.js</h2> <p> The Bootstrap code is so repetitive because HTML and CSS do not support the abstractions necessary for a nice library of components. That's why we have to write <code>btn</code> three times, within an element called <code>button</code>. </p> <p> <strong> The React.js solution is to write directly in Javascript. </strong> React takes over the page-rendering entirely. You just give it a tree of Javascript objects, and tell it how state is transmitted between them. </p> <p> For instance, we might tell React to render a page displaying a single button, styled using the handy Bootstrap CSS: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = React.DOM.button({ className: "btn btn-lg btn-success", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> But now that we're in Javascript, we can wrap the HTML/CSS, and provide a much better API: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = ReactBootstrap.Button({ bsStyle: "success", bsSize: "large", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> React-Bootstrap is a library of such components, which you can also easily extend and enhance with your own functionality. </p> <h3>JSX Syntax</h3> <p> While each React component is really just a Javascript object, writing tree-structures that way gets tedious. React encourages the use of a syntactic-sugar called JSX, which lets you write the tree in an HTML-like syntax: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var buttonGroupInstance = ( <ButtonGroup> <DropdownButton bsStyle="success" title="Dropdown"> <MenuItem key="1">Dropdown link</MenuItem> <MenuItem key="2">Dropdown link</MenuItem> </DropdownButton> <Button bsStyle="info">Middle</Button> <Button bsStyle="info">Right</Button> </ButtonGroup> ); React.render(buttonGroupInstance, mountNode);` } /> </div> <p> Some people's first impression of React.js is that it seems messy to mix Javascript and HTML in this way. However, compare the code required to add a dropdown button in the example above to the <a href="http://getbootstrap.com/javascript/#dropdowns"> Bootstrap Javascript</a> and <a href="http://getbootstrap.com/components/#btn-dropdowns"> Components</a> documentation for creating a dropdown button. The documentation is split in two because you have to implement the component in two places in your code: first you must add the HTML/CSS elements, and then you must call some Javascript setup code to wire the component together. </p> <p> The React-Bootstrap component library tries to follow the React.js philosophy that a single piece of functionality should be defined in a single place. View the current React-Bootstrap library on the <a href="/components.html">components page</a>. </p> </div> </div> </div> </div> <PageFooter /> </div> ); } }); export default IntroductionPage;
src/views/components/formatted-volume/formatted-volume.js
r-park/soundcloud-redux
import React from 'react'; import PropTypes from 'prop-types'; function FormattedVolume({value = 0}) { if (!value) { value = '0.0'; } else { value /= 10; let precision = value >= 1 ? 2 : 1; value = value.toPrecision(precision); } return <span>{value}</span>; } FormattedVolume.propTypes = { value: PropTypes.number }; export default FormattedVolume;
examples/mobx/src/Counter.js
gaearon/react-hot-loader
import React, { Component } from 'react'; import { hot } from 'react-hot-loader'; import { observer } from 'mobx-react'; import { observable } from 'mobx'; class Counter extends React.Component { state = { count: Math.round(Math.random() * 1000) }; componentDidMount() { //this.interval = setInterval(this.increment, 200) } componentWillUnmount() { clearInterval(this.interval); } increment = () => { this.setState(prevState => ({ count: prevState.count + 1 })); }; render() { return this.state.count; } } class Comp extends Component { state = { obsObj: null, }; static getDerivedStateFromProps(nextProps, prevState) { return { obsObj: nextProps.obsObj }; } componentDidMount() { //setInterval(() => this.setState({update: 1}), 5000); } render() { const { prop1 } = this.state.obsObj || {}; return ( <div style={{ border: '10px solid red' }}> {prop1} <Counter /> </div> ); } } const ObsComp = observer(Comp); class App extends Component { @observable obj = { prop1: 'Example', }; render() { return ( <div> <ObsComp obsObj={this.obj} /> </div> ); } } export default App;
src/app/components/shell/index.js
drivesense/server
'use strict'; import React from 'react'; import {connect} from 'react-redux'; import AppBar from './AppBar'; import LeftNav from './LeftNav'; import * as leftNav from './redux'; import {logout, hasRole} from '../../auth/redux'; const flex = { flex: 1, display: 'flex', boxSizing: 'border-box', flexDirection: 'column' }; const content = { flex: 1, display: 'flex', flexDirection: 'column' }; @connect(state => ({leftNav: state.leftNav, user: state.auth.user}), Object.assign({}, leftNav, {logout})) export default class Shell extends React.Component { render() { return ( <div style={flex}> <AppBar toggle={this.props.toggle}/> <LeftNav isOpen={this.props.leftNav.isOpen} user={this.props.user} toggle={this.props.toggle} logout={this.props.logout} redirect={this.props.redirect} hasRole={hasRole}/> <div style={content}> {this.props.children} </div> </div> ); } }
client/views/room/contextualBar/Call/Jitsi/components/CallModal.js
VoiSmart/Rocket.Chat
import { Box, Button, ButtonGroup, Icon, Modal } from '@rocket.chat/fuselage'; import React from 'react'; import { useTranslation } from '../../../../../../contexts/TranslationContext'; export const CallModal = ({ handleYes, handleCancel }) => { const t = useTranslation(); return ( <Modal> <Modal.Header> <Modal.Title>{t('Video_Conference')}</Modal.Title> <Modal.Close onClick={handleCancel} /> </Modal.Header> <Modal.Content display='flex' flexDirection='column' alignItems='center'> <Icon name='modal-warning' size='x128' color='warning-500' /> <Box fontScale='s1'>{t('Start_video_call')}</Box> </Modal.Content> <Modal.Footer> <ButtonGroup align='end'> <Button onClick={handleCancel}>{t('Cancel')}</Button> <Button primary onClick={handleYes}> {t('Yes')} </Button> </ButtonGroup> </Modal.Footer> </Modal> ); }; export default CallModal;
news/routes/index.js
HKuz/FreeCodeCamp
import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import Show from './Show'; import Featured from './Featured'; export const routes = [ <Route component={Featured} exact={true} path='/' />, <Route exact={true} path='/:username' render={() => <Redirect to='/' />} />, <Route component={Show} path='/:username/:slug' /> ].map(el => ({ ...el, key: el.props.path })); // <Route component={EditArticle} path='/new' />
frontend/landing_page/src/pages/NotFound/index.js
linea-it/dri
/* eslint-disable max-len */ import React from 'react'; import { Grid, Container, Typography, Breadcrumbs, Link, IconButton, } from '@material-ui/core'; import { YouTube, Twitter, GitHub } from '@material-ui/icons'; import styles from './styles'; function AboutUs() { const handlerClick = (socialMedia) => { let uri = ''; switch (socialMedia) { case 'YouTube': uri = 'https://www.youtube.com/user/lineamcti'; break; case 'Twitter': uri = 'https://twitter.com/LIneA_mcti'; break; case 'GitHub': uri = 'https://github.com/linea-it/dri'; break; default: uri = 'https://www.youtube.com/user/lineamcti'; } window.open(uri, '_blank'); }; const classes = styles(); return ( <div className={classes.initContainer}> <Container> <Grid item xs={12} > <Breadcrumbs aria-label="breadcrumb"> <Link color="inherit" href="/"> Home </Link> <Typography color="textPrimary">Not Found</Typography> </Breadcrumbs> <> <div className={classes.notfound}> <Typography variant="h1" className={classes.title}>404</Typography> <Typography variant="h2" className={classes.subTitle}> Oops! Nothing was found </Typography> <Typography variant="subtitle1" className={classes.description}> The page you are looking for might have been removed, had its name changed or is temporarily unavailable. {' '} <Link color="inherit" className={classes.returnPage} href="/">Return to homepage</Link> </Typography> <> <IconButton className={classes.icon} onClick={() => { handlerClick('Youtube'); }} color="inherit" aria-label="YouTube" component="span" > <YouTube /> </IconButton> <IconButton className={classes.icon} onClick={() => { handlerClick('Twitter'); }} color="inherit" aria-label="Twitter" component="span" > <Twitter /> </IconButton> <IconButton className={classes.icon} onClick={() => { handlerClick('GitHub'); }} color="inherit" aria-label="GitHub" component="span" > <GitHub /> </IconButton> </> </div> </> </Grid> </Container> </div> ); } export default AboutUs;
src/TimeSlot.js
mitul45/ta-calendar
import React from 'react'; import Utils from './Utils'; import ReactDOM from 'react-dom'; var TimeSlot = React.createClass({ getInitialState() { return { taskName: this.props.timeSlot.taskName, editable: false, } }, /** * Format a slot object to human readable time. * @param {Object} slot * @returns {String} */ formatSlot(slot) { return Utils.formatTime(slot.startTime); }, deleteTask() { this.props.deleteTask(this.props.timeSlot); }, handleCheckboxChange(event) { this.props.completeTask(this.props.timeSlot, event.target.checked); }, /** * Mark this slot as editable, and show input field. */ handleDoubleClick() { this.setState({ editable: true, newTask: this.props.timeSlot.taskName, }) }, /** * Keep view and state in sync */ handleTextChange(event) { this.setState({ newTask: event.target.value, }) }, /** * Save task on enter and restore to previous on esc. */ handleKeyDown(event) { if (event.keyCode === 13 ) { this.createTask(this.state.newTask); } else if (event.keyCode === 27) { this.setState({ editable: false, }) } }, /** * create task in parent scope. * @param {any} taskName */ createTask(taskName) { this.props.createTask(this.props.timeSlot, taskName); this.setState({ editable: false, }) }, render() { return ( <tr className={this.props.timeSlot.active? 'time-slot--active': ''}> <td> { this.formatSlot(this.props.timeSlot.slot) } </td> <td className={this.props.timeSlot.done ? 'time-slot__task time-slot__task--done' : 'time-slot__task'} onDoubleClick={this.handleDoubleClick} > { this.props.timeSlot.taskName ? <input type="checkbox" checked={this.props.timeSlot.done} onChange={this.handleCheckboxChange} /> : null } <span className='time-slot__task__name'> { this.state.editable ? <input autoFocus className='time-slot__task__name--input' type='text' value={this.state.newTask} onKeyDown={this.handleKeyDown} onChange={this.handleTextChange} /> : this.props.timeSlot.taskName } </span> { this.props.timeSlot.taskName !== '' ? <button className='time-slot__remove-btn' type='button' onClick={this.deleteTask}> Remove </button> : null } </td> </tr> ) } }) export default TimeSlot;
ui/js/header/index.js
beni55/spigo
'use strict'; import React from 'react'; export default React.createClass({ render () { return ( <header id="header"> <div className="branding"> <h1> SIMIANVIZ </h1> </div> </header> ); } });