path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
packages/node_modules/@webex/react-component-presence-avatar/src/index.js
ciscospark/react-ciscospark
import React from 'react'; import PropTypes from 'prop-types'; import {Avatar} from '@momentum-ui/react'; import { PRESENCE_TYPE_ACTIVE, PRESENCE_TYPE_INACTIVE, PRESENCE_TYPE_DND, PRESENCE_TYPE_OOO } from '@webex/redux-module-presence'; import './momentum.scss'; const propTypes = { image: PropTypes.string, isSelfAvatar: PropTypes.bool, isTyping: PropTypes.bool, onClick: PropTypes.func, name: PropTypes.string, size: PropTypes.oneOfType([ PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge']), PropTypes.number ]), spaceType: PropTypes.string, presenceStatus: PropTypes.string }; const defaultProps = { image: undefined, isSelfAvatar: false, isTyping: false, name: undefined, onClick: undefined, size: 40, spaceType: undefined, presenceStatus: undefined }; function PresenceAvatar(props) { const { image, isSelfAvatar, isTyping, name, onClick, size, spaceType, presenceStatus } = props; let type = ''; // Do not show presence on self avatars if (!isSelfAvatar) { switch (presenceStatus) { case PRESENCE_TYPE_ACTIVE: type = 'active'; break; case PRESENCE_TYPE_INACTIVE: type = 'inactive'; break; case PRESENCE_TYPE_OOO: type = 'ooo'; break; case PRESENCE_TYPE_DND: type = 'dnd'; break; default: type = ''; } if (isTyping) { type = 'typing'; } if (spaceType === 'group') { type = 'group'; } } else { type = 'self'; } return ( <Avatar onClick={onClick} title={name} type={type} src={image} size={size} /> ); } PresenceAvatar.propTypes = propTypes; PresenceAvatar.defaultProps = defaultProps; export default PresenceAvatar;
site/IndexPage.js
hiddentao/react-dnd
import './base.less'; import Constants, { APIPages, ExamplePages, Pages } from './Constants'; import HomePage from './pages/HomePage'; import APIPage from './pages/APIPage'; import ExamplePage from './pages/ExamplePage'; import React, { Component } from 'react'; const APIDocs = { OVERVIEW: require('../docs/00 Quick Start/Overview.md'), TUTORIAL: require('../docs/00 Quick Start/Tutorial.md'), TESTING: require('../docs/00 Quick Start/Testing.md'), FAQ: require('../docs/00 Quick Start/FAQ.md'), TROUBLESHOOTING: require('../docs/00 Quick Start/Troubleshooting.md'), DRAG_SOURCE: require('../docs/01 Top Level API/DragSource.md'), DRAG_SOURCE_MONITOR: require('../docs/03 Monitoring State/DragSourceMonitor.md'), DRAG_SOURCE_CONNECTOR: require('../docs/02 Connecting to DOM/DragSourceConnector.md'), DROP_TARGET: require('../docs/01 Top Level API/DropTarget.md'), DROP_TARGET_CONNECTOR: require('../docs/02 Connecting to DOM/DropTargetConnector.md'), DROP_TARGET_MONITOR: require('../docs/03 Monitoring State/DropTargetMonitor.md'), DRAG_DROP_CONTEXT: require('../docs/01 Top Level API/DragDropContext.md'), DRAG_LAYER: require('../docs/01 Top Level API/DragLayer.md'), DRAG_LAYER_MONITOR: require('../docs/03 Monitoring State/DragLayerMonitor.md'), HTML5_BACKEND: require('../docs/04 Backends/HTML5.md'), TEST_BACKEND: require('../docs/04 Backends/Test.md') }; const Examples = { CHESSBOARD_TUTORIAL_APP: require('../examples/00 Chessboard/Tutorial App'), DUSTBIN_SINGLE_TARGET: require('../examples/01 Dustbin/Single Target'), DUSTBIN_MULTIPLE_TARGETS: require('../examples/01 Dustbin/Multiple Targets'), DUSTBIN_STRESS_TEST: require('../examples/01 Dustbin/Stress Test'), DRAG_AROUND_NAIVE: require('../examples/02 Drag Around/Naive'), DRAG_AROUND_CUSTOM_DRAG_LAYER: require('../examples/02 Drag Around/Custom Drag Layer'), NESTING_DRAG_SOURCES: require('../examples/03 Nesting/Drag Sources'), NESTING_DROP_TARGETS: require('../examples/03 Nesting/Drop Targets'), SORTABLE_SIMPLE: require('../examples/04 Sortable/Simple'), SORTABLE_CANCEL_ON_DROP_OUTSIDE: require('../examples/04 Sortable/Cancel on Drop Outside'), SORTABLE_STRESS_TEST: require('../examples/04 Sortable/Stress Test'), CUSTOMIZE_HANDLES_AND_PREVIEWS: require('../examples/05 Customize/Handles and Previews'), CUSTOMIZE_DROP_EFFECTS: require('../examples/05 Customize/Drop Effects') }; export default class IndexPage extends Component { static getDoctype() { return '<!doctype html>'; } static renderToString(props) { return IndexPage.getDoctype() + React.renderToString(<IndexPage {...props} />); } constructor(props) { super(props); this.state = { renderPage: !this.props.devMode }; } render() { // Dump out our current props to a global object via a script tag so // when initialising the browser environment we can bootstrap from the // same props as what each page was rendered with. const browserInitScriptObj = { __html: 'window.INITIAL_PROPS = ' + JSON.stringify(this.props) + ';\n' }; return ( <html> <head> <meta charSet="utf-8" /> <title>React DnD</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" /> <link rel="stylesheet" type="text/css" href={this.props.files['main.css']} /> <base target="_blank" /> </head> <body> {this.state.renderPage && this.renderPage()} <script dangerouslySetInnerHTML={browserInitScriptObj} /> <script src={this.props.files['main.js']}></script> </body> </html> ); } renderPage() { switch (this.props.location) { case Pages.HOME.location: return <HomePage />; } for (let groupIndex in APIPages) { const group = APIPages[groupIndex]; const pageKeys = Object.keys(group.pages); for (let i = 0; i < pageKeys.length; i++) { const key = pageKeys[i]; const page = group.pages[key]; if (this.props.location === page.location) { return <APIPage example={page} html={APIDocs[key]} />; } } } for (let groupIndex in ExamplePages) { const group = ExamplePages[groupIndex]; const pageKeys = Object.keys(group.pages); for (let i = 0; i < pageKeys.length; i++) { const key = pageKeys[i]; const page = group.pages[key]; const Component = Examples[key]; if (this.props.location === page.location) { return ( <ExamplePage example={page}> <Component /> </ExamplePage> ); } } } throw new Error( 'Page of location ' + JSON.stringify(this.props.location) + ' not found.' ); } componentDidMount() { if (!this.state.renderPage) { this.setState({ renderPage: true }); } } }
public/src/routes/home.js
rafaelfbs/rmodel
import React from 'react'; import { observer } from 'mobx-react'; import UserForm from '../forms/user_form'; import Form from '../components/form/index'; @observer export default class Home extends React.Component { render () { return <div className="container"> <div className="card"> <div className="card-content"> <Form form={UserForm} buttons={[ {name: 'Add'} ]}/> </div> </div> </div> } }
tests/react/createElementRequiredProp_string.js
gabro/flow
// @flow import React from 'react'; class Bar extends React.Component { props: { test: number, }; render() { return ( <div> {this.props.test} </div> ) } } class Foo extends React.Component { render() { const Cmp = Math.random() < 0.5 ? 'div' : Bar; return (<Cmp/>); } }
packages/ringcentral-widgets/components/ActiveCallPanel/CallInfo.js
ringcentral/ringcentral-js-widget
import React from 'react'; import PropTypes from 'prop-types'; import ContactDisplay from '../ContactDisplay'; import styles from './styles.scss'; import CallAvatar from '../CallAvatar'; export default function CallInfo(props) { let avatar; if (props.avatarUrl) { avatar = <CallAvatar avatarUrl={props.avatarUrl} />; } else { avatar = <CallAvatar avatarUrl={null} />; } return ( <div className={styles.userInfo}> <div className={styles.avatarContainer}> <div className={styles.avatar}>{avatar}</div> </div> <div className={styles.userName}> {props.callQueueName} <ContactDisplay className={styles.contactDisplay} selectClassName={styles.dropdown} contactMatches={props.nameMatches} phoneNumber={props.phoneNumber} fallBackName={props.fallBackName} currentLocale={props.currentLocale} areaCode={props.areaCode} countryCode={props.countryCode} showType={false} selected={props.selectedMatcherIndex} onSelectContact={props.onSelectMatcherName} isLogging={false} enableContactFallback brand={props.brand} showPlaceholder={props.showContactDisplayPlaceholder} sourceIcons={props.sourceIcons} phoneTypeRenderer={props.phoneTypeRenderer} phoneSourceNameRenderer={props.phoneSourceNameRenderer} /> </div> <div className={styles.userPhoneNumber} data-sign="userPhoneNumber"> {props.formatPhone(props.phoneNumber)} </div> </div> ); } CallInfo.propTypes = { phoneNumber: PropTypes.string, formatPhone: PropTypes.func.isRequired, nameMatches: PropTypes.array.isRequired, fallBackName: PropTypes.string.isRequired, areaCode: PropTypes.string.isRequired, countryCode: PropTypes.string.isRequired, currentLocale: PropTypes.string.isRequired, selectedMatcherIndex: PropTypes.number.isRequired, onSelectMatcherName: PropTypes.func.isRequired, avatarUrl: PropTypes.string, brand: PropTypes.string, showContactDisplayPlaceholder: PropTypes.bool, sourceIcons: PropTypes.object, phoneTypeRenderer: PropTypes.func, phoneSourceNameRenderer: PropTypes.func, callQueueName: PropTypes.string, }; CallInfo.defaultProps = { phoneNumber: null, avatarUrl: null, brand: 'RingCentral', showContactDisplayPlaceholder: true, sourceIcons: undefined, phoneTypeRenderer: undefined, phoneSourceNameRenderer: undefined, callQueueName: null, };
react-native-pagination/index.js
garrettmac/react-native-pagination
/** * @author garrettmac <garrett@vyga.io> (http://vyga.io) * @version 1.0.4 * @module ReactNativePagination (https://github.com/garrettmac/react-native-pagination) */ import React, { Component } from 'react'; import { Dimensions, LayoutAnimation, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import _ from 'lodash'; _.mixin({ compactObject: (o) => _.each(o, (v, k) => { if (!v) delete o[k]; }) }); import Icon from './components/Icon'; import Dot from './components/Dot'; const { width, height } = Dimensions.get('window'); import PropTypes from 'prop-types'; /* * Helper functions * Export default class Pagination extends Component { */ class Pagination extends Component { render() { let { iconFamily, textStyle, containerStyle, nextButtonStyle, backButtonStyle, backwardStyle, dotStyle, backText, backStyle, nextText, nextStyle, paginationItemPadSize, paginationVisibleItems, paginationItems, horizontal, startDotStyle, DotComponent, endDotStyle, debugMode, dotAnimation, dotAnimationType, paginationStyle, pagingEnabled, // ShowStartingJumpDot,showEndingJumpDot,endingJumpSize,startingJumpSize, hideEmptyDots } = this.props; paginationItems = paginationItems.map((item, i) => { item.paginationIndexId = i; item.index = i; item.paginationHasSeenItem = false; item.paginationHasPressedItem = false; item.paginationSelectedItem = false; return item; }); // PaginationVisibleItemsIndexList this list of index that you want to remove or you'll see two active icon buttons const paginationVisibleItemsIndexList = paginationVisibleItems.map((i) => i.index); if (pagingEnabled) // Fix issue where it says two visable list items are active when only one should be if (paginationVisibleItemsIndexList.length > 1) { paginationVisibleItems = paginationVisibleItems.map((o) => { if (o.index === _.min(paginationVisibleItemsIndexList)) return { index: _.get(o, 'index'), key: _.get(o, 'key'), item: _.get(o, 'item', {}), isViewable: false }; return o; }); } // Gets max and min pads. should look something like [0, -1, -2, 2, 3, 4] if [0,1] are viewable and paginationItemPadSize is 3 const getVisibleArrayIndexes = (paginationVisibleItems, paginationVisibleItemsIndexList, paginationItemPadSize) => { const preIniquePaddedIndexList = [ ..._.times(paginationItemPadSize, (i) => _.min(paginationVisibleItemsIndexList) - (i + 1)), ..._.times(paginationItemPadSize, (i) => _.max(paginationVisibleItemsIndexList) + (i + 1)) ], uniquePaddedIndexList = preIniquePaddedIndexList.map((num, i) => { if (num < 0) return _.max(paginationVisibleItemsIndexList) + (num *= -1); return num; }); return _.uniq(uniquePaddedIndexList); }, paginationVisableItemsIndexArray = getVisibleArrayIndexes(paginationVisibleItems, paginationVisibleItemsIndexList, paginationItemPadSize), paginationVisiblePadItems = paginationVisableItemsIndexArray.map((o, i) => ({ index: _.get(paginationItems, `[${o}].paginationIndexId`), key: _.get(paginationItems, `[${o}].paginationIndexId`), item: _.get(paginationItems, `[${o}]`, {}), isViewable: false })), flatListPaginationItems = _.sortBy([ ...paginationVisibleItems, ...paginationVisiblePadItems ], 'index'); if (debugMode) { const paginationItemsIndexList = paginationItems.map((i) => i.index), allDotsIndexList = flatListPaginationItems.map((i) => i.index), NOT_ACTIVE_DOTS_INDEXES = _.sortBy(paginationVisiblePadItems.map((i) => i.index)), ALL_DOTS_INDEXES = flatListPaginationItems.map((i) => i.isViewable), ___ = '%c __________________________________________\n', ADBY = `%c all paginationVisibleItems dots: ${allDotsIndexList} \n`, ADI = `%c active paginationVisibleItems dots: ${paginationVisibleItemsIndexList} \n`, ANDI = `%c not active dots: (padding): ${NOT_ACTIVE_DOTS_INDEXES} \n`, ADI_ISVIEWABLE = `%c each "paginationVisibleItems dots" "isViewable" attribute:\n ${ALL_DOTS_INDEXES} \n`, AID = `%c all "paginationItems"'s': ${paginationItemsIndexList} \n`; console.log(`${'\n\n%cGarrett Mac\'s React Native Pagination' + '%c \ndebugMode: ON\n'}${___}${ADBY}${ADI}${ANDI}${___}${ADI_ISVIEWABLE}${___}${AID}`, 'color: #01a699', 'color: #f99137', 'color: #f99137', 'color: #a94920', 'color: #00a7f8', 'color: #3b539a', 'color: #32db64', 'color: #00c59e', 'color: #3b539a', 'color: #488aff'); } let verticalStyle = { height, alignItems: 'center', justifyContent: 'space-between', position: 'absolute', top: 0, margin: 0, bottom: 0, right: 0, bottom: 0, padding: 0, flex: 1 }, horizontalStyle = { width, alignItems: 'center', justifyContent: 'space-between', position: 'absolute', margin: 0, bottom: 10, left: 0, right: 0, padding: 0, flex: 1 }; if (horizontal === true)PaginationContainerStyle = horizontalStyle; else if (paginationStyle)PaginationContainerStyle = paginationStyle; else PaginationContainerStyle = verticalStyle; return ( <View style={[ PaginationContainerStyle, containerStyle ]} > <View style={[ { flex: 1, marginTop: horizontal === true ? 0 : 20, marginBottom: horizontal === true ? 0 : 20, marginLeft: horizontal === true ? 5 : 0, marginRight: horizontal === true ? 5 : 0, width: horizontal === true ? width : 40, height: horizontal === false ? height : 30, flexDirection: horizontal == true ? 'row' : 'column', justifyContent: 'center', alignItems: 'center' } ]} > <Dot StartDot {...this.props} onPress={this.onStartDotPress} styles={[ dotStyle, startDotStyle ]} /> {/* {showStartingJumpDot && <Dot jumpItems={flatListPaginationItems} endingJumpSize={(endingJumpSize)?endingJumpSize:5} {...this.props} styles={[dotStyle,endDotStyle]}/> } */} {flatListPaginationItems.map((item, i) => { if(dotAnimation){ LayoutAnimation.configureNext(dotAnimationType); } return (<View key={i} style={{flex:1}}> {!DotComponent && <Dot {...this.props} key={`paginationDot${i}`} item={item} /> } {DotComponent && <DotComponent {...this.props} key={`paginationDot${i}`} /> } </View>) })} {/* {showEndingJumpDot && <Dot jumpItems={flatListPaginationItems} startingJumpSize={(startingJumpSize)?startingJumpSize:5} {...this.props} styles={[dotStyle,endDotStyle]}/> } */} <Dot EndDot {...this.props} onPress={this.onEndDotPress} styles={[ dotStyle, endDotStyle ]} /> </View> </View> ); } } const s = StyleSheet.create({ container: { } }); Pagination.defaultProps = { // ContainerStyle:{flex: 1,backgroundColor:"red",width,height:null}, containerStyle: null, // TextStyle:{color:"rgba(0,0,0,0.5)",textAlign: "center",}, paginationVisibleItems: [], paginationItems: [], horizontal: false, pageRangeDisplayed: 10, hideEmptyDots: false, activeItemIndex: null, hideEmptyDotComponents: false, paginationItemPadSize: 3, dotAnimation:true, dotAnimationType: LayoutAnimation.Presets.easeInEaseOut }; // NOT WORKING (I dont know why) Pagination.propTypes = { paginationItems: PropTypes.array, visableItemList: PropTypes.array }; export default Pagination; export { Icon, Dot };
frontend/src/Components/Table/Cells/TableSelectCell.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import CheckInput from 'Components/Form/CheckInput'; import TableRowCell from './TableRowCell'; import styles from './TableSelectCell.css'; class TableSelectCell extends Component { // // Lifecycle componentDidMount() { const { id, isSelected, onSelectedChange } = this.props; onSelectedChange({ id, value: isSelected }); } componentWillUnmount() { const { id, onSelectedChange } = this.props; onSelectedChange({ id, value: null }); } // // Listeners onChange = ({ value, shiftKey }, a, b, c, d) => { const { id, onSelectedChange } = this.props; onSelectedChange({ id, value, shiftKey }); }; // // Render render() { const { className, id, isSelected, ...otherProps } = this.props; return ( <TableRowCell className={className}> <CheckInput className={styles.input} name={id.toString()} value={isSelected} {...otherProps} onChange={this.onChange} /> </TableRowCell> ); } } TableSelectCell.propTypes = { className: PropTypes.string.isRequired, id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, isSelected: PropTypes.bool.isRequired, onSelectedChange: PropTypes.func.isRequired }; TableSelectCell.defaultProps = { className: styles.selectCell, isSelected: false }; export default TableSelectCell;
dashboard/src/components/commons/Footer.js
leapfrogtechnology/chill
import React from 'react'; /** * Renders footer component */ const Footer = () => { return ( <div className="footer"> <div className="container"> Powered by <a target="_blank" rel="noopener noreferrer" href="https://github.com/leapfrogtechnology/chill"> Chill </a> </div> </div> ); }; export default Footer;
client/scripts/components/blue-button/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; export function BlueButton (props) { return ( <button {...props} className={`${styles.container} ${props.className}`} > {props.children} </button> ); }
src/svg-icons/image/brightness-3.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrightness3 = (props) => ( <SvgIcon {...props}> <path d="M9 2c-1.05 0-2.05.16-3 .46 4.06 1.27 7 5.06 7 9.54 0 4.48-2.94 8.27-7 9.54.95.3 1.95.46 3 .46 5.52 0 10-4.48 10-10S14.52 2 9 2z"/> </SvgIcon> ); ImageBrightness3 = pure(ImageBrightness3); ImageBrightness3.displayName = 'ImageBrightness3'; ImageBrightness3.muiName = 'SvgIcon'; export default ImageBrightness3;
src/router.js
ykx456654/hr_admin
import React from 'react' import PropTypes from 'prop-types' import { Router } from 'dva/router' import App from './routes/app' const registerModel = (app, model) => { if (!(app._models.filter(m => m.namespace === model.namespace).length === 1)) { app.model(model) } } const Routers = function ({ history, app }) { const routes = [ { path: '/', component: App, getIndexRoute (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/article')) cb(null, { component: require('./routes/article/list') }) }, 'article-list') }, childRoutes: [ { path:'/article', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/article')) cb(null, require('./routes/article/')) }, 'article') } }, { path:'/articleList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/article')) cb(null, require('./routes/article/list')) }, 'article') } }, { path:'/video', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/video')) cb(null, require('./routes/video/')) }, 'video') } }, { path:'/videoList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/video')) cb(null, require('./routes/video/list')) }, 'video') } }, { path:'/bannerList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/banner')) cb(null, require('./routes/banner/list')) }, 'banner') } }, { path:'/banner', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/banner')) cb(null, require('./routes/banner')) }, 'banner') } }, { path:'/subjectList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/subject')) cb(null, require('./routes/subject/list')) }, 'subject') } }, { path:'/subject', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/subject')) cb(null, require('./routes/subject')) }, 'subject') } }, { path:'/broadcastList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/broadcast')) cb(null, require('./routes/broadcast/list')) }, 'broadcast') } }, { path:'/broadcast', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/broadcast')) cb(null, require('./routes/broadcast')) }, 'broadcast') } }, { path:'/saleList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/sale')) cb(null, require('./routes/sale/list')) }, 'sale') } }, { path:'/sale', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/sale')) cb(null, require('./routes/sale')) }, 'sale') } }, { path:'/linkList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/link')) cb(null, require('./routes/link/list')) }, 'link') } }, { path:'/link', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/link')) cb(null, require('./routes/link')) }, 'link') } }, { path:'/qrcodeList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/qrcode')) cb(null, require('./routes/qrcode/list')) }, 'qrcode') } }, { path:'/academiaLinkList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/academia')) cb(null, require('./routes/academia/academiaLinkList/')) }, 'academia-link-list') }, }, { path:'/questions', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/questions')) cb(null, require('./routes/questions/')) }, 'questions') } }, { path:'/academiaVideoList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/academia')) cb(null, require('./routes/academia/academiaVideoList/')) }, 'academia-video-list') }, }, { path:'/newsList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/news')) cb(null, require('./routes/news/newsList/')) }, 'news-list') }, }, { path:'/lectureList', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/lecture')) cb(null, require('./routes/lecture/lectureList')) }, 'lecture-list') }, }, { path: '/login', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/login')) cb(null, require('./routes/login/')) }, 'login') }, }, { path: '/push', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/push')) cb(null, require('./routes/push/')) }, 'push') }, }, { path: '/quesType', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/quesType')) cb(null, require('./routes/quesType/')) }, 'quesType') }, }, { path: '/tags', getComponent (nextState, cb) { require.ensure([], require => { registerModel(app, require('./models/tags')) cb(null, require('./routes/tags/')) }, 'tags') }, }, { path: '*', getComponent (nextState, cb) { require.ensure([], require => { cb(null, require('./routes/error/')) }, 'error') }, }, ], }, ] return <Router history={history} routes={routes} /> } Routers.propTypes = { history: PropTypes.object, app: PropTypes.object, } export default Routers
components/Cage/Cage.js
sloiselle/reptile
import React from 'react'; import SkyLight from 'react-skylight'; import classnames from 'classnames/bind'; import styles from './Cage.scss'; const cx = classnames.bind(styles); // const Cage = ({cageNumber, temp='N/A', hum='N/A', lightOn, alert, empty}) => { class Cage extends React.Component { constructor(props) { super(props); } render() { let cageNumberRow, cageTempRow, cageHumidityRow, modalTitle, feedingTime, feedingItem, feedingQty; if (!this.props.empty) { cageNumberRow = <p onClick={() => this.refs.CageModal.show()} className={cx('Cage-number')}>Cage {this.props.cageNumber}</p>; cageTempRow = <p onClick={() => this.refs.CageModal.show()} className={cx('Cage-text')}><span className={cx('Cage-text-label')}>Temp:</span> {this.props.temp}&#8457;</p>; cageHumidityRow = <p onClick={() => this.refs.CageModal.show()} className={cx('Cage-text')}><span className={cx('Cage-text-label')}>Humidity:</span> {this.props.hum}%</p>; modalTitle = `Cage ${this.props.cageNumber}`; } if (this.props.feedings !== undefined) { feedingTime = this.props.feedings[0].date; feedingItem = this.props.feedings[0].item; if (this.props.feedings[0].qty > 0) { feedingQty = `(x${this.props.feedings[0].qty})`; } } return ( <div className={cx( 'Cage', {'Cage-light': this.props.lightOn}, {'Cage-alert': this.props.alert}, {'Cage-empty': this.props.empty} )} > {cageNumberRow} {cageTempRow} {cageHumidityRow} <SkyLight hideOnOverlayClicked className={cx('Cage-modal')} ref="CageModal" title={modalTitle}> <div className={cx('Cage-modal-details')}> <img alt={this.props.species} width={260} height={173} className={cx('Cage-modal-image')} src='https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/Varanus_salvator_-_01.jpg/260px-Varanus_salvator_-_01.jpg' /> <div className={cx('Cage-modal-details-block')}> <p><span className={cx('Cage-modal-title')}>Name: </span>{this.props.name}</p> <p><span className={cx('Cage-modal-title')}>Species: </span>{this.props.species}</p> <p><span className={cx('Cage-modal-title')}>Sex: </span>{this.props.sex}</p> </div> <div className={cx('Cage-modal-details-block')}> <p><span className={cx('Cage-modal-title')}>Last Feeding: </span>{feedingTime}</p> <p><span className={cx('Cage-modal-title')}>Item(s) Fed: </span>{feedingItem} {feedingQty}</p> <p><span className={cx('Cage-modal-title')}>Temperature: </span>{this.props.temp}&#8457;</p> <p><span className={cx('Cage-modal-title')}>Humidity: </span>{this.props.hum}%</p> </div> </div> <div className={cx('Cage-modal-details')}> <p><span className={cx('Cage-modal-title')}>Description: </span>{this.props.desc}</p> </div> </SkyLight> </div> ); } }; Cage.displayName = 'Cage'; export default Cage;
src/js/app.js
dmitriidar/BabyTap
import React from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import ReactDOM from 'react-dom'; import { Container, createApp, UI, View, ViewManager } from 'touchstonejs'; // App Config // ------------------------------ const images = [ { imageUrl: "img/gallery/1.png", soundUrl: "/android_asset/www/audio/1.mp3", title: "0" }, { imageUrl: "img/gallery/1.png", soundUrl: "/android_asset/www/audio/1.mp3", title: "1" }, { imageUrl: "img/gallery/1.png", soundUrl: "/android_asset/www/audio/1.mp3", title: "2" } ] var App = React.createClass({ mixins: [createApp()], childContextTypes: { peopleStore: React.PropTypes.object }, getChildContext () { return { }; }, componentDidMount () { // Hide the splash screen when the app is mounted if (navigator.splashscreen) { navigator.splashscreen.hide(); } }, buildImageView (images) { return images.map(function(image, index){ return <View galleryLength={images.length} key={index} viewKey={index} name={"image-" + index} image={image} component={require('./views/transitions')} />; }); }, render () { let appWrapperClassName = 'app-wrapper device--' + (window.device || {}).platform return ( <div className={appWrapperClassName}> <div className="device-silhouette"> <Container> <ViewManager ref="vm" name="app" defaultView="image-0"> {this.buildImageView(images)} </ViewManager> </Container> </div> </div> ); } }); function startApp () { if (window.StatusBar) { window.StatusBar.styleDefault(); } ReactDOM.render(<App />, document.getElementById('app')); } if (!window.cordova) { startApp(); } else { document.addEventListener('deviceready', startApp, false); }
app/components/loaders/ProgressBar.ios.js
mol42/iett-asistani
/* @flow */ import React, { Component } from 'react'; import { ProgressViewIOS } from 'react-native'; export default class ProgressBarNB extends Component { render() { return ( <ProgressViewIOS {...this.props} progress={this.props.progress ? this.props.progress / 100 : 0.5} progressTintColor={this.props.color ? this.props.color : '#FFF'} trackTintColor='rgba(255,255,255,0.5)' /> ); } }
src/components/attributes/scatter-plot/Data.js
jjeffreyma/ID3-React
import React from 'react'; export default (props) => { // console.log('Data', props); return( <div> </div> ); }
src/containers/DevTools/DevTools.js
martinval/boiler2
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="H" changePositionKey="Q"> <LogMonitor /> </DockMonitor> );
examples/normalization/src/components/CreateButton.js
lore/lore
import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import _ from 'lodash'; export default createReactClass({ displayName: 'CreateButton', onClick: function() { lore.dialog.show(function() { return lore.dialogs.tweet.create({ request: function(data) { return lore.actions.tweet.create(_.assign({}, data, { createdAt: new Date().toISOString() })).payload; } }); }); }, render: function() { return ( <button type="button" className="btn btn-primary btn-lg create-button" onClick={this.onClick}> + </button> ); } });
actor-apps/app-web/src/app/components/modals/preferences/Session.react.js
gaolichuang/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ import React, { Component } from 'react'; import { Container } from 'flux/utils'; import PreferencesActionCreators from 'actions/PreferencesActionCreators'; import PreferencesStore from 'stores/PreferencesStore'; class SessionItem extends Component { static getStores = () => [PreferencesStore]; static calculateState = () => {}; static propTypes = { appTitle: React.PropTypes.string.isRequired, holder: React.PropTypes.string.isRequired, id: React.PropTypes.number.isRequired, authTime: React.PropTypes.object.isRequired }; onTerminate = () => PreferencesActionCreators.terminateSession(this.props.id); render() { const { appTitle, holder, authTime } = this.props; const currentDevice = (holder === 'THIS_DEVICE') ? <small>Current session</small> : null; return ( <li className="session-list__session"> <div className="title"> {appTitle} {currentDevice} </div> <small><b>Auth time:</b> {authTime.toString()}</small> <a className="session-list__session__terminate link--blue" onClick={this.onTerminate}>Kill</a> </li> ) } } export default Container.create(SessionItem);
frontWeb/main/react/react-router/basic/dev/ambiguousExample.js
skycolor/study
import React from 'react' import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom' const AmbiguousExample = () => ( <Router> <div> <ul> <li><Link to="/about">About Us (static)</Link></li> <li><Link to="/company">Company (static)</Link></li> <li><Link to="/kim">Kim (dynamic)</Link></li> <li><Link to="/chris">Chris (dynamic)</Link></li> </ul> {/* Sometimes you want to have a whitelist of static paths like "/about" and "/company" but also allow for dynamic patterns like "/:user". The problem is that "/about" is ambiguous and will match both "/about" and "/:user". Most routers have an algorithm to decide for you what it will match since they only allow you to match one "route". React Router lets you match in multiple places on purpose (sidebars, breadcrumbs, etc). So, when you want to clear up any ambiguous matching, and not match "/about" to "/:user", just wrap your <Route>s in a <Switch>. It will render the first one that matches. */} <Switch> <Route path="/about" component={About}/> <Route path="/company" component={Company}/> <Route path="/:user" component={User}/> </Switch> </div> </Router> ) const About = () => <h2>About</h2> const Company = () => <h2>Company</h2> const User = ({ match }) => ( <div> <h2>User: {match.params.user}</h2> </div> ) export default AmbiguousExample
src/pages/places/MeetingPoint.js
ayltai/fishing-club
// @flow 'use strict'; import React from 'react'; import muiThemeable from 'material-ui/styles/muiThemeable'; import { Card, CardMedia, CardTitle, CardText } from 'material-ui/Card'; import LazyLoad from 'react-lazy-load'; import ReactGA from 'react-ga'; import './MeetingPoint.css'; import RaftEveningImage from '../../images/raft-evening.jpg'; import SamPuiChauPierImage from '../../images/sam-pui-chau-pier.jpg'; import TsengTauTsuenImage from '../../images/tseng-tau-tsuen.jpg'; import YungShueORaftImage from '../../images/yung-shue-o-raft.jpg'; class MeetingPoint extends React.Component { componentDidMount() : void { window.scrollTo(0, 0); } render() : any { return ( <div> <Card className="meetingPointItem"> <CardMedia> <img src={TsengTauTsuenImage} style={{ maxWidth : '100%' }} /> </CardMedia> <CardTitle title={<div><strong>11:30 AM</strong> Tseng Tau Tsuen (井頭村) Minibus Terminus</div>} /> <CardText> <p>If you take Green Minibus <a href="http://www.16seats.net/eng/gmb/gn_807k.html" title="Minibus route 807K" target="_blank">route 807K</a>, it will take you to Tseng Tau Tsuen at the last stop.</p> <p>It should not be too difficult to walk to there even if you take other routes. Click <a href="/places/getting-there" title="Getting there">here</a> to learn how you can get there.</p> <LazyLoad width={768} height={450} onContentVisible={() : void => ReactGA.event({ category : 'Meeting Point', action : 'Display', label : 'Google Map (Tseng Tau Tsuen Minibus Terminus)' })}> <div style={{ textAlign : 'center' }}> <div dangerouslySetInnerHTML={{ __html : '<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d118076.89549807012!2d114.09542218135105!3d22.357291765113327!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x34040f135a9753fd%3A0x7b16803ad7ba2578!2sTseng+Tau+Tsuen!5e0!3m2!1sen!2shk!4v1497718219869" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>' }} /> </div> </LazyLoad> <p>There are 3 piers near Tseng Tau Tsuen. We will walk 10 minutes to the farthest one, Kei Ling Ha Hoi Pier (企嶺下海碼頭), aka Sam Pui Chau Pier (三杯酒碼頭).</p> </CardText> </Card> <Card className="meetingPointItem"> <CardMedia> <img src={SamPuiChauPierImage} style={{ maxWidth : '100%' }} /> </CardMedia> <CardTitle title={<div>Sam Pui Chau Pier (三杯酒碼頭)</div>} /> <CardText> <p>We will walk from the minibus terminus to the pier. Part of the road is covered by trees.</p> <LazyLoad width={768} height={450} onContentVisible={() : void => ReactGA.event({ category : 'Meeting Point', action : 'Display', label : 'Google Map (Sam Pui Chau Pier)' })}> <div style={{ textAlign : 'center' }}> <div dangerouslySetInnerHTML={{ __html : '<iframe src="https://www.google.com/maps/embed?pb=!1m0!4v1497720781547!6m8!1m7!1sF%3A-fdAcu4b9pSo%2FVWPjmljUzqI%2FAAAAAAABNu8%2FuVblQhFXCA8dJteEehAfsukFs8jXNOuWwCJkC!2m2!1d22.4317466!2d114.2694121!3f215.51966352377502!4f18.855990498735693!5f0.7820865974627469" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>' }} /> </div> </LazyLoad> <p>We will take the boat provided by the raft owner. In a few minutes, we will arrive at the raft.</p> </CardText> </Card> <Card className="meetingPointItem"> <CardMedia> <img src={YungShueORaftImage} style={{ maxWidth : '100%' }} /> </CardMedia> <CardTitle title={<div><strong>12:15 PM</strong> Yung Shue O Rafts (榕樹澳漁排)</div>} /> <CardText> <p>There are over 100 rafts and we will spend our day on one of these.</p> <LazyLoad width={768} height={450} onContentVisible={() : void => ReactGA.event({ category : 'Meeting Point', action : 'Display', label : 'Google Map (Yung Shue O Rafts)' })}> <div style={{ textAlign : 'center' }}> <div dangerouslySetInnerHTML={{ __html : '<iframe src="https://www.google.com/maps/embed?pb=!1m0!4v1497721548633!6m8!1m7!1sF%3A-VrMR0TfFtys%2FVgFlCaK9KWI%2FAAAAAAAAfXM%2FlgIkW-sv43ovS31ljaaIgvCJ37JFTIxQgCLIB!2m2!1d22.4219482!2d114.2769164!3f16.208133242012664!4f1.518324652762871!5f0.7820865974627469" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>' }} /> </div> </LazyLoad> </CardText> </Card> <Card className="meetingPointItem"> <CardMedia> <img src={RaftEveningImage} style={{ maxWidth : '100%' }} /> </CardMedia> <CardTitle title={<div><strong>Evening</strong> Yung Shue O Rafts (榕樹澳漁排)</div>} /> <CardText> <p>We will again take the boat provided by the raft owner to go back to the pier, and walk the way back to the minibus terminus.</p> <p>We will dismiss at the minibus terminus. You can take minibus route 807K, walk to the bus station, or by taxi.</p> </CardText> </Card> </div> ); } } export default muiThemeable()(MeetingPoint);
app/components/TodolistComponenet.js
RogerZZZZZ/widget_electron
import React from 'react' import { Component } from 'react' import Button from "./Button.js" import DatePicker from "react-datepicker" import Storage from 'electron-json-storage'; import moment from 'moment' import testData from './textData.js' import Utils from '../utils/utils.js' import 'react-datepicker/dist/react-datepicker.css'; let utils = new Utils(); class Input extends Component{ constructor(props){ super(props) } render(){ return( <div className="input-container"> <input type="text" placeholder={this.props.placeholder} className={this.props.styleClass} onFocus={this.props.onFocus} onBlur={this.props.onBlur} onKeyUp={this.props.onKeyUp}/> </div> ) } } class TodolistItem extends Component{ constructor(props){ super(props) this.state = { data: this.props.data, editStatus: false, isOpen: false } } _changeInputStatus(){ this.setState({ editStatus: !this.state.editStatus }); } _inputSubmit(event){ if(event.keyCode == "13"){ this.state.data.title = event.target.value; this.setState({data: this.state.data}) this._saveTitle() event.target.blur(); }else if(event.keyCode == '27'){ this._changeInputStatus(); } } _renderTitle(data, status){ let self = this; return( <div className={"content-container " + (status === 'done' ? 'content-container--complete': '')}> <div className="text-container">{data.title}</div> { status === 'done' ? null : ( <div className="date-left">{utils.timeCalculator(moment(), moment(self.state.data.end), 'day')} days left</div> ) } </div> ) } _saveTitle(type){ let self = this; Storage.get('todolist', function(err, data) { if(err) throw err; let newData = utils.modifyElementInArr(data, self.state.data); Storage.set('todolist', newData, ()=> {}) }) if(type !== false){ this._changeInputStatus(); } } _renderTitleInput(data){ return( <input autoComplete="off" autoFocus defaultValue={data.title} maxLength="64" ref="inputBox" className="inputBox" onKeyUp={this._inputSubmit.bind(this)} type="text"/> ) } _handleStartTime(date) { if(utils.judgeValidTime(moment(date), moment(this.state.data.end))){ this.state.data.start = date; this.setState({ data: this.state.data }) }else{ alert("Invalid time period! please input again!") } this._toggleCalendar() } _handleEndTime(date){ if(utils.judgeValidTime(moment(this.state.data.start), moment(date))){ this.state.data.end = date; this.setState({ data: this.state.data }) }else{ alert("Invalid time period! please input again!") } this._toggleCalendar() } _toggleCalendar(e) { e && e.preventDefault() this.setState({ isOpen: !this.state.isOpen }) } _checkButtonClick(){ this.state.data.status = (this.state.data.status === 'done' ? 'wait': 'done') this._saveTitle(false); this.setState({ data: this.state.data }) } _deleteButtonClick(itemId){ let self = this; Storage.get('todolist', function(err, data) { if(err) throw err; let newData = utils.deleteElementInArr(data, itemId); Storage.set('todolist', newData, () => { self.setState({ data: null }) }) }) } render(){ let self = this; let data = this.state.data; return( <div> { data === null? null : ( <div className="todolist-item"> <div className="todolist-item-main"> { !self.state.editStatus ? ( data.status === 'done' ? ( <Button name="check" static={true} buttonClick={self._checkButtonClick.bind(self)} className="left-button" align="left" status={true}/> ) :( <Button name="check" buttonClick={self._checkButtonClick.bind(self)} className="left-button" align="left" status={false}/> )):null } {self.state.editStatus ? this._renderTitleInput(data) : this._renderTitle(data, data.status)} { self.state.editStatus || data.status === 'done' ? null: ( <Button name="edit" buttonClick={self._changeInputStatus.bind(this)} align="right" /> ) } <Button name="trash" buttonClick={self._deleteButtonClick.bind(self, data.id)} align="right"/> </div> { !self.state.editStatus ? null: ( <div className="todolist-item-additional"> <div className="todolist-data-select-pane"> <div className="select-pane-content">Start Time:</div> <div className="select-pane-date"> <DatePicker customInput={<DatePickerComponent />} selected={moment(data.start)} onChange={this._handleStartTime.bind(self)} /> </div> </div> <div className="todolist-data-select-pane"> <div className="select-pane-content">End Time:</div> <div className="select-pane-date"> <DatePicker customInput={<DatePickerComponent />} selected={moment(data.end)} onChange={this._handleEndTime.bind(self)} /> </div> </div> <div className="todolist-data-select-pane"> <div className="select-pane-content">Duration:</div> <div className="select-pane-content">{utils.timeCalculator(moment(data.start), moment(data.end), 'day')} days</div> </div> </div> ) } </div> ) } </div> ) } } class TodolistPane extends Component{ constructor(props){ super(props) this.state = { data: this.props.todolist } } render(){ let self = this; let keyCount = 0; return ( <div> { self.props.todolist.map(function(item){ return (<TodolistItem data={item} key={keyCount++}/>) }) } </div> ) } } class DatePickerComponent extends Component{ render() { return ( <button className={this.props.type === 'big'? "date-picker-big-input" :"date-picker-input"} onClick={this.props.onClick}> {this.props.value} </button> ) } } module.exports = { Input: Input, TodolistItem: TodolistItem, TodolistPane: TodolistPane, DatePickerComponent: DatePickerComponent }
src/components/Toast/demo/basic/index.js
lebra/lebra-components
import React, { Component } from 'react'; import Toast from '../../index'; import { render } from 'react-dom'; import './index.less'; export default class ToastDemo extends Component{ state = { showToast: false, }; showToast = () => { this.setState({showToast: true}); } render() { return ( <div className="nav-demo"> <button onClick={this.showToast} type="default">show toast</button> <Toast show={this.state.showToast} position='center'>Donsdafskjfksdfjlksdjfkldsjalkfjsdlf;jdsla;fjsdaljflsdajflkasdjflksdajflkasdjflkasdjfklasdjfklsadjfklsdjfklsadjfklajsdflkje</Toast> </div> ) } } let root = document.getElementById('app'); render(<ToastDemo />, root);
src/components/CommentModal/CommentModal.js
eunvanz/flowerhada
import React from 'react' import CustomModal from 'components/CustomModal' import TextField from 'components/TextField' import { postCommentImage, postComment, putComment } from 'common/CommentService' import { postPointHistory } from 'common/PointHistoryService' import Button from 'components/Button' import { Tooltip } from 'react-bootstrap' import numeral from 'numeral' class CommentModal extends React.Component { constructor (props) { super(props) let validImagePoint = false if (!this.props.comment) { validImagePoint = true } else if (this.props.comment && this.props.comment.image === '') { validImagePoint = true } this.state = { title: this.props.comment ? this.props.comment.title : '', content: this.props.comment ? this.props.comment.content.replace(/<br>/g, '\r\n') : '', image: this.props.comment ? this.props.comment.image : '', mode: this.props.comment ? 'put' : 'post', process: false, validImagePoint } this._handleOnChangeInput = this._handleOnChangeInput.bind(this) this._handleOnClickSubmit = this._handleOnClickSubmit.bind(this) } _handleOnChangeInput (e) { const value = e.target.value const id = e.target.id const limit = e.target.dataset.limit if (limit && limit < value.length) { return } this.setState({ [id]: value }) } _handleOnClickSubmit () { this.setState({ process: true }) const imageInput = document.getElementById('image') const file = imageInput.files[0] const finalizeSubmit = () => { this.setState({ title: '', content: '', image: '', process: false }) this.props.close() this.props.afterSubmit() } const doActionComment = () => { const comment = { title: this.state.title, content: this.state.content.replace(/\n/g, '<br>'), type: this.props.type, image: this.state.image, groupName: this.props.groupName, userId: this.props.userId } if (this.props.parentId || (this.props.comment && this.props.comment.parentId)) { comment.parentId = this.props.parentId || this.props.comment.parentId } return this.state.mode === 'post' ? postComment(comment) : putComment(comment, this.props.comment.id) } const handlePoint = () => { if (this.state.mode === 'post') { const pointHistory = { userId: this.props.userId, amount: this.props.point, action: '리뷰 작성' } return postPointHistory(pointHistory) } else { return Promise.resolve() } } const handleImagePoint = () => { if (this.state.validImagePoint) { const pointHistory = { userId: this.props.userId, amount: this.props.imagePoint, action: '리뷰에 이미지 업로드' } return postPointHistory(pointHistory) } else { Promise.resolve() } } const validate = () => { return this.props.type === 'review' && this.state.mode === 'post' ? this.props.validator() : Promise.resolve() } validate() .then(() => { if (file) { return postCommentImage(file) .then(res => { const imgUrl = res.data.data.link this.setState({ image: imgUrl }) return doActionComment() }) .then(() => { if (this.state.mode === 'post' && this.props.type === 'review') return handlePoint() else return Promise.resolve() }) .then(() => { if (this.state.mode === 'post' && this.props.type === 'review' && this.props.imagePoint) return handleImagePoint() else return Promise.resolve() }) .then(() => { return finalizeSubmit() }) } else { return doActionComment() .then(() => { if (this.props.type === 'review') return handlePoint() else return Promise.resolve() }) .then(() => { return finalizeSubmit() }) } }) .catch(() => { this.setState({ process: false }) alert('레슨 수강완료 혹은 상품 배송완료 후에 작성 가능합니다.') }) } render () { const renderImageTooltip = () => { if (this.props.type === 'review' && this.props.imagePoint) { return ( <Tooltip placement='right' className='in' id='imagePointInfo' style={{ display: 'inline' }}> <span className='text-default'>+{numeral(this.props.imagePoint).format('0,0')}P</span> 추가적립 </Tooltip> ) } } const renderBody = () => { return ( <div className='row'> <div className='col-md-12'> <form role='form'> <TextField id='title' label='제목' onChange={this._handleOnChangeInput} value={this.state.title} limit={30} length={this.state.title.length} data-limit={30} placeholder='제목을 입력해주세요.' /> <label>내용</label> <textarea id='content' className='form-control' rows='8' placeholder='내용을 입력해주세요.' value={this.state.content} onChange={this._handleOnChangeInput} data-limit={1000} /> <div className='text-right small'> (<span className='text-default'>{this.state.content.length}</span>/1000) </div> <p /> <label>이미지첨부 {renderImageTooltip()} </label> <input type='file' id='image' accept='image/*' /> </form> </div> </div> ) } const renderFooter = () => { return ( <div style={{ textAlign: 'right' }}> <Button className='margin-clear' color='dark' onClick={this.props.close} textComponent={<span>취소</span>} /> {this.state.title !== '' && this.state.content !== '' && <Button className='margin-clear' onClick={this.state.process ? null : this._handleOnClickSubmit} animated process={this.state.process} textComponent={<span>작성완료 <i className='fa fa-check' /></span>} />} </div> ) } return ( <CustomModal title={`${this.props.type === 'review' ? '후기작성' : '문의하기'}`} width='600px' backdrop show={this.props.show} close={this.props.close} bodyComponent={renderBody()} footerComponent={renderFooter()} id={this.props.id} /> ) } } CommentModal.propTypes = { comment: React.PropTypes.object, type: React.PropTypes.string, // 'review' 혹은 'inquiry' show: React.PropTypes.bool.isRequired, close: React.PropTypes.func.isRequired, groupName: React.PropTypes.string, userId: React.PropTypes.number, afterSubmit: React.PropTypes.func.isRequired, parentId: React.PropTypes.number, id: React.PropTypes.string.isRequired, imagePoint: React.PropTypes.number, point: React.PropTypes.number, validator: React.PropTypes.func } export default CommentModal
docs/app/Examples/elements/Button/Variations/ButtonExampleFloated.js
ben174/Semantic-UI-React
import React from 'react' import { Button } from 'semantic-ui-react' const ButtonExampleFloated = () => ( <div> <Button floated='right'>Right Floated</Button> <Button floated='left'>Left Floated</Button> </div> ) export default ButtonExampleFloated
client/components/users/reset-password.js
LIYINGZHEN/meteor-react-redux-base
import React from 'react'; export default class extends React.Component { constructor(props) { super(props); this.state = {uiState: 'INIT'}; this.onSubmit = this.onSubmit.bind(this); } onSubmit(e) { e.preventDefault(); this.setState({uiState: 'SENDING'});console.log(this._input.value); this.props.resetPassword(this._input.value, (err) => { if (err) { console.log(err); this.setState({uiState: 'FAIL'}); } else { this.setState({uiState: 'SUCCESS'}); } }); } render() { if (this.state.uiState === 'SENDING') return <div style={{marginTop: 60, marginLeft: 10}}>正在设置密码...</div>; if (this.state.uiState === 'SUCCESS') return <div style={{marginTop: 60, marginLeft: 10}}>密码设置成功</div>; return ( <form style={{marginTop: 60, marginLeft: 10}} onSubmit={this.onSubmit}> {this.state.uiState === 'FAIL' && <p>密码设置失败,请重试</p>} 密码:<input type="password" ref={(c) => this._input = c}/> <input type="submit" value="设置" /> </form>); } }
wwwroot/app/src/components/MyRecipesPage/Ingredients.js
AlinCiocan/PlanEatSave
import React, { Component } from 'react'; import uuid from 'uuid'; import classNames from 'classnames'; import RemoveIcon from '../base/icons/RemoveIcon'; import Label from '../base/form/Label'; import { applicationSettings, recipeSettings } from '../../constants/settings'; import IconButton from '../base/buttons/IconButton'; const ENTER_KEY = 13; const UP_ARROW_KEY = 38; const DOWN_ARROW_KEY = 40; class Ingredients extends Component { createEmptyIngredient() { return { name: '', id: uuid.v4(), canBeDeleted: false }; } onItemFocus(ingredientOnFocus) { if (ingredientOnFocus.canBeDeleted) { return; } if (this.ingredients.length >= recipeSettings.MAX_NUMBER_OF_INGREDIENTS) { return; } const ingredients = this.ingredients.map(ingredient => ingredient === ingredientOnFocus ? { ...ingredientOnFocus, canBeDeleted: true } : ingredient); this.props.onChange([...ingredients, this.createEmptyIngredient()]); } onItemRemove(ingredientToRemove) { const ingredients = this.ingredients.filter(ingredient => ingredient !== ingredientToRemove); this.props.onChange(ingredients); } onIngredientValueChange(ingredient, newValue) { const ingredients = this.ingredients.map(x => x === ingredient ? { ...ingredient, name: newValue } : x); this.props.onChange(ingredients); } doFocusOnIngredient(ingredient) { const ingredientDomElement = this.refs[ingredient.id]; // hack in order to move the cursor of the input always at the end ingredientDomElement.value = ''; ingredientDomElement.value = ingredient.name; ingredientDomElement.focus(); } doFocusOnNextIngredient(ingredient) { const nextIngredientIndex = this.ingredients.indexOf(ingredient) + 1; if (nextIngredientIndex >= this.ingredients.length) { return; } this.doFocusOnIngredient(this.ingredients[nextIngredientIndex]); } doFocusOnPreviousIngredient(ingredient) { const previousIngredientIndex = this.ingredients.indexOf(ingredient) - 1; if (previousIngredientIndex < 0) { return; } this.doFocusOnIngredient(this.ingredients[previousIngredientIndex]); } onIngredientKeyDown(evt, ingredient) { if (evt.keyCode === ENTER_KEY || evt.keyCode === DOWN_ARROW_KEY) { this.doFocusOnNextIngredient(ingredient); return; } if (evt.keyCode === UP_ARROW_KEY) { evt.preventDefault(); this.doFocusOnPreviousIngredient(ingredient); } } renderRemoveButton(ingredient) { const cannotBeDeleted = !ingredient.canBeDeleted; const buttonClasses = classNames({ "ingredients__remove-button--not-visible": cannotBeDeleted }); return ( <IconButton className={buttonClasses} onClick={() => this.onItemRemove(ingredient)} > <RemoveIcon /> </IconButton> ); } renderItem(ingredient) { return ( <div key={ingredient.id} className="ingredients__item"> <input className="ingredients__item-input" type="text" placeholder="Add new ingredient" maxLength={applicationSettings.MAX_LENGTH_INPUT} value={ingredient.name} onChange={evt => this.onIngredientValueChange(ingredient, evt.target.value)} onFocus={() => this.onItemFocus(ingredient)} ref={ingredient.id} onKeyDown={evt => this.onIngredientKeyDown(evt, ingredient)} /> {this.renderRemoveButton(ingredient)} </div> ); } renderItems() { return this.ingredients.map(ingredient => { return this.renderItem(ingredient); }); } render() { // TODO: refactor this (Ingredients should be split in IngredientsList and IngredientItem) const ingredients = [...this.props.ingredients]; if (ingredients.every(ingredient => ingredient.canBeDeleted)) { ingredients.push(this.createEmptyIngredient()); } this.ingredients = ingredients; return ( <div className={this.props.className}> <Label text="Ingredients" /> <div className="ingredients__list"> {this.renderItems()} </div> </div> ); } } Ingredients.propTypes = { ingredients: React.PropTypes.arrayOf(React.PropTypes.shape({ name: React.PropTypes.string.isRequired, id: React.PropTypes.string.isRequired, canBeDeleted: React.PropTypes.bool.isRequired })).isRequired }; export default Ingredients;
packages/metadata-react/src/Diagrams/Radar.js
oknosoft/metadata.js
/** * ### Диаграмма Radar * * @module Radar * * Created by Evgeniy Malyarov on 18.08.2018. */ import React from 'react'; import PropTypes from 'prop-types'; import {chartData} from './Bar'; function Radar({width, height, data, isFullscreen, Recharts}) { const {Radar, RadarChart, PolarGrid, Legend, Tooltip, PolarAngleAxis, PolarRadiusAxis} = Recharts; if(isFullscreen) { width = window.innerWidth - 64; height = window.innerHeight - 64; } else if(!height) { height = width <= 600 ? width * 1.2 : width / 2.4; } const xDataKey = data.points && data.points.length && data.points[0].name || 'name'; return ( <RadarChart width={width} height={height} margin={{left: isFullscreen ? 0 : -8, top: 8, bottom: 8}} data={chartData(data)}> <PolarGrid /> {!data.hideXAxis && <PolarAngleAxis dataKey={xDataKey}/>} {!data.hideYAxis && <PolarRadiusAxis/>} {!data.hideTooltip && <Tooltip/>} {!data.hideLegend && <Legend/>} { data.series.map((ser, key) => <Radar name={ser.presentation || ser.name} key={`ser-${key}`} dataKey={ser.name} stroke={ser.color || '#8884d8'} fill={ser.color || '#8884d8'} fillOpacity={ser.opacity || 0.6} />) } </RadarChart> ); } Radar.propTypes = { width: PropTypes.number.isRequired, height: PropTypes.number, data: PropTypes.object.isRequired, isFullscreen: PropTypes.bool, Recharts: PropTypes.func.isRequired, }; export default Radar;
src/step-3/client/main.js
DJCordhose/react-intro-live-coding
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from '../common/store'; import HelloMessage from '../common/HelloMessage'; const mountNode = document.getElementById('mount'); ReactDOM.render( <Provider store={store}> <HelloMessage /> </Provider>, mountNode );
packages/mineral-ui-icons/src/IconRestore.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconRestore(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M13 3a9 9 0 0 0-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"/> </g> </Icon> ); } IconRestore.displayName = 'IconRestore'; IconRestore.category = 'action';
fields/types/code/CodeField.js
brianjd/keystone
import _ from 'lodash'; import CodeMirror from 'codemirror'; import Field from '../Field'; import React from 'react'; import { findDOMNode } from 'react-dom'; import { FormInput } from '../../../admin/client/App/elemental'; import classnames from 'classnames'; /** * TODO: * - Remove dependency on lodash */ // See CodeMirror docs for API: // http://codemirror.net/doc/manual.html module.exports = Field.create({ displayName: 'CodeField', statics: { type: 'Code', }, getInitialState () { return { isFocused: false, }; }, componentDidMount () { if (!this.refs.codemirror) { return; } var options = _.defaults({}, this.props.editor, { lineNumbers: true, readOnly: this.shouldRenderField() ? false : true, }); this.codeMirror = CodeMirror.fromTextArea(findDOMNode(this.refs.codemirror), options); this.codeMirror.setSize(null, this.props.height); this.codeMirror.on('change', this.codemirrorValueChanged); this.codeMirror.on('focus', this.focusChanged.bind(this, true)); this.codeMirror.on('blur', this.focusChanged.bind(this, false)); this._currentCodemirrorValue = this.props.value; }, componentWillUnmount () { // todo: is there a lighter-weight way to remove the cm instance? if (this.codeMirror) { this.codeMirror.toTextArea(); } }, componentWillReceiveProps (nextProps) { if (this.codeMirror && this._currentCodemirrorValue !== nextProps.value) { this.codeMirror.setValue(nextProps.value); } }, focus () { if (this.codeMirror) { this.codeMirror.focus(); } }, focusChanged (focused) { this.setState({ isFocused: focused, }); }, codemirrorValueChanged (doc, change) { var newValue = doc.getValue(); this._currentCodemirrorValue = newValue; this.props.onChange({ path: this.props.path, value: newValue, }); }, renderCodemirror () { const className = classnames('CodeMirror-container', { 'is-focused': this.state.isFocused && this.shouldRenderField(), }); return ( <div className={className}> <FormInput autoComplete="off" multiline name={this.getInputName(this.props.path)} onChange={this.valueChanged} ref="codemirror" value={this.props.value} /> </div> ); }, renderValue () { return this.renderCodemirror(); }, renderField () { return this.renderCodemirror(); }, });
lens-ui/app/components/LoaderComponent.js
guptapuneet/lens
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { GridLoader } from 'halogen'; // TODO add warnings if size and margin props aren't sent. class Loader extends React.Component { render () { return ( <section style={{margin: '0 auto', maxWidth: '12%'}}> <GridLoader {...this.props} color='#337ab7'/> </section> ); } } export default Loader;
react-flux-mui/js/material-ui/src/svg-icons/maps/navigation.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsNavigation = (props) => ( <SvgIcon {...props}> <path d="M12 2L4.5 20.29l.71.71L12 18l6.79 3 .71-.71z"/> </SvgIcon> ); MapsNavigation = pure(MapsNavigation); MapsNavigation.displayName = 'MapsNavigation'; MapsNavigation.muiName = 'SvgIcon'; export default MapsNavigation;
src/map/js/components/AnalysisPanel/WatershedChart.js
wri/gfw-water
import {analysisPanelText as text} from 'js/config'; import React from 'react'; let generateChart = (id, feature) => { /** * rs_tl_c - Recent forest loss * rs_pf_c - Historic forest loss * rs_sed_c - Erosion risk * rs_fire_c - Fire risk */ let { rs_tl_c, rs_pf_c, rs_sed_c, rs_fire_c } = feature.attributes; //- TCL and HTCL can have Not applicable values, this number is 10 and if present, we should not render the //- bar but keep it in the chart, so set it to a negative value, as long as highcharts has a yAxis min of 0 //- the bar will not render if (rs_tl_c === 10) { rs_tl_c = -1; } if (rs_pf_c === 10) { rs_pf_c = -1; } if (rs_sed_c === 10) { rs_sed_c = -1; } // Don't use arrow functions in here, highcharts already is binding the scope $(`#${id}`).highcharts({ chart: { backgroundColor: 'transparent', type: 'column' }, title: { text: '' }, xAxis: { tickLength: 0, labels: { enabled: false } }, yAxis: { min: 0, max: 5, tickPositions: [0, 1, 2, 3, 4, 5], title: { text: '' }, labels: { formatter: function () { switch (this.value) { case 0: return 'low'; case 5: return 'high'; default: return ''; } } } }, legend: { align: 'right', layout: 'vertical', verticalAlign: 'middle', itemStyle: { width: '150px', fontWeight: 300, fontFamily: '\'Fira Sans\', Georgia, serif' } }, plotOptions: { column: { pointPadding: 0.1, borderWidth: 0 }, series: { groupPadding: 0 } }, tooltip: { formatter: function () { return `${this.series.name} - ${this.y}<br>${text.riskLookup[this.y]}`; } }, credits: { enabled: false }, series: [{ type: 'column', name: 'Recent forest loss', data: [rs_tl_c], color: '#FF6097', pointPlacement: 'between' }, { type: 'column', name: 'Historical forest loss', data: [rs_pf_c], color: '#D2DF2E', pointPlacement: 'between' }, { type: 'column', name: 'Erosion risk', data: [rs_sed_c], color: '#A79261', pointPlacement: 'between' }, { type: 'column', name: 'Fire risk', data: [rs_fire_c], color: '#EA5A00', pointPlacement: 'between' }] }); }; export default class WatershedChart extends React.Component { componentDidMount() { generateChart(this.props.id, this.props.feature); } componentDidUpdate(prevProps) { if (this.props.feature !== prevProps.feature && this.props.feature !== null) { generateChart(this.props.id, this.props.feature); } } render () { return ( <div className='watershed-chart' id={this.props.id} /> ); } }
app/javascript/packs/client.js
legislated/legislated-web
// @flow import '@/styles/hydrate' import React from 'react' import { renderReact } from 'hypernova-react' import { BrowserRouter } from 'react-router-dom' import { ScrollContext } from 'react-router-scroll-4' import { App } from '../src/App' export default renderReact('client', () => ( <BrowserRouter> <ScrollContext> <App /> </ScrollContext> </BrowserRouter> ))
src/svg-icons/social/public.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPublic = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/> </SvgIcon> ); SocialPublic = pure(SocialPublic); SocialPublic.displayName = 'SocialPublic'; SocialPublic.muiName = 'SvgIcon'; export default SocialPublic;
src/Switch/Switch.js
AndriusBil/material-ui
// @flow weak import React from 'react'; import type { Node } from 'react'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; import createSwitch from '../internal/SwitchBase'; export const styles = (theme: Object) => ({ root: { display: 'inline-flex', width: 62, position: 'relative', flexShrink: 0, }, bar: { borderRadius: 7, display: 'block', position: 'absolute', width: 34, height: 14, top: '50%', marginTop: -7, left: '50%', marginLeft: -17, transition: theme.transitions.create(['opacity', 'background-color'], { duration: theme.transitions.duration.shortest, }), backgroundColor: theme.palette.type === 'light' ? '#000' : '#fff', opacity: theme.palette.type === 'light' ? 0.38 : 0.3, }, icon: { boxShadow: theme.shadows[1], backgroundColor: 'currentColor', width: 20, height: 20, borderRadius: '50%', }, // For SwitchBase default: { zIndex: 1, color: theme.palette.type === 'light' ? theme.palette.grey[50] : theme.palette.grey[400], transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shortest, }), }, checked: { color: theme.palette.primary[500], transform: 'translateX(14px)', '& + $bar': { backgroundColor: theme.palette.primary[500], opacity: 0.5, }, }, disabled: { color: theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[800], '& + $bar': { backgroundColor: theme.palette.type === 'light' ? '#000' : '#fff', opacity: theme.palette.type === 'light' ? 0.12 : 0.1, }, }, }); const SwitchBase = createSwitch(); type DefaultProps = { classes: Object, }; export type Props = { /** * If `true`, the component is checked. */ checked?: boolean | string, /** * The CSS class name of the root element when checked. */ checkedClassName?: string, /** * The icon to display when the component is checked. * If a string is provided, it will be used as a font ligature. */ checkedIcon?: Node, /** * Useful to extend the style applied to components. */ classes?: Object, /** * @ignore */ className?: string, /** * @ignore */ defaultChecked?: boolean, /** * If `true`, the switch will be disabled. */ disabled?: boolean, /** * The CSS class name of the root element when disabled. */ disabledClassName?: string, /** * If `true`, the ripple effect will be disabled. */ disableRipple?: boolean, /** * The icon to display when the component is unchecked. * If a string is provided, it will be used as a font ligature. */ icon?: Node, /** * Properties applied to the `input` element. */ inputProps?: Object, /** * Use that property to pass a ref callback to the native input component. */ inputRef?: Function, /* * @ignore */ name?: string, /** * Callback fired when the state is changed. * * @param {object} event The event source of the callback * @param {boolean} checked The `checked` value of the switch */ onChange?: Function, /** * @ignore */ tabIndex?: number | string, /** * The value of the component. */ value?: string, }; type AllProps = DefaultProps & Props; function Switch(props: AllProps) { const { classes, className, ...other } = props; const icon = <div className={classes.icon} />; return ( <div className={classNames(classes.root, className)}> <SwitchBase icon={icon} classes={{ default: classes.default, checked: classes.checked, disabled: classes.disabled, }} checkedIcon={icon} {...other} /> <div className={classes.bar} /> </div> ); } export default withStyles(styles, { name: 'MuiSwitch' })(Switch);
src/svg-icons/maps/local-offer.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalOffer = (props) => ( <SvgIcon {...props}> <path d="M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58.55 0 1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41 0-.55-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7z"/> </SvgIcon> ); MapsLocalOffer = pure(MapsLocalOffer); MapsLocalOffer.displayName = 'MapsLocalOffer'; MapsLocalOffer.muiName = 'SvgIcon'; export default MapsLocalOffer;
src/stories/onRender.js
phola/react-xlsx
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import Button from '../index'; import WorkBook from '../WorkBook' import Cell from '../Cell' import Sheet from '../Sheet' storiesOf('WorkBook', module).add( 'renderXLSX setting ', () => { const defaultCellStyle = { font: { name: "Verdana", sz: 11, color: "FF00FF88"}, fill: {fgColor: {rgb: "FFFFAA00"}}} const handleXLSX = (blob) => { console.log(blob) }; return ( <div> <WorkBook ref='wb' fileName='bob.xlsx' render renderXLSX defaultCellStyle={defaultCellStyle} onXLSXRendered={handleXLSX}> <Sheet name='woooo'> <div>bob</div> <Cell row={0} col={1}><div><div>nested</div></div></Cell> </Sheet> <Sheet name='hoooo'> <Cell row={1} col={2} style={{font:{bold:true}}}>I am bold</Cell> <Cell cellRef='C9'>plain string</Cell> </Sheet> </WorkBook> </div> ); } );
src/svg-icons/image/wb-cloudy.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageWbCloudy = (props) => ( <SvgIcon {...props}> <path d="M19.36 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.64-4.96z"/> </SvgIcon> ); ImageWbCloudy = pure(ImageWbCloudy); ImageWbCloudy.displayName = 'ImageWbCloudy'; ImageWbCloudy.muiName = 'SvgIcon'; export default ImageWbCloudy;
src/form/TextInput/TextInput.js
jeffdowdle/l-systems
import React from 'react'; import PropTypes from 'prop-types'; import Control from '../Control'; import Label from '../Label'; import './text-input.scss'; const fieldId = id => `param-${id}`; const TextInput = ({ id, label, value, onChange, }) => ( <Control> <Label htmlFor={fieldId}>{label}</Label> <input id={fieldId(id)} styleName="text-input" type="text" value={value} onChange={e => onChange(e.target.value)} /> </Control> ); TextInput.propTypes = { value: PropTypes.number.isRequired, onChange: PropTypes.func.isRequired, }; export default TextInput;
packages/wix-style-react/src/FilePicker/FilePicker.js
wix/wix-style-react
import React from 'react'; import PropTypes from 'prop-types'; import Add from 'wix-ui-icons-common/Add'; import uniqueId from 'lodash/uniqueId'; import { classes } from './FilePicker.st.css'; import FormField from '../FormField'; import TextButton from '../TextButton'; import Text from '../Text'; import FileUpload from '../FileUpload'; /** * # `<FilePicker/>` * * Component that opens system browser dialog for choosing files to upload */ class FilePicker extends React.PureComponent { constructor(props) { super(props); this.state = { selectedFileName: props.subLabel, }; this.id = props.id || uniqueId('file_picker_input_'); } /** A callback which is invoked every time a file is chosen */ onChooseFile(file) { const { maxSize, onChange } = this.props; if (file) { onChange(file); if (file.size <= maxSize) { this.setState({ selectedFileName: file.name }); } } } render() { const { header, mainLabel, supportedFormats, error, errorMessage, name, dataHook, } = this.props; return ( <FileUpload accept={supportedFormats} onChange={files => this.onChooseFile(files[0])} name={name} > {({ openFileUploadDialog }) => ( <FormField label={header} dataHook={dataHook}> <label className={classes.label} onClick={openFileUploadDialog}> <div className={classes.icon}> <Add /> </div> <div className={classes.content}> <TextButton dataHook="main-label">{mainLabel}</TextButton> <Text className={classes.info} size="small" secondary dataHook="sub-label" > {this.state.selectedFileName} </Text> {error && ( <Text skin="error" size="small" dataHook="filePicker-error"> {errorMessage} </Text> )} </div> </label> </FormField> )} </FileUpload> ); } } FilePicker.displayName = 'FilePicker'; FilePicker.defaultProps = { mainLabel: 'Choose File', subLabel: 'No file chosen (Max size 5 MB)', onChange: () => {}, supportedFormats: '*', errorMessage: '', maxSize: 5000000, // 5MB }; FilePicker.propTypes = { /** Some text that will appear above the Icon */ header: PropTypes.string, /** Callback function for when a file is uploaded */ onChange: PropTypes.func, /** Some text that will appear as a main label besides the Icon */ mainLabel: PropTypes.string, /** Some text that will appear as a sub label besides the Icon */ subLabel: PropTypes.string, /** supported formats separated by comma (.png, .pdf) */ supportedFormats: PropTypes.string, /** Max size of file allowed */ maxSize: PropTypes.number, /** should present error */ error: PropTypes.bool, /** error message to present */ errorMessage: PropTypes.string, /** id for the filePicker */ id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** Name for inner input */ name: PropTypes.string, /** Data attribute for testing purposes */ dataHook: PropTypes.string, }; export default FilePicker;
src/pages/audiovisual.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Audiovisual' /> )
src/parser/hunter/survival/modules/spells/CoordinatedAssault.js
FaideWW/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import { formatNumber, formatPercentage } from 'common/format'; import StatisticBox from 'interface/others/StatisticBox'; import SpellIcon from 'common/SpellIcon'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; import SpellUsable from 'parser/shared/modules/SpellUsable'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import StatisticListBoxItem from 'interface/others/StatisticListBoxItem'; import SpellLink from 'common/SpellLink'; import ItemDamageDone from 'interface/others/ItemDamageDone'; /** * You and your pet attack as one, increasing all damage you both deal by * 20% for 20 sec. While Coordinated Assault is active, Kill Command's * chance to reset is increased by 25%. * * Example log: https://www.warcraftlogs.com/reports/pNJbYdLrMW2ynKGa#fight=3&type=damage-done&source=16&translate=true */ const CA_DMG_MODIFIER = 0.2; class CoordinatedAssault extends Analyzer { static dependencies = { spellUsable: SpellUsable, }; casts = 0; playerDamage = 0; petDamage = 0; on_byPlayerPet_damage(event) { if (!this.selectedCombatant.hasBuff(SPELLS.COORDINATED_ASSAULT.id)) { return; } this.petDamage += calculateEffectiveDamage(event, CA_DMG_MODIFIER); } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.COORDINATED_ASSAULT.id) { this.casts += 1; } } on_byPlayer_damage(event) { if (!this.selectedCombatant.hasBuff(SPELLS.COORDINATED_ASSAULT.id)) { return; } if (this.casts === 0) { this.casts += 1; this.spellUsable.beginCooldown(SPELLS.COORDINATED_ASSAULT.id, this.owner.fight.start_time); } this.playerDamage += calculateEffectiveDamage(event, CA_DMG_MODIFIER); } get totalDamage() { return this.playerDamage + this.petDamage; } get percentUptime() { return this.selectedCombatant.getBuffUptime(SPELLS.COORDINATED_ASSAULT.id) / this.owner.fightDuration; } statistic() { return ( <StatisticBox position={STATISTIC_ORDER.CORE(17)} icon={<SpellIcon id={SPELLS.COORDINATED_ASSAULT.id} />} value={`${formatPercentage(this.percentUptime)}%`} label="Coordinated Assault uptime" tooltip={`Over the course of the encounter you had Coordinated Assault up for a total of ${(this.selectedCombatant.getBuffUptime(SPELLS.COORDINATED_ASSAULT.id) / 1000).toFixed(1)} seconds.`} /> ); } subStatistic() { return ( <StatisticListBoxItem title={<SpellLink id={SPELLS.COORDINATED_ASSAULT.id} />} value={<ItemDamageDone amount={this.totalDamage} />} valueTooltip={`Total damage breakdown: <ul> <li>Player damage: ${formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.playerDamage))}% / ${formatNumber(this.playerDamage / (this.owner.fightDuration / 1000))} DPS</li> <li>Pet damage: ${formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.petDamage))}% / ${formatNumber(this.petDamage / (this.owner.fightDuration / 1000))} DPS</li> </ul>`} /> ); } } export default CoordinatedAssault;
front_end/src/pages/AdGroups/AdGroupCreatePage.js
ncloudioj/splice
import React, { Component } from 'react'; import { connect } from 'react-redux'; import reactMixin from 'react-mixin'; import { Link, Lifecycle } from 'react-router'; import { updateDocTitle } from 'actions/App/AppActions'; import { fetchHierarchy } from 'actions/App/BreadCrumbActions'; import { fetchAccounts } from 'actions/Accounts/AccountActions'; import AdGroupForm from 'components/AdGroups/AdGroupForm/AdGroupForm'; @reactMixin.decorate(Lifecycle) class AdGroupCreatePage extends Component { constructor(props) { super(props); this.routerWillLeave = this.routerWillLeave.bind(this); } componentWillMount(){ this.props.Campaign.rows = []; this.props.AdGroup.details = {}; } componentDidMount(){ this.fetchAdGroupDetails(this.props); } componentWillReceiveProps(nextProps) { if (nextProps.params.campaignId !== this.props.params.campaignId) { this.fetchCampaignDetails(nextProps); } } render() { let output = null; if(this.props.Campaign.details){ output = ( <div> <div className="form-module"> <div className="form-module-header">{(this.props.params.campaignId && this.props.Campaign.details.name) ? this.props.Campaign.details.name + ': ' : ''} Create Ad Group</div> <div className="form-module-body"> <AdGroupForm editMode={false} {...this.props}/> </div> </div> </div> ); } return output; } routerWillLeave() { if(this.props.App.formChanged){ return 'Your progress is not saved. Are you sure you want to leave?'; } } fetchAdGroupDetails(props) { const { dispatch } = props; updateDocTitle('Edit AdGroup'); if(this.props.params.campaignId !== undefined){ dispatch(fetchHierarchy('campaign', props)) .then(() => { if(this.props.Campaign.details.id){ updateDocTitle(this.props.Campaign.details.name + ': Create Ad Group'); } else{ props.history.replaceState(null, '/error404'); } }); } else{ dispatch(fetchAccounts()); } } } AdGroupCreatePage.propTypes = {}; // Which props do we want to inject, given the global state? function select(state) { return { App: state.App, Account: state.Account, Campaign: state.Campaign, AdGroup: state.AdGroup, Init: state.Init }; } // Wrap the component to inject dispatch and state into it export default connect(select)(AdGroupCreatePage);
common/routes/Main/containers/UserTracks.js
kuguarpwnz/musix
import React from 'react'; import { connect } from 'react-redux'; import { addTrack } from '../actions/tracks'; import { getSearchTracks } from '../reducers/search'; import Playlist from '../components/Playlist'; const mapStateToProps = (state) => ({ userAudio: state.user.audio, searchAudio: getSearchTracks(state) }); const mapDispatchToProps = { addTrack }; const UserTracks = ({ userAudio, searchAudio, addTrack }) => ( <Playlist tracks={ searchAudio.length ? searchAudio : userAudio } onClick={addTrack} /> ); export default connect(mapStateToProps, mapDispatchToProps)(UserTracks);
Webpack/待整理/Tutorial/webpack-demos by ruanyifeng/demo15/App.js
ymqy/LearnBook
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <h1>Hello World</h1> ); } }
webpack/scenes/RedHatRepositories/components/EnabledRepository/EnabledRepository.stories.js
ares/katello
import React from 'react'; import { storiesOf } from '@storybook/react'; import EnabledRepository from './EnabledRepository.js'; storiesOf('RedHat Repositories Page', module).add('Enabled Repository', () => ( <EnabledRepository id={638} name="Red Hat Enterprise Linux 6 Server Kickstart x86_64 6.8" releasever="6.8" arch="x86_64" type="rpm" /> ));
src/containers/HeroStats.js
byronsha/open_dota
import React from 'react' import {connect} from 'react-redux' import Loader from '../components/Loader' import HeroStatsNav from '../components/hero_stats/HeroStatsNav' import {fetchHeroStats} from '../actions/api' import { proSetOrderBy, proSetOrderDirection, publicSetOrderBy, publicSetOrderDirection } from '../actions/heroStats' class HeroStats extends React.Component { componentDidMount() { this.props.fetchHeroStats() } renderHeroStats() { if (this.props.heroStatsLoading) { return <Loader /> } else { return ( <div> {this.props.children && React.cloneElement(this.props.children, { ...this.props })} </div> ) } } render() { const { location, router, errorMessage } = this.props return ( <div> <HeroStatsNav router={router} /> {this.renderHeroStats()} {errorMessage && <div>{errorMessage}</div>} </div> ) } } function orderProHeroStats(stats, orderBy, direction) { const statsCopy = JSON.parse(JSON.stringify(stats)) return statsCopy.sort((a, b) => { if (direction === 'desc') { switch (orderBy) { case 'winrate': return b.pro_win / b.pro_pick - a.pro_win / a.pro_pick case 'picks': return b.pro_pick - a.pro_pick case 'bans': return b.pro_ban - a.pro_ban case 'name': return b.localized_name < a.localized_name ? -1 : 1 default: return b.localized_name < a.localized_name ? -1 : 1 } } else { switch (orderBy) { case 'winrate': return a.pro_win / a.pro_pick - b.pro_win / b.pro_pick case 'picks': return a.pro_pick - b.pro_pick case 'bans': return a.pro_ban - b.pro_ban case 'name': return a.localized_name < b.localized_name ? -1 : 1 default: return a.localized_name < b.localized_name ? -1 : 1 } } }) } function orderPublicHeroStats(stats, orderBy, direction) { const statsCopy = JSON.parse(JSON.stringify(stats)) return statsCopy.sort((a, b) => { if (direction === 'desc') { switch (orderBy) { case '1k_winrate': return b['1000_win'] / b['1000_pick'] - a['1000_win'] / a['1000_pick'] case '1k_picks': return b['1000_pick'] - a['1000_pick'] case '2k_winrate': return b['2000_win'] / b['2000_pick'] - a['2000_win'] / a['2000_pick'] case '2k_picks': return b['2000_pick'] - a['2000_pick'] case '3k_winrate': return b['3000_win'] / b['3000_pick'] - a['3000_win'] / a['3000_pick'] case '3k_picks': return b['3000_pick'] - a['3000_pick'] case '4k_winrate': return b['4000_win'] / b['4000_pick'] - a['4000_win'] / a['4000_pick'] case '4k_picks': return b['4000_pick'] - a['4000_pick'] case '5k_winrate': return b['5000_win'] / b['5000_pick'] - a['5000_win'] / a['5000_pick'] case '5k_picks': return b['5000_pick'] - a['5000_pick'] case 'name': return b.localized_name < a.localized_name ? -1 : 1 default: return b.localized_name < a.localized_name ? -1 : 1 } } else { switch (orderBy) { case '1k_winrate': return a['1000_win'] / a['1000_pick'] - b['1000_win'] / b['1000_pick'] case '1k_picks': return a['1000_pick'] - b['1000_pick'] case '2k_winrate': return a['2000_win'] / a['2000_pick'] - b['2000_win'] / b['2000_pick'] case '2k_picks': return a['2000_pick'] - b['2000_pick'] case '3k_winrate': return a['3000_win'] / a['3000_pick'] - b['3000_win'] / b['3000_pick'] case '3k_picks': return a['3000_pick'] - b['3000_pick'] case '4k_winrate': return a['4000_win'] / a['4000_pick'] - b['4000_win'] / b['4000_pick'] case '4k_picks': return a['4000_pick'] - b['4000_pick'] case '5k_winrate': return a['5000_win'] / a['5000_pick'] - b['5000_win'] / b['5000_pick'] case '5k_picks': return a['5000_pick'] - b['5000_pick'] case 'name': return a.localized_name < b.localized_name ? -1 : 1 default: return a.localized_name < b.localized_name ? -1 : 1 } } }) } function mapStateToProps(state) { const { heroStatsLoading, heroStats, errorMessage } = state.api const { proOrderBy, proOrderDirection, publicOrderBy, publicOrderDirection } = state.heroStats const proStats = orderProHeroStats(heroStats, proOrderBy, proOrderDirection) const publicStats = orderPublicHeroStats(heroStats, publicOrderBy, publicOrderDirection) return { heroStatsLoading, heroStatsPro: proStats, heroStatsPublic: publicStats, errorMessage, proOrderBy, proOrderDirection, publicOrderBy, publicOrderDirection } } const mapDispatchToProps = ({ fetchHeroStats, proSetOrderBy, proSetOrderDirection, publicSetOrderBy, publicSetOrderDirection }) export default connect( mapStateToProps, mapDispatchToProps )(HeroStats)
app/javascript/mastodon/features/ui/components/image_loader.js
pixiv/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import ZoomableImage from './zoomable_image'; export default class ImageLoader extends React.PureComponent { static propTypes = { alt: PropTypes.string, src: PropTypes.string.isRequired, previewSrc: PropTypes.string, width: PropTypes.number, height: PropTypes.number, onClick: PropTypes.func, } static defaultProps = { alt: '', width: null, height: null, }; state = { loading: true, error: false, } removers = []; canvas = null; get canvasContext() { if (!this.canvas) { return null; } this._canvasContext = this._canvasContext || this.canvas.getContext('2d'); return this._canvasContext; } componentDidMount () { this.loadImage(this.props); } componentWillReceiveProps (nextProps) { if (this.props.src !== nextProps.src) { this.loadImage(nextProps); } } componentWillUnmount () { this.removeEventListeners(); } loadImage (props) { this.removeEventListeners(); this.setState({ loading: true, error: false }); Promise.all([ props.previewSrc && this.loadPreviewCanvas(props), this.hasSize() && this.loadOriginalImage(props), ].filter(Boolean)) .then(() => { this.setState({ loading: false, error: false }); this.clearPreviewCanvas(); }) .catch(() => this.setState({ loading: false, error: true })); } loadPreviewCanvas = ({ previewSrc, width, height }) => new Promise((resolve, reject) => { const image = new Image(); const removeEventListeners = () => { image.removeEventListener('error', handleError); image.removeEventListener('load', handleLoad); }; const handleError = () => { removeEventListeners(); reject(); }; const handleLoad = () => { removeEventListeners(); if (width && height) { this.canvasContext.drawImage(image, 0, 0, width, height); } resolve(); }; image.addEventListener('error', handleError); image.addEventListener('load', handleLoad); image.src = previewSrc; this.removers.push(removeEventListeners); }) clearPreviewCanvas () { const { width, height } = this.canvas; if (width && height) { this.canvasContext.clearRect(0, 0, width, height); } } loadOriginalImage = ({ src }) => new Promise((resolve, reject) => { const image = new Image(); const removeEventListeners = () => { image.removeEventListener('error', handleError); image.removeEventListener('load', handleLoad); }; const handleError = () => { removeEventListeners(); reject(); }; const handleLoad = () => { removeEventListeners(); resolve(); }; image.addEventListener('error', handleError); image.addEventListener('load', handleLoad); image.src = src; this.removers.push(removeEventListeners); }); removeEventListeners () { this.removers.forEach(listeners => listeners()); this.removers = []; } hasSize () { const { width, height } = this.props; return typeof width === 'number' && typeof height === 'number'; } setCanvasRef = c => { this.canvas = c; } render () { const { alt, src, width, height, onClick } = this.props; const { loading } = this.state; const className = classNames('image-loader', { 'image-loader--loading': loading, 'image-loader--amorphous': !this.hasSize(), }); return ( <div className={className}> {loading ? width && height && ( <canvas className='image-loader__preview-canvas' ref={this.setCanvasRef} width={width} height={height} /> ) : ( <ZoomableImage alt={alt} src={src} onClick={onClick} /> )} </div> ); } }
web/src/viewer/Viewer.js
bolddp/pixerva
import React, { Component } from 'react'; import Rating from './Rating'; import Hourglass from './Hourglass'; import PauseIndicator from './PauseIndicator'; import ErrorIndicator from './ErrorIndicator'; import DateLabel from './DateLabel'; import Menu from './Menu'; import Canvas from './Canvas'; import imageProvider from '../service/imageProvider'; import keyboardListener from '../service/keyboardListener'; import './Viewer.css'; export default class Viewer extends Component { constructor(props) { super(props); this.handleMouseMove = this.handleMouseMove.bind(this); this.state = { isBusy: false, isPaused: false, displayMenu: false, dateTaken: 0, rating: 0, backgroundColor: '#333333' } } componentDidMount() { imageProvider.setup(this); keyboardListener.setup(imageProvider); document.addEventListener('mousemove', this.handleMouseMove, false); } componentWillUnmount() { keyboardListener.teardown(); document.removeEventListener('mousemove', this.handleMouseMove); return imageProvider.resetSchedule(); } handleMouseMove(event) { this.setMenuVisible(true); } onImageUpdate(imageData, img) { console.debug(`Image data: ${JSON.stringify(imageData)}`); return new Promise((resolve, reject) => { this.setState({ ...this.state, errorInfo: null, img, rating: imageData.rating, dateTaken: imageData.dateTaken }) resolve(); }); } onRatingUpdate(rating) { return new Promise((resolve, reject) => { this.setState({ ...this.state, rating }); resolve(); }); } onBusy(value) { console.debug(`onBusy: ${value}`); return new Promise((resolve, reject) => { this.setState({ ...this.state, isBusy: value }); resolve(); }); } onPause(value) { console.debug(`Viewer.onPause: ${value}`); return new Promise((resolve, reject) => { this.setState({ ...this.state, isPaused: value }) }); } onError(error, retryDelay) { return new Promise((resolve, reject) => { this.setState({ ...this.state, errorInfo: { message: error.message || error.statusText, retryDelay } }) resolve(); }); } setMenuVisible(value) { if (this.state.displayMenu !== value) { this.setState({ ...this.state, displayMenu: value }); } if (value) { if (this.hideMenuTimer) { clearTimeout(this.hideMenuTimer); this.hideMenuTimer = 0; } this.hideMenuTimer = setTimeout(() => this.setMenuVisible(false), 5000); } } handleKeyPress(e) { e = e || window.event; if (e.keyCode === 38) { alert('up!'); } } render() { return ( <div id="viewer" className={ this.state.displayMenu ? '' : 'noCursor' } style={{ position: 'relative' }}> <div style={{ position: 'absolute', right: '10px', bottom: '10px' }}> <Rating rating={this.state.rating} /> <div style={{ clear: 'both' }}> <DateLabel dateTaken={this.state.dateTaken} /> <Hourglass isBusy={this.state.isBusy} /> <PauseIndicator isPaused={this.state.isPaused} /> <ErrorIndicator errorInfo={this.state.errorInfo} /> </div> </div> <Menu isVisible={this.state.displayMenu} /> <Canvas img={this.state.img} backgroundColor={this.state.backgroundColor} /> </div> ); } }
frontend/src/Calendar/CalendarConnector.js
Radarr/Radarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import * as commandNames from 'Commands/commandNames'; import * as calendarActions from 'Store/Actions/calendarActions'; import { clearMovieFiles, fetchMovieFiles } from 'Store/Actions/movieFileActions'; import { clearQueueDetails, fetchQueueDetails } from 'Store/Actions/queueActions'; import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector'; import hasDifferentItems from 'Utilities/Object/hasDifferentItems'; import selectUniqueIds from 'Utilities/Object/selectUniqueIds'; import { registerPagePopulator, unregisterPagePopulator } from 'Utilities/pagePopulator'; import Calendar from './Calendar'; const UPDATE_DELAY = 3600000; // 1 hour function createMapStateToProps() { return createSelector( (state) => state.calendar, (state) => state.settings.ui.item.firstDayOfWeek, createCommandExecutingSelector(commandNames.REFRESH_MOVIE), (calendar, firstDayOfWeek, isRefreshingMovie) => { return { ...calendar, isRefreshingMovie, firstDayOfWeek }; } ); } const mapDispatchToProps = { ...calendarActions, fetchMovieFiles, clearMovieFiles, fetchQueueDetails, clearQueueDetails }; class CalendarConnector extends Component { // // Lifecycle constructor(props, context) { super(props, context); this.updateTimeoutId = null; } componentDidMount() { const { useCurrentPage, fetchCalendar, gotoCalendarToday } = this.props; registerPagePopulator(this.repopulate); if (useCurrentPage) { fetchCalendar(); } else { gotoCalendarToday(); } this.scheduleUpdate(); } componentDidUpdate(prevProps) { const { items, time, view, isRefreshingMovie, firstDayOfWeek } = this.props; if (hasDifferentItems(prevProps.items, items)) { const movieFileIds = selectUniqueIds(items, 'movieFileId'); if (movieFileIds.length) { this.props.fetchMovieFiles({ movieFileIds }); } if (items.length) { this.props.fetchQueueDetails(); } } if (prevProps.time !== time) { this.scheduleUpdate(); } if (prevProps.firstDayOfWeek !== firstDayOfWeek) { this.props.fetchCalendar({ time, view }); } if (prevProps.isRefreshingMovie && !isRefreshingMovie) { this.props.fetchCalendar({ time, view }); } } componentWillUnmount() { unregisterPagePopulator(this.repopulate); this.props.clearCalendar(); this.props.clearQueueDetails(); this.props.clearMovieFiles(); this.clearUpdateTimeout(); } // // Control repopulate = () => { const { time, view } = this.props; this.props.fetchQueueDetails({ time, view }); this.props.fetchCalendar({ time, view }); }; scheduleUpdate = () => { this.clearUpdateTimeout(); this.updateTimeoutId = setTimeout(this.updateCalendar, UPDATE_DELAY); }; clearUpdateTimeout = () => { if (this.updateTimeoutId) { clearTimeout(this.updateTimeoutId); } }; updateCalendar = () => { this.props.gotoCalendarToday(); this.scheduleUpdate(); }; // // Listeners onCalendarViewChange = (view) => { this.props.setCalendarView({ view }); }; onTodayPress = () => { this.props.gotoCalendarToday(); }; onPreviousPress = () => { this.props.gotoCalendarPreviousRange(); }; onNextPress = () => { this.props.gotoCalendarNextRange(); }; // // Render render() { return ( <Calendar {...this.props} onCalendarViewChange={this.onCalendarViewChange} onTodayPress={this.onTodayPress} onPreviousPress={this.onPreviousPress} onNextPress={this.onNextPress} /> ); } } CalendarConnector.propTypes = { useCurrentPage: PropTypes.bool.isRequired, time: PropTypes.string, view: PropTypes.string.isRequired, firstDayOfWeek: PropTypes.number.isRequired, items: PropTypes.arrayOf(PropTypes.object).isRequired, isRefreshingMovie: PropTypes.bool.isRequired, setCalendarView: PropTypes.func.isRequired, gotoCalendarToday: PropTypes.func.isRequired, gotoCalendarPreviousRange: PropTypes.func.isRequired, gotoCalendarNextRange: PropTypes.func.isRequired, clearCalendar: PropTypes.func.isRequired, fetchCalendar: PropTypes.func.isRequired, fetchMovieFiles: PropTypes.func.isRequired, clearMovieFiles: PropTypes.func.isRequired, fetchQueueDetails: PropTypes.func.isRequired, clearQueueDetails: PropTypes.func.isRequired }; export default connect(createMapStateToProps, mapDispatchToProps)(CalendarConnector);
test/Form/index.js
WolfgaungBeer/scado
import React from 'react'; import styled from 'styled-components'; import { Text } from '../../src/scado'; import Form from './Form'; const Wrapper = styled.div` margin-top: 3rem; width: 100%; `; const FormWrapper = styled.div` width: 40%; margin: auto; `; const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); const onFormSubmit = values => sleep(2000).then(() => console.log(values)); // eslint-disable-line const FormPage = () => ( <Wrapper> <FormWrapper> <Text.H1 color="black" scale="xl">Neuen Account anlegen:</Text.H1> <Form onSubmit={onFormSubmit} /> </FormWrapper> </Wrapper> ); export default FormPage;
src/components/SelectInput/SelectInput.stories.js
InsideSalesOfficial/insidesales-components
import React from "react"; import { storiesOf, action } from "@storybook/react"; import styled, { ThemeProvider } from "styled-components"; import _ from "lodash"; import { renderThemeIfPresentOrDefault, generateFlexedThemeBackground, colors, typography } from "../styles"; import Icons from "../icons"; import { lineSelectInputTheme, transparentSelectInputTheme } from "./SelectInputThemes"; import SelectInput from "./"; const promotedOptions = [ { value: "101", label: "Promoted Option 1", disabled: true }, { value: "102", label: "Promoted Option 2" } ]; const genericOptions = [ { value: "1", label: "Option One" }, { value: "2", label: "Option Two" }, { value: "3", label: "Option Three" }, { value: "4", label: "Option Four" }, { value: "5", label: "Option Five" }, { value: "6", label: "Option Six" }, { value: "7", label: "Option Seven" }, { value: "8", label: "Option Eight" }, { value: "9", label: "Option Nine" }, { value: "10", label: "Option Ten" }, { value: "11", label: "A really long string A really long string A really long string A really long string A really long string A really long string A really long string A really long string A really long string A really long string" } ]; const selectedOptions = ["1", "2"]; const AddButton = styled.div` ${typography.body2}; color: ${renderThemeIfPresentOrDefault({ key: "brand01", defaultValue: colors.green })}; padding-left: 32px; position: relative; svg { position: absolute; left: 0; } `; function wrapComponentWithContainerAndTheme(theme, Component, wrapperStyling) { const storyContainerStyle = generateFlexedThemeBackground( { theme }, { padding: "16px 16px" } ); return ( <ThemeProvider theme={theme}> <div style={{ ...storyContainerStyle, ...wrapperStyling }}> {Component} </div> </ThemeProvider> ); } storiesOf("Form", module) .addWithChapters("Default SelectInput", renderChapterWithTheme({})) .addWithChapters( "SelectInput w/ BlueYellowTheme", renderChapterWithTheme(colors.blueYellowTheme) ); function renderChapterWithTheme(theme) { const darkExample = { height: "220px", backgroundColor: theme.primary01 || "#2a434a", padding: "16px" }; const lightExample = { height: "220px", backgroundColor: theme.primary01 || "#2a434a", padding: "16px" }; return { info: ` Usage ~~~ import React from 'react'; import {SelectInput} from 'insidesales-components'; ~~~ `, chapters: [ { sections: [ { title: "Default Theme", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput onChange={action("Option Selected")} options={genericOptions} />, darkExample ) }, { subtitle: "Header Label", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput onChange={action("Option Selected")} headerLabel="Custom Label" options={genericOptions} />, darkExample ) }, { subtitle: "Custom Label", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput onChange={action("Option Selected")} defaultLabel="Custom Label" options={genericOptions} />, darkExample ) }, { subtitle: "Disabled", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput options={genericOptions} isDisabled onChange={action("Option Selected")} defaultLabel="Custom Default" />, darkExample ) }, { title: "Line Select Input Theme", subtitle: "Generally used in modals (lineSelectInputTheme)", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput options={genericOptions} onChange={action("Option Selected")} defaultLabel="Custom Selected Option Name" theme={lineSelectInputTheme} />, lightExample ) }, { title: "Transparent Select Input Theme", subtitle: "Used as filter on People page (transparentSelectInputTheme)", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput options={genericOptions} onChange={action("Option Selected")} defaultLabel="Custom Default" theme={transparentSelectInputTheme} />, darkExample ) }, { subtitle: "Disabled Transparent Select Input Theme", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput options={genericOptions} onChange={action("Option Selected")} defaultLabel="Custom Default" isDisabled theme={transparentSelectInputTheme} />, darkExample ) }, { title: "Additional state for options", subtitle: "Promoted Items", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput options={genericOptions} theme={lineSelectInputTheme} onChange={action("Option Selected")} defaultLabel={""} promotedOptions={promotedOptions} />, lightExample ) }, { title: "Searchable Options", subtitle: "Places a search input at the top of the options list.", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput options={genericOptions} theme={lineSelectInputTheme} onChange={action("Option Selected")} defaultLabel={""} searchable />, lightExample ) }, { title: "Searchable div Options", subtitle: "Searchable list of divs", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput options={_.map(genericOptions, opt => ({ value: opt.value, label: <div>{opt.label}</div>, searchText: opt.label }))} theme={lineSelectInputTheme} onChange={action("Option Selected")} defaultLabel={""} searchable />, lightExample ) }, { title: "Add Button Select List", subtitle: `Shows the select input as an Add button instead of the select input styling. The defaultLabel prop will determing the button text. This is convenient for when you need a select list to choose options from to add to another list.`, sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput options={genericOptions} theme={lineSelectInputTheme} onChange={action("Option Selected")} defaultLabel={"ADD"} addButtonList searchable />, {} ) }, { title: "Multi Select", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput onChange={action("Option Selected")} options={genericOptions} value={selectedOptions} multiSelect />, darkExample ) }, { title: "Multi Select None Selected", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput onChange={action("Option Selected")} options={genericOptions} value={[]} multiSelect />, darkExample ) }, { title: "Multi Select/Bottom Action Area", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput onChange={action("Option Selected")} options={genericOptions} value={selectedOptions} multiSelect selectOptionsWidth={250} bottomActionArea={ <AddButton> <Icons.AddCircleIcon fill={colors.green} size={{ width: 24, height: 24 }} />{" "} {"Add Tag"} </AddButton> } />, darkExample ) }, { title: "Custom Dropdown Width", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput onChange={action("Option Selected")} options={genericOptions} value={selectedOptions} selectOptionsWidth={600} multiSelect />, { ...darkExample, width: "400px" } ) }, { title: "Dropdown Max Height", sectionFn: () => wrapComponentWithContainerAndTheme( theme, <SelectInput onChange={action("Option Selected")} options={genericOptions} value={selectedOptions} maxHeight={"600px"} multiSelect />, darkExample ) } ] } ] }; }
src/index.js
mdvb1001/BlogReactRedux
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { Router, browserHistory } from 'react-router'; // Must import both of these... import reducers from './reducers'; import routes from "./routes"; import promise from 'redux-promise'; const createStoreWithMiddleware = applyMiddleware( promise )(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <Router history={browserHistory} routes={routes} /> </Provider> , document.querySelector('.container'));
src/routes.js
nfcortega89/nikkotoonaughty
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/app'; import Main from './components/main'; import Card from './components/card'; export default ( <Route path="/" component={App}> <IndexRoute component={Main} /> <Route path="/redirect" component={Main} /> </Route> )
src/svg-icons/content/undo.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentUndo = (props) => ( <SvgIcon {...props}> <path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/> </SvgIcon> ); ContentUndo = pure(ContentUndo); ContentUndo.displayName = 'ContentUndo'; ContentUndo.muiName = 'SvgIcon'; export default ContentUndo;
frontWeb/main/react/react-router/basic/dev/animationExample.js
skycolor/study
import React from 'react' import { CSSTransitionGroup } from 'react-transition-group' import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom' /* you'll need this CSS somewhere .fade-enter { opacity: 0; z-index: 1; } .fade-enter.fade-enter-active { opacity: 1; transition: opacity 250ms ease-in; } */ const AnimationExample = () => ( <Router> <Route render={({ location }) => ( <div style={styles.fill}> <Route exact path="/" render={() => ( <Redirect to="/10/90/50"/> )}/> <ul style={styles.nav}> <NavLink to="/10/90/50">Red</NavLink> <NavLink to="/120/100/40">Green</NavLink> <NavLink to="/200/100/40">Blue</NavLink> <NavLink to="/310/100/50">Pink</NavLink> </ul> <div style={styles.content}> <CSSTransitionGroup transitionName="fade" transitionEnterTimeout={300} transitionLeaveTimeout={300} > {/* no different than other usage of CSSTransitionGroup, just make sure to pass `location` to `Route` so it can match the old location as it animates out */} <Route location={location} key={location.key} path="/:h/:s/:l" component={HSL} /> </CSSTransitionGroup> </div> </div> )}/> </Router> ) const NavLink = (props) => ( <li style={styles.navItem}> <Link {...props} style={{ color: 'inherit' }}/> </li> ) const HSL = ({ match: { params } }) => ( <div style={{ background: `hsl(${params.h}, ${params.s}%, ${params.l}%)` }}>hsl({params.h}, {params.s}%, {params.l}%)</div> ) const styles = {} styles.fill = { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0 } styles.content = { top: '40px', textAlign: 'center' } styles.nav = { padding: 0, margin: 0, position: 'absolute', top: 0, height: '40px', width: '100%', display: 'flex' } styles.navItem = { textAlign: 'center', flex: 1, listStyleType: 'none', padding: '10px' } styles.hsl = { color: 'white', paddingTop: '20px', fontSize: '30px' } export default AnimationExample
src/Voting/Question/Question.js
cityofsurrey/polltal-app
import React from 'react' import PropTypes from 'prop-types' import Radium from 'radium' import FlatCard from 'components/FlatCard' import Header from './Header' import Response from './Response' const styles = { card: { padding: 0, }, content: { padding: '20px 20px 10px', '@media (min-width: 1150px)': { padding: '70px 50px', }, }, backgroundCard: { position: 'absolute', width: '95%', margin: 0, top: -10, left: '2.5%', zIndex: -5, '@media (min-width: 1150px)': { display: 'none', }, }, } const Question = ({ question, responses, length, index, onSelect, }) => ( <FlatCard style={styles.card}> <div style={styles.content}> { question ? ( <div> <FlatCard style={styles.backgroundCard} /> <Header length={length} index={index} question={question.question} /> <Response selected={responses[question.questionId]} onSelect={onSelect} id={question.questionId} /> </div> ) : <div>No questions are released...</div> } </div> </FlatCard> ) Question.propTypes = { question: PropTypes.objectOf(PropTypes.oneOfType([ PropTypes.object, PropTypes.array, PropTypes.string, PropTypes.bool, ])), responses: PropTypes.objectOf(PropTypes.string), length: PropTypes.number, index: PropTypes.number, onSelect: PropTypes.func, } Question.defaultProps = { question: null, responses: {}, length: 0, index: 0, onSelect: () => {}, } export default Radium(Question)
docs/app/Examples/elements/Header/Variations/HeaderExampleDividing.js
koenvg/Semantic-UI-React
import React from 'react' import { Header } from 'semantic-ui-react' const HeaderExampleDividing = () => ( <Header as='h3' dividing> Dividing Header </Header> ) export default HeaderExampleDividing
app/components/Home.js
eccorley/electron-starter
import React, { Component } from 'react'; import { Link } from 'react-router'; export default class Home extends Component { render() { return ( <div> <div> </div> </div> ); } }
src/proptypes.js
brekk/glass-menagerie
import React from 'react' import curry from 'lodash/fp/curry' import clone from 'lodash/fp/cloneDeep' import memoize from 'lodash/fp/memoize' import identity from 'lodash/fp/identity' import flow from 'lodash/fp/flow' import compact from 'lodash/fp/compact' import reduce from 'lodash/fp/reduce' import merge from 'lodash/fp/merge' import toPairs from 'lodash/fp/toPairs' import map from 'lodash/fp/map' import {mergePairs} from 'f-utility/fp/merge-pairs' import random from 'f-utility/testing/random' import {debug as makeDebugger} from 'f-utility/dev/debug' const LIBRARY = `glass-menagerie` const _debug = makeDebugger(LIBRARY) const debug = { genericPropTypeLookup: _debug([`proptypes`, `genericPropTypeLookup`]), compareFnToKeyPair: _debug([`proptypes`, `compareFnToKeyPair`]), alterKV: _debug([`proptypes`, `alterKV`]), alterRequiredKeys: _debug([`proptypes`, `alterRequiredKeys`]), inferPropTypeObject: _debug([`proptypes`, `inferPropTypeObject`]), genericInferPropType: _debug([`proptypes`, `genericInferPropType`]), convertSimplePropTypes: _debug([`proptypes`, `convertSimplePropTypes`]) } export const {PropTypes: types} = React export const genericPropTypeLookup = curry(function _propTypeLookup( givenTypes, isRequired, lookup, x ) { if (!givenTypes[lookup] || (isRequired && !givenTypes[lookup].isRequired)) { throw new TypeError(`Expected to be given valid propType method. (${lookup})`) } const match = isRequired ? givenTypes[lookup].isRequired : givenTypes[lookup] return x === match }) // we export the generic for easier testing, but in almost all other cases // we wanna preload the lookup with React.PropTypes export const isRequiredPropType = genericPropTypeLookup(types, true) // throw this on the function so our devs don't have to look it up by hand later isRequiredPropType.types = types export const isPropType = genericPropTypeLookup(types, false) isPropType.types = types export const compareFnToKeyPair = curry(function _compareFnToKeyPair(toCompare, keyPair) { const [key, typeFn] = keyPair if (typeof toCompare === `function`) { const matches = typeFn(toCompare) if (matches) { return key } } return toCompare }) const alterKV = curry((alterKey, alterValue, pair) => { // if (!pair || !pair[0] || !pair[1]) { // return null // } const [key, value] = pair return {[alterKey(key)]: alterValue(value)} }) const capitalize = memoize((str) => (str[0].toUpperCase() + str.slice(1))) export const alterRequiredKeys = (inputObject) => { const consume = flow( (x) => x.required, toPairs, map(alterKV((k) => `required${capitalize(k)}`, identity)), compact, reduce(merge, {}) ) const copy = clone(inputObject) const consumed = consume(copy) delete copy.required return { ...consumed, ...copy } } export const is = { required: { array: isRequiredPropType(`array`), bool: isRequiredPropType(`bool`), func: isRequiredPropType(`func`), number: isRequiredPropType(`number`), object: isRequiredPropType(`object`), string: isRequiredPropType(`string`), any: isRequiredPropType(`any`), element: isRequiredPropType(`element`), node: isRequiredPropType(`node`) }, // unrequired array: isPropType(`array`), bool: isPropType(`bool`), func: isPropType(`func`), number: isPropType(`number`), object: isPropType(`object`), string: isPropType(`string`), any: isPropType(`any`), element: isPropType(`element`), node: isPropType(`node`), // functions, unrequited instanceOf: isPropType(`instanceOf`), arrayOf: isPropType(`arrayOf`), objectOf: isPropType(`objectOf`), oneOf: isPropType(`oneOf`), oneOfType: isPropType(`oneOfType`), shape: isPropType(`shape`) } const resolveWhenNotAFunction = (x) => { if (typeof x === `function`) { return false } return x } export const genericInferPropType = curry(function _inferPropType(dataStructure, fnToMatch) { const inferenceFunction = flow( alterRequiredKeys, toPairs, reduce(compareFnToKeyPair, fnToMatch), resolveWhenNotAFunction ) return inferenceFunction(dataStructure) }) export const inferPropType = genericInferPropType(is) export const inferPropTypeObject = flow( toPairs, map(flow( ([k, v]) => ([k, inferPropType(v)]), (pair) => { return (pair && pair[0] && pair[1]) ? {[pair[0]]: pair[1]} : null } )), compact, reduce(merge, {}) ) export const convertSimplePropTypes = (y) => { const match = `required` const reqIndex = y.indexOf(match) const x = reqIndex > -1 ? y.slice(match.length).toLowerCase() : y debug.convertSimplePropTypes(`reqIndex`, `council of thirteen`, x, reqIndex) if (x === `object` || x === `any`) { return {} } else if (x === `bool`) { return true } else if (x === `string`) { return random.word(10) } else if (x === `number`) { return random.floorMin(1, 1e3) } else if (x === `array`) { return random.word(10).split(``) } else if (x === `func`) { return identity } else if (x === `node` || x === `element`) { return (<span />) } } export const createMock = (typesObject) => { return flow( inferPropTypeObject, toPairs, map(([k, v]) => ([k, convertSimplePropTypes(v)])), mergePairs )(typesObject) }
client/src/components/Forecast.js
kanissimov/meteo-demo
import React, { Component } from 'react'; import ReactHighcharts from 'react-highcharts'; class Forecast extends Component { render() { const { config } = this.props; return config ? <ReactHighcharts config={config} ref="chart" /> : <div />; } } export default Forecast; // componentDidMount() { // let chart = this.refs.chart.getChart(); // chart.series[0].addPoint({x: 10, y: 12}); // }
src/components/modals/EditGroup.react.js
EaglesoftZJ/iGem_Web
/* * Copyright (C) 2016 Actor LLC. <https://actor.im> */ import React, { Component } from 'react'; import { Container } from 'flux/utils'; import { FormattedMessage } from 'react-intl'; import Modal from 'react-modal'; import { ModalTypes } from '../../constants/ActorAppConstants'; import EditGroupStore from '../../stores/EditGroupStore'; import EditGroupActionCreators from '../../actions/EditGroupActionCreators'; import TextField from '../common/TextField.react'; import PictureChanger from './profile/PictureChanger.react'; class EditGroup extends Component { static getStores() { return [EditGroupStore]; } static calculateState() { return { group: EditGroupStore.getGroup(), isAdmin: EditGroupStore.isAdmin(), title: EditGroupStore.getTitle(), about: EditGroupStore.getAbout() } } constructor(props) { super(props); this.handleClose = this.handleClose.bind(this); this.handleTitleChange = this.handleTitleChange.bind(this); this.handleAboutChange = this.handleAboutChange.bind(this); this.handleSave = this.handleSave.bind(this); this.handleChangeGroupAvatar = this.handleChangeGroupAvatar.bind(this); this.handleRemoveGroupPicture = this.handleRemoveGroupPicture.bind(this); } handleClose() { EditGroupActionCreators.hide(); } handleTitleChange(event) { this.setState({ title: event.target.value }); } handleAboutChange(event) { this.setState({ about: event.target.value }); } handleSave() { const { group, title, about, isAdmin } = this.state; EditGroupActionCreators.editGroupTitle(group.id, title); if (isAdmin) { EditGroupActionCreators.editGroupAbout(group.id, about); } this.handleClose(); } handleChangeGroupAvatar(croppedImage) { const { group } = this.state; EditGroupActionCreators.changeGroupAvatar(group.id, croppedImage); } handleRemoveGroupPicture() { const { group } = this.state; EditGroupActionCreators.removeGroupAvatar(group.id); } renderTitle() { const { title, isAdmin } = this.state; return ( <TextField className="input__material--wide" floatingLabel={<FormattedMessage id="modal.group.name"/>} onChange={this.handleTitleChange} disabled={!isAdmin} ref="name" value={title}/> ); } renderAbout() { const { isAdmin, about } = this.state; if (!isAdmin) return null; return ( <div className="about"> <label htmlFor="about"><FormattedMessage id="modal.group.about"/></label> <textarea className="textarea" value={about} onChange={this.handleAboutChange} id="about"/> </div> ); } render() { const { group } = this.state; return ( <Modal overlayClassName="modal-overlay" className="modal" onRequestClose={this.handleClose} isOpen> <div className="edit-group"> <div className="modal__content"> <header className="modal__header"> <i className="modal__header__icon material-icons">edit</i> <FormattedMessage id="modal.group.title" tagName="h1"/> <button className="button button--lightblue" onClick={this.handleSave}> <FormattedMessage id="button.done"/> </button> </header> <div className="modal__body row"> <div className="col-xs"> {this.renderTitle()} {this.renderAbout()} </div> <PictureChanger {...group} small fromModal={ModalTypes.EDIT_GROUP} onRemove={this.handleRemoveGroupPicture} onChange={this.handleChangeGroupAvatar}/> </div> </div> </div> </Modal> ); } } export default Container.create(EditGroup, { pure: false });
src/components/HistoryUserBookings.js
onlinebooking/booking-frontend
import React from 'react'; import classNames from 'classnames'; import UserBookingListItem from './UserBookingListItem'; import { range } from 'lodash'; import { humanizeBookingStatus } from '../utils/booking'; import { ListGroup, Badge, FormGroup, FormControl, ButtonGroup, Button } from 'react-bootstrap'; // TODO: Let it become an util general purpose component... class Paginator extends React.Component { render() { const { count, pages, pageSize, currentPage, onSetPage } = this.props; return ( <div className="paginator"> <ButtonGroup> {range(1, pages + 1).map(page => ( <Button key={page} onClick={() => onSetPage(page)} className={classNames({ 'active': page === currentPage })}>{page}</Button> ))} </ButtonGroup> </div> ); } } class HistoryUserBookingsList extends React.Component { render() { const { bookings } = this.props; return ( <ListGroup> {bookings.map(booking => ( <UserBookingListItem {...booking} key={booking.id} /> ))} </ListGroup> ); } } class HistoryUserBookingsControls extends React.Component { render() { return ( <div> {this.renderSearchBar()} </div> ); } renderSearchBar() { const { searchText, onSearchTextChanged } = this.props; return ( <FormGroup> <FormControl type="text" placeholder="Cerca" value={searchText} onChange={e => onSearchTextChanged(e.target.value)} /> </FormGroup> ); } } export default class HistoryUserBookings extends React.Component { render() { const { bookings, pagination, onSetPage, searchText, onSearchTextChanged } = this.props; return ( <div> <HistoryUserBookingsControls searchText={searchText} onSearchTextChanged={onSearchTextChanged} /> <hr /> <HistoryUserBookingsList bookings={bookings} /> <Paginator onSetPage={onSetPage} {...pagination} /> </div> ); } }
src/svg-icons/action/find-in-page.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionFindInPage = (props) => ( <SvgIcon {...props}> <path d="M20 19.59V8l-6-6H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c.45 0 .85-.15 1.19-.4l-4.43-4.43c-.8.52-1.74.83-2.76.83-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5c0 1.02-.31 1.96-.83 2.75L20 19.59zM9 13c0 1.66 1.34 3 3 3s3-1.34 3-3-1.34-3-3-3-3 1.34-3 3z"/> </SvgIcon> ); ActionFindInPage = pure(ActionFindInPage); ActionFindInPage.displayName = 'ActionFindInPage'; ActionFindInPage.muiName = 'SvgIcon'; export default ActionFindInPage;
src/Parser/MistweaverMonk/Modules/Core/HealingDone.js
Yuyz0112/WoWAnalyzer
import React from 'react'; import { formatThousands, formatNumber } from 'common/format'; import Module from 'Parser/Core/Module'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; class HealingDone extends Module { statistic() { return ( <StatisticBox icon={( <img src="/img/healing.png" style={{ border: 0 }} alt="Healing" /> )} value={`${formatNumber(this.owner.totalHealing / this.owner.fightDuration * 1000)} HPS`} label="Healing done" tooltip={`The total healing done recorded was ${formatThousands(this.owner.totalHealing)}.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(0); } export default HealingDone;
src/clincoded/static/components/methods.js
ClinGen/clincoded
'use strict'; import React from 'react'; import _ from 'underscore'; import moment from 'moment'; import { Input } from '../libs/bootstrap/form'; import * as curator from './curator'; // Utilities so any pages that have a Methods panel can use this shared code // To display the panel, and convert its values to an object. // This object assumes it has a React component's 'this', so these need to be called // with <method>.call(this). module.exports = { /** * Render a Methods panel. * @param {object} method - Methods data of evidence being curated. * @param {string} evidenceType - Type of evidence being curated (group, family, individual or case-control). * @param {string} prefix - Prefix to default form field names (only necessary for case-control). * @param {object} parentMethod - Methods data of "parent" evidence (e.g. a family's associated group). * @param {string} parentName - Name of "parent" evidence (Group or Family). */ render: function(method, evidenceType, prefix, parentMethod, parentName) { let isFamily = false; let isCaseControl = false; let hasParentMethods = false; let headerLabel; let specificMutationPlaceholder = 'Note any aspects of the genotyping method that may impact the strength of this evidence. For example: Was the entire gene sequenced, or were a few specific variants genotyped? Was copy number assessed?'; if (evidenceType === 'individual' || evidenceType === 'family') { if (parentMethod && ((parentMethod.previousTesting === true || parentMethod.previousTesting === false) || parentMethod.previousTestingDescription || (parentMethod.genomeWideStudy === true || parentMethod.genomeWideStudy === false) || parentMethod.genotypingMethods.length || parentMethod.specificMutationsGenotypedMethod) && parentName) { hasParentMethods = true; } if (evidenceType === 'family') { isFamily = true; } } else if (evidenceType === 'case-control') { isCaseControl = true; if (prefix === 'caseCohort_') { headerLabel = 'CASE'; } if (prefix === 'controlCohort_') { headerLabel = 'CONTROL'; } } return ( <div className={(isCaseControl) ? 'row section section-method' : 'row'}> {(isCaseControl) ? <h3><i className="icon icon-chevron-right"></i> Methods <span className="label label-group">{headerLabel}</span></h3> : null} {hasParentMethods ? <Input type="button" ref="copyparentmethods" wrapperClassName="col-sm-7 col-sm-offset-5 methods-copy" inputClassName="btn-copy btn-sm" title={'Copy Methods from Associated ' + parentName} clickHandler={module.exports.copy.bind(this, parentMethod, isCaseControl, prefix)} /> : null} {hasParentMethods ? curator.renderParentEvidence('Previous Testing Associated with ' + parentName + ':', (parentMethod.previousTesting === true ? 'Yes' : (parentMethod.previousTesting === false ? 'No' : ''))) : null} <Input type="select" ref={prefix ? prefix + 'prevtesting' : 'prevtesting'} label="Previous Testing:" defaultValue="none" value={curator.booleanToDropdown(method.previousTesting)} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group"> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="Yes">Yes</option> <option value="No">No</option> </Input> {hasParentMethods ? curator.renderParentEvidence('Description of Previous Testing Associated with ' + parentName + ':', parentMethod.previousTestingDescription) : null} <Input type="textarea" ref={prefix ? prefix + 'prevtestingdesc' : 'prevtestingdesc'} label="Description of Previous Testing:" rows="5" value={method.previousTestingDescription} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" /> {hasParentMethods ? curator.renderParentEvidence('Answer to Genome-Wide Analysis Methods Question Associated with ' + parentName + ':', (parentMethod.genomeWideStudy === true ? 'Yes' : (parentMethod.genomeWideStudy === false ? 'No' : ''))) : null} <Input type="select" ref={prefix ? prefix + 'genomewide' : 'genomewide'} label="Were genome-wide analysis methods used to identify the variant(s) described in this publication?:" defaultValue="none" value={curator.booleanToDropdown(method.genomeWideStudy)} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7 label-box-match-middle" groupClassName="form-group"> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="Yes">Yes</option> <option value="No">No</option> </Input> <h4 className="col-sm-7 col-sm-offset-5">Genotyping Method</h4> {hasParentMethods ? curator.renderParentEvidence('Method 1 Associated with ' + parentName + ':', parentMethod.genotypingMethods[0]) : null} <Input type="select" ref={prefix ? prefix + 'genotypingmethod1' : 'genotypingmethod1'} label="Method 1:" handleChange={this.handleChange} defaultValue="none" value={method.genotypingMethods && method.genotypingMethods[0] ? method.genotypingMethods[0] : null} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group"> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="Chromosomal microarray">Chromosomal microarray</option> <option value="Denaturing gradient gel">Denaturing gradient gel</option> <option value="Exome sequencing">Exome sequencing</option> <option value="Genotyping">Genotyping</option> <option value="High resolution melting">High resolution melting</option> <option value="Homozygosity mapping">Homozygosity mapping</option> <option value="Linkage analysis">Linkage analysis</option> <option value="Next generation sequencing panels">Next generation sequencing panels</option> <option value="Other">Other</option> <option value="PCR">PCR</option> <option value="Restriction digest">Restriction digest</option> <option value="Sanger sequencing">Sanger sequencing</option> <option value="SSCP">SSCP</option> <option value="Whole genome shotgun sequencing">Whole genome shotgun sequencing</option> </Input> {hasParentMethods ? curator.renderParentEvidence('Method 2 Associated with ' + parentName + ':', parentMethod.genotypingMethods[1]) : null} <Input type="select" ref={prefix ? prefix + 'genotypingmethod2' : 'genotypingmethod2'} label="Method 2:" defaultValue="none" value={method.genotypingMethods && method.genotypingMethods[1] ? method.genotypingMethods[1] : null} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputDisabled={prefix ? (prefix === 'caseCohort_' ? this.state.caseCohort_genotyping2Disabled : this.state.controlCohort_genotyping2Disabled) : this.state.genotyping2Disabled}> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="Chromosomal microarray">Chromosomal microarray</option> <option value="Denaturing gradient gel">Denaturing gradient gel</option> <option value="Exome sequencing">Exome sequencing</option> <option value="Genotyping">Genotyping</option> <option value="High resolution melting">High resolution melting</option> <option value="Homozygosity mapping">Homozygosity mapping</option> <option value="Linkage analysis">Linkage analysis</option> <option value="Next generation sequencing panels">Next generation sequencing panels</option> <option value="Other">Other</option> <option value="PCR">PCR</option> <option value="Restriction digest">Restriction digest</option> <option value="Sanger sequencing">Sanger sequencing</option> <option value="SSCP">SSCP</option> <option value="Whole genome shotgun sequencing">Whole genome shotgun sequencing</option> </Input> {hasParentMethods ? curator.renderParentEvidence('Description of genotyping method Associated with ' + parentName + ':', parentMethod.specificMutationsGenotypedMethod) : null} <Input type="textarea" ref={prefix ? prefix + 'specificmutation' : 'specificmutation'} label="Description of genotyping method:" rows="5" value={method.specificMutationsGenotypedMethod} placeholder={specificMutationPlaceholder} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" /> {isFamily ? <Input type="textarea" ref={prefix ? prefix + 'additionalinfomethod' : 'additionalinfomethod'} label="Additional Information about Family Method:" rows="8" value={method.additionalInformation} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" /> : null} </div> ); }, // Create method object based on the form values create: function(prefix) { var newMethod = {}; var value1, value2; // Put together a new 'method' object value1 = this.getFormValue(prefix ? prefix + 'prevtesting' : 'prevtesting'); if (value1 !== 'none') { newMethod.previousTesting = value1 === 'Yes'; } value1 = this.getFormValue(prefix ? prefix + 'prevtestingdesc' : 'prevtestingdesc'); if (value1) { newMethod.previousTestingDescription = value1; } value1 = this.getFormValue(prefix ? prefix + 'genomewide' : 'genomewide'); if (value1 !== 'none') { newMethod.genomeWideStudy = value1 === 'Yes'; } value1 = this.getFormValue(prefix ? prefix + 'genotypingmethod1' : 'genotypingmethod1'); value2 = this.getFormValue(prefix ? prefix + 'genotypingmethod2' : 'genotypingmethod2'); if (value1 !== 'none' || value2 !== 'none') { newMethod.genotypingMethods = _([value1, value2]).filter(function(val) { return val !== 'none'; }); } value1 = this.getFormValue(prefix ? prefix + 'specificmutation' : 'specificmutation'); if (value1) { newMethod.specificMutationsGenotypedMethod = value1; } value1 = this.getFormValue(prefix ? prefix + 'additionalinfomethod' : 'additionalinfomethod'); if (value1) { newMethod.additionalInformation = value1; } newMethod.dateTime = moment().format(); return Object.keys(newMethod).length ? newMethod : null; }, // Copy methods data from source object into form fields (expected to be initiated by a button click) copy: function(sourceMethod, isCaseControl, prefix, e) { e.preventDefault(); e.stopPropagation(); if (sourceMethod.previousTesting === true) { this.refs[prefix ? prefix + 'prevtesting' : 'prevtesting'].setValue('Yes'); } else if (sourceMethod.previousTesting === false) { this.refs[prefix ? prefix + 'prevtesting' : 'prevtesting'].setValue('No'); } if (sourceMethod.previousTestingDescription) { this.refs[prefix ? prefix + 'prevtestingdesc' : 'prevtestingdesc'].setValue(sourceMethod.previousTestingDescription); } if (sourceMethod.genomeWideStudy === true) { this.refs[prefix ? prefix + 'genomewide' : 'genomewide'].setValue('Yes'); } else if (sourceMethod.genomeWideStudy === false) { this.refs[prefix ? prefix + 'genomewide' : 'genomewide'].setValue('No'); } if (sourceMethod.genotypingMethods[0]) { this.refs[prefix ? prefix + 'genotypingmethod1' : 'genotypingmethod1'].setValue(sourceMethod.genotypingMethods[0]); // Check if the "Method 2" drop-down needs to be enabled if (isCaseControl) { if (prefix === 'caseCohort_') { if (this.state.caseCohort_genotyping2Disabled === true && sourceMethod.genotypingMethods[0] !== 'none') { this.setState({caseCohort_genotyping2Disabled: false}); } } else if (this.state.controlCohort_genotyping2Disabled === true && sourceMethod.genotypingMethods[0] !== 'none') { this.setState({controlCohort_genotyping2Disabled: false}); } } else if (this.state.genotyping2Disabled === true && sourceMethod.genotypingMethods[0] !== 'none') { this.setState({genotyping2Disabled: false}); } if (sourceMethod.genotypingMethods[1]) { this.refs[prefix ? prefix + 'genotypingmethod2' : 'genotypingmethod2'].setValue(sourceMethod.genotypingMethods[1]); } } if (sourceMethod.specificMutationsGenotypedMethod) { this.refs[prefix ? prefix + 'specificmutation' : 'specificmutation'].setValue(sourceMethod.specificMutationsGenotypedMethod); } } };
js/jqwidgets/demos/react/app/treemap/bindingtojson/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxTreeMap from '../../../jqwidgets-react/react_jqxtreemap.js'; class App extends React.Component { render () { let data = [ { "id": "2", "parentid": "1", "text": "Hot Chocolate", "value": "$5.2" }, { "id": "3", "parentid": "1", "text": "Peppermint Hot Chocolate", "value": "$4.0" }, { "id": "4", "parentid": "1", "text": "Salted Caramel Hot Chocolate", "value": "$2.4" }, { "id": "5", "parentid": "1", "text": "White Hot Chocolate", "value": "$2.5" }, { "text": "Chocolate Beverage", "id": "1", "parentid": "-1", "value": "$1.1" }, { "id": "6", "text": "Espresso Beverage", "parentid": "-1", "value": "$0.9" }, { "id": "7", "parentid": "6", "text": "Caffe Americano", "value": "$1.2" }, { "id": "8", "text": "Caffe Latte", "parentid": "6", "value": "$3.3" }, { "id": "9", "text": "Caffe Mocha", "parentid": "6", "value": "$2.5" }, { "id": "10", "text": "Cappuccino", "parentid": "6", "value": "$1.5" }, { "id": "11", "text": "Pumpkin Spice Latte", "parentid": "6", "value": "$1.6" }, { "id": "12", "text": "Frappuccino", "parentid": "-1" }, { "id": "13", "text": "Caffe Vanilla Frappuccino", "parentid": "12", "value": "$1.2" }]; let source = { datatype: "json", datafields: [ { name: 'id' }, { name: 'parentid' }, { name: 'text' }, { name: 'value' } ], id: 'id', localdata: data }; // create data adapter. let dataAdapter = new $.jqx.dataAdapter(source); // perform Data Binding. dataAdapter.dataBind(); // get the treemap sectors. The first parameter is the item's id. The second parameter is the parent item's id. The 'items' parameter represents // the sub items collection name. Each jqxTreeMap item has a 'label' property, but in the JSON data, we have a 'text' field. The last parameter // specifies the mapping between the 'text' and 'label' fields. let records = dataAdapter.getRecordsHierarchy('id', 'parentid', 'items', [{ name: 'text', map: 'label' }]); let renderCallbacks = { '*': (element, data) => { if (!data.parent) { element.css({ backgroundColor: '#fff', border: '1px solid #aaa' }); } else { let nThreshold = 105; let bgDelta = (data.rgb.r * 0.299) + (data.rgb.g * 0.587) + (data.rgb.b * 0.114); let foreColor = (255 - bgDelta < nThreshold) ? 'Black' : 'White'; element.css({ color: foreColor }); } } }; return ( <JqxTreeMap width={850} height={600} source={records} baseColor={'#0afaaa'} renderCallbacks={renderCallbacks} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
ui/src/app/components/modals/AddPipeline.js
mnewswanger/kube-ci
import React from 'react'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import PipelineForm from '../forms/Pipeline'; /** * A modal dialog can only be closed by selecting one of the actions. */ export default class AddPipeline extends React.Component { state = { open: false, }; handleOpen = () => { this.setState({open: true}); }; handleClose = () => { this.setState({open: false}); }; render() { const actions = [ <FlatButton label="Cancel" primary={true} onTouchTap={this.handleClose} />, <FlatButton label="Submit" primary={true} disabled={true} onTouchTap={this.handleClose} />, ]; return ( <div> <RaisedButton label="Add Pipeline" onTouchTap={this.handleOpen} /> <Dialog title="Create New Pipeline" actions={actions} modal={true} open={this.state.open} > <PipelineForm /> </Dialog> </div> ); } }
modules/time/DigitalClock.js
JandJGroup/MagicMirror
//Orginally copied from http://jsfiddle.net/rainev/vx4r5qzv/ import React from 'react'; var DigitalClockFace = React.createClass({ render: function () { var d = this.props.date; var millis = d.getMilliseconds(); var second = d.getSeconds() * 6 + millis * (6 / 1000); var minute = d.getMinutes(); // Get minute number var minuteZero = (minute <= 9) ? "0" : ""; // Add a zero in front of single digit numbers var hour = d.getHours(); // Get hour number; var postm = (hour >= 12) ? "PM" : "AM"; // this has to be done after postm calculation hour %= 12; // Convert to 12 12 hour format if (hour === 0) { hour = 12; } return ( <div className="digitalClock" style={{ height: 330 * this.props.scale, fontSize: 330 * this.props.scale }}> <div className="digitalHour">{hour}</div> <div className="digitalMinute">{minuteZero + minute}</div> <div className="digitalPostM">{postm}</div> </div> ); } }); function transform(str) { return { transform: str }; } function rotate(deg) { return 'rotate(' + deg + 'deg)'; } var DigitalClock = React.createClass({ getInitialState: function () { return { date: new Date() }; }, componentDidMount: function () { this.start(); }, start: function () { var self = this; (function tick() { self.setState({ date: new Date() }); requestAnimationFrame(tick); } ()); }, render: function () { return <DigitalClockFace date={this.state.date} scale={this.props.scale}/>; } }); export {DigitalClock};
src/ProfileMenuItem/index.js
christianalfoni/ducky-components
import LabelTab from '../LabelTab'; import ActionButton from '../ActionButton'; import Typography from '../Typography'; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import styles from './styles.css'; function ProfileMenuItem(props) { let icon = 'icon-check_circle'; let label = 'Aktivitet'; let caption = `Siste aktivitet ${props.dateOfLastActivity}`; let buttonIcon = 'icon-keyboard_arrow_right'; if (props.type.toUpperCase() === 'PERSONAL') { icon = 'icon-verified_user'; label = 'Personlige mål'; caption = `${props.numberGoals} aktive og kommende mål`; buttonIcon = 'icon-add'; } else if (props.type.toUpperCase() === 'INSIGHT') { icon = 'icon-timeline'; label = 'Innsikt'; const totalSavings = props.totalSavings.toLocaleString(); caption = `${totalSavings} kgCO\u2082e innspart totalt`; } else if (props.type.toUpperCase() === 'FOOTPRINT') { icon = 'icon-gnome'; label = 'Fotavtrykk'; const absPercentCompare = Math.abs(props.percentCompare); const percentCompare = props.percentCompare > 0 ? `${absPercentCompare}% over` : `${absPercentCompare}% under`; caption = `Ca. ${percentCompare} norsk gjennomsnitt`; } else if (props.type.toUpperCase() === 'CHALLENGES') { icon = 'icon-trophy'; label = 'Utfordringer'; caption = `${props.numberChallenges} aktive og kommende utfordringer`; } return ( <div className={classNames(styles.wrapper, { [props.className]: props.className })} > <div className={styles.innerWrapper}> <LabelTab className={styles.labelTab} icon={icon} label={label} /> <Typography className={styles.caption} type={'caption2Normal'} > {caption} </Typography> </div> { props.type.toUpperCase() === 'PERSONAL' && props.profileType === 'others' ? null : <div> <ActionButton className={props.type.toUpperCase() === 'PERSONAL' ? styles.buttonIconActivity : styles.buttonIcon} icon={buttonIcon} onClick={props.onClick} size={'standard'} /> </div> } </div> ); } ProfileMenuItem.propTypes = { className: PropTypes.string, dateOfLastActivity: PropTypes.string, numberChallenges: PropTypes.number, numberGoals: PropTypes.number, onClick: PropTypes.func, percentCompare: PropTypes.number, profileType: PropTypes.oneOf(['self', 'others']), totalSavings: PropTypes.number, type: PropTypes.oneOf(['personal', 'insight', 'footprint', 'challenges', 'activity']) }; export default ProfileMenuItem;
docs/app/Examples/collections/Table/Variations/TableExampleColumnWidth.js
koenvg/Semantic-UI-React
import React from 'react' import { Table } from 'semantic-ui-react' const TableExampleColumnWidth = () => { return ( <Table> <Table.Header> <Table.Row> <Table.HeaderCell width={10}>Name</Table.HeaderCell> <Table.HeaderCell width='six'>Status</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> <Table.Row> <Table.Cell>John</Table.Cell> <Table.Cell>Approved</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jamie</Table.Cell> <Table.Cell>Approved</Table.Cell> </Table.Row> <Table.Row> <Table.Cell>Jill</Table.Cell> <Table.Cell>Denied</Table.Cell> </Table.Row> </Table.Body> <Table.Footer> <Table.Row> <Table.HeaderCell>3 People</Table.HeaderCell> <Table.HeaderCell>2 Approved</Table.HeaderCell> </Table.Row> </Table.Footer> </Table> ) } export default TableExampleColumnWidth
src/views/AboutView.js
realalexhomer/redux-react-todo
import React from 'react' import { Link } from 'react-router' const AboutView = () => ( <div className='container text-center'> <h1>This is the about view!</h1> <hr /> <Link to='/'>Back To Home View</Link> </div> ) export default AboutView
app/containers/ResumePage/index.js
DwightBe/Portfolio-2017
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; export default class ResumePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <div style={{ margin: '20px auto', textAlign: 'left', maxWidth: '800px'}}> <p> <h2> Contact</h2> dwightbenignus@gmail.com </p> <p> <h3> Skills </h3> • Javascript, HTML, CSS, React, Redux, PHP, underscore.js, lodash, SQL <br/> • Photoshop, Illustrator, Visual/Conceptual/Graphic Arts, Pixel Art <br/> • Illustration, Painting and Drawing <br/> </p> </div> ); } }
src/docs/examples/TextInputStyledComponents/errorExample.js
choudlet/ps-react-choudlet
import React from 'react'; import TextInputStyledComponents from 'ps-react/TextInputStyledComponents'; /** Required TextBox with error */ export default class ExampleError extends React.Component { render() { return ( <TextInputStyledComponents htmlId="example-optional" label="First Name" name="firstname" onChange={() => {}} required error="First name is required." /> ) } }
src/premade/SummaryTimelineChart.js
ornl-sava/vis-react-components
import React from 'react' import PropTypes from 'prop-types' import { extent, min, max } from 'd3' import { setScale, isOrdinalScale } from '../util/d3' import { spreadRelated } from '../util/react' import Chart from '../Chart' import Axis from '../Axis' import SummaryTimeline from '../SummaryTimeline' class SummaryTimelineChart extends React.Component { constructor (props) { super(props) this.xScale = setScale(props.xScaleType) this.yScale = setScale(props.yScaleType) this.opacityScale = setScale('linear') this.xDomain = this.props.xDomain this.yDomain = this.props.yDomain this.onClick = this.onClick.bind(this) this.onBrush = this._onBrush.bind(this) this.onEnter = this.onEnter.bind(this) this.onLeave = this.onLeave.bind(this) this.onResize = this.onResize.bind(this) this.updateDomain = this.updateDomain.bind(this) this.updateRange = this.updateRange.bind(this) this.updateDomain(props, this.state) this.updateColorScales(props, this.state) } componentWillReceiveProps (nextProps) { this.updateDomain(nextProps, this.state) this.updateColorScales(nextProps, this.state) } componentWillUnmount () { if (this.props.tipFunction) { this.tip.destroy() } } updateColorScales (props, state) { let opacityDomain = [] let opacityRange = [] if (props.data.length > 0) { var domainMin = min(props.data, (d) => { return d.opacityValue }) var domainMax = max(props.data, (d) => { return d.opacityValue }) opacityDomain = [domainMin, domainMax] opacityRange = [0.20, 0.90] } this.opacityScale .domain(opacityDomain) .range(opacityRange) } updateDomain (props, state) { // console.log('SummaryTimelineChart.updateDomain()') if (props.data.length > 0) { this.xDomain = extent(props.data, (d) => { return d.date }) let yMin = Infinity let yMax = -Infinity if (props.showRange1Area && props.showRange2Area) { // console.log('Showing both ranges') yMin = min(props.data, (d) => { return Math.min(d.avg, Math.min(d.innerRangeMin, d.outerRangeMin)) }) yMax = max(props.data, (d) => { return Math.max(d.avg, Math.max(d.innerRangeMax, d.outerRangeMax)) }) } else if (props.showRange1Area && !props.showRange2Area) { // console.log('Showing only range 1 area') yMin = min(props.data, (d) => { return Math.min(d.avg, d.innerRangeMin) }) yMax = max(props.data, (d) => { return Math.max(d.avg, d.innerRangeMax) // return d.innerRangeMax }) } else if (!props.showRange1Area && props.showRange2Area) { // console.log('Showing only range 2 area') yMin = min(props.data, (d) => { return Math.min(d.avg, d.outerRangeMin) // return d.outerRangeMin }) yMax = max(props.data, (d) => { return Math.max(d.avg, d.outerRangeMax) // return d.outerRangeMax }) } else { // console.log('Showing neither range, just avg points') yMin = min(props.data, (d) => { return d.avg }) yMax = max(props.data, (d) => { return d.avg }) } // let yMin = min(props.data, (d) => { return Math.min(d.innerRangeMin, d.outerRangeMin) }) // let yMax = max(props.data, (d) => { return Math.max(d.innerRangeMax, d.outerRangeMax) }) this.yDomain = [yMin, yMax] this.xScale.domain(this.xDomain) this.yScale.domain(this.yDomain) } } updateRange (props, state) { this.yScale.range([this.refs.chart.chartHeight, 0]) if (props.yAxis.innerPadding && isOrdinalScale(this.yScale.type)) { this.yScale.paddingInner(props.yAxis.innerPadding) } if (props.yAxis.outerPadding && isOrdinalScale(this.yScale.type)) { this.yScale.paddingOuter(props.yAxis.outerPadding) } this.xScale.range([0, this.refs.chart.chartWidth]) if (props.xAxis.innerPadding && isOrdinalScale(this.xScale.type)) { this.xScale.paddingInner(props.xAxis.innerPadding) } if (props.xAxis.outerPadding && isOrdinalScale(this.xScale.type)) { this.xScale.paddingOuter(props.xAxis.outerPadding) } } _onBrush (data) { if (data && data.length === 2) { this.props.onBrush(data) } } onClick (event, data) { this.props.onClick(event, data) } onEnter (event, data) { if (data && this.tip) { this.tip.show(event, data) } this.props.onEnter(event, data) } onLeave (event, data) { if (data && this.tip) { this.tip.hide(event, data) } this.props.onLeave(event, data) } onResize () { this.updateRange(this.props, this.state) } render () { let props = this.props return ( <Chart ref='chart' {...spreadRelated(Chart, props)} resizeHandler={this.onResize}> <SummaryTimeline className='summaryTimeline' {...spreadRelated(SummaryTimeline, props)} opacityScale={this.opacityScale} xScale={this.xScale} yScale={this.yScale} onBrush={this.onBrush} /> <Axis className='x axis' {...props.xAxis} scale={this.xScale} /> <Axis className='y axis' {...props.yAxis} scale={this.yScale} /> </Chart> ) } } SummaryTimelineChart.defaultProps = { // Premade default data: [], xDomain: [], yDomain: [], xAxis: { type: 'x', orient: 'bottom', innerPadding: null, outerPadding: null, animationDuration: 500 }, yAxis: { type: 'y', orient: 'left', innerPadding: null, outerPadding: null, animationDuration: 500 }, xScaleType: 'time', yScaleType: 'linear', // Spread chart default ...Chart.defaultProps, // Spread scatterplot default ...SummaryTimeline.defaultProps } SummaryTimelineChart.propTypes = { ...SummaryTimeline.propTypes, ...Chart.propTypes, onBrush: PropTypes.func, onClick: PropTypes.func, onEnter: PropTypes.func, onLeave: PropTypes.func, tipFunction: PropTypes.func, xScaleType: PropTypes.string, yScaleType: PropTypes.string, xDomain: PropTypes.array, yDomain: PropTypes.array, xAccessor: PropTypes.any, yAccessor: PropTypes.any, xAxis: PropTypes.object, yAxis: PropTypes.object } export default SummaryTimelineChart
src/components/Repl.js
boneskull/Mancy
import React from 'react'; import _ from 'lodash'; import ReplEntries from './ReplEntries'; import ReplPrompt from './ReplPrompt'; import ReplStatusBar from './ReplStatusBar'; import ReplStore from '../stores/ReplStore'; import ReplDOMEvents from '../common/ReplDOMEvents'; import ReplDOM from '../common/ReplDOM'; import ReplActiveInputActions from '../actions/ReplActiveInputActions'; import ReplPreferencesActions from '../actions/ReplPreferencesActions'; import ReplConsoleActions from '../actions/ReplConsoleActions'; import ReplSuggestionActions from '../actions/ReplSuggestionActions'; import ReplStatusBarActions from '../actions/ReplStatusBarActions'; import Reflux from 'reflux'; import {ipcRenderer} from 'electron'; import {writeFile, readFile} from 'fs'; import {EOL} from 'os'; import remote from 'remote'; import ReplStreamHook from '../common/ReplStreamHook'; import ReplConsoleHook from '../common/ReplConsoleHook'; import ReplConsole from './ReplConsole'; import ReplOutput from '../common/ReplOutput'; import ContextMenu from '../menus/context-menu.json'; import ReplConstants from '../constants/ReplConstants'; import ReplContext from '../common/ReplContext'; import ReplCommon from '../common/ReplCommon'; import ReplLanguages from '../languages/ReplLanguages'; import {format} from 'util'; export default class Repl extends React.Component { constructor(props) { super(props); _.each([ 'onStateChange', 'onPaste', 'onContextMenu', 'onKeydown', 'onBreakPrompt', 'onClearCommands', 'onCollapseAll', 'onExpandAll', 'onDrag', 'onToggleConsole', 'onFormatPromptCode', 'onStdout', 'onStderr', 'onStdMessage', 'onConsole', 'onConsoleChange', 'getPromptKey', 'onImport', 'onExport', 'onAddPath', 'loadPreferences', 'onSaveCommands', 'onLoadScript', 'checkNewRelease', 'onNewRelease', 'resizeWindow', 'onSetREPLMode', 'loadStartupScript', 'onInit' ], (field) => { this[field] = this[field].bind(this); }); this.loadPreferences(); ReplCommon.addUserDataToPath(ReplContext.getContext()); this.state = _.cloneDeep(ReplStore.getStore()); } componentDidMount() { // set REPL language ReplLanguages.setREPL(global.Mancy.preferences.lang); this.setupContextMenu(); this.activePromptKey = Date.now(); //register events this.unsubscribe = ReplStore.listen(this.onStateChange); window.addEventListener('paste', this.onPaste, false); window.addEventListener('contextmenu', this.onContextMenu, false); window.addEventListener('keydown', this.onKeydown, false); // hooks ReplStreamHook.on('stdout', this.onStdout); ReplStreamHook.on('stderr', this.onStderr); ReplConsoleHook.on('console', this.onConsole); ipcRenderer.on('application:import-file', this.onImport); ipcRenderer.on('application:export-file', this.onExport); ipcRenderer.on('application:add-path', this.onAddPath); ipcRenderer.on('application:save-as', this.onSaveCommands); ipcRenderer.on('application:load-file', this.onLoadScript); ipcRenderer.on('application:prompt-clear-all', this.onClearCommands); ipcRenderer.on('application:prompt-expand-all', this.onExpandAll); ipcRenderer.on('application:prompt-collapse-all', this.onCollapseAll); ipcRenderer.on('application:prompt-break', this.onBreakPrompt); ipcRenderer.on('application:prompt-format', this.onFormatPromptCode); ipcRenderer.on('application:prompt-mode', (sender, value) => this.onSetREPLMode(value)); ipcRenderer.on('application:prompt-language', (sender, value) => { global.Mancy.session.lang = value; ReplLanguages.setREPL(value); ReplStatusBarActions.updateLanguage(value); }); ipcRenderer.on('application:preferences', ReplPreferencesActions.openPreferences); ipcRenderer.on('application:preference-theme-dark', () => ReplPreferencesActions.setTheme('Dark Theme')); ipcRenderer.on('application:preference-theme-light', () => ReplPreferencesActions.setTheme('Light Theme')); ipcRenderer.on('application:view-theme-dark', () => document.body.className = 'dark-theme'); ipcRenderer.on('application:view-theme-light', () => document.body.className = 'light-theme'); ipcRenderer.on('application:new-release', this.onNewRelease); this.onInit(); } onInit() { this.checkNewRelease(); this.onSetREPLMode(global.Mancy.preferences.mode); ReplPreferencesActions.setTheme(global.Mancy.preferences.theme); this.resizeWindow(); this.loadStartupScript(); ipcRenderer.send('application:prompt-on-close', global.Mancy.preferences.promptOnClose); } onLoadScript(sender, script) { if(script) { let ext = script.replace(/(?:.*)\.(\w+)$/, '$1'); let lang = ReplLanguages.getLangName(ext); if(lang) { ReplLanguages.setREPL(lang); ReplActiveInputActions.playCommands([`.load ${script}`]); if(lang !== global.Mancy.session.lang) { setTimeout(() => { ReplLanguages.setREPL(global.Mancy.session.lang); ReplStore.onReloadPrompt(''); }, 200); } } else { let options = { buttons: ['Close'], title: 'Failed to load script', type: 'error', message: `Failed to load '${script}'. '${ext}' extension is not supported.` }; ipcRenderer.send('application:message-box', options); } } } loadStartupScript() { this.onLoadScript(null, global.Mancy.preferences.loadScript); } resizeWindow() { let setSize = (w, h) => localStorage.setItem('window', JSON.stringify({ width: w, height: h })); let win = remote.getCurrentWindow(); let lastWindow = JSON.parse(localStorage.getItem('window')); let [width, height] = win.getSize(); if(!lastWindow) { setSize(width, height) } else { try { win.setSize(lastWindow.width, lastWindow.height); } catch(e) {} } win.on('resize', () => { let [width, height] = win.getSize(); setSize(width, height); }); } setupContextMenu() { let Menu = remote.require('menu'); let contextMenu = _.cloneDeep(ContextMenu); let actionTemplates = [ { label: 'Clear All', accelerator: 'Ctrl+L', click: this.onClearCommands }, { label: 'Collapse All', accelerator: 'CmdOrCtrl+K', click: this.onCollapseAll }, { label: 'Expand All', accelerator: 'CmdOrCtrl+E', click: this.onExpandAll }, { label: 'Break Prompt', accelerator: 'Ctrl+D', click: this.onBreakPrompt }, { label: 'Format', accelerator: 'Shift+Ctrl+F', click: this.onFormatPromptCode } ]; _.each(actionTemplates, (template) => contextMenu.push(template)); this.menu = Menu.buildFromTemplate(contextMenu); } componentWillUnmount() { this.unsubscribe(); window.removeEventListener('paste', this.onPaste, false); window.removeEventListener('contextmenu', this.onContextMenu, false); window.removeEventListener('keydown', this.onKeydown, false); ReplStreamHook.removeListener('stdout', this.onStdout); ReplStreamHook.removeListener('stderr', this.onStderr); ReplStreamHook.disable(); ReplConsoleHook.removeListener('console', this.onConsole); ReplConsoleHook.disable(); } checkNewRelease() { setTimeout(() => ipcRenderer.send('application:check-new-release'), 2000); } loadPreferences() { let preferences = JSON.parse(localStorage.getItem('preferences')); ipcRenderer.send('application:sync-preference', preferences); } onNewRelease(release) { ReplStatusBarActions.newRelease(release); } onSaveCommands(sender, filename) { let {history} = ReplStore.getStore(); let data = _.chain(history) .map((h) => h.plainCode) .filter((c) => !/^\s*\./.test(c)) .value() .join(EOL); writeFile(filename, data, { encoding: ReplConstants.REPL_ENCODING }, (err) => { let options = { buttons: ['Close'] }; if(err) { options = _.extend(options, { title: 'Save Error', type: 'error', message: err.name || ' Error', detail: err.toString() }); } else { options = _.extend(options, { title: 'Commands saved', type: 'info', message: `Commands saved to ${filename}` }); } ipcRenderer.send('application:message-box', options); }); } onImport(sender, filename) { readFile(filename, (err, data) => { if(!err) { try { let history = JSON.parse(data); if(!Array.isArray(history) || !_.every(history, (h) => typeof h === 'string')) { throw Error(`Invalid session file ${filename}`); } ReplActiveInputActions.playCommands(history); return; } catch(e) { err = e; } } ipcRenderer.send('application:message-box', { title: 'Load session error', buttons: ['Close'], type: 'error', message: err.toString() }); }); } onExport(sender, filename) { let {history} = ReplStore.getStore(); let data = JSON.stringify(_.map(history, (h) => h.plainCode)); writeFile(filename, data, { encoding: ReplConstants.REPL_ENCODING }, (err) => { let options = { buttons: ['Close'] }; if(err) { options = _.extend(options, { title: 'Export Error', type: 'error', message: err.name || ' Error', detail: err.toString() }); } else { options = _.extend(options, { title: 'Session saved', type: 'info', message: `Session saved to ${filename}` }); } ipcRenderer.send('application:message-box', options); }); } onAddPath(sender, paths) { ReplCommon.addToPath(paths, ReplContext.getContext()); } onContextMenu(e) { e.preventDefault(); this.menu.popup(remote.getCurrentWindow()); } onSetREPLMode(mode) { ReplStore.onSetREPLMode(mode); ReplStatusBarActions.updateMode(mode); global.Mancy.session.mode = mode; } onPaste(e) { e.preventDefault(); var text = e.clipboardData.getData("text/plain"); document.execCommand("insertHTML", false, text); ReplSuggestionActions.removeSuggestion(); } onKeydown(e) { if(ReplDOMEvents.isEnter(e)) { ReplDOM.scrollToEnd(); return; } if(e.ctrlKey && ReplDOMEvents.isSpace(e)) { ReplActiveInputActions.performAutoComplete(); return; } if(e.ctrlKey && e.shiftKey && ReplDOMEvents.isNumber(e)) { let num = e.which - ReplDOMEvents.zero; ReplStore.onReloadPromptByIndex(num + 1, true); return; } } onFormatPromptCode() { ReplActiveInputActions.formatCode(); } onCollapseAll() { ReplStore.collapseAll(); } onExpandAll() { ReplStore.expandAll(); } onBreakPrompt() { ReplActiveInputActions.breakPrompt(); } onClearCommands() { ReplStore.clearStore(); ReplConsoleActions.clear(); } onStateChange() { this.setState(ReplStore.getStore()); } onDrag(e) { let replConsole = document.getElementsByClassName('repl-console')[0]; let replContainerRight = document.getElementsByClassName('repl-container-right')[0]; let {clientX} = e; let {width} = document.defaultView.getComputedStyle(replConsole); let initWidth = parseInt(width, 10); let startDrag = (e) => { let adj = e.clientX - clientX; replContainerRight.style.flex = '0 0 ' + (initWidth - adj) + 'px'; } let stopDrag = (e) => { document.documentElement.removeEventListener('mousemove', startDrag, false); document.documentElement.removeEventListener('mouseup', stopDrag, false); } document.documentElement.addEventListener('mousemove', startDrag, false); document.documentElement.addEventListener('mouseup', stopDrag, false); } onToggleConsole() { this.reloadPrompt = false; ReplStore.toggleConsole(); } onStdMessage(data, type) { let {formattedOutput} = ReplOutput.some(data).highlight(data); ReplConsoleActions.addEntry({ type: type, data: [formattedOutput] }); this.onConsoleChange(); } onStdout(msg) { this.onStdMessage(msg.data ? msg.data.toString() : msg, 'log'); } onStderr(msg) { this.onStdMessage(msg.data ? msg.data.toString() : msg, 'error'); } onConsole({type, data}) { if(data.length === 0) { return; } let results; if(data.length > 1 && typeof data[0] === 'string' && data[0].match(/%[%sdj]/)) { results = [format.apply(null, data)]; } else { results = _.reduce(data, function(result, datum) { let {formattedOutput} = ReplOutput.some(datum).highlight(datum); result.push(formattedOutput); return result; }, []); } ReplConsoleActions.addEntry({ type: type, data: results }); this.onConsoleChange(type); } onConsoleChange(type) { let currentWindow = remote.getCurrentWindow(); if(!currentWindow.isFocused() && process.platform === 'darwin') { ipcRenderer.send('application:dock-message-notification', currentWindow.id); } if(this.state.showConsole) { return; } ReplStore.showBell(); } getPromptKey() { if(!this.state.reloadPrompt) { return this.activePromptKey; } this.activePromptKey = Date.now(); return this.activePromptKey; } render() { // force to recreate ReplPrompt return ( <div className='repl-container'> <div className='repl-container-left'> <div className='repl-header' key='header-left'></div> <ReplEntries entries={this.state.entries} /> <ReplPrompt key={this.getPromptKey()} history={this.state.history} historyIndex={this.state.historyIndex} historyStaged={this.state.historyStaged} command={this.state.command} cursor= {this.state.cursor} /> </div> { this.state.showConsole ? <div className='repl-container-right'> <div className='repl-header' key='header-right'></div> <div className="repl-console"> <div className="repl-console-resizeable" onMouseDown={this.onDrag}> <span className='repl-console-drag-lines'> </span> </div> <ReplConsole /> </div> </div> : null } <ReplStatusBar history={this.state.entries} showConsole={this.state.showConsole} showBell={this.state.showBell} onToggleConsole={this.onToggleConsole}/> </div> ); } }
app/src/assets/js/components/global/sequential-nav-bar.js
Huskie/ScottishPremiershipData
import React from 'react'; import { Link } from 'react-router'; import firebaseApp from '../../modules/firebase'; import convertObjectPropertiesToArray from '../../modules/utilities/convert-object-properties-to-array'; import orderArrayAlphabeticallyByObjectKey from '../../modules/utilities/order-array-alphabetically-by-object-key'; import deslugify from '../../modules/utilities/deslugify'; import slugify from '../../modules/utilities/slugify'; class SequentialNavBarComponent extends React.Component { constructor (props) { super(props); // We must have a currentClub and league parameter to proceed if (typeof this.props.currentClub !== 'string' || typeof this.props.league !== 'string') { return false; } this.state = { league: this.props.league, nextLabel: null, nextLink: null, nextTitle: null, previousLabel: null, previousLink: null, previousTitle: null }; } componentWillReceiveProps(nextProps) { // Get the clubs in this league from the database firebaseApp.database().ref('clubs/' + this.props.league).on('value', snapshot => { const clubsInLeague = snapshot.val().teams; let previousClub = null; let nextClub = null; // Loop through the clubs clubsInLeague.forEach((club, index) => { // Check if this iteration matches the current club if (club === this.props.currentClub) { // We have a match, we can start to assign the previous and next club state data if (clubsInLeague[index - 1]) { previousClub = clubsInLeague[index - 1]; } else { previousClub = clubsInLeague[clubsInLeague.length - 1]; } if (clubsInLeague[index + 1]) { nextClub = clubsInLeague[index + 1]; } else { nextClub = clubsInLeague[0]; } } }); this.setState({ nextLabel: nextClub ? deslugify(nextClub) : null, nextLink: nextClub ? '/clubs/' + nextClub : null, nextLogo: nextClub ? '/assets/img/logos/scotland/' + nextClub + '.png' : null, nextSlug: nextClub ? nextClub : null, nextTitle: nextClub ? `View the ${nextClub} club page` : null, previousLabel: previousClub ? deslugify(previousClub) : null, previousLink: previousClub ? '/clubs/' + previousClub : null, previousLogo: previousClub ? '/assets/img/logos/scotland/' + previousClub + '.png' : null, previousSlug: previousClub ? previousClub : null, previousTitle: previousClub ? `View the ${previousClub} club page` : null }); }); } render() { // We must have state to render if (this.state.nextLabel === null) { return false; } return ( <div className="sequential-nav-bar"> <div className="container"> <ul className="sequential-nav-bar__list"> <li className="sequential-nav-bar__item sequential-nav-bar__item--previous"> <Link className={"sequential-nav-bar__link sequential-nav-bar__link--" + this.state.previousSlug} to={this.state.previousLink} style={{backgroundImage: 'url(' + this.state.previousLogo + ')'}} title={this.state.previousTitle}> <span className="sequential-nav-bar__text">&larr; {this.state.previousLabel}</span> </Link> </li> <li className="sequential-nav-bar__item sequential-nav-bar__item--next"> <Link className={"sequential-nav-bar__link sequential-nav-bar__link--" + this.state.nextSlug} to={this.state.nextLink} style={{backgroundImage: 'url(' + this.state.nextLogo + ')'}} title={this.state.nextTitle}> <span className="sequential-nav-bar__text">{this.state.nextLabel} &rarr;</span> </Link> </li> </ul> </div> </div> ) } } SequentialNavBarComponent.defaultProps = {}; SequentialNavBarComponent.displayName = 'SequentialNavBarComponent'; SequentialNavBarComponent.propTypes = {}; export default SequentialNavBarComponent;
examples/_drag-around-custom/index.js
prometheusresearch/react-dnd
'use strict'; import React from 'react'; import LinkedStateMixin from 'react/lib/LinkedStateMixin'; import Container from './Container'; import DragLayer from './DragLayer'; const DragAroundCustom = React.createClass({ mixins: [LinkedStateMixin], getInitialState() { return { snapToGridAfterDrop: false, snapToGridWhileDragging: false }; }, render() { const { snapToGridAfterDrop, snapToGridWhileDragging } = this.state; return ( <div> <Container snapToGrid={snapToGridAfterDrop} /> <DragLayer snapToGrid={snapToGridWhileDragging} /> <p> <input type='checkbox' checkedLink={this.linkState('snapToGridAfterDrop')}> Snap to grid after drop </input> <br /> <input type='checkbox' checkedLink={this.linkState('snapToGridWhileDragging')}> Snap to grid while dragging </input> </p> <hr /> <p> Browser APIs provide no way to change drag preview or its behavior once drag has started. Libraries such as jQuery UI implement drag and drop from scratch to work around this, but react-dnd only supports browser drag and drop “backend” for now, so we have to accept its limitations. </p> <p> We can, however, customize behavior a great deal if we feed the browser an empty image as drag preview. This library provides <code>DragLayerMixin</code> that you can use to implement a fixed layer on top of your app where you'd draw a custom drag preview component. </p> <p> Note that we can draw a completely different component on our drag layer if we wish so. It's not just a screenshot. </p> <p> With this approach, we miss out on default “return” animation when dropping outside the container. However, we get great flexibility in customizing drag feedback and zero flicker. </p> </div> ); } }); export default DragAroundCustom;
frontend/src/routes/Skills/components/Skills.js
blalasaadri/TechTalent
import React from 'react'; import LoadingIndicator from 'components/LoadingIndicator'; import SkillsDetails from 'components/SkillsDetails'; class Skills extends React.Component { constructor (props) { super(props); props.fetchSkills(); } render () { return ( <LoadingIndicator isFetched={this.props.isFetched} error={this.props.skills.error} element={SkillsDetails} skills={this.props.skills} /> ); } } Skills.propTypes = { isFetching: React.PropTypes.bool.isRequired, isFetched: React.PropTypes.bool.isRequired, error: React.PropTypes.string, skills: React.PropTypes.array.isRequired, fetchSkills: React.PropTypes.func.isRequired }; export default Skills;
app/components/Store/Icons/LoginIcon.js
VineRelay/VineRelayStore
import React from 'react'; import Icon from 'react-icon-base'; const LoginIcon = (props) => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m35.9 31.4q0 2.6-1.6 4.2t-4.3 1.5h-19.5q-2.7 0-4.4-1.5t-1.6-4.2q0-1.2 0.1-2.3t0.3-2.5 0.6-2.4 0.9-2.2 1.4-1.8 1.9-1.2 2.5-0.4q0.2 0 1 0.5t1.6 1 2.4 1.1 3 0.5 3-0.5 2.4-1.1 1.7-1 0.9-0.5q1.4 0 2.5 0.4t1.9 1.2 1.4 1.8 0.9 2.2 0.6 2.4 0.4 2.5 0 2.3z m-7.1-20q0 3.6-2.5 6.1t-6.1 2.5-6-2.5-2.6-6.1 2.6-6 6-2.5 6.1 2.5 2.5 6z" /></g> </Icon> ); export default LoginIcon;
src/components/orders/orders_table.js
DavidSunny/mastering-react
import React from 'react'; import OrderRow from './order_row.js'; class OrdersTable extends React.Component { render() { const rows = this.props.orders.map((order, i) => { return <OrderRow order={order} key={i} />; }) return ( <table className="orders-table"> <thead> <tr> <th>Order #</th> <th>Customer</th> <th className='sorted-by'>Ordered at</th> <th>Product(s)</th> <th className='amount'>Amount</th> <th className='status'>Payment</th> <th className='status'>Order</th> </tr> </thead> <tbody> {rows} </tbody> </table> ) } } export default OrdersTable;
docs/src/app/components/pages/components/IconButton/ExampleSize.js
rscnt/material-ui
import React from 'react'; import IconButton from 'material-ui/IconButton'; import ActionHome from 'material-ui/svg-icons/action/home'; const styles = { smallIcon: { width: 36, height: 36, }, mediumIcon: { width: 48, height: 48, }, largeIcon: { width: 60, height: 60, }, small: { width: 72, height: 72, padding: 16, }, medium: { width: 96, height: 96, padding: 24, }, large: { width: 120, height: 120, padding: 30, }, }; const IconButtonExampleSize = () => ( <div> <IconButton> <ActionHome /> </IconButton> <IconButton iconStyle={styles.smallIcon} style={styles.small} > <ActionHome /> </IconButton> <IconButton iconStyle={styles.mediumIcon} style={styles.medium} > <ActionHome /> </IconButton> <IconButton iconStyle={styles.largeIcon} style={styles.large} > <ActionHome /> </IconButton> </div> ); export default IconButtonExampleSize;
blueocean-material-icons/src/js/components/svg-icons/action/assignment-returned.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionAssignmentReturned = (props) => ( <SvgIcon {...props}> <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm0 15l-5-5h3V9h4v4h3l-5 5z"/> </SvgIcon> ); ActionAssignmentReturned.displayName = 'ActionAssignmentReturned'; ActionAssignmentReturned.muiName = 'SvgIcon'; export default ActionAssignmentReturned;
app/containers/ToolTypeAllFull/index.js
BeautifulTrouble/beautifulrising-client
/** * * ToolTypeAllFull * */ import React from 'react'; import styled from 'styled-components'; import Isvg from 'react-inlinesvg'; import {Link} from 'react-router'; import { injectIntl } from 'react-intl'; import TranslatableStaticText from 'containers/TranslatableStaticText'; import Container from 'components/ToolTypeAllFull/Container'; import Desc from 'components/ToolTypeAllFull/Desc'; import Head from 'components/ToolTypeAllFull/Head'; import Row from 'components/ToolTypeAllFull/Row'; import ToolType from 'components/ToolTypeAllFull/ToolType'; import MethodologyIcon from 'assets/images/type/methodologies-option.svg'; import PrincipleIcon from 'assets/images/type/principles-option.svg'; import StoryIcon from 'assets/images/type/stories-option.svg'; import TacticIcon from 'assets/images/type/tactics-option.svg'; import TheoryIcon from 'assets/images/type/theories-option.svg'; import messages from '../ToolTypeArea/messages'; import staticText from './staticText'; function ToolTypeAllFull(props) { const lang = props.intl.locale; return ( <Container {...props} lang={lang} showLine={props.showLine}> <div> <Row> <ToolType to={'/type/story'} lang={lang}> <Head ar={lang==='ar'}> <TranslatableStaticText {...staticText.stories} /> </Head> <Isvg src={StoryIcon} /> </ToolType> <ToolType to={'/type/story'} style={{paddingTop: 35}} lang={lang}> <Desc ar={lang==='ar'}> <TranslatableStaticText {...staticText.shortDefinitionStory} /> </Desc> </ToolType> </Row> <Row> <ToolType to={'/type/tactic'} lang={lang}> <Head ar={lang==='ar'}> <TranslatableStaticText {...staticText.tactics} /> </Head> <Isvg src={TacticIcon} /> </ToolType> <ToolType to={'/type/tactic'} style={{paddingTop: 35}} lang={lang}> <Desc ar={lang==='ar'}> <TranslatableStaticText {...staticText.shortDefinitionTactic} /> </Desc> </ToolType> </Row> <Row> <ToolType to={'/type/principle'} lang={lang}> <Head ar={lang==='ar'}> <TranslatableStaticText {...staticText.principles} /> </Head> <Isvg src={PrincipleIcon} /> </ToolType> <ToolType to={'/type/principle'} style={{paddingTop: 35}} lang={lang}> <Desc ar={lang==='ar'}> <TranslatableStaticText {...staticText.shortDefinitionPrinciple} /> </Desc> </ToolType> </Row> <Row> <ToolType to={'/type/theory'} lang={lang}> <Head ar={lang==='ar'}> <TranslatableStaticText {...staticText.theories} /> </Head> <Isvg src={TheoryIcon} /> </ToolType> <ToolType to={'/type/theory'} style={{paddingTop: 35}} lang={lang}> <Desc ar={lang==='ar'}> <TranslatableStaticText {...staticText.shortDefinitionTheory} /> </Desc> </ToolType> </Row> <Row> <ToolType to={'/type/methodology'} lang={lang}> <Head ar={lang==='ar'}> <TranslatableStaticText {...staticText.methodologies} /> </Head> <Isvg src={MethodologyIcon} /> </ToolType> <ToolType to={'/type/methodology'} style={{paddingTop: 35}} lang={lang}> <Desc ar={lang==='ar'}> <TranslatableStaticText {...staticText.shortDefinitionMethodology} /> </Desc> </ToolType> </Row> </div> </Container> ); } /** <Row> <ToolType to={'/type/tactic'} lang={lang}> <Head ar={lang==='ar'}> <TranslatableStaticText {...staticText.tactics} /> </Head> <Isvg src={TacticIcon} /> <Desc ar={lang==='ar'}> <TranslatableStaticText {...staticText.shortDefinitionTactic} /> </Desc> </ToolType> <ToolType to={'/type/principle'} lang={lang}> <Head ar={lang==='ar'}> <TranslatableStaticText {...staticText.principles} /> </Head> <Isvg src={PrincipleIcon} /> <Desc ar={lang==='ar'}> <TranslatableStaticText {...staticText.shortDefinitionPrinciple} /> </Desc> </ToolType> <ToolType to={'/type/theory'} lang={lang}> <Head ar={lang==='ar'}> <TranslatableStaticText {...staticText.theories} /> </Head> <Isvg src={TheoryIcon} /> <Desc ar={lang==='ar'}> <TranslatableStaticText {...staticText.shortDefinitionTheory} /> </Desc> </ToolType> <ToolType to={'/type/methodology'} lang={lang}> <Head ar={lang==='ar'}> <TranslatableStaticText {...staticText.methodologies} /> </Head> <Isvg src={MethodologyIcon} /> <Desc ar={lang==='ar'}> <TranslatableStaticText {...staticText.shortDefinitionMethodology} /> </Desc> </ToolType> </Row>*/ ToolTypeAllFull.propTypes = { }; export default injectIntl(ToolTypeAllFull);
demo/src/index.js
insin/react-router-form
import './style.css' import React from 'react' import {render} from 'react-dom' import {IndexRoute, Link, Route, Router, hashHistory} from 'react-router' import Form from '../../src' let CONTACTS = [{ first: 'Ryan', last: 'Florence', avatar: 'http://ryanflorence.com/jsconf-avatars/avatars/ryan.jpg', }, { first: 'Michael', last: 'Jackson', avatar: 'http://ryanflorence.com/jsconf-avatars/avatars/michael.jpg', }, { first: 'Jeremy', last: 'Ashkenas', avatar: 'http://ryanflorence.com/jsconf-avatars/avatars/jeremy.jpg', }, { first: 'Yehuda', last: 'Katz', avatar: 'http://ryanflorence.com/jsconf-avatars/avatars/yehuda.jpg', }, { first: 'Tom', last: 'Dale', avatar: 'http://ryanflorence.com/jsconf-avatars/avatars/tom.jpg', }, { first: 'Pete', last: 'Hunt', avatar: 'http://ryanflorence.com/jsconf-avatars/avatars/pete.jpg', }, { first: 'Misko', last: 'Hevery', avatar: 'http://ryanflorence.com/jsconf-avatars/avatars/misko.png', }, { first: 'Scott', last: 'Miles', avatar: 'http://ryanflorence.com/jsconf-avatars/avatars/scott.png', }, { first: 'Matt', last: 'Zabriskie', avatar: 'http://ryanflorence.com/jsconf-avatars/avatars/matt.jpeg', }] let ContactService = { add(contact, cb) { if (!contact.first || !contact.last || !contact.avatar || !contact.PIN) { return cb(null, 'All fields are required.') } // Simulated server-only check let dupe = CONTACTS.some(existing => { return existing.first.toUpperCase() === contact.first.toUpperCase() && existing.last.toUpperCase() === contact.last.toUpperCase() }) if (dupe) { return cb(null, 'Duplicate contact name.') } CONTACTS.push(contact) cb(null) } } let App = React.createClass({ render() { return <div className="App"> <p> Reuses components from the <a href="http://react-router-mega-demo.herokuapp.com/">React Router Mega Demo</a>, but uses the <code>&lt;Form&gt;</code> component from <a href="https://github.com/insin/react-router-form">react-router-form</a> to automatically retrieve and submit form data. </p> {this.props.children} </div> } }) let Contacts = React.createClass({ render() { return <div> <h2>Contacts</h2> <Link to="/new-contact">New Contact</Link> <hr/> {CONTACTS.map((contact, index) => <div className="Contact" key={index}> <h3>{contact.first} {contact.last}</h3> <img src={contact.avatar}/> </div>)} <hr/> <Link to="/new-contact">New Contact</Link> </div> } }) let NewContact = React.createClass({ getInitialState() { return { error: null } }, componentWillReceiveProps(nextProps) { let {state} = this.props.location let {state: nextState} = nextProps.location if (nextState && nextState.error && (!state || state.error !== nextState.error)) { this.setState({error: nextState.error}) } }, _onSubmit(e, contact) { let error = this.state.error if (Object.keys(contact).some(prop => contact[prop] === '')) { e.preventDefault() error = 'All fields are required.' } this.setState({error}) }, render() { let {location} = this.props let contact = location.state && location.state.contact || {} return <div> <h1>New Contact</h1> <p><em> (Enter a duplicate name to simulate a service call resulting in an error response) </em></p> <div> <Form method="POST" to="/create-contact" dataKey="contact" onSubmit={this._onSubmit}> {this.state.error && <p className="error">{this.state.error}</p>} <p><input name="first" placeholder="first name" defaultValue={contact.first}/></p> <p><input name="last" placeholder="last name" defaultValue={contact.last}/></p> <p><input name="avatar" placeholder="avatar url" defaultValue={contact.avatar}/></p> <p><input name="PIN" type="password" placeholder="PIN" defaultValue={contact.PIN}/></p> <p><button type="submit">Add</button> or <Link to="/">Cancel</Link></p> </Form> </div> </div> } }) function handleCreateContact({location}, replace, cb) { let {contact} = location.state ContactService.add(contact, (_, error) => { if (!error) { replace('/') } else { replace({pathname: '/new-contact', state: {contact, error}}) } cb() }) } let routes = <Route path="/" component={App}> <IndexRoute component={Contacts}/> <Route path="new-contact" component={NewContact}/> <Route path="create-contact" onEnter={handleCreateContact}/> </Route> render(<Router history={hashHistory} routes={routes}/>, document.querySelector('#demo'))
iOS/views/components/RecomendRef.js
MOTOMUR/plz_donation
import React, { Component } from 'react'; import { StyleSheet, View, Image } from 'react-native'; import { Container, Header, Content, Card, CardItem, Thumbnail, Text, Button, Left, Body, Right } from 'native-base'; import Timestamp from 'react-timestamp'; import Icon from 'react-native-vector-icons/MaterialIcons' import firebase from 'firebase' import { StarBtn, StarredBtn } from './StarBtn' // import LocalizedStrings from 'react-native-localization' class RecomendRef extends Component{ constructor(props) { super(props); this.state = { profile_image:'', star:'', }; } starBtnClick = () => { const myUserId = this.props.myuid const starUserData = this.props.searchRef.uid firebase.database().ref('users/' + starUserData + '/userStar').once("value").then(function(snapshot) { const starData = snapshot.val() var updates = {} if(starData.stars&&starData.stars[myUserId]){ updates['users/' + starUserData + '/userStar/stars/' + myUserId]= null updates['users/' + starUserData + '/userStar/starCount']= starData.starCount-1 updates['users/' + myUserId + '/starred_users/' + starUserData]= null }else{ updates['users/' + starUserData + '/userStar/stars/' + myUserId]= true updates['users/' + starUserData + '/userStar/starCount']= starData.starCount+1 updates['users/' + myUserId + '/starred_users/' + starUserData]= true } return firebase.database().ref().update(updates) }) } render() { return ( <Card> <CardItem> <Left> <Thumbnail source={{uri:this.props.searchRef.profile_image}} /> <Body> <Text style={{fontWeight:'bold'}}>{this.props.searchRef.user}</Text> </Body> </Left> </CardItem> <CardItem> <Body> <Text> {this.props.searchRef.explain} </Text> </Body> </CardItem> <CardItem> { this.props.searchRef.uid === this.props.myuid ? <Left></Left> : <Left> { (this.props.searchRef.userStar.stars && this.props.searchRef.userStar.stars[this.props.myuid]) ?<StarredBtn onStarBtnClick={this.starBtnClick}/> :<StarBtn onStarBtnClick={this.starBtnClick}/> } </Left> } </CardItem> </Card> ) } } export default RecomendRef
docs/src/sections/ThumbnailSection.js
egauci/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function ThumbnailSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="thumbnail">Thumbnails</Anchor> <small>Thumbnail</small> </h2> <p>Thumbnails are designed to showcase linked images with minimal required markup. You can extend the grid component with thumbnails.</p> <h3><Anchor id="thumbnail-anchor">Anchor Thumbnail</Anchor></h3> <p>Creates an anchor wrapping an image.</p> <ReactPlayground codeText={Samples.ThumbnailAnchor} /> <h3><Anchor id="thumbnail-divider">Divider Thumbnail</Anchor></h3> <p>Creates a divider wrapping an image and other children elements.</p> <ReactPlayground codeText={Samples.ThumbnailDiv} /> <h3><Anchor id="thumbnail-props">Props</Anchor></h3> <PropTable component="Thumbnail"/> </div> ); }
src/components/home.js
syvzies/recipe-recommender
import React, { Component } from 'react'; class Home extends Component { render () { return ( <div> <h1>Recipe Recommendations</h1> </div> ); } } export default Home;
client/src/pages/index.js
hstandaert/hstandaert.com
import React from 'react' import { Link } from 'gatsby' import Layout from '../components/layout' const IndexPage = () => ( <Layout> <h1>Hi people</h1> <p>Welcome to your new Gatsby site.</p> <p>Now go build something great.</p> <Link to="/page-2/">Go to page 2</Link> </Layout> ) export default IndexPage
vertex_ui/src/components/Navbar/components/MenuSection/MenuSection.js
zapcoop/vertex
import React from 'react'; import { PropTypes } from 'prop-types'; import _ from 'underscore'; import { Link } from 'react-router'; import routes, { findSectionBySlug, urlMatcher } from 'routes/routesStructure'; import classes from './MenuSection.scss'; const MenuSection = props => { const { slug, currentPath, onNavigation, ...otherProps } = props; const section = findSectionBySlug(routes, slug); return ( <div className={classes.menuSection} {...otherProps}> <h5 className={classes.header}>{section.title}</h5> {section.children ? ( <ul className={classes.list}> {_.map( section.children, (item, index) => item.url && ( <li key={index} className={ urlMatcher(item, currentPath) ? classes.active : '' } > <Link to={item.url} onClick={() => onNavigaiton()}> {item.title} </Link> </li> ), )} </ul> ) : ( <ul className={classes.list}> <li className={`${urlMatcher(section, currentPath) && 'active'}`}> <Link to={section.url} onClick={() => onNavigation()}> {section.title} </Link> </li> </ul> )} </div> ); }; MenuSection.propTypes = { slug: PropTypes.string.isRequired, currentPath: PropTypes.string.isRequired, onNavigation: PropTypes.func, }; MenuSection.defaultProps = { onNavigation: () => {}, }; export default MenuSection;
src/views/components/shared/track/no-track.js
EragonJ/Kaku
import React, { Component } from 'react'; import L10nSpan from '../l10n-span'; class NoTrack extends Component { constructor(props) { super(props); } render() { return ( <div className="notracks"> <L10nSpan l10nId="component_no_track"/> </div> ); } } module.exports = NoTrack;
client/app/index.js
juanmanuelromeraferrio/start-android
import React from 'react'; import ReactDOM from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import styles from './index.css'; import App from './components/App'; injectTapEventPlugin(); ReactDOM.render( < App / > , document.getElementById('app') );
src/components/ReactHotReloadWrapper.js
evonsdesigns/markts-app
import React from 'react'; import { hot } from 'react-hot-loader'; import AppRoutes from './AppRoutes'; export default hot(module)(AppRoutes);
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/DefaultProps.js
popham/flow
// @flow import React from 'react'; class MyComponent extends React.Component { static defaultProps: DefaultProps = {}; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { static defaultProps: DefaultProps = {}; props: Props; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
node_modules/@material-ui/core/es/OutlinedInput/NotchedOutline.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { withStyles } from '../styles'; import { capitalize } from '../utils/helpers'; export const styles = theme => { const align = theme.direction === 'rtl' ? 'right' : 'left'; return { /* Styles applied to the root element. */ root: { position: 'absolute', bottom: 0, right: 0, top: -5, left: 0, margin: 0, padding: 0, pointerEvents: 'none', borderRadius: theme.shape.borderRadius, borderStyle: 'solid', borderWidth: 1, // Match the Input Label transition: theme.transitions.create([`padding-${align}`, 'border-color', 'border-width'], { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }) }, /* Styles applied to the legend element. */ legend: { textAlign: 'left', padding: 0, lineHeight: '11px', transition: theme.transitions.create('width', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }) } }; }; /** * @ignore - internal component. */ const NotchedOutline = React.forwardRef(function NotchedOutline(props, ref) { const { classes, className, labelWidth: labelWidthProp, notched, style, theme } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "labelWidth", "notched", "style", "theme"]); const align = theme.direction === 'rtl' ? 'right' : 'left'; const labelWidth = labelWidthProp > 0 ? labelWidthProp * 0.75 + 8 : 0; return React.createElement("fieldset", _extends({ "aria-hidden": true, style: _extends({ [`padding${capitalize(align)}`]: 8 + (notched ? 0 : labelWidth / 2) }, style), className: clsx(classes.root, className), ref: ref }, other), React.createElement("legend", { className: classes.legend, style: { // IE 11: fieldset with legend does not render // a border radius. This maintains consistency // by always having a legend rendered width: notched ? labelWidth : 0.01 } }, React.createElement("span", { dangerouslySetInnerHTML: { __html: '&#8203;' } }))); }); process.env.NODE_ENV !== "production" ? NotchedOutline.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The width of the label. */ labelWidth: PropTypes.number.isRequired, /** * If `true`, the outline is notched to accommodate the label. */ notched: PropTypes.bool.isRequired, /** * @ignore */ style: PropTypes.object, /** * @ignore */ theme: PropTypes.object } : void 0; export default withStyles(styles, { name: 'PrivateNotchedOutline', withTheme: true })(NotchedOutline);
src/components/message.js
gthomas-appfolio/appfolio-react-template
import React, { Component } from 'react'; import styles from './message.scss'; /** * Simple example component. */ export default class Message extends Component { render() { return ( <div className={styles.message}> <h1>Hello Appfolio!</h1> </div> ); } }
codes/reactstrap-demo/src/containers/Full/Full.js
atlantis1024/react-step-by-step
import React, { Component } from 'react'; import Header from '../../components/Header/'; import Sidebar from '../../components/Sidebar/'; import Aside from '../../components/Aside/'; import Footer from '../../components/Footer/'; import Breadcrumbs from 'react-breadcrumbs'; class Full extends Component { render() { return ( <div className="app"> <Header /> <div className="app-body"> <Sidebar {...this.props}/> <main className="main"> <Breadcrumbs wrapperElement="ol" wrapperClass="breadcrumb" itemClass="breadcrumb-item" separator="" routes={this.props.routes} params={this.props.params} /> <div className="container-fluid"> {this.props.children} </div> </main> <Aside /> </div> <Footer /> </div> ); } } export default Full;
src/Router.js
pvijeh/isomorphic-react
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/HttpClient'; import App from './components/App'; import $ from 'jquery'; import ContentPage from './components/ContentPage'; import WorkPage from './components/WorkPage'; import IdeasPage from './components/IdeasPage'; import ClientsPage from './components/ClientsPage'; import AboutPage from './components/AboutPage'; import CareersPage from './components/CareersPage'; import NewsPage from './components/NewsPage'; import MediaPage from './components/MediaPage'; import ContactPage from './components/ContactPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; import PostTemplateOne from './components/PostTemplateOne'; import TestPage from './components/TestPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('/work', async () => <WorkPage />); on('/ideas', async () => <IdeasPage />); on('/clients', async () => <ClientsPage />); on('/about', async () => <AboutPage />); on('/careers', async () => <CareersPage />); on('/contact', async () => <ContactPage />); on('/news', async () => <NewsPage />); on('/work/:id', async (req) => <PostTemplateOne />); on('/', async () => <TestPage />); 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/docs/components/markdown/MarkdownExamplesDoc.js
karatechops/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Markdown from 'grommet/components/Markdown'; import InteractiveExample from '../../../components/InteractiveExample'; Markdown.displayName = 'Markdown'; const TEXT = ` # H1 Paragraph [link](/). ## H2 ![image](/img/carousel-1.png) `; const COMPONENTS = { h1: { props: { strong: true } }, h2: { props: { strong: true } }, p: { props: { size: 'large' } }, img: { props: { size: 'small' } } }; const PROPS_SCHEMA = { components: { value: COMPONENTS } }; export default class MarkdownExamplesDoc extends Component { constructor () { super(); this.state = { elementProps: {} }; } render () { const { elementProps } = this.state; const element = <Markdown {...elementProps} content={TEXT} />; return ( <InteractiveExample contextLabel='Markdown' contextPath='/docs/markdown' preamble={`import Markdown from 'grommet/components/Markdown';`} propsSchema={PROPS_SCHEMA} element={element} onChange={elementProps => this.setState({ elementProps })} /> ); } }; // import Anchor from 'grommet/components/Anchor'; // import ExamplesDoc from '../../../components/ExamplesDoc'; // import Example from '../../Example'; // // Markdown.displayName = 'Markdown'; // // const MarkdownExample = (props) => ( // <Example align="start" code={ // <Markdown {...props} /> // } /> // ); // // const TEXT = ` // # H1 // // Paragraph [link](/). // // ## H2 // // ![image](/img/carousel-1.png) // `; // // const COMPONENTS = { // h1: { // props: { // strong: true // } // }, // h2: { // props: { // strong: true // } // }, // p: { // props: { // size: 'large' // } // }, // img: { // props: { // size: 'small' // } // } // }; // // export default class MarkdownExamplesDoc extends ExamplesDoc {}; // // MarkdownExamplesDoc.defaultProps = { // context: <Anchor path="/docs/markdown">Markdown</Anchor>, // examples: [ // { label: 'Default', component: MarkdownExample, // props: { content: TEXT } }, // { label: 'Custom Components', component: MarkdownExample, // props: { content: TEXT, components: COMPONENTS } } // ], // title: 'Examples' // };