path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
example/examples/LoadingMap.js
ksincennes/react-native-maps
import React from 'react'; import { Text, View, Dimensions, StyleSheet, } from 'react-native'; import MapView from 'react-native-maps'; import flagImg from './assets/flag-blue.png'; const { width, height } = Dimensions.get('window'); const ASPECT_RATIO = width / height; const LATITUDE = 37.78825; const LONGITUDE = -122.4324; const LATITUDE_DELTA = 0.0922; const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO; const SPACE = 0.01; class LoadingMap extends React.Component { constructor(props) { super(props); this.state = { region: { latitude: LATITUDE, longitude: LONGITUDE, latitudeDelta: LATITUDE_DELTA, longitudeDelta: LONGITUDE_DELTA, }, }; } render() { return ( <View style={styles.container}> <MapView provider={this.props.provider} style={styles.map} initialRegion={this.state.region} onPress={this.onMapPress} loadingEnabled loadingIndicatorColor="#666666" loadingBackgroundColor="#eeeeee" > <MapView.Marker coordinate={{ latitude: LATITUDE + SPACE, longitude: LONGITUDE + SPACE, }} centerOffset={{ x: -18, y: -60 }} anchor={{ x: 0.69, y: 1 }} image={flagImg} /> <MapView.Marker coordinate={{ latitude: LATITUDE - SPACE, longitude: LONGITUDE - SPACE, }} centerOffset={{ x: -42, y: -60 }} anchor={{ x: 0.84, y: 1 }} > <MapView.Callout> <View> <Text>This is a plain view</Text> </View> </MapView.Callout> </MapView.Marker> </MapView> <View style={styles.buttonContainer}> <View style={styles.bubble}> <Text>Map with Loading</Text> </View> </View> </View> ); } } LoadingMap.propTypes = { provider: MapView.ProviderPropType, }; const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, justifyContent: 'flex-end', alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject, }, bubble: { backgroundColor: 'rgba(255,255,255,0.7)', paddingHorizontal: 18, paddingVertical: 12, borderRadius: 20, }, buttonContainer: { flexDirection: 'row', marginVertical: 20, backgroundColor: 'transparent', }, }); module.exports = LoadingMap;
app/App.js
pro-react/react-app-boilerplate
import React, { Component } from 'react'; import {render} from 'react-dom'; class App extends Component { render(){ return ( <h1>Hello World</h1> ); } } render(<App />, document.getElementById('root'));
client/app/Core/MultiSelectDropDown/index.js
puja1234/DTA
/** * Created by saubhagya on 1/8/17. */ import React, { Component } from 'react'; import TtnButton from 'core/Button/btn'; class MultiSelectDropdown extends Component{ constructor(){ super(); } render(){ return( <div> {this.props.newCollab.map((item, index) => { return ( <div key={index}> {item} <TtnButton iconButton level = "primary" rounded icon = "glyphicon glyphicon-remove" onClick={(event) => this.props.onDeleteCollab(item)}/> </div> ) })} <div> <select value={this.props.title} onChange={(event) => {this.props.onSelectedVal(event.target.value)}}> <option>Select</option> {this.props.collabArray.map((item, index) => { return (<option value={item} key={index}>{item}</option>) })} </select> </div> </div> ); } } export default MultiSelectDropdown; //Earlier in place of <TtnButton/> we had the following code... :- /*<button key={index} value={item} onClick={(event) => this.props.onDeleteCollab(item)}>{item} <span className="glyphicon glyphicon-remove"></span> </button>*/
web/src/components/SimpleReport.js
Ding-Jun/Analysis
import React from 'react'; import { Link } from 'react-router' import { Card, Row, Col } from 'antd'; var RANK_LOW=0; var RANK_MEDIUM=3; var RANK_HIGH=5; class SimpleReport extends React.Component{ handleClick(e){ e.preventDefault(); console.log(this.props.id) } render(){ var rankCls; switch (this.props.rank){ case RANK_LOW:rankCls='red lighten-5';break; case RANK_MEDIUM:rankCls='orange lighten-5';break; case RANK_HIGH:rankCls='light-green lighten-5';break; default:break; } var layout={ xs:24, sm:12 } return ( <Card key={this.props.id} className={rankCls} title={this.props.reportName} bordered={true} extra={<Link to={'/report/'+this.props.id}>更多</Link>} > <Row> <Col {...layout}> <p>良率: {this.props.passPercent}</p> <p>测试工程师: {this.props.testMan}</p> </Col> <Col {...layout} > <p>测试数量: {this.props.testCount}</p> <p>时间: {this.props.time}</p> </Col> </Row> </Card> ) } } export default SimpleReport;
packages/react-scripts/fixtures/kitchensink/src/features/webpack/ImageInclusion.js
xiaohu-developer/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React from 'react' import tiniestCat from './assets/tiniest-cat.jpg' export default () => ( <img id="feature-image-inclusion" src={tiniestCat} alt="tiniest cat" /> )
src/pages/julia-plus.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Julia Plus' /> )
app/index.js
atomixinteractions/material-theme-generator
import React from 'react' import ReactDOM from 'react-dom' import RedBox from 'redbox-react' import { AppContainer } from 'react-hot-loader' import RootComponent from './root' import baseStyles from './styles' const rootPoint = document.createElement('div') document.body.insertBefore(rootPoint, document.body.firstChild) const link = document.createElement('link') link.rel = 'stylesheet' link.href = 'https://fonts.googleapis.com/css?family=Noto+Sans:300,400,600,700&subset=cyrillic' document.head.insertBefore(link, document.head.getElementsByTagName('title')[0]) baseStyles() const render = Root => { try { ReactDOM.render(( <AppContainer> <Root /> </AppContainer> ), rootPoint) } catch(e) { ReactDOM.render(<RedBox error={e} />, rootPoint) } } render(RootComponent) if (module.hot) { module.hot.accept('./root', () => { const NewApp = require('./root').default render(NewApp) }) }
components/date_picker/DatePicker.js
showings/react-toolbox
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { themr } from 'react-css-themr'; import { DATE_PICKER } from '../identifiers'; import events from '../utils/events'; import time from '../utils/time'; import InjectIconButton from '../button/IconButton'; import InjectInput from '../input/Input'; import InjectDialog from '../dialog/Dialog'; import calendarFactory from './Calendar'; import datePickerDialogFactory from './DatePickerDialog'; const factory = (Input, DatePickerDialog) => { class DatePicker extends Component { static propTypes = { active: PropTypes.bool, autoOk: PropTypes.bool, cancelLabel: PropTypes.string, className: PropTypes.string, disabledDates: PropTypes.arrayOf(PropTypes.instanceOf(Date)), enabledDates: PropTypes.arrayOf(PropTypes.instanceOf(Date)), error: PropTypes.string, icon: PropTypes.oneOfType([ PropTypes.string, PropTypes.element, ]), inputClassName: PropTypes.string, inputFormat: PropTypes.func, label: PropTypes.string, locale: PropTypes.oneOfType([ PropTypes.string, PropTypes.object, ]), maxDate: PropTypes.instanceOf(Date), minDate: PropTypes.instanceOf(Date), name: PropTypes.string, okLabel: PropTypes.string, onChange: PropTypes.func, onClick: PropTypes.func, onDismiss: PropTypes.func, onEscKeyDown: PropTypes.func, onKeyPress: PropTypes.func, onOverlayClick: PropTypes.func, readonly: PropTypes.bool, sundayFirstDayOfWeek: PropTypes.bool, theme: PropTypes.shape({ container: PropTypes.string, input: PropTypes.string, }), value: PropTypes.oneOfType([ PropTypes.instanceOf(Date), PropTypes.string, ]), }; static defaultProps = { active: false, locale: 'en', sundayFirstDayOfWeek: false, }; state = { active: this.props.active, }; componentWillReceiveProps(nextProps) { if (nextProps.active !== this.props.active && this.state.active !== nextProps.active) { this.setState({ active: nextProps.active }); } } handleDismiss = () => { this.setState({ active: false }); if (this.props.onDismiss) { this.props.onDismiss(); } }; handleInputFocus = (event) => { events.pauseEvent(event); this.setState({ active: true }); }; handleInputBlur = (event) => { events.pauseEvent(event); this.setState({ active: false }); }; handleInputClick = (event) => { events.pauseEvent(event); this.setState({ active: true }); if (this.props.onClick) this.props.onClick(event); }; handleInputKeyPress = (event) => { if (event.charCode === 13) { events.pauseEvent(event); this.setState({ active: true }); } if (this.props.onKeyPress) this.props.onKeyPress(event); }; handleSelect = (value, event) => { if (this.props.onChange) this.props.onChange(value, event); this.setState({ active: false }); }; render() { const { active, onDismiss,// eslint-disable-line autoOk, cancelLabel, enabledDates, disabledDates, inputClassName, inputFormat, locale, maxDate, minDate, okLabel, onEscKeyDown, onOverlayClick, readonly, sundayFirstDayOfWeek, value, ...others } = this.props; const finalInputFormat = inputFormat || time.formatDate; const date = Object.prototype.toString.call(value) === '[object Date]' ? value : undefined; const formattedDate = date === undefined ? '' : finalInputFormat(value, locale); return ( <div data-react-toolbox="date-picker" className={this.props.theme.container}> <Input {...others} className={classnames(this.props.theme.input, { [inputClassName]: inputClassName })} disabled={readonly} error={this.props.error} icon={this.props.icon} label={this.props.label} name={this.props.name} onFocus={this.handleInputFocus} onKeyPress={this.handleInputKeyPress} onClick={this.handleInputClick} readOnly type="text" value={formattedDate} /> <DatePickerDialog active={this.state.active} autoOk={autoOk} cancelLabel={cancelLabel} className={this.props.className} disabledDates={disabledDates} enabledDates={enabledDates} locale={locale} maxDate={maxDate} minDate={minDate} name={this.props.name} onDismiss={this.handleDismiss} okLabel={okLabel} onEscKeyDown={onEscKeyDown || this.handleDismiss} onOverlayClick={onOverlayClick || this.handleDismiss} onSelect={this.handleSelect} sundayFirstDayOfWeek={sundayFirstDayOfWeek} theme={this.props.theme} value={date} /> </div> ); } } return DatePicker; }; const Calendar = calendarFactory(InjectIconButton); const DatePickerDialog = datePickerDialogFactory(InjectDialog, Calendar); const DatePicker = factory(InjectInput, DatePickerDialog); export default themr(DATE_PICKER)(DatePicker); export { DatePickerDialog, factory as datePickerFactory, }; export { Calendar }; export { DatePicker };
src/app/components/EthernetConnection.js
UrgBenri/UrgBenriWeb
import React from 'react'; import Paper from 'material-ui/Paper'; import TextField from 'material-ui/TextField'; import IconButton from 'material-ui/IconButton'; import ActionLabelOutline from 'material-ui/svg-icons/action/label-outline'; import ActionLabel from 'material-ui/svg-icons/action/label'; import Subheader from 'material-ui/Subheader'; const styles = { paper: { margin: 5, padding: 5, }, container: { display: 'flex', flexDirection: 'row', alignItems: 'center' }, textField: { flexGrow: 2 }, iconButton: { flexGrow: 1 } }; class EthernetConnection extends React.Component { constructor(props) { super(props) this.state = { connected: false, }; this.handleConnect = this.handleConnect.bind(this); this.handleDisconnect = this.handleDisconnect.bind(this); } handleConnect() { this.setState({ connected: false }); } handleDisconnect() { this.setState({ connected: true }); } handleConnected() { } render() { return ( <Paper style={styles.paper} zDepth={2} > <div style={styles.container}> <TextField ref={(input) => { this.textInput = input; }} style={styles.textField} hintText="192.168.0.10" floatingLabelText="IP Address" /> <IconButton style={styles.iconButton} > {this.state.connected ? (<ActionLabel onClick={this.handleConnect} />) : (<ActionLabelOutline onClick={this.handleDisconnect} />)} </IconButton> </div> </Paper> ) } } export default EthernetConnection;
client/node_modules/uu5g03/doc/main/server/public/data/source/uu5-bricks-tree.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import {BaseMixin, ElementaryMixin, ContentMixin} from './../common/common.js'; import List from './tree-list.js'; import Item from './tree-item.js'; import './tree.less'; export const Tree = React.createClass({ //@@viewOn:mixins mixins: [ BaseMixin, ElementaryMixin, ContentMixin ], //@@viewOff:mixins //@@viewOn:statics statics: { tagName: 'UU5.Bricks.Tree', classNames: { main: 'uu5-bricks-tree' }, defaults: { childTagName: 'UU5.Bricks.Tree.Item' } }, //@@viewOff:statics //@@viewOn:propTypes propTypes: { items: React.PropTypes.array, glyphiconExpanded: React.PropTypes.string, glyphiconCollapsed: React.PropTypes.string }, //@@viewOff:propTypes //@@viewOn:getDefaultProps getDefaultProps: function () { return { items: null, glyphiconExpanded: 'uu-glyphicon-minus', glyphiconCollapsed: 'uu-glyphicon-plus' }; }, //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle //@@viewOff:standardComponentLifeCycle //@@viewOn:interface //@@viewOff:interface //@@viewOn:overridingMethods //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers //@@viewOff:componentSpecificHelpers //@@viewOn:render render: function () { return ( <List {...this.getMainPropsToPass()} items={this.props.items || this.getChildren()} glyphiconExpanded={this.props.glyphiconExpanded} glyphiconCollapsed={this.props.glyphiconCollapsed} > {this.props.children && React.Children.toArray(this.props.children)} {this.getDisabledCover()} </List> ); } //@@viewOff:render }); Tree.List = List; Tree.Item = Item; export default Tree;
fields/types/relationship/RelationshipColumn.js
kwangkim/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/src/components/ItemsTableCell'; import ItemsTableValue from '../../../admin/src/components/ItemsTableValue'; const moreIndicatorStyle = { color: '#bbb', fontSize: '.8rem', fontWeight: 500, marginLeft: 8, }; var RelationshipColumn = React.createClass({ displayName: 'RelationshipColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderMany (value) { if (!value || !value.length) return; let refList = this.props.col.field.refList; let items = []; for (let i = 0; i < 3; i++) { if (!value[i]) break; if (i) { items.push(<span key={'comma' + i}>, </span>); } items.push( <ItemsTableValue interior truncate={false} key={'anchor' + i} href={'/keystone/' + refList.path + '/' + value[i].id}> {value[i].name} </ItemsTableValue> ); } if (value.length > 3) { items.push(<span key="more" style={moreIndicatorStyle}>[...{value.length - 3} more]</span>); } return ( <ItemsTableValue field={this.props.col.type}> {items} </ItemsTableValue> ); }, renderValue (value) { if (!value) return; let refList = this.props.col.field.refList; return ( <ItemsTableValue href={'/keystone/' + refList.path + '/' + value.id} padded interior field={this.props.col.type}> {value.name} </ItemsTableValue> ); }, render () { let value = this.props.data.fields[this.props.col.path]; let many = this.props.col.field.many; return ( <ItemsTableCell> {many ? this.renderMany(value) : this.renderValue(value)} </ItemsTableCell> ); } }); module.exports = RelationshipColumn;
examples/js/column-filter/date-filter-programmatically.js
rolandsusans/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-unused-vars: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; const startDate = new Date(2015, 0, 1); const endDate = new Date(); for (let i = 0; i < quantity; i++) { const date = new Date(startDate.getTime() + Math.random() * (endDate.getTime() - startDate.getTime())); const id = startId + i; products.push({ id: id, name: 'Item name ' + id, inStockDate: date }); } } addProducts(5); function dateFormatter(cell, row) { return `${('0' + cell.getDate()).slice(-2)}/${('0' + (cell.getMonth() + 1)).slice(-2)}/${cell.getFullYear()}`; } export default class ProgrammaticallyDateFilter extends React.Component { handleBtnClick = () => { this.refs.nameCol.applyFilter({ date: products[2].inStockDate, comparator: '=' }); } render() { return ( <div> <button onClick={ this.handleBtnClick } className='btn btn-default'>Click to apply select filter</button> <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn ref='nameCol' dataField='inStockDate' dataFormat={ dateFormatter } filter={ { type: 'DateFilter' } }>In Stock From</TableHeaderColumn> </BootstrapTable> </div> ); } }
src/shared/universal/components/App/Posts/Post/Post.js
DAppx/SharpReact
/* */ import React from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import * as FromState from '../../../../reducers'; function Post({ post }) { if (!post) { // Post hasn't been fetched yet. It would be better if we had a "status" // reducer attached to our posts which gave us a bit more insight, such // as whether the post is currently being fetched, or if the fetch failed. return null; } const { title, body } = post; return ( <div> <Helmet title={`Posts - ${title}`} /> <h1>{title}</h1> <div> {body} </div> <div> Foo </div> </div> ); } function mapStateToProps(state, { params: { id } }) { return { post: FromState.getPostById(state, id), }; } export default connect(mapStateToProps)(Post);
src/shared/views/plugins/Model3d/Model3d.js
in-depth/indepth-demo
import React from 'react' import styles from './Model3d.css' const Model3d = (props) => { return ( <div className={styles.holder}> <iframe width="100%" height="100%" src={props.url} frameBorder="0" allowFullScreen /> </div> ) } Model3d.propTypes = { url: React.PropTypes.string.isRequired, } export default Model3d
src/index.dev.js
ryanswapp/react-starter-template
import 'App/style/index'; import React from 'react'; import { render } from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import routes from 'config/routes.js'; import { createStore, compose, applyMiddleware, combineReducers } from 'redux'; import { Provider } from 'react-redux'; import thunkMiddleware from 'redux-thunk'; import { syncHistory, routeReducer } from 'react-router-redux'; import Actions from 'App/state/actions.js'; import Reducers from 'App/state/reducers.js'; import createSagaMiddleware from 'redux-saga'; import rootSaga from 'App/state/sagas.js'; import DevTools from 'config/DevTools.js'; import { reducer as formReducer } from 'redux-form'; const reducer = combineReducers(Object.assign({}, Reducers, { form: formReducer, routing: routeReducer })); const reduxRouterMiddleware = syncHistory(browserHistory); const sagaMiddleware = createSagaMiddleware(); let finalCreateStore = compose( applyMiddleware( thunkMiddleware, reduxRouterMiddleware, sagaMiddleware ), DevTools.instrument() )(createStore); const store = finalCreateStore(reducer); reduxRouterMiddleware.listenForReplays(store); sagaMiddleware.run(rootSaga); render( <Provider store={ store }> <div> <Router history={ browserHistory }> { routes } </Router> <DevTools /> </div> </Provider>, document.getElementById('app') );
monkey/monkey_island/cc/ui/src/components/attack/techniques/T1107.js
guardicore/monkey
import React from 'react'; import ReactTable from 'react-table'; import {renderMachineFromSystemData, ScanStatus} from './Helpers' import MitigationsComponent from './MitigationsComponent'; class T1107 extends React.Component { constructor(props) { super(props); } static renderDelete(status) { if (status === ScanStatus.USED) { return <span>Yes</span> } else { return <span>No</span> } } static getDeletedFileColumns() { return ([{ columns: [ { Header: 'Machine', id: 'machine', accessor: x => renderMachineFromSystemData(x._id.machine), style: {'whiteSpace': 'unset'} }, {Header: 'Path', id: 'path', accessor: x => x._id.path, style: {'whiteSpace': 'unset'}}, { Header: 'Deleted?', id: 'deleted', accessor: x => this.renderDelete(x._id.status), style: {'whiteSpace': 'unset'}, width: 160 }] }]) } render() { return ( <div> <div>{this.props.data.message_html}</div> <br/> {this.props.data.deleted_files.length !== 0 ? <ReactTable columns={T1107.getDeletedFileColumns()} data={this.props.data.deleted_files} showPagination={false} defaultPageSize={this.props.data.deleted_files.length} /> : ''} <MitigationsComponent mitigations={this.props.data.mitigations}/> </div> ); } } export default T1107;
client/components/todo-list.js
wbinnssmith/react-redo
import values from 'lodash/values'; import React from 'react'; import { connect } from 'react-redux'; import { pure } from 'recompose'; import Todo from './todo'; import { deleteTodo, toggleTodo, updateTodo } from '../modules/todos'; function stateToProps(state, props) { return { todos: values(state.todos).sort((a, b) => a.id - b.id), isEditing: state.ui.isEditing } } const dispatchToProps = { deleteTodo, toggleTodo, updateTodo } export class TodoList extends React.Component { render() { const { deleteTodo, isEditing, todos, toggleTodo, updateTodo } = this.props; return ( <ul className="TodoList"> {todos.map(todo => <Todo todo={todo} initialValues={todo} isEditing={isEditing} key={todo.id} formKey={`${todo.id}`} onDelete={() => deleteTodo(todo.id)} onToggle={() => toggleTodo(todo.id)} onSubmit={attrs => updateTodo(todo.id, attrs)} /> )} </ul> ); } } export default pure(connect(stateToProps, dispatchToProps)(TodoList));
frontend/src/Artist/Index/Overview/ArtistIndexOverviews.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { Grid, WindowScroller } from 'react-virtualized'; import ArtistIndexItemConnector from 'Artist/Index/ArtistIndexItemConnector'; import Measure from 'Components/Measure'; import dimensions from 'Styles/Variables/dimensions'; import getIndexOfFirstCharacter from 'Utilities/Array/getIndexOfFirstCharacter'; import hasDifferentItemsOrOrder from 'Utilities/Object/hasDifferentItemsOrOrder'; import ArtistIndexOverview from './ArtistIndexOverview'; import styles from './ArtistIndexOverviews.css'; // Poster container dimensions const columnPadding = parseInt(dimensions.artistIndexColumnPadding); const columnPaddingSmallScreen = parseInt(dimensions.artistIndexColumnPaddingSmallScreen); const progressBarHeight = parseInt(dimensions.progressBarSmallHeight); const detailedProgressBarHeight = parseInt(dimensions.progressBarMediumHeight); function calculatePosterWidth(posterSize, isSmallScreen) { const maxiumPosterWidth = isSmallScreen ? 192 : 202; if (posterSize === 'large') { return maxiumPosterWidth; } if (posterSize === 'medium') { return Math.floor(maxiumPosterWidth * 0.75); } return Math.floor(maxiumPosterWidth * 0.5); } function calculateRowHeight(posterHeight, sortKey, isSmallScreen, overviewOptions) { const { detailedProgressBar } = overviewOptions; const heights = [ posterHeight, detailedProgressBar ? detailedProgressBarHeight : progressBarHeight, isSmallScreen ? columnPaddingSmallScreen : columnPadding ]; return heights.reduce((acc, height) => acc + height, 0); } function calculatePosterHeight(posterWidth) { return posterWidth; } class ArtistIndexOverviews extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.state = { width: 0, columnCount: 1, posterWidth: 238, posterHeight: 238, rowHeight: calculateRowHeight(238, null, props.isSmallScreen, {}) }; this._grid = null; } componentDidUpdate(prevProps, prevState) { const { items, sortKey, overviewOptions, jumpToCharacter, scrollTop } = this.props; const { width, rowHeight } = this.state; if (prevProps.sortKey !== sortKey || prevProps.overviewOptions !== overviewOptions) { this.calculateGrid(); } if (this._grid && (prevState.width !== width || prevState.rowHeight !== rowHeight || hasDifferentItemsOrOrder(prevProps.items, items))) { // recomputeGridSize also forces Grid to discard its cache of rendered cells this._grid.recomputeGridSize(); } if (jumpToCharacter != null && jumpToCharacter !== prevProps.jumpToCharacter) { const index = getIndexOfFirstCharacter(items, jumpToCharacter); if (this._grid && index != null) { this._grid.scrollToCell({ rowIndex: index, columnIndex: 0 }); } } if (this._grid && scrollTop !== 0) { this._grid.scrollToPosition({ scrollTop }); } } // // Control setGridRef = (ref) => { this._grid = ref; } calculateGrid = (width = this.state.width, isSmallScreen) => { const { sortKey, overviewOptions } = this.props; const posterWidth = calculatePosterWidth(overviewOptions.size, isSmallScreen); const posterHeight = calculatePosterHeight(posterWidth); const rowHeight = calculateRowHeight(posterHeight, sortKey, isSmallScreen, overviewOptions); this.setState({ width, posterWidth, posterHeight, rowHeight }); } cellRenderer = ({ key, rowIndex, style }) => { const { items, sortKey, overviewOptions, showRelativeDates, shortDateFormat, longDateFormat, timeFormat, isSmallScreen } = this.props; const { posterWidth, posterHeight, rowHeight } = this.state; const artist = items[rowIndex]; if (!artist) { return null; } return ( <div key={key} style={style} > <ArtistIndexItemConnector key={artist.id} component={ArtistIndexOverview} sortKey={sortKey} posterWidth={posterWidth} posterHeight={posterHeight} rowHeight={rowHeight} overviewOptions={overviewOptions} showRelativeDates={showRelativeDates} shortDateFormat={shortDateFormat} longDateFormat={longDateFormat} timeFormat={timeFormat} isSmallScreen={isSmallScreen} artistId={artist.id} qualityProfileId={artist.qualityProfileId} metadataProfileId={artist.metadataProfileId} /> </div> ); } // // Listeners onMeasure = ({ width }) => { this.calculateGrid(width, this.props.isSmallScreen); } // // Render render() { const { items, isSmallScreen, scroller } = this.props; const { width, rowHeight } = this.state; return ( <Measure whitelist={['width']} onMeasure={this.onMeasure} > <WindowScroller scrollElement={isSmallScreen ? undefined : scroller} > {({ height, registerChild, onChildScroll, scrollTop }) => { if (!height) { return <div />; } return ( <div ref={registerChild}> <Grid ref={this.setGridRef} className={styles.grid} autoHeight={true} height={height} columnCount={1} columnWidth={width} rowCount={items.length} rowHeight={rowHeight} width={width} onScroll={onChildScroll} scrollTop={scrollTop} overscanRowCount={2} cellRenderer={this.cellRenderer} onSectionRendered={this.onSectionRendered} scrollToAlignment={'start'} isScrollingOptOut={true} /> </div> ); } } </WindowScroller> </Measure> ); } } ArtistIndexOverviews.propTypes = { items: PropTypes.arrayOf(PropTypes.object).isRequired, sortKey: PropTypes.string, overviewOptions: PropTypes.object.isRequired, scrollTop: PropTypes.number.isRequired, jumpToCharacter: PropTypes.string, scroller: PropTypes.instanceOf(Element).isRequired, showRelativeDates: PropTypes.bool.isRequired, shortDateFormat: PropTypes.string.isRequired, longDateFormat: PropTypes.string.isRequired, isSmallScreen: PropTypes.bool.isRequired, timeFormat: PropTypes.string.isRequired }; export default ArtistIndexOverviews;
packages/map-gl/src/overlays/GeoJSONLayer.expo.js
wq/wq.app
import React from 'react'; import PropTypes from 'prop-types'; import { Marker as RNMarker, Polyline as RNPolyline } from 'react-native-maps'; import { Colors } from 'react-native-paper'; import { useGeoJSON } from '@wq/map'; const COLOR_LIST = Object.values(Colors); export default function GeoJSONLayer({ id, data }) { data = useGeoJSON(data); const features = (data && data.features) || []; return ( <> {features.map(feature => ( <Feature key={feature.id} feature={{ ...feature, layer: { source: id } }} /> ))} </> ); } function makePoint([longitude, latitude]) { return { latitude, longitude }; } function makeLine(line) { return line.map(makePoint); } function Feature({ feature }) { if (feature.geometry.type === 'Point') { return ( <RNMarker pinColor={getColor(feature)} coordinate={makePoint(feature.geometry.coordinates)} /> ); } else if (feature.geometry.type === 'MultiLineString') { return ( <RNPolyline strokeColor={getColor(feature)} strokeWidth={8} coordinates={makeLine(feature.geometry.coordinates[0])} /> ); } else if (feature.geometry.type === 'Polygon') { return ( <RNPolyline strokeColor={getColor(feature)} fillColor={getColor(feature)} strokeWidth={8} coordinates={makeLine(feature.geometry.coordinates[0])} /> ); } else { return null; } } GeoJSONLayer.propTypes = { id: PropTypes.string, data: PropTypes.object }; const colors = {}; function getColor(feature) { const layerName = feature.layer.source; if (!colors[layerName]) { colors[layerName] = COLOR_LIST[Math.round(COLOR_LIST.length * Math.random())]; } return colors[layerName]; }
Redux-Weather/src/containers/searchBar.js
vivekbharatha/ModernReactWithReduxCourseUdemy
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchWeather } from './../actions/index'; class SearchBar extends Component { constructor(props){ super(props); this.state = { term: '' }; this.onInputChange = this.onInputChange.bind(this); this.onSearchFormSubmit = this.onSearchFormSubmit.bind(this); } render() { return ( <form className="input-group" onSubmit={this.onSearchFormSubmit}> <input className="form-control" placeholder="Grab 5 day forecast in any city" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Submit</button> </span> </form> ); } onInputChange(event) { this.setState({ term: event.target.value }); } onSearchFormSubmit(event) { event.preventDefault(); // Let's call OpenWeatherAPI here and nail it! this.props.fetchWeather(this.state.term); this.setState({ term: '' }); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar);
app/javascript/mastodon/features/list_editor/components/search.js
codl/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { defineMessages, injectIntl } from 'react-intl'; import { fetchListSuggestions, clearListSuggestions, changeListSuggestions } from '../../../actions/lists'; import classNames from 'classnames'; const messages = defineMessages({ search: { id: 'lists.search', defaultMessage: 'Search among people you follow' }, }); const mapStateToProps = state => ({ value: state.getIn(['listEditor', 'suggestions', 'value']), }); const mapDispatchToProps = dispatch => ({ onSubmit: value => dispatch(fetchListSuggestions(value)), onClear: () => dispatch(clearListSuggestions()), onChange: value => dispatch(changeListSuggestions(value)), }); @connect(mapStateToProps, mapDispatchToProps) @injectIntl export default class Search extends React.PureComponent { static propTypes = { intl: PropTypes.object.isRequired, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, }; handleChange = e => { this.props.onChange(e.target.value); } handleKeyUp = e => { if (e.keyCode === 13) { this.props.onSubmit(this.props.value); } } handleClear = () => { this.props.onClear(); } render () { const { value, intl } = this.props; const hasValue = value.length > 0; return ( <div className='list-editor__search search'> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.search)}</span> <input className='search__input' type='text' value={value} onChange={this.handleChange} onKeyUp={this.handleKeyUp} placeholder={intl.formatMessage(messages.search)} /> </label> <div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}> <i className={classNames('fa fa-search', { active: !hasValue })} /> <i aria-label={intl.formatMessage(messages.search)} className={classNames('fa fa-times-circle', { active: hasValue })} /> </div> </div> ); } }
app/containers/Merchant/index.js
theterra/newsb
import React from 'react'; import { connect } from 'react-redux'; import AuthStyle from './AuthStyle'; import BackgrndStyle from './BackgrndStyle'; import AuthForm from '../../components/AuthForm'; import CurveStyle from './CurveStyle'; import LogoStyles from './LogoStyles'; import LoadingStyle from './LoadingStyle'; import { loginRequest } from '../AuthPage/actions'; import Logo from './logo.png'; import Loading from './loading.gif'; class MerchantPage extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { const { formState, currentlySending, error } = this.props.data; return ( <BackgrndStyle> <CurveStyle> { !currentlySending ? <div className="ink-flex push-center"> <AuthStyle className="all-50"> <LogoStyles className="ink-flex push-center"> <img src={Logo} className="logo" alt="logo" /> </LogoStyles> <AuthForm data={formState} onSubmit={this.props.login} stateError={error} userRole={'CUSTOMER'} /> </AuthStyle> </div> : <LoadingStyle className="ink-flex push-center"> <img src={Loading} alt="loading" /> </LoadingStyle>} </CurveStyle> </BackgrndStyle> ); } } function mapDispatchToProps(dispatch) { return { login: (username, password, userRole) => { dispatch(loginRequest({ username, password, userRole })); } }; } function mapStateToProps(state) { const data = state.get('auth'); return { data, }; } export default connect(mapStateToProps, mapDispatchToProps)(MerchantPage);
examples/src/components/Contributors.js
MattMcFarland/react-select
import React from 'react'; import Select from 'react-select'; const CONTRIBUTORS = require('../data/contributors'); const MAX_CONTRIBUTORS = 6; const ASYNC_DELAY = 500; const Contributors = React.createClass({ displayName: 'Contributors', propTypes: { label: React.PropTypes.string, }, getInitialState () { return { multi: true, value: [CONTRIBUTORS[0]], }; }, onChange (value) { this.setState({ value: value, }); }, switchToMulti () { this.setState({ multi: true, value: [this.state.value], }); }, switchToSingle () { this.setState({ multi: false, value: this.state.value[0], }); }, getContributors (input, callback) { input = input.toLowerCase(); var options = CONTRIBUTORS.filter(i => { return i.github.substr(0, input.length) === input; }); var data = { options: options.slice(0, MAX_CONTRIBUTORS), complete: options.length <= MAX_CONTRIBUTORS, }; setTimeout(function() { callback(null, data); }, ASYNC_DELAY); }, gotoContributor (value, event) { window.open('https://github.com/' + value.github); }, render () { return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select.Async multi={this.state.multi} value={this.state.value} onChange={this.onChange} onValueClick={this.gotoContributor} valueKey="github" labelKey="name" loadOptions={this.getContributors} /> <div className="checkbox-list"> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.multi} onChange={this.switchToMulti}/> <span className="checkbox-label">Multiselect</span> </label> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={!this.state.multi} onChange={this.switchToSingle}/> <span className="checkbox-label">Single Value</span> </label> </div> <div className="hint">This example implements custom label and value properties, async options and opens the github profiles in a new window when values are clicked</div> </div> ); } }); module.exports = Contributors;
src/components/GameWrapper/GameWrapper.js
rainbowland302/hangman
import React from 'react'; import { Row, Col } from 'react-flexbox-grid'; import './GameWrapper.scss'; import WordChipContainer from '../../containers/WordChipContainer'; export const GameWrapper = (props) => { return ( <div id="gameContainer" className="game-wrapper"> <div className="row"> { Array(props.totalWordCount) .fill(true) .map((m, index) => <WordChipContainer key={index} targetId={index} />) } </div> </div> ); }; GameWrapper.propTypes = { totalWordCount: React.PropTypes.number.isRequired }; export default GameWrapper;
src/index.js
alpjs/alp-react-redux
import React from 'react'; import { renderToString } from 'react-dom/server'; import Helmet from 'react-helmet'; import reactTreeWalker from 'react-tree-walker'; import Logger from 'nightingale-logger/src'; import createIsModernBrowser from 'modern-browsers'; import htmlLayout from './layout/htmlLayout'; import createAlpAppWrapper from './createAlpAppWrapper'; import createServerStore from './store/createServerStore'; import createModuleVisitor from './module/createModuleVisitor'; import type { ReduxActionType } from './types'; export { Helmet }; export { combineReducers } from 'redux/src'; export { connect } from 'react-redux/src'; export * from './types'; export { createAction, createReducer, createLoader, classNames, createPureStatelessComponent, identityReducer, } from './utils/index'; export AlpModule from './module/AlpModule'; export AlpReduxModule from './module/AlpReduxModuleServer'; export Body from './layout/Body'; export AppContainer from './layout/AppContainer'; const logger = new Logger('alp:react-redux'); const renderHtml = (app, options) => { const content = renderToString(app); const helmet = Helmet.renderStatic(); return htmlLayout(helmet, content, options); }; const isModernBrowser = createIsModernBrowser(); type OptionsType = {| polyfillFeatures?: ?string, scriptName?: ?string | false, sharedReducers?: ?{ [string]: any }, styleName?: ?string | false, |}; export default () => app => { app.reduxReducers = {}; app.reduxMiddlewares = []; return { middleware: (ctx, next) => { ctx.reduxInitialContext = {}; return next(); }, createApp: (App, options: ?OptionsType = {}) => async ctx => { const version: string = ctx.config.get('version'); // TODO create alp-useragent with getter in context const ua = ctx.req.headers['user-agent']; const name = isModernBrowser(ua) ? 'modern-browsers' : 'es5'; const app = React.createElement(App); const moduleVisitor = createModuleVisitor(); const preRenderStore = { getState: () => ({ ctx }) }; const PreRenderWrappedApp = createAlpAppWrapper(app, { context: ctx, store: preRenderStore }); await reactTreeWalker(React.createElement(PreRenderWrappedApp), moduleVisitor.visitor); const store = createServerStore(ctx, moduleVisitor.getReducers(), { sharedReducers: options.sharedReducers, }); const WrappedApp = createAlpAppWrapper(app, { context: ctx, store }); // eslint-disable-next-line no-unused-vars const { ctx: removeCtxFromInitialData, ...initialData } = store.getState(); ctx.body = await renderHtml(React.createElement(WrappedApp), { version, scriptName: options.scriptName !== undefined ? options.scriptName : name, styleName: options.styleName !== undefined ? options.styleName : name, polyfillFeatures: options.polyfillFeatures, initialData, }); }, }; }; const loggerWebsocket = logger.child('websocket'); export function emitAction(to: string, action: ReduxActionType) { loggerWebsocket.debug('emitAction', action); to.emit('redux:action', action); }
client/routes.js
pandaben7890/react-panda-style-level-1
import React from 'react' import { Router, Route, IndexRoute, browserHistory } from 'react-router' import { App, Home, About } from './components' export default () => { return ( <Router history={browserHistory}> <Route path='/' component={App}> <IndexRoute component={Home} /> <Route path='about' component={About} /> </Route> </Router> ) }
src/actions/search.js
ello/webapp
import React from 'react' import * as ACTION_TYPES from '../constants/action_types' import * as MAPPING_TYPES from '../constants/mapping_types' import * as api from '../networking/api' import * as StreamRenderables from '../components/streams/StreamRenderables' import { ZeroState } from '../components/zeros/Zeros' export function searchForPosts(terms) { return { type: ACTION_TYPES.LOAD_STREAM, payload: { endpoint: api.searchPosts({ per_page: api.PER_PAGE, terms: encodeURIComponent(terms), }), }, meta: { mappingType: MAPPING_TYPES.POSTS, renderStream: { asGrid: StreamRenderables.postsAsGrid, asList: StreamRenderables.postsAsList, asZero: <ZeroState />, }, resultKey: '/search/posts', }, } } export function searchForUsers(terms) { return { type: ACTION_TYPES.LOAD_STREAM, payload: { endpoint: api.searchUsers({ per_page: api.PER_PAGE, terms: encodeURIComponent(terms), }), }, meta: { mappingType: MAPPING_TYPES.USERS, renderStream: { asGrid: StreamRenderables.usersAsGrid, asList: StreamRenderables.usersAsGrid, asZero: <ZeroState />, }, resultKey: '/search/users', }, } }
actor-apps/app-web/src/app/components/activity/UserProfile.react.js
mxw0417/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import ContactActionCreators from 'actions/ContactActionCreators'; import DialogActionCreators from 'actions/DialogActionCreators'; import PeerStore from 'stores/PeerStore'; import DialogStore from 'stores/DialogStore'; import AvatarItem from 'components/common/AvatarItem.react'; import UserProfileContactInfo from 'components/activity/UserProfileContactInfo.react'; const getStateFromStores = (userId) => { const thisPeer = PeerStore.getUserPeer(userId); return { thisPeer: thisPeer, isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer) }; }; var UserProfile = React.createClass({ propTypes: { user: React.PropTypes.object.isRequired }, mixins: [PureRenderMixin], getInitialState() { return getStateFromStores(this.props.user.id); }, componentWillMount() { DialogStore.addNotificationsListener(this.whenNotificationChanged); }, componentWillUnmount() { DialogStore.removeNotificationsListener(this.whenNotificationChanged); }, componentWillReceiveProps(newProps) { this.setState(getStateFromStores(newProps.user.id)); }, addToContacts() { ContactActionCreators.addContact(this.props.user.id); }, removeFromContacts() { ContactActionCreators.removeContact(this.props.user.id); }, onNotificationChange(event) { DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked); }, whenNotificationChanged() { this.setState(getStateFromStores(this.props.user.id)); }, render() { const user = this.props.user; const isNotificationsEnabled = this.state.isNotificationsEnabled; let addToContacts; if (user.isContact === false) { addToContacts = <a className="link__blue" onClick={this.addToContacts}>Add to contacts</a>; } else { addToContacts = <a className="link__red" onClick={this.removeFromContacts}>Remove from contacts</a>; } return ( <div className="activity__body profile"> <div className="profile__name"> <AvatarItem image={user.bigAvatar} placeholder={user.placeholder} size="medium" title={user.name}/> <h3>{user.name}</h3> </div> <div className="notifications"> <label htmlFor="notifications">Enable Notifications</label> <div className="switch pull-right"> <input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange} type="checkbox"/> <label htmlFor="notifications"></label> </div> </div> <UserProfileContactInfo phones={user.phones}/> <ul className="profile__list profile__list--usercontrols"> <li className="profile__list__item"> {addToContacts} </li> </ul> </div> ); } }); export default UserProfile;
src/index.js
sPyOpenSource/personal-website
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, hashHistory } from 'react-router'; import './index.css'; import Layout from './Layout'; import Home from './view/Home'; import About from './view/About'; import Media from './view/Media'; import Projects from './view/Projects'; import Game from './view/Game'; ReactDOM.render( <Router history={hashHistory}> <Route path="/" component={Layout}> <IndexRoute component={Home}></IndexRoute> <Route path="home" component={Home}></Route> <Route path="about" component={About}></Route> <Route path="media" component={Media}></Route> <Route path="projects" component={Projects}></Route> <Route path="game" component={Game}></Route> </Route> </Router>, document.getElementById('root') );
frontend/src/client/index.js
tsurupin/portfolio
import 'shared/styles/vendors'; import 'shared/styles/globals'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import useScroll from 'react-router-scroll'; import { createStore, applyMiddleware } from 'redux'; import routes from './routes'; import reducers from './reducers'; import injectTapEventPlugin from 'react-tap-event-plugin'; import thunk from 'redux-thunk'; const store = createStore(reducers, applyMiddleware(thunk)); injectTapEventPlugin(); ReactDOM.render( <Provider store={store}> <Router history={browserHistory} routes={routes} render={applyRouterMiddleware(useScroll())} /> </Provider> , document.querySelector('.container'));
docs/app/Examples/modules/Sidebar/SlideOut/index.js
Rohanhacker/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const SidebarVariationsExamples = () => ( <ExampleSection title='Slide Out'> <ComponentExample title='Left Slide Out' description='Sidebar attached to the left of the pushable container sliding out from the pusher.' examplePath='modules/Sidebar/SlideOut/SidebarExampleLeftSlideOut' /> <ComponentExample title='Right Slide Out' description='Sidebar attached to the right of the pushable container sliding out from the pusher.' examplePath='modules/Sidebar/SlideOut/SidebarExampleRightSlideOut' /> </ExampleSection> ) export default SidebarVariationsExamples
src/app/modules/HeaderBar/components/HeaderBar.js
toxzilla/app
import React from 'react'; import {connect} from 'cerebral-view-react'; import {classNames} from 'react-dom-stylesheet'; import {User} from './../../../common/User'; import {Badge, Button, ButtonGroup, Icon, Popover, PopoverControl, Text} from './../../../common/UserInterface'; import profile from './../../../store/computed/profile'; import {Profile} from './../../Profile'; import isCropAvatarDialogOpen from './../../Dialog/computed/isCropAvatarDialogOpen'; import {Notifications} from './../../Notifications'; import unreadNotifications from './../../Notifications/computed/unreadNotifications'; import {NetworkMonitor, Proxies} from './../../Network'; import isDHTOffline from './../../Network/computed/isDHTOffline'; export default connect({ isLoggingOut: 'store.app.isLoggingOut', isUpdatingProxies: 'store.app.isUpdatingProxies', isDHTConnecting: 'store.app.isDHTConnecting', connectionStatus: 'store.session.network.connectionStatus', profile: profile(), isCropAvatarDialogOpen: isCropAvatarDialogOpen(), isDHTOffline: isDHTOffline(), unreadNotifications: unreadNotifications() }, class HeaderBar extends React.Component { static displayName = 'HeaderBar' static propTypes = { signals: React.PropTypes.object.isRequired, isLoggingOut: React.PropTypes.bool.isRequired, isUpdatingProxies: React.PropTypes.bool.isRequired, isDHTConnecting: React.PropTypes.bool.isRequired, connectionStatus: React.PropTypes.number.isRequired, profile: React.PropTypes.object.isRequired, isCropAvatarDialogOpen: React.PropTypes.bool.isRequired, isDHTOffline: React.PropTypes.bool.isRequired, unreadNotifications: React.PropTypes.array.isRequired } state = { isProfileOpen: false } render () { const { isLoggingOut, isUpdatingProxies, isDHTConnecting, connectionStatus, profile, isCropAvatarDialogOpen, isDHTOffline, unreadNotifications } = this.props; const {isProfileOpen} = this.state; const totalUnreadNotifications = unreadNotifications.length; const hasUnreadNotifications = totalUnreadNotifications > 0; const notificationsPopoverClasses = classNames('notifications-popover', { unread: hasUnreadNotifications }); const notificationsLabel = Object.assign({}, { id: totalUnreadNotifications > 0 ? 'showUnreadNotifications' : 'showNotifications' }, hasUnreadNotifications ? {args: {count: totalUnreadNotifications}} : null); return ( <div className='header-bar' role='banner'> <Popover open={isProfileOpen} className='profile-popover' position='left' skippable={!isCropAvatarDialogOpen} onOpen={this._handleOpenProfile} onClose={this._handleCloseProfile}> <PopoverControl label={{id: 'showProfile', args: {nickname: profile.nickname ? profile.nickname : profile.address}}} tabIndex={0}> <User model={profile} connectionStatus={connectionStatus} showStatus={true} showNickname={false} showMessage={false}/> </PopoverControl> <Profile/> <div className='navigation'> <ButtonGroup> <Button title={{id: 'logout'}} disabled={isLoggingOut} onMouseUp={this._handleLogout} onKeyboardEnter={this._handleLogout} onKeyboardPress={this._handleLogout}> <Text l10n={{id: 'logout'}}/> </Button> <Button title={{id: 'settings'}} onMouseUp={this._handleSettings} onKeyboardEnter={this._handleSettings} onKeyboardPress={this._handleSettings}> <Text l10n={{id: 'settings'}}/> </Button> </ButtonGroup> </div> </Popover> <Popover className={notificationsPopoverClasses} onBeforeOpen={this._handleOnBeforeOpenNotifications} onClose={this._handleCloseNotifications}> <PopoverControl label={notificationsLabel} tabIndex={0}> <Icon iconName={hasUnreadNotifications ? 'notification' : 'notification_none'}/> <Badge count={totalUnreadNotifications}/> </PopoverControl> <Notifications ref='notifications' visible={true}/> </Popover> <Popover className='network'> <PopoverControl label={{id: 'showNetworkMonitor', args: {status: connectionStatus }}} tabIndex={0}> <Icon iconName={isDHTConnecting ? 'network_connecting' : isDHTOffline ? 'network_offline' : 'network_online'}/> </PopoverControl> <NetworkMonitor/> <Proxies/> <div className='navigation'> <ButtonGroup> <Button title={{id: 'addProxy'}} disabled={isUpdatingProxies} onMouseUp={this._handleAddProxy} onKeyboardEnter={this._handleAddProxy} onKeyboardPress={this._handleAddProxy}> <Text l10n={{id: 'addProxy'}}/> </Button> </ButtonGroup> </div> </Popover> </div> ); } _handleOpenProfile = () => { this.setState({ isProfileOpen: true }); } _handleCloseProfile = () => { this.setState({ isProfileOpen: false }); this.props.signals.profile.resetProfile(); } _handleLogout = () => { this.setState({ isProfileOpen: false }); this.props.signals.authenticate.logoutAccount(); } _handleSettings = () => { this.setState({ isProfileOpen: false }); this.props.signals.store.changeRoute({ route: 'settings' }); } _handleAddProxy = () => { this.props.signals.network.addProxy(); } _handleOnBeforeOpenNotifications = () => { if (this.refs.notifications.refs.scrollBar) { this.refs.notifications.refs.scrollBar.reset(); this.refs.notifications.refs.scrollBar.resize(); } } _handleCloseNotifications = () => { this.props.signals.notifications.unreadAllNotifications(); } });
app/main.js
firewenda/testwebsite
import React from 'react'; import Router from 'react-router'; import ReactDOM from 'react-dom'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import routes from './routes'; import Navbar from './components/Navbar'; let history = createBrowserHistory(); ReactDOM.render(<Router history={history}>{routes}</Router>, document.getElementById('app'));
src/RadioButton/RadioButtonGroup.js
rscnt/material-ui
import React from 'react'; import RadioButton from '../RadioButton'; import warning from 'warning'; class RadioButtonGroup extends React.Component { static propTypes = { /** * Should be used to pass `RadioButton` components. */ children: React.PropTypes.node, /** * The CSS class name of the root element. */ className: React.PropTypes.string, /** * The `value` property (case-sensitive) of the radio button that will be * selected by default. This takes precedence over the `checked` property * of the `RadioButton` elements. */ defaultSelected: React.PropTypes.string, /** * Where the label will be placed for all child radio buttons. * This takes precedence over the `labelPosition` property of the * `RadioButton` elements. */ labelPosition: React.PropTypes.oneOf(['left', 'right']), /** * The name that will be applied to all child radio buttons. */ name: React.PropTypes.string.isRequired, /** * Callback function that is fired when a radio button has * been checked. * * @param {object} event `change` event targeting the selected * radio button. * @param {string} value The `value` of the selected radio button. */ onChange: React.PropTypes.func, /** * Override the inline-styles of the root element. */ style: React.PropTypes.object, /** * The `value` of the currently selected radio button. */ valueSelected: React.PropTypes.string, }; static defaultProps = { style: {}, }; static contextTypes = { muiTheme: React.PropTypes.object.isRequired, }; state = { numberCheckedRadioButtons: 0, selected: this.props.valueSelected || this.props.defaultSelected || '', }; componentWillMount() { let cnt = 0; React.Children.forEach(this.props.children, (option) => { if (this.hasCheckAttribute(option)) cnt++; }, this); this.setState({numberCheckedRadioButtons: cnt}); } componentWillReceiveProps(nextProps) { if (nextProps.hasOwnProperty('valueSelected')) { this.setState({ selected: nextProps.valueSelected, }); } } hasCheckAttribute(radioButton) { return radioButton.props.hasOwnProperty('checked') && radioButton.props.checked; } updateRadioButtons(newSelection) { if (this.state.numberCheckedRadioButtons === 0) { this.setState({selected: newSelection}); } else { warning(false, `Cannot select a different radio button while another radio button has the 'checked' property set to true.`); } } handleChange = (event, newSelection) => { this.updateRadioButtons(newSelection); // Successful update if (this.state.numberCheckedRadioButtons === 0) { if (this.props.onChange) this.props.onChange(event, newSelection); } }; getSelectedValue() { return this.state.selected; } setSelectedValue(newSelectionValue) { this.updateRadioButtons(newSelectionValue); } clearValue() { this.setSelectedValue(''); } render() { const {prepareStyles} = this.context.muiTheme; const options = React.Children.map(this.props.children, (option) => { const { name, // eslint-disable-line no-unused-vars value, // eslint-disable-line no-unused-vars label, // eslint-disable-line no-unused-vars onCheck, // eslint-disable-line no-unused-vars ...other, } = option.props; return ( <RadioButton {...other} ref={option.props.value} name={this.props.name} key={option.props.value} value={option.props.value} label={option.props.label} labelPosition={this.props.labelPosition} onCheck={this.handleChange} checked={option.props.value === this.state.selected} /> ); }, this); return ( <div style={prepareStyles(Object.assign({}, this.props.style))} className={this.props.className} > {options} </div> ); } } export default RadioButtonGroup;
components/GroupRow.js
Jack3113/edtBordeaux
import React from 'react'; import { Text, TouchableHighlight, View } from 'react-native'; import PropTypes from 'prop-types'; import style from '../Style'; export default class GroupRow extends React.PureComponent { static propTypes = { cleanName: PropTypes.string.isRequired, color: PropTypes.string, fontColor: PropTypes.string, name: PropTypes.string.isRequired, sectionStyle: PropTypes.object, }; constructor(props) { super(props); this._onPress = this._onPress.bind(this); } _onPress(e) { requestAnimationFrame(() => { this.props.openGroup(this.props.name); }); } render() { return ( <TouchableHighlight onPress={this._onPress} underlayColor={style.hintColors.gray}> <View style={[style.list.view, this.props.sectionStyle, { backgroundColor: this.props.color }]}> <Text style={{ color: this.props.fontColor }}>{this.props.cleanName}</Text> </View> </TouchableHighlight> ); } }
src/components/search-mapping-view/index.js
datea/datea-webapp-react
import './search-mapping-view.scss'; import React from 'react'; import {observer, inject} from 'mobx-react'; import InfiniteScroll from 'react-infinite-scroller'; import InfiniteLoaderIcon from '../infinite-loader-icon'; import Button from '@material-ui/core/Button'; import MappingColumnLayout from '../mapping-card-grid'; import DIcon from '../../icons'; import {Tr} from '../../i18n'; @inject('store') @observer export default class SearchMappingView extends React.Component { constructor(props, context) { super(props, context); } render() { const {mappings, numResults, limit, loadMore} = this.props.store.searchMappingView; return ( <div className="search-page-container mapping-column-container"> <h1><Tr id="SEARCHBOX.GLOBAL_PH" /></h1> {!this.props.store.ui.loading && (numResults > 0 ? <div className="num-results"> {numResults} <Tr id="CAMPAIGNS.RESULTS" /> </div> : <div className="no-results"> <DIcon name="daterito2" /> <div className="txt"> <Tr id="SEARCH_PAGE.NO_RESULTS" />. <Tr id="ERROR.RETRY" /> </div> </div> ) } {!!mappings.length && <div className="mappings"> <div className="mapping-group"> <InfiniteScroll pageStart={0} loadMore={loadMore} hasMore={numResults > limit} loader={<InfiniteLoaderIcon key={0} />}> <MappingColumnLayout mappings={mappings} /> </InfiniteScroll> </div> </div> } </div> ) } }
assets/jqwidgets/demos/react/app/treegrid/xmldata/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxTreeGrid from '../../../jqwidgets-react/react_jqxtreegrid.js'; class App extends React.Component { componentDidMount() { this.refs.myTreeGrid.on('bindingComplete', () => { this.refs.myTreeGrid.expandRow(2); }); } render() { let source = { dataType: "xml", dataFields: [ { name: 'EmployeeID', type: 'number' }, { name: 'ReportsTo', type: 'number' }, { name: 'FirstName', type: 'string' }, { name: 'LastName', type: 'string' }, { name: 'City', type: 'string' }, { name: 'Address', type: 'string' }, { name: 'Title', type: 'string' }, { name: 'HireDate', type: 'date' }, { name: 'BirthDate', type: 'date' } ], hierarchy: { keyDataField: { name: 'EmployeeID' }, parentDataField: { name: 'ReportsTo' } }, id: 'EmployeeID', root: 'Employees', record: 'Employee', url: '../sampledata/employees.xml' }; let dataAdapter = new $.jqx.dataAdapter(source); let columns = [ { text: 'FirstName', dataField: 'FirstName', minWidth: 100, width: 200 }, { text: 'LastName', dataField: 'LastName', width: 200 }, { text: 'Title', dataField: 'Title', width: 300 }, { text: 'Address', dataField: 'Address', width: 200 }, { text: 'City', dataField: 'City', width: 150 }, { text: 'Birth Date', dataField: 'BirthDate', cellsFormat: 'd', width: 120 }, { text: 'Hire Date', dataField: 'HireDate', cellsFormat: 'd', width: 120 } ]; return ( <JqxTreeGrid ref='myTreeGrid' width={850} source={dataAdapter} pageable={true} columnsResize={true} columns={columns} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/components/App.js
phuchle/recipeas
import React from 'react'; import Navigation from './Nav'; import Main from './Main'; import 'bootstrap/dist/css/bootstrap.css'; import '../App.css'; const App = (props) => { return ( <div className="App"> <Navigation /> <Main /> </div> ); }; export default App;
client/src/javascript/components/modals/settings-modal/ConnectivityTab.js
stephdewit/flood
import {Checkbox, Form, FormRow, Textbox} from 'flood-ui-kit'; import {FormattedMessage} from 'react-intl'; import React from 'react'; import ModalFormSectionHeader from '../ModalFormSectionHeader'; import SettingsTab from './SettingsTab'; export default class ConnectivityTab extends SettingsTab { state = {}; getDHTEnabledValue() { if (this.state.dhtEnabled != null) { return this.state.dhtEnabled; } return this.props.settings.dhtStats.dht === 'auto'; } handleFormChange = ({event}) => { if (event.target.name === 'dhtEnabled') { const dhtEnabled = !this.getDHTEnabledValue(); const dhtEnabledString = dhtEnabled ? 'auto' : 'disable'; this.setState({dhtEnabled}); this.props.onCustomSettingsChange({ id: 'dht', data: [dhtEnabledString], overrideID: 'dhtStats', overrideData: {dht: dhtEnabledString}, }); } else { this.handleClientSettingFieldChange(event.target.name, event); } }; render() { return ( <Form onChange={this.handleFormChange}> <ModalFormSectionHeader> <FormattedMessage defaultMessage="Incoming Connections" id="settings.connectivity.incoming.heading" /> </ModalFormSectionHeader> <FormRow> <Textbox defaultValue={this.getFieldValue('networkPortRange')} id="networkPortRange" label={ <FormattedMessage id="settings.connectivity.port.range.label" defaultMessage="Listening Port Range" /> } width="one-quarter" /> <Checkbox checked={this.getFieldValue('networkPortRandom') === '1'} grow={false} id="networkPortRandom" labelOffset matchTextboxHeight> <FormattedMessage id="settings.connectivity.port.randomize.label" defaultMessage="Randomize Port" /> </Checkbox> <Checkbox checked={this.getFieldValue('networkPortOpen') === '1'} grow={false} id="networkPortOpen" labelOffset matchTextboxHeight> <FormattedMessage id="settings.connectivity.port.open.label" defaultMessage="Open Port" /> </Checkbox> </FormRow> <FormRow> <Textbox defaultValue={this.getFieldValue('networkLocalAddress')} id="networkLocalAddress" label={ <FormattedMessage id="settings.connectivity.ip.hostname.label" defaultMessage="Reported IP/Hostname" /> } /> <Textbox defaultValue={this.getFieldValue('networkHttpMaxOpen')} id="networkHttpMaxOpen" label={ <FormattedMessage id="settings.connectivity.max.http.connections" defaultMessage="Maximum HTTP Connections" /> } /> </FormRow> <ModalFormSectionHeader> <FormattedMessage id="settings.connectivity.dpd.heading" defaultMessage="Decentralized Peer Discovery" /> </ModalFormSectionHeader> <FormRow> <Textbox defaultValue={this.getFieldValue('dhtPort')} id="dhtPort" label={<FormattedMessage id="settings.connectivity.dht.port.label" defaultMessage="DHT Port" />} width="one-quarter" /> <Checkbox checked={this.getDHTEnabledValue()} grow={false} id="dhtEnabled" labelOffset matchTextboxHeight> <FormattedMessage id="settings.connectivity.dht.label" defaultMessage="Enable DHT" /> </Checkbox> <Checkbox checked={this.getFieldValue('protocolPex') === '1'} grow={false} id="protocolPex" labelOffset matchTextboxHeight> <FormattedMessage id="settings.connectivity.peer.exchange.label" defaultMessage="Enable Peer Exchange" /> </Checkbox> </FormRow> <ModalFormSectionHeader> <FormattedMessage id="settings.connectivity.peers.heading" defaultMessage="Peers" /> </ModalFormSectionHeader> <FormRow> <Textbox defaultValue={this.getFieldValue('throttleMinPeersNormal')} id="throttleMinPeersNormal" label={<FormattedMessage id="settings.connectivity.peers.min.label" defaultMessage="Minimum Peers" />} /> <Textbox defaultValue={this.getFieldValue('throttleMaxPeersNormal')} id="throttleMaxPeersNormal" label={<FormattedMessage id="settings.connectivity.peers.max.label" defaultMessage="Maxmimum Peers" />} /> </FormRow> <FormRow> <Textbox defaultValue={this.getFieldValue('throttleMinPeersSeed')} id="throttleMinPeersSeed" label={ <FormattedMessage id="settings.connectivity.peers.seeding.min.label" defaultMessage="Minimum Peers Seeding" /> } /> <Textbox defaultValue={this.getFieldValue('throttleMaxPeersSeed')} id="throttleMaxPeersSeed" label={ <FormattedMessage id="settings.connectivity.peers.seeding.max.label" defaultMessage="Maxmimum Peers Seeding" /> } /> </FormRow> <FormRow> <Textbox defaultValue={this.getFieldValue('trackersNumWant')} id="trackersNumWant" label={<FormattedMessage id="settings.connectivity.peers.desired.label" defaultMessage="Peers Desired" />} width="one-half" /> </FormRow> </Form> ); } }
ajax/libs/react-select/1.0.0/react-select.es.js
holtkamp/cdnjs
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import AutosizeInput from 'react-input-autosize'; import classNames from 'classnames'; function arrowRenderer(_ref) { var onMouseDown = _ref.onMouseDown; return React.createElement('span', { className: 'Select-arrow', onMouseDown: onMouseDown }); } arrowRenderer.propTypes = { onMouseDown: PropTypes.func }; var map = [{ 'base': 'A', 'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g }, { 'base': 'AA', 'letters': /[\uA732]/g }, { 'base': 'AE', 'letters': /[\u00C6\u01FC\u01E2]/g }, { 'base': 'AO', 'letters': /[\uA734]/g }, { 'base': 'AU', 'letters': /[\uA736]/g }, { 'base': 'AV', 'letters': /[\uA738\uA73A]/g }, { 'base': 'AY', 'letters': /[\uA73C]/g }, { 'base': 'B', 'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g }, { 'base': 'C', 'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g }, { 'base': 'D', 'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g }, { 'base': 'DZ', 'letters': /[\u01F1\u01C4]/g }, { 'base': 'Dz', 'letters': /[\u01F2\u01C5]/g }, { 'base': 'E', 'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g }, { 'base': 'F', 'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g }, { 'base': 'G', 'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g }, { 'base': 'H', 'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g }, { 'base': 'I', 'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g }, { 'base': 'J', 'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g }, { 'base': 'K', 'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g }, { 'base': 'L', 'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g }, { 'base': 'LJ', 'letters': /[\u01C7]/g }, { 'base': 'Lj', 'letters': /[\u01C8]/g }, { 'base': 'M', 'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g }, { 'base': 'N', 'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g }, { 'base': 'NJ', 'letters': /[\u01CA]/g }, { 'base': 'Nj', 'letters': /[\u01CB]/g }, { 'base': 'O', 'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g }, { 'base': 'OI', 'letters': /[\u01A2]/g }, { 'base': 'OO', 'letters': /[\uA74E]/g }, { 'base': 'OU', 'letters': /[\u0222]/g }, { 'base': 'P', 'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g }, { 'base': 'Q', 'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g }, { 'base': 'R', 'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g }, { 'base': 'S', 'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g }, { 'base': 'T', 'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g }, { 'base': 'TZ', 'letters': /[\uA728]/g }, { 'base': 'U', 'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g }, { 'base': 'V', 'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g }, { 'base': 'VY', 'letters': /[\uA760]/g }, { 'base': 'W', 'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g }, { 'base': 'X', 'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g }, { 'base': 'Y', 'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g }, { 'base': 'Z', 'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g }, { 'base': 'a', 'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g }, { 'base': 'aa', 'letters': /[\uA733]/g }, { 'base': 'ae', 'letters': /[\u00E6\u01FD\u01E3]/g }, { 'base': 'ao', 'letters': /[\uA735]/g }, { 'base': 'au', 'letters': /[\uA737]/g }, { 'base': 'av', 'letters': /[\uA739\uA73B]/g }, { 'base': 'ay', 'letters': /[\uA73D]/g }, { 'base': 'b', 'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g }, { 'base': 'c', 'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g }, { 'base': 'd', 'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g }, { 'base': 'dz', 'letters': /[\u01F3\u01C6]/g }, { 'base': 'e', 'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g }, { 'base': 'f', 'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g }, { 'base': 'g', 'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g }, { 'base': 'h', 'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g }, { 'base': 'hv', 'letters': /[\u0195]/g }, { 'base': 'i', 'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g }, { 'base': 'j', 'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g }, { 'base': 'k', 'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g }, { 'base': 'l', 'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g }, { 'base': 'lj', 'letters': /[\u01C9]/g }, { 'base': 'm', 'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g }, { 'base': 'n', 'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g }, { 'base': 'nj', 'letters': /[\u01CC]/g }, { 'base': 'o', 'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g }, { 'base': 'oi', 'letters': /[\u01A3]/g }, { 'base': 'ou', 'letters': /[\u0223]/g }, { 'base': 'oo', 'letters': /[\uA74F]/g }, { 'base': 'p', 'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g }, { 'base': 'q', 'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g }, { 'base': 'r', 'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g }, { 'base': 's', 'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g }, { 'base': 't', 'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g }, { 'base': 'tz', 'letters': /[\uA729]/g }, { 'base': 'u', 'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g }, { 'base': 'v', 'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g }, { 'base': 'vy', 'letters': /[\uA761]/g }, { 'base': 'w', 'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g }, { 'base': 'x', 'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g }, { 'base': 'y', 'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g }, { 'base': 'z', 'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g }]; function stripDiacritics(str) { for (var i = 0; i < map.length; i++) { str = str.replace(map[i].letters, map[i].base); } return str; } function trim(str) { return str.replace(/^\s+|\s+$/g, ''); } function filterOptions(options, filterValue, excludeOptions, props) { var _this = this; if (props.ignoreAccents) { filterValue = stripDiacritics(filterValue); } if (props.ignoreCase) { filterValue = filterValue.toLowerCase(); } if (props.trimFilter) { filterValue = trim(filterValue); } if (excludeOptions) excludeOptions = excludeOptions.map(function (i) { return i[props.valueKey]; }); return options.filter(function (option) { if (excludeOptions && excludeOptions.indexOf(option[props.valueKey]) > -1) return false; if (props.filterOption) return props.filterOption.call(_this, option, filterValue); if (!filterValue) return true; var valueTest = String(option[props.valueKey]); var labelTest = String(option[props.labelKey]); if (props.ignoreAccents) { if (props.matchProp !== 'label') valueTest = stripDiacritics(valueTest); if (props.matchProp !== 'value') labelTest = stripDiacritics(labelTest); } if (props.ignoreCase) { if (props.matchProp !== 'label') valueTest = valueTest.toLowerCase(); if (props.matchProp !== 'value') labelTest = labelTest.toLowerCase(); } return props.matchPos === 'start' ? props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue || props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue : props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0 || props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0; }); } function menuRenderer(_ref) { var focusedOption = _ref.focusedOption, instancePrefix = _ref.instancePrefix, labelKey = _ref.labelKey, onFocus = _ref.onFocus, onSelect = _ref.onSelect, optionClassName = _ref.optionClassName, optionComponent = _ref.optionComponent, optionRenderer = _ref.optionRenderer, options = _ref.options, valueArray = _ref.valueArray, valueKey = _ref.valueKey, onOptionRef = _ref.onOptionRef; var Option = optionComponent; return options.map(function (option, i) { var isSelected = valueArray && valueArray.some(function (x) { return x[valueKey] == option[valueKey]; }); var isFocused = option === focusedOption; var optionClass = classNames(optionClassName, { 'Select-option': true, 'is-selected': isSelected, 'is-focused': isFocused, 'is-disabled': option.disabled }); return React.createElement( Option, { className: optionClass, instancePrefix: instancePrefix, isDisabled: option.disabled, isFocused: isFocused, isSelected: isSelected, key: 'option-' + i + '-' + option[valueKey], onFocus: onFocus, onSelect: onSelect, option: option, optionIndex: i, ref: function ref(_ref2) { onOptionRef(_ref2, isFocused); } }, optionRenderer(option, i) ); }); } function clearRenderer() { return React.createElement('span', { className: 'Select-clear', dangerouslySetInnerHTML: { __html: '&times;' } }); } var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var asyncGenerator = function () { function AwaitValue(value) { this.value = value; } function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; if (value instanceof AwaitValue) { Promise.resolve(value.value).then(function (arg) { resume("next", arg); }, function (arg) { resume("throw", arg); }); } else { settle(result.done ? "return" : "normal", result.value); } } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; return { wrap: function (fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; }, await: function (value) { return new AwaitValue(value); } }; }(); var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var Option = function (_React$Component) { inherits(Option, _React$Component); function Option(props) { classCallCheck(this, Option); var _this = possibleConstructorReturn(this, (Option.__proto__ || Object.getPrototypeOf(Option)).call(this, props)); _this.handleMouseDown = _this.handleMouseDown.bind(_this); _this.handleMouseEnter = _this.handleMouseEnter.bind(_this); _this.handleMouseMove = _this.handleMouseMove.bind(_this); _this.handleTouchStart = _this.handleTouchStart.bind(_this); _this.handleTouchEnd = _this.handleTouchEnd.bind(_this); _this.handleTouchMove = _this.handleTouchMove.bind(_this); _this.onFocus = _this.onFocus.bind(_this); return _this; } createClass(Option, [{ key: 'blockEvent', value: function blockEvent(event) { event.preventDefault(); event.stopPropagation(); if (event.target.tagName !== 'A' || !('href' in event.target)) { return; } if (event.target.target) { window.open(event.target.href, event.target.target); } else { window.location.href = event.target.href; } } }, { key: 'handleMouseDown', value: function handleMouseDown(event) { event.preventDefault(); event.stopPropagation(); this.props.onSelect(this.props.option, event); } }, { key: 'handleMouseEnter', value: function handleMouseEnter(event) { this.onFocus(event); } }, { key: 'handleMouseMove', value: function handleMouseMove(event) { this.onFocus(event); } }, { key: 'handleTouchEnd', value: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; this.handleMouseDown(event); } }, { key: 'handleTouchMove', value: function handleTouchMove(event) { // Set a flag that the view is being dragged this.dragging = true; } }, { key: 'handleTouchStart', value: function handleTouchStart(event) { // Set a flag that the view is not being dragged this.dragging = false; } }, { key: 'onFocus', value: function onFocus(event) { if (!this.props.isFocused) { this.props.onFocus(this.props.option, event); } } }, { key: 'render', value: function render() { var _props = this.props, option = _props.option, instancePrefix = _props.instancePrefix, optionIndex = _props.optionIndex; var className = classNames(this.props.className, option.className); return option.disabled ? React.createElement( 'div', { className: className, onMouseDown: this.blockEvent, onClick: this.blockEvent }, this.props.children ) : React.createElement( 'div', { className: className, style: option.style, role: 'option', 'aria-label': option.label, onMouseDown: this.handleMouseDown, onMouseEnter: this.handleMouseEnter, onMouseMove: this.handleMouseMove, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove, onTouchEnd: this.handleTouchEnd, id: instancePrefix + '-option-' + optionIndex, title: option.title }, this.props.children ); } }]); return Option; }(React.Component); Option.propTypes = { children: PropTypes.node, className: PropTypes.string, // className (based on mouse position) instancePrefix: PropTypes.string.isRequired, // unique prefix for the ids (used for aria) isDisabled: PropTypes.bool, // the option is disabled isFocused: PropTypes.bool, // the option is focused isSelected: PropTypes.bool, // the option is selected onFocus: PropTypes.func, // method to handle mouseEnter on option element onSelect: PropTypes.func, // method to handle click on option element onUnfocus: PropTypes.func, // method to handle mouseLeave on option element option: PropTypes.object.isRequired, // object that is base for that option optionIndex: PropTypes.number // index of the option, used to generate unique ids for aria }; var Value = function (_React$Component) { inherits(Value, _React$Component); function Value(props) { classCallCheck(this, Value); var _this = possibleConstructorReturn(this, (Value.__proto__ || Object.getPrototypeOf(Value)).call(this, props)); _this.handleMouseDown = _this.handleMouseDown.bind(_this); _this.onRemove = _this.onRemove.bind(_this); _this.handleTouchEndRemove = _this.handleTouchEndRemove.bind(_this); _this.handleTouchMove = _this.handleTouchMove.bind(_this); _this.handleTouchStart = _this.handleTouchStart.bind(_this); return _this; } createClass(Value, [{ key: 'handleMouseDown', value: function handleMouseDown(event) { if (event.type === 'mousedown' && event.button !== 0) { return; } if (this.props.onClick) { event.stopPropagation(); this.props.onClick(this.props.value, event); return; } if (this.props.value.href) { event.stopPropagation(); } } }, { key: 'onRemove', value: function onRemove(event) { event.preventDefault(); event.stopPropagation(); this.props.onRemove(this.props.value); } }, { key: 'handleTouchEndRemove', value: function handleTouchEndRemove(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.onRemove(event); } }, { key: 'handleTouchMove', value: function handleTouchMove(event) { // Set a flag that the view is being dragged this.dragging = true; } }, { key: 'handleTouchStart', value: function handleTouchStart(event) { // Set a flag that the view is not being dragged this.dragging = false; } }, { key: 'renderRemoveIcon', value: function renderRemoveIcon() { if (this.props.disabled || !this.props.onRemove) return; return React.createElement( 'span', { className: 'Select-value-icon', 'aria-hidden': 'true', onMouseDown: this.onRemove, onTouchEnd: this.handleTouchEndRemove, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove }, '\xD7' ); } }, { key: 'renderLabel', value: function renderLabel() { var className = 'Select-value-label'; return this.props.onClick || this.props.value.href ? React.createElement( 'a', { className: className, href: this.props.value.href, target: this.props.value.target, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleMouseDown }, this.props.children ) : React.createElement( 'span', { className: className, role: 'option', 'aria-selected': 'true', id: this.props.id }, this.props.children ); } }, { key: 'render', value: function render() { return React.createElement( 'div', { className: classNames('Select-value', this.props.value.className), style: this.props.value.style, title: this.props.value.title }, this.renderRemoveIcon(), this.renderLabel() ); } }]); return Value; }(React.Component); Value.propTypes = { children: PropTypes.node, disabled: PropTypes.bool, // disabled prop passed to ReactSelect id: PropTypes.string, // Unique id for the value - used for aria onClick: PropTypes.func, // method to handle click on value label onRemove: PropTypes.func, // method to handle removal of the value value: PropTypes.object.isRequired // the option object for this value }; /*! Copyright (c) 2017 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/react-select */ var stringifyValue = function stringifyValue(value) { return typeof value === 'string' ? value : value !== null && JSON.stringify(value) || ''; }; var stringOrNode = PropTypes.oneOfType([PropTypes.string, PropTypes.node]); var stringOrNumber = PropTypes.oneOfType([PropTypes.string, PropTypes.number]); var instanceId = 1; var Select$1 = function (_React$Component) { inherits(Select, _React$Component); function Select(props) { classCallCheck(this, Select); var _this = possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props)); ['clearValue', 'focusOption', 'handleInputBlur', 'handleInputChange', 'handleInputFocus', 'handleInputValueChange', 'handleKeyDown', 'handleMenuScroll', 'handleMouseDown', 'handleMouseDownOnArrow', 'handleMouseDownOnMenu', 'handleRequired', 'handleTouchOutside', 'handleTouchMove', 'handleTouchStart', 'handleTouchEnd', 'handleTouchEndClearValue', 'handleValueClick', 'getOptionLabel', 'onOptionRef', 'removeValue', 'selectValue'].forEach(function (fn) { return _this[fn] = _this[fn].bind(_this); }); _this.state = { inputValue: '', isFocused: false, isOpen: false, isPseudoFocused: false, required: false }; return _this; } createClass(Select, [{ key: 'componentWillMount', value: function componentWillMount() { this._instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId) + '-'; var valueArray = this.getValueArray(this.props.value); if (this.props.required) { this.setState({ required: this.handleRequired(valueArray[0], this.props.multi) }); } } }, { key: 'componentDidMount', value: function componentDidMount() { if (typeof this.props.autofocus !== 'undefined' && typeof console !== 'undefined') { console.warn('Warning: The autofocus prop has changed to autoFocus, support will be removed after [email protected]'); } if (this.props.autoFocus || this.props.autofocus) { this.focus(); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var valueArray = this.getValueArray(nextProps.value, nextProps); if (nextProps.required) { this.setState({ required: this.handleRequired(valueArray[0], nextProps.multi) }); } else if (this.props.required) { // Used to be required but it's not any more this.setState({ required: false }); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps, prevState) { // focus to the selected option if (this.menu && this.focused && this.state.isOpen && !this.hasScrolledToOption) { var focusedOptionNode = findDOMNode(this.focused); var menuNode = findDOMNode(this.menu); menuNode.scrollTop = focusedOptionNode.offsetTop; this.hasScrolledToOption = true; } else if (!this.state.isOpen) { this.hasScrolledToOption = false; } if (this._scrollToFocusedOptionOnUpdate && this.focused && this.menu) { this._scrollToFocusedOptionOnUpdate = false; var focusedDOM = findDOMNode(this.focused); var menuDOM = findDOMNode(this.menu); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom) { menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight; } else if (focusedRect.top < menuRect.top) { menuDOM.scrollTop = focusedDOM.offsetTop; } } if (this.props.scrollMenuIntoView && this.menuContainer) { var menuContainerRect = this.menuContainer.getBoundingClientRect(); if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) { window.scrollBy(0, menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight); } } if (prevProps.disabled !== this.props.disabled) { this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state this.closeMenu(); } if (prevState.isOpen !== this.state.isOpen) { this.toggleTouchOutsideEvent(this.state.isOpen); var handler = this.state.isOpen ? this.props.onOpen : this.props.onClose; handler && handler(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.toggleTouchOutsideEvent(false); } }, { key: 'toggleTouchOutsideEvent', value: function toggleTouchOutsideEvent(enabled) { if (enabled) { if (!document.addEventListener && document.attachEvent) { document.attachEvent('ontouchstart', this.handleTouchOutside); } else { document.addEventListener('touchstart', this.handleTouchOutside); } } else { if (!document.removeEventListener && document.detachEvent) { document.detachEvent('ontouchstart', this.handleTouchOutside); } else { document.removeEventListener('touchstart', this.handleTouchOutside); } } } }, { key: 'handleTouchOutside', value: function handleTouchOutside(event) { // handle touch outside on ios to dismiss menu if (this.wrapper && !this.wrapper.contains(event.target)) { this.closeMenu(); } } }, { key: 'focus', value: function focus() { if (!this.input) return; this.input.focus(); } }, { key: 'blurInput', value: function blurInput() { if (!this.input) return; this.input.blur(); } }, { key: 'handleTouchMove', value: function handleTouchMove(event) { // Set a flag that the view is being dragged this.dragging = true; } }, { key: 'handleTouchStart', value: function handleTouchStart(event) { // Set a flag that the view is not being dragged this.dragging = false; } }, { key: 'handleTouchEnd', value: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.handleMouseDown(event); } }, { key: 'handleTouchEndClearValue', value: function handleTouchEndClearValue(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Clear the value this.clearValue(event); } }, { key: 'handleMouseDown', value: function handleMouseDown(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } if (event.target.tagName === 'INPUT') { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // for the non-searchable select, toggle the menu if (!this.props.searchable) { // TODO: This code means that if a select is searchable, onClick the options menu will not appear, only on subsequent click will it open. this.focus(); return this.setState({ isOpen: !this.state.isOpen }); } if (this.state.isFocused) { // On iOS, we can get into a state where we think the input is focused but it isn't really, // since iOS ignores programmatic calls to input.focus() that weren't triggered by a click event. // Call focus() again here to be safe. this.focus(); var input = this.input; if (typeof input.getInput === 'function') { // Get the actual DOM input if the ref is an <AutosizeInput /> component input = input.getInput(); } // clears the value so that the cursor will be at the end of input when the component re-renders input.value = ''; // if the input is focused, ensure the menu is open this.setState({ isOpen: true, isPseudoFocused: false }); } else { // otherwise, focus the input and open the menu this._openAfterFocus = this.props.openOnClick; this.focus(); } } }, { key: 'handleMouseDownOnArrow', value: function handleMouseDownOnArrow(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } // If the menu isn't open, let the event bubble to the main handleMouseDown if (!this.state.isOpen) { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // close the menu this.closeMenu(); } }, { key: 'handleMouseDownOnMenu', value: function handleMouseDownOnMenu(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this._openAfterFocus = true; this.focus(); } }, { key: 'closeMenu', value: function closeMenu() { if (this.props.onCloseResetsInput) { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: this.handleInputValueChange('') }); } else { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi }); } this.hasScrolledToOption = false; } }, { key: 'handleInputFocus', value: function handleInputFocus(event) { if (this.props.disabled) return; var isOpen = this.state.isOpen || this._openAfterFocus || this.props.openOnFocus; if (this.props.onFocus) { this.props.onFocus(event); } this.setState({ isFocused: true, isOpen: isOpen }); this._openAfterFocus = false; } }, { key: 'handleInputBlur', value: function handleInputBlur(event) { // The check for menu.contains(activeElement) is necessary to prevent IE11's scrollbar from closing the menu in certain contexts. if (this.menu && (this.menu === document.activeElement || this.menu.contains(document.activeElement))) { this.focus(); return; } if (this.props.onBlur) { this.props.onBlur(event); } var onBlurredState = { isFocused: false, isOpen: false, isPseudoFocused: false }; if (this.props.onBlurResetsInput) { onBlurredState.inputValue = this.handleInputValueChange(''); } this.setState(onBlurredState); } }, { key: 'handleInputChange', value: function handleInputChange(event) { var newInputValue = event.target.value; if (this.state.inputValue !== event.target.value) { newInputValue = this.handleInputValueChange(newInputValue); } this.setState({ isOpen: true, isPseudoFocused: false, inputValue: newInputValue }); } }, { key: 'handleInputValueChange', value: function handleInputValueChange(newValue) { if (this.props.onInputChange) { var nextState = this.props.onInputChange(newValue); // Note: != used deliberately here to catch undefined and null if (nextState != null && (typeof nextState === 'undefined' ? 'undefined' : _typeof(nextState)) !== 'object') { newValue = '' + nextState; } } return newValue; } }, { key: 'handleKeyDown', value: function handleKeyDown(event) { if (this.props.disabled) return; if (typeof this.props.onInputKeyDown === 'function') { this.props.onInputKeyDown(event); if (event.defaultPrevented) { return; } } switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue && this.props.backspaceRemoves) { event.preventDefault(); this.popValue(); } return; case 9: // tab if (event.shiftKey || !this.state.isOpen || !this.props.tabSelectsValue) { return; } event.preventDefault(); this.selectFocusedOption(); return; case 13: // enter event.preventDefault(); event.stopPropagation(); if (this.state.isOpen) { this.selectFocusedOption(); } else { this.focusNextOption(); } return; break; case 27: // escape if (this.state.isOpen) { this.closeMenu(); event.stopPropagation(); } else if (this.props.clearable && this.props.escapeClearsValue) { this.clearValue(event); event.stopPropagation(); } break; case 32: // space if (this.props.searchable) { return; } event.preventDefault(); if (!this.state.isOpen) { this.focusNextOption(); return; } event.stopPropagation(); this.selectFocusedOption(); break; case 38: // up this.focusPreviousOption(); break; case 40: // down this.focusNextOption(); break; case 33: // page up this.focusPageUpOption(); break; case 34: // page down this.focusPageDownOption(); break; case 35: // end key if (event.shiftKey) { return; } this.focusEndOption(); break; case 36: // home key if (event.shiftKey) { return; } this.focusStartOption(); break; case 46: // delete if (!this.state.inputValue && this.props.deleteRemoves) { event.preventDefault(); this.popValue(); } return; default: return; } event.preventDefault(); } }, { key: 'handleValueClick', value: function handleValueClick(option, event) { if (!this.props.onValueClick) return; this.props.onValueClick(option, event); } }, { key: 'handleMenuScroll', value: function handleMenuScroll(event) { if (!this.props.onMenuScrollToBottom) return; var target = event.target; if (target.scrollHeight > target.offsetHeight && target.scrollHeight - target.offsetHeight - target.scrollTop <= 0) { this.props.onMenuScrollToBottom(); } } }, { key: 'handleRequired', value: function handleRequired(value, multi) { if (!value) return true; return multi ? value.length === 0 : Object.keys(value).length === 0; } }, { key: 'getOptionLabel', value: function getOptionLabel(op) { return op[this.props.labelKey]; } /** * Turns a value into an array from the given options * @param {String|Number|Array} value - the value of the select input * @param {Object} nextProps - optionally specify the nextProps so the returned array uses the latest configuration * @returns {Array} the value of the select represented in an array */ }, { key: 'getValueArray', value: function getValueArray(value, nextProps) { var _this2 = this; /** support optionally passing in the `nextProps` so `componentWillReceiveProps` updates will function as expected */ var props = (typeof nextProps === 'undefined' ? 'undefined' : _typeof(nextProps)) === 'object' ? nextProps : this.props; if (props.multi) { if (typeof value === 'string') { value = value.split(props.delimiter); } if (!Array.isArray(value)) { if (value === null || value === undefined) return []; value = [value]; } return value.map(function (value) { return _this2.expandValue(value, props); }).filter(function (i) { return i; }); } var expandedValue = this.expandValue(value, props); return expandedValue ? [expandedValue] : []; } /** * Retrieve a value from the given options and valueKey * @param {String|Number|Array} value - the selected value(s) * @param {Object} props - the Select component's props (or nextProps) */ }, { key: 'expandValue', value: function expandValue(value, props) { var valueType = typeof value === 'undefined' ? 'undefined' : _typeof(value); if (valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') return value; var options = props.options, valueKey = props.valueKey; if (!options) return; for (var i = 0; i < options.length; i++) { if (String(options[i][valueKey]) === String(value)) return options[i]; } } }, { key: 'setValue', value: function setValue(value) { var _this3 = this; if (this.props.autoBlur) { this.blurInput(); } if (this.props.required) { var required = this.handleRequired(value, this.props.multi); this.setState({ required: required }); } if (this.props.onChange) { if (this.props.simpleValue && value) { value = this.props.multi ? value.map(function (i) { return i[_this3.props.valueKey]; }).join(this.props.delimiter) : value[this.props.valueKey]; } this.props.onChange(value); } } }, { key: 'selectValue', value: function selectValue(value) { var _this4 = this; // NOTE: we actually add/set the value in a callback to make sure the // input value is empty to avoid styling issues in Chrome if (this.props.closeOnSelect) { this.hasScrolledToOption = false; } if (this.props.multi) { var updatedValue = this.props.onSelectResetsInput ? '' : this.state.inputValue; this.setState({ focusedIndex: null, inputValue: this.handleInputValueChange(updatedValue), isOpen: !this.props.closeOnSelect }, function () { var valueArray = _this4.getValueArray(_this4.props.value); if (valueArray.some(function (i) { return i[_this4.props.valueKey] === value[_this4.props.valueKey]; })) { _this4.removeValue(value); } else { _this4.addValue(value); } }); } else { this.setState({ inputValue: this.handleInputValueChange(''), isOpen: !this.props.closeOnSelect, isPseudoFocused: this.state.isFocused }, function () { _this4.setValue(value); }); } } }, { key: 'addValue', value: function addValue(value) { var valueArray = this.getValueArray(this.props.value); var visibleOptions = this._visibleOptions.filter(function (val) { return !val.disabled; }); var lastValueIndex = visibleOptions.indexOf(value); this.setValue(valueArray.concat(value)); if (visibleOptions.length - 1 === lastValueIndex) { // the last option was selected; focus the second-last one this.focusOption(visibleOptions[lastValueIndex - 1]); } else if (visibleOptions.length > lastValueIndex) { // focus the option below the selected one this.focusOption(visibleOptions[lastValueIndex + 1]); } } }, { key: 'popValue', value: function popValue() { var valueArray = this.getValueArray(this.props.value); if (!valueArray.length) return; if (valueArray[valueArray.length - 1].clearableValue === false) return; this.setValue(this.props.multi ? valueArray.slice(0, valueArray.length - 1) : null); } }, { key: 'removeValue', value: function removeValue(value) { var _this5 = this; var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.filter(function (i) { return i[_this5.props.valueKey] !== value[_this5.props.valueKey]; })); this.focus(); } }, { key: 'clearValue', value: function clearValue(event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this.setValue(this.getResetValue()); this.setState({ isOpen: false, inputValue: this.handleInputValueChange('') }, this.focus); } }, { key: 'getResetValue', value: function getResetValue() { if (this.props.resetValue !== undefined) { return this.props.resetValue; } else if (this.props.multi) { return []; } else { return null; } } }, { key: 'focusOption', value: function focusOption(option) { this.setState({ focusedOption: option }); } }, { key: 'focusNextOption', value: function focusNextOption() { this.focusAdjacentOption('next'); } }, { key: 'focusPreviousOption', value: function focusPreviousOption() { this.focusAdjacentOption('previous'); } }, { key: 'focusPageUpOption', value: function focusPageUpOption() { this.focusAdjacentOption('page_up'); } }, { key: 'focusPageDownOption', value: function focusPageDownOption() { this.focusAdjacentOption('page_down'); } }, { key: 'focusStartOption', value: function focusStartOption() { this.focusAdjacentOption('start'); } }, { key: 'focusEndOption', value: function focusEndOption() { this.focusAdjacentOption('end'); } }, { key: 'focusAdjacentOption', value: function focusAdjacentOption(dir) { var options = this._visibleOptions.map(function (option, index) { return { option: option, index: index }; }).filter(function (option) { return !option.option.disabled; }); this._scrollToFocusedOptionOnUpdate = true; if (!this.state.isOpen) { this.setState({ isOpen: true, inputValue: '', focusedOption: this._focusedOption || (options.length ? options[dir === 'next' ? 0 : options.length - 1].option : null) }); return; } if (!options.length) return; var focusedIndex = -1; for (var i = 0; i < options.length; i++) { if (this._focusedOption === options[i].option) { focusedIndex = i; break; } } if (dir === 'next' && focusedIndex !== -1) { focusedIndex = (focusedIndex + 1) % options.length; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedIndex = focusedIndex - 1; } else { focusedIndex = options.length - 1; } } else if (dir === 'start') { focusedIndex = 0; } else if (dir === 'end') { focusedIndex = options.length - 1; } else if (dir === 'page_up') { var potentialIndex = focusedIndex - this.props.pageSize; if (potentialIndex < 0) { focusedIndex = 0; } else { focusedIndex = potentialIndex; } } else if (dir === 'page_down') { var potentialIndex = focusedIndex + this.props.pageSize; if (potentialIndex > options.length - 1) { focusedIndex = options.length - 1; } else { focusedIndex = potentialIndex; } } if (focusedIndex === -1) { focusedIndex = 0; } this.setState({ focusedIndex: options[focusedIndex].index, focusedOption: options[focusedIndex].option }); } }, { key: 'getFocusedOption', value: function getFocusedOption() { return this._focusedOption; } }, { key: 'selectFocusedOption', value: function selectFocusedOption() { if (this._focusedOption) { return this.selectValue(this._focusedOption); } } }, { key: 'renderLoading', value: function renderLoading() { if (!this.props.isLoading) return; return React.createElement( 'span', { className: 'Select-loading-zone', 'aria-hidden': 'true' }, React.createElement('span', { className: 'Select-loading' }) ); } }, { key: 'renderValue', value: function renderValue(valueArray, isOpen) { var _this6 = this; var renderLabel = this.props.valueRenderer || this.getOptionLabel; var ValueComponent = this.props.valueComponent; if (!valueArray.length) { return !this.state.inputValue ? React.createElement( 'div', { className: 'Select-placeholder' }, this.props.placeholder ) : null; } var onClick = this.props.onValueClick ? this.handleValueClick : null; if (this.props.multi) { return valueArray.map(function (value, i) { return React.createElement( ValueComponent, { id: _this6._instancePrefix + '-value-' + i, instancePrefix: _this6._instancePrefix, disabled: _this6.props.disabled || value.clearableValue === false, key: 'value-' + i + '-' + value[_this6.props.valueKey], onClick: onClick, onRemove: _this6.removeValue, value: value }, renderLabel(value, i), React.createElement( 'span', { className: 'Select-aria-only' }, '\xA0' ) ); }); } else if (!this.state.inputValue) { if (isOpen) onClick = null; return React.createElement( ValueComponent, { id: this._instancePrefix + '-value-item', disabled: this.props.disabled, instancePrefix: this._instancePrefix, onClick: onClick, value: valueArray[0] }, renderLabel(valueArray[0]) ); } } }, { key: 'renderInput', value: function renderInput(valueArray, focusedOptionIndex) { var _classNames, _this7 = this; var className = classNames('Select-input', this.props.inputProps.className); var isOpen = !!this.state.isOpen; var ariaOwns = classNames((_classNames = {}, defineProperty(_classNames, this._instancePrefix + '-list', isOpen), defineProperty(_classNames, this._instancePrefix + '-backspace-remove-message', this.props.multi && !this.props.disabled && this.state.isFocused && !this.state.inputValue), _classNames)); var inputProps = _extends({}, this.props.inputProps, { role: 'combobox', 'aria-expanded': '' + isOpen, 'aria-owns': ariaOwns, 'aria-haspopup': '' + isOpen, 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', 'aria-describedby': this.props['aria-describedby'], 'aria-labelledby': this.props['aria-labelledby'], 'aria-label': this.props['aria-label'], className: className, tabIndex: this.props.tabIndex, onBlur: this.handleInputBlur, onChange: this.handleInputChange, onFocus: this.handleInputFocus, ref: function ref(_ref) { return _this7.input = _ref; }, required: this.state.required, value: this.state.inputValue }); if (this.props.inputRenderer) { return this.props.inputRenderer(inputProps); } if (this.props.disabled || !this.props.searchable) { var _props$inputProps = this.props.inputProps, inputClassName = _props$inputProps.inputClassName, divProps = objectWithoutProperties(_props$inputProps, ['inputClassName']); var _ariaOwns = classNames(defineProperty({}, this._instancePrefix + '-list', isOpen)); return React.createElement('div', _extends({}, divProps, { role: 'combobox', 'aria-expanded': isOpen, 'aria-owns': _ariaOwns, 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', 'aria-labelledby': this.props['aria-labelledby'], 'aria-label': this.props['aria-label'], className: className, tabIndex: this.props.tabIndex || 0, onBlur: this.handleInputBlur, onFocus: this.handleInputFocus, ref: function ref(_ref2) { return _this7.input = _ref2; }, 'aria-disabled': '' + !!this.props.disabled, style: { border: 0, width: 1, display: 'inline-block' } })); } if (this.props.autosize) { return React.createElement(AutosizeInput, _extends({ id: this.props.id }, inputProps, { minWidth: '5' })); } return React.createElement( 'div', { className: className, key: 'input-wrap' }, React.createElement('input', _extends({ id: this.props.id }, inputProps)) ); } }, { key: 'renderClear', value: function renderClear() { var valueArray = this.getValueArray(this.props.value); if (!this.props.clearable || !valueArray.length || this.props.disabled || this.props.isLoading) return; var clear = this.props.clearRenderer(); return React.createElement( 'span', { className: 'Select-clear-zone', title: this.props.multi ? this.props.clearAllText : this.props.clearValueText, 'aria-label': this.props.multi ? this.props.clearAllText : this.props.clearValueText, onMouseDown: this.clearValue, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove, onTouchEnd: this.handleTouchEndClearValue }, clear ); } }, { key: 'renderArrow', value: function renderArrow() { if (!this.props.arrowRenderer) return; var onMouseDown = this.handleMouseDownOnArrow; var isOpen = this.state.isOpen; var arrow = this.props.arrowRenderer({ onMouseDown: onMouseDown, isOpen: isOpen }); if (!arrow) { return null; } return React.createElement( 'span', { className: 'Select-arrow-zone', onMouseDown: onMouseDown }, arrow ); } }, { key: 'filterOptions', value: function filterOptions$$1(excludeOptions) { var filterValue = this.state.inputValue; var options = this.props.options || []; if (this.props.filterOptions) { // Maintain backwards compatibility with boolean attribute var filterOptions$$1 = typeof this.props.filterOptions === 'function' ? this.props.filterOptions : filterOptions; return filterOptions$$1(options, filterValue, excludeOptions, { filterOption: this.props.filterOption, ignoreAccents: this.props.ignoreAccents, ignoreCase: this.props.ignoreCase, labelKey: this.props.labelKey, matchPos: this.props.matchPos, matchProp: this.props.matchProp, valueKey: this.props.valueKey, trimFilter: this.props.trimFilter }); } else { return options; } } }, { key: 'onOptionRef', value: function onOptionRef(ref, isFocused) { if (isFocused) { this.focused = ref; } } }, { key: 'renderMenu', value: function renderMenu(options, valueArray, focusedOption) { if (options && options.length) { return this.props.menuRenderer({ focusedOption: focusedOption, focusOption: this.focusOption, inputValue: this.state.inputValue, instancePrefix: this._instancePrefix, labelKey: this.props.labelKey, onFocus: this.focusOption, onSelect: this.selectValue, optionClassName: this.props.optionClassName, optionComponent: this.props.optionComponent, optionRenderer: this.props.optionRenderer || this.getOptionLabel, options: options, selectValue: this.selectValue, removeValue: this.removeValue, valueArray: valueArray, valueKey: this.props.valueKey, onOptionRef: this.onOptionRef }); } else if (this.props.noResultsText) { return React.createElement( 'div', { className: 'Select-noresults' }, this.props.noResultsText ); } else { return null; } } }, { key: 'renderHiddenField', value: function renderHiddenField(valueArray) { var _this8 = this; if (!this.props.name) return; if (this.props.joinValues) { var value = valueArray.map(function (i) { return stringifyValue(i[_this8.props.valueKey]); }).join(this.props.delimiter); return React.createElement('input', { type: 'hidden', ref: function ref(_ref3) { return _this8.value = _ref3; }, name: this.props.name, value: value, disabled: this.props.disabled }); } return valueArray.map(function (item, index) { return React.createElement('input', { key: 'hidden.' + index, type: 'hidden', ref: 'value' + index, name: _this8.props.name, value: stringifyValue(item[_this8.props.valueKey]), disabled: _this8.props.disabled }); }); } }, { key: 'getFocusableOptionIndex', value: function getFocusableOptionIndex(selectedOption) { var options = this._visibleOptions; if (!options.length) return null; var valueKey = this.props.valueKey; var focusedOption = this.state.focusedOption || selectedOption; if (focusedOption && !focusedOption.disabled) { var focusedOptionIndex = -1; options.some(function (option, index) { var isOptionEqual = option[valueKey] === focusedOption[valueKey]; if (isOptionEqual) { focusedOptionIndex = index; } return isOptionEqual; }); if (focusedOptionIndex !== -1) { return focusedOptionIndex; } } for (var i = 0; i < options.length; i++) { if (!options[i].disabled) return i; } return null; } }, { key: 'renderOuter', value: function renderOuter(options, valueArray, focusedOption) { var _this9 = this; var menu = this.renderMenu(options, valueArray, focusedOption); if (!menu) { return null; } return React.createElement( 'div', { ref: function ref(_ref5) { return _this9.menuContainer = _ref5; }, className: 'Select-menu-outer', style: this.props.menuContainerStyle }, React.createElement( 'div', { ref: function ref(_ref4) { return _this9.menu = _ref4; }, role: 'listbox', tabIndex: -1, className: 'Select-menu', id: this._instancePrefix + '-list', style: this.props.menuStyle, onScroll: this.handleMenuScroll, onMouseDown: this.handleMouseDownOnMenu }, menu ) ); } }, { key: 'render', value: function render() { var _this10 = this; var valueArray = this.getValueArray(this.props.value); var options = this._visibleOptions = this.filterOptions(this.props.multi && this.props.removeSelected ? valueArray : null); var isOpen = this.state.isOpen; if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false; var focusedOptionIndex = this.getFocusableOptionIndex(valueArray[0]); var focusedOption = null; if (focusedOptionIndex !== null) { focusedOption = this._focusedOption = options[focusedOptionIndex]; } else { focusedOption = this._focusedOption = null; } var className = classNames('Select', this.props.className, { 'Select--multi': this.props.multi, 'Select--single': !this.props.multi, 'is-clearable': this.props.clearable, 'is-disabled': this.props.disabled, 'is-focused': this.state.isFocused, 'is-loading': this.props.isLoading, 'is-open': isOpen, 'is-pseudo-focused': this.state.isPseudoFocused, 'is-searchable': this.props.searchable, 'has-value': valueArray.length, 'Select--rtl': this.props.rtl }); var removeMessage = null; if (this.props.multi && !this.props.disabled && valueArray.length && !this.state.inputValue && this.state.isFocused && this.props.backspaceRemoves) { removeMessage = React.createElement( 'span', { id: this._instancePrefix + '-backspace-remove-message', className: 'Select-aria-only', 'aria-live': 'assertive' }, this.props.backspaceToRemoveMessage.replace('{label}', valueArray[valueArray.length - 1][this.props.labelKey]) ); } return React.createElement( 'div', { ref: function ref(_ref7) { return _this10.wrapper = _ref7; }, className: className, style: this.props.wrapperStyle }, this.renderHiddenField(valueArray), React.createElement( 'div', { ref: function ref(_ref6) { return _this10.control = _ref6; }, className: 'Select-control', style: this.props.style, onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleTouchEnd, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove }, React.createElement( 'span', { className: 'Select-multi-value-wrapper', id: this._instancePrefix + '-value' }, this.renderValue(valueArray, isOpen), this.renderInput(valueArray, focusedOptionIndex) ), removeMessage, this.renderLoading(), this.renderClear(), this.renderArrow() ), isOpen ? this.renderOuter(options, valueArray, focusedOption) : null ); } }]); return Select; }(React.Component); Select$1.propTypes = { 'aria-describedby': PropTypes.string, // html id(s) of element(s) that should be used to describe this input (for assistive tech) 'aria-label': PropTypes.string, // aria label (for assistive tech) 'aria-labelledby': PropTypes.string, // html id of an element that should be used as the label (for assistive tech) arrowRenderer: PropTypes.func, // create the drop-down caret element autoBlur: PropTypes.bool, // automatically blur the component when an option is selected autoFocus: PropTypes.bool, // autofocus the component on mount autofocus: PropTypes.bool, // deprecated; use autoFocus instead autosize: PropTypes.bool, // whether to enable autosizing or not backspaceRemoves: PropTypes.bool, // whether backspace removes an item if there is no text input backspaceToRemoveMessage: PropTypes.string, // message to use for screenreaders to press backspace to remove the current item - {label} is replaced with the item label className: PropTypes.string, // className for the outer element clearAllText: stringOrNode, // title for the "clear" control when multi: true clearRenderer: PropTypes.func, // create clearable x element clearValueText: stringOrNode, // title for the "clear" control clearable: PropTypes.bool, // should it be possible to reset value closeOnSelect: PropTypes.bool, // whether to close the menu when a value is selected deleteRemoves: PropTypes.bool, // whether delete removes an item if there is no text input delimiter: PropTypes.string, // delimiter to use to join multiple values for the hidden field value disabled: PropTypes.bool, // whether the Select is disabled or not escapeClearsValue: PropTypes.bool, // whether escape clears the value when the menu is closed filterOption: PropTypes.func, // method to filter a single option (option, filterString) filterOptions: PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values]) id: PropTypes.string, // html id to set on the input element for accessibility or tests ignoreAccents: PropTypes.bool, // whether to strip diacritics when filtering ignoreCase: PropTypes.bool, // whether to perform case-insensitive filtering inputProps: PropTypes.object, // custom attributes for the Input inputRenderer: PropTypes.func, // returns a custom input component instanceId: PropTypes.string, // set the components instanceId isLoading: PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded) joinValues: PropTypes.bool, // joins multiple values into a single form field with the delimiter (legacy mode) labelKey: PropTypes.string, // path of the label value in option objects matchPos: PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: PropTypes.string, // (any|label|value) which option property to filter on menuBuffer: PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu menuContainerStyle: PropTypes.object, // optional style to apply to the menu container menuRenderer: PropTypes.func, // renders a custom menu with options menuStyle: PropTypes.object, // optional style to apply to the menu multi: PropTypes.bool, // multi-value input name: PropTypes.string, // generates a hidden <input /> tag with this field name for html forms noResultsText: stringOrNode, // placeholder displayed when there are no matching search results onBlur: PropTypes.func, // onBlur handler: function (event) {} onBlurResetsInput: PropTypes.bool, // whether input is cleared on blur onChange: PropTypes.func, // onChange handler: function (newValue) {} onClose: PropTypes.func, // fires when the menu is closed onCloseResetsInput: PropTypes.bool, // whether input is cleared when menu is closed through the arrow onFocus: PropTypes.func, // onFocus handler: function (event) {} onInputChange: PropTypes.func, // onInputChange handler: function (inputValue) {} onInputKeyDown: PropTypes.func, // input keyDown handler: function (event) {} onMenuScrollToBottom: PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options onOpen: PropTypes.func, // fires when the menu is opened onSelectResetsInput: PropTypes.bool, // whether input is cleared on select (works only for multiselect) onValueClick: PropTypes.func, // onClick handler for value labels: function (value, event) {} openOnClick: PropTypes.bool, // boolean to control opening the menu when the control is clicked openOnFocus: PropTypes.bool, // always open options menu on focus optionClassName: PropTypes.string, // additional class(es) to apply to the <Option /> elements optionComponent: PropTypes.func, // option component to render in dropdown optionRenderer: PropTypes.func, // optionRenderer: function (option) {} options: PropTypes.array, // array of options pageSize: PropTypes.number, // number of entries to page when using page up/down keys placeholder: stringOrNode, // field placeholder, displayed when there's no value removeSelected: PropTypes.bool, // whether the selected option is removed from the dropdown on multi selects required: PropTypes.bool, // applies HTML5 required attribute when needed resetValue: PropTypes.any, // value to use when you clear the control rtl: PropTypes.bool, // set to true in order to use react-select in right-to-left direction scrollMenuIntoView: PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged searchable: PropTypes.bool, // whether to enable searching feature or not simpleValue: PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false style: PropTypes.object, // optional style to apply to the control tabIndex: stringOrNumber, // optional tab index of the control tabSelectsValue: PropTypes.bool, // whether to treat tabbing out while focused to be value selection trimFilter: PropTypes.bool, // whether to trim whitespace around filter value value: PropTypes.any, // initial field value valueComponent: PropTypes.func, // value component to render valueKey: PropTypes.string, // path of the label value in option objects valueRenderer: PropTypes.func, // valueRenderer: function (option) {} wrapperStyle: PropTypes.object // optional style to apply to the component wrapper }; Select$1.defaultProps = { arrowRenderer: arrowRenderer, autosize: true, backspaceRemoves: true, backspaceToRemoveMessage: 'Press backspace to remove {label}', clearable: true, clearAllText: 'Clear all', clearRenderer: clearRenderer, clearValueText: 'Clear value', closeOnSelect: true, deleteRemoves: true, delimiter: ',', disabled: false, escapeClearsValue: true, filterOptions: filterOptions, ignoreAccents: true, ignoreCase: true, inputProps: {}, isLoading: false, joinValues: false, labelKey: 'label', matchPos: 'any', matchProp: 'any', menuBuffer: 0, menuRenderer: menuRenderer, multi: false, noResultsText: 'No results found', onBlurResetsInput: true, onSelectResetsInput: true, onCloseResetsInput: true, openOnClick: true, optionComponent: Option, pageSize: 5, placeholder: 'Select...', removeSelected: true, required: false, rtl: false, scrollMenuIntoView: true, searchable: true, simpleValue: false, tabSelectsValue: true, trimFilter: true, valueComponent: Value, valueKey: 'value' }; var propTypes = { autoload: PropTypes.bool.isRequired, // automatically call the `loadOptions` prop on-mount; defaults to true cache: PropTypes.any, // object to use to cache results; set to null/false to disable caching children: PropTypes.func.isRequired, // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element ignoreAccents: PropTypes.bool, // strip diacritics when filtering; defaults to true ignoreCase: PropTypes.bool, // perform case-insensitive filtering; defaults to true loadOptions: PropTypes.func.isRequired, // callback to load options asynchronously; (inputValue: string, callback: Function): ?Promise loadingPlaceholder: PropTypes.oneOfType([// replaces the placeholder while options are loading PropTypes.string, PropTypes.node]), multi: PropTypes.bool, // multi-value input noResultsText: PropTypes.oneOfType([// field noResultsText, displayed when no options come back from the server PropTypes.string, PropTypes.node]), onChange: PropTypes.func, // onChange handler: function (newValue) {} onInputChange: PropTypes.func, // optional for keeping track of what is being typed options: PropTypes.array.isRequired, // array of options placeholder: PropTypes.oneOfType([// field placeholder, displayed when there's no value (shared with Select) PropTypes.string, PropTypes.node]), searchPromptText: PropTypes.oneOfType([// label to prompt for search input PropTypes.string, PropTypes.node]), value: PropTypes.any // initial field value }; var defaultCache = {}; var defaultProps = { autoload: true, cache: defaultCache, children: defaultChildren, ignoreAccents: true, ignoreCase: true, loadingPlaceholder: 'Loading...', options: [], searchPromptText: 'Type to search' }; var Async = function (_Component) { inherits(Async, _Component); function Async(props, context) { classCallCheck(this, Async); var _this = possibleConstructorReturn(this, (Async.__proto__ || Object.getPrototypeOf(Async)).call(this, props, context)); _this._cache = props.cache === defaultCache ? {} : props.cache; _this.state = { inputValue: '', isLoading: false, options: props.options }; _this.onInputChange = _this.onInputChange.bind(_this); return _this; } createClass(Async, [{ key: 'componentDidMount', value: function componentDidMount() { var autoload = this.props.autoload; if (autoload) { this.loadOptions(''); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.options !== this.props.options) { this.setState({ options: nextProps.options }); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this._callback = null; } }, { key: 'loadOptions', value: function loadOptions(inputValue) { var _this2 = this; var loadOptions = this.props.loadOptions; var cache = this._cache; if (cache && Object.prototype.hasOwnProperty.call(cache, inputValue)) { this._callback = null; this.setState({ isLoading: false, options: cache[inputValue] }); return; } var callback = function callback(error, data) { var options = data && data.options || []; if (cache) { cache[inputValue] = options; } if (callback === _this2._callback) { _this2._callback = null; _this2.setState({ isLoading: false, options: options }); } }; // Ignore all but the most recent request this._callback = callback; var promise = loadOptions(inputValue, callback); if (promise) { promise.then(function (data) { return callback(null, data); }, function (error) { return callback(error); }); } if (this._callback && !this.state.isLoading) { this.setState({ isLoading: true }); } } }, { key: 'onInputChange', value: function onInputChange(inputValue) { var _props = this.props, ignoreAccents = _props.ignoreAccents, ignoreCase = _props.ignoreCase, onInputChange = _props.onInputChange; var newInputValue = inputValue; if (onInputChange) { var value = onInputChange(newInputValue); // Note: != used deliberately here to catch undefined and null if (value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') { newInputValue = '' + value; } } var transformedInputValue = newInputValue; if (ignoreAccents) { transformedInputValue = stripDiacritics(transformedInputValue); } if (ignoreCase) { transformedInputValue = transformedInputValue.toLowerCase(); } this.setState({ inputValue: newInputValue }); this.loadOptions(transformedInputValue); // Return new input value, but without applying toLowerCase() to avoid modifying the user's view case of the input while typing. return newInputValue; } }, { key: 'noResultsText', value: function noResultsText() { var _props2 = this.props, loadingPlaceholder = _props2.loadingPlaceholder, noResultsText = _props2.noResultsText, searchPromptText = _props2.searchPromptText; var _state = this.state, inputValue = _state.inputValue, isLoading = _state.isLoading; if (isLoading) { return loadingPlaceholder; } if (inputValue && noResultsText) { return noResultsText; } return searchPromptText; } }, { key: 'focus', value: function focus() { this.select.focus(); } }, { key: 'render', value: function render() { var _this3 = this; var _props3 = this.props, children = _props3.children, loadingPlaceholder = _props3.loadingPlaceholder, multi = _props3.multi, onChange = _props3.onChange, placeholder = _props3.placeholder; var _state2 = this.state, isLoading = _state2.isLoading, options = _state2.options; var props = { noResultsText: this.noResultsText(), placeholder: isLoading ? loadingPlaceholder : placeholder, options: isLoading && loadingPlaceholder ? [] : options, ref: function ref(_ref) { return _this3.select = _ref; } }; return children(_extends({}, this.props, props, { isLoading: isLoading, onInputChange: this.onInputChange })); } }]); return Async; }(Component); Async.propTypes = propTypes; Async.defaultProps = defaultProps; function defaultChildren(props) { return React.createElement(Select$1, props); } var CreatableSelect = function (_React$Component) { inherits(CreatableSelect, _React$Component); function CreatableSelect(props, context) { classCallCheck(this, CreatableSelect); var _this = possibleConstructorReturn(this, (CreatableSelect.__proto__ || Object.getPrototypeOf(CreatableSelect)).call(this, props, context)); _this.filterOptions = _this.filterOptions.bind(_this); _this.menuRenderer = _this.menuRenderer.bind(_this); _this.onInputKeyDown = _this.onInputKeyDown.bind(_this); _this.onInputChange = _this.onInputChange.bind(_this); _this.onOptionSelect = _this.onOptionSelect.bind(_this); return _this; } createClass(CreatableSelect, [{ key: 'createNewOption', value: function createNewOption() { var _props = this.props, isValidNewOption = _props.isValidNewOption, newOptionCreator = _props.newOptionCreator, onNewOptionClick = _props.onNewOptionClick, _props$options = _props.options, options = _props$options === undefined ? [] : _props$options; if (isValidNewOption({ label: this.inputValue })) { var option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); var _isOptionUnique = this.isOptionUnique({ option: option }); // Don't add the same option twice. if (_isOptionUnique) { if (onNewOptionClick) { onNewOptionClick(option); } else { options.unshift(option); this.select.selectValue(option); } } } } }, { key: 'filterOptions', value: function filterOptions$$1() { var _props2 = this.props, filterOptions$$1 = _props2.filterOptions, isValidNewOption = _props2.isValidNewOption, options = _props2.options, promptTextCreator = _props2.promptTextCreator; // TRICKY Check currently selected options as well. // Don't display a create-prompt for a value that's selected. // This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array. var excludeOptions = (arguments.length <= 2 ? undefined : arguments[2]) || []; var filteredOptions = filterOptions$$1.apply(undefined, arguments) || []; if (isValidNewOption({ label: this.inputValue })) { var _newOptionCreator = this.props.newOptionCreator; var option = _newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); // TRICKY Compare to all options (not just filtered options) in case option has already been selected). // For multi-selects, this would remove it from the filtered list. var _isOptionUnique2 = this.isOptionUnique({ option: option, options: excludeOptions.concat(filteredOptions) }); if (_isOptionUnique2) { var prompt = promptTextCreator(this.inputValue); this._createPlaceholderOption = _newOptionCreator({ label: prompt, labelKey: this.labelKey, valueKey: this.valueKey }); filteredOptions.unshift(this._createPlaceholderOption); } } return filteredOptions; } }, { key: 'isOptionUnique', value: function isOptionUnique(_ref) { var option = _ref.option, options = _ref.options; var isOptionUnique = this.props.isOptionUnique; options = options || this.props.options; return isOptionUnique({ labelKey: this.labelKey, option: option, options: options, valueKey: this.valueKey }); } }, { key: 'menuRenderer', value: function menuRenderer$$1(params) { var menuRenderer$$1 = this.props.menuRenderer; return menuRenderer$$1(_extends({}, params, { onSelect: this.onOptionSelect, selectValue: this.onOptionSelect })); } }, { key: 'onInputChange', value: function onInputChange(input) { var onInputChange = this.props.onInputChange; // This value may be needed in between Select mounts (when this.select is null) this.inputValue = input; if (onInputChange) { this.inputValue = onInputChange(input); } return this.inputValue; } }, { key: 'onInputKeyDown', value: function onInputKeyDown(event) { var _props3 = this.props, shouldKeyDownEventCreateNewOption = _props3.shouldKeyDownEventCreateNewOption, onInputKeyDown = _props3.onInputKeyDown; var focusedOption = this.select.getFocusedOption(); if (focusedOption && focusedOption === this._createPlaceholderOption && shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })) { this.createNewOption(); // Prevent decorated Select from doing anything additional with this keyDown event event.preventDefault(); } else if (onInputKeyDown) { onInputKeyDown(event); } } }, { key: 'onOptionSelect', value: function onOptionSelect(option, event) { if (option === this._createPlaceholderOption) { this.createNewOption(); } else { this.select.selectValue(option); } } }, { key: 'focus', value: function focus() { this.select.focus(); } }, { key: 'render', value: function render() { var _this2 = this; var _props4 = this.props, newOptionCreator = _props4.newOptionCreator, shouldKeyDownEventCreateNewOption = _props4.shouldKeyDownEventCreateNewOption, refProp = _props4.ref, restProps = objectWithoutProperties(_props4, ['newOptionCreator', 'shouldKeyDownEventCreateNewOption', 'ref']); var children = this.props.children; // We can't use destructuring default values to set the children, // because it won't apply work if `children` is null. A falsy check is // more reliable in real world use-cases. if (!children) { children = defaultChildren$2; } var props = _extends({}, restProps, { allowCreate: true, filterOptions: this.filterOptions, menuRenderer: this.menuRenderer, onInputChange: this.onInputChange, onInputKeyDown: this.onInputKeyDown, ref: function ref(_ref2) { _this2.select = _ref2; // These values may be needed in between Select mounts (when this.select is null) if (_ref2) { _this2.labelKey = _ref2.props.labelKey; _this2.valueKey = _ref2.props.valueKey; } if (refProp) { refProp(_ref2); } } }); return children(props); } }]); return CreatableSelect; }(React.Component); function defaultChildren$2(props) { return React.createElement(Select$1, props); } function isOptionUnique(_ref3) { var option = _ref3.option, options = _ref3.options, labelKey = _ref3.labelKey, valueKey = _ref3.valueKey; return options.filter(function (existingOption) { return existingOption[labelKey] === option[labelKey] || existingOption[valueKey] === option[valueKey]; }).length === 0; } function isValidNewOption(_ref4) { var label = _ref4.label; return !!label; } function newOptionCreator(_ref5) { var label = _ref5.label, labelKey = _ref5.labelKey, valueKey = _ref5.valueKey; var option = {}; option[valueKey] = label; option[labelKey] = label; option.className = 'Select-create-option-placeholder'; return option; } function promptTextCreator(label) { return 'Create option "' + label + '"'; } function shouldKeyDownEventCreateNewOption(_ref6) { var keyCode = _ref6.keyCode; switch (keyCode) { case 9: // TAB case 13: // ENTER case 188: // COMMA return true; } return false; } // Default prop methods CreatableSelect.isOptionUnique = isOptionUnique; CreatableSelect.isValidNewOption = isValidNewOption; CreatableSelect.newOptionCreator = newOptionCreator; CreatableSelect.promptTextCreator = promptTextCreator; CreatableSelect.shouldKeyDownEventCreateNewOption = shouldKeyDownEventCreateNewOption; CreatableSelect.defaultProps = { filterOptions: filterOptions, isOptionUnique: isOptionUnique, isValidNewOption: isValidNewOption, menuRenderer: menuRenderer, newOptionCreator: newOptionCreator, promptTextCreator: promptTextCreator, shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption }; CreatableSelect.propTypes = { // Child function responsible for creating the inner Select component // This component can be used to compose HOCs (eg Creatable and Async) // (props: Object): PropTypes.element children: PropTypes.func, // See Select.propTypes.filterOptions filterOptions: PropTypes.any, // Searches for any matching option within the set of options. // This function prevents duplicate options from being created. // ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean isOptionUnique: PropTypes.func, // Determines if the current input text represents a valid option. // ({ label: string }): boolean isValidNewOption: PropTypes.func, // See Select.propTypes.menuRenderer menuRenderer: PropTypes.any, // Factory to create new option. // ({ label: string, labelKey: string, valueKey: string }): Object newOptionCreator: PropTypes.func, // input change handler: function (inputValue) {} onInputChange: PropTypes.func, // input keyDown handler: function (event) {} onInputKeyDown: PropTypes.func, // new option click handler: function (option) {} onNewOptionClick: PropTypes.func, // See Select.propTypes.options options: PropTypes.array, // Creates prompt/placeholder option text. // (filterText: string): string promptTextCreator: PropTypes.func, ref: PropTypes.func, // Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option. shouldKeyDownEventCreateNewOption: PropTypes.func }; var AsyncCreatableSelect = function (_React$Component) { inherits(AsyncCreatableSelect, _React$Component); function AsyncCreatableSelect() { classCallCheck(this, AsyncCreatableSelect); return possibleConstructorReturn(this, (AsyncCreatableSelect.__proto__ || Object.getPrototypeOf(AsyncCreatableSelect)).apply(this, arguments)); } createClass(AsyncCreatableSelect, [{ key: 'focus', value: function focus() { this.select.focus(); } }, { key: 'render', value: function render() { var _this2 = this; return React.createElement( Async, this.props, function (_ref) { var ref = _ref.ref, asyncProps = objectWithoutProperties(_ref, ['ref']); var asyncRef = ref; return React.createElement( CreatableSelect, asyncProps, function (_ref2) { var ref = _ref2.ref, creatableProps = objectWithoutProperties(_ref2, ['ref']); var creatableRef = ref; return _this2.props.children(_extends({}, creatableProps, { ref: function ref(select) { creatableRef(select); asyncRef(select); _this2.select = select; } })); } ); } ); } }]); return AsyncCreatableSelect; }(React.Component); function defaultChildren$1(props) { return React.createElement(Select$1, props); } AsyncCreatableSelect.propTypes = { children: PropTypes.func.isRequired // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element }; AsyncCreatableSelect.defaultProps = { children: defaultChildren$1 }; Select$1.Async = Async; Select$1.AsyncCreatable = AsyncCreatableSelect; Select$1.Creatable = CreatableSelect; Select$1.Value = Value; Select$1.Option = Option; export { Async, AsyncCreatableSelect as AsyncCreatable, CreatableSelect as Creatable, Value, Option, menuRenderer as defaultMenuRenderer, arrowRenderer as defaultArrowRenderer, clearRenderer as defaultClearRenderer, filterOptions as defaultFilterOptions }; export default Select$1;
client/admin/info/UsageSection.stories.js
Sing-Li/Rocket.Chat
import React from 'react'; import { UsageSection } from './UsageSection'; export default { title: 'admin/info/UsageSection', component: UsageSection, decorators: [ (fn) => <div className='rc-old'>{fn()}</div>, ], }; const statistics = { totalUsers: 'statistics.totalUsers', nonActiveUsers: 'nonActiveUsers', activeUsers: 'statistics.activeUsers', totalConnectedUsers: 'statistics.totalConnectedUsers', onlineUsers: 'statistics.onlineUsers', awayUsers: 'statistics.awayUsers', offlineUsers: 'statistics.offlineUsers', totalRooms: 'statistics.totalRooms', totalChannels: 'statistics.totalChannels', totalPrivateGroups: 'statistics.totalPrivateGroups', totalDirect: 'statistics.totalDirect', totalLivechat: 'statistics.totalLivechat', totalDiscussions: 'statistics.totalDiscussions', totalThreads: 'statistics.totalThreads', totalMessages: 'statistics.totalMessages', totalChannelMessages: 'statistics.totalChannelMessages', totalPrivateGroupMessages: 'statistics.totalPrivateGroupMessages', totalDirectMessages: 'statistics.totalDirectMessages', totalLivechatMessages: 'statistics.totalLivechatMessages', uploadsTotal: 'statistics.uploadsTotal', uploadsTotalSize: 1024, integrations: { totalIntegrations: 'statistics.integrations.totalIntegrations', totalIncoming: 'statistics.integrations.totalIncoming', totalIncomingActive: 'statistics.integrations.totalIncomingActive', totalOutgoing: 'statistics.integrations.totalOutgoing', totalOutgoingActive: 'statistics.integrations.totalOutgoingActive', totalWithScriptEnabled: 'statistics.integrations.totalWithScriptEnabled', }, }; const apps = { totalInstalled: 'statistics.apps.totalInstalled', totalActive: 'statistics.apps.totalActive', }; export const _default = () => <UsageSection statistics={statistics} />; export const withApps = () => <UsageSection statistics={{ ...statistics, apps }} />; export const loading = () => <UsageSection statistics={{}} isLoading />;
js/jqwidgets/demos/react/app/scheduler/monthviewwithautorowheight/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxScheduler from '../../../jqwidgets-react/react_jqxscheduler.js'; class App extends React.Component { componentDidMount () { this.refs.myScheduler.ensureAppointmentVisible('id1'); } render () { let appointments = new Array(); let appointment1 = { id: 'id1', description: 'George brings projector for presentations.', location: '', subject: 'Quarterly Project Review Meeting', calendar: 'Room 1', start: new Date(2016, 10, 23, 9, 0, 0), end: new Date(2016, 10, 23, 16, 0, 0) } let appointment2 = { id: 'id2', description: '', location: '', subject: 'IT Group Mtg.', calendar: 'Room 2', start: new Date(2016, 10, 24, 10, 0, 0), end: new Date(2016, 10, 24, 15, 0, 0) } let appointment3 = { id: 'id3', description: '', location: '', subject: 'Course Social Media', calendar: 'Room 3', start: new Date(2016, 10, 23, 11, 0, 0), end: new Date(2016, 10, 26, 13, 0, 0) } let appointment4 = { id: 'id4', description: '', location: '', subject: 'New Projects Planning', calendar: 'Room 2', start: new Date(2016, 10, 23, 16, 0, 0), end: new Date(2016, 10, 27, 18, 0, 0) } let appointment5 = { id: 'id5', description: '', location: '', subject: 'Interview with James', calendar: 'Room 1', start: new Date(2016, 10, 24, 15, 0, 0), end: new Date(2016, 10, 25, 17, 0, 0) } let appointment6 = { id: 'id6', description: '', location: '', subject: 'Interview with Nancy', calendar: 'Room 4', start: new Date(2016, 10, 24, 14, 0, 0), end: new Date(2016, 10, 30, 16, 0, 0) } appointments.push(appointment1); appointments.push(appointment2); appointments.push(appointment3); appointments.push(appointment4); appointments.push(appointment5); appointments.push(appointment6); // prepare the data let source = { dataType: 'array', dataFields: [ { name: 'id', type: 'string' }, { name: 'description', type: 'string' }, { name: 'location', type: 'string' }, { name: 'subject', type: 'string' }, { name: 'calendar', type: 'string' }, { name: 'start', type: 'date' }, { name: 'end', type: 'date' } ], id: 'id', localData: appointments }; let adapter = new $.jqx.dataAdapter(source); let resources = { colorScheme: 'scheme05', dataField: 'calendar', source: new $.jqx.dataAdapter(source) }; let appointmentDataFields = { from: 'start', to: 'end', id: 'id', description: 'description', location: 'place', subject: 'subject', resourceId: 'calendar' }; let views = [ 'dayView', 'weekView', { type: 'monthView', monthRowAutoHeight: true } ]; return ( <JqxScheduler ref='myScheduler' width={850} height={600} source={adapter} date={new $.jqx.date(2016, 11, 23)} showLegend={true} view={'monthView'} resources={resources} views={views} appointmentDataFields={appointmentDataFields} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
app/user/profile/UnselectedProfileSkillListItem.js
ecellju/internship-portal
import React from 'react'; import { Label, Icon } from 'semantic-ui-react'; import PropTypes from 'prop-types'; export default class UnselectedProfileSkillListItem extends React.Component { constructor() { super(); this.handleClick = (event, data) => { console.log(data.children[0].props.children); this.props.restoreSkill(data.children[0].props.children); }; } render() { return ( <Label onClick={this.handleClick} key={this.props.skill} className="hover-add-label" as="a" > <span className="hover-label-text">{this.props.skill}</span> <Icon className="hover-visible" name="checkmark" /> </Label> ); } } UnselectedProfileSkillListItem.propTypes = { skill: PropTypes.string.isRequired, restoreSkill: PropTypes.func.isRequired, };
packages/television/src/components/Head/Favicons.js
accosine/poltergeist
import React from 'react'; export default ({ config: { media, mediasuffix } }) => [ <link rel="apple-touch-icon" sizes="57x57" href={`${media}apple-touch-icon-57x57.png${mediasuffix}`} />, <link rel="apple-touch-icon" sizes="60x60" href={`${media}apple-touch-icon-60x60.png${mediasuffix}`} />, <link rel="apple-touch-icon" sizes="72x72" href={`${media}apple-touch-icon-72x72.png${mediasuffix}`} />, <link rel="apple-touch-icon" sizes="76x76" href={`${media}apple-touch-icon-76x76.png${mediasuffix}`} />, <link rel="apple-touch-icon" sizes="114x114" href={`${media}apple-touch-icon-114x114.png${mediasuffix}`} />, <link rel="apple-touch-icon" sizes="120x120" href={`${media}apple-touch-icon-120x120.png${mediasuffix}`} />, <link rel="apple-touch-icon" sizes="144x144" href={`${media}apple-touch-icon-144x144.png${mediasuffix}`} />, <link rel="apple-touch-icon" sizes="152x152" href={`${media}apple-touch-icon-152x152.png${mediasuffix}`} />, <link rel="apple-touch-icon" sizes="180x180" href={`${media}apple-touch-icon-180x180.png${mediasuffix}`} />, <link rel="icon" type="image/png" href={`${media}favicon-32x32.png${mediasuffix}`} sizes="32x32" />, <link rel="icon" type="image/png" href={`${media}android-chrome-192x192.png${mediasuffix}`} sizes="192x192" />, <link rel="icon" type="image/png" href={`${media}favicon-96x96.png${mediasuffix}`} sizes="96x96" />, <link rel="icon" type="image/png" href={`${media}favicon-16x16.png${mediasuffix}`} sizes="16x16" />, <link rel="mask-icon" href={`${media}safari-pinned-tab.svg${mediasuffix}`} color="#5bbad5" />, <meta name="msapplication-TileColor" content="#da532c" />, <meta name="msapplication-TileImage" content={`${media}mstile-144x144.png${mediasuffix}`} />, <meta name="theme-color" content="#ffffff" />, ];
docs/client/components/pages/Focus/SimpleFocusEditor/index.js
dagopert/draft-js-plugins
import React, { Component } from 'react'; import { convertFromRaw, EditorState, } from 'draft-js'; import Editor, { composeDecorators } from 'draft-js-plugins-editor'; import createFocusPlugin from 'draft-js-focus-plugin'; import createColorBlockPlugin from './colorBlockPlugin'; import editorStyles from './editorStyles.css'; const focusPlugin = createFocusPlugin(); const decorator = composeDecorators( focusPlugin.decorator, ); const colorBlockPlugin = createColorBlockPlugin({ decorator }); const plugins = [focusPlugin, colorBlockPlugin]; /* eslint-disable */ const initialState = { "entityMap": { "0": { "type": "colorBlock", "mutability": "IMMUTABLE", "data": {} } }, "blocks": [{ "key": "9gm3s", "text": "This is a simple example. Focus the block by clicking on it and change alignment via the toolbar.", "type": "unstyled", "depth": 0, "inlineStyleRanges": [], "entityRanges": [], "data": {} }, { "key": "ov7r", "text": " ", "type": "atomic", "depth": 0, "inlineStyleRanges": [], "entityRanges": [{ "offset": 0, "length": 1, "key": 0 }], "data": {} }, { "key": "e23a8", "text": "More text here to demonstrate how inline left/right alignment works …", "type": "unstyled", "depth": 0, "inlineStyleRanges": [], "entityRanges": [], "data": {} }] }; /* eslint-enable */ export default class CustomImageEditor extends Component { state = { editorState: EditorState.createWithContent(convertFromRaw(initialState)), }; onChange = (editorState) => { this.setState({ editorState, }); }; focus = () => { this.editor.focus(); }; render() { return ( <div className={editorStyles.editor} onClick={this.focus}> <Editor editorState={this.state.editorState} onChange={this.onChange} plugins={plugins} ref={(element) => { this.editor = element; }} /> </div> ); } }
packages/ndla-image-search/src/ImageSearchForm.js
netliferesearch/frontend-packages
/** * Copyright (c) 2016-present, NDLA. * * This source code is licensed under the GPLv3 license found in the * LICENSE file in the root directory of this source tree. * */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Button } from 'ndla-ui'; import BEMHelper from 'react-bem-helper'; const classes = new BEMHelper({ name: 'image-search', prefix: 'c-', }); class SearchForm extends Component { constructor(props) { super(props); this.state = { query: props.query, }; this.handleQueryChange = this.handleQueryChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.onKeyPress = this.onKeyPress.bind(this); } onKeyPress(evt) { if (evt.key === 'Enter') { this.handleSubmit(evt); } } handleQueryChange(evt) { this.setState({ query: evt.target.value }); } handleSubmit(evt) { evt.preventDefault(); this.props.onSearchQuerySubmit(this.state.query); } render() { const { searching, searchPlaceholder, searchButtonTitle } = this.props; return ( <div {...classes('form')}> <input {...classes('form-query')} type="text" onChange={this.handleQueryChange} onKeyPress={this.onKeyPress} value={this.state.query} placeholder={searchPlaceholder} /> <Button {...classes('form-button')} onClick={this.handleSubmit} loading={searching}> {searchButtonTitle} </Button> </div> ); } } SearchForm.propTypes = { query: PropTypes.string, searching: PropTypes.bool.isRequired, onSearchQuerySubmit: PropTypes.func.isRequired, searchPlaceholder: PropTypes.string.isRequired, searchButtonTitle: PropTypes.string.isRequired, }; SearchForm.defaultProps = { query: '', }; export default SearchForm;
packages/components/src/DateTimePickers/pickers/TimePicker/TimePicker.component.js
Talend/ui
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { timeToStr, pad } from '../../Time/time-extraction'; import withListGesture from '../../../Gesture/withListGesture'; import theme from './TimePicker.scss'; function isBefore(a, b) { if (a.hours > b.hours) { return false; } else if (a.hours === b.hours && a.minutes > b.minutes) { return false; } else if (a.hours === b.hours && a.minutes === b.minutes && a.seconds >= b.seconds) { return false; } return true; } function addInterval({ hours, minutes, ...seconds }, interval = 60) { let newMinutes = minutes + interval; let newHours = hours; if (Math.floor(newMinutes / 60) > 0) { newHours += Math.floor(newMinutes / 60); newMinutes %= 60; } return { hours: newHours, minutes: newMinutes, ...seconds, }; } function getOptions(interval = 60, useSeconds) { const options = []; const start = { hours: 0, minutes: 0, seconds: 0 }; const end = { hours: 23, minutes: 59, seconds: 59 }; let current = start; while (isBefore(current, end)) { options.push({ label: timeToStr(current, useSeconds), value: current }); current = addInterval(current, interval); } return options; } export class TimePicker extends React.Component { static propTypes = { interval: PropTypes.number, onChange: PropTypes.func.isRequired, onKeyDown: PropTypes.func.isRequired, textInput: PropTypes.string, useSeconds: PropTypes.bool, }; static defaultProps = { interval: 60, useSeconds: false, }; constructor(props) { super(props); this.onSelect = this.onSelect.bind(this); this.updateHighlightIndex = this.updateHighlightIndex.bind(this); this.scrollItemIntoView = this.scrollItemIntoView.bind(this); this.options = getOptions(props.interval, props.useSeconds); this.state = { hightlightedItemIndex: this.options.findIndex(option => option.label.includes(props.textInput), ), }; } componentDidMount() { if (this.props.textInput) { this.scrollItemIntoView(this.props.textInput); } } onSelect(event, option, index) { this.setState({ hightlightedItemIndex: index }, () => this.props.onChange(event, { textInput: option.label, time: { hours: pad(option.value.hours), minutes: pad(option.value.minutes), seconds: pad(option.value.seconds), }, }), ); } scrollItemIntoView(textInput) { const found = this.options.findIndex(option => option.label.includes(textInput)); if (found) { const ref = this.containerRef.childNodes[found]; if (ref) { ref.scrollIntoView({ block: 'center', }); } if (found !== this.state.hightlightedItemIndex) { this.updateHighlightIndex(found); } } } updateHighlightIndex(index) { this.setState(({ hightlightedItemIndex }) => { if (hightlightedItemIndex !== index) { return { hightlightedItemIndex: index, }; } return null; }); } render() { return ( <div className={theme.container} ref={ref => (this.containerRef = ref)} role="list"> {this.options.map((option, index) => { const className = classNames('tc-time-picker-time', { highlight: index === this.state.hightlightedItemIndex, }); const ariaProps = {}; if (index === this.state.hightlightedItemIndex) { ariaProps['aria-current'] = 'time'; } return ( <button tabIndex={-1} role="listitem" type="button" key={index} className={className} onClick={event => this.onSelect(event, option)} onKeyDown={event => this.props.onKeyDown(event, this.containerRef.childNodes[index])} {...ariaProps} > {option.label} </button> ); })} </div> ); } } export default withListGesture(TimePicker, true);
mdbreact/components/NavItem.js
ryanwashburne/react-skeleton
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; class NavItem extends Component { render() { const { children, className, tag: Tag, ...attributes } = this.props; const classes = classNames( 'nav-item', className, ); return ( <Tag {...attributes} className={classes}> {children} </Tag> ); } } NavItem.propTypes = { tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]), className: PropTypes.string, children: PropTypes.node }; NavItem.defaultProps = { tag: 'li' }; export default NavItem;
graphwalker-studio/src/main/js/index.js
KristianKarl/graphwalker-project
import "core-js/stable"; import "regenerator-runtime/runtime"; import React from 'react'; import { render } from "react-dom"; import { Provider } from 'react-redux' import store from './redux/store' import Application from './Application'; render(<Provider store={store}><Application /></Provider>, document.getElementById('root'));
src/js/admin/articles/filters/label-filter/label-filter.js
ucev/blog
import React from 'react' import { connect } from 'react-redux' import FilterInput from '../filter-input' const LabelFilter = ({ value }) => ( <FilterInput title="标签" label="label" value={value} /> ) const mapStateToProps = state => ({ value: state.filters.label, }) const mapDispatchToProps = () => ({}) const _LabelFilter = connect( mapStateToProps, mapDispatchToProps )(LabelFilter) export default _LabelFilter
packages/veritone-react-common/src/components/OAuthLoginButton/story.js
veritone/veritone-sdk
import React from 'react'; import { storiesOf } from '@storybook/react'; import OAuthLoginButton from './'; storiesOf('OAuthLoginButton', module) .add('With text', () => { return <OAuthLoginButton />; }) .add('Logo icon only', () => { return <OAuthLoginButton iconOnly />; });
frontend/js/components/ecosystems/LocationForm.js
Code4HR/okcandidate-platform
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Hr from './../atoms/Hr'; import Alert from './../organisms/Alert'; import TextField from './../organisms/TextField'; import { getLocationByGPS, getLocationByAddress, fetchNonRegionLimitedSurveys } from './../../redux/actions/pick-survey-actions'; class LocationForm extends Component { constructor(props) { super(props); this.state = {address: ''}; } updateAddress(event) { const address = event.target.value; this.setState({ address: address }); } search(event) { event && event.preventDefault(); this.props.dispatch(getLocationByAddress(this.state.address), () => { this.setState({address: ''}); }); } geolocate() { this.props.dispatch(getLocationByGPS()); } skip() { this.props.dispatch(fetchNonRegionLimitedSurveys()); } render() { return ( <form className="location-form" onSubmit={this.search.bind(this)}> <section> {this.props.status.message && <Alert level={this.props.status.level} message={this.props.status.message} /> } </section> <section className="by-address"> <TextField label="Locate Using Address" name="address" value={this.state.address} onChange={this.updateAddress.bind(this)} button={ <button type="button" onClick={this.search.bind(this)}> Search </button> }/> </section> <Hr label="or" /> <section className="by-gps"> <label htmlFor="gps">Or use GPS</label> <button type="button" id="gps" onClick={this.geolocate.bind(this)}> Use GPS </button> </section> <Hr label="or" /> <section className="skip"> <label htmlFor="skip">Or skip it</label> <button type="button" id="skip" onClick={this.skip.bind(this)}> Don't search </button> </section> </form> ); } } LocationForm.propTypes = { dispatch: PropTypes.func, addressError: PropTypes.string, status: PropTypes.object }; export default LocationForm;
src/screens/App/components/Header.js
enesTufekci/react-clear-starter-kit
/* @flow */ import React from 'react'; const Header = () => ( <div className="App-header"> <h2>React Clear Starter Kit</h2> </div> ); export default Header;
webpack/containers/questions/QuestionModalContainer.js
CDCgov/SDP-Vocabulary-Service
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { Modal, Button, Row, Col } from 'react-bootstrap'; import $ from 'jquery'; import { saveQuestion } from '../../actions/questions_actions'; import { fetchPotentialDuplicateQuestions } from '../../actions/search_results_actions'; import Errors from '../../components/Errors'; import QuestionEdit from '../../components/questions/QuestionEdit'; import ResponseSetList from '../../components/response_sets/ResponseSetList'; import ResponseSetDragWidget from '../response_sets/ResponseSetDragWidget'; import { fetchResponseTypes } from '../../actions/response_type_actions'; import { fetchCategories } from '../../actions/category_actions'; import currentUserProps from '../../prop-types/current_user_props'; const DUPLICATE_QUESTION_MODAL_CONTEXT = "DUPLICATE_QUESTION_MODAL_CONTEXT"; class QuestionModalContainer extends Component { constructor(props) { super(props); this.state = {linkedResponseSets: [], showResponseSetWidget: false, showResponseSets: false}; this.saveNewQuestion = this.saveNewQuestion.bind(this); this.closeQuestionModal = this.closeQuestionModal.bind(this); this.handleResponseSetsChange = this.handleResponseSetsChange.bind(this); this.handleResponseTypeChange = this.handleResponseTypeChange.bind(this); this.fetchPotentialDuplicateQuestions = this.fetchPotentialDuplicateQuestions.bind(this); } componentWillMount() { this.props.fetchCategories(); this.props.fetchResponseTypes(); } handleResponseSetsChange(newResponseSets){ this.unsavedState = true; this.setState({linkedResponseSets: newResponseSets}); } handleResponseTypeChange(newResponseType){ if(['Choice', 'Open Choice'].indexOf(newResponseType.name)!==-1){ this.setState({showResponseSets: true}); } else { this.setState({showResponseSets: false, linkedResponseSets: []}); } } saveNewQuestion(newQuestion){ newQuestion.linkedResponseSets = this.state.linkedResponseSets; this.props.saveQuestion(newQuestion, '', false, {}, (successResponse) => { this.setState({showResponseSetWidget: false, linkedResponseSets: [], errors: null}); this.props.handleSaveQuestionSuccess(successResponse); }, (failureResponse) => { this.setState({errors: failureResponse.response.data}); }); } closeQuestionModal(){ this.setState({showResponseSets: false, showResponseSetWidget:false, linkedResponseSets: [], errors: null}); this.props.closeQuestionModal(); } fetchPotentialDuplicateQuestions(content, description) { this.props.fetchPotentialDuplicateQuestions(DUPLICATE_QUESTION_MODAL_CONTEXT, content, description); } responseSetWidgetBody(){ return ( <div className={this.state.showResponseSetWidget ? '' : 'hidden'}> <Modal.Body bsStyle='response-set'> <Row className="response-set-row"> <Col md={6} className="response-set-label"> <h2>Response Sets</h2> </Col> <Col md={6} className="response-set-label"> <h2 className="tags-table-header">Selected Response Sets</h2> </Col> </Row> <ResponseSetDragWidget selectedResponseSets={this.state.linkedResponseSets} handleResponseSetsChange={this.handleResponseSetsChange} /> </Modal.Body> <Modal.Footer> <Button onClick={() => this.setState({showResponseSetWidget:false})} bsStyle="primary">Done</Button> </Modal.Footer> </div> ); } questionFormFooter(){ if(this.state.showResponseSets){ return ( <Modal.Footer> <Button onClick={() => $('#submit-question-form').click()}>Add Question</Button> <Button onClick={() => this.setState({showResponseSetWidget:true})} bsStyle="primary">Response Sets</Button> </Modal.Footer> ); } else { return ( <Modal.Footer> <Button onClick={() => $('#submit-question-form').click()}>Add Question</Button> </Modal.Footer> ); } } questionFormBody(){ var responseSetsDiv = (<div></div>); var footer = ( <Modal.Footer> <Button onClick={() => $('#submit-question-form').click()}>Add Question</Button> </Modal.Footer> ); if(this.state.showResponseSets){ responseSetsDiv = ( <Row className="selected_response_sets"> <Col md={12} className="response-set-label"> <h2>Response Sets</h2> </Col> <Col md={8}> <div className="panel panel-default"> <div className="panel-body"> {this.state.linkedResponseSets.length > 0 ? <ResponseSetList responseSets={this.state.linkedResponseSets} /> : 'No Response Sets selected'} </div> </div> </Col> </Row> ); footer = ( <Modal.Footer> <Button onClick={() => $('#submit-question-form').click()}>Add Question</Button> <Button onClick={() => this.setState({showResponseSetWidget:true})} bsStyle="primary">Response Sets</Button> </Modal.Footer> ); } return ( <div className={this.state.showResponseSetWidget ? 'hidden' : ''}> <Modal.Body bsStyle='question'> <QuestionEdit action={'new'} question={{}} categories={this.props.categories} responseTypes={this.props.responseTypes} draftSubmitter ={()=>{}} deleteSubmitter={()=>{}} publishSubmitter ={()=>{}} fetchPotentialDuplicateQuestions={this.fetchPotentialDuplicateQuestions} currentUser={this.props.currentUser} potentialDuplicates={this.props.potentialDuplicates} questionSubmitter={this.saveNewQuestion} handleResponseTypeChange={this.handleResponseTypeChange} /> {responseSetsDiv} </Modal.Body> {footer} </div> ); } render() { if(!this.props.categories || !this.props.responseTypes){ return ( <div>Loading...</div> ); } return ( <Modal bsStyle='question' show={this.props.showModal} onHide={this.closeQuestionModal} aria-label="New Question"> <Modal.Header closeButton bsStyle='question'> <Modal.Title componentClass="h1">New Question</Modal.Title> </Modal.Header> <Errors errors={this.state.errors} /> {this.questionFormBody()} {this.responseSetWidgetBody()} </Modal> ); } } function mapStateToProps(state) { return {categories: state.categories, responseTypes: state.responseTypes, currentUser: state.currentUser, potentialDuplicates: state.searchResults[DUPLICATE_QUESTION_MODAL_CONTEXT] || {}}; } function mapDispatchToProps(dispatch) { return bindActionCreators({fetchCategories, fetchResponseTypes, saveQuestion, fetchPotentialDuplicateQuestions}, dispatch); } QuestionModalContainer.propTypes = { route: PropTypes.object.isRequired, router: PropTypes.object.isRequired, showModal: PropTypes.bool.isRequired, saveQuestion: PropTypes.func, categories: PropTypes.object, responseTypes: PropTypes.object, fetchCategories: PropTypes.func, fetchResponseTypes: PropTypes.func, closeQuestionModal: PropTypes.func.isRequired, handleSaveQuestionSuccess: PropTypes.func.isRequired, fetchPotentialDuplicateQuestions: PropTypes.func, currentUser: currentUserProps, potentialDuplicates: PropTypes.object }; export default connect(mapStateToProps, mapDispatchToProps)(QuestionModalContainer);
src/components/UserDetailSections/ExtendedInfo/components/RequestPreferencesView/RequestPreferencesView.js
folio-org/ui-users
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Col, KeyValue, Row, } from '@folio/stripes/components'; import { requestPreferencesShape } from '../../../../../shapes'; import styles from './RequestPreferencesView.css'; class RequestPreferencesView extends Component { static propTypes = { requestPreferences: requestPreferencesShape, defaultServicePointName: PropTypes.string, defaultDeliveryAddressTypeName: PropTypes.string.isRequired, }; getHoldShelfStateTranslationKey() { return this.props.requestPreferences.holdShelf ? 'ui-users.requests.holdShelfYes' : 'ui-users.requests.holdShelfNo'; } getDeliveryStateTranslationKey() { return this.props.requestPreferences.delivery ? 'ui-users.requests.deliveryYes' : 'ui-users.requests.deliveryNo'; } render() { const { requestPreferences, defaultServicePointName, defaultDeliveryAddressTypeName, } = this.props; return ( <> <Row> <Col xs={4}> <span className={styles.heading}> <FormattedMessage id="ui-users.requests.preferences" /> </span> </Col> </Row> <Row className={styles['request-preferences-row']}> <Col xs={4} data-test-hold-shelf> <FormattedMessage id={this.getHoldShelfStateTranslationKey()} /> </Col> <Col xs={4} data-test-delivery> <FormattedMessage id={this.getDeliveryStateTranslationKey()} /> </Col> </Row> <Row> <Col xs={4}> {requestPreferences.holdShelf && ( <KeyValue label={<FormattedMessage id="ui-users.requests.defaultPickupServicePoint" />}> <span data-test-default-pickup-service-point> { defaultServicePointName || '-' } </span> </KeyValue> )} </Col> <Col xs={4}> {requestPreferences.delivery && ( <KeyValue label={<FormattedMessage id="ui-users.requests.fulfillmentPreference" />}> <span data-test-fulfillment-preference> { requestPreferences.fulfillment } </span> </KeyValue> )} </Col> </Row> <Row> <Col xsOffset={4} xs={8}> {requestPreferences.delivery && ( <KeyValue label={<FormattedMessage id="ui-users.requests.defaultDeliveryAddress" />}> <span data-test-default-delivery-address> { defaultDeliveryAddressTypeName || '-'} </span> </KeyValue> )} </Col> </Row> </> ); } } export default RequestPreferencesView;
src/containers/views/PageNew.js
jekyll/jekyll-admin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { browserHistory, withRouter } from 'react-router'; import DocumentTitle from 'react-document-title'; import CreateMarkdownPage from '../../components/CreateMarkdownPage'; import { updateTitle, updateBody, updatePath } from '../../ducks/metadata'; import { createPage } from '../../ducks/pages'; import { clearErrors } from '../../ducks/utils'; import { preventDefault, getDocumentTitle } from '../../utils/helpers'; import { ADMIN_PREFIX } from '../../constants'; import translations from '../../translations'; const { getLeaveMessage } = translations; export class PageNew extends Component { componentDidMount() { const { router, route } = this.props; router.setRouteLeaveHook(route, this.routerWillLeave); } componentWillReceiveProps(nextProps) { if (this.props.updated !== nextProps.updated) { browserHistory.push(`${ADMIN_PREFIX}/pages/${nextProps.page.path}`); } } componentWillUnmount() { const { clearErrors, errors } = this.props; errors.length && clearErrors(); } routerWillLeave = nextLocation => { if (this.props.fieldChanged) { return getLeaveMessage(); } }; handleClickSave = e => { preventDefault(e); const { fieldChanged, createPage, params } = this.props; fieldChanged && createPage(params.splat); }; render() { const { params, config, errors, updated, updateBody, updatePath, updateTitle, fieldChanged, } = this.props; const title = getDocumentTitle('pages', params.splat, 'New page'); return ( <DocumentTitle title={title}> <CreateMarkdownPage type="pages" params={params} config={config} errors={errors} updated={updated} updateBody={updateBody} updatePath={updatePath} updateTitle={updateTitle} fieldChanged={fieldChanged} onClickSave={this.handleClickSave} /> </DocumentTitle> ); } } PageNew.propTypes = { createPage: PropTypes.func.isRequired, updateTitle: PropTypes.func.isRequired, updateBody: PropTypes.func.isRequired, updatePath: PropTypes.func.isRequired, clearErrors: PropTypes.func.isRequired, errors: PropTypes.array.isRequired, fieldChanged: PropTypes.bool.isRequired, updated: PropTypes.bool.isRequired, router: PropTypes.object.isRequired, route: PropTypes.object.isRequired, params: PropTypes.object.isRequired, config: PropTypes.object.isRequired, page: PropTypes.object.isRequired, }; const mapStateToProps = state => ({ page: state.pages.page, fieldChanged: state.metadata.fieldChanged, errors: state.utils.errors, updated: state.pages.updated, config: state.config.config, }); const mapDispatchToProps = dispatch => bindActionCreators( { updateTitle, updateBody, updatePath, createPage, clearErrors, }, dispatch ); export default withRouter( connect(mapStateToProps, mapDispatchToProps)(PageNew) );
app/containers/SignUpContainer.js
jcarral/cafeADE
import React, { Component } from 'react'; import { connect } from 'react-redux'; import SignUp from '../components/SignUp'; import LoadingPage from '../components/LoadingPage'; import { signUp } from '../actions/statusActions'; class SignUpContainer extends Component { static navigationOptions = { title: 'Registro' } constructor(props){ super(props); this.state = { username : '', pwd: '', email: '' }; } handleUsername = (e) => { this.setState({username: e}); } handlePwd = (e) => { this.setState({pwd: e}); } handleEmail = (e) => { this.setState({email: e}); } handleSubmit = () => { this.props.dispatch(signUp(this.state)) } render(){ if(this.props.loading){ return (<LoadingPage />); }else{ return ( <SignUp handlePwd={this.handlePwd} handleUsername={this.handleUsername} handleEmail={this.handleEmail} handleSubmit={this.handleSubmit} error={this.props.error} pwd={this.state.pwd} name={this.state.username} email={this.state.email} /> ); } } } const mapStateToProps = (state, action) => ({ error: state.status.error, loading: state.status.loading }); export default connect(mapStateToProps)(SignUpContainer);
src/routes/authority/account/Filter.js
muidea/magicSite
import React from 'react' import PropTypes from 'prop-types' import { Form, Button, Row, Col, Input, Popconfirm } from 'antd' const { Search } = Input const ColProps = { xs: 24, sm: 12, style: { marginBottom: 16 }, } const TwoColProps = { ...ColProps, xl: 96, } const Filter = ({ onAdd, onFilterChange, onDeleteItems, selectedRowKeys, filter, form: { getFieldDecorator, getFieldsValue, setFieldsValue, }, }) => { const handleFields = (fields) => { return fields } const handleSubmit = () => { let fields = getFieldsValue() fields = handleFields(fields) onFilterChange(fields) } const handleReset = () => { const fields = getFieldsValue() for (const item in fields) { if ({}.hasOwnProperty.call(fields, item)) { if (fields[item] instanceof Array) { fields[item] = [] } else { fields[item] = undefined } } } setFieldsValue(fields) handleSubmit() } const handleDeleteItems = () => { onDeleteItems() } const { name } = filter return ( <Row gutter={24}> <Col {...ColProps} xl={{ span: 14 }} md={{ span: 14 }}> {getFieldDecorator('name', { initialValue: name })(<Search placeholder="查找分组" size="large" onSearch={handleSubmit} />)} </Col> <Col {...TwoColProps} xl={{ span: 10 }} md={{ span: 10 }} sm={{ span: 10 }}> <div style={{ display: 'flex', justifyContent: 'space-between' }}> <div > <Button type="primary" size="large" className="margin-right" onClick={handleSubmit}>查找</Button> <Button size="large" onClick={handleReset}>重置</Button> </div> <div> { selectedRowKeys.length > 0 && <Popconfirm title="确认删除选中项?" placement="left" onConfirm={handleDeleteItems}> <Button type="primary" style={{ marginRight: 16 }} size="large">删除</Button> </Popconfirm> } <Button size="large" type="ghost" onClick={onAdd}>新建</Button> </div> </div> </Col> </Row> ) } Filter.propTypes = { selectedRowKeys: PropTypes.array, onDeleteItems: PropTypes.func, onAdd: PropTypes.func, form: PropTypes.object, filter: PropTypes.object, onFilterChange: PropTypes.func, } export default Form.create()(Filter)
packages/es-components/src/components/controls/radio-buttons/RadioButton.js
jrios/es-components
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Label from '../label/Label'; import getRadioFillVariables from './radio-fill-variables'; import { useTheme } from '../../util/useTheme'; import ValidationContext from '../ValidationContext'; import useUniqueId from '../../util/useUniqueId'; function radioFill(color) { return ` background-color: ${color}; border-radius: 50%; content: ''; display: block; height: 13px; left: 3px; position: relative; width: 13px; top: 3px; transition: background 0.25s linear; `; } const RadioLabel = styled(Label)` align-self: flex-start; cursor: pointer; display: flex; font-family: 'Source Sans Pro', 'Segoe UI', Segoe, Calibri, Tahoma, sans-serif; font-size: ${props => props.theme.sizes.baseFontSize}; font-weight: normal; line-height: ${props => props.theme.sizes.baseLineHeight}; margin-right: 15px; margin-bottom: 10px; position: relative; padding: 10px 0 10px 10px; text-transform: none; &:hover .es-radio__fill:before { ${props => !props.checked && radioFill(props.hoverFillColor)}; } @media (min-width: ${props => props.theme.screenSize.tablet}) { padding: 5px 0; } `; const RadioInput = styled.input` clip: rect(0, 0, 0, 0); pointer-events: none; position: absolute; &:focus ~ .es-radio__fill { box-shadow: 0 0 3px 3px ${props => props.theme.colors.inputFocus}; } `; const RadioDisplay = styled.span` border: 3px solid ${props => props.borderColor}; border-radius: 50%; box-sizing: border-box; height: 25px; margin-right: 8px; min-width: 25px; &:before { ${props => radioFill(props.fill)}; } `; export function RadioButton({ children, ...radioProps }) { const id = useUniqueId(radioProps.id); const isChecked = radioProps.checked || radioProps.defaultChecked; const theme = useTheme(); const validationState = React.useContext(ValidationContext); const { hover, fill } = getRadioFillVariables( isChecked, radioProps.disabled, validationState, theme.colors ); const radioDisplayFill = isChecked ? fill : theme.colors.white; const labelProps = { disabled: radioProps.disabled, htmlFor: id, hoverFillColor: hover, validationState, checked: isChecked }; return ( <RadioLabel {...labelProps}> <RadioInput type="radio" id={id} {...radioProps} /> <RadioDisplay className="es-radio__fill" borderColor={fill} fill={radioDisplayFill} /> {children} </RadioLabel> ); } RadioButton.propTypes = { children: PropTypes.any }; RadioButton.defaultProps = { children: undefined }; export default RadioButton;
test/integration/scss-fixtures/npm-import-nested/pages/_app.js
JeromeFitz/next.js
import React from 'react' import App from 'next/app' import '../styles/global.scss' class MyApp extends App { render() { const { Component, pageProps } = this.props return <Component {...pageProps} /> } } export default MyApp
app/components/Product.js
Byte-Code/lm-digital-store-private-test
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { Map, fromJS } from 'immutable'; import glamorous from 'glamorous'; import throttle from 'lodash/throttle'; import inRange from 'lodash/inRange'; import ImageSlider from './ImageSlider'; import ProductInfo from './ProductInfo'; import ProductInfoBadge from './ProductInfoBadge'; import SimilarProducts from './SimilarProducts'; import ScrollableDiv from './ScrollableDiv'; export default class Product extends Component { static propTypes = { params: PropTypes.shape({ productCode: PropTypes.string.isRequired }).isRequired, productInfo: ImmutablePropTypes.map, requestFetchProduct: PropTypes.func.isRequired, clearProductList: PropTypes.func.isRequired, setAnalyticsProductClick: PropTypes.func.isRequired, similarProducts: ImmutablePropTypes.list.isRequired, hasNearbyStores: PropTypes.bool.isRequired }; static defaultProps = { productInfo: Map() }; constructor(props) { super(props); this.throttleValue = 500; this.onScrolling = this.onScrolling.bind(this); this.setScrollValue = this.setScrollValue.bind(this); this.renderAnimatedTitle = this.renderAnimatedTitle.bind(this); this.getOpacity = this.getOpacity.bind(this); this.state = { scrollValue: 0 }; } componentDidMount() { const { params: { productCode }, requestFetchProduct } = this.props; requestFetchProduct(productCode); } componentWillReceiveProps(nextProps) { const prevProductCode = this.props.params.productCode; const { params: { productCode }, requestFetchProduct } = nextProps; if (prevProductCode !== productCode) { requestFetchProduct(productCode); } } componentWillUnmount() { this.props.clearProductList(); } onScrolling(scrollValue) { this.setScrollValue(scrollValue); } setScrollValue(scrollValue) { (throttle(() => { this.setState({ scrollValue }); }, this.throttleValue))(); } getOpacity() { const { scrollValue } = this.state; let opacity = 1; if (this.state.scrollValue) { if (inRange(scrollValue, 1, 400)) opacity = 0.75; if (inRange(scrollValue, 401, 600)) opacity = 0.5; if (inRange(scrollValue, 601, 1078)) opacity = 0.25; if (inRange(scrollValue, 1079, 2000)) opacity = 0; } return opacity; } renderSimilarProducts() { const { similarProducts, productInfo } = this.props; if (similarProducts.isEmpty()) { return null; } const relatedProd = productInfo.get('similarProducts'); return relatedProd.map(sp => { const products = similarProducts.filter(p => sp.get('products').includes(p.get('code'))); return ( <SimilarProducts key={sp.get('name')} similarProducts={products} title={sp.get('name')} setAnalyticsProductClick={this.props.setAnalyticsProductClick} /> ); }); } renderAnimatedTitle(config) { const { name, code } = config; const isShadowBox = this.state.scrollValue >= 1100; return ( isShadowBox ? <FixedTitleWrapper> <Title>{name}</Title> <Ref>{`REF. ${code}`}</Ref> </FixedTitleWrapper> : <div /> ); } render() { const { productInfo, hasNearbyStores } = this.props; if (productInfo.isEmpty()) { return null; } const name = productInfo.get('name'); const code = productInfo.get('code'); const slug = productInfo.get('slug'); const productType = productInfo.getIn(['productDetail', 'descriptionType']); const marketingDescriptions = productInfo.getIn(['productDetail', 'marketingDescriptions']); const marketingAttributes = productInfo.get('marketingAttributes'); const loyaltyProgram = productInfo.get('loyaltyProgram'); const descriptions = productInfo.getIn(['productDetail', 'descriptions']); const price = productInfo.getIn(['price', 'selling']); const pricingInfo = productInfo.get('pricingInformations'); const currentStoreStock = fromJS({ storeStock: productInfo.get('storeStock'), stockStatus: productInfo.getIn(['productStockInfo', 'vendibilityValue']) }); const imageIDList = productInfo.get('images'); const imageOptions = { width: 1080, height: 1080, crop: 'fit' }; return ( <Wrapper> <ScrollableDiv onScrolling={this.onScrolling}> <Title>{name}</Title> <Ref>{`REF. ${code}`}</Ref> {this.renderAnimatedTitle({ name, code })} <SliderWrapper opacity={this.getOpacity()}> <ImageSlider imageIDList={imageIDList} imageOptions={imageOptions} alt={name} /> </SliderWrapper> <ProductInfo productType={productType} marketingDescriptions={marketingDescriptions} descriptions={descriptions} /> <SimilarProductsWrapper> {this.renderSimilarProducts()} </SimilarProductsWrapper> <PriceWrapper> <ProductInfoBadge productName={name} productCode={code} productSlug={slug} pricingInfo={pricingInfo} currentStoreStock={currentStoreStock} marketingAttributes={marketingAttributes} loyaltyProgram={loyaltyProgram} price={price} scrollValue={this.state.scrollValue} hasNearbyStores={hasNearbyStores} /> </PriceWrapper> </ScrollableDiv> </Wrapper> ); } } const Wrapper = glamorous.div({ position: 'relative' }); const Title = glamorous.h1({ padding: '40px 100px 0', textAlign: 'center', fontSize: 48, lineHeight: '70px', textTransform: 'capitalize' }); const Ref = glamorous.h3({ textTransform: 'uppercase', fontSize: 16, lineHeight: '24px', textAlign: 'center', marginBottom: 16 }); const SliderWrapper = glamorous.div(({ opacity }) => ({ width: '100%', opacity })); const PriceWrapper = glamorous.div({ position: 'fixed', right: '2%', top: '12%' }); const SimilarProductsWrapper = glamorous.div({ margin: '60px 0 0', '&>div': { marginBottom: 80 } }); const FixedTitleWrapper = glamorous.div({ width: '100%', backgroundColor: 'white', boxShadow: '0px 6px 5px #888888', zIndex: 1, position: 'fixed', top: '0px' });
src/entry-points/client.js
shaunstanislaus/react-redux-starter-kit
import React from 'react'; import App from 'containers/app'; import { history } from 'react-router/lib/BrowserHistory'; React.render(<App history={history} />, document.getElementById('mount'));
src/svg-icons/image/filter-7.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter7 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-8-2l4-8V5h-6v2h4l-4 8h2z"/> </SvgIcon> ); ImageFilter7 = pure(ImageFilter7); ImageFilter7.displayName = 'ImageFilter7'; export default ImageFilter7;
__tests__/TestComponentWhichShouldThrow4.js
liegeandlief/whitelodge
'use strict' import React from 'react' import {AddStoreSubscriptions} from '../src/' class TestComponent extends React.Component { render () { return null } } export default AddStoreSubscriptions(TestComponent, ['testStore'], window, ['notAString'])
app/javascript/mastodon/components/column_back_button_slim.js
esetomo/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; export default class ColumnBackButtonSlim extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; handleClick = () => { if (window.history && window.history.length === 1) this.context.router.history.push('/'); else this.context.router.history.goBack(); } render () { return ( <div className='column-back-button--slim'> <div role='button' tabIndex='0' onClick={this.handleClick} className='column-back-button column-back-button--slim-button'> <i className='fa fa-fw fa-chevron-left column-back-button__icon' /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </div> </div> ); } }
docs/src/app/components/pages/components/Avatar/Page.js
pradel/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import avatarReadmeText from './README'; import AvatarExampleSimple from './ExampleSimple'; import avatarExampleSimpleCode from '!raw!./ExampleSimple'; import avatarCode from '!raw!material-ui/lib/Avatar/Avatar'; const description = 'Examples of `Avatar` using an image, [Font Icon](/#/components/font-icon), ' + '[SVG Icon](/#/components/svg-icon) and "Letter" (string), with and without custom colors.'; const AvatarsPage = () => ( <div> <Title render={(previousTitle) => `Avatar - ${previousTitle}`} /> <MarkdownElement text={avatarReadmeText} /> <CodeExample code={avatarExampleSimpleCode} title="Examples" description={description} > <AvatarExampleSimple /> </CodeExample> <PropTypeDescription code={avatarCode} /> </div> ); export default AvatarsPage;
src/bundles/ApplicationsAdmin/components/AppDiff/AppDiff.js
AusDTO/dto-digitalmarketplace-frontend
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Control, LocalForm } from 'react-redux-form'; import { appSave } from '../../redux/modules/application'; import { diff_match_patch } from 'diff-match-patch'; import styles from './AppDiff.css'; import traverse from 'traverse'; class AppDiff extends Component { cleanup(supplier, application) { if (supplier) { delete supplier.links; delete supplier.prices; delete supplier.domains; delete supplier.steps; delete supplier.updated_at; delete supplier.last_update_time; delete supplier.lastUpdateTime; delete supplier.created_at; delete supplier.createdAt; delete supplier.creationTime; delete supplier.creation_time; delete supplier.text_vector; delete supplier.contacts; delete supplier.supplierCode; delete supplier.supplier_code; delete supplier.frameworks; delete supplier.status; delete supplier.id; delete supplier.application_id; delete supplier.signed_agreements; } if (application) { delete application.links; delete application.steps; delete application.updated_at; delete application.last_update_time; delete application.lastUpdateTime; delete application.created_at; delete application.createdAt; delete application.creationTime; delete application.creation_time; delete application.text_vector; delete application.supplierCode; delete application.supplier_code; delete application.frameworks; delete application.type; delete application.status; delete application.id; delete application.application_id; } } render() { const { application, meta } = this.props; this.cleanup(meta.supplier, application.data); var differences = []; traverse(meta.supplier).forEach(function (v) { if (this.isLeaf && this.path.indexOf('links') < 0) { differences.push({ property: this.path.join('.'), original: v ? v : '', updated: '', html: undefined }); } }); traverse(application.data).forEach(function (v) { if (this.isLeaf && this.path.indexOf('links') < 0) { const property = this.path.join('.'); const existing = differences.find(e => e.property == property); if (existing) { existing.updated = v ? v : ''; } else { differences.push({ property, original: '', updated: v ? v : '', html: undefined }); } } }); differences.forEach(v => { if (`${v.original}` !== `${v.updated}`) { let dmp = new diff_match_patch(); let diffs = dmp.diff_main(`${v.original}`, `${v.updated}`); dmp.diff_cleanupEfficiency(diffs); v.html = dmp.diff_prettyHtml(diffs);; } }) differences.sort((a, b) => { if (a.property < b.property) { return -1; } if (a.property > b.property) { return 1; } return 0; }) return ( <article id="content"> <table styleName="diff-table"> <tbody> <tr> <th>{'Property'}</th> <th>{'Original'}</th> <th>{'Updated'}</th> <th>{'Difference'}</th> </tr> {differences.map(d => { return d.html && <tr key={d.property}> <td>{d.property}</td> <td>{`${d.original}`}</td> <td>{`${d.updated}`}</td> <td><span dangerouslySetInnerHTML={{ __html: d.html }} /></td> </tr> })} </tbody> </table> </article> ) } } const mapStateToProps = (ownProps) => { return { ...ownProps, }; }; const mapDispatchToProps = (dispatch) => { return { onAppSubmit: (values) => { dispatch(appSave(values)) } } }; export default connect(mapStateToProps, mapDispatchToProps)(AppDiff);
app/javascript/mastodon/components/missing_indicator.js
codl/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; const MissingIndicator = () => ( <div className='regeneration-indicator missing-indicator'> <div> <div className='regeneration-indicator__figure' /> <div className='regeneration-indicator__label'> <FormattedMessage id='missing_indicator.label' tagName='strong' defaultMessage='Not found' /> <FormattedMessage id='missing_indicator.sublabel' defaultMessage='This resource could not be found' /> </div> </div> </div> ); export default MissingIndicator;
src/html/tags/HtmlTagLi.js
saketkumar95/zulip-mobile
import React from 'react'; import { StyleSheet, View } from 'react-native'; import styles from '../HtmlStyles'; import HtmlNodeText from '../HtmlNodeText'; import renderHtmlChildren from '../renderHtmlChildren'; const BULLET = '\u2022'; const customStyles = StyleSheet.create({ text: { flexWrap: 'wrap', flex: 1, width: '100%', flexDirection: 'row', } }); export default ({ style, ...restProps }) => ( <View style={[styles.li, style]}> <HtmlNodeText style={styles.bullet} data={` ${BULLET} `} /> <View style={customStyles.text}> {renderHtmlChildren({ ...restProps })} </View> </View> );
src/index.js
ebn646/react-moviesearch
import React from 'react' import { render } from 'react-dom' import { browserHistory, hashHistory,Router, Route, IndexRoute, Link, withRouter } from 'react-router' import App from './components/app/app.js' import Home from './components/home/home.js' import Movie from './components/movie/movie.js' import MovieList from './components/movielist/movielist.js' import SearchResults from './components/searchResults/searchResults.js' import './styles/app.scss' render(( <Router history={hashHistory}> <Route path={"/"} component={App}> <IndexRoute component={Home}/> <Route path="category/:category" component={MovieList}/> <Route path="movie/:id" component={Movie}/> <Route path="search/:query=fight+club" component={SearchResults}/> </Route> </Router> ), document.getElementById('main'))
src/server.js
samerce/lampshade
/** * 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 'babel-polyfill'; import path from 'path'; import express from 'express'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import expressJwt from 'express-jwt'; import expressGraphQL from 'express-graphql'; import jwt from 'jsonwebtoken'; import React from 'react'; import ReactDOM from 'react-dom/server'; import UniversalRouter from 'universal-router'; import PrettyError from 'pretty-error'; import App from './components/App'; import Html from './components/Html'; import { ErrorPageWithoutStyle } from './routes/error/ErrorPage'; import errorPageStyle from './routes/error/ErrorPage.css'; import passport from './core/passport'; import models from './data/models'; import schema from './data/schema'; import routes from './routes'; import assets from './assets'; // eslint-disable-line import/no-unresolved import configureStore from './store/configureStore'; import { setRuntimeVariable } from './actions/runtime'; import { port, auth } from './config'; const app = express(); // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(express.static(path.join(__dirname, 'public'))); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // // Authentication // ----------------------------------------------------------------------------- app.use(expressJwt({ secret: auth.jwt.secret, credentialsRequired: false, getToken: req => req.cookies.id_token, })); app.use(passport.initialize()); if (process.env.NODE_ENV !== 'production') { app.enable('trust proxy'); } app.get('/login/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false }), ); app.get('/login/facebook/return', passport.authenticate('facebook', { failureRedirect: '/login', session: false }), (req, res) => { const expiresIn = 60 * 60 * 24 * 180; // 180 days const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn }); res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true }); res.redirect('/'); }, ); // // Register API middleware // ----------------------------------------------------------------------------- app.use('/graphql', expressGraphQL(req => ({ schema, graphiql: process.env.NODE_ENV !== 'production', rootValue: { request: req }, pretty: process.env.NODE_ENV !== 'production', }))); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async (req, res, next) => { try { const store = configureStore({ user: req.user || null, }, { cookie: req.headers.cookie, }); store.dispatch(setRuntimeVariable({ name: 'initialNow', value: Date.now(), })); const css = new Set(); // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader insertCss: (...styles) => { // eslint-disable-next-line no-underscore-dangle styles.forEach(style => css.add(style._getCss())); }, // Initialize a new Redux store // http://redux.js.org/docs/basics/UsageWithReact.html store, }; const route = await UniversalRouter.resolve(routes, { ...context, path: req.path, query: req.query, }); if (route.redirect) { res.redirect(route.status || 302, route.redirect); return; } const data = { ...route }; data.children = ReactDOM.renderToString(<App context={context}>{route.component}</App>); data.style = [...css].join(''); data.scripts = [ assets.vendor.js, assets.client.js, ]; data.state = context.store.getState(); if (assets[route.chunk]) { data.scripts.push(assets[route.chunk].js); } const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(route.status || 200); res.send(`<!doctype html>${html}`); } catch (err) { next(err); } }); // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars console.log(pe.render(err)); // eslint-disable-line no-console const html = ReactDOM.renderToStaticMarkup( <Html title="Internal Server Error" description={err.message} style={errorPageStyle._getCss()} // eslint-disable-line no-underscore-dangle > {ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)} </Html>, ); res.status(err.status || 500); res.send(`<!doctype html>${html}`); }); // // Launch the server // ----------------------------------------------------------------------------- /* eslint-disable no-console */ models.sync().catch(err => console.error(err.stack)).then(() => { app.listen(port, () => { console.log(`The server is running at http://localhost:${port}/`); }); }); /* eslint-enable no-console */
app/app.js
maciejsikora/react-task-list
import React from 'react'; import ReactDOM from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import TaskBox from './tasklist/taskbox.jsx'; const App = React.createClass({ render:function(){ return ( <MuiThemeProvider> <TaskBox /> </MuiThemeProvider> ) } }); ReactDOM.render( <App />, document.getElementById('content') );
frontend/components/Question.js
ParroApp/parro
import React from 'react'; import Navbar from './Navbar'; import TypeWriter from 'react-typewriter'; import RecordRTC from 'recordrtc'; const StereoAudioRecorder = RecordRTC.StereoAudioRecorder; import {captureUserMedia, uploadAudio} from './AppUtils'; class Question extends React.Component { constructor(props) { super(props); this.state = { doneTyping: false, isBotAsking: true, typewriter: '', isRecording: false, time: null, showButtons: false } this.nextQuestion = this.nextQuestion.bind(this); this.index = 0; } componentDidMount() { window.addEventListener("load", function() { var synth = window.speechSynthesis; var voices = synth.getVoices(); console.log('VOICES'); }); setTimeout(() => { this.talk("Thank you for interviewing with us today. Do you have any questions for the company? I will do my best to answer."); }, 1000); // show buttons setTimeout(() => { console.log('showButtons'); this.setState({ showButtons: true }); }, 9000); captureUserMedia((stream) => { this.setState({ stream: stream, src: window.URL.createObjectURL(stream) }); }); // first question setTimeout(() => { this.talk("Our employees have said the best part is working with great, intelligent people."); }, 10000 + 9000); // first question setTimeout(() => { this.talk("We're looking for engineers who bring fresh ideas from all areas, distributed computing, large-scale system design, and mobile; the list goes on and is growing every day."); }, 20000 + 10000 + 9000); setTimeout(() => { this.talk("Thank you! We'll get back to you soon"); }, 15000 + 20000 + 10000 + 9000); setTimeout(() => { this.props.history.push('/end'); }, 5000 + 15000 + 20000 + 10000 + 9000); } talk(val) { setTimeout(function() { var synth = window.speechSynthesis; var voices = synth.getVoices(); for (var i = 0; i < voices.length; i++) { if (voices[i].name === 'Google US English') { voices = voices[i]; break; } } var msg = new SpeechSynthesisUtterance(); msg.text = val; msg.voice = voices; msg.pitch = 1; msg.rate = 0.9; synth.speak(msg); this.setState({ typewriter: val }); }.bind(this), 500); } nextQuestion() { this.setState({ time: null, isRecording: true }); // console.log('next question'); // console.log('start recording here', this.state); // // if (this.state.isRecording) { // console.log('stop audio recording old and upload...'); // this.stopRecord(() => { // this.startRecord(); // }); // } else { // this.startRecord(); // } // // this.setState({ doneTyping: false }); // this.index++; // if (this.index === 1) { // this.talk('Tell me about yourself'); // } else if (this.index === 2) { // this.talk('Tell me about a project'); // } else if (this.index === 3) { // this.talk('What is bubble sort?'); // } else { // // END OF BEHAVIORAL SECTION // this.state.recordVideo.stopRecording(() => { // console.log('Stop recording video'); // let params = { // type: 'video/webm', // data: this.state.recordVideo.blob, // id: Math.floor(Math.random() * 90000) + 10000 // } // clearInterval(this.state.intervalId); // this.setState({ uploading: true, intervalId: null, time: '' }); // }); // this.state.stream.getVideoTracks().forEach(function(track) { // track.stop(); // }); // this.props.history.push('/end'); // } } startRecord() { // this.setState({isRecording: true}) // setTimeout(() => { // console.log('YOYOYO'); // this.setState({ time: 2 }); // }, 3000) // // start recording audio // console.log('start audio recording'); // var recordAudio = RecordRTC(this.state.stream, { // recorderType: StereoAudioRecorder, // type: 'audio' // }); // recordAudio.startRecording(); // // // stores state // this.setState({ // recordAudio: recordAudio, // }); } stopRecord(temp) { // this.state.recordAudio.stopRecording(() => { // console.log('Stop recording audio'); // // uploadAudio(this.state.recordAudio.blob, this.state.userId); // // console.log(this.state.recordAudio.blob); // // console.log(this.state.recordAudio); // // temp(); // }); // this.setState({isRecording: false}); } // componentWillMount() { // setTimeout(() => { // this.setState({doneTyping: true}) // }, 7000) // } render() { console.log('THIS.STATE', this.state); return( <div> <Navbar {...this.props}/> <video autoPlay muted src={this.state.src} style={{display: 'none'}}/> <div style={{height: '60px', width: '100%'}}></div> <div className="robot"><svg className="robotSVG" version="1.1" xmlns="http://www.w3.org/2000/svg"> <g id="hover"> <ellipse id="shadow_2_" opacity="0.4" fill="#2C3332" cx="300" cy="703.375" rx="88.971" ry="30.625"></ellipse> </g> <g id="arms"> <g id="left"> <path id="arm_1_" fill="#BABEB7" d="M183.975,430.936c-50.27-21.595-96.437,29.654-96.132,54.383 c0.06,4.868,7.836,11.424,11.509,7.079c12.145-14.369,36.979-35.733,55.676-16.486 C156.498,477.423,189.086,433.132,183.975,430.936z"></path> <g id="hand_1_"> <path id="shadow" fill="#BABEB7" d="M63.712,520.545l5.657-7.071c0,0-11.453-8.997-9.402-12.554 c4.469-7.751,15.935-9.515,25.612-3.936c9.676,5.579,13.898,16.385,9.43,24.136c-1.736,3.013-7.363,0.091-7.363,0.091 l-5.657,7.071l0.058,6.027c8.473,0.83,16.454-1.564,21.692-6.847c1.235-1.245,6.329-7.287,7.229-8.85 c1.826-3.166-7.579-26.607-18.73-33.036c-8.361-4.82-31.172-5.074-31.172-5.074s-5.691,5.814-8.805,11.216 c-5.77,10.006-2.253,23.271,7.678,32.486L63.712,520.545z"></path> <path id="top" fill="#DCE0DA" d="M69.37,513.474c-5.443-5.817-7.202-13.631-3.746-19.625c4.469-7.751,15.935-9.514,25.612-3.935 c9.676,5.578,13.899,16.385,9.43,24.135c-2.575,4.468-7.478,6.932-13.02,7.162l0.058,6.027 c10.471,1.026,20.192-2.873,24.911-11.06c6.976-12.099,0.385-28.965-14.719-37.673c-15.104-8.708-33.002-5.957-39.977,6.142 c-5.769,10.007-2.253,23.271,7.679,32.486L69.37,513.474z"></path> </g> </g> <g id="right"> <path id="arm" fill="#DCE0DA" d="M416.025,430.936c50.27-21.595,96.437,29.654,96.131,54.383 c-0.059,4.868-7.836,11.424-11.509,7.079c-12.145-14.369-36.979-35.733-55.676-16.486 C443.502,477.423,410.914,433.132,416.025,430.936z"></path> <g id="hand"> <path id="shadow_1_" fill="#BABEB7" d="M536.287,520.545l-5.656-7.071c0,0,11.453-8.997,9.402-12.554 c-4.469-7.751-15.936-9.515-25.612-3.936s-13.898,16.385-9.43,24.136c1.736,3.013,7.362,0.091,7.362,0.091l5.657,7.071 l-0.058,6.027c-8.474,0.83-16.455-1.564-21.692-6.847c-1.235-1.245-6.329-7.287-7.229-8.85 c-1.826-3.166,7.578-26.607,18.73-33.036c8.361-4.82,31.172-5.074,31.172-5.074s5.691,5.814,8.805,11.216 c5.77,10.006,2.253,23.271-7.678,32.486L536.287,520.545z"></path> <path id="top_1_" fill="#DCE0DA" d="M530.631,513.474c5.443-5.817,7.201-13.631,3.745-19.625 c-4.469-7.751-15.935-9.514-25.612-3.935c-9.676,5.578-13.898,16.385-9.43,24.135c2.575,4.468,7.479,6.932,13.02,7.162 l-0.058,6.027c-10.472,1.026-20.192-2.873-24.911-11.06c-6.975-12.099-0.385-28.965,14.72-37.673s33.003-5.957,39.978,6.142 c5.769,10.007,2.252,23.271-7.68,32.486L530.631,513.474z"></path> </g> </g> </g> <g id="body"> <g id="chassie"> <g id="base"> <path fill="#DCE0DA" d="M137.424,525.622c0-47.887,60.669-219.342,162.576-219.342c101.907,0,162.576,171.854,162.576,219.342 c0,47.489-137.88,56.438-162.576,56.438C275.303,582.06,137.424,573.511,137.424,525.622z"></path> </g> <g id="highlight"> <defs> <path id="SVGID_1_" d="M137.424,525.622c0-47.887,60.669-219.342,162.576-219.342c101.907,0,162.576,171.854,162.576,219.342 c0,47.489-137.88,56.438-162.576,56.438C275.303,582.06,137.424,573.511,137.424,525.622z"></path> </defs> <clipPath id="SVGID_2_"> <use xlinkHref="#SVGID_1_" overflow="visible"></use> </clipPath> <path clipPath="url(#SVGID_2_)" fill="#BABEB7" d="M455.667,419c0,0-38.299,61.503-156.983,61.503 c-67.685,0-86.351,14.831-96.684,39.164S203.368,588,298.684,588s1.816,21.923,1.816,21.923s-198.833-42.589-198.833-43.589 s54.333-215,54.333-215L455.667,419z"></path> </g> </g> <g id="progress-indicator"> <g id="divet"> <path id="highlight-bottom" fill="#EAECE8" d="M425.182,524.775l-4.682-21.211c0,0-48.18,19.563-120.34,19.563 s-120.82-19.079-120.82-19.079l-4.542,20.636c0,0,37.523,20.052,125.363,20.052S425.182,524.775,425.182,524.775z"></path> <path id="divet-bottom" fill="#4C4C4C" d="M420.682,521.823l-4.514-16.654c0,0-46.447,17.959-116.014,17.959 c-69.566,0-116.477-17.551-116.477-17.551l-4.379,16.159c0,0,36.174,18.597,120.856,18.597 C384.837,540.333,420.682,521.823,420.682,521.823z"></path> <polygon id="shadow-right_1_" fill="#BABEB7" points="416.168,505.169 420.5,503.564 425.182,524.775 420.682,521.823 "></polygon> <polygon id="shadow-left" fill="#8F918D" points="183.677,505.577 179.34,504.049 174.797,524.685 179.297,521.736 "></polygon> <path id="shadow-bottom" fill="#BABEB7" d="M204.738,530.305l-5.786,2.959c0,0-8.125-2.072-14.702-4.556 s-9.453-4.023-9.453-4.023l4.5-2.948c0,0,4.039,2.192,11.313,4.463S204.738,530.305,204.738,530.305z"></path> </g> <g id="completed"> <path id="blue" fill="#84D3E8" d="M300.154,523.128c-69.566,0-116.477-17.551-116.477-17.551l-4.379,16.159 c0,0,36.174,18.597,120.856,18.597c28.812,0,51.965-2.144,69.983-4.971l-1.808-18.073 C349.822,520.518,326.67,523.128,300.154,523.128z"></path> <path id="blue-shadow" fill="#6DADBC" d="M208.568,512.712c-15.682-3.741-24.93-7.135-24.93-7.135l-4.437,16.159 c0,0,8.037,4.175,25.537,8.568C205.625,524.125,206,520.875,208.568,512.712z"></path> </g> </g> </g> <g id="head"> <g id="face"> <path id="screen-shadow" fill="#9AB2B0" d="M418.268,235.276C377.932,233.144,327.52,232,300.003,232 c-27.517,0-77.766,1.144-118.102,3.276c-34.071,1.801-41.222,17.035-41.222,69.742s3.15,88.311,24.65,107.819 c35.831,32.511,101.258,47.829,134.673,47.829c33.832,0,99.06-15.318,134.891-47.829c21.5-19.508,24.758-55.112,24.758-107.819 S452.338,237.078,418.268,235.276z"></path> <path id="screen" fill="#A4BCB9" d="M164.381,353.965c0,55.225,107.043,76.693,135.619,76.693 c28.576,0,135.618-21.469,135.618-76.693c0-100.027-60.717-123.293-135.618-123.293 C225.101,230.671,164.381,253.938,164.381,353.965z"></path> <path id="case_x5F_shadow" fill="#EAECE8" d="M300,239c27.54,0,78.739,1.16,119.383,3.309c15.837,0.837,18.06,4.715,19.388,7.032 c5.026,8.771,5.671,29.167,5.671,45.955c0,49.954-0.156,81.738-16.287,96.374c-31.639,28.708-96.014,44.997-128.154,44.997 c-32.048,0-95.295-16.289-126.934-44.997c-16.039-14.552-17.176-46.356-17.176-96.374c0-16.825,0.638-37.258,5.614-46 c1.395-2.45,3.503-6.153,19.279-6.987C221.426,240.16,272.541,239,300,239 M300,210.5c-80.5,0-160.11,7.167-160.11,60.795 S141.095,385.151,162.971,405C199.429,438.08,266,453.666,300,453.666c34.424,0,100.792-15.586,137.25-48.666 c21.876-19.849,23.191-80.076,23.191-133.705S380.5,210.5,300,210.5z"></path> <path id="case" fill="#DCE0DA" d="M300,248c27.54,0,78.739,1.16,119.383,3.309c15.837,0.837,18.06,4.715,19.388,7.032 c5.026,8.771,5.671,29.167,5.671,45.955c0,49.954-3.156,81.738-19.287,96.374c-31.639,28.708-93.014,43.997-125.154,43.997 c-32.048,0-93.295-15.289-124.934-43.997c-16.039-14.552-19.176-46.356-19.176-96.374c0-16.825,0.638-37.258,5.614-46 c1.395-2.45,3.503-6.153,19.279-6.987C221.426,249.16,272.541,248,300,248 M300,230c-27.999,0-79.126,1.164-120.167,3.333 c-34.667,1.833-41.943,17.333-41.943,70.962s3.205,89.856,25.081,109.705C199.429,447.08,266,462.666,300,462.666 c34.424,0,100.792-15.586,137.25-48.666c21.876-19.849,25.191-56.076,25.191-109.705s-7.441-69.129-42.108-70.962 C379.292,231.164,327.998,230,300,230L300,230z"></path> </g> <g id="eyes"> <ellipse id="left_1_" fill="#2C3332" cx="231" cy="316.667" rx="6.333" ry="17"></ellipse> <ellipse id="right_1_" fill="#2C3332" cx="369" cy="316.667" rx="6.334" ry="17"></ellipse> </g> <g id="indicators"> <path id="mount" fill="#DCE0DA" d="M354.333,220.333c0-29.916-24.252-54.167-54.167-54.167c-29.916,0-54.167,24.251-54.167,54.167 c0,4.667,24.251,4.667,54.167,4.667C330.081,225,354.333,225,354.333,220.333z"></path> <g id="leds"> <circle id="yellow" fill="#F0C419" cx="300.418" cy="207" r="8.084"></circle> <circle id="red" fill="#E64C3C" cx="324.67" cy="206" r="8.084"></circle> <circle id="green" fill="#4EBA64" cx="275.33" cy="206" r="8.083"></circle> </g> </g> </g> </svg> </div> <div className="container" style={{textAlign: 'center', display: 'flex', justifyContent: 'center', alignItems: 'center'}}> <div className="columns"> <div className="column is-vertical"> <TypeWriter fixed={true} style={{fontSize: '30px', textAlign: 'center'}} typing={0.8}> {this.state.typewriter} </TypeWriter> </div> </div> </div> {this.state.showButtons && this.state.isRecording && (<button onClick={this.stopRecord.bind(this)} style={{position: 'absolute', top: '80%', left: '43%'}} className="button is-info is-large"> <span className="icon"> <i className="fa fa-question"></i> </span> <span>Finished asking</span> </button>) } {this.state.showButtons && !this.state.isRecording && (<button onClick={this.nextQuestion} style={{position: 'absolute', top: '80%', left: '43%'}} className="button is-info is-large"> <span className="icon"> <i className="fa fa-question"></i> </span> <span>Ask a question</span> </button>) } </div> ) } } export default Question;
src/DataTables/DataTablesTable.js
hyojin/material-ui-datatables
import React from 'react'; import {Table} from 'material-ui/Table'; class DataTablesTable extends Table { createTableBody(base) { return React.cloneElement( base, { allRowsSelected: this.state.allRowsSelected, multiSelectable: this.props.multiSelectable, onCellClick: this.onCellClick, onCellDoubleClick: this.onCellDoubleClick, onCellHover: this.onCellHover, onCellHoverExit: this.onCellHoverExit, onRowHover: this.onRowHover, onRowHoverExit: this.onRowHoverExit, onRowSelection: this.onRowSelection, selectable: this.props.selectable, style: Object.assign({height: this.props.height}, base.props.style), } ); } onCellDoubleClick = (rowNumber, columnNumber, event) => { if (this.props.onCellDoubleClick) this.props.onCellDoubleClick(rowNumber, columnNumber, event); }; } export default DataTablesTable;
node_modules/react-router/es/Redirect.js
juhov/travis-test
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; /** * The public API for updating the location programatically * with a component. */ var Redirect = function (_React$Component) { _inherits(Redirect, _React$Component); function Redirect() { _classCallCheck(this, Redirect); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Redirect.prototype.isStatic = function isStatic() { return this.context.router && this.context.router.staticContext; }; Redirect.prototype.componentWillMount = function componentWillMount() { if (this.isStatic()) this.perform(); }; Redirect.prototype.componentDidMount = function componentDidMount() { if (!this.isStatic()) this.perform(); }; Redirect.prototype.perform = function perform() { var history = this.context.router.history; var _props = this.props, push = _props.push, to = _props.to; if (push) { history.push(to); } else { history.replace(to); } }; Redirect.prototype.render = function render() { return null; }; return Redirect; }(React.Component); Redirect.propTypes = { push: PropTypes.bool, from: PropTypes.string, to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]) }; Redirect.defaultProps = { push: false }; Redirect.contextTypes = { router: PropTypes.shape({ history: PropTypes.shape({ push: PropTypes.func.isRequired, replace: PropTypes.func.isRequired }).isRequired, staticContext: PropTypes.object }).isRequired }; export default Redirect;
app/private/indexerApp/imports/ui/pages/Documents.js
ericvrp/GameCollie
import React from 'react'; import { Link } from 'react-router'; import { Row, Col, Button } from 'react-bootstrap'; import DocumentsList from '../components/DocumentsList'; const Documents = () => ( <div className="Documents"> <Row> <Col xs={ 12 }> <div className="page-header clearfix"> <h4 className="pull-left">Documents</h4> <Link to="/documents/new"> <Button bsStyle="success" className="pull-right" >New Document</Button> </Link> </div> <DocumentsList /> </Col> </Row> </div> ); export default Documents;
src/svg-icons/social/poll.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPoll = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/> </SvgIcon> ); SocialPoll = pure(SocialPoll); SocialPoll.displayName = 'SocialPoll'; SocialPoll.muiName = 'SvgIcon'; export default SocialPoll;
client/src/javascript/components/icons/DownloadThickIcon.js
jfurrow/flood
import React from 'react'; import BaseIcon from './BaseIcon'; export default class DownloadThickIcon extends BaseIcon { render() { return ( <svg className={`icon icon--download ${this.props.className}`} viewBox={this.getViewBox()}> <polygon points="44.1,23 33,39.7 33,4.6 27,4.6 27,39.7 15.9,23 10.9,26.4 30,55 49.1,26.4 " /> </svg> ); } }
src/index.js
arimaulana/rest-api-frontend-in-react
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import jwtDecode from 'jwt-decode'; import setAuthorizationToken from './utils/setAuthorizationToken'; import { setCurrentUser } from './actions/authActions'; import App from './components/App'; import store from './store'; if (localStorage.jwtToken) { setAuthorizationToken(localStorage.jwtToken); store.dispatch(setCurrentUser(jwtDecode(localStorage.jwtToken))); } ReactDOM.render( <Provider store={store}> <MuiThemeProvider> <App /> </MuiThemeProvider> </Provider>, document.getElementById('root') );
stories/props/drilldownView.stories.js
jquense/react-big-calendar
import React from 'react' import moment from 'moment' import { Calendar, Views, momentLocalizer } from '../../src' import demoEvents from '../resources/events' import mdx from './drilldownView.mdx' const mLocalizer = momentLocalizer(moment) export default { title: 'props', component: Calendar, argTypes: { localizer: { control: { type: null } }, events: { control: { type: null } }, defaultDate: { control: { type: null, }, }, drilldownView: { control: { type: 'select', options: ['day', 'agenda'], defaultValue: Views.DAY, }, }, }, parameters: { docs: { page: mdx, }, }, } const Template = (args) => ( <div className="height600"> <Calendar {...args} /> </div> ) export const DrilldownView = Template.bind({}) DrilldownView.storyName = 'drilldownView' DrilldownView.args = { defaultDate: new Date(2015, 3, 1), drilldownView: Views.AGENDA, events: demoEvents, localizer: mLocalizer, }
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/actual.js
leechuanjun/TLReactNativeProject
import React, { Component } from 'react'; class Foo extends Component { render() {} }
src/components/Sidebar/Copyright/Copyright.js
Chogyuwon/chogyuwon.github.io
import React from 'react'; import styles from './Copyright.module.scss'; const Copyright = ({ copyright }) => ( <div className={styles['copyright']}> {copyright} </div> ); export default Copyright;
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/actual.js
horizon-z40/RN-homework
import React, { Component } from 'react'; class Foo extends Component { render() {} }
docs/src/app/components/pages/get-started/ServerRendering.js
skarnecki/material-ui
import React from 'react'; import Title from 'react-title-component'; import MarkdownElement from '../../MarkdownElement'; import serverRenderingText from './serverRendering.md'; const ServerRendering = () => ( <div> <Title render={(previousTitle) => `Server Rendering - ${previousTitle}`} /> <MarkdownElement text={serverRenderingText} /> </div> ); export default ServerRendering;
src/svg-icons/navigation/subdirectory-arrow-right.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationSubdirectoryArrowRight = (props) => ( <SvgIcon {...props}> <path d="M19 15l-6 6-1.42-1.42L15.17 16H4V4h2v10h9.17l-3.59-3.58L13 9l6 6z"/> </SvgIcon> ); NavigationSubdirectoryArrowRight = pure(NavigationSubdirectoryArrowRight); NavigationSubdirectoryArrowRight.displayName = 'NavigationSubdirectoryArrowRight'; NavigationSubdirectoryArrowRight.muiName = 'SvgIcon'; export default NavigationSubdirectoryArrowRight;
clients/libs/slate-editor-alignment-plugin/src/AlignmentCenterButton.js
nossas/bonde-client
/* eslint-disable react/prop-types */ import React from 'react' import classnames from 'classnames' import FontAwesome from 'react-fontawesome' import { Button } from '@slate-editor/components' import { alignmentMarkStrategy, hasMark, getMark } from './AlignmentUtils' const AlignmentCenterButton = ({ value, onChange, className, style, type }) => ( <Button style={style} type={type} onClick={() => onChange(alignmentMarkStrategy(value.change(), 'center'))} className={classnames( 'slate-alignment-plugin--button', { active: hasMark(value) && getMark(value).data.get('align') === 'center' }, className, )} > <FontAwesome name="align-center" /> </Button> ) export default AlignmentCenterButton
src/routes/contact/Contact.js
MxMcG/tourlookup-react
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Contact.css'; class Contact extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>{this.props.title}</h1> <p>...</p> </div> </div> ); } } export default withStyles(s)(Contact);
examples/huge-apps/routes/Course/routes/Grades/components/Grades.js
KamilSzot/react-router
import React from 'react'; class Grades extends React.Component { //static loadProps (params, cb) { //cb(null, { //assignments: COURSES[params.courseId].assignments //}); //} render () { //var { assignments } = this.props; var assignments = COURSES[this.props.params.courseId].assignments; return ( <div> <h3>Grades</h3> <ul> {assignments.map(assignment => ( <li key={assignment.id}>{assignment.grade} - {assignment.title}</li> ))} </ul> </div> ); } } export default Grades;
mlflow/server/js/src/experiment-tracking/components/artifact-view-components/ShowArtifactPdfView.js
mlflow/mlflow
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { getSrc } from './ShowArtifactPage'; import { Document, Page, pdfjs } from 'react-pdf'; import { Pagination, Spin } from 'antd'; import { getArtifactBytesContent } from '../../../common/utils/ArtifactUtils'; import './ShowArtifactPdfView.css'; // See: https://github.com/wojtekmaj/react-pdf/blob/master/README.md#enable-pdfjs-worker for how // workerSrc is supposed to be specified. pdfjs.GlobalWorkerOptions.workerSrc = `./static-files/pdf.worker.js`; class ShowArtifactPdfView extends Component { state = { loading: true, error: undefined, pdfData: undefined, currentPage: 1, numPages: 1, }; static propTypes = { runUuid: PropTypes.string.isRequired, path: PropTypes.string.isRequired, getArtifact: PropTypes.func, }; static defaultProps = { getArtifact: getArtifactBytesContent, }; /** Fetches artifacts and updates component state with the result */ fetchPdf() { const artifactLocation = getSrc(this.props.path, this.props.runUuid); this.props .getArtifact(artifactLocation) .then((artifactPdfData) => { this.setState({ pdfData: { data: artifactPdfData }, loading: false }); }) .catch((error) => { this.setState({ error: error, loading: false }); }); } componentDidMount() { this.fetchPdf(); } componentDidUpdate(prevProps) { if (this.props.path !== prevProps.path || this.props.runUuid !== prevProps.runUuid) { this.fetchPdf(); } } onDocumentLoadSuccess = ({ numPages }) => { this.setState({ numPages }); }; onPageChange = (newPageNumber, itemsPerPage) => { this.setState({ currentPage: newPageNumber }); }; renderPdf = () => { return ( <React.Fragment> <div className='pdf-viewer'> <div className='paginator'> <Pagination simple current={this.state.currentPage} total={this.state.numPages} pageSize={1} onChange={this.onPageChange} /> </div> <div className='document'> <Document file={this.state.pdfData} onLoadSuccess={this.onDocumentLoadSuccess} loading={<Spin />} > <Page pageNumber={this.state.currentPage} loading={<Spin />} /> </Document> </div> </div> </React.Fragment> ); }; render() { if (this.state.loading) { return <div className='artifact-pdf-view-loading'>Loading...</div>; } if (this.state.error) { return ( <div className='artifact-pdf-view-error'> Oops we couldn't load your file because of an error. Please reload the page to try again. </div> ); } else { return <div className='pdf-outer-container'>{this.renderPdf()}</div>; } } } export default ShowArtifactPdfView;
packages/icons/src/dv/GithubAlt.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function DvGithubAlt(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M7.25 16.633c-.563-2.05.198-6.693 1.375-9.524 2.664.284 5.942 1.787 9.868 4.5 3.516-.726 7.162-.68 10.914 0 3.572-2.35 6.914-4.014 9.861-4.5 1.129 2.832 2.036 7.966 1.392 9.524h.005c6.843 7.45 2.714 22.533-8.36 23.766-3.614.64-13.789.671-16.698 0C3.03 38.388 1.396 22.44 7.25 16.633zM23.954 38.88c4.792 0 8.5-.572 10.952-1.722 2.447-1.154 3.691-3.528 3.691-7.105-.035-1.356-.221-2.677-1.22-3.975-3.172-4.123-7.101-2.353-13.331-2.35-8.596-.405-13.707-1.592-14.635 6.32 0 3.579 1.212 5.95 3.634 7.1 2.42 1.158 6.116 1.732 10.91 1.732zm-8.297-4.852c-1.878-1.493-1.878-5.246 0-6.74 1.877-1.492 4.237.384 4.237 3.37s-2.36 4.863-4.237 3.37zm18.006-3.37c0-2.986-2.36-4.862-4.237-3.37-1.878 1.494-1.878 5.247 0 6.74 1.877 1.493 4.237-.384 4.237-3.37z" /> </IconBase> ); } export default DvGithubAlt;
src/components/ShareExperience/TimeSalaryForm/BasicInfo.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import subscribeValidation from 'common/subscribeValidation'; import Select from 'common/form/Select'; import TextInput from 'common/form/TextInput'; import CompanyQuery from '../common/CompanyQuery'; import IsEmployed from '../WorkExperiencesForm/WorkInfo/IsEmployed'; import JobTitle from '../common/JobTitle'; import EmploymentType from '../common/EmploymentType'; import InputTitle from '../common/InputTitle'; import styles from './TimeSalaryForm.module.css'; import { company as companyValidator, jobTitle as jobTitleValidator, employmentType as employmentTypeValidator, } from './formCheck'; import { COMPANY, JOB_TITLE, EMPLOYMENT_TYPE, } from '../../../constants/formElements'; const CompanyWithValidation = subscribeValidation( CompanyQuery, props => props.validator(props.companyQuery), COMPANY, ); const JobTitleWithValidation = subscribeValidation( JobTitle, props => props.validator(props.jobTitle), JOB_TITLE, ); const EmploymentTypeWithValidation = subscribeValidation( EmploymentType, props => props.validator(props.employmentType), EMPLOYMENT_TYPE, ); class BasicInfo extends React.PureComponent { render() { const { handleState, company, isCurrentlyEmployed, jobEndingTimeYear, jobEndingTimeMonth, jobTitle, sector, employmentType, gender, submitted, changeValidationStatus, } = this.props; return ( <div> <div className={styles.formSection}> <div className={styles.formGroupTwo}> <CompanyWithValidation companyQuery={company} onChange={v => { handleState('company')(v); handleState('title')(`${v} 薪資工時分享`); }} onCompanyId={handleState('companyId')} validator={companyValidator} submitted={submitted} changeValidationStatus={changeValidationStatus} /> </div> </div> <div className={styles.formSection}> <div className={styles.formGroupTwo}> <IsEmployed idPrefix4Radio="timeSalary" isCurrentlyEmployed={isCurrentlyEmployed} jobEndingTimeYear={jobEndingTimeYear} jobEndingTimeMonth={jobEndingTimeMonth} onIsCurrentlyEmployed={handleState('isCurrentlyEmployed')} onJobEndingTimeYear={handleState('jobEndingTimeYear')} onJobEndingTimeMonth={handleState('jobEndingTimeMonth')} /> </div> </div> <div className={styles.formSection}> <div className={styles.formGroupTwo}> <div className={styles.formGroup}> <JobTitleWithValidation inputTitle="職稱" jobTitle={jobTitle} onChange={handleState('jobTitle')} validator={jobTitleValidator} submitted={submitted} changeValidationStatus={changeValidationStatus} /> </div> <div className={styles.formGroup}> <InputTitle text="廠區/門市/分公司" /> <TextInput value={sector} placeholder="楠梓廠區 研發部" onChange={e => handleState('sector')(e.target.value)} /> </div> </div> </div> <div className={styles.formSection}> <div className={styles.formGroupTwo}> <div className={styles.formGroup}> <EmploymentTypeWithValidation employmentType={employmentType} inputTitle={'職務型態'} onChange={handleState('employmentType')} validator={employmentTypeValidator} submitted={submitted} changeValidationStatus={changeValidationStatus} /> </div> <div className={styles.formGroup}> <InputTitle text="性別" /> <Select value={gender} options={[ { label: '男', value: 'male', }, { label: '女', value: 'female', }, { label: '其他', value: 'other', }, ]} onChange={e => handleState('gender')(e.target.value)} /> </div> </div> </div> </div> ); } } BasicInfo.propTypes = { handleState: PropTypes.func, company: PropTypes.string, isCurrentlyEmployed: PropTypes.string, jobEndingTimeYear: PropTypes.number, jobEndingTimeMonth: PropTypes.number, jobTitle: PropTypes.string, sector: PropTypes.string, employmentType: PropTypes.string, gender: PropTypes.string, submitted: PropTypes.bool, changeValidationStatus: PropTypes.func, }; export default BasicInfo;
fields/types/relationship/RelationshipField.js
andreufirefly/keystone
import async from 'async'; import Lists from '../../../admin/client/stores/Lists'; import Field from '../Field'; import React from 'react'; import Select from 'react-select'; import xhr from 'xhr'; import { Button, InputGroup } from 'elemental'; function compareValues (current, next) { const currentLength = current ? current.length : 0; const nextLength = next ? next.length : 0; if (currentLength !== nextLength) return false; for (let i = 0; i < currentLength; i++) { if (current[i] !== next[i]) return false; } return true; } module.exports = Field.create({ displayName: 'RelationshipField', getInitialState () { return { value: null, createIsOpen: false, }; }, componentDidMount () { this._itemsCache = {}; this.loadValue(this.props.value); }, componentWillReceiveProps (nextProps) { if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return; this.loadValue(nextProps.value); }, shouldCollapse () { if (this.props.many) { // many:true relationships have an Array for a value return this.props.collapse && !this.props.value.length; } return this.props.collapse && !this.props.value; }, buildFilters () { var filters = {}; _.forEach(this.props.filters, (value, key) => { if (_.isString(value) && value[0] == ':') { // eslint-disable-line eqeqeq var fieldName = value.slice(1); var val = this.props.values[fieldName]; if (val) { filters[key] = val; return; } // check if filtering by id and item was already saved if (fieldName === ':_id' && Keystone.item) { filters[key] = Keystone.item.id; return; } } else { filters[key] = value; } }, this); var parts = []; _.forEach(filters, function (val, key) { parts.push('filters[' + key + '][value]=' + encodeURIComponent(val)); }); return parts.join('&'); }, cacheItem (item) { item.href = Keystone.adminPath + '/' + this.props.refList.path + '/' + item.id; this._itemsCache[item.id] = item; }, loadValue (values) { if (!values) { return this.setState({ loading: false, value: null, }); }; values = Array.isArray(values) ? values : values.split(','); const cachedValues = values.map(i => this._itemsCache[i]).filter(i => i); if (cachedValues.length === values.length) { this.setState({ loading: false, value: this.props.many ? cachedValues : cachedValues[0], }); return; } this.setState({ loading: true, value: null, }); async.map(values, (value, done) => { xhr({ url: Keystone.adminPath + '/api/' + this.props.refList.path + '/' + value + '?basic', responseType: 'json', }, (err, resp, data) => { if (err || !data) return done(err); this.cacheItem(data); done(err, data); }); }, (err, expanded) => { if (!this.isMounted()) return; this.setState({ loading: false, value: this.props.many ? expanded : expanded[0], }); }); }, // NOTE: this seems like the wrong way to add options to the Select loadOptionsCallback: {}, loadOptions (input, callback) { // NOTE: this seems like the wrong way to add options to the Select this.loadOptionsCallback = callback; const filters = this.buildFilters(); xhr({ url: Keystone.adminPath + '/api/' + this.props.refList.path + '?basic&search=' + input + '&' + filters, responseType: 'json', }, (err, resp, data) => { if (err) { console.error('Error loading items:', err); return callback(null, []); } data.results.forEach(this.cacheItem); callback(null, { options: data.results, complete: data.results.length === data.count, }); }); }, valueChanged (value) { this.props.onChange({ path: this.props.path, value: value, }); }, toggleCreate (visible) { this.setState({ createIsOpen: visible, }); }, onCreate (item) { this.cacheItem(item); if (Array.isArray(this.state.value)) { // For many relationships, append the new item to the end const values = this.state.value.map((item) => item.id); values.push(item.id); this.valueChanged(values.join(',')); } else { this.valueChanged(item.id); } // NOTE: this seems like the wrong way to add options to the Select this.loadOptionsCallback(null, { complete: true, options: Object.keys(this._itemsCache).map((k) => this._itemsCache[k]), }); this.toggleCreate(false); }, renderSelect (noedit) { return ( <Select.Async multi={this.props.many} disabled={noedit} loadOptions={this.loadOptions} labelKey="name" name={this.props.path} onChange={this.valueChanged} simpleValue value={this.state.value} valueKey="id" /> ); }, renderInputGroup () { // TODO: find better solution // when importing the CreateForm using: import CreateForm from '../../../admin/client/components/CreateForm'; // CreateForm was imported as a blank object. This stack overflow post suggested lazilly requiring it: // http://stackoverflow.com/questions/29807664/cyclic-dependency-returns-empty-object-in-react-native const CreateForm = require('../../../admin/client/components/Forms/CreateForm'); return ( <InputGroup> <InputGroup.Section grow> {this.renderSelect()} </InputGroup.Section> <InputGroup.Section> <Button onClick={() => this.toggleCreate(true)} type="success">+</Button> </InputGroup.Section> <CreateForm list={Lists[this.props.refList.key]} isOpen={this.state.createIsOpen} onCreate={(data) => this.onCreate(data)} onCancel={() => this.toggleCreate(false)} /> </InputGroup> ); }, renderValue () { return this.renderSelect(true); }, renderField () { if (this.props.createInline) { return this.renderInputGroup(); } else { return this.renderSelect(); } }, });
react/features/overlay/components/web/ReloadButton.js
jitsi/jitsi-meet
// @flow import React, { Component } from 'react'; import { reloadNow } from '../../../app/actions'; import { translate } from '../../../base/i18n'; import { connect } from '../../../base/redux'; /** * The type of the React {@code Component} props of {@link ReloadButton}. */ type Props = { /** * Reloads the page. */ _reloadNow: Function, /** * The function to translate human-readable text. */ t: Function, /** * The translation key for the text in the button. */ textKey: string }; /** * Implements a React Component for button for the overlays that will reload * the page. */ class ReloadButton extends Component<Props> { /** * Renders the button for relaod the page if necessary. * * @private * @returns {ReactElement} */ render() { const className = 'button-control button-control_overlay button-control_center'; /* eslint-disable react/jsx-handler-names */ return ( <button className = { className } onClick = { this.props._reloadNow }> { this.props.t(this.props.textKey) } </button> ); /* eslint-enable react/jsx-handler-names */ } } /** * Maps part of redux actions to component's props. * * @param {Function} dispatch - Redux's {@code dispatch} function. * @private * @returns {Object} */ function _mapDispatchToProps(dispatch: Function): Object { return { /** * Dispatches the redux action to reload the page. * * @protected * @returns {Object} Dispatched action. */ _reloadNow() { dispatch(reloadNow()); } }; } export default translate(connect(undefined, _mapDispatchToProps)(ReloadButton));
app/react-icons/fa/text-height.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaTextHeight extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m38.9 31.4q0.8 0 1 0.4t-0.3 1l-2.8 3.7q-0.4 0.5-1.1 0.5t-1.1-0.5l-2.8-3.7q-0.4-0.5-0.2-1t0.9-0.4h1.8v-22.8h-1.8q-0.7 0-0.9-0.4t0.2-1l2.8-3.7q0.5-0.5 1.1-0.5t1.1 0.5l2.8 3.7q0.5 0.5 0.3 1t-1 0.4h-1.8v22.8h1.8z m-37.1-28.5l1.2 0.6q0.3 0.1 4.7 0.1 1 0 3-0.1t2.9 0q0.8 0 2.4 0t2.4 0h6.6q0.1 0 0.4 0t0.5 0 0.3 0 0.4-0.2 0.4-0.4l0.9 0q0.1 0 0.3 0t0.3 0q0.1 2.5 0.1 7.5 0 1.8-0.1 2.4-0.9 0.3-1.6 0.4-0.5-1-1.2-2.8 0-0.2-0.2-1.1t-0.3-1.7-0.2-0.7q-0.1-0.2-0.3-0.3t-0.3-0.2-0.3 0-0.4 0-0.4 0q-0.4 0-1.5 0t-1.6 0-1.4 0-1.6 0.1q-0.2 1.8-0.2 3.1 0 2.1 0 8.6t0.1 10.2q0 0.4-0.1 1.6t0 2 0.3 1.6q0.9 0.4 2.8 0.9t2.6 0.9q0.2 0.8 0.2 1.1 0 0.3-0.1 0.6l-0.8 0q-1.7 0.1-4.8-0.1t-4.7-0.3q-1.1 0-3.3 0.2t-3.4 0.2q-0.1-1.1-0.1-1.1v-0.2q0.4-0.6 1.4-1t2.2-0.6 1.7-0.6q0.5-1 0.5-8.6 0-2.2-0.1-6.7t-0.1-6.8v-2.6q0-0.1 0-0.4t0-0.5 0-0.6-0.1-0.5-0.1-0.3q-0.2-0.3-3.6-0.3-0.7 0-2.1 0.3t-1.7 0.5q-0.5 0.3-0.8 1.7t-0.7 2.4-0.9 1.2q-1-0.6-1.3-1v-8.5z"/></g> </IconBase> ); } }
docs/app/Examples/collections/Breadcrumb/Types/BreadcrumbExampleProps.js
koenvg/Semantic-UI-React
import React from 'react' import { Breadcrumb } from 'semantic-ui-react' const sections = [ { key: 'Home', content: 'Home', link: true }, { key: 'Store', content: 'Store', link: true }, { key: 'Shirt', content: 'T-Shirt', active: true }, ] const BreadcrumbExampleProps = () => ( <Breadcrumb icon='right angle' sections={sections} /> ) export default BreadcrumbExampleProps
examples/globalsaga-pair-of-random-gif-viewers/src/boilerplate.js
HansDP/redux-container-state
import React from 'react' import { render } from 'react-dom' import { createStore, compose, combineReducers } from 'redux' import { Provider, connect } from 'react-redux' import { sagaStoreEnhancer } from 'redux-container-state-globalsaga' export default (containerDomId, View, updater) => { const storeFactory = compose( sagaStoreEnhancer(), window.devToolsExtension ? window.devToolsExtension() : f => f )(createStore) const store = storeFactory(combineReducers({ root: updater })) const ConnectedView = connect(appState => ({ model: appState.root }))(View) render(( <Provider store={store}> <ConnectedView /> </Provider> ), document.getElementById(containerDomId)) }
src/components/Login.js
ValentinAlexandrovGeorgiev/iStore
import React, { Component } from 'react'; import auth from './Auth'; import ajax from 'superagent'; import SERVER_URL from '../config'; class Login extends Component { constructor(){ super(); this.state = { }; this.authenticate = this.authenticate.bind(this); } authenticate(event){ event.preventDefault(); let postParams = {email:event.target.email.value,password: event.target.password.value}; ajax.post(SERVER_URL + '/user/authenticate',postParams) .end((error, response) => { if(!!error) { alert(error); } else if(!!response.body.err){ alert(response.body.err); window.localStorage.setItem('counter',response.body.counter); } else if(response.body.success === true){ this.login(response.body.token,response.body.userType,response.body.id); } }); } login(token,userType,id){ auth.checkUserType(userType); window.localStorage.setItem('jwt-token',token); window.localStorage.setItem('profile-id',id); //clear localStorage counter window.localStorage.removeItem('counter'); window.location.replace('/profile'); } render() { return ( <div className="row"> <div className="col-xs-12 register"> <h2>Login:</h2> <form className="form-group" onSubmit={this.authenticate}> <div className="form-group email-group-login"> <label htmlFor="email">Email: </label> <input type="email" id="email" className="form-control" name="email"/> </div> <div className="form-group"> <label htmlFor="password">Password: </label> <input type="password" id="password" className="form-control" name="password" /> </div> <input type="submit" value="Login" className="btn btn-default" /> </form> </div> </div> ); } } export default Login;
src/svg-icons/content/archive.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentArchive = (props) => ( <SvgIcon {...props}> <path d="M20.54 5.23l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27zM12 17.5L6.5 12H10v-2h4v2h3.5L12 17.5zM5.12 5l.81-1h12l.94 1H5.12z"/> </SvgIcon> ); ContentArchive = pure(ContentArchive); ContentArchive.displayName = 'ContentArchive'; ContentArchive.muiName = 'SvgIcon'; export default ContentArchive;
src/scenes/Auth/components/AuthPage.js
ntxcode/react-base
import React from 'react'; import './AuthPage.css'; const AuthPage = props => <div className="AuthPage"> <header> <h1 className="AuthPageTitle">{props.title}</h1> </header> {props.children} </div>; export default AuthPage;
src/server.js
avantcontra/react-redux-custom-starter
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/store/configureStore'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import { match } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect'; import createHistory from 'react-router/lib/createMemoryHistory'; import {Provider} from 'react-redux'; import getRoutes from './routes'; const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort; const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: targetUrl, ws: true }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(Express.static(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res, {target: targetUrl}); }); app.use('/ws', (req, res) => { proxy.web(req, res, {target: targetUrl + '/ws'}); }); server.on('upgrade', (req, socket, head) => { proxy.ws(req, socket, head); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } json = {error: 'proxy_error', reason: error.message}; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const memoryHistory = createHistory(req.originalUrl); const store = createStore(memoryHistory, client); const history = syncHistoryWithStore(memoryHistory, store); function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } match({ history, routes: getRoutes(store), location: req.originalUrl }, (error, redirectLocation, renderProps) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (renderProps) { loadOnServer({...renderProps, store, helpers: {client}}).then(() => { const component = ( <Provider store={store} key="provider"> <ReduxAsyncConnect {...renderProps} /> </Provider> ); res.status(200); global.navigator = {userAgent: req.headers['user-agent']}; res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }); } else { res.status(404).send('Not found'); } }); }); if (config.port) { server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }