path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/components/settings/settings.js
imankit/dashboard-ui
/** * Created by Darkstar on 11/29/2016. */ import React from 'react'; import {connect} from 'react-redux'; import Toolbar from '../toolbar/toolbar.js'; import Footer from '../footer/footer.jsx'; import {fetchAppSettings, resetAppSettings} from '../../actions'; import RefreshIndicator from 'material-ui/RefreshIndicator'; // icons and mui comps import {List, ListItem} from 'material-ui/List'; import EmailIcon from 'material-ui/svg-icons/communication/email'; import SettingIcon from 'material-ui/svg-icons/action/settings'; import NotificationsIcon from 'material-ui/svg-icons/alert/add-alert'; import AuthIcon from 'material-ui/svg-icons/social/person'; import ImportIcon from 'material-ui/svg-icons/communication/import-export'; import DBIcon from 'material-ui/svg-icons/device/storage'; import RaisedButton from 'material-ui/RaisedButton'; import {grey500, blue500, grey300} from 'material-ui/styles/colors'; import {Tabs, Tab} from 'material-ui/Tabs'; import {FontIcon} from 'material-ui'; import ActionFlightTakeoff from 'material-ui/svg-icons/action/flight-takeoff'; // sub comps import General from './general' import Email from './email' import Push from './push' import ImportExport from './import' import MongoAccess from './mongo' import Auth from './auth' const navStyles = { backgroundColor: 'white', boxSizing: 'border-box', boxShadow: '0px 1px 3px rgba(0, 0, 0, 0.2)', maxWidth: '300px', minWidth: '250px' } class Settings extends React.Component { constructor(props) { super(props) this.state = { selected: 'general', renderComponent: false } } static get contextTypes() { return {router: React.PropTypes.object.isRequired} } componentWillMount() { // load settings if not already found if (!this.props.settingsLoaded) { this.props.onLoad(this.props.appData.appId, this.props.appData.masterKey) } } componentWillUnmount() { this.props.resetAppSettings() } selectTab(whichTab) { this.setState({selected: whichTab}) } getCompToRender(tab) { switch (tab) { case 'general': return <General/> case 'email': return <Email/> case 'push': return <Push/> case 'auth': return <Auth/> case 'import': return <ImportExport/> case 'mongo': return <MongoAccess/> } } handleActive(tab) { this.setState({renderComponent: true}); } render() { const settingsIcon = <SettingIcon color="red"/>; return ( <div id="" style={{ backgroundColor: '#FFF' }}> <div className="settings tables campaign cache"> <Tabs className="settingtabs" tabItemContainerStyle={{ background: 'white' }}> <Tab className="tabbbb" icon={< i className = "ion ion-android-settings tabicon" > </i>} children={< General />}></Tab> <Tab icon={< i className = "ion ion-email tabicon" />} children={< Email color = { grey300 } />}></Tab> <Tab icon={< i className = "ion ion-ios-bell tabicon" />} children={< Push />}></Tab> <Tab icon={< i className = "ion ion-android-person tabicon" />} onActive={this.handleActive.bind(this, 'auth')} children={< Auth renderComponent = { this.state.renderComponent } />}></Tab> <Tab icon={< i className = "ion ion-arrow-swap tabicon" />} children={< ImportExport />}></Tab> <Tab icon={< i className = "ion ion-android-list tabicon" />} children={< MongoAccess />}></Tab> </Tabs> </div> </div> ); } } const mapStateToProps = (state) => { return {appData: state.manageApp, loading: state.loader.secondary_loading, settingsLoaded: state.settings.length} } const mapDispatchToProps = (dispatch) => { return { onLoad: (appId, masterKey) => dispatch(fetchAppSettings(appId, masterKey)), resetAppSettings: () => dispatch(resetAppSettings()) } }; export default connect(mapStateToProps, mapDispatchToProps)(Settings);
src/basic/Swipe/SwipeoutBtn.js
sampsasaarela/NativeBase
import React, { Component } from 'react'; import { Text, TouchableHighlight, View } from 'react-native'; import NativeButton from './NativeButton'; import { connectStyle } from 'native-base-shoutem-theme'; import mapPropsToStyleNames from '../../Utils/mapPropsToStyleNames'; class SwipeoutBtn extends Component { static get defaultProps() { return { backgroundColor: null, color: null, component: null, underlayColor: null, height: 0, key: null, onPress: null, disabled: false, text: 'Click me', type: '', width: 0, }; } render() { var btn = this.props; var styleSwipeoutBtn = [styles.swipeoutBtn]; // apply "type" styles (delete || primary || secondary) if (btn.type === 'delete') styleSwipeoutBtn.push(styles.colorDelete); else if (btn.type === 'primary') styleSwipeoutBtn.push(styles.colorPrimary); else if (btn.type === 'secondary') styleSwipeoutBtn.push(styles.colorSecondary); // apply background color if (btn.backgroundColor) styleSwipeoutBtn.push([{ backgroundColor: btn.backgroundColor }]); styleSwipeoutBtn.push([{ height: btn.height, width: btn.width, }]); var styleSwipeoutBtnComponent = []; // set button dimensions styleSwipeoutBtnComponent.push([{ height: btn.height, width: btn.width, }]); var styleSwipeoutBtnText = [styles.swipeoutBtnText]; // apply text color if (btn.color) styleSwipeoutBtnText.push([{ color: btn.color }]); // apply text color if (btn.color) styleSwipeoutBtnText.push([{ color: btn.color }]) return ( <NativeButton onPress={this.props.onPress} style={styles.swipeoutBtnTouchable} underlayColor={this.props.underlayColor} disabled={this.props.disabled} style={styleSwipeoutBtn} textStyle={styleSwipeoutBtnText}> { (btn.component ? <View style={styleSwipeoutBtnComponent}>{btn.component}</View> : btn.text ) } </NativeButton> ); } } SwipeoutBtn.propTypes = { ...Text.propTypes, style: React.PropTypes.object, }; const StyledSwipeoutBtn = connectStyle('NativeBase.SwipeoutBtn', {}, mapPropsToStyleNames)(SwipeoutBtn); export { StyledSwipeoutBtn as SwipeoutBtn, };
js/fw/components/listSwipe/multi-list-swipe.js
linh918/react-native-starter-kit-demo-
import React, { Component } from 'react'; import { ListView } from 'react-native'; import { Container, Header, Title, Content, Button, Icon, List, ListItem, Text, Left, Right, Body, Item, Input, View, } from 'native-base'; import styles from './styles'; const datas = [ 'Simon Mignolet', 'Nathaniel Clyne', 'Dejan Lovren', 'Mama Sakho', 'Alberto Moreno', 'Emre Can', 'Joe Allen', 'Phil Coutinho', ]; class MultiListSwipe extends Component { constructor(props) { super(props); this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); this.state = { basic: true, listViewData: datas, }; } deleteRow(secId, rowId, rowMap) { rowMap[`${secId}${rowId}`].props.closeRow(); const newData = [...this.state.listViewData]; newData.splice(rowId, 1); this.setState({ listViewData: newData }); } render() { const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => this.props.navigation.goBack()}> <Icon name="arrow-back" /> </Button> </Left> <Body style={{ flex: 3 }}> <Title>Multi List Swipe</Title> </Body> <Right /> </Header> <Content> <List dataSource={this.ds.cloneWithRows(this.state.listViewData)} renderRow={data => <ListItem style={{ paddingLeft: 20 }}> <Text> {data} </Text> </ListItem>} renderLeftHiddenRow={data => <Button full onPress={() => alert(data)} style={{ backgroundColor: '#CCC', flex: 1, alignItems: 'center', justifyContent: 'center', }} > <Icon active name="information-circle" /> </Button>} renderRightHiddenRow={(data, secId, rowId, rowMap) => <Button full danger onPress={_ => this.deleteRow(secId, rowId, rowMap)} style={{ flex: 1, alignItems: 'center', justifyContent: 'center', }} > <Icon active name="trash" /> </Button>} leftOpenValue={75} rightOpenValue={-75} onRowDidOpen={()=>console.log("DidOpen")} onRowOpen={()=>console.log("Opening")} onRowDidClose={()=>console.log("DidClose")} onRowClosen={()=>console.log("Closing")} /> </Content> </Container> ); } } export default MultiListSwipe;
app/containers/LoginPage/LoginForm.js
EpiAggregator/web
import React from 'react' import { Field, reduxForm } from 'redux-form/immutable' import messages from './messages'; import { FormattedMessage } from 'react-intl'; import { TextField } from 'redux-form-material-ui' import RaisedButton from 'material-ui/RaisedButton' const LoginForm = (props) => { const { error, onRegister, onLogin, handleSubmit, submitting } = props this.clicked = ''; let formRouter = (action) => { if (this.clicked === 'register') onRegister(action); else if (this.clicked === 'login') onLogin(action); }; return ( <form style={{width: '260px'}} onSubmit={handleSubmit(formRouter)}> <div> <Field name="email" type="email" component={TextField} floatingLabelText={<FormattedMessage {...messages.email} />} /> </div> <div className="form-group"> <Field name="password" type="password" component={TextField} floatingLabelText={<FormattedMessage {...messages.password} />} label="Password"/> </div> {/* Render error if any. */} {error && <strong>{error}</strong>} <div> <RaisedButton style={{float: 'left'}} type="submit" onClick={() => this.clicked='register'} disabled={submitting}><FormattedMessage {...messages.register} /></RaisedButton> <RaisedButton style={{float: 'right'}} type="submit" onClick={() => this.clicked='login'} disabled={submitting}><FormattedMessage {...messages.login} /></RaisedButton> </div> </form> ) } export default reduxForm({ form: 'loginForm' })(LoginForm)
weather/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
rmfranciacastillo/freecodecamp_projects
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
definitions/npm/react-select_v1.x.x/flow_v0.31.x-v0.52.x/test_react-select_v1.x.x.js
doberkofler/flow-typed
import React from 'react'; import { default as SelectComponent } from 'react-select'; import type Select from 'react-select'; const ArrowRenderer = (props: { onMouseDown: Event }): React$Element<*> => <span>Arrow</span>; const ClearRenderer = (): React$Element<*> => <span />; const filterOption = (option: Object, filterString: string) => { return true; }; const InputRenderer = (props: Object) => <span />; const MenuRenderer = (props: Object) => [<span />]; const OptionComponent = (props: Object) => <span />; const OptionRenderer = (props: Object) => <span />; const options = [ { value: 123, label: 'first item' }, { value: 345, label: 'second item' }, { value: 'foo', label: 'third item', clearableValue: true }, ]; const ValueComponent = (props: Object) => <span />; const ValueRenderer = (props: Object) => <span />; <SelectComponent addLabelText="Add label, plz" aria-describedby="aria-describedby" aria-label="aria-label" aria-labelledby="aria-labelledby" arrowRenderer={ArrowRenderer} autoBlur={false} autofocus={false} autosize={false} backspaceRemoves={false} backspaceToRemoveMessage="Click backspace to remove" className="my-class-name" clearAllText="Clear all" clearRenderer={ClearRenderer} clearValueText="Clear value" clearable={true} deleteRemoves={false} delimiter="," disabled={false} escapeClearsValue={false} filterOption={filterOption} filterOptions={false} ignoreAccents={false} ignoreCase={false} inputProps={{ someCustomProp: false }} inputRenderer={InputRenderer} instanceId="UNIQUE_ID_HERE" isLoading={false} joinValues={false} labelKey="labelKey" matchPos="start" matchProp="label" menuBuffer={10} menuContainerStyle={{ color: 'green' }} menuRenderer={MenuRenderer} menuStyle={{ color: 'green' }} multi={false} name="fance name" noResultsText="No results found. I'm so terribly sorry. I'll just go now. :ยด(" onBlur={(event: Event): void => {}} onBlurResetsInput={false} onChange={(value: any): void => {}} onClose={(): void => {}} onCloseResetsInput={false} onFocus={(event: Event) => {}} onInputChange={(value: any) => { return 'foo'; }} onInputKeyDown={(event: Event) => {}} onMenuScrollToBottom={(): void => {}} onOpen={() => {}} onValueClick={(value: string, event: Event) => {}} openAfterFocus={false} openOnFocus={false} optionClassName="fancy-class-for-option" optionComponent={OptionComponent} optionRenderer={OptionRenderer} options={options} pageSize={10} placeholder="Placeholder text" required={false} resetValue={0} scrollMenuIntoView={false} searchable={true} simpleValue={false} style={{ color: 'gray' }} tabIndex={-1} tabSelectsValue={false} value={0} valueComponent={ValueComponent} valueKey="valueKey" valueRenderer={ValueRenderer} wrapperStyle={{ backgroundColor: 'white' }} />; // $ExpectError addLabelText cannot be number <SelectComponent addLabelText={123} />;
src/index.js
ohmyjersh/sso-component
import React from 'react'; import Immutable from 'immutable'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import { createStore, applyMiddleware } from 'redux'; import App from './containers/App'; import reducer from './state'; const url = window.location.href; const referrer = _getParam('referrer', url); const redirect = _getParam('redirect', url); const initialState = Immutable.Map(); const store = createStore(reducer,initialState, applyMiddleware(thunk)); ReactDOM.render( <Provider store={store}> <App redirect={redirect} referrer={referrer}/> </Provider>, document.getElementById('root') ); function _getParam(field, url) { var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i'); var string = reg.exec(url); return string ? string[1] : null; };
components/centered-map/map.js
sgmap/inspire
import React from 'react' import PropTypes from 'prop-types' import mapboxgl from 'mapbox-gl' import mapStyle from 'mapbox-gl/dist/mapbox-gl.css' import enhanceMapData from './enhance-map-data' import Empty from './empty' import Feature from './feature' class CenteredMap extends React.Component { static propTypes = { data: PropTypes.shape({ features: PropTypes.array.isRequired }).isRequired, bbox: PropTypes.array.isRequired, frozen: PropTypes.bool.isRequired } state = { highlight: null } constructor(props) { super(props) this.handlers = [] if (!props.frozen) { for (const layer of ['point', 'polygon-fill', 'line']) { this.handlers.push({ event: 'mousemove', layer, handler: this.onMouseMove.bind(this, layer) }, { event: 'mouseleave', layer, handler: this.onMouseLeave.bind(this, layer) }) } } } componentDidMount() { const {frozen, bbox} = this.props this.map = new mapboxgl.Map({ container: this.mapContainer, style: 'https://openmaptiles.geo.data.gouv.fr/styles/osm-bright/style.json', interactive: !frozen }) this.map.once('load', this.onLoad) this.map.fitBounds(bbox, { padding: 30, linear: true, duration: 0 }) for (const {event, layer, handler} of this.handlers) { this.map.on(event, layer, handler) } } componentWillUnmount() { const {map} = this for (const {event, layer, handler} of this.handlers) { map.off(event, layer, handler) } } onLoad = () => { const {map} = this const {data} = this.props map.addSource('data', { type: 'geojson', data }) map.addLayer({ id: 'point', type: 'circle', source: 'data', paint: { 'circle-radius': 5, 'circle-color': [ 'case', ['boolean', ['feature-state', 'hover'], false], '#2c3e50', '#3099df' ], 'circle-opacity': [ 'case', ['boolean', ['feature-state', 'hover'], false], 0.8, 0.6 ] }, filter: ['==', '$type', 'Point'] }) map.addLayer({ id: 'polygon-fill', type: 'fill', source: 'data', paint: { 'fill-color': [ 'case', ['boolean', ['feature-state', 'hover'], false], '#2c3e50', '#3099df' ], 'fill-opacity': [ 'case', ['boolean', ['feature-state', 'hover'], false], 0.5, 0.3 ] }, filter: ['==', '$type', 'Polygon'] }) map.addLayer({ id: 'polygon-outline', type: 'line', source: 'data', paint: { 'line-color': '#4790E5', 'line-width': 2 }, filter: ['==', '$type', 'Polygon'] }) map.addLayer({ id: 'line', type: 'line', source: 'data', paint: { 'line-color': [ 'case', ['boolean', ['feature-state', 'hover'], false], '#2c3e50', '#3099df' ], 'line-width': 5, 'line-opacity': 0.8 }, filter: ['==', '$type', 'LineString'] }) } onMouseMove = (layer, event) => { const {map} = this const canvas = map.getCanvas() canvas.style.cursor = 'pointer' const [feature] = event.features if (this.highlighted) { map.setFeatureState({source: 'data', id: this.highlighted}, {hover: false}) } this.highlighted = feature.id map.setFeatureState({source: 'data', id: this.highlighted}, {hover: true}) this.setState({ highlight: { properties: feature.properties, count: event.features.length } }) } onMouseLeave = () => { const {map} = this const canvas = map.getCanvas() canvas.style.cursor = '' if (this.highlighted) { map.setFeatureState({source: 'data', id: this.highlighted}, {hover: false}) } this.setState({ highlight: null }) } render() { const {highlight} = this.state const {data} = this.props return ( <div className='container'> <div ref={el => { this.mapContainer = el }} className='container' /> {highlight && ( <div className='info'> <Feature properties={highlight.properties} otherFeaturesCount={highlight.count - 1} /> </div> )} {data.features.length === 0 && ( <div className='info'> <Empty /> </div> )} <style dangerouslySetInnerHTML={{__html: mapStyle}} // eslint-disable-line react/no-danger /> <style jsx>{` .container { position: relative; height: 100%; width: 100%; } .info { position: absolute; pointer-events: none; top: 10px; left: 10px; max-width: 40%; overflow: hidden; } `}</style> </div> ) } } export default enhanceMapData(CenteredMap)
src/components/ModalDisplayer.js
jcuenod/react-lafwebpy-client
import React from 'react' import {render} from 'react-dom' import ResultsDisplayer from './Modals/ResultsDisplayer' import NavigationDisplayer from './Modals/NavigationDisplayer' import HelpDisplayer from './Modals/HelpDisplayer' class ModalDisplayer extends React.Component { render() { return ( <div> <ResultsDisplayer /> <NavigationDisplayer /> <HelpDisplayer /> </div> ) } } export default ModalDisplayer
frontend/src/Settings/Indexers/Indexers/EditIndexerModalConnector.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { clearPendingChanges } from 'Store/Actions/baseActions'; import { cancelSaveIndexer, cancelTestIndexer } from 'Store/Actions/settingsActions'; import EditIndexerModal from './EditIndexerModal'; function createMapDispatchToProps(dispatch, props) { const section = 'settings.indexers'; return { dispatchClearPendingChanges() { dispatch(clearPendingChanges({ section })); }, dispatchCancelTestIndexer() { dispatch(cancelTestIndexer({ section })); }, dispatchCancelSaveIndexer() { dispatch(cancelSaveIndexer({ section })); } }; } class EditIndexerModalConnector extends Component { // // Listeners onModalClose = () => { this.props.dispatchClearPendingChanges(); this.props.dispatchCancelTestIndexer(); this.props.dispatchCancelSaveIndexer(); this.props.onModalClose(); }; // // Render render() { const { dispatchClearPendingChanges, dispatchCancelTestIndexer, dispatchCancelSaveIndexer, ...otherProps } = this.props; return ( <EditIndexerModal {...otherProps} onModalClose={this.onModalClose} /> ); } } EditIndexerModalConnector.propTypes = { onModalClose: PropTypes.func.isRequired, dispatchClearPendingChanges: PropTypes.func.isRequired, dispatchCancelTestIndexer: PropTypes.func.isRequired, dispatchCancelSaveIndexer: PropTypes.func.isRequired }; export default connect(null, createMapDispatchToProps)(EditIndexerModalConnector);
test/test_helper.js
ryankopf/bnc-website
import _$ from 'jquery' import React from 'react' import ReactDOM from 'react-dom' import TestUtils from 'react-addons-test-utils' import jsdom from 'jsdom' import chai, { expect } from 'chai' import chaiJquery from 'chai-jquery' import { Provider } from 'react-redux' import { createStore } from 'redux' import reducers from '../src/reducers' global.document = jsdom.jsdom('<!doctype html><html><body></body></html>') global.window = global.document.defaultView const $ = _$(window) chaiJquery(chai, chai.util, $) function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ) return $(ReactDOM.findDOMNode(componentInstance)) } $.fn.simulate = function (eventName, value) { if (value) { this.val(value) } TestUtils.Simulate[eventName](this[0]) } export { renderComponent, expect }
src/applications/static-pages/health-care-manage-benefits/get-medical-records-page/index.js
department-of-veterans-affairs/vets-website
// Node modules. import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; export default (store, widgetType) => { const root = document.querySelector(`[data-widget-type="${widgetType}"]`); if (root) { import(/* webpackChunkName: "get-medical-records-page" */ './components/App').then(module => { const App = module.default; ReactDOM.render( <Provider store={store}> <App /> </Provider>, root, ); }); } };
Libraries/Image/ImageBackground.js
hoastoolshop/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule ImageBackground * @flow * @format */ 'use strict'; const Image = require('Image'); const React = require('React'); const StyleSheet = require('StyleSheet'); const View = require('View'); const ensureComponentIsNative = require('ensureComponentIsNative'); /** * Very simple drop-in replacement for <Image> which supports nesting views. * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, ImageBackground, Text } from 'react-native'; * * class DisplayAnImageBackground extends Component { * render() { * return ( * <ImageBackground * style={{width: 50, height: 50}} * source={{uri: 'https://facebook.github.io/react-native/img/opengraph.png'}} * > * <Text>React</Text> * </ImageBackground> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent('DisplayAnImageBackground', () => DisplayAnImageBackground); * ``` */ class ImageBackground extends React.Component<$FlowFixMeProps> { setNativeProps(props: Object) { // Work-around flow const viewRef = this._viewRef; if (viewRef) { ensureComponentIsNative(viewRef); viewRef.setNativeProps(props); } } _viewRef: ?React.ElementRef<typeof View> = null; _captureRef = ref => { this._viewRef = ref; }; render() { const {children, style, imageStyle, imageRef, ...props} = this.props; return ( <View style={style} ref={this._captureRef}> <Image {...props} style={[ StyleSheet.absoluteFill, { // Temporary Workaround: // Current (imperfect yet) implementation of <Image> overwrites width and height styles // (which is not quite correct), and these styles conflict with explicitly set styles // of <ImageBackground> and with our internal layout model here. // So, we have to proxy/reapply these styles explicitly for actual <Image> component. // This workaround should be removed after implementing proper support of // intrinsic content size of the <Image>. width: style.width, height: style.height, }, imageStyle, ]} ref={imageRef} /> {children} </View> ); } } module.exports = ImageBackground;
react-playground/src/index.js
vtrpldn/javascript-cookbook
import React from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter} from 'react-router-dom'; import './index.css'; import App from './components/App/App'; const Root = () => { return ( <BrowserRouter> <App/> </BrowserRouter> ) } ReactDOM.render(<Root />, document.getElementById('root'));
src/routes.js
eiriklv/redux-undo-boilerplate
import React from 'react'; import { Route } from 'react-router'; import App from './containers/App'; import * as containers from './containers'; const { CounterPage } = containers; export default ( <Route component={App}> <Route path="/" component={CounterPage} /> </Route> );
src/components/ConnectionIndicator/index.js
u-wave/web
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import Card from '@mui/material/Card/Card'; import CardHeader from '@mui/material/CardHeader'; import OfflineIcon from './OfflineIcon'; function ConnectionIndicator({ isConnected }) { const { t } = useTranslator(); if (isConnected) { return null; } return ( <div className="ConnectionIndicator-position"> <Card> <CardHeader title={t('server.connectionLost')} subheader={t('server.reconnecting')} avatar={<OfflineIcon />} /> </Card> </div> ); } ConnectionIndicator.propTypes = { isConnected: PropTypes.bool.isRequired, }; export default ConnectionIndicator;
src/components/Home.js
clayhan/reactserver
// src/components/Home.js import React from 'react'; import { Link } from 'react-router'; import Recipe from './Recipe'; import GroceryList from './GroceryList'; export default class Home extends React.Component { constructor(props) { super(props); } render() { const recipes = [ { name: 'Pizza', ingredients: ['Cheese', 'Dough', 'Pepperoni'], image: 'http://i.imgur.com/wh76K45.jpg' }, { name: 'Burrito', ingredients: ['Tortilla', 'Beans', 'Rice'], image: 'http://i.imgur.com/h3VHWCO.jpg' }, { name: 'Ramen', ingredients: ['Noodles', 'Pork', 'Eggs'], image: 'http://i.imgur.com/TIy3UaX.jpg', } ]; console.log('FE Render: Home'); return ( <div className='component home'> <div>Home Component</div> <h1 className='center-text'>Cooking Recipes</h1> <p className='center-text'>Did you ever want to not suck at cooking?</p> <p className='center-text'>Click on every ingredient you need to buy to make the meal!</p> <div className='foodlist'> {recipes.map((foodItem) => { return ( <div> <Recipe key={'Recipe: ' + foodItem.name} name={foodItem.name} ingredients={foodItem.ingredients} image={foodItem.image}/> </div> ); })} </div> </div> ); } }
packages/bonde-admin/src/components/basic-color-picker/basic-color-picker-item.js
ourcities/rebu-client
import PropTypes from 'prop-types' import React from 'react' import classnames from 'classnames' const BasicColorPickerItem = ({ color, isSelected, onSelectColor }) => ( <div className='col col-1 p1'> <div className={classnames( 'col col-12 border-only-bottom border-darken-3 rounded btn bg-white', color )} style={isSelected ? { borderWidth: '5px' } : null} onClick={() => onSelectColor(color)} > <br /> </div> </div> ) BasicColorPickerItem.propTypes = { color: PropTypes.string.isRequired, isSelected: PropTypes.bool, onSelectColor: PropTypes.func } export default BasicColorPickerItem
src/ButtonGroup.js
dozoisch/react-bootstrap
import classNames from 'classnames'; import React from 'react'; import all from 'react-prop-types/lib/all'; import Button from './Button'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; const propTypes = { vertical: React.PropTypes.bool, justified: React.PropTypes.bool, /** * Display block buttons; only useful when used with the "vertical" prop. * @type {bool} */ block: all( React.PropTypes.bool, ({ block, vertical }) => ( block && !vertical ? new Error('`block` requires `vertical` to be set to have any effect') : null ), ), }; const defaultProps = { block: false, justified: false, vertical: false, }; class ButtonGroup extends React.Component { render() { const { block, justified, vertical, className, ...props } = this.props; const [bsProps, elementProps] = splitBsProps(props); const classes = { ...getClassSet(bsProps), [prefix(bsProps)]: !vertical, [prefix(bsProps, 'vertical')]: vertical, [prefix(bsProps, 'justified')]: justified, // this is annoying, since the class is `btn-block` not `btn-group-block` [prefix(Button.defaultProps, 'block')]: block, }; return ( <div {...elementProps} className={classNames(className, classes)} /> ); } } ButtonGroup.propTypes = propTypes; ButtonGroup.defaultProps = defaultProps; export default bsClass('btn-group', ButtonGroup);
packages/zensroom/lib/components/bookings/BookingsRoomUser.js
SachaG/Zensroom
/* Show a user's bookings for a given room. Wrapped with withList. Example: <Components.BookingsRoomUser terms={{view: 'userBookings', userId: currentUser._id, roomId: documentId}}/> http://docs.vulcanjs.org/data-loading.html#List-Resolver */ import React from 'react'; import { Components, registerComponent, withList, withCurrentUser } from 'meteor/vulcan:core'; import compose from 'recompose/compose'; import { FormattedMessage } from 'meteor/vulcan:i18n'; import Bookings from '../../modules/bookings/collection.js'; const BookingsRoomUser = ({loading, results }) => <div className="room-bookings"> <h3><FormattedMessage id='bookings.bookings'/></h3> {loading ? <Components.Loading/> : <div> {results.length ? <h5><FormattedMessage id='bookings.your_bookings'/></h5> : <h5><FormattedMessage id='bookings.no_bookings'/></h5>} {results.map(booking => <Components.Card fields={['startAt', 'endAt']} className="card" key={booking._id} collection={Bookings} document={booking}/>)} </div> } </div> const options = { collection: Bookings } registerComponent('BookingsRoomUser', BookingsRoomUser, [withList, options]); // export default compose( // withList(options), // )(BookingsRoomUser);
src/components/App.js
jasonrundell/jasonrundell-react-site-2017
import React from 'react' import { Provider, connect } from 'react-redux'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import Home from './Home'; import Skills from './Skills'; import Projects from './Projects'; import ProjectPost from './ProjectPost'; import Blog from './Blog'; import BlogPost from './BlogPost'; import Contact from './Contact'; import FontAwesome from 'react-fontawesome'; import '../lense.css'; import './App.css'; import { READ, UNREAD } from '../constants' const App = ({ store = () => {} }) => <Provider store={ store }> <div> <Router> <div> <div className="ls-layout"> <div className="ls-row"> <div className="ls-col-12"> <ul className="list-links ls-text-center"> <li><Link to="/"><FontAwesome name="rocket" /> Home</Link></li> <li><Link to="/skills"><FontAwesome name="tasks" /> Skills</Link></li> <li><Link to="/projects"><FontAwesome name="cubes" /> Projects</Link></li> <li><Link to="/blog"><FontAwesome name="book" /> Blog</Link></li> <li><Link to="/contact"><FontAwesome name="bullhorn" /> Contact</Link></li> </ul> </div> </div> </div> <Route exact path="/" component={ Home } /> <Route exact path="/skills" component={ Skills } /> <Route exact path="/projects" component={ Projects } /> <Route path="/projects/:slug" component={ ProjectPost } /> <Route exact path="/blog" component={ Blog } /> <Route path="/blog/:slug" component={ BlogPost } /> <Route exact path="/contact" component={ Contact } /> </div> </Router> </div> </Provider>; const mapStateToProps = (state) => ({ blogs: state.blogs, projects: state.projects, }); const mapDispatchToProps = (dispatch) => ({ markPostAsRead: () => dispatch({ type: READ }), markPostAsUnread: () => dispatch({ type: UNREAD }) }); export default connect(mapStateToProps, mapDispatchToProps)(App);
js/components/logIn.js
brainly/datacontest
import React from 'react'; const LogIn = (props) => { return ( <div className="app-contest__slide"> <div className="app-contest__header"> <h1 className="sg-text-bit"> <span className="sg-text-bit__hole"> <div className="sg-logo sg-logo--small"> </div> </span> Data Contest </h1> </div> <p className="sg-text">Do you like contests? Do you enjoy getting prizes? This thing might be for you.</p> <div className="app-contest__action js-log-in"> <a className="sg-button-primary sg-button-primary--full" onClick={props.handleClick}> <div className="sg-button-primary__hole"> Join the fun! </div> </a> </div> </div> ) }; export default LogIn;
ui/src/js/profile/tools/ButtonBar.js
Dica-Developer/weplantaforest
import counterpart from 'counterpart'; import React, { Component } from 'react'; import CircleButton from '../../common/components/CircleButton'; export default class ButtonBar extends Component { constructor(props) { super(props); } switchTo(page, index) { this.props.switchTo(page, index); } render() { return ( <div className="buttons"> <div className="col-md-3 align-center"> <CircleButton text={counterpart.translate('TOOLS')} onClick={() => { this.switchTo('overview', 0); }} glyphIcon="glyphicon-forward" className={this.props.clickedIndex == 0 ? 'circleButtonActive' : ''} /> </div> <div className={'col-md-3 align-center'}> <CircleButton text={counterpart.translate('WIDGETS')} onClick={() => { this.switchTo('widgets', 1); }} glyphIcon="glyphicon-forward" className={this.props.clickedIndex == 1 ? 'circleButtonActive' : ''} /> </div> <div className={'col-md-3 align-center'}> <CircleButton text={counterpart.translate('CERTIFICATES')} onClick={() => { this.switchTo('certificates', 2); }} glyphIcon="glyphicon-forward" className={this.props.clickedIndex == 2 ? 'circleButtonActive' : ''} /> </div> <div className={'col-md-3 align-center'}> <CircleButton text={counterpart.translate('BANNER')} onClick={() => { this.switchTo('banner', 3); }} glyphIcon="glyphicon-forward" className={this.props.clickedIndex == 3 ? 'circleButtonActive' : ''} /> </div> </div> ); } } /* vim: set softtabstop=2:shiftwidth=2:expandtab */
app/javascript/mastodon/components/status_content.js
cobodo/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Permalink from './permalink'; import classnames from 'classnames'; import PollContainer from 'mastodon/containers/poll_container'; import Icon from 'mastodon/components/icon'; import { autoPlayGif } from 'mastodon/initial_state'; const MAX_HEIGHT = 642; // 20px * 32 (+ 2px padding at the top) export default class StatusContent extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, expanded: PropTypes.bool, showThread: PropTypes.bool, onExpandedToggle: PropTypes.func, onClick: PropTypes.func, collapsable: PropTypes.bool, onCollapsedToggle: PropTypes.func, }; state = { hidden: true, }; _updateStatusLinks () { const node = this.node; if (!node) { return; } const links = node.querySelectorAll('a'); for (var i = 0; i < links.length; ++i) { let link = links[i]; if (link.classList.contains('status-link')) { continue; } link.classList.add('status-link'); let mention = this.props.status.get('mentions').find(item => link.href === item.get('url')); if (mention) { link.addEventListener('click', this.onMentionClick.bind(this, mention), false); link.setAttribute('title', mention.get('acct')); } else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) { link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false); } else { link.setAttribute('title', link.href); link.classList.add('unhandled-link'); } link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); } if (this.props.status.get('collapsed', null) === null) { let collapsed = this.props.collapsable && this.props.onClick && node.clientHeight > MAX_HEIGHT && this.props.status.get('spoiler_text').length === 0; if(this.props.onCollapsedToggle) this.props.onCollapsedToggle(collapsed); this.props.status.set('collapsed', collapsed); } } handleMouseEnter = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-original'); } } handleMouseLeave = ({ currentTarget }) => { if (autoPlayGif) { return; } const emojis = currentTarget.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; emoji.src = emoji.getAttribute('data-static'); } } componentDidMount () { this._updateStatusLinks(); } componentDidUpdate () { this._updateStatusLinks(); } onMentionClick = (mention, e) => { if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/@${mention.get('acct')}`); } } onHashtagClick = (hashtag, e) => { hashtag = hashtag.replace(/^#/, ''); if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(`/tags/${hashtag}`); } } handleMouseDown = (e) => { this.startXY = [e.clientX, e.clientY]; } handleMouseUp = (e) => { if (!this.startXY) { return; } const [ startX, startY ] = this.startXY; const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)]; let element = e.target; while (element) { if (element.localName === 'button' || element.localName === 'a' || element.localName === 'label') { return; } element = element.parentNode; } if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) { this.props.onClick(); } this.startXY = null; } handleSpoilerClick = (e) => { e.preventDefault(); if (this.props.onExpandedToggle) { // The parent manages the state this.props.onExpandedToggle(); } else { this.setState({ hidden: !this.state.hidden }); } } setRef = (c) => { this.node = c; } render () { const { status } = this.props; const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden; const renderReadMore = this.props.onClick && status.get('collapsed'); const renderViewThread = this.props.showThread && status.get('in_reply_to_id') && status.get('in_reply_to_account_id') === status.getIn(['account', 'id']); const content = { __html: status.get('contentHtml') }; const spoilerContent = { __html: status.get('spoilerHtml') }; const classNames = classnames('status__content', { 'status__content--with-action': this.props.onClick && this.context.router, 'status__content--with-spoiler': status.get('spoiler_text').length > 0, 'status__content--collapsed': renderReadMore, }); const showThreadButton = ( <button className='status__content__read-more-button' onClick={this.props.onClick}> <FormattedMessage id='status.show_thread' defaultMessage='Show thread' /> </button> ); const readMoreButton = ( <button className='status__content__read-more-button' onClick={this.props.onClick} key='read-more'> <FormattedMessage id='status.read_more' defaultMessage='Read more' /><Icon id='angle-right' fixedWidth /> </button> ); if (status.get('spoiler_text').length > 0) { let mentionsPlaceholder = ''; const mentionLinks = status.get('mentions').map(item => ( <Permalink to={`/@${item.get('acct')}`} href={item.get('url')} key={item.get('id')} className='mention'> @<span>{item.get('username')}</span> </Permalink> )).reduce((aggregate, item) => [...aggregate, item, ' '], []); const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />; if (hidden) { mentionsPlaceholder = <div>{mentionLinks}</div>; } return ( <div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}> <span dangerouslySetInnerHTML={spoilerContent} className='translate' /> {' '} <button tabIndex='0' className={`status__content__spoiler-link ${hidden ? 'status__content__spoiler-link--show-more' : 'status__content__spoiler-link--show-less'}`} onClick={this.handleSpoilerClick}>{toggleText}</button> </p> {mentionsPlaceholder} <div tabIndex={!hidden ? 0 : null} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''} translate`} dangerouslySetInnerHTML={content} /> {!hidden && !!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} </div> ); } else if (this.props.onClick) { const output = [ <div className={classNames} ref={this.setRef} tabIndex='0' onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp} key='status-content' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} /> {!!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} </div>, ]; if (renderReadMore) { output.push(readMoreButton); } return output; } else { return ( <div className={classNames} ref={this.setRef} tabIndex='0' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <div className='status__content__text status__content__text--visible translate' dangerouslySetInnerHTML={content} /> {!!status.get('poll') && <PollContainer pollId={status.get('poll')} />} {renderViewThread && showThreadButton} </div> ); } } }
react/src/pages/feedback/message-edit.js
motiko/sfdc-debug-logs
import React from 'react' import ReplyIcon from 'material-ui-icons/Reply' import Button from 'material-ui/Button' import TextField from 'material-ui/TextField' import { DialogActions } from 'material-ui/Dialog' export default class MessageEdit extends React.Component { constructor(props) { super(props) this.state = { name: '', body: '', error: '' } this.handleSubmit = this.handleSubmit.bind(this) } handleNameChange(e) { this.setState({ name: e.target.value }) } componentDidMount() { if (this.nameElement) { this.nameElement.focus() } } handleBodyChange(e) { const newBody = e.target.value const newLines = newBody.match(/\n/g) if (newLines && newLines.length > 1) return if (newBody.length > 140) return this.setState({ body: newBody }) } handleSubmit() { if (this.state.body.trim() === '' || this.state.body.length < 5) { this.setState({ error: 'This field is required (at least 5 characters)' }) return } const msg = { body: this.state.body, author: this.state.name } this.props.onSubmit(msg) } handleKeyDown(e) { if (e.keyCode === 13) { if (e.altKey || e.shiftKey || e.ctrlKey || e.metaKey) this.handleSubmit() } } render() { return ( <React.Fragment> <TextField label="Name (Optional)" value={this.state.name} onChange={e => this.handleNameChange(e)} inputRef={element => { this.nameElement = element }} /> <TextField label={`Any thoughts (${this.state.body.length}/140)`} value={this.state.body} onChange={e => this.handleBodyChange(e)} multiline fullWidth rowsMax="2" onKeyDown={e => this.handleKeyDown(e)} error={this.state.error.length > 0} helperText={this.state.error} /> <DialogActions> <Button color="primary" onClick={this.handleSubmit}> <ReplyIcon /> Send </Button> </DialogActions> </React.Fragment> ) } }
src/svg-icons/action/opacity.js
verdan/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionOpacity = (props) => ( <SvgIcon {...props}> <path d="M17.66 8L12 2.35 6.34 8C4.78 9.56 4 11.64 4 13.64s.78 4.11 2.34 5.67 3.61 2.35 5.66 2.35 4.1-.79 5.66-2.35S20 15.64 20 13.64 19.22 9.56 17.66 8zM6 14c.01-2 .62-3.27 1.76-4.4L12 5.27l4.24 4.38C17.38 10.77 17.99 12 18 14H6z"/> </SvgIcon> ); ActionOpacity = pure(ActionOpacity); ActionOpacity.displayName = 'ActionOpacity'; ActionOpacity.muiName = 'SvgIcon'; export default ActionOpacity;
app/handlers/page1.js
samarpanda/react-webpack-express
import React from 'react'; var App = module.exports = React.createClass({ getInitialState(){ return {page: 1}; }, render(){ return ( <div>Page{this.state.page} handler</div> ); } }); //export default App;
src/js/components/members/membersTable.js
jrnail23/sitterswap-ui
import React from 'react' import {Link} from 'react-router' import EmailLink from '../common/emailLink' class MemberRow extends React.Component { static propTypes = { member: React.PropTypes.shape({ key: React.PropTypes.string.isRequired, firstName: React.PropTypes.string.isRequired, lastName: React.PropTypes.string.isRequired, emailAddress: React.PropTypes.string.isRequired }) } render () { const member = this.props.member return ( <tr> <td><Link to={`/members/${member.key}`}>{member.lastName + ', ' + member.firstName}</Link></td> <td><EmailLink emailAddress={member.emailAddress} /></td> </tr> ) } } export default class MembersTable extends React.Component { static propTypes = { members: React.PropTypes.array } render () { return ( <div> <table className='table table-striped table-bordered table-condensed'> <thead> <tr> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> {this.props.members.map(member => { return <MemberRow key={member.key} member={member} /> })} </tbody> </table> </div> ) } }
src/svg-icons/av/closed-caption.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvClosedCaption = (props) => ( <SvgIcon {...props}> <path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 7H9.5v-.5h-2v3h2V13H11v1c0 .55-.45 1-1 1H7c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v1zm7 0h-1.5v-.5h-2v3h2V13H18v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v1z"/> </SvgIcon> ); AvClosedCaption = pure(AvClosedCaption); AvClosedCaption.displayName = 'AvClosedCaption'; AvClosedCaption.muiName = 'SvgIcon'; export default AvClosedCaption;
src/Preloader.js
react-materialize/react-materialize
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import Spinner from './Spinner'; const colors = ['blue', 'red', 'yellow', 'green']; const Preloader = ({ active, size, color, flashing, className }) => { let classes = cx('preloader-wrapper', { active }, size); let spinners; if (flashing) { spinners = colors.map(color => ( <Spinner color={color} only={false} key={color} /> )); } else { spinners = <Spinner color={color} />; } return <div className={cx(className, classes)}>{spinners}</div>; }; Preloader.propTypes = { className: PropTypes.string, /** * The scale of the circle * @default 'medium' */ size: PropTypes.oneOf(['big', 'small', 'medium']), /** * Whether to spin * @default true */ active: PropTypes.bool, /** * The color of the circle, if not flashing * @default 'blue' */ color: PropTypes.oneOf(['blue', 'red', 'yellow', 'green']), /** * Wheter to circle four different colors * @default false */ flashing: PropTypes.bool }; Preloader.defaultProps = { active: true, flashing: false, color: 'blue' }; export default Preloader;
client/src/components/NavBar/NavBarForm.js
ccabrales/espn-fantasy-stats
import React from 'react'; import PropTypes from 'prop-types'; import { Button, Form, Input, Select } from 'semantic-ui-react'; /** * Form for the nav bar to allow the user to update the League ID and season * @class NavBarForm */ class NavBarForm extends React.Component { /** * Initial state to keep track of the form field values prior to submission * @type {Object} */ state = { leagueId: { value: this.props.navBarData.leagueId, error: false }, season: { value: this.props.navBarData.seasonId, error: false } }; /** * Season options starting from 2000 and going to the current year (descending order) * @returns {Array} */ seasonOptions = () => { const originalYear = 2000; const currYear = new Date().getFullYear(); const range = currYear - originalYear; return Array.from(new Array(range), (val, index) => ({ key: currYear - index, value: currYear - index, text: currYear - index })); }; /** * Handle form submission * @param e - Event */ handleFormSubmit = e => { e.preventDefault(); this.props.updateLeagueData(this.state.leagueId.value, this.state.season.value); }; /** * Update the value for the given field in local state, and validate it * @param e - Event * @param name - Field name * @param value - Field value */ handleFieldChange = (e, { name, value }) => { const nameProperty = { ...this.state[name] }; nameProperty.value = value; if (typeof value === 'string') { nameProperty.error = !(this.isNumber(value) && this.isWithinMaxLength(10)(value)); } else { nameProperty.error = !this.isNumber(value); } this.setState({ [name]: nameProperty }); }; /** * Validates that the given input is a number. Returns true if value is a number * @param value * @returns {*|boolean} */ isNumber = value => { // eslint-disable-line arrow-body-style return value && !isNaN(Number(value)); }; /** * Validates that the given input is no longer than len characters. Returns true if value is within max length * @param len */ isWithinMaxLength = len => value => { // eslint-disable-line arrow-body-style return value && value.length <= len; }; render() { const seasonYears = this.seasonOptions(); const { navBarData } = this.props; return ( <Form size='tiny' onSubmit={this.handleFormSubmit}> <Form.Group inline> <Form.Field required control={Input} name='leagueId' label='League ID' placeholder='League ID' error={this.state.leagueId.error} onChange={this.handleFieldChange} defaultValue={this.state.leagueId.value} /> <Form.Field required control={Select} name='season' label='Season ID' placeholder='Season' options={seasonYears} defaultValue={navBarData.seasonId} error={this.state.season.error} onChange={this.handleFieldChange} /> <Form.Field primary control={Button} disabled={!this.state.leagueId.value || this.state.leagueId.error || this.state.season.error} > Update </Form.Field> {/* TODO: show success message when the form has been submitted? https://react.semantic-ui.com/collections/form#form-example-success */} </Form.Group> </Form> ); } } NavBarForm.propTypes = { navBarData: PropTypes.shape({ leagueId: PropTypes.string, seasonId: PropTypes.number.isRequired }).isRequired, updateLeagueData: PropTypes.func.isRequired }; export default NavBarForm;
src/components/ReduxFormFields/DateField.js
zerkedev/zerke-app
import React, { Component } from 'react'; import DatePicker from './DatePicker'; import { Field } from 'redux-form'; import { TextField } from 'redux-form-material-ui'; import muiThemeable from 'material-ui/styles/muiThemeable'; import { injectIntl, intlShape } from 'react-intl'; import FontIcon from 'material-ui/FontIcon'; import IconButton from 'material-ui/IconButton'; import { formatDateToObject, formatDateToString } from '../../utils/dateTime' import PropTypes from 'prop-types'; const defaultFormatOptions = {day: '2-digit', month: '2-digit', year: 'numeric'}; class DateField extends Component { constructor(props) { super(props); this.state = { value: '' } } handleOnDatePickerChange = (e, newVal) => { const { change, name, formatOptions } = this.props; const format = formatOptions?formatOptions:defaultFormatOptions; if(newVal !== null) { this.setState({value: new Date(newVal).toLocaleString('de-DE', format)}); change(name, new Date(newVal).toISOString()); } } handleDateTextBlur = (state, e) => { const { change, input, formatOptions } = this.props; const { name } = input; const newVal = this.state.value; const format = formatOptions?formatOptions:defaultFormatOptions; if(!newVal) { return; } this.setState({value: formatDateToString(newVal, format)}); change(name, formatDateToObject(newVal, format).toISOString()); } componentWillReceiveProps(nextProps){ const { formatOptions } = this.props; const format = formatOptions?formatOptions:defaultFormatOptions; if(nextProps!==undefined){ const { input } = nextProps; const { value } = input; if(value!==undefined && value!==null && value.length>0){ this.setState({value: new Date(value).toLocaleString('de-DE', format)}); } } } handleDateTextChange = (evt) => { this.setState({value: evt.target.value}); } render() { const { disabled, input, floatingLabelText, datePickerText, muiTheme, intl, } = this.props; const { name } = input; return ( <div style={{display: 'flex', alignItems: 'flex-end'}}> <TextField name={`${name}Text`} value={this.state.value} onBlur={this.handleDateTextBlur} onChange={this.handleDateTextChange} disabled={disabled} floatingLabelText={floatingLabelText} style={{width: 90, alignItems: 'center'}} ref={`${name}Text`} /> <Field name={name} textFieldStyle={{display: 'none'}} autoOk={true} tabIndex={-1} DateTimeFormat={global.Intl.DateTimeFormat} okLabel="OK" cancelLabel={intl.formatMessage({id: 'cancel'})} locale={intl.formatMessage({id: 'current_locale'})} disabled={disabled} component={DatePicker} onChange={this.handleOnDatePickerChange} floatingLabelText={''} ref={name} withRef /> <IconButton onClick={()=>{this.refs[name].getRenderedComponent().refs.component.openDialog();}} tabIndex={-1} disabled={disabled} tooltip={datePickerText}> <FontIcon className="material-icons" style={{fontSize: 12}} color={muiTheme.palette.primary1Color}> event </FontIcon> </IconButton> </div> ); } } DateField.propTypes = { disabled: PropTypes.bool.isRequired, input: PropTypes.object.isRequired, floatingLabelText: PropTypes.string.isRequired, datePickerText: PropTypes.string.isRequired, muiTheme: PropTypes.object.isRequired, intl: intlShape.isRequired, }; export default muiThemeable()(injectIntl(DateField));
www/ui/documentation/code-block.js
ForbesLindesay/cabbie
import React from 'react'; import styled from 'styled-components'; const Pre = styled.pre` overflow-x: auto; `; const Code = styled.code` font-size: 1em; @media(min-width: 1200px) { font-size: 1.3vw; } @media(min-width: 1550px) { font-size: 1.35em; } `; function CodeBlock(props) { return <Pre><Code {...props} /></Pre>; } export default CodeBlock;
src/svg-icons/device/battery-20.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery20 = (props) => ( <SvgIcon {...props}> <path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z"/><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z"/> </SvgIcon> ); DeviceBattery20 = pure(DeviceBattery20); DeviceBattery20.displayName = 'DeviceBattery20'; DeviceBattery20.muiName = 'SvgIcon'; export default DeviceBattery20;
app/components/Block.js
yandan66/react-native-maicai
import React from 'react'; import { StyleSheet, Text, View, Dimensions, Image, TouchableOpacity } from 'react-native'; export default class Block extends React.Component { render() { return ( <View style={styles.block}> {this.renderHeader()} <View style={styles.blockContent}> {this.props.children} </View> </View> ) } renderHeader() { let type = parseInt(this.props.type, 10) let header = null; switch (type) { case 1: if (this.props.title) { header = ( <View style={styles.blockHeader}> <View style={styles.headerTitleMain}> <Text style={[styles.titleMain, styles.titleMainLeft, styles.titleWithBorderLeft]}> {this.props.title} </Text> {this.renderLink()} </View> </View> ) } else { header = null } break; case 2: header = ( <View style={styles.blockHeader}> <View style={styles.headerTitleMain}> <Text style={styles.titleMain}>{this.props.title}</Text> {this.renderLink()} </View> {this.props.subTitle ? ( <View style={styles.headerTitleSub}> <Text style={styles.titleSub}>{this.props.subTitle}</Text> </View> ) : null} </View> ); break; default: break } return header; } renderLink() { let link = this.props.link; const navigate = this.props.navigation; if (link) { return ( <TouchableOpacity activeOpacity={1} focusedOpacity={1} onPress={() => navigate.navigate('Detail')}> <Text style={styles.headerLink}>{this.props.link || 'ๆ›ดๅคš'}</Text> </TouchableOpacity> ); } else { return null; } } } const styles = StyleSheet.create({ block: { marginBottom: 8, justifyContent: 'space-between', minHeight: 50, backgroundColor: '#fff' }, blockHeader: { padding: 10, // alignItems: 'center', borderBottomWidth: 1, borderColor: '#efefef' }, headerTitleMain: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }, headerTitleSub: { alignItems: 'center' }, titleMain: { fontSize: 20, color: '#333', flex: 1, textAlign: 'center' }, titleMainLeft: { textAlign: 'left' }, titleWithBorderLeft: { paddingLeft: 10, borderColor: '#2eb257', borderLeftWidth: 3 }, titleSub: { paddingRight: 28, fontSize: 12, color: '#666' }, headerLink: { fontSize: 14, width: 28, height: 20, color: '#2eb257' }, headerLinkRight: {}, blockContent: { paddingVertical: 10 } })
src/containers/HistoryUserBookingsPage.js
qandobooking/booking-frontend
import React from 'react'; import HistoryUserBookings from '../components/HistoryUserBookings'; import { connect } from 'react-redux'; import { toInteger, debounce } from 'lodash'; import { loadHistoryUserBookings, setHistoryUserBookingsPage, setHistoryUserBookingsSearchFilter, } from '../actions/user-bookings'; import { getHistoryUserBookings, getHistoryUserBookingsPagination } from '../selectors/bookings'; function setFilters(props) { const { search, status } = props.location.query; props.setHistoryUserBookingsSearchFilter(search || ''); } function setPage(props) { const page = toInteger(props.location.query.page); // When 0 page go to the first and set location props.setHistoryUserBookingsPage(page > 0 ? page : 1, true); } function loadData(props) { props.loadHistoryUserBookings(); } class HistoryUserBookingsPage extends React.Component { constructor(props) { super(props); this.onSetPage = this.onSetPage.bind(this); this.onSearchTextChanged = this.onSearchTextChanged.bind(this); // Debounced version of loadHistoryUserBookings this.loadHistoryUserBookingsDebounced = debounce(this.props.loadHistoryUserBookings, 100); } componentWillMount() { setFilters(this.props); setPage(this.props); loadData(this.props); } onSetPage(page) { if (this.props.pagination.currentPage !== page) { this.props.setHistoryUserBookingsPage(page, true); this.props.loadHistoryUserBookings(); } } onSearchTextChanged(search) { this.props.setHistoryUserBookingsSearchFilter(search, true); this.loadHistoryUserBookingsDebounced(); } render() { const { bookings, pagination, search } = this.props; return ( <div className="container-fluid margin-top-20"> <HistoryUserBookings bookings={bookings} pagination={pagination} searchText={search} onSearchTextChanged={this.onSearchTextChanged} onSetPage={this.onSetPage} /> </div> ); } } function mapStateToProps(state) { const filters = state.userData.bookings.history.filters; return { bookings: getHistoryUserBookings(state), pagination: getHistoryUserBookingsPagination(state), ...filters }; } export default connect(mapStateToProps, { loadHistoryUserBookings, setHistoryUserBookingsPage, setHistoryUserBookingsSearchFilter, })(HistoryUserBookingsPage);
demos/toggles/demos/checkboxOn.js
isogon/styled-mdl-website
import React from 'react' import { Checkbox } from 'styled-mdl' const demo = () => <Checkbox label="Checkbox" defaultChecked /> const caption = 'Checkbox On' const code = '<Checkbox label="Checkbox" defaultChecked />' export default { demo, caption, code }
app/src/Frontend/modules/mission/containers/mission/verify/index.js
ptphp/ptphp
/** * Created by jf on 15/12/10. */ "use strict"; import React from 'react'; import { ButtonArea, Button, CellsTitle, CellBody, Cell, Form, FormCell, TextArea, Uploader, Toast, Dialog } from '../../../../../index'; const {Alert} = Dialog; var Sentry = require('react-sentry'); import Page from '../../../components/page/index'; import './index.less'; export default React.createClass( { mixins: [Sentry], contextTypes: { dataStore: React.PropTypes.object.isRequired, router: React.PropTypes.object.isRequired }, getInitialState(){ return { loading:false, pics:[], note:"", toast_title:"ๅฎŒๆˆ", toast_show:false, toastTimer:null, showAlert:false, alert: { title: '', buttons: [ { label: 'ๅ…ณ้—ญ', onClick: this.hideAlert } ] } } }, onUploadChange(file,e){ let pics = this.state.pics; pics.push({ url:file.data, onRemove:(idx)=>{ let {pics} = this.state pics = pics.filter((file,key)=>{ return idx !== key; }); this.setState({pics}); } }); this.setState({ pics }); }, hideAlert() { this.setState({showAlert: false}); }, componentDidMount(){ Utils.set_site_title("ไบคไปปๅŠก"); }, doVerify(){ let {alert} = this.state; if(this.state.pics.length == 0){ alert.title = "่ฏทๅ…ˆไธŠไผ ๅ›พ็‰‡"; this.setState({ alert, showAlert:true }); return; } let $mession_id = this.props.parent.state.mission.id; let $task_key = this.props.parent.state.taskKey; let pics = []; this.state.pics.map(pic=>{ pics.push(pic.url) }); let $note = this.state.note; this.setState({ loading:true }); this.context.dataStore.do_verify($mession_id,$task_key,pics.join("|"),$note,(result,error)=>{ if(error){ //alert(result); }else{ this.state.toastTimer = setTimeout(()=> { this.setState({toast_show: false}); this.props.parent.hideVerifyModal(); this.props.parent.getDetail(); }, 1500); this.setState({ loading:false, toast_show:true, toast_title:"ๆไบคๆˆๅŠŸ" }); } }) }, componentWillUnmount() { this.state.toastTimer && clearTimeout(this.state.toastTimer); }, renderDetail(){ return ( <div> <Form> <FormCell> <CellBody> <Uploader title="ๅฎกๆ ธๅ›พ็‰‡ไธŠไผ " maxCount={6} files={this.state.pics} onError={msg => alert(msg)} onChange={this.onUploadChange} /> </CellBody> </FormCell> <CellsTitle>ๅค‡ๆณจ</CellsTitle> <FormCell> <CellBody> <TextArea valu={this.state.note} onChange={e=>{this.setState({note:e.target.value})}} placeholder="่ฏท่พ“ๅ…ฅๅค‡ๆณจ" rows="3" maxlength="200" /> </CellBody> </FormCell> <div style={{margin:"16px 20px"}}> <Button onClick={this.doVerify}>ๆไบค</Button> </div> </Form> </div> ) }, render() { let detail = this.renderDetail(); return ( <div> {detail} <Toast icon="loading" show={this.state.loading}>ๆไบคไธญ...</Toast> <Toast show={this.state.toast_show}>{this.state.toast_title}</Toast> <Alert title={this.state.alert.title} buttons={this.state.alert.buttons} show={this.state.showAlert} /> </div> ); } });
components/range/Range.js
zooshgroup/react-toolbox-components
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import classnames from 'classnames'; import styleShape from 'react-style-proptype'; import { themr } from 'react-css-themr'; import { round, range } from 'react-toolbox/lib/utils/utils'; import { SLIDER } from 'react-toolbox/lib/identifiers'; import events from 'react-toolbox/lib/utils/events'; import InjectProgressBar from 'react-toolbox/lib/progress_bar/ProgressBar'; import InjectInput from 'react-toolbox/lib/input/Input'; const factory = (ProgressBar, Input) => { class Range extends Component { static propTypes = { className: PropTypes.string, disabled: PropTypes.bool, editable: PropTypes.bool, mapValueOnPin: PropTypes.func, max: PropTypes.number, min: PropTypes.number, onChange: PropTypes.func, onDragStart: PropTypes.func, onDragStop: PropTypes.func, pinned: PropTypes.bool, showValues: PropTypes.bool, snaps: PropTypes.bool, step: PropTypes.number, style: styleShape, theme: PropTypes.shape({ buffer: PropTypes.string, container: PropTypes.string, editable: PropTypes.string, innerknob: PropTypes.string, innerprogress: PropTypes.string, input: PropTypes.string, knob: PropTypes.string, pinned: PropTypes.string, pressed: PropTypes.string, progress: PropTypes.string, ring: PropTypes.string, showValues: PropTypes.string, slider: PropTypes.string, snap: PropTypes.string, snaps: PropTypes.string, }), value: PropTypes.shape({ first: PropTypes.number, second: PropTypes.number, }), }; static defaultProps = { buffer: 0, className: '', editable: false, mapValueOnPin: x => x, max: 100, min: 0, onDragStart: () => {}, onDragStop: () => {}, pinned: false, showValues: false, snaps: false, step: 0.01, value: { first: 0, second: 0, }, }; state = { inputFocused: { first: false, second: false, }, inputValue: { first: null, second: null, }, rangeLength: 0, rangeStart: 0, }; componentDidMount() { window.addEventListener('resize', this.handleResize); this.handleResize(); } componentWillReceiveProps(nextProps) { if (this.state.inputFocused.first && this.props.value.first !== nextProps.value.first) { this.setState({ inputValue: { ...this.state.inputValue, first: this.valueForInput(nextProps.value.first), }, }); } if (this.state.inputFocused.second && this.props.value.second !== nextProps.value.second) { this.setState({ inputValue: { ...this.state.inputValue, second: this.valueForInput(nextProps.value.second), }, }); } } shouldComponentUpdate(nextProps, nextState) { return this.state.inputFocused.first || !nextState.inputFocused.first || this.state.inputFocused.second || !nextState.inputFocused.second; } componentWillUpdate(nextProps, nextState) { if (nextState.pressed !== this.state.pressed) { if (nextState.pressed) { this.props.onDragStart(); } else { this.props.onDragStop(); } } } componentWillUnmount() { window.removeEventListener('resize', this.handleResize); events.removeEventsFromDocument(this.getMouseEventMap()); events.removeEventsFromDocument(this.getTouchEventMap()); events.removeEventsFromDocument(this.getKeyboardEvents()); } getInput(type) { return this[`${type}InputNode`] && this[`${type}InputNode`].getWrappedInstance ? this[`${type}InputNode`].getWrappedInstance() : this[`${type}InputNode`]; } getKeyboardEvents() { return { keydown: this.handleKeyDown, }; } getMouseEventMap() { return { mousemove: this.handleMouseMove, mouseup: this.handleMouseUp, }; } getTouchEventMap() { return { touchmove: this.handleTouchMove, touchend: this.handleTouchEnd, }; } grabbedKnob = null; addToValue(type, increment) { let value = this.state.inputFocused[type] ? parseFloat(this.state.inputValue[type]) : this.props.value[type]; value = this.trimValue(value + increment); if (value !== this.props.value[type]) { const newValue = { ...this.props.value, [type]: value }; this.props.onChange(newValue); } } handleInputFocus = (type) => { this.setState({ inputFocused: { ...this.state.inputValue, [type]: true, }, inputValue: { ...this.state.inputValue, [type]: this.valueForInput(this.props.value[type]), }, }); }; handleInputChange = (type, value) => { this.setState({ inputValue: { ...this.state.inputValue, [type]: value, }, }); }; handleInputBlur = (type, event) => { const value = this.state.inputValue[type] || 0; this.setState({ inputFocused: false, inputValue: { ...this.state.inputValue, [type]: null }, }, () => { const newValue = { ...this.props.value, [type]: this.trimValue(value) }; this.props.onChange(newValue, event); }); }; handleKeyDown = (event) => { const type = this.state.inputFocused.first ? 'first' : (this.state.inputFocused.second ? 'second' : null); // eslint-disable-line no-nested-ternary if (type) { if ([13, 27].indexOf(event.keyCode) !== -1) this.getInput(type).blur(); if (event.keyCode === 38) this.addToValue(type, this.props.step); if (event.keyCode === 40) this.addToValue(type, -this.props.step); } }; handleMouseDown = (type, event) => { if (this.state.inputFocused[type]) this.getInput(type).blur(); this.grabbedKnob = type; events.addEventsToDocument(this.getMouseEventMap()); this.start(events.getMousePosition(event)); events.pauseEvent(event); }; handleMouseMove = (event) => { events.pauseEvent(event); this.move(events.getMousePosition(event)); }; handleMouseUp = () => { this.end(this.getMouseEventMap()); }; handleResize = (event, callback) => { const { left, right } = ReactDOM.findDOMNode(this.progressbarNode).getBoundingClientRect(); const cb = (callback) || (() => {}); this.setState({ rangeStart: left, rangeLength: right - left }, cb); }; handleRangeBlur = () => { events.removeEventsFromDocument(this.getKeyboardEvents()); }; handleRangeFocus = () => { events.addEventsToDocument(this.getKeyboardEvents()); }; handleTouchEnd = () => { this.end(this.getTouchEventMap()); }; handleTouchMove = (event) => { this.move(events.getTouchPosition(event)); }; handleTouchStart = (event) => { if (this.state.inputFocused) this.getInput().blur(); this.start(events.getTouchPosition(event)); events.addEventsToDocument(this.getTouchEventMap()); events.pauseEvent(event); }; end(revents) { events.removeEventsFromDocument(revents); this.setState({ pressed: false }); } knobOffset(value) { const { max, min } = this.props; return 100 * ((value - min) / (max - min)); } move(position) { const newKnobValue = this.positionToValue(position); if (newKnobValue !== this.props.value[this.grabbedKnob]) { const newValue = { ...this.props.value, [this.grabbedKnob]: newKnobValue }; this.props.onChange(newValue); } } positionToValue(position) { const { rangeStart: start, rangeLength: length } = this.state; const { max, min, step } = this.props; const pos = ((position.x - start) / length) * (max - min); return this.trimValue((Math.round(pos / step) * step) + min); } start(position) { this.handleResize(null, () => { this.setState({ pressed: true }); const newKnobValue = this.positionToValue(position); const newValue = { ...this.props.value, [this.grabbedKnob]: newKnobValue }; this.props.onChange(newValue); }); } stepDecimals() { return (this.props.step.toString().split('.')[1] || []).length; } trimValue(value) { if (value < this.props.min) return this.props.min; if (value > this.props.max) return this.props.max; return round(value, this.stepDecimals()); } valueForInput(value) { const decimals = this.stepDecimals(); return decimals > 0 ? value.toFixed(decimals) : value.toString(); } renderSnaps() { if (!this.props.snaps) return undefined; return ( <div className={this.props.theme.snaps}> {range(0, (this.props.max - this.props.min) / this.props.step).map(i => <div key={`span-${i}`} className={this.props.theme.snap} />, )} </div> ); } renderInput() { if (!this.props.editable) return undefined; return ( <div style={{ display: 'flex' }}> <Input ref={(node) => { this.firstInputNode = node; }} className={this.props.theme.input} disabled={this.props.disabled} onFocus={() => this.handleInputFocus('first')} onChange={value => this.handleInputChange('first', value)} onBlur={event => this.handleInputBlur('first', event)} value={this.state.inputFocused.first ? this.state.inputValue.first : this.valueForInput(this.props.value.first)} /> <Input ref={(node) => { this.secondInputNode = node; }} className={this.props.theme.input} disabled={this.props.disabled} onFocus={() => this.handleInputFocus('second')} onChange={value => this.handleInputChange('second', value)} onBlur={event => this.handleInputBlur('second', event)} value={this.state.inputFocused.second ? this.state.inputValue.second : this.valueForInput(this.props.value.second)} /> </div> ); } renderPinnedValue = (value) => { const intValue = parseInt(value, 10); return this.props.mapValueOnPin(intValue); } render() { const { theme } = this.props; const knobStyles = { left: `${this.knobOffset(this.props.value.first)}%` }; const otherKnobStyles = { left: `${this.knobOffset(this.props.value.second)}%` }; const className = classnames(theme.range, { [theme.editable]: this.props.editable, [theme.disabled]: this.props.disabled, [theme.pinned]: this.props.pinned, [theme.pressed]: this.state.pressed, [theme.showValues]: this.props.showValues, [theme.ring]: this.props.value.first === this.props.value.second, }, this.props.className); return ( <div className={className} disabled={this.props.disabled} data-react-toolbox="range" onBlur={this.handleRangeBlur} onFocus={this.handleRangeFocus} style={this.props.style} tabIndex="0" > <div ref={(node) => { this.rangeNode = node; }} className={theme.container} onMouseDown={(event) => { event.preventDefault(); event.stopPropagation(); }} onTouchStart={this.handleTouchStart} > <div ref={(node) => { this.minKnobNode = node; }} className={theme.knob} onMouseDown={(event) => { this.handleMouseDown('first', event); }} onTouchStart={this.handleTouchStart} style={knobStyles} > <div className={theme.innerknob} data-value={this.renderPinnedValue(this.props.value.first)} /> </div> <div ref={(node) => { this.maxKnobNode = node; }} className={theme.knob} onMouseDown={(event) => { this.handleMouseDown('second', event); }} onTouchStart={this.handleTouchStart} style={otherKnobStyles} > <div className={theme.innerknob} data-value={this.renderPinnedValue(this.props.value.second)} /> </div> <div className={theme.progress}> <ProgressBar disabled={this.props.disabled} ref={(node) => { this.progressbarNode = node; }} className={theme.innerprogress} theme={this.props.theme} max={this.props.max} min={this.props.min} mode="determinate" value={Math.min(this.props.value.first, this.props.value.second)} buffer={Math.max(this.props.value.first, this.props.value.second)} /> {this.renderSnaps()} </div> </div> {this.renderInput()} </div> ); } } return Range; }; const Range = factory(InjectProgressBar, InjectInput); export default themr(SLIDER)(Range); export { factory as rangeFactory }; export { Range };
Libraries/Text/Text.web.js
sprightco/react-web
/** * Copyright (c) 2015-present, Alibaba Group Holding Limited. * All rights reserved. * * Copyright (c) 2015, Facebook, Inc. All rights reserved. * * @providesModule ReactText */ 'use strict'; import React from 'react'; import { Mixin as TouchableMixin } from 'ReactTouchable'; import { Mixin as LayoutMixin } from 'ReactLayoutMixin'; import { Mixin as NativeMethodsMixin } from 'NativeMethodsMixin'; /** * A React component for displaying text which supports nesting, * styling, and touch handling. In the following example, the nested title and * body text will inherit the `fontFamily` from `styles.baseText`, but the title * provides its own additional styles. The title and body will stack on top of * each other on account of the literal newlines: * * ``` * renderText: function() { * return ( * <Text style={styles.baseText}> * <Text style={styles.titleText} onPress={this.onPressTitle}> * {this.state.titleText + '\n\n'} * </Text> * <Text numberOfLines={5}> * {this.state.bodyText} * </Text> * </Text> * ); * }, * ... * var styles = StyleSheet.create({ * baseText: { * fontFamily: 'Cochin', * }, * titleText: { * fontSize: 20, * fontWeight: 'bold', * }, * }; * ``` */ var Text = React.createClass({ mixins: [LayoutMixin, TouchableMixin, NativeMethodsMixin], propTypes: { /** * Used to truncate the text with an elipsis after computing the text * layout, including line wrapping, such that the total number of lines * does not exceed this number. */ numberOfLines: React.PropTypes.number, /** * Invoked on mount and layout changes with * * `{nativeEvent: {layout: {x, y, width, height}}}` */ onLayout: React.PropTypes.func, /** * This function is called on press. */ onPress: React.PropTypes.func, /** * When true, no visual change is made when text is pressed down. By * default, a gray oval highlights the text on press down. * @platform ios */ suppressHighlighting: React.PropTypes.bool, /** * Used to locate this view in end-to-end tests. */ testID: React.PropTypes.string, /** * Specifies should fonts scale to respect Text Size accessibility setting on iOS. */ allowFontScaling: React.PropTypes.bool, }, getInitialState: function(): Object { return {...this.touchableGetInitialState(), ...{ isHighlighted: false, }}; }, getDefaultProps: function(): Object { return { allowFontScaling: true, }; }, // componentDidMount: function() { // console.log('mount') // }, // // componentDidUpdate: function() { // console.log('update') // }, onStartShouldSetResponder: function(): bool { var shouldSetFromProps = this.props.onStartShouldSetResponder && this.props.onStartShouldSetResponder(); return shouldSetFromProps || !!this.props.onPress; }, /* * Returns true to allow responder termination */ handleResponderTerminationRequest: function(): bool { // Allow touchable or props.onResponderTerminationRequest to deny // the request var allowTermination = this.touchableHandleResponderTerminationRequest(); if (allowTermination && this.props.onResponderTerminationRequest) { allowTermination = this.props.onResponderTerminationRequest(); } return allowTermination; }, handleResponderGrant: function(e: SyntheticEvent, dispatchID: string) { this.touchableHandleResponderGrant(e, dispatchID); this.props.onResponderGrant && this.props.onResponderGrant.apply(this, arguments); }, handleResponderMove: function(e: SyntheticEvent) { this.touchableHandleResponderMove(e); this.props.onResponderMove && this.props.onResponderMove.apply(this, arguments); }, handleResponderRelease: function(e: SyntheticEvent) { this.touchableHandleResponderRelease(e); this.props.onResponderRelease && this.props.onResponderRelease.apply(this, arguments); }, handleResponderTerminate: function(e: SyntheticEvent) { this.touchableHandleResponderTerminate(e); this.props.onResponderTerminate && this.props.onResponderTerminate.apply(this, arguments); }, touchableHandleActivePressIn: function() { if (this.props.suppressHighlighting || !this.props.onPress) { return; } this.setState({ isHighlighted: true, }); }, touchableHandleActivePressOut: function() { if (this.props.suppressHighlighting || !this.props.onPress) { return; } this.setState({ isHighlighted: false, }); }, touchableHandlePress: function() { this.props.onPress && this.props.onPress(); }, touchableGetPressRectOffset: function(): RectOffset { return PRESS_RECT_OFFSET; }, getChildContext: function(): Object { return {isInAParentText: true}; }, contextTypes: { isInAParentText: React.PropTypes.bool }, childContextTypes: { isInAParentText: React.PropTypes.bool }, render: function() { var props = {...this.props}; // Text is accessible by default if (props.accessible !== false) { props.accessible = true; } props.isHighlighted = this.state.isHighlighted; props.onStartShouldSetResponder = this.onStartShouldSetResponder; props.onResponderTerminationRequest = this.handleResponderTerminationRequest; props.onResponderGrant = this.handleResponderGrant; props.onResponderMove = this.handleResponderMove; props.onResponderRelease = this.handleResponderRelease; props.onResponderTerminate = this.handleResponderTerminate; var { numberOfLines, style } = props; style = {...props.style}; if (typeof style.lineHeight == 'number') { style.lineHeight += 'px'; } // Default lineHeight is 1.2 x fontSize var lineHeight = style.lineHeight || (style.fontSize || 16) * 1.2; // FIXME: not sure 16px is the default line height if (typeof lineHeight == 'number') { lineHeight += 'px'; } style.lineHeight = lineHeight; if (style.textDecorationLine) { style.textDecoration = style.textDecorationLine; } if (!props.children) { // TODO set a linebreak } return ( <span {...props} style={{ ...{ display: this.context.isInAParentText ? 'inline' : 'inline-block', margin: 0, padding: 0, wordWrap: 'break-word', fontFamily: 'Helvetica Neue, STHeiTi, sans-serif' }, ...style, ...(numberOfLines && { overflow: 'hidden', textOverflow: 'ellipsis', wordWrap: 'break-word', display: '-webkit-box', WebkitLineClamp: numberOfLines, WebkitBoxOrient: 'vertical', maxHeight: parseFloat(lineHeight) * numberOfLines, }) }} /> ); }, }); type RectOffset = { top: number; left: number; right: number; bottom: number; } var PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; module.exports = Text;
fields/types/select/SelectFilter.js
tanbo800/keystone
import React from 'react'; import { Checkbox, FormField, SegmentedControl } from 'elemental'; import PopoutList from '../../../admin/src/components/PopoutList'; const TOGGLE_OPTIONS = [ { label: 'Matches', value: false }, { label: 'Does NOT Match', value: true } ]; var SelectFilter = React.createClass({ getInitialState () { return { inverted: TOGGLE_OPTIONS[0].value, selectedOptions: {}, allSelected: false, indeterminate: false }; }, toggleAllOptions () { this.props.field.ops.map(opt => this.toggleOption(opt.value, !this.state.allSelected)); }, toggleOption (option, value) { let newOptions = this.state.selectedOptions; if (value) { newOptions[option] = value; } else { delete newOptions[option]; } let optionCount = Object.keys(newOptions).length; this.setState({ selectedOptions: newOptions, indeterminate: !!optionCount && optionCount !== this.props.field.ops.length, allSelected: optionCount === this.props.field.ops.length }); }, renderToggle () { return ( <FormField> <SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.state.inverted} onChange={() => this.setState({ inverted: !this.state.inverted })} /> </FormField> ); }, renderOptions () { let options = this.props.field.ops.map((opt) => { let optionKey = opt.value; let optionValue = this.state.selectedOptions[optionKey]; return ( <PopoutList.Item key={'item_' + opt.value} icon={optionValue ? 'check' : 'dash'} isSelected={optionValue} label={opt.label} onClick={this.toggleOption.bind(this, optionKey, !optionValue)} /> ); }); return options; }, render () { return ( <div> {this.renderToggle()} <FormField style={{ borderBottom: '1px dashed rgba(0,0,0,0.1)', paddingBottom: '1em' }}> <Checkbox focusOnMount onChange={this.toggleAllOptions} label="Select all options" value={true} checked={this.state.allSelected} indeterminate={this.state.indeterminate} /> </FormField> {this.renderOptions()} </div> ); } }); module.exports = SelectFilter;
app/components/About.js
YuHuaiChen/meteor-react-redux-starter-kit
import React from 'react' import { Link } from 'react-router' const About = () => { return ( <div> <h2> About </h2> <Link to="/">Back to Home</Link> </div> ) } export default About
src/components/PresetCard/PresetCard.js
jeffdowdle/l-systems
import React from 'react'; import PropTypes from 'prop-types'; import './preset-card.scss'; const PresetCard = ({ preset, onLoadClicked, }) => ( <div styleName="preset-card"> <span styleName="title">{preset.title}</span> <button styleName="load-preset" onClick={onLoadClicked}>Load</button> </div> ); export default PresetCard;
src/containers/Widgets/Widgets.js
delwiv/saphir
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import * as widgetActions from 'redux/modules/widgets'; import WidgetForm from 'components/WidgetForm/WidgetForm'; import { asyncConnect } from 'redux-connect'; const { isLoaded, load: loadWidgets } = widgetActions; @asyncConnect([{ deferred: true, promise: ({ store: { dispatch, getState } }) => { if (!isLoaded(getState())) { return dispatch(loadWidgets()); } } }]) @connect( state => ({ widgets: state.widgets.data, editing: state.widgets.editing, error: state.widgets.error, loading: state.widgets.loading }), { ...widgetActions }) export default class Widgets extends Component { static propTypes = { widgets: PropTypes.array, error: PropTypes.string, loading: PropTypes.bool, editing: PropTypes.object.isRequired, load: PropTypes.func.isRequired, editStart: PropTypes.func.isRequired }; static defaultProps = { widgets: null, error: null, loading: false } render() { const handleEdit = widget => { const { editStart } = this.props; return () => editStart(String(widget.id)); }; const { widgets, error, editing, loading, load } = this.props; const styles = require('./Widgets.scss'); return ( <div className={`${styles.widgets} container`}> <h1> Widgets <button className={`${styles.refreshBtn} btn btn-success`} onClick={load}> <i className={`fa fa-refresh ${loading ? ' fa-spin' : ''}`} />{' '}Reload Widgets </button> </h1> <Helmet title="Widgets" /> <p> If you hit refresh on your browser, the data loading will take place on the server before the page is returned. If you navigated here from another page, the data was fetched from the client after the route transition. This uses the decorator method <code>@asyncConnect</code> with the <code>deferred: true</code> flag. To block a route transition until some data is loaded, remove the <code>deffered: true</code> flag. To always render before loading data, even on the server, use <code>componentDidMount</code>. </p> <p> This widgets are stored in your session, so feel free to edit it and refresh. </p> {error && <div className="alert alert-danger" role="alert"> <span className="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>{' '}{error} </div>} {widgets && widgets.length && <table className="table table-striped"> <thead> <tr> <th className={styles.idCol}>ID</th> <th className={styles.colorCol}>Color</th> <th className={styles.sprocketsCol}>Sprockets</th> <th className={styles.ownerCol}>Owner</th> <th className={styles.buttonCol}></th> </tr> </thead> <tbody> { /* eslint-disable react/jsx-indent */ widgets.map(widget => (editing[widget.id] ? <WidgetForm form={String(widget.id)} key={String(widget.id)} initialValues={widget} /> : <tr key={widget.id}> <td className={styles.idCol}>{widget.id}</td> <td className={styles.colorCol}>{widget.color}</td> <td className={styles.sprocketsCol}>{widget.sprocketCount}</td> <td className={styles.ownerCol}>{widget.owner}</td> <td className={styles.buttonCol}> <button className="btn btn-primary" onClick={handleEdit(widget)}> <i className="fa fa-pencil" /> Edit </button> </td> </tr>) ) /* eslint-enable react/jsx-indent */ } </tbody> </table>} </div> ); } }
app/javascript/mastodon/components/avatar_overlay.js
kagucho/mastodon
import React from 'react'; import PropTypes from 'prop-types'; export default class AvatarOverlay extends React.PureComponent { static propTypes = { staticSrc: PropTypes.string.isRequired, overlaySrc: PropTypes.string.isRequired, }; render() { const { staticSrc, overlaySrc } = this.props; const baseStyle = { backgroundImage: `url(${staticSrc})`, }; const overlayStyle = { backgroundImage: `url(${overlaySrc})`, }; return ( <div className='account__avatar-overlay'> <div className='account__avatar-overlay-base' style={baseStyle} /> <div className='account__avatar-overlay-overlay' style={overlayStyle} /> </div> ); } }
src/app/components/Court.js
lubosz/tetris.js
/** * Created by bmonkey on 8/31/15. */ import React from 'react'; import {randomPiece, nx, ny, nu, mode, DIR, setBlock, eachblock} from '../logic'; import {drawBlock, drawPiece} from '../renderer'; import {sound} from '../utils'; class Court extends React.Component { constructor(props) { super(props); this.dx = 0; this.dy = 0; this.speed = { start: 0.6, decrement: 0.005, min: 0.1 }; // how long before piece drops by 1 row (seconds) this.updateStep(0); } componentDidMount() { this.canvas = this.refs.court.getDOMNode(); this.ctx = this.canvas.getContext('2d'); } updateStep (rows) { this.step = Math.max(this.speed.min, this.speed.start - (this.speed.decrement * rows)); } checkLose() { if (this.occupied(this.current.type, this.current.x, this.current.y, this.current.dir)) { this.lose(); sound("lose"); } } //----------------------------------------------------- // check if a piece can fit into a position in the grid //----------------------------------------------------- occupied(type, x, y, dir) { var result = false; var actualBlocks = this.blocks; eachblock(type, x, y, dir, function (x, y) { if ((x < 0) || (x >= nx) || (y >= ny) || (actualBlocks && actualBlocks[x] ? actualBlocks[x][y] : null)) { result = true; } }); return result; } puyuoccupied(type, x, y, dir) { var result = null; var actualBlocks = this.blocks; eachblock(type, x, y + 1, dir, function (x, y) { if (!((x < 0) || (x >= nx) || (y >= ny) || (actualBlocks && actualBlocks[x] ? actualBlocks[x][y] : null))) { result = { type: type = { size: 1, blocks: [0x8000, 0x8000, 0x8000, 0x8000], color: "yellow" }, dir: DIR.UP, x: x, y: y - 1 }; } }); return result; } unoccupied(type, x, y, dir) { return !this.occupied(type, x, y, dir); } move(dir) { var x = this.current.x, y = this.current.y; switch (dir) { case DIR.RIGHT: x = x + 1; break; case DIR.LEFT: x = x - 1; break; case DIR.DOWN: y = y + 1; break; } if (this.unoccupied(this.current.type, x, y, this.current.dir)) { this.current.x = x; this.current.y = y; this.draw(); return true; } else { return false; } } // offset the piece at the borders for rotation horizontalFitOffset(type, x, y, dir) { let offset = 0; let step = 0; let wouldFit = true; // try to offset at screen border if (this.current.x <= 0) step = 1; else if (this.current.x >= 7) step = -1; while (this.occupied(type, x + offset, y, dir)) { //console.log(type.name, "would not fit", x+offset, y); offset += step; // max offset is 2, required for I, break if not at border if (Math.abs(offset) > 2 || step == 0) { wouldFit = false; break; } } //console.log(type.name, "seems that would fit", wouldFit, x+offset, y); return [wouldFit, offset]; } rotate(dir) { let newdir = this.current.dir; if (dir == DIR.TURNRIGHT) newdir++; else if (dir == DIR.TURNLEFT) newdir--; newdir = (newdir + 4) % 4; let offset = this.horizontalFitOffset(this.current.type, this.current.x, this.current.y, newdir); if (offset[0]) { this.current.x += offset[1]; this.current.dir = newdir; this.draw(); sound("rotate"); } } instantDrop() { var flying = this.move(DIR.DOWN); while (flying) { flying = this.move(DIR.DOWN); } this.addScore(10); this.dropPiece(); this.removeLines(); this.dropCb(); this.checkLose(); } puyuGravityDrop() { var flying = this.move(DIR.DOWN); var last = timestamp(); var now = last; while (flying) { now = timestamp(); var deltatime = now - last; if (deltatime > 100) { flying = this.move(DIR.DOWN); } } this.addScore(10); this.dropPiece(); this.removeLines(); this.dropCb(); this.checkLose(); } drop() { if (!this.move(DIR.DOWN)) { this.addScore(10); this.dropPiece(); this.removeLines(); this.dropCb(); this.checkLose(); } } dropPiece() { var type = this.current.type; var playerBlocks = this.blocks; var inval = false; eachblock(this.current.type, this.current.x, this.current.y, this.current.dir, function (x, y) { inval = true; playerBlocks = setBlock(x, y, playerBlocks, type); }); this.blocks = playerBlocks; sound("drop"); if (inval) this.draw(); if (mode == "puyu") { //check if a bean is still falling var fallingBean = this.puyuoccupied(this.current.type, this.current.x, this.current.y, this.current.dir); if (fallingBean != undefined) { this.current = fallingBean; this.puyuGravityDrop(); } } } removeLines() { var x, y, complete, n = 0; for (y = ny; y > 0; --y) { complete = true; for (x = 0; x < nx; ++x) { if (!(this.blocks && this.blocks[x] ? this.blocks[x][y] : null)) { complete = false; } } if (complete) { this.removeLine(y); y = y + 1; // recheck same line n++; } } if (n > 0) { this.addRows(n); this.addScore(100 * Math.pow(2, n - 1)); // 1: 100, 2: 200, 3: 400, 4: 800 switch (n) { case 4: sound("tetris"); break; default: sound("line"); break; } //send lines to an opponent player if 2, 3 or 4 lines where removed if (n == 4) { //tetris: send all 4 lines this.addOpponentLines(4); } if (n == 2 || n == 3) { //send n-1 lines this.addOpponentLines(n - 1); } } //sound("line"); } removeLine(n) { var x, y; for (y = n; y >= 0; --y) { for (x = 0; x < nx; ++x) { setBlock(x, y, this.blocks, (y == 0) ? null : (this.blocks && this.blocks[x] ? this.blocks[x][y - 1] : null)); } } } receiveLines(n) { var gap = Math.floor(Math.random() * nx); //do n times: for (var i = 0; i < n; i++) { //shift blocks 1 to top for (var y = 0; y < ny + 1; y++) { for (x = 0; x < nx; ++x) { setBlock(x, y, this.blocks, (y == 0) ? null : (this.blocks && this.blocks[x] ? this.blocks[x][y + 1] : null)); } } } //then add received rows for (var y = ny - n; y < ny; y++) { for (var x = 0; x < nx; ++x) { if (x != gap) { setBlock(x, y, this.blocks, 'cyan'); } } } } draw() { if (!this.current) return; this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.ctx.strokeStyle = 'white'; drawPiece(this.ctx, this.current.type, this.current.x, this.current.y, this.dx, this.dy, this.current.dir); //ghost this.ctx.globalAlpha = 0.4; let y = 0; while (!this.occupied(this.current.type, this.current.x, y+1, this.current.dir)) { y++; } drawPiece(this.ctx, this.current.type, this.current.x, y, this.dx, this.dy, this.current.dir); this.ctx.globalAlpha = 1.0; let x, block; for (y = 0; y < ny; y++) { for (x = 0; x < nx; x++) { if (block = (this.blocks && this.blocks[x] ? this.blocks[x][y] : null)) { drawBlock(this.ctx, x, y, this.dx, this.dy, block.color); } } } this.ctx.strokeRect(0, 0, nx * this.dx - 1, ny * this.dy - 1); // court boundary } clearBlocks() { this.blocks = []; if (this.current) this.draw(); } setCurrentPiece(piece = randomPiece()) { this.current = piece; this.draw(); } resize() { if (!this.canvas) return; this.canvas.width = this.canvas.clientWidth; // set canvas logical size equal to its physical size this.canvas.height = this.canvas.clientHeight; // (ditto) this.dx = this.canvas.width / nx; // pixel size of a single tetris block this.dy = this.canvas.height / ny; // (ditto) if (this.current) this.draw(); } reset() { this.dt = 0; this.clearBlocks(); this.setCurrentPiece(); } update(idt) { this.dt = this.dt + idt; if (this.dt > this.step) { this.dt = this.dt - this.step; this.drop(); } } render() { let style = { display: 'inline-block', background: '#01093a', border: '2px solid #333', opacity: 0.8, width: '45vh', height: '90vh', marginTop: '5vh' }; return ( <canvas style={style} ref="court" /> ); } } export default Court;
src/components/ListPagination.js
tilgram/tilgram-frontend
import React from 'react'; import agent from '../agent'; import { connect } from 'react-redux'; import { SET_PAGE } from '../constants/actionTypes'; const mapDispatchToProps = dispatch => ({ onSetPage: (page, payload) => dispatch({ type: SET_PAGE, page, payload }) }); const ListPagination = props => { if (props.articlesCount <= 10) { return null; } const range = []; for (let i = 0; i < Math.ceil(props.articlesCount / 10); ++i) { range.push(i); } const setPage = page => { if(props.pager) { props.onSetPage(page, props.pager(page)); }else { props.onSetPage(page, agent.Articles.all(page)) } }; return ( <nav> <ul className="pagination"> { range.map(v => { const isCurrent = v === props.currentPage; const onClick = ev => { ev.preventDefault(); setPage(v); }; return ( <li className={ isCurrent ? 'page-item active' : 'page-item' } onClick={onClick} key={v.toString()}> <a className="page-link" href="">{v + 1}</a> </li> ); }) } </ul> </nav> ); }; export default connect(() => ({}), mapDispatchToProps)(ListPagination);
app/components/ShareLine.js
RoadToGlobal/ClientDistro
import React from 'react'; import GeneralInput from '../components/GeneralInput'; const shareInput = { fontFamily: 'arial', height: '2em', width: '100%', borderRadius: '2px', border: 'none', }; class Button extends React.Component { render() { return ( <div style={{width: '80%'}}> <GeneralInput inputStyle={shareInput} inputValue={' http://groupapp.com/group/test'} /> </div> ); } } export default Button;
src/routes.js
henryhuang/appshowpub
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright ยฉ 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Router from 'react-routing/src/Router'; import fetch from './core/fetch'; import App from './components/App'; import ContentPage from './components/ContentPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const routes = [ require('./routes/home2'), require('./routes/home'), require('./routes/contact'), require('./routes/login'), require('./routes/register'), ]; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); routes.forEach(route => { on(route.path, route.action); }); on('*', async (state) => { const query = `/graphql?query={content(path:"${state.path}"){path,title,content,component}}`; const response = await fetch(query); const { data } = await response.json(); return data && data.content && <ContentPage {...data.content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
src/components/Notifs/Notifs.js
prakash-u/react-redux
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; @connect((state, props) => ({ notifs: state.notifs[props.namespace] || [] })) export default class Notifs extends Component { static propTypes = { notifs: PropTypes.arrayOf(PropTypes.object).isRequired, NotifComponent: PropTypes.func.isRequired, className: PropTypes.string.isRequired }; render() { const { notifs, className, NotifComponent } = this.props; return ( <div className={`notif-container ${className}`}> {notifs.map(notif => <NotifComponent key={notif.id} message={notif.message} kind={notif.kind} />)} </div> ); } }
app/components/HeaderOld/style.js
ArtemDervoed/DiplomWork
import React from 'react'; import styled from 'styled-components'; export const WrapperHeader = styled.header` transition: .5s; display: flex; align-items: center; justify-content: space-between; text-transform: uppercase; position: statik; width: 100%; max-width: 1903px; min-width: 1024px; background-color: #fafafa; `; export const HeaderLogo = styled.span` padding-left: 20px; font-size: 36px; & > a { font-family: LatoBold; color: rgba(0,0,0,0.35); text-decoration: none; } `; export const HeaderButton = styled.span` font-family: LatoBold; font-size: 16px; margin-right: 20px; & > a { text-decoration: none; color: rgba(0,0,0,0.35); transition: .5s; } & > a:hover { transition: .5s; color: red; } `;
app/components/PageView.js
pbillerot/reacteur
'use strict'; import React from 'react' import ReactDOM from 'react-dom' import 'whatwg-fetch' import { Link } from 'react-router' // W3 const { Alerter, Button, Card, Content, Footer, Header, IconButton , Menubar, Nav, Navbar, NavGroup, Sidebar, Window } = require('./w3.jsx') import ContainerSidebar from './ContainerSidebar'; import ContainerContent from './ContainerContent'; import ContainerView from './ContainerView'; import { Dico } from '../config/Dico' import { Tools } from '../config/Tools' import { ToolsUI } from '../config/ToolsUI' export default class PageView extends React.Component { constructor(props) { super(props); this.state = { is_data_recepted: false, w3_sidebar_open: false, app: this.props.params.app, table: this.props.params.table, view: this.props.params.view, is_error: false, error: { code: '', message: '' }, ctx: { elements: {}, session: {}, } } this.handlePage = this.handlePage.bind(this); } handlePage(obj) { this.setState(obj) } componentWillReceiveProps(nextProps) { //console.log('PageView.componentWillReceiveProps', nextProps) if (nextProps.params) { this.setState({ app: nextProps.params.app, table: nextProps.params.table, view: nextProps.params.view, }) } else { this.setState({ app: nextProps.app, table: nextProps.table, view: nextProps.view, }) } } componentDidMount() { //console.log('PageView.componentDidMount...') this.state.is_data_recepted = false fetch('/api/session', { credentials: 'same-origin' }) .then(response => { response.json().then(json => { //console.log('PageView SESSION: ', json) this.state.is_data_recepted = true // Recup des donnรฉes de la session this.state.ctx.session = json.session // load du dico de l'application let dico_app = require('../config/dico/' + this.state.app + '/' + this.state.app + '.js') Dico.apps[this.state.app] = dico_app this.setState({}) ToolsUI.showAlert(this.state.ctx.session.alerts) }) }) } render() { //console.log("PageView.render", this.state, Dico.apps[this.state.app]) if (Dico.apps[this.state.app] && Dico.apps[this.state.app].tables[this.state.table] && Dico.apps[this.state.app].tables[this.state.table].views[this.state.view] && this.state.is_data_recepted) { let app = this.state.app let table = this.state.table let view = this.state.view return ( <div> <ContainerSidebar page={this} {...this.state} {...this.props} /> <ContainerContent> <div id="myTop" className="w3-top w3-container w3-padding-16 w3-theme-l1 w3-large w3-show-inline-block"> <i className="fa fa-bars w3-opennav w3-hide-large w3-xlarge w3-margin-right" onClick={(e) => this.handlePage({ w3_sidebar_open: true })} ></i> <span id="myIntro">{Dico.apps[app].tables[table].views[view].title}</span> </div> {this.state.is_error && <div className="w3-margin w3-panel w3-pale-red w3-leftbar w3-border-red"> <p>{this.state.error.code} {this.state.error.message}</p> </div> } {!this.state.is_error && <Card> <ContainerView {...this.props} ctx={this.state.ctx} app={app} table={table} view={view} /> </Card> } <Footer> <p>{Dico.application.copyright}</p> </Footer> </ContainerContent> <Alerter /> </div> ) } else { return ( <div className="w3-margin w3-panel w3-leftbar "> <p>Veuillez patienter...</p> </div> ) } } }
docs/app/Examples/modules/Dropdown/States/DropdownExampleError.js
vageeshb/Semantic-UI-React
import React from 'react' import { Dropdown } from 'semantic-ui-react' const DropdownExampleError = () => ( <Dropdown text='Dropdown' error> <Dropdown.Menu> <Dropdown.Item>Choice 1</Dropdown.Item> <Dropdown.Item>Choice 2</Dropdown.Item> </Dropdown.Menu> </Dropdown> ) export default DropdownExampleError
react/features/base/participants/components/ParticipantView.native.js
KalinduDN/kalindudn.github.io
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { JitsiParticipantConnectionStatus } from '../../lib-jitsi-meet'; import { MEDIA_TYPE, shouldRenderVideoTrack, VideoTrack } from '../../media'; import { Container } from '../../react'; import { getTrackByMediaTypeAndParticipant } from '../../tracks'; import Avatar from './Avatar'; import { getAvatarURL, getParticipantById } from '../functions'; import styles from './styles'; /** * Implements a React Component which depicts a specific participant's avatar * and video. * * @extends Component */ class ParticipantView extends Component { /** * ParticipantView component's property types. * * @static */ static propTypes = { /** * The indicator which determines whether conferencing is in audio-only * mode. * * @private */ _audioOnly: React.PropTypes.bool, /** * The source (e.g. URI, URL) of the avatar image of the participant * with {@link #participantId}. * * @private */ _avatar: React.PropTypes.string, /** * The connection status of the participant. Her video will only be * rendered if the connection status is 'active'; otherwise, the avatar * will be rendered. If undefined, 'active' is presumed. * * @private */ _connectionStatus: React.PropTypes.string, /** * The video Track of the participant with {@link #participantId}. */ _videoTrack: React.PropTypes.object, /** * The style, if any, of the avatar in addition to the default style. */ avatarStyle: React.PropTypes.object, /** * The ID of the participant (to be) depicted by ParticipantView. * * @public */ participantId: React.PropTypes.string, /** * True if the avatar of the depicted participant is to be shown should * the avatar be available and the video of the participant is not to be * shown; otherwise, false. If undefined, defaults to true. */ showAvatar: React.PropTypes.bool, /** * True if the video of the depicted participant is to be shown should * the video be available. If undefined, defaults to true. */ showVideo: React.PropTypes.bool, /** * The style, if any, to apply to ParticipantView in addition to its * default style. */ style: React.PropTypes.object, /** * The z-order of the Video of ParticipantView in the stacking space of * all Videos. For more details, refer to the zOrder property of the * Video class for React Native. */ zOrder: React.PropTypes.number }; /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { const { _avatar: avatar, _connectionStatus: connectionStatus, _videoTrack: videoTrack } = this.props; // Is the video to be rendered? // FIXME It's currently impossible to have true as the value of // waitForVideoStarted because videoTrack's state videoStarted will be // updated only after videoTrack is rendered. const waitForVideoStarted = false; const renderVideo = !this.props._audioOnly && (connectionStatus === JitsiParticipantConnectionStatus.ACTIVE) && shouldRenderVideoTrack(videoTrack, waitForVideoStarted); // Is the avatar to be rendered? const renderAvatar = Boolean(!renderVideo && avatar); return ( <Container style = {{ ...styles.participantView, ...this.props.style }}> { renderVideo // The consumer of this ParticipantView is allowed to forbid // showing the video if the private logic of this // ParticipantView determines that the video could be // rendered. && _toBoolean(this.props.showVideo, true) && <VideoTrack videoTrack = { videoTrack } waitForVideoStarted = { waitForVideoStarted } zOrder = { this.props.zOrder } /> } { renderAvatar // The consumer of this ParticipantView is allowed to forbid // showing the avatar if the private logic of this // ParticipantView determines that the avatar could be // rendered. && _toBoolean(this.props.showAvatar, true) && <Avatar style = { this.props.avatarStyle } uri = { avatar } /> } </Container> ); } } /** * Converts the specified value to a boolean value. If the specified value is * undefined, returns the boolean value of undefinedValue. * * @param {any} value - The value to convert to a boolean value should it not be * undefined. * @param {any} undefinedValue - The value to convert to a boolean value should * the specified value be undefined. * @private * @returns {boolean} */ function _toBoolean(value, undefinedValue) { return Boolean(typeof value === 'undefined' ? undefinedValue : value); } /** * Maps (parts of) the Redux state to the associated ParticipantView's props. * * @param {Object} state - The Redux state. * @param {Object} ownProps - The React Component props passed to the associated * (instance of) ParticipantView. * @private * @returns {{ * _audioOnly: boolean, * _avatar: string, * _connectionStatus: string, * _videoTrack: Track * }} */ function _mapStateToProps(state, ownProps) { const { participantId } = ownProps; const participant = getParticipantById( state['features/base/participants'], participantId); let avatar; let connectionStatus; if (participant) { avatar = getAvatarURL(participant); connectionStatus = participant.connectionStatus; } return { _audioOnly: state['features/base/conference'].audioOnly, _avatar: avatar, _connectionStatus: connectionStatus || JitsiParticipantConnectionStatus.ACTIVE, _videoTrack: getTrackByMediaTypeAndParticipant( state['features/base/tracks'], MEDIA_TYPE.VIDEO, participantId) }; } export default connect(_mapStateToProps)(ParticipantView);
web/src/components/Calendar/components/Agenda/index.js
AcrylicInc/totalblu
import PropTypes from 'prop-types'; import React from 'react'; import classes from 'dom-helpers/class'; import getWidth from 'dom-helpers/query/width'; import scrollbarSize from 'dom-helpers/util/scrollbarSize'; import localizer from 'components/Calendar/localizer' import message from 'components/Calendar/utils/messages'; import dates from 'components/Calendar/utils/dates'; import { navigate } from 'components/Calendar/utils/constants'; import { accessor as get } from 'components/Calendar/utils/accessors'; import { accessor, dateFormat, dateRangeFormat } from 'components/Calendar/utils/propTypes'; import { inRange } from 'components/Calendar/utils/eventLevels'; class Agenda extends React.Component { static propTypes = { events: PropTypes.array, date: PropTypes.instanceOf(Date), length: PropTypes.number.isRequired, titleAccessor: accessor.isRequired, allDayAccessor: accessor.isRequired, startAccessor: accessor.isRequired, endAccessor: accessor.isRequired, agendaDateFormat: dateFormat, agendaTimeFormat: dateFormat, agendaTimeRangeFormat: dateRangeFormat, culture: PropTypes.string, components: PropTypes.object.isRequired, messages: PropTypes.shape({ date: PropTypes.string, time: PropTypes.string, }) }; static defaultProps = { length: 30 }; componentDidMount() { this._adjustHeader() } componentDidUpdate() { this._adjustHeader() } render() { let { length, date, events, startAccessor } = this.props; let messages = message(this.props.messages); let end = dates.add(date, length, 'day') let range = dates.range(date, end, 'day'); events = events.filter(event => inRange(event, date, end, this.props) ) events.sort((a, b) => +get(a, startAccessor) - +get(b, startAccessor)) return ( <div className='rbc-agenda-view'> <table ref='header'> <thead> <tr> <th className='rbc-header' ref='dateCol'> {messages.date} </th> <th className='rbc-header' ref='timeCol'> {messages.time} </th> <th className='rbc-header'> {messages.event} </th> </tr> </thead> </table> <div className='rbc-agenda-content' ref='content'> <table> <tbody ref='tbody'> { range.map((day, idx) => this.renderDay(day, events, idx)) } </tbody> </table> </div> </div> ); } renderDay = (day, events, dayKey) => { let { culture, components , titleAccessor, agendaDateFormat } = this.props; let EventComponent = components.event; let DateComponent = components.date; events = events.filter(e => inRange(e, day, day, this.props)) return events.map((event, idx) => { let dateLabel = idx === 0 && localizer.format(day, agendaDateFormat, culture) let first = idx === 0 ? ( <td rowSpan={events.length} className='rbc-agenda-date-cell'> { DateComponent ? <DateComponent day={day} label={dateLabel}/> : dateLabel } </td> ) : false let title = get(event, titleAccessor) return ( <tr key={dayKey + '_' + idx}> {first} <td className='rbc-agenda-time-cell'> { this.timeRangeLabel(day, event) } </td> <td className='rbc-agenda-event-cell'> { EventComponent ? <EventComponent event={event} title={title}/> : title } </td> </tr> ) }, []) }; timeRangeLabel = (day, event) => { let { endAccessor, startAccessor, allDayAccessor , culture, messages, components } = this.props; let labelClass = '' , TimeComponent = components.time , label = message(messages).allDay let start = get(event, startAccessor) let end = get(event, endAccessor) if (!get(event, allDayAccessor)) { if (dates.eq(start, end, 'day')){ label = localizer.format({ start, end }, this.props.agendaTimeRangeFormat, culture) } else if (dates.eq(day, start, 'day')){ label = localizer.format(start, this.props.agendaTimeFormat, culture) } else if (dates.eq(day, end, 'day')){ label = localizer.format(end, this.props.agendaTimeFormat, culture) } } if (dates.gt(day, start, 'day')) labelClass = 'rbc-continues-prior' if (dates.lt(day, end, 'day')) labelClass += ' rbc-continues-after' return ( <span className={labelClass.trim()}> { TimeComponent ? <TimeComponent event={event} label={label}/> : label } </span> ) }; _adjustHeader = () => { let header = this.refs.header; let firstRow = this.refs.tbody.firstChild if (!firstRow) return let isOverflowing = this.refs.content.scrollHeight > this.refs.content.clientHeight; let widths = this._widths || [] this._widths = [ getWidth(firstRow.children[0]), getWidth(firstRow.children[1]) ] if (widths[0] !== this._widths[0] || widths[1] !== this._widths[1]) { this.refs.dateCol.style.width = this._widths[0] + 'px' this.refs.timeCol.style.width = this._widths[1] + 'px'; } if (isOverflowing) { classes.addClass(header, 'rbc-header-overflowing') header.style.marginRight = scrollbarSize() + 'px' } else { classes.removeClass(header, 'rbc-header-overflowing') } }; } Agenda.navigate = (date, action)=>{ switch (action){ case navigate.PREVIOUS: return dates.add(date, -1, 'day'); case navigate.NEXT: return dates.add(date, 1, 'day') default: return date; } } Agenda.range = (start, { length = Agenda.defaultProps.length }) => { let end = dates.add(start, length, 'day') return { start, end } } export default Agenda
src/components/Tile.js
longyarnz/WelFurnish-E-Commerce
import React from 'react'; export default function Tile(props) { const { src, title, desc, reNumber } = props; let { price } = props; price = reNumber(price); return ( <figure onClick={props.onClick}> <img className="" src={src} alt="" /> <figcaption> {title} <br /> <div>{desc}</div> <span>โ‚ฆ {price}</span> <span className={props.status ? "show-tile" : "no-display"}>ADDED</span> </figcaption> </figure> ) }
src/SyncContacts.js
sumurthy/xlcontacts
import React, { Component } from 'react'; export class SyncContacts extends Component { render() { return ( <div> <h2> Sync MyContacts </h2> </div> ); } } export default SyncContacts
src/components/CryptoDropdown.js
davidoevans/react-redux-dapp
import React from 'react' const CryptoDropdown = ({ label, cryptos, action }) => ( <div className="form-group form-group-sm"> <label className="col-sm-2 control-label">{label}</label> <div className="col-sm-10"> <select className="form-control" onChange={ (e) => action(e.target.value)}> <option value="" selected disabled>Select Account</option> {cryptos.map(crypto => <option key={crypto.id}>{crypto.symbol}</option> ) } </select> </div> </div> ) export default CryptoDropdown
cms/react-static/src/containers/Blog.js
fishjar/gabe-study-notes
import React from 'react' import { withRouteData, Link } from 'react-static' // export default withRouteData(({ posts }) => ( <div> <h1>It's blog time.</h1> <br /> All Posts: <ul> {posts.map(post => ( <li key={post.id}> <Link to={`/blog/post/${post.id}/`}>{post.title}</Link> </li> ))} </ul> </div> ))
components/partials/view.js
wi2/isomorphic-sails-react-example
"use strict"; import React from 'react' import {ReactItem} from 'sails-react-store' export class View extends ReactItem { render() { let item = this.state.item; return ( <div> <h1 className="doc-title">{item.title}</h1> <p className="doc-content">{item.content||''}</p> </div> ) } }
example/pages/icons/index.js
woshisbb43/coinMessageWechat
import React from 'react'; import {Icon} from '../../../build/packages'; import Page from '../../component/page'; import './icons.less'; const IconBox = (props) => ( <div className="icon-box"> {props.icon} <div className="icon-box__ctn"> <h3 className="icon-box__title">{props.title}</h3> <p className="icon-box__desc">{props.desc}</p> </div> </div> ) export default class IconDemo extends React.Component { render() { return ( <Page className="icons" title="Icons" subTitle="ๅ›พๆ ‡"spacing> <IconBox icon={<Icon size="large" value="success" />} title="Well done!" desc="You successfully read this important alert message." /> <IconBox icon={<Icon size="large" value="info" />} title="Heads up!" desc="This alert needs your attention, but it's not super important." /> <IconBox icon={<Icon size="large" value="warn" primary/>} title="Attention!" desc="This is your default warning with the primary property" /> <IconBox icon={<Icon size="large" value="warn"/>} title="Attention!" desc="This is your strong warning without the primary property" /> <IconBox icon={<Icon size="large" value="waiting"/>} title="Hold on!" desc="We are working hard to bring the best ui experience" /> <Icon size="large" value="safe-success" /> <Icon size="large" value="safe-warn" /> <div className="icon_sp_area"> <Icon value="success" /> <Icon value="success-circle" /> <Icon value="success-no-circle" /> <Icon value="info" /> <Icon value="waiting" /> <Icon value="waiting-circle" /> <Icon value="circle" /> <Icon value="warn" /> <Icon value="download" /> <Icon value="info-circle" /> <Icon value="cancel" /> <Icon value="clear" /> <Icon value="search" /> </div> </Page> ); } };
packages/bonde-admin-canary/src/scenes/Auth/scenes/ResetPassword/InvalidToken.js
ourcities/rebu-client
import React from 'react' import { Trans } from 'react-i18next' import { Flexbox2 as Flexbox, Title } from 'bonde-styleguide' import Link, { ButtonLink } from 'components/Link' export default ({ t }) => ( <Flexbox vertical> <Title.H2 margin={{ bottom: 20 }}>{t('resetPassword.invalidToken.title')}</Title.H2> <Title.H4 margin={{ bottom: 25 }}>{t('resetPassword.invalidToken.subtitle')}</Title.H4> <Title.H4 margin={{ bottom: 25 }}> <Trans i18nKey='resetPassword.invalidToken.resendToken'> <Link to='/auth/forget-password'>{`click here`}</Link> </Trans> </Title.H4> <ButtonLink to='/auth/login'> {t('resetPassword.invalidToken.goBackLogin')} </ButtonLink> </Flexbox> )
src/index.js
great-design-and-systems/cataloguing-app
/* eslint-disable import/default */ import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page. import '../node_modules/normalize.css/normalize.css'; import '../node_modules/bootstrap/dist/css/bootstrap.css'; import './theme/bootstrap/bootstrap.css'; import { AppContainer } from 'react-hot-loader'; import React from 'react'; import Root from './components/Root'; import { browserHistory } from 'react-router'; import configureStore from './store/configureStore'; import { loadSettings } from './actions/SettingsActions'; import { loadSubjects } from './actions/BookSubjectActions'; import { render } from 'react-dom'; import { syncHistoryWithStore } from 'react-router-redux'; require('./favicon.ico'); // Tell webpack to load favicon.ico const store = configureStore(); // Create an enhanced history that syncs navigation events with the store const history = syncHistoryWithStore(browserHistory, store); store.dispatch(loadSubjects()); store.dispatch(loadSettings()); render( <AppContainer> <Root store={store} history={history} /> </AppContainer>, document.getElementById('app') ); if (module.hot) { module.hot.accept('./components/Root', () => { const NewRoot = require('./components/Root').default; render( <AppContainer> <NewRoot store={store} history={history} /> </AppContainer>, document.getElementById('app') ); }); }
packages/react-error-overlay/src/components/Header.js
johnslay/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React from 'react'; import { red } from '../styles'; const headerStyle = { fontSize: '2em', fontFamily: 'sans-serif', color: red, whiteSpace: 'pre-wrap', // Top bottom margin spaces header // Right margin revents overlap with close button margin: '0 2rem 0.75rem 0', flex: '0 0 auto', maxHeight: '50%', overflow: 'auto', }; type HeaderPropType = {| headerText: string, |}; function Header(props: HeaderPropType) { return <div style={headerStyle}>{props.headerText}</div>; } export default Header;
src/components/Handle.js
mirokk/react-content-builder
import React from 'react'; import order from '../order'; let rem=(rid)=>{ var element = document.getElementById(rid); element.outerHTML = ""; order(); } export default ({clazz, children, rid})=>( <div className={"handle "+clazz}> {children} <i className="fa fa-trash" onClick={rem.bind(null, rid)} aria-hidden="true"></i> <i className="fa fa-arrows" aria-hidden="true"></i> </div> ); /* var Handle = React.createClass({ render: function(){ return( <div className={"handle "+this.props.clazz}>Move</div> ); } }); export default Handle*/
app/routes.js
BloodMoonShard/react-blog
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import { Layout } from './components/Layout/Layout'; import { Home } from './components/Home/Home'; import { Formblog } from './components/Formblog/Formblog'; export default ( <Route path="/" component={Layout}> <IndexRoute component={Home} /> <Route path="/add" component={Formblog} /> <Route path="/edit" component={Formblog} /> </Route> );
src/containers/components/NewExperiment/DepVar.js
mdboop/francis
// import React and Redux dependencies import React from 'react'; import { connect } from 'react-redux'; import _ from 'underscore'; import { bindActionCreators } from 'redux'; import MeasureWrapper from './MeasureWrapper'; // import actions import DepVarActions from '../../actions/DepVars'; import MeasureActions from '../../actions/Measures'; import NewExperimentActions from '../../actions/NewExperiment'; const Actions = extend(NewExperimentActions, MeasureActions, DepVarActions); function mapStatetoProps (state, ownProps) { return { name: state.DepVars.getIn([ownProps.depVarId, 'name']) }; } function mapDispatchtoProps (dispatch) { return { actions: bindActionCreators(Actions, dispatch) }; } var DepVar = React.createClass({ setName: function () { this.props.actions.setDepVarName(this.refs.depVarName.value, this.props.depVarId); }, render: function () { return ( <div> <label>dep Variable Name: <input type="text" ref="depVarName" onChange={this.setName} value={this.props.name}/> </label> <div> Name: {this.props.name} </div> <MeasureWrapper key={this.props.depVarId} depVarId={this.props.depVarId} /> </div> ); } }); module.exports = connect(mapStatetoProps, mapDispatchtoProps)(DepVar);
stories/TabbedForm.js
Fundflow/apollo-redux-form
import React from 'react'; import defaultRenderers from './defaultRenderers'; import { Tabs } from 'antd'; const TabPane = Tabs.TabPane; import gql from 'graphql-tag'; import { apolloForm } from '../lib/src/index'; import { capitalizeFirstLetter } from './utils'; const schema = gql` input UserInput { profile: ProfileInput address: AddressInput company: CompanyInput } input CompanyInput { legalName: String address: AddressInput } input AddressInput { street: String streetNumber: String city: String } input ProfileInput { name: String surname: String } `; export const query = gql` mutation createUser($user: UserInput) { createUser(user: $user) { id createdAt } } `; const TabbedForm = apolloForm(query, { schema, renderers: { ...defaultRenderers, UserInput: props => { return ( <Tabs defaultActiveKey="1"> {props.children.map((child, index) => { return ( <TabPane tab={capitalizeFirstLetter(child.props.name)} key={index} > {child} </TabPane> ); })} </Tabs> ); }, }, }); export default TabbedForm;
assets/jqwidgets/demos/react/app/dockinglayout/righttoleftlayout/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxDockingLayout from '../../../jqwidgets-react/react_jqxdockinglayout.js'; import JqxTree from '../../../jqwidgets-react/react_jqxtree.js'; class App extends React.Component { render() { let layout = [{ type: 'layoutGroup', orientation: 'horizontal', items: [{ type: 'autoHideGroup', alignment: 'left', width: 80, unpinnedWidth: 200, items: [{ type: 'layoutPanel', title: 'Toolbox', contentContainer: 'ToolboxPanel' }, { type: 'layoutPanel', title: 'Help', contentContainer: 'HelpPanel' }] }, { type: 'layoutGroup', orientation: 'vertical', width: 500, items: [{ type: 'documentGroup', height: 400, minHeight: 200, items: [{ type: 'documentPanel', title: 'Document 1', contentContainer: 'Document1Panel' }, { type: 'documentPanel', title: 'Document 2', contentContainer: 'Document2Panel' }] }, { type: 'tabbedGroup', height: 200, pinnedHeight: 30, items: [{ type: 'layoutPanel', title: 'Error List', contentContainer: 'ErrorListPanel' }] }] }, { type: 'tabbedGroup', width: 220, minWidth: 200, items: [{ type: 'layoutPanel', title: 'Solution Explorer', contentContainer: 'SolutionExplorerPanel', initContent: () => { // initialize a jqxTree inside the Solution Explorer Panel let source = [{ icon: '../../../images/earth.png', label: 'Project', expanded: true, items: [{ icon: '../../../images/folder.png', label: 'css', expanded: true, items: [{ icon: '../../../images/nav1.png', label: 'jqx.base.css' }, { icon: '../../../images/nav1.png', label: 'jqx.energyblue.css' }, { icon: '../../../images/nav1.png', label: 'jqx.orange.css' }] }, { icon: '../../../images/folder.png', label: 'scripts', items: [{ icon: '../../../images/nav1.png', label: 'jqxcore.js' }, { icon: '../../../images/nav1.png', label: 'jqxdata.js' }, { icon: '../../../images/nav1.png', label: 'jqxgrid.js' }] }, { icon: '../../../images/nav1.png', label: 'index.htm' }] }]; ReactDOM.render( <JqxTree style={{ border: 'none' }} width={190} source={source} rtl={true} /> , document.getElementById('solutionExplorerTree')); } }, { type: 'layoutPanel', title: 'Properties', contentContainer: 'PropertiesPanel' }] }] }, { type: 'floatGroup', width: 500, height: 300, position: { x: 350, y: 250 }, items: [{ type: 'layoutPanel', title: 'Output', contentContainer: 'OutputPanel', selected: true }] }]; return ( <JqxDockingLayout width={800} height={600} layout={layout} rtl={true}> <div data-container="ToolboxPanel"> List of tools </div> <div data-container="HelpPanel"> Help topics </div> <div data-container="Document1Panel"> Document 1 content </div> <div data-container="Document2Panel"> Document 2 content </div> <div data-container="ErrorListPanel"> List of errors </div> <div data-container="SolutionExplorerPanel"> <div id="solutionExplorerTree" /> </div> <div data-container="PropertiesPanel"> List of properties </div> <div data-container="OutputPanel"> <div style={{ fontFamily: 'Consolas' }}> <p> Themes installation complete. </p> <p> List of installed stylesheet files. Include at least one stylesheet Theme file and the images folder: </p> <ul> <li>styles/jqx.base.css: Stylesheet for the base Theme. The jqx.base.css file should be always included in your project.</li> <li>styles/jqx.arctic.css: Stylesheet for the Arctic Theme</li> <li>styles/jqx.web.css: Stylesheet for the Web Theme</li> <li>styles/jqx.bootstrap.css: Stylesheet for the Bootstrap Theme</li> <li>styles/jqx.classic.css: Stylesheet for the Classic Theme</li> <li>styles/jqx.darkblue.css: Stylesheet for the DarkBlue Theme</li> <li>styles/jqx.energyblue.css: Stylesheet for the EnergyBlue Theme</li> <li>styles/jqx.shinyblack.css: Stylesheet for the ShinyBlack Theme</li> <li>styles/jqx.office.css: Stylesheet for the Office Theme</li> <li>styles/jqx.metro.css: Stylesheet for the Metro Theme</li> <li>styles/jqx.metrodark.css: Stylesheet for the Metro Dark Theme</li> <li>styles/jqx.orange.css: Stylesheet for the Orange Theme</li> <li>styles/jqx.summer.css: Stylesheet for the Summer Theme</li> <li>styles/jqx.black.css: Stylesheet for the Black Theme</li> <li>styles/jqx.fresh.css: Stylesheet for the Fresh Theme</li> <li>styles/jqx.highcontrast.css: Stylesheet for the HighContrast Theme</li> <li>styles/jqx.blackberry.css: Stylesheet for the Blackberry Theme</li> <li>styles/jqx.android.css: Stylesheet for the Android Theme</li> <li>styles/jqx.mobile.css: Stylesheet for the Mobile Theme</li> <li>styles/jqx.windowsphone.css: Stylesheet for the Windows Phone Theme</li> <li>styles/jqx.ui-darkness.css: Stylesheet for the UI Darkness Theme</li> <li>styles/jqx.ui-lightness.css: Stylesheet for the UI Lightness Theme</li> <li>styles/jqx.ui-le-frog.css: Stylesheet for the UI Le Frog Theme</li> <li>styles/jqx.ui-overcast.css: Stylesheet for the UI Overcast Theme</li> <li>styles/jqx.ui-redmond.css: Stylesheet for the UI Redmond Theme</li> <li>styles/jqx.ui-smoothness.css: Stylesheet for the UI Smoothness Theme</li> <li>styles/jqx.ui-start.css: Stylesheet for the UI Start Theme</li> <li>styles/jqx.ui-sunny.css: Stylesheet for the UI Sunny Theme</li> <li>styles/images: contains images referenced in the stylesheet files</li> </ul> </div> </div> </JqxDockingLayout> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/legacyRoutes.js
OpenSourceMe/Website
import React from 'react'; import { Redirect } from 'react-router'; const legacyRoutes = ( <div> <Redirect from="/portfolio" to="/page/portfolio" /> <Redirect from="/about" to="/page/about" /> <Redirect from="/music" to="/page/music" /> <Redirect from="/resume" to="/page/resume" /> <Redirect from="/:anyOther" to="page/notfound" /> </div> ); export default legacyRoutes;
src/containers/DashboardJobsPage/components/SubscriptionItem/index.js
apedyashev/react-universal-jobs-aggregator
// libs import React from 'react'; import {PropTypes} from 'prop-types'; export default function SubscriptionItem({subscription}) { return ( <div>{subscription.title}</div> ); } SubscriptionItem.propTypes = { subscription: PropTypes.shape({ id: PropTypes.string, title: PropTypes.string, }).isRequired, };
main.js
yogeshkhatri1989/rc-month-calendar
import React, { Component } from 'react'; import ReactDom from 'react-dom'; import MonthCalendar from './Calendar'; import './Calendar.less'; class App extends Component { render() { return <MonthCalendar containerClass={"cal-container"} prevButtonClass={"cal-prev-button"} nextButtonClass={"cal-next-button"} disabledDateClass={"cal-disabled-date"} enabledDateClass={"cal-enabled-date"} dateClass={"cal-date"} prevButtonHtml={"<<"} nextButtonHtml={">>"} onDateClick={console.log} isDateEnabled={date => date.getDate() == new Date().getDate()} selectedDate={new Date(Date.now() - (34 * 1000 * 60 * 60 * 24))} currentDate={new Date(Date.now() - (64 * 1000 * 60 * 60 * 24))} onMonthChange={console.log} /> } } function enabledDates() { return [new Date, new Date(Date.now() - 3 * 1000 * 60 * 60 * 24)] } import "./style.less"; ReactDom.render(<App />, document.getElementById("app"));
docs/html.js
jribeiro/storybook
import React from 'react'; import PropTypes from 'prop-types'; import DocumentTitle from 'react-document-title'; import { prefixLink } from 'gatsby/dist/isomorphic/gatsby-helpers'; import favicon from './design/homepage/storybook-icon.png'; const BUILD_TIME = new Date().getTime(); const HTML = props => { const title = DocumentTitle.rewind(); let css; if (process.env.NODE_ENV === 'production') { // eslint-disable-next-line css = <style dangerouslySetInnerHTML={{ __html: require('!raw!./public/styles.css') }} />; } const searchScript = [ <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.css" />, <script type="text/javascript" src="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.js" />, <script type="text/javascript" dangerouslySetInnerHTML={{ __html: `docsearch({ apiKey: 'a4f7f972f1d8f99a66e237e7fd2e489f', indexName: 'storybook-js', inputSelector: '#search', debug: false // Set debug to true if you want to inspect the dropdown });`, }} />, ]; return ( <html lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title> {title} </title> <link rel="icon" href={favicon} type="image/x-icon" /> {css} </head> <body> <div id="react-mount" dangerouslySetInnerHTML={{ __html: props.body }} /> <script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} /> {searchScript} </body> </html> ); }; HTML.displayName = 'HTML'; HTML.propTypes = { body: PropTypes.string, }; HTML.defaultProps = { body: '', }; export default HTML;
app/javascript/mastodon/features/notifications/index.js
masarakki/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandNotifications, scrollTopNotifications } from '../../actions/notifications'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import NotificationContainer from './containers/notification_container'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnSettingsContainer from './containers/column_settings_container'; import { createSelector } from 'reselect'; import { List as ImmutableList } from 'immutable'; import { debounce } from 'lodash'; import ScrollableList from '../../components/scrollable_list'; import LoadGap from '../../components/load_gap'; const messages = defineMessages({ title: { id: 'column.notifications', defaultMessage: 'Notifications' }, }); const getNotifications = createSelector([ state => ImmutableList(state.getIn(['settings', 'notifications', 'shows']).filter(item => !item).keys()), state => state.getIn(['notifications', 'items']), ], (excludedTypes, notifications) => notifications.filterNot(item => item !== null && excludedTypes.includes(item.get('type')))); const mapStateToProps = state => ({ notifications: getNotifications(state), isLoading: state.getIn(['notifications', 'isLoading'], true), isUnread: state.getIn(['notifications', 'unread']) > 0, hasMore: state.getIn(['notifications', 'hasMore']), }); export default @connect(mapStateToProps) @injectIntl class Notifications extends React.PureComponent { static propTypes = { columnId: PropTypes.string, notifications: ImmutablePropTypes.list.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, intl: PropTypes.object.isRequired, isLoading: PropTypes.bool, isUnread: PropTypes.bool, multiColumn: PropTypes.bool, hasMore: PropTypes.bool, }; static defaultProps = { trackScroll: true, }; componentWillUnmount () { this.handleLoadOlder.cancel(); this.handleScrollToTop.cancel(); this.handleScroll.cancel(); this.props.dispatch(scrollTopNotifications(false)); } handleLoadGap = (maxId) => { this.props.dispatch(expandNotifications({ maxId })); }; handleLoadOlder = debounce(() => { const last = this.props.notifications.last(); this.props.dispatch(expandNotifications({ maxId: last && last.get('id') })); }, 300, { leading: true }); handleScrollToTop = debounce(() => { this.props.dispatch(scrollTopNotifications(true)); }, 100); handleScroll = debounce(() => { this.props.dispatch(scrollTopNotifications(false)); }, 100); handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('NOTIFICATIONS', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setColumnRef = c => { this.column = c; } handleMoveUp = id => { const elementIndex = this.props.notifications.findIndex(item => item !== null && item.get('id') === id) - 1; this._selectChild(elementIndex); } handleMoveDown = id => { const elementIndex = this.props.notifications.findIndex(item => item !== null && item.get('id') === id) + 1; this._selectChild(elementIndex); } _selectChild (index) { const element = this.column.node.querySelector(`article:nth-of-type(${index + 1}) .focusable`); if (element) { element.focus(); } } render () { const { intl, notifications, shouldUpdateScroll, isLoading, isUnread, columnId, multiColumn, hasMore } = this.props; const pinned = !!columnId; const emptyMessage = <FormattedMessage id='empty_column.notifications' defaultMessage="You don't have any notifications yet. Interact with others to start the conversation." />; let scrollableContent = null; if (isLoading && this.scrollableContent) { scrollableContent = this.scrollableContent; } else if (notifications.size > 0 || hasMore) { scrollableContent = notifications.map((item, index) => item === null ? ( <LoadGap key={'gap:' + notifications.getIn([index + 1, 'id'])} disabled={isLoading} maxId={index > 0 ? notifications.getIn([index - 1, 'id']) : null} onClick={this.handleLoadGap} /> ) : ( <NotificationContainer key={item.get('id')} notification={item} accountId={item.get('account')} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} /> )); } else { scrollableContent = null; } this.scrollableContent = scrollableContent; const scrollContainer = ( <ScrollableList scrollKey={`notifications-${columnId}`} trackScroll={!pinned} isLoading={isLoading} hasMore={hasMore} emptyMessage={emptyMessage} onLoadMore={this.handleLoadOlder} onScrollToTop={this.handleScrollToTop} onScroll={this.handleScroll} shouldUpdateScroll={shouldUpdateScroll} > {scrollableContent} </ScrollableList> ); return ( <Column ref={this.setColumnRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='bell' active={isUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer /> </ColumnHeader> {scrollContainer} </Column> ); } }
addons/themes/phantom/layouts/Single.js
rendact/rendact
import React from 'react' import Header from '../includes/Header'; import FooterWidgets from '../includes/FooterWidgets'; import MenuItems from '../includes/MenuItems'; import Footer from '../includes/Footer'; class Single extends React.Component { componentDidMount(){ require("../css/style.css") document.body.className = "" } render(){ let {postData} = this.props return ( <div> <div id="wrapper" style={{background: "#fff"}}> <Header {...this.props}/> <div id="main"> <div className="inner"> <h1>{postData.title}</h1> <span className="image main"> {postData.imageFeatured && <img src={postData.imageFeatured.blobUrl} alt={postData.title}/>} </span> <div dangerouslySetInnerHTML={{__html: postData.content}}/> </div> </div> <Footer {...this.props}/> <Footer /> </div> <MenuItems {...this.props}/> </div> ) } } export default Single;
src/js/client/app.js
janjakubnanista/rain
import React from 'react'; import { connect } from 'react-redux'; class App extends React.Component { render() { return <h1>App</h1>; } } export default connect(state => state)(App);
RNApp/node_modules/react-native/Libraries/Components/WebView/WebView.ios.js
abhaytalreja/react-native-telescope
/** * 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. * * @providesModule WebView * @noflow */ 'use strict'; var ActivityIndicator = require('ActivityIndicator'); var EdgeInsetsPropType = require('EdgeInsetsPropType'); var React = require('React'); var ReactNative = require('react/lib/ReactNative'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var UIManager = require('UIManager'); var View = require('View'); var ScrollView = require('ScrollView'); var deprecatedPropType = require('deprecatedPropType'); var invariant = require('fbjs/lib/invariant'); var keyMirror = require('fbjs/lib/keyMirror'); var processDecelerationRate = require('processDecelerationRate'); var requireNativeComponent = require('requireNativeComponent'); var resolveAssetSource = require('resolveAssetSource'); var PropTypes = React.PropTypes; var RCTWebViewManager = require('NativeModules').WebViewManager; var BGWASH = 'rgba(255,255,255,0.8)'; var RCT_WEBVIEW_REF = 'webview'; var WebViewState = keyMirror({ IDLE: null, LOADING: null, ERROR: null, }); const NavigationType = keyMirror({ click: true, formsubmit: true, backforward: true, reload: true, formresubmit: true, other: true, }); const JSNavigationScheme = 'react-js-navigation'; type ErrorEvent = { domain: any; code: any; description: any; } type Event = Object; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; var defaultRenderLoading = () => ( <View style={styles.loadingView}> <ActivityIndicator /> </View> ); var defaultRenderError = (errorDomain, errorCode, errorDesc) => ( <View style={styles.errorContainer}> <Text style={styles.errorTextTitle}> Error loading page </Text> <Text style={styles.errorText}> {'Domain: ' + errorDomain} </Text> <Text style={styles.errorText}> {'Error Code: ' + errorCode} </Text> <Text style={styles.errorText}> {'Description: ' + errorDesc} </Text> </View> ); /** * `WebView` renders web content in a native view. * *``` * import React, { Component } from 'react'; * import { WebView } from 'react-native'; * * class MyWeb extends Component { * render() { * return ( * <WebView * source={{uri: 'https://github.com/facebook/react-native'}} * style={{marginTop: 20}} * /> * ); * } * } *``` * * You can use this component to navigate back and forth in the web view's * history and configure various properties for the web content. */ var WebView = React.createClass({ statics: { JSNavigationScheme: JSNavigationScheme, NavigationType: NavigationType, }, propTypes: { ...View.propTypes, html: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), url: deprecatedPropType( PropTypes.string, 'Use the `source` prop instead.' ), /** * Loads static html or a uri (with optional headers) in the WebView. */ source: PropTypes.oneOfType([ PropTypes.shape({ /* * The URI to load in the `WebView`. Can be a local or remote file. */ uri: PropTypes.string, /* * The HTTP Method to use. Defaults to GET if not specified. * NOTE: On Android, only GET and POST are supported. */ method: PropTypes.string, /* * Additional HTTP headers to send with the request. * NOTE: On Android, this can only be used with GET requests. */ headers: PropTypes.object, /* * The HTTP body to send with the request. This must be a valid * UTF-8 string, and will be sent exactly as specified, with no * additional encoding (e.g. URL-escaping or base64) applied. * NOTE: On Android, this can only be used with POST requests. */ body: PropTypes.string, }), PropTypes.shape({ /* * A static HTML page to display in the WebView. */ html: PropTypes.string, /* * The base URL to be used for any relative links in the HTML. */ baseUrl: PropTypes.string, }), /* * Used internally by packager. */ PropTypes.number, ]), /** * Function that returns a view to show if there's an error. */ renderError: PropTypes.func, // view to show if there's an error /** * Function that returns a loading indicator. */ renderLoading: PropTypes.func, /** * Function that is invoked when the `WebView` has finished loading. */ onLoad: PropTypes.func, /** * Function that is invoked when the `WebView` load succeeds or fails. */ onLoadEnd: PropTypes.func, /** * Function that is invoked when the `WebView` starts loading. */ onLoadStart: PropTypes.func, /** * Function that is invoked when the `WebView` load fails. */ onError: PropTypes.func, /** * Boolean value that determines whether the web view bounces * when it reaches the edge of the content. The default value is `true`. * @platform ios */ bounces: PropTypes.bool, /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. You may also use the * string shortcuts `"normal"` and `"fast"` which match the underlying iOS * settings for `UIScrollViewDecelerationRateNormal` and * `UIScrollViewDecelerationRateFast` respectively: * * - normal: 0.998 * - fast: 0.99 (the default for iOS web view) * @platform ios */ decelerationRate: ScrollView.propTypes.decelerationRate, /** * Boolean value that determines whether scrolling is enabled in the * `WebView`. The default value is `true`. * @platform ios */ scrollEnabled: PropTypes.bool, /** * Controls whether to adjust the content inset for web views that are * placed behind a navigation bar, tab bar, or toolbar. The default value * is `true`. */ automaticallyAdjustContentInsets: PropTypes.bool, /** * The amount by which the web view content is inset from the edges of * the scroll view. Defaults to {top: 0, left: 0, bottom: 0, right: 0}. */ contentInset: EdgeInsetsPropType, /** * Function that is invoked when the `WebView` loading starts or ends. */ onNavigationStateChange: PropTypes.func, /** * Boolean value that forces the `WebView` to show the loading view * on the first load. */ startInLoadingState: PropTypes.bool, /** * The style to apply to the `WebView`. */ style: View.propTypes.style, /** * Determines the types of data converted to clickable URLs in the web viewโ€™s content. * By default only phone numbers are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * Boolean value to enable JavaScript in the `WebView`. Used on Android only * as JavaScript is enabled by default on iOS. The default value is `true`. * @platform android */ javaScriptEnabled: PropTypes.bool, /** * Boolean value to control whether DOM Storage is enabled. Used only in * Android. * @platform android */ domStorageEnabled: PropTypes.bool, /** * Set this to provide JavaScript that will be injected into the web page * when the view loads. */ injectedJavaScript: PropTypes.string, /** * Sets the user-agent for the `WebView`. * @platform android */ userAgent: PropTypes.string, /** * Boolean that controls whether the web content is scaled to fit * the view and enables the user to change the scale. The default value * is `true`. */ scalesPageToFit: PropTypes.bool, /** * Function that allows custom handling of any web view requests. Return * `true` from the function to continue loading the request and `false` * to stop loading. * @platform ios */ onShouldStartLoadWithRequest: PropTypes.func, /** * Boolean that determines whether HTML5 videos play inline or use the * native full-screen controller. The default value is `false`. * * **NOTE** : In order for video to play inline, not only does this * property need to be set to `true`, but the video element in the HTML * document must also include the `webkit-playsinline` attribute. * @platform ios */ allowsInlineMediaPlayback: PropTypes.bool, /** * Boolean that determines whether HTML5 audio and video requires the user * to tap them before they start playing. The default value is `false`. */ mediaPlaybackRequiresUserAction: PropTypes.bool, }, getInitialState: function() { return { viewState: WebViewState.IDLE, lastErrorEvent: (null: ?ErrorEvent), startInLoadingState: true, }; }, componentWillMount: function() { if (this.props.startInLoadingState) { this.setState({viewState: WebViewState.LOADING}); } }, render: function() { var otherView = null; if (this.state.viewState === WebViewState.LOADING) { otherView = (this.props.renderLoading || defaultRenderLoading)(); } else if (this.state.viewState === WebViewState.ERROR) { var errorEvent = this.state.lastErrorEvent; invariant( errorEvent != null, 'lastErrorEvent expected to be non-null' ); otherView = (this.props.renderError || defaultRenderError)( errorEvent.domain, errorEvent.code, errorEvent.description ); } else if (this.state.viewState !== WebViewState.IDLE) { console.error( 'RCTWebView invalid state encountered: ' + this.state.loading ); } var webViewStyles = [styles.container, styles.webView, this.props.style]; if (this.state.viewState === WebViewState.LOADING || this.state.viewState === WebViewState.ERROR) { // if we're in either LOADING or ERROR states, don't show the webView webViewStyles.push(styles.hidden); } var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => { var shouldStart = this.props.onShouldStartLoadWithRequest && this.props.onShouldStartLoadWithRequest(event.nativeEvent); RCTWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier); }); var decelerationRate = processDecelerationRate(this.props.decelerationRate); var source = this.props.source || {}; if (this.props.html) { source.html = this.props.html; } else if (this.props.url) { source.uri = this.props.url; } var webView = <RCTWebView ref={RCT_WEBVIEW_REF} key="webViewKey" style={webViewStyles} source={resolveAssetSource(source)} injectedJavaScript={this.props.injectedJavaScript} bounces={this.props.bounces} scrollEnabled={this.props.scrollEnabled} decelerationRate={decelerationRate} contentInset={this.props.contentInset} automaticallyAdjustContentInsets={this.props.automaticallyAdjustContentInsets} onLoadingStart={this._onLoadingStart} onLoadingFinish={this._onLoadingFinish} onLoadingError={this._onLoadingError} onShouldStartLoadWithRequest={onShouldStartLoadWithRequest} scalesPageToFit={this.props.scalesPageToFit} allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback} mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction} dataDetectorTypes={this.props.dataDetectorTypes} />; return ( <View style={styles.container}> {webView} {otherView} </View> ); }, /** * Go forward one page in the web view's history. */ goForward: function() { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goForward, null ); }, /** * Go back one page in the web view's history. */ goBack: function() { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.goBack, null ); }, /** * Reloads the current page. */ reload: function() { this.setState({viewState: WebViewState.LOADING}); UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.reload, null ); }, /** * Stop loading the current page. */ stopLoading: function() { UIManager.dispatchViewManagerCommand( this.getWebViewHandle(), UIManager.RCTWebView.Commands.stopLoading, null ); }, /** * We return an event with a bunch of fields including: * url, title, loading, canGoBack, canGoForward */ _updateNavigationState: function(event: Event) { if (this.props.onNavigationStateChange) { this.props.onNavigationStateChange(event.nativeEvent); } }, /** * Returns the native `WebView` node. */ getWebViewHandle: function(): any { return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]); }, _onLoadingStart: function(event: Event) { var onLoadStart = this.props.onLoadStart; onLoadStart && onLoadStart(event); this._updateNavigationState(event); }, _onLoadingError: function(event: Event) { event.persist(); // persist this event because we need to store it var {onError, onLoadEnd} = this.props; onError && onError(event); onLoadEnd && onLoadEnd(event); console.warn('Encountered an error loading page', event.nativeEvent); this.setState({ lastErrorEvent: event.nativeEvent, viewState: WebViewState.ERROR }); }, _onLoadingFinish: function(event: Event) { var {onLoad, onLoadEnd} = this.props; onLoad && onLoad(event); onLoadEnd && onLoadEnd(event); this.setState({ viewState: WebViewState.IDLE, }); this._updateNavigationState(event); }, }); var RCTWebView = requireNativeComponent('RCTWebView', WebView, { nativeOnly: { onLoadingStart: true, onLoadingError: true, onLoadingFinish: true, }, }); var styles = StyleSheet.create({ container: { flex: 1, }, errorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: BGWASH, }, errorText: { fontSize: 14, textAlign: 'center', marginBottom: 2, }, errorTextTitle: { fontSize: 15, fontWeight: '500', marginBottom: 10, }, hidden: { height: 0, flex: 0, // disable 'flex:1' when hiding a View }, loadingView: { backgroundColor: BGWASH, flex: 1, justifyContent: 'center', alignItems: 'center', height: 100, }, webView: { backgroundColor: '#ffffff', } }); module.exports = WebView;
src/pages/AccessDenied/index.js
aggiedefenders/aggiedefenders.github.io
import React, { Component } from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; // import PageHeader from 'react-bootstrap/lib/PageHeader'; // import database from './database'; class AccessDenied extends Component { constructor(props) { super(props); this.state = { }; } render(){ return ( <div> <div className="col-lg-12"> <h3>Admin Access Required </h3> </div> </div> ); } } export default AccessDenied;
packages/ringcentral-widgets-cli/templates/Project/src/containers/AppView/index.js
u9520107/ringcentral-js-widget
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import withPhone from 'ringcentral-widgets/lib/withPhone'; import OfflineModeBadge from 'ringcentral-widgets/components/OfflineModeBadge'; import Environment from 'ringcentral-widgets/components/Environment'; import styles from './styles.scss'; function AppView(props) { return ( <div className={styles.root}> {props.children} <OfflineModeBadge offline={props.offline} showOfflineAlert={props.showOfflineAlert} currentLocale={props.currentLocale} /> <Environment server={props.server} enabled={props.enabled} onSetData={props.onSetData} redirectUri={props.redirectUri} recordingHost={''} /> </div> ); } AppView.propTypes = { children: PropTypes.node, server: PropTypes.string, enabled: PropTypes.bool, onSetData: PropTypes.func, currentLocale: PropTypes.string.isRequired, offline: PropTypes.bool.isRequired, showOfflineAlert: PropTypes.func.isRequired, redirectUri: PropTypes.string.isRequired, }; AppView.defaultProps = { children: null, server: null, appSecret: null, appKey: null, enabled: false, onSetData: undefined, }; export default withPhone(connect((_, { phone: { locale, oAuth, environment, connectivityMonitor, rateLimiter, } }) => ({ currentLocale: locale.currentLocale, server: environment.server, enabled: environment.enabled, offline: ( !connectivityMonitor.connectivity || oAuth.proxyRetryCount > 0 || rateLimiter.throttling ), redirectUri: oAuth.redirectUri }), (_, { phone: { environment, connectivityMonitor, rateLimiter, }, }) => ({ onSetData: (options) => { environment.setData(options); }, showOfflineAlert: () => { rateLimiter.showAlert(); connectivityMonitor.showAlert(); }, }))(AppView));
app/containers/UGTourPage/touritem.js
perry-ugroop/ugroop-react-dup2
/** * Created by yunzhou on 26/11/2016. */ import React from 'react'; // import { connect } from 'react-redux'; import messages from './messages'; // import { FormattedMessage } from 'react-intl'; import { Tabs, NavDropdown, MenuItem } from 'react-bootstrap'; import UGTab from './UGTab'; import A from '../../components/A'; import UGMainHeading from '../../components/UGMainHeading'; import TourDate from './TourDate'; import TourDescText from './TourDescText'; import TourImg from './TourImg'; import TourHead from './TourHead'; import AttendantTab from './attendanttab'; import NewsFeedTab from './newsfeedtab'; import MockNewsFeed from './mockdata/mockNewsFeed'; export function TourItem(props) { const tour = props.item; const tourImg = tour.tourImg; const participants = tour.Participants || []; const organizer = tour.Organizer || []; const viewers = tour.Viewers || []; const newsFeed = tour.NewsFeed || []; return ( <div className="media"> <div className="media-left"> <A href="#"> <TourImg src={tourImg.imgSrc} alt={tourImg.alt} /> </A> </div> <div className="media-body"> <UGMainHeading className="media-heading"> <NavDropdown eventKey="options" className="btn-group pull-right" title={messages.optionButton.defaultMessage} id={`tour-option${tour.tourId}`}> <MenuItem eventKey="options.edittour">{messages.optionsEditTour.defaultMessage}</MenuItem> <MenuItem eventKey="options.addplan">{messages.optionsAddPlan.defaultMessage}</MenuItem> <MenuItem eventKey="options.sharetour">{messages.optionsShareTour.defaultMessage}</MenuItem> <MenuItem eventKey="options.mergetour">{messages.optionsMergeTour.defaultMessage}</MenuItem> <MenuItem eventKey="options.deletetour">{messages.optionsDeleteTour.defaultMessage}</MenuItem> </NavDropdown> <TourHead href={`/tour/Details?tourId=${tour.tourId}`}>{tour.tourName}</TourHead> <TourDate>{`${tour.tourFromDate} - ${tour.tourToDate}`}</TourDate> <p /> <TourDescText> {tour.tourDesc} </TourDescText> <p /> <Tabs className="nav nav-tabs" defaultActiveKey={1} animation={false} id="tour-users" style={{ background: 'white' }} > <UGTab eventKey={1} title={`${messages.participantTabTitle.defaultMessage}(${participants.length})`} style={{ paddingTop: '10px' }} > <AttendantTab items={participants} tourId={tour.tourId} attendType="participant" /> </UGTab> <UGTab eventKey={2} title={`${messages.organizerTabTitle.defaultMessage}(${organizer.length})`}> <AttendantTab items={organizer} tourId={tour.tourId} attendType="organizer" /> </UGTab> <UGTab eventKey={3} title={`${messages.viewerTabTitle.defaultMessage}(${viewers.length})`}> <AttendantTab items={viewers} tourId={tour.tourId} attendType="viewer" /> </UGTab> <UGTab eventKey={4} title={`${messages.newsFeedTabTitle.defaultMessage}(${newsFeed.length})`}> <NewsFeedTab tourId={tour.tourId} items={MockNewsFeed} /> </UGTab> </Tabs> </UGMainHeading> </div> </div> ); } TourItem.propTypes = { item: React.PropTypes.any, }; export default TourItem;
app/containers/LobbyItem/index.js
VonIobro/ab-web
import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import { createStructuredSelector } from 'reselect'; import Button from 'components/Button'; import Link from 'components/Link'; import { makeSelectTableData, makeSelectTableLastHandId } from './selectors'; import { formatNtz } from '../../utils/amountFormatter'; const Tr = styled.tr` &:nth-of-type(odd) { background-color: rgba(0, 0, 0, 0.05); } `; const Td = styled.td` padding: 0.75rem; vertical-align: top; text-align: center; border-top: 1px solid #eceeef; `; const ADDR_EMPTY = '0x0000000000000000000000000000000000000000'; class LobbyItem extends React.PureComponent { // eslint-disable-line render() { if (!this.props.data || !this.props.data.seats) { return (<tr />); } let players = 0; this.props.data.seats.forEach((seat) => { if (seat && seat.address && seat.address.length >= 40 && seat.address !== ADDR_EMPTY) { players += 1; } }); const sb = this.props.data.smallBlind; const bb = sb * 2; return ( <Tr> <Td key="ta">{this.props.tableAddr.substring(2, 8)}</Td> <Td key="sb">{formatNtz(sb)} NTZ / {formatNtz(bb)} NTZ</Td> <Td key="np">{`${players}/${this.props.data.seats.length}`}</Td> <Td key="lh">{this.props.lastHandId}</Td> <Td key="ac"> <Link to={`/table/${this.props.tableAddr}`} size="small" icon="fa fa-eye" component={Button} /> </Td> </Tr> ); } } LobbyItem.propTypes = { tableAddr: React.PropTypes.string, data: React.PropTypes.object, lastHandId: React.PropTypes.number, }; const mapStateToProps = createStructuredSelector({ data: makeSelectTableData(), lastHandId: makeSelectTableLastHandId(), }); export default connect(mapStateToProps)(LobbyItem);
src/svg-icons/maps/local-car-wash.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalCarWash = (props) => ( <SvgIcon {...props}> <path d="M17 5c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zm-5 0c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zM7 5c.83 0 1.5-.67 1.5-1.5C8.5 2.5 7 .8 7 .8S5.5 2.5 5.5 3.5C5.5 4.33 6.17 5 7 5zm11.92 3.01C18.72 7.42 18.16 7 17.5 7h-11c-.66 0-1.21.42-1.42 1.01L3 14v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 18c-.83 0-1.5-.67-1.5-1.5S5.67 15 6.5 15s1.5.67 1.5 1.5S7.33 18 6.5 18zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 13l1.5-4.5h11L19 13H5z"/> </SvgIcon> ); MapsLocalCarWash = pure(MapsLocalCarWash); MapsLocalCarWash.displayName = 'MapsLocalCarWash'; MapsLocalCarWash.muiName = 'SvgIcon'; export default MapsLocalCarWash;
app/index.js
zhangmhao/memo
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import routes from './routes'; import configureStore from './store/configureStore'; import './app.global.css'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') );
src/components/Main.js
teafn/react-webpack-sample
require('normalize.css/normalize.css'); require('styles/App.scss'); import React from 'react'; import ReactDOM from 'react-dom'; import FigureImgComponent from './FigureImgComponent'; import ControllerComponent from './ControllerComponent' let imgData = require('../data/imgData.json'); import {randRange,randDeg} from '../utilities/index' imgData = imgData.map((data) => { data.imgUrl = require('../images/'+ data.fileName); return data; }); class AppComponent extends React.Component { constructor(props){ super(props); this.Constant = { centerPos: { //ไธญๅคฎไฝ็ฝฎ left: 0, right: 0 }, hPosRange: { //ๆฐดๅนณๆ–นๅ‘๏ผˆๅทฆ้ƒจๅ’Œๅณ้ƒจๅŒบๅŸŸ๏ผ‰็š„ๅ–ๅ€ผ่Œƒๅ›ด leftSecX: [0, 0], rightSecX: [0, 0], y: [0, 0] }, vPosRange: { //ๅž‚็›ดๆ–นๅ‘๏ผˆไธŠ้ƒจ๏ผ‰ topX: [0, 0], topY: [0, 0] } }; this.state = { imgsArrangeArr: [] }; } inverse(index){ let imgsArrange = this.state.imgsArrangeArr; imgsArrange[index].isInverse = !imgsArrange[index].isInverse; this.setState({imgsArrangeArr : imgsArrange}); } center(index){ this.rearrange(index); } rearrange(centerIndex){ let imgsArrangeArr = this.state.imgsArrangeArr, Constant = this.Constant, centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecX, hPosRangeY = hPosRange.y, vPosRangeTopY = vPosRange.topY, vPosRangeX = vPosRange.topX, imgsArrangTopArr = [], topImgNum = Math.floor(Math.random() * 2), //ๅ–ไธ€ไธชๆˆ–่€…ไธๅ– topImgSpiceIndex = 0, imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1); //้ฆ–ๅ…ˆๅฑ…ไธญcenterIndexๅ›พ็‰‡ ,centerIndexๅ›พ็‰‡ไธ้œ€่ฆๆ—‹่ฝฌ imgsArrangeCenterArr[0] = { pos: centerPos, rotate: 0, isCenter: true } //ๅ–ๅ‡บ่ฆๅธƒๅฑ€ไธŠๆต‹็š„ๅ›พ็‰‡็š„็Šถๆ€ไฟกๆฏ topImgSpiceIndex = Math.floor(Math.random() * (imgsArrangeArr.length - topImgNum)); imgsArrangTopArr = imgsArrangeArr.splice(topImgSpiceIndex, topImgNum); //ๅธƒๅฑ€ไฝไบŽไธŠไพง็š„ๅ›พ็‰‡ imgsArrangTopArr.forEach((value, index) => { imgsArrangTopArr[index] = { pos: { top: randRange(vPosRangeTopY[0], vPosRangeTopY[1]), left: randRange(vPosRangeX[0], vPosRangeX[1]) }, rotate: randDeg(), isCenter: false }; }); //ๅธƒๅฑ€ๅทฆไธคไพง็š„ๅ›พ็‰‡ for (let i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) { let hPosRangeLORX = null; //ๅ‰ๅŠ้ƒจๅˆ†ๅธƒๅฑ€ๅทฆ่พน,ๅณ่พน้ƒจๅˆ†ๅธƒๅฑ€ๅณ่พน if (i < k) { hPosRangeLORX = hPosRangeLeftSecX; } else { hPosRangeLORX = hPosRangeRightSecX } imgsArrangeArr[i] = { pos: { top: randRange(hPosRangeY[0], hPosRangeY[1]), left: randRange(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate: randDeg(), isCenter: false }; } if (imgsArrangTopArr && imgsArrangTopArr[0]) { imgsArrangeArr.splice(topImgSpiceIndex, 0, imgsArrangTopArr[0]); } imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]); this.setState({ imgsArrangeArr: imgsArrangeArr }); } handleClick(index) { let imgsArrange = this.state.imgsArrangeArr; let app = this; return (e) => { if (imgsArrange[index].isCenter) { app.inverse(index) } else { app.center(index); } } } componentDidMount() { let stageDOM = ReactDOM.findDOMNode(this.stage), stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); //ๆ‹ฟๅˆฐไธ€ไธชimgFigure็š„ๅคงๅฐ let imgW = 280,imgH = 320, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); //่ฎก็ฎ—ไธญๅฟƒๅ›พ็‰‡็š„ไฝ็ฝฎ็‚น this.Constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH } //console.log(this.Constant.centerPos); //่ฎก็ฎ—ๅทฆไพง,ๅณไพงๅŒบๅŸŸๅ›พ็‰‡ๆŽ’ๅธƒ็š„ๅ–ๅ€ผ่Œƒๅ›ด this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[1] = stageH - halfImgH; //่ฎก็ฎ—ไธŠๆต‹ๅŒบๅŸŸๅ›พ็‰‡ๆŽ’ๅธƒ็š„ๅ–ๅ€ผ่Œƒๅ›ด this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.Constant.vPosRange.topX[0] = halfStageW - imgW; this.Constant.vPosRange.topX[1] = halfStageW; let num = Math.floor(Math.random() * 10); this.rearrange(num); } render() { return ( <div className="stage" ref={(stage) => { this.stage = stage; }}> <div className="front"> { imgData.map( (data,index) => { if (!this.state.imgsArrangeArr[index]) { this.state.imgsArrangeArr[index] = { pos: { left: 0, top: 0 }, rotate: 0, isInverse: false, isCenter: false } } return <FigureImgComponent key={index} data={data} arrange={this.state.imgsArrangeArr[index]} handleClick={this.handleClick(index)}/> }) } </div> <div className="controller"> { imgData.map( (data,index) => { if (!this.state.imgsArrangeArr[index]) { this.state.imgsArrangeArr[index] = { pos: { left: 0, top: 0 }, rotate: 0, isInverse: false, isCenter: false } } return <ControllerComponent key={index} index={index} data={data} arrange={this.state.imgsArrangeArr[index]} handleClick={this.handleClick(index)} /> }) } </div> </div> ); } } AppComponent.defaultProps = { }; export default AppComponent;
src/components/switch/Switch.js
f0zze/rosemary-ui
import isUndefined from 'lodash/isUndefined'; import React from 'react'; import cn from 'classnames'; const PROP_TYPES = { disable: React.PropTypes.bool, checked: React.PropTypes.bool, title: React.PropTypes.string }; const DEFAULT_PROPS = { disabled: false, onChange: () => { } }; class Switch extends React.Component { constructor(props) { super(props); this.state = { checked: this.props.checked }; this._handleOnChange = this._handleOnChange.bind(this); } _isControlled() { return !isUndefined(this.props.checked); } _handleOnChange(event) { if (this.props.disabled) { return; } if (this._isControlled()) { this.props.onChange(this.props.checked, event); } else { this.setState((prevState, props) => ({ checked: !this.state.checked }), () => { this.props.onChange(this.state.checked, event); }); } } _isChecked() { return this._isControlled() ? this.props.checked : this.state.checked; } _getTitle() { return isUndefined(this.props.title) ? null : (<label className="ros-switch__title">{this.props.title}</label>); } render() { const classNames = cn('ros-switch', { 'disabled': this.props.disabled, 'checked': this._isChecked() }); return ( <div onClick={this._handleOnChange} className={classNames}> <span className="ros-switch__control"> <i /> </span> {this._getTitle()} </div> ); } } Switch.propTypes = PROP_TYPES; Switch.defaultProps = DEFAULT_PROPS; export default Switch;
src/components/NotFoundPage.js
svitekpavel/chatbot-website
import React from 'react'; import { Link } from 'react-router'; const NotFoundPage = () => { return ( <div> <h4> 404 Page Not Found </h4> <Link to="/"> Go back to homepage </Link> </div> ); }; export default NotFoundPage;
spec/javascripts/jsx/blueprint_courses/components/ExpandableLockOptionsSpec.js
djbender/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import * as enzyme from 'enzyme' import ExpandableLockOptions from 'jsx/blueprint_courses/components/ExpandableLockOptions' QUnit.module('ExpandableLockOptions component') const defaultProps = () => ({ objectType: 'assignment', isOpen: false, lockableAttributes: ['content', 'points', 'due_dates', 'availability_dates'], locks: { content: false, points: false, due_dates: false, availability_dates: false } }) test('renders the ToggleMenuTab component', () => { const tree = enzyme.shallow(<ExpandableLockOptions {...defaultProps()} />) const node = tree.find('.bcs__object-tab') ok(node.exists()) }) test('renders the closed toggle Icon', () => { const tree = enzyme.shallow(<ExpandableLockOptions {...defaultProps()} />) const icon = tree.find('.bcs_tab_indicator-icon IconArrowOpenEndSolid') equal(icon.length, 1) }) test('renders the opened toggle Icon', () => { const props = defaultProps() props.isOpen = true const tree = enzyme.shallow(<ExpandableLockOptions {...props} />) const icon = tree.find('.bcs_tab_indicator-icon IconArrowOpenDownSolid') equal(icon.length, 1) }) test('opens the submenu when toggle is clicked', assert => { const done = assert.async() const tree = enzyme.mount(<ExpandableLockOptions {...defaultProps()} />) const toggle = tree.find('.bcs_tab-icon') toggle.at(0).simulate('click') setTimeout(() => { const submenu = tree.find('LockCheckList') ok(submenu.exists()) done() }, 0) }) test('doesnt render the sub list initially', () => { const tree = enzyme.shallow(<ExpandableLockOptions {...defaultProps()} />) const list = tree.find('.bcs_check_box-group') notOk(list.exists()) }) test('renders the unlocked lock Icon when unlocked', () => { const tree = enzyme.shallow(<ExpandableLockOptions {...defaultProps()} />) const icon = tree.find('.bcs_tab-icon IconUnlock') equal(icon.length, 1) }) test('renders the locked lock Icon when locked', () => { const props = defaultProps() props.locks.content = true const tree = enzyme.shallow(<ExpandableLockOptions {...props} />) const icon = tree.find('.bcs_tab-icon IconLock') equal(icon.length, 1) })
src/components/products/products-by-series.js
FranckCo/Operation-Explorer
import React from 'react'; import { sparqlConnect } from 'sparql-connect'; import ProductList from './product-list'; import Spinner from 'components/shared/spinner' import D, { getLang } from 'i18n' /** * Builds the query that retrieves the products issued of a given series. */ const queryBuilder = series => ` PREFIX skos: <http://www.w3.org/2004/02/skos/core#> PREFIX prov: <http://www.w3.org/ns/prov#> SELECT ?product ?label FROM <http://rdf.insee.fr/graphes/produits> WHERE { ?product prov:wasGeneratedBy <${series}> . ?product skos:prefLabel ?label . FILTER (lang(?label) = '${getLang()}') } ORDER BY ?product ` const connector = sparqlConnect(queryBuilder, { queryName: 'productsBySeries', params: ['series'] }) function ProductsBySeries({ productsBySeries, title }) { if (productsBySeries.length === 0) { return <span>{D.seriesHoldsNoProduct}</span> } return <ProductList products={productsBySeries} title={title} /> } export default connector(ProductsBySeries, { loading: () => <Spinner text={D.loadingProducts} /> })
src/containers/DevTools.js
VinSpee/react-redux-postcss-boilerplate
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q" > <LogMonitor /> </DockMonitor> );
docs/tutorial/DO_NOT_TOUCH/06/src/index.js
idream3/cerebral
import React from 'react' import {render} from 'react-dom' import {Controller} from 'cerebral' import App from './components/App' import {Container} from 'cerebral/react' import Devtools from 'cerebral/devtools' import {set, wait} from 'cerebral/operators' import {state, input} from 'cerebral/tags' function showToast (message, ms) { return [ set(state`toast`, message), wait(ms), set(state`toast`, null) ] } const controller = Controller({ devtools: Devtools(), state: { title: 'Hello from Cerebral!', subTitle: 'Working on my state management', toast: null }, signals: { buttonClicked: [ ...showToast(input`message`, 1000) ] } }) render(( <Container controller={controller}> <App /> </Container> ), document.querySelector('#root'))
src/constants/marioParty.js
jhlav/mpn-web-app
/* eslint-disable import/prefer-default-export, global-require */ import React from 'react'; import Avatar from 'react-md/lib/Avatars'; export const getBoards = game => { const list = ['Unknown']; switch (game) { case 'Mario Party 1': return list.concat([ "Bowser's Magma Mountain", "DK's Jungle Adventure", 'Eternal Star', "Luigi's Engine Room", "Mario's Rainbow Castle", "Peach's Birthday Cake", "Wario's Battle Canyon", "Yoshi's Tropical Island", ]); case 'Mario Party 2': return list.concat([ 'Bowser Land', 'Horror Land', 'Mystery Land', 'Pirate Land', 'Space Land', 'Western Land', ]); case 'Mario Party 3': return list.concat([ 'Chilly Waters', 'Creepy Cavern', 'Deep Blooper Sea', 'Spiny Desert', "Waluigi's Island", 'Woody Woods', ]); case 'Mario Party 4': return list.concat([ "Boo's Haunted Bash", "Bowser's Gnarly Party", "Goomba's Greedy Gala", "Koopa's Seaside Soiree", "Shy Guy's Jungle Jam", "Toad's Midway Madness", ]); case 'Mario Party 5': return list.concat([ 'Bowser Nightmare', 'Future Dream', 'Pirate Dream', 'Rainbow Dream', 'Sweet Dream', 'Toy Dream', 'Undersea Dream', ]); case 'Mario Party 6': return list.concat([ 'Castaway Bay', 'Clockwork Castle', "E. Gadd's Garage", 'Faire Square', 'Snowflake Lake', 'Towering Treetop', ]); case 'Mario Party 7': return list.concat([ "Bowser's Enchanted Inferno!", 'Grand Canal', 'Neon Heights', 'Pagoda Peak', 'Pyramid Park', 'Windmillville', ]); case 'Mario Party 8': return list.concat([ "Bowser's Warped Orbit", "DK's Treetop Temple", "Goomba's Booty Boardwalk", "King Boo's Haunted Hideaway", "Koopa's Tycoon Town", "Shy Guy's Perplex Express", ]); case 'Mario Party 9': return list.concat([ 'Blooper Beach', 'Bob-omb Factory', "Boo's Horror Castle", 'Bowser Station', "DK's Jungle Ruins", 'Magma Mine', 'Toad Road', ]); default: return list; } }; export const getCharacterImage = character => { switch (character) { case 'Birdo': return require('../components/_SharedAssets/p_birdo.png'); case 'Blooper': return require('../components/_SharedAssets/p_blooper.png'); case 'Boo': return require('../components/_SharedAssets/p_boo.png'); case 'Daisy': return require('../components/_SharedAssets/p_daisy.png'); case 'Donkey Kong': return require('../components/_SharedAssets/p_donkeykong.png'); case 'Dry Bones': return require('../components/_SharedAssets/p_drybones.png'); case 'Hammer Bro': return require('../components/_SharedAssets/p_hammerbro.png'); case 'Kamek': return require('../components/_SharedAssets/p_kamek.png'); case 'Koopa Kid': return require('../components/_SharedAssets/p_koopakid.png'); case 'Koopa Troopa': return require('../components/_SharedAssets/p_koopatroopa.png'); case 'Luigi': return require('../components/_SharedAssets/p_luigi.png'); case 'Mario': return require('../components/_SharedAssets/p_mario.png'); case 'Peach': return require('../components/_SharedAssets/p_peach.png'); case 'Shy Guy': return require('../components/_SharedAssets/p_shyguy.png'); case 'Toad': return require('../components/_SharedAssets/p_toad.png'); case 'Toadette': return require('../components/_SharedAssets/p_toadette.png'); case 'Waluigi': return require('../components/_SharedAssets/p_waluigi.png'); case 'Wario': return require('../components/_SharedAssets/p_wario.png'); case 'Yoshi': return require('../components/_SharedAssets/p_yoshi.png'); default: return require('../components/_SharedAssets/mushroom.svg'); } }; const characterList = [ { name: 'Birdo', leftAvatar: <Avatar src={getCharacterImage('Birdo')} />, }, { name: 'Blooper', leftAvatar: <Avatar src={getCharacterImage('Blooper')} />, }, { name: 'Boo', leftAvatar: <Avatar src={getCharacterImage('Boo')} />, }, { name: 'Daisy', leftAvatar: <Avatar src={getCharacterImage('Daisy')} />, }, { name: 'Donkey Kong', leftAvatar: <Avatar src={getCharacterImage('Donkey Kong')} />, }, { name: 'Dry Bones', leftAvatar: <Avatar src={getCharacterImage('Dry Bones')} />, }, { name: 'Hammer Bro', leftAvatar: <Avatar src={getCharacterImage('Hammer Bro')} />, }, { name: 'Kamek', leftAvatar: <Avatar src={getCharacterImage('Kamek')} />, }, { name: 'Koopa Kid', leftAvatar: <Avatar src={getCharacterImage('Koopa Kid')} />, }, { name: 'Koopa Troopa', leftAvatar: <Avatar src={getCharacterImage('Koopa Troopa')} />, }, { name: 'Luigi', leftAvatar: <Avatar src={getCharacterImage('Luigi')} />, }, { name: 'Mario', leftAvatar: <Avatar src={getCharacterImage('Mario')} />, }, { name: 'Peach', leftAvatar: <Avatar src={getCharacterImage('Peach')} />, }, { name: 'Shy Guy', leftAvatar: <Avatar src={getCharacterImage('Shy Guy')} />, }, { name: 'Toad', leftAvatar: <Avatar src={getCharacterImage('Toad')} />, }, { name: 'Toadette', leftAvatar: <Avatar src={getCharacterImage('Toadette')} />, }, { name: 'Waluigi', leftAvatar: <Avatar src={getCharacterImage('Waluigi')} />, }, { name: 'Wario', leftAvatar: <Avatar src={getCharacterImage('Wario')} />, }, { name: 'Yoshi', leftAvatar: <Avatar src={getCharacterImage('Yoshi')} />, }, ]; export const getCharacters = game => { const list = []; switch (game) { case 'Mario Party 1': return list.concat([ characterList[4], characterList[10], characterList[11], characterList[12], characterList[17], characterList[18], ]); case 'Mario Party 2': return list.concat([ characterList[3], characterList[4], characterList[10], characterList[11], characterList[12], characterList[16], characterList[17], characterList[18], ]); case 'Mario Party 3': return list.concat([ characterList[3], characterList[4], characterList[10], characterList[11], characterList[12], characterList[16], characterList[17], characterList[18], ]); case 'Mario Party 4': return list.concat([ characterList[3], characterList[4], characterList[10], characterList[11], characterList[12], characterList[16], characterList[17], characterList[18], ]); case 'Mario Party 5': return list.concat([ characterList[2], characterList[3], characterList[8], characterList[10], characterList[11], characterList[12], characterList[14], characterList[16], characterList[17], characterList[18], ]); case 'Mario Party 6': return list.concat([ characterList[2], characterList[3], characterList[8], characterList[10], characterList[11], characterList[12], characterList[14], characterList[15], characterList[16], characterList[17], characterList[18], ]); case 'Mario Party 7': return list.concat([ characterList[0], characterList[2], characterList[3], characterList[5], characterList[10], characterList[11], characterList[12], characterList[14], characterList[15], characterList[16], characterList[17], characterList[18], ]); case 'Mario Party 8': return list.concat([ characterList[0], characterList[1], characterList[2], characterList[3], characterList[5], characterList[6], characterList[10], characterList[11], characterList[12], characterList[14], characterList[15], characterList[16], characterList[17], characterList[18], ]); case 'Mario Party 9': return list.concat([ characterList[0], characterList[3], characterList[7], characterList[9], characterList[10], characterList[11], characterList[12], characterList[13], characterList[14], characterList[16], characterList[17], characterList[18], ]); default: return characterList; } };
src/components/icons/Waves.js
niekert/soundify
import React from 'react'; import { string } from 'prop-types'; function Waves({ fill, ...props }) { return ( <svg height="432" width="561" fill={fill} viewBox="0 0 561 432" {...props}> <g fill={fill} transform="translate(-180 -244)"> <path d="M291.578 323.262c14.578 0 26.396 11.818 26.396 26.396v225.943c0 14.578-11.818 26.396-26.396 26.396-14.578 0-26.396-11.818-26.396-26.396V349.658c0-14.578 11.818-26.396 26.396-26.396zm168.935 2.104c14.579 0 26.397 11.818 26.397 26.396v225.942c0 14.579-11.818 26.397-26.397 26.397-14.578 0-26.396-11.818-26.396-26.397V351.762c0-14.578 11.818-26.396 26.396-26.396zm168.936 0c14.578 0 26.396 11.818 26.396 26.396v225.942c0 14.579-11.818 26.397-26.396 26.397-14.578 0-26.396-11.818-26.396-26.397V351.762c0-14.578 11.818-26.396 26.396-26.396zM207.11 402.149c14.579 0 26.397 11.818 26.397 26.397v62.908c0 14.579-11.818 26.397-26.397 26.397-14.578 0-26.396-11.818-26.396-26.397v-62.908c0-14.579 11.818-26.397 26.396-26.397zm337.871 4.208c14.578 0 26.396 11.818 26.396 26.396v62.909c0 14.578-11.818 26.396-26.396 26.396-14.578 0-26.396-11.818-26.396-26.396v-62.91c0-14.577 11.818-26.395 26.396-26.395zm168.935 1.052c14.579 0 26.396 11.817 26.396 26.396v62.909c0 14.578-11.817 26.396-26.396 26.396-14.578 0-26.396-11.818-26.396-26.396v-62.91c0-14.578 11.818-26.395 26.396-26.395zm-337.87-163.034c14.578 0 26.396 11.818 26.396 26.396V649.23c0 14.578-11.818 26.396-26.396 26.396-14.578 0-26.396-11.818-26.396-26.396V270.77c0-14.578 11.818-26.396 26.396-26.396z" /> <path d="M291.578 323.262c14.578 0 26.396 11.818 26.396 26.396v225.943c0 14.578-11.818 26.396-26.396 26.396-14.578 0-26.396-11.818-26.396-26.396V349.658c0-14.578 11.818-26.396 26.396-26.396zm168.935 2.104c14.579 0 26.397 11.818 26.397 26.396v225.942c0 14.579-11.818 26.397-26.397 26.397-14.578 0-26.396-11.818-26.396-26.397V351.762c0-14.578 11.818-26.396 26.396-26.396zm168.936 0c14.578 0 26.396 11.818 26.396 26.396v225.942c0 14.579-11.818 26.397-26.396 26.397-14.578 0-26.396-11.818-26.396-26.397V351.762c0-14.578 11.818-26.396 26.396-26.396zM207.11 402.149c14.579 0 26.397 11.818 26.397 26.397v62.908c0 14.579-11.818 26.397-26.397 26.397-14.578 0-26.396-11.818-26.396-26.397v-62.908c0-14.579 11.818-26.397 26.396-26.397zm337.871 4.208c14.578 0 26.396 11.818 26.396 26.396v62.909c0 14.578-11.818 26.396-26.396 26.396-14.578 0-26.396-11.818-26.396-26.396v-62.91c0-14.577 11.818-26.395 26.396-26.395zm168.935 1.052c14.579 0 26.396 11.817 26.396 26.396v62.909c0 14.578-11.817 26.396-26.396 26.396-14.578 0-26.396-11.818-26.396-26.396v-62.91c0-14.578 11.818-26.395 26.396-26.395zm-337.87-163.034c14.578 0 26.396 11.818 26.396 26.396V649.23c0 14.578-11.818 26.396-26.396 26.396-14.578 0-26.396-11.818-26.396-26.396V270.77c0-14.578 11.818-26.396 26.396-26.396z" /> </g> </svg> ); } Waves.propTypes = { fill: string, }; Waves.defaultProps = { fill: 'currentColor', }; export default Waves;
src/components/OnsetGraph.js
rikner/spectral-beat
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import * as actions from '../actions'; const propTypes = { canvasHeight: PropTypes.number.isRequired, canvasWidth: PropTypes.number.isRequired, graphScale: PropTypes.number.isRequired, onsetData: PropTypes.shape({ isPeak: PropTypes.bool.isRequired, threshold: PropTypes.number.isRequired, value: PropTypes.number.isRequired, }).isRequired, setOnsetGraphScale: PropTypes.func.isRequired, }; const mapStateToProps = state => ({ graphScale: state.onsetDetection.graphScale, onsetData: state.onsetDetection.onsetData, }); const mapDispatchToProps = { setOnsetGraphScale: actions.setOnsetGraphScale, }; class OnsetGraph extends Component { constructor(props) { super(props); const { canvasWidth } = props; this.createDataArrays(canvasWidth); } createDataArrays(length) { this.onsetValues = Array.from({ length }, _ => 0); this.thresholdValues = Array.from({ length }, _ => 0); this.peakValues = Array.from({ length }, _ => false); } componentDidMount = () => { this.startLoop(); }; componentWillUnmount = () => { this.stopLoop(); }; shouldComponentUpdate = (nextProps, nextState) => { const { onsetData, canvasWidth } = nextProps; if (this.props.canvasWidth !== canvasWidth) { this.createDataArrays(canvasWidth); return true; } const { value, threshold, isPeak } = onsetData; this.onsetValues.shift(); this.onsetValues.push(onsetData.value); this.thresholdValues.shift(); this.thresholdValues.push(onsetData.threshold); this.peakValues.shift(); this.peakValues.push(onsetData.isPeak); return false; }; startLoop = () => { if (!this.frameId) { this.frameId = window.requestAnimationFrame(this.loop); } if (!this.scalingTimer) { this.scalingTimer = setInterval(() => { const maxValue = Math.max(...this.onsetValues); const newGraphScale = this.props.canvasHeight / maxValue; this.props.setOnsetGraphScale(newGraphScale); }, 2500); } } loop = () => { this.drawCanvas(); this.frameId = window.requestAnimationFrame(this.loop); } stopLoop = () => { window.cancelAnimationFrame(this.frameId); clearInterval(this.scalingTimer); } drawCanvas = () => { const { canvasHeight, canvasWidth, graphScale } = this.props; const onsetCanvasCtx = this.canvas.getContext("2d"); onsetCanvasCtx.fillStyle = "grey"; onsetCanvasCtx.fillRect(0, 0, canvasWidth, canvasHeight); onsetCanvasCtx.fillStyle = "blue"; this.thresholdValues.forEach((value, i) => { onsetCanvasCtx.fillRect(i, canvasHeight, 1, -value * graphScale); }); onsetCanvasCtx.fillStyle = "white"; this.onsetValues.forEach((value, i) => { onsetCanvasCtx.fillRect(i, canvasHeight, 1, -value * graphScale); }); onsetCanvasCtx.fillStyle = "black"; this.peakValues.forEach((value, i) => { if (value === true) { onsetCanvasCtx.fillRect(i, canvasHeight, 1, -canvasHeight); } }); } render() { const { canvasHeight, canvasWidth } = this.props; return ( <div style={{ height: canvasHeight, opacity: 0.5, width: canvasWidth, }}> <canvas ref={canvas => { this.canvas = canvas; }} width={canvasWidth} height={canvasHeight} /> </div> ); } } OnsetGraph.propTypes = propTypes; export default connect(mapStateToProps, mapDispatchToProps)(OnsetGraph);
fields/types/url/UrlColumn.js
linhanyang/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var UrlColumn = React.createClass({ displayName: 'UrlColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { var value = this.props.data.fields[this.props.col.path]; if (!value) return; // if the value doesn't start with a prototcol, assume http for the href var href = value; if (href && !/^(mailto\:)|(\w+\:\/\/)/.test(href)) { href = 'http://' + value; } // strip the protocol from the link if it's http(s) var label = value.replace(/^https?\:\/\//i, ''); return ( <ItemsTableValue to={href} padded exterior field={this.props.col.type}> {label} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = UrlColumn;
Example/Example.js
FishErr/react-native-camera
import React from 'react'; import { Image, StatusBar, StyleSheet, TouchableOpacity, View, } from 'react-native'; import Camera from 'react-native-camera'; const styles = StyleSheet.create({ container: { flex: 1, }, preview: { flex: 1, justifyContent: 'flex-end', alignItems: 'center', }, overlay: { position: 'absolute', padding: 16, right: 0, left: 0, alignItems: 'center', }, topOverlay: { top: 0, flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }, bottomOverlay: { bottom: 0, backgroundColor: 'rgba(0,0,0,0.4)', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, captureButton: { padding: 15, backgroundColor: 'white', borderRadius: 40, }, typeButton: { padding: 5, }, flashButton: { padding: 5, }, buttonsSpace: { width: 10, }, }); export default class Example extends React.Component { constructor(props) { super(props); this.camera = null; this.state = { camera: { aspect: Camera.constants.Aspect.fill, captureTarget: Camera.constants.CaptureTarget.cameraRoll, type: Camera.constants.Type.back, orientation: Camera.constants.Orientation.auto, flashMode: Camera.constants.FlashMode.auto, }, isRecording: false }; } takePicture = () => { if (this.camera) { this.camera.capture() .then((data) => console.log(data)) .catch(err => console.error(err)); } } startRecording = () => { if (this.camera) { this.camera.capture({mode: Camera.constants.CaptureMode.video}) .then((data) => console.log(data)) .catch(err => console.error(err)); this.setState({ isRecording: true }); } } stopRecording = () => { if (this.camera) { this.camera.stopCapture(); this.setState({ isRecording: false }); } } switchType = () => { let newType; const { back, front } = Camera.constants.Type; if (this.state.camera.type === back) { newType = front; } else if (this.state.camera.type === front) { newType = back; } this.setState({ camera: { ...this.state.camera, type: newType, }, }); } get typeIcon() { let icon; const { back, front } = Camera.constants.Type; if (this.state.camera.type === back) { icon = require('./assets/ic_camera_rear_white.png'); } else if (this.state.camera.type === front) { icon = require('./assets/ic_camera_front_white.png'); } return icon; } switchFlash = () => { let newFlashMode; const { auto, on, off } = Camera.constants.FlashMode; if (this.state.camera.flashMode === auto) { newFlashMode = on; } else if (this.state.camera.flashMode === on) { newFlashMode = off; } else if (this.state.camera.flashMode === off) { newFlashMode = auto; } this.setState({ camera: { ...this.state.camera, flashMode: newFlashMode, }, }); } get flashIcon() { let icon; const { auto, on, off } = Camera.constants.FlashMode; if (this.state.camera.flashMode === auto) { icon = require('./assets/ic_flash_auto_white.png'); } else if (this.state.camera.flashMode === on) { icon = require('./assets/ic_flash_on_white.png'); } else if (this.state.camera.flashMode === off) { icon = require('./assets/ic_flash_off_white.png'); } return icon; } render() { return ( <View style={styles.container}> <StatusBar animated hidden /> <Camera ref={(cam) => { this.camera = cam; }} style={styles.preview} aspect={this.state.camera.aspect} captureTarget={this.state.camera.captureTarget} type={this.state.camera.type} flashMode={this.state.camera.flashMode} onFocusChanged={() => {}} onZoomChanged={() => {}} defaultTouchToFocus mirrorImage={false} /> <View style={[styles.overlay, styles.topOverlay]}> <TouchableOpacity style={styles.typeButton} onPress={this.switchType} > <Image source={this.typeIcon} /> </TouchableOpacity> <TouchableOpacity style={styles.flashButton} onPress={this.switchFlash} > <Image source={this.flashIcon} /> </TouchableOpacity> </View> <View style={[styles.overlay, styles.bottomOverlay]}> { !this.state.isRecording && <TouchableOpacity style={styles.captureButton} onPress={this.takePicture} > <Image source={require('./assets/ic_photo_camera_36pt.png')} /> </TouchableOpacity> || null } <View style={styles.buttonsSpace} /> { !this.state.isRecording && <TouchableOpacity style={styles.captureButton} onPress={this.startRecording} > <Image source={require('./assets/ic_videocam_36pt.png')} /> </TouchableOpacity> || <TouchableOpacity style={styles.captureButton} onPress={this.stopRecording} > <Image source={require('./assets/ic_stop_36pt.png')} /> </TouchableOpacity> } </View> </View> ); } }
packages/reaxtor-redux-example/client/index.js
trxcllnt/reaxtor
import React from 'react'; import App from '../common/containers/App'; import { Scheduler } from 'rxjs'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { connect } from 'reaxtor-redux'; import { Model } from 'reaxtor-falcor'; import DataSource from 'falcor-http-datasource'; import { configureStore } from '../common/store/configureStore'; const ConnectedApp = connect(App); render( <Provider store={configureStore()}> <ConnectedApp falcor={getRootModel()}/> </Provider>, document.getElementById('app') ) function getRootModel() { return new Model({ scheduler: Scheduler.async, source: new DataSource('/model.json'), cache: window.__PRELOADED_STATE__ || {} }); }
containers/Agreement.js
goominc/goommerce-seller-native
'use strict'; import React from 'react'; import { Alert, StyleSheet, Text, View } from 'react-native'; import Button from 'react-native-button'; import { connect } from 'react-redux' import { authActions } from 'goommerce-redux'; import Icon from '../components/Icon'; import TermsAndConditions from '../components/TermsAndConditions'; import PersonalInfomation from '../components/PersonalInfomation'; const Agreement = React.createClass({ getInitialState() { return { termsAndConditions: false, showTermsAndConditions: false, personalInfo: false, showPersonalInfo: false, }; }, render() { const { termsAndConditions, personalInfo } = this.state; if (this.state.showTermsAndConditions) { return ( <View style={styles.container}> <View style={styles.title}> <Text style={styles.titleText}>์ด์šฉ์•ฝ๊ด€</Text> </View> <TermsAndConditions style={{ backgroundColor: 'white' }}/> <View style={styles.popupButtonBox}> <Button containerStyle={styles.popupButton} style={styles.confirmText} onPress={() => this.setState({ showTermsAndConditions: false })} > ํ™•์ธ </Button> </View> </View> ); } if (this.state.showPersonalInfo) { return ( <View style={styles.container}> <View style={styles.title}> <Text style={styles.titleText}>์ด์šฉ์•ฝ๊ด€</Text> </View> <PersonalInfomation style={{ backgroundColor: 'white' }}/> <View style={styles.popupButtonBox}> <Button containerStyle={styles.popupButton} style={styles.confirmText} onPress={() => this.setState({ showPersonalInfo: false })} > ํ™•์ธ </Button> </View> </View> ); } return ( <View style={styles.container}> <View style={styles.title}> <Text style={styles.titleText}>์•ฝ๊ด€๋™์˜</Text> </View> <View style={styles.main}> <View style={styles.desc}> <Text>๋งํฌ์ƒต์˜ ์„œ๋น„์Šค๋ฅผ ์ด์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š”</Text> <Text>'์ด์šฉ์•ฝ๊ด€ ๋™์˜'์™€ '๊ฐœ์ธ์ •๋ณด ์ˆ˜์ง‘๋ฐฉ์นจ ๋™์˜'๊ฐ€ ํ•„์ˆ˜์ž…๋‹ˆ๋‹ค.</Text> </View> <View style={styles.buttonBox}> <Button onPress={() => this.setState({ termsAndConditions: !termsAndConditions })} containerStyle={styles.button} > <Icon name='checkbox' size={30} color={termsAndConditions ? '#1fcbfb' : 'grey' } /> <Text style={styles.buttonText}>์ด์šฉ์•ฝ๊ด€ ๋™์˜</Text> </Button> <Button style={styles.detailText} onPress={() => this.setState({ showTermsAndConditions: true })} > ๋‚ด์šฉ๋ณด๊ธฐ </Button> </View> <View style={styles.buttonBox}> <Button onPress={() => this.setState({ personalInfo: !personalInfo })} containerStyle={styles.button} > <Icon name='checkbox' size={30} color={personalInfo ? '#1fcbfb' : 'grey' } /> <Text style={styles.buttonText}>๊ฐœ์ธ์ •๋ณด ์ˆ˜์ง‘๋ฐฉ์นจ ๋™์˜</Text> </Button> <Button style={styles.detailText} onPress={() => this.setState({ showPersonalInfo: true })} > ๋‚ด์šฉ๋ณด๊ธฐ </Button> </View> <Button containerStyle={styles.confirmButton} style={styles.confirmText} onPress={() => { if (!this.state.termsAndConditions) { Alert.alert('์ด์šฉ์•ฝ๊ด€์„ ๋™์˜ํ•ด ์ฃผ์„ธ์š”.'); } else if (!this.state.personalInfo) { Alert.alert('๊ฐœ์ธ์ •๋ณด ์ˆ˜์ง‘๋ฐฉ์นจ์„ ๋™์˜ํ•ด ์ฃผ์„ธ์š”.'); } else { this.props.updateAgreements({ seller: 1, personalInfomation: 1 }); } }} > ์•ฝ๊ด€ ๋™์˜ํ•˜๊ธฐ </Button> </View> </View> ); }, }); const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f2f2f2', alignItems: 'center', paddingTop: 20, // FIXME: StatusBar iOS }, title: { height: 44, justifyContent: 'center', alignSelf: 'stretch', alignItems: 'center', backgroundColor: '#3f4c5d', }, titleText: { color: 'white', fontWeight: 'bold', }, main: { alignItems: 'center', paddingVertical: 10, }, desc: { flex: 1, alignItems: 'center', paddingVertical: 20, }, buttonBox: { backgroundColor: 'white', alignItems: 'center', alignSelf: 'stretch', flexDirection: 'row', justifyContent: 'space-between', height: 50, marginVertical: 2, marginHorizontal: 10, }, button: { marginLeft: 10, }, buttonText: { marginHorizontal: 10, fontWeight: 'bold', }, detailText: { fontSize: 12, marginHorizontal: 10, color: 'grey', }, confirmButton: { backgroundColor: '#1fcbf6', borderRadius: 6, marginTop: 20, overflow:'hidden', paddingHorizontal: 60, paddingVertical: 10, }, confirmText: { color: 'white', }, popupButtonBox: { height: 60, justifyContent: 'center', alignSelf: 'stretch', alignItems: 'center', backgroundColor: 'white', }, popupButton: { backgroundColor: '#1fcbf6', borderRadius: 6, overflow:'hidden', paddingHorizontal: 60, paddingVertical: 10, }, }); export default connect( (state) => ({ auth: state.auth }) , authActions )(Agreement);
src/form/FieldRow.js
carab/Pinarium
import React from 'react' import {makeStyles} from '@material-ui/styles' const useStyles = makeStyles(theme => ({ root: { padding: theme.spacing.unit * 2, display: 'flex', flexWrap: 'wrap', '& > *': { margin: theme.spacing.unit, }, }, })) export default function FieldRow({children}) { const classes = useStyles() return <div className={classes.root}>{children}</div> }
app/containers/App.js
transparantnederland/relationizer
import React from 'react'; import NavContainer from './NavContainer'; import FlagModalContainer from './FlagModalContainer'; import './app.css'; const App = React.createClass({ render() { return ( <div className="App"> <NavContainer /> {this.props.children} <FlagModalContainer /> </div> ); }, }); export default App;
src/main/app/scripts/routes/index.js
ondrejhudek/pinboard
import React from 'react' import { Route, IndexRoute, Redirect } from 'react-router' import auth from '../services/auth/login' import Layout from '../layouts/Layout' /* views */ import HomeView from '../views/Home' import LostPasswordView from '../views/LostPassword' import DashboardView from '../views/Dashboard' import NoteView from '../views/Note' import TodoView from '../views/Todo' import CalendarView from '../views/Calendar' import SettingsView from '../views/Settings' import NotFoundView from '../views/NotFound' import LogoutView from '../views/Logout' function requireAuth(nextState, replace) { if (!auth.loggedIn()) { replace({ pathname: '/signin', state: {nextPathname: nextState.location.pathname} }) } } function notRequireAuth(nextState, replace) { if (auth.loggedIn()) { replace({ pathname: '/', state: {nextPathname: nextState.location.pathname} }) } } export default ( <Route path='/' component={Layout}> <IndexRoute component={DashboardView} onEnter={requireAuth}/> <Route path='signin' component={HomeView} onEnter={notRequireAuth}/> <Route path="signout" component={LogoutView}/> <Route path='lost-password' component={LostPasswordView} onEnter={notRequireAuth}/> <Route path='dashboard' component={DashboardView} onEnter={requireAuth}/> <Route path='note' component={NoteView} onEnter={requireAuth}/> <Route path='todo' component={TodoView} onEnter={requireAuth}/> <Route path='calendar' component={CalendarView} onEnter={requireAuth}/> <Route path='settings' component={SettingsView} onEnter={requireAuth}/> <Route path='404' component={NotFoundView}/> <Redirect from='*' to='/404'/> </Route> )