path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
app/javascript/mastodon/features/compose/components/upload_button.js
tateisu/mastodon
import React from 'react'; import IconButton from '../../../components/icon_button'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; const messages = defineMessages({ upload: { id: 'upload_button.label', defaultMessage: 'Add media ({formats})' }, }); const SUPPORTED_FORMATS = 'JPEG, PNG, GIF, WebM, MP4, MOV, OGG, WAV, MP3, FLAC'; const makeMapStateToProps = () => { const mapStateToProps = state => ({ acceptContentTypes: state.getIn(['media_attachments', 'accept_content_types']), }); return mapStateToProps; }; const iconStyle = { height: null, lineHeight: '27px', }; export default @connect(makeMapStateToProps) @injectIntl class UploadButton extends ImmutablePureComponent { static propTypes = { disabled: PropTypes.bool, unavailable: PropTypes.bool, onSelectFile: PropTypes.func.isRequired, style: PropTypes.object, resetFileKey: PropTypes.number, acceptContentTypes: ImmutablePropTypes.listOf(PropTypes.string).isRequired, intl: PropTypes.object.isRequired, }; handleChange = (e) => { if (e.target.files.length > 0) { this.props.onSelectFile(e.target.files); } } handleClick = () => { this.fileElement.click(); } setRef = (c) => { this.fileElement = c; } render () { const { intl, resetFileKey, unavailable, disabled, acceptContentTypes } = this.props; if (unavailable) { return null; } return ( <div className='compose-form__upload-button'> <IconButton icon='paperclip' title={intl.formatMessage(messages.upload, { formats: SUPPORTED_FORMATS })} disabled={disabled} onClick={this.handleClick} className='compose-form__upload-button-icon' size={18} inverted style={iconStyle} /> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.upload, { formats: SUPPORTED_FORMATS })}</span> <input key={resetFileKey} ref={this.setRef} type='file' multiple accept={acceptContentTypes.toArray().join(',')} onChange={this.handleChange} disabled={disabled} style={{ display: 'none' }} /> </label> </div> ); } }
node_modules/react-navigation/lib-rn/views/Header.js
joan17cast/Enigma
'no babel-plugin-flow-react-proptypes'; import React from 'react'; import { Animated, Platform, StyleSheet, View } from 'react-native'; import HeaderTitle from './HeaderTitle'; import HeaderBackButton from './HeaderBackButton'; import HeaderStyleInterpolator from './HeaderStyleInterpolator'; const APPBAR_HEIGHT = Platform.OS === 'ios' ? 44 : 56; const STATUSBAR_HEIGHT = Platform.OS === 'ios' ? 20 : 0; const TITLE_OFFSET = Platform.OS === 'ios' ? 70 : 40; class Header extends React.PureComponent { static HEIGHT = APPBAR_HEIGHT + STATUSBAR_HEIGHT; state = { widths: {} }; _getHeaderTitleString(scene) { const sceneOptions = this.props.getScreenDetails(scene).options; if (typeof sceneOptions.headerTitle === 'string') { return sceneOptions.headerTitle; } return sceneOptions.title; } _getLastScene(scene) { return this.props.scenes.find(s => s.index === scene.index - 1); } _getBackButtonTitleString(scene) { const lastScene = this._getLastScene(scene); if (!lastScene) { return null; } const { headerBackTitle } = this.props.getScreenDetails(lastScene).options; if (headerBackTitle || headerBackTitle === null) { return headerBackTitle; } return this._getHeaderTitleString(lastScene); } _getTruncatedBackButtonTitle(scene) { const lastScene = this._getLastScene(scene); if (!lastScene) { return null; } return this.props.getScreenDetails(lastScene).options.headerTruncatedBackTitle; } _renderTitleComponent = props => { const details = this.props.getScreenDetails(props.scene); const headerTitle = details.options.headerTitle; if (headerTitle && typeof headerTitle !== 'string') { return headerTitle; } const titleString = this._getHeaderTitleString(props.scene); const titleStyle = details.options.headerTitleStyle; const color = details.options.headerTintColor; // On iOS, width of left/right components depends on the calculated // size of the title. const onLayoutIOS = Platform.OS === 'ios' ? e => { this.setState({ widths: { ...this.state.widths, [props.scene.key]: e.nativeEvent.layout.width } }); } : undefined; return <HeaderTitle onLayout={onLayoutIOS} style={[color ? { color } : null, titleStyle]}> {titleString} </HeaderTitle>; }; _renderLeftComponent = props => { const options = this.props.getScreenDetails(props.scene).options; if (typeof options.headerLeft !== 'undefined') { return options.headerLeft; } if (props.scene.index === 0) { return null; } const backButtonTitle = this._getBackButtonTitleString(props.scene); const truncatedBackButtonTitle = this._getTruncatedBackButtonTitle(props.scene); const width = this.state.widths[props.scene.key] ? (this.props.layout.initWidth - this.state.widths[props.scene.key]) / 2 : undefined; return <HeaderBackButton onPress={() => { this.props.navigation.goBack(null); }} pressColorAndroid={options.headerPressColorAndroid} tintColor={options.headerTintColor} title={backButtonTitle} truncatedTitle={truncatedBackButtonTitle} titleStyle={options.headerBackTitleStyle} width={width} />; }; _renderRightComponent = props => { const details = this.props.getScreenDetails(props.scene); const { headerRight } = details.options; return headerRight || null; }; _renderLeft(props) { return this._renderSubView(props, 'left', this._renderLeftComponent, HeaderStyleInterpolator.forLeft); } _renderTitle(props, options) { const style = {}; if (Platform.OS === 'android') { if (!options.hasLeftComponent) { style.left = 0; } if (!options.hasRightComponent) { style.right = 0; } } return this._renderSubView({ ...props, style }, 'title', this._renderTitleComponent, HeaderStyleInterpolator.forCenter); } _renderRight(props) { return this._renderSubView(props, 'right', this._renderRightComponent, HeaderStyleInterpolator.forRight); } _renderSubView(props, name, renderer, styleInterpolator) { const { scene } = props; const { index, isStale, key } = scene; const offset = this.props.navigation.state.index - index; if (Math.abs(offset) > 2) { // Scene is far away from the active scene. Hides it to avoid unnecessary // rendering. return null; } const subView = renderer(props); if (subView == null) { return null; } const pointerEvents = offset !== 0 || isStale ? 'none' : 'box-none'; return <Animated.View pointerEvents={pointerEvents} key={`${name}_${key}`} style={[styles.item, styles[name], props.style, styleInterpolator({ // todo: determine if we really need to splat all this.props ...this.props, ...props })]}> {subView} </Animated.View>; } _renderHeader(props) { const left = this._renderLeft(props); const right = this._renderRight(props); const title = this._renderTitle(props, { hasLeftComponent: !!left, hasRightComponent: !!right }); return <View style={[StyleSheet.absoluteFill, styles.header]} key={`scene_${props.scene.key}`}> {title} {left} {right} </View>; } render() { let appBar; if (this.props.mode === 'float') { const scenesProps = this.props.scenes.map(scene => ({ position: this.props.position, progress: this.props.progress, scene })); appBar = scenesProps.map(this._renderHeader, this); } else { appBar = this._renderHeader({ position: new Animated.Value(this.props.scene.index), progress: new Animated.Value(0), scene: this.props.scene }); } // eslint-disable-next-line no-unused-vars const { scenes, scene, position, screenProps, progress, style, ...rest } = this.props; const { options } = this.props.getScreenDetails(scene, screenProps); const headerStyle = options.headerStyle; return <Animated.View {...rest} style={[styles.container, headerStyle, style]}> <View style={styles.appBar}> {appBar} </View> </Animated.View>; } } const styles = StyleSheet.create({ container: { paddingTop: STATUSBAR_HEIGHT, backgroundColor: Platform.OS === 'ios' ? '#EFEFF2' : '#FFF', height: STATUSBAR_HEIGHT + APPBAR_HEIGHT, shadowColor: 'black', shadowOpacity: 0.1, shadowRadius: StyleSheet.hairlineWidth, shadowOffset: { height: StyleSheet.hairlineWidth }, elevation: 4 }, appBar: { flex: 1 }, header: { flexDirection: 'row' }, item: { justifyContent: 'center', alignItems: 'center', backgroundColor: 'transparent' }, title: { bottom: 0, left: TITLE_OFFSET, right: TITLE_OFFSET, top: 0, position: 'absolute', alignItems: Platform.OS === 'ios' ? 'center' : 'flex-start' }, left: { left: 0, bottom: 0, top: 0, position: 'absolute' }, right: { right: 0, bottom: 0, top: 0, position: 'absolute' } }); export default Header;
src/svg-icons/device/signal-cellular-connected-no-internet-3-bar.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularConnectedNoInternet3Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M17 22V7L2 22h15zm3-12v8h2v-8h-2zm0 12h2v-2h-2v2z"/> </SvgIcon> ); DeviceSignalCellularConnectedNoInternet3Bar = pure(DeviceSignalCellularConnectedNoInternet3Bar); DeviceSignalCellularConnectedNoInternet3Bar.displayName = 'DeviceSignalCellularConnectedNoInternet3Bar'; DeviceSignalCellularConnectedNoInternet3Bar.muiName = 'SvgIcon'; export default DeviceSignalCellularConnectedNoInternet3Bar;
src/AffixMixin.js
deerawan/react-bootstrap
import React from 'react'; import domUtils from './utils/domUtils'; import EventListener from './utils/EventListener'; const AffixMixin = { propTypes: { offset: React.PropTypes.number, offsetTop: React.PropTypes.number, offsetBottom: React.PropTypes.number }, getInitialState() { return { affixClass: 'affix-top' }; }, getPinnedOffset(DOMNode) { if (this.pinnedOffset) { return this.pinnedOffset; } DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, ''); DOMNode.className += DOMNode.className.length ? ' affix' : 'affix'; this.pinnedOffset = domUtils.getOffset(DOMNode).top - window.pageYOffset; return this.pinnedOffset; }, checkPosition() { let DOMNode, scrollHeight, scrollTop, position, offsetTop, offsetBottom, affix, affixType, affixPositionTop; // TODO: or not visible if (!this.isMounted()) { return; } DOMNode = React.findDOMNode(this); scrollHeight = domUtils.getDocumentHeight(); scrollTop = window.pageYOffset; position = domUtils.getOffset(DOMNode); if (this.affixed === 'top') { position.top += scrollTop; } offsetTop = this.props.offsetTop != null ? this.props.offsetTop : this.props.offset; offsetBottom = this.props.offsetBottom != null ? this.props.offsetBottom : this.props.offset; if (offsetTop == null && offsetBottom == null) { return; } if (offsetTop == null) { offsetTop = 0; } if (offsetBottom == null) { offsetBottom = 0; } if (this.unpin != null && (scrollTop + this.unpin <= position.top)) { affix = false; } else if (offsetBottom != null && (position.top + DOMNode.offsetHeight >= scrollHeight - offsetBottom)) { affix = 'bottom'; } else if (offsetTop != null && (scrollTop <= offsetTop)) { affix = 'top'; } else { affix = false; } if (this.affixed === affix) { return; } if (this.unpin != null) { DOMNode.style.top = ''; } affixType = 'affix' + (affix ? '-' + affix : ''); this.affixed = affix; this.unpin = affix === 'bottom' ? this.getPinnedOffset(DOMNode) : null; if (affix === 'bottom') { DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, 'affix-bottom'); affixPositionTop = scrollHeight - offsetBottom - DOMNode.offsetHeight - domUtils.getOffset(DOMNode).top; } this.setState({ affixClass: affixType, affixPositionTop }); }, checkPositionWithEventLoop() { setTimeout(this.checkPosition, 0); }, componentDidMount() { this._onWindowScrollListener = EventListener.listen(window, 'scroll', this.checkPosition); this._onDocumentClickListener = EventListener.listen(domUtils.ownerDocument(this), 'click', this.checkPositionWithEventLoop); }, componentWillUnmount() { if (this._onWindowScrollListener) { this._onWindowScrollListener.remove(); } if (this._onDocumentClickListener) { this._onDocumentClickListener.remove(); } }, componentDidUpdate(prevProps, prevState) { if (prevState.affixClass === this.state.affixClass) { this.checkPositionWithEventLoop(); } } }; export default AffixMixin;
src/svg-icons/av/remove-from-queue.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvRemoveFromQueue = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-7v2H8v-2h8z"/> </SvgIcon> ); AvRemoveFromQueue = pure(AvRemoveFromQueue); AvRemoveFromQueue.displayName = 'AvRemoveFromQueue'; AvRemoveFromQueue.muiName = 'SvgIcon'; export default AvRemoveFromQueue;
app/pages/Splash.js
c446984928/playtogether
import React from 'react'; import { Dimensions, Animated } from 'react-native'; import store from 'react-native-simple-store'; import { registerApp } from 'react-native-wechat'; import AV from 'leancloud-storage'; import NavigationUtil from '../utils/NavigationUtil'; const maxHeight = Dimensions.get('window').height; const maxWidth = Dimensions.get('window').width; const splashImg = require('../img/splash.png'); class Splash extends React.Component { static navigationOptions = { header: null }; constructor(props) { super(props); this.state = { bounceValue: new Animated.Value(1) }; // registerApp('wxb24c445773822c79'); // AV.init({ // appId: 'Tfi1z7dN9sjMwSul8sYaTEvg-gzGzoHsz', // appKey: '57qmeEJonefntNqRe17dAgi4' // }); } componentDidMount() { const { navigate } = this.props.navigation; Animated.timing(this.state.bounceValue, { toValue: 1.2, duration: 1000 }).start(); this.timer = setTimeout(() => { store.get('isInit').then((isInit) => { if (!isInit) { NavigationUtil.reset(this.props.navigation, 'City',{ isFirst: true }); // navigate('Category', { isFirst: true }); } else { NavigationUtil.reset(this.props.navigation, 'Home'); } }); }, 1000); } componentWillUnmount() { clearTimeout(this.timer); } render() { return ( <Animated.Image style={{ width: maxWidth, height: maxHeight, transform: [{ scale: this.state.bounceValue }] }} source={splashImg} /> ); } } export default Splash;
Libraries/Utilities/throwOnWrongReactAPI.js
htc2u/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule throwOnWrongReactAPI * @flow */ 'use strict'; function throwOnWrongReactAPI(key: string) { throw new Error( `Seems you're trying to access 'ReactNative.${key}' from the 'react-native' package. Perhaps you meant to access 'React.${key}' from the 'react' package instead? For example, instead of: import React, { Component, View } from 'react-native'; You should now do: import React, { Component } from 'react'; import { View } from 'react-native'; Check the release notes on how to upgrade your code - https://github.com/facebook/react-native/releases/tag/v0.25.1 `); } module.exports = throwOnWrongReactAPI;
src/svg-icons/image/broken-image.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrokenImage = (props) => ( <SvgIcon {...props}> <path d="M21 5v6.59l-3-3.01-4 4.01-4-4-4 4-3-3.01V5c0-1.1.9-2 2-2h14c1.1 0 2 .9 2 2zm-3 6.42l3 3.01V19c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2v-6.58l3 2.99 4-4 4 4 4-3.99z"/> </SvgIcon> ); ImageBrokenImage = pure(ImageBrokenImage); ImageBrokenImage.displayName = 'ImageBrokenImage'; export default ImageBrokenImage;
src/components/settlement/receipt/SettlementReceiptHeader.js
HuZai/react_settlement
import React from 'react'; import {render} from 'react-dom'; import ReceiptTips from 'components/settlement/receipt/SettlementReceiptTips'; class SettlementReceiptHeader extends React.Component { rightClick() { // 发票须知 render( <ReceiptTips/>, document.getElementById("receipt-pops")); } backClick() { this.context.router.goBack(); } render() { return <div className="innerHeader"> <div className="back" onClick={()=>this.backClick()}> <div><span className="secoo_icon_back"></span></div> </div> <div className="content"> <div>发票</div> </div> <div className="more"></div> <div className="moreText" onClick={this.rightClick}>发票须知</div> </div> } } SettlementReceiptHeader.defaultProps = {}; SettlementReceiptHeader.contextTypes = { router: React.PropTypes.object.isRequired }; export default SettlementReceiptHeader;
app/imports/ui/app/HomePage.js
raiden-network/raiden-token
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; export default class HomePage extends Component { render() { const { location } = this.props; return React.createElement('div', {}, React.createElement('div', {}, React.createElement(Link, { className: 'dapp-small', to: '/admin' }, 'Admin' ), ' - register and test already deployed smart contracts.' ), React.createElement('div', {}, React.createElement(Link, { className: 'dapp-small', to: '/auction' }, 'Auction View' ), ' - test registered auction contracts.' ) ); } }
client/components/Privacy/Privacy.js
bjoberg/social-pulse
import React from 'react'; // Styles import styles from '../../main.css'; export function Privacy() { return ( <div className={styles.container}> <h1> Privacy </h1> <p> We take privacy very seriously. We do not pass on your information to any third party device or application. We use your data to post your information to the social media sites of your choice - after that, we will store the post for you, and only you, to view. </p> <p> The only way for someone to get access to your information is if they log into your account; therefore, if you believe your account has ever been compromised, please contact us and we will do our best to protect your information. </p> <p> Furthermore, every piece of data that you give us, we encrypt it. That means the data is locked; only we can see what the data means. Trust us, your data is safe in our hands. </p> </div> ); } export default Privacy;
src/icons/FavoriteIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class FavoriteIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M24 42.7l-2.9-2.63C10.8 30.72 4 24.55 4 17 4 10.83 8.83 6 15 6c3.48 0 6.82 1.62 9 4.17C26.18 7.62 29.52 6 33 6c6.17 0 11 4.83 11 11 0 7.55-6.8 13.72-17.1 23.07L24 42.7z"/></svg>;} };
src/MessageBox/MessageBoxLayout2.js
nirhart/wix-style-react
import React from 'react'; import * as styles from './MessageBoxLayout2.scss'; import {HeaderLayout1, FooterLayout1} from './'; const MessageBoxLayout2 = ({title, onCancel, onOk, confirmText, children, hideFooter, cancelText, style, theme}) => { //TODO When deprecation ends, _theme won't be needed. const _theme = theme || style; if (style) { console.warn('[wix-style-react>MessageBoxLayout2] Warning. Property \'style\' has been deprecated, and will be removed Jan 1st 2017. Please use \'theme\' instead.'); } return ( <div className={styles.content}> <HeaderLayout1 title={title} onCancel={onCancel} theme={_theme}/> <div className={styles.body} > {children} </div> { !hideFooter ? <FooterLayout1 confirmText={confirmText} cancelText={cancelText} onCancel={onCancel} onOk={onOk} theme={_theme}/> : null } </div> ); }; MessageBoxLayout2.propTypes = { hideFooter: React.PropTypes.bool, confirmText: React.PropTypes.string, cancelText: React.PropTypes.string, style: React.PropTypes.string, theme: React.PropTypes.string, onOk: React.PropTypes.func, onCancel: React.PropTypes.func, title: React.PropTypes.node, children: React.PropTypes.any }; export default MessageBoxLayout2;
examples/browserify-gulp-example/src/app/app.js
rhaedes/material-ui
import React from 'react'; import ReactDOM from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Main from './Main'; // Our custom react component //Needed for onTouchTap //Can go away when react 1.0 release //Check this repo: //https://github.com/zilverline/react-tap-event-plugin injectTapEventPlugin(); // Render the main app react component into the app div. // For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render ReactDOM.render(<Main />, document.getElementById('app'));
frontend/src/InteractiveImport/AlbumRelease/SelectAlbumReleaseModal.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import Modal from 'Components/Modal/Modal'; import SelectAlbumReleaseModalContentConnector from './SelectAlbumReleaseModalContentConnector'; class SelectAlbumReleaseModal extends Component { // // Render render() { const { isOpen, onModalClose, ...otherProps } = this.props; return ( <Modal isOpen={isOpen} onModalClose={onModalClose} > <SelectAlbumReleaseModalContentConnector {...otherProps} onModalClose={onModalClose} /> </Modal> ); } } SelectAlbumReleaseModal.propTypes = { isOpen: PropTypes.bool.isRequired, onModalClose: PropTypes.func.isRequired }; export default SelectAlbumReleaseModal;
src/containers/Profile/media/github.js
TheodorTomas/theodortomas.github.io
import React from 'react'; export default ( <svg className="icon github" width="32" height="32" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg" > <path d="M896 128q209 0 385.5 103t279.5 279.5 103 385.5q0 251-146.5 451.5t-378.5 277.5q-27 5-40-7t-13-30q0-3 .5-76.5t.5-134.5q0-97-52-142 57-6 102.5-18t94-39 81-66.5 53-105 20.5-150.5q0-119-79-206 37-91-8-204-28-9-81 11t-92 44l-38 24q-93-26-192-26t-192 26q-16-11-42.5-27t-83.5-38.5-85-13.5q-45 113-8 204-79 87-79 206 0 85 20.5 150t52.5 105 80.5 67 94 39 102.5 18q-39 36-49 103-21 10-45 15t-57 5-65.5-21.5-55.5-62.5q-19-32-48.5-52t-49.5-24l-20-3q-21 0-29 4.5t-5 11.5 9 14 13 12l7 5q22 10 43.5 38t31.5 51l10 23q13 38 44 61.5t67 30 69.5 7 55.5-3.5l23-4q0 38 .5 88.5t.5 54.5q0 18-13 30t-40 7q-232-77-378.5-277.5t-146.5-451.5q0-209 103-385.5t279.5-279.5 385.5-103zm-477 1103q3-7-7-12-10-3-13 2-3 7 7 12 9 6 13-2zm31 34q7-5-2-16-10-9-16-3-7 5 2 16 10 10 16 3zm30 45q9-7 0-19-8-13-17-6-9 5 0 18t17 7zm42 42q8-8-4-19-12-12-20-3-9 8 4 19 12 12 20 3zm57 25q3-11-13-16-15-4-19 7t13 15q15 6 19-6zm63 5q0-13-17-11-16 0-16 11 0 13 17 11 16 0 16-11zm58-10q-2-11-18-9-16 3-14 15t18 8 14-14z" /> </svg> );
client/src/app/install/install-step-3-database.js
ivandiazwm/opensupports
import React from 'react'; import _ from 'lodash'; import history from 'lib-app/history'; import i18n from 'lib-app/i18n'; import API from 'lib-app/api-call'; import Button from 'core-components/button'; import Header from 'core-components/header'; import Form from 'core-components/form'; import FormField from 'core-components/form-field'; import SubmitButton from 'core-components/submit-button'; import Message from 'core-components/message'; class InstallStep3Database extends React.Component { state = { loading: false, error: false, errorMessage: '' }; render() { return ( <div className="install-step-3"> <Header title={i18n('STEP_TITLE', {title: i18n('DATABASE_CONFIGURATION'), current: 3, total: 7})} description={i18n('STEP_3_DESCRIPTION')}/> {this.renderMessage()} <Form loading={this.state.loading} onSubmit={this.onSubmit.bind(this)}> <FormField name="dbHost" label={i18n('DATABASE_HOST')} fieldProps={{size: 'large'}} required/> <FormField name="dbPort" label={i18n('DATABASE_PORT')} fieldProps={{size: 'large'}} infoMessage={i18n('DEFAULT_PORT')}/> <FormField name="dbName" label={i18n('DATABASE_NAME')} fieldProps={{size: 'large'}} infoMessage={i18n('LEFT_EMPTY_DATABASE')}/> <FormField name="dbUser" label={i18n('DATABASE_USER')} fieldProps={{size: 'large'}} required/> <FormField name="dbPassword" label={i18n('DATABASE_PASSWORD')} fieldProps={{size: 'large', password: true}}/> <div className="install-step-3__buttons"> <SubmitButton className="install-step-3__next" size="medium" type="secondary">{i18n('NEXT')}</SubmitButton> <Button className="install-step-3__previous" size="medium" onClick={this.onPreviousClick.bind(this)}>{i18n('PREVIOUS')}</Button> </div> </Form> </div> ); } renderMessage() { let message = null; if(this.state.error) { message = ( <Message className="install-step-3__message" type="error"> {i18n('ERROR_UPDATING_SETTINGS')}: {this.state.errorMessage} </Message> ); } return message; } onPreviousClick(event) { event.preventDefault(); history.push('/install/step-2'); } onSubmit(form) { this.setState({ loading: true }, () => { API.call({ path: '/system/init-database', data: _.extend({}, form, {dbPort: form.dbPort || 3306}) }) .then(() => history.push('/install/step-4')) .catch(({message}) => this.setState({ loading: false, error: true, errorMessage: message })); }); } } export default InstallStep3Database;
src/components/texts/info-text.js
tuantle/hypertoxin
/** * Copyright 2016-present Tuan Le. * * Licensed under the MIT License. * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.html * * 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. * *------------------------------------------------------------------------ * * @module InfoText * @description - Info text component. * * @author Tuan Le (tuan.t.lei@gmail.com) * * * @flow */ 'use strict'; // eslint-disable-line import React from 'react'; import ReactNative from 'react-native'; // eslint-disable-line import PropTypes from 'prop-types'; import { Text as AnimatedText } from 'react-native-animatable'; import { DefaultTheme, DefaultThemeContext } from '../../themes/default-theme'; const DEFAULT_ANIMATION_DURATION_MS = 300; const DEFAULT_INFO_TEXT_STYLE = DefaultTheme.text.font.info; const readjustStyle = (newStyle = { shade: `themed`, alignment: `left`, decoration: `none`, font: `themed`, indentation: 0, color: `themed` }, prevAdjustedStyle = DEFAULT_INFO_TEXT_STYLE, Theme = DefaultTheme) => { const { shade, alignment, decoration, font, indentation, color, style } = newStyle; const themedShade = shade === `themed` ? Theme.text.info.shade : shade; let themedColor; if (color === `themed`) { if (Theme.text.color.info.hasOwnProperty(Theme.text.info.color)) { themedColor = Theme.text.color.info[Theme.text.info.color][themedShade]; } else { themedColor = Theme.text.info.color; } } else if (Theme.text.color.info.hasOwnProperty(color)) { themedColor = Theme.text.color.info[color][themedShade]; } else { themedColor = color; } return { small: { ...prevAdjustedStyle.small, ...Theme.text.font.info.small, fontFamily: font === `themed` ? Theme.text.font.info.small.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) }, normal: { ...prevAdjustedStyle.normal, ...Theme.text.font.info.normal, fontFamily: font === `themed` ? Theme.text.font.info.normal.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) }, large: { ...prevAdjustedStyle.large, ...Theme.text.font.info.large, fontFamily: font === `themed` ? Theme.text.font.info.large.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) } }; }; export default class InfoText extends React.Component { static contextType = DefaultThemeContext static propTypes = { exclusions: PropTypes.arrayOf(PropTypes.string), room: PropTypes.oneOf([ `none`, `content-left`, `content-middle`, `content-right`, `content-bottom`, `content-top`, `media`, `badge`, `activity-indicator` ]), shade: PropTypes.oneOf([ `themed`, `light`, `dark` ]), alignment: PropTypes.oneOf([ `left`, `center`, `right` ]), decoration: PropTypes.oneOf([ `none`, `underline`, `line-through` ]), size: PropTypes.oneOf([ `themed`, `small`, `normal`, `large` ]), font: PropTypes.string, indentation: PropTypes.number, uppercased: PropTypes.bool, lowercased: PropTypes.bool, color: PropTypes.string, initialAnimation: PropTypes.oneOfType([ PropTypes.string, PropTypes.shape({ refName: PropTypes.string, transitions: PropTypes.arrayOf(PropTypes.shape({ to: PropTypes.oneOfType([ PropTypes.func, PropTypes.object ]), from: PropTypes.oneOfType([ PropTypes.func, PropTypes.object ]), option: PropTypes.shape({ duration: PropTypes.number, delay: PropTypes.number, easing: PropTypes.string }) })), onTransitionBegin: PropTypes.func, onTransitionEnd: PropTypes.func, onAnimationBegin: PropTypes.func, onAnimationEnd: PropTypes.func }) ]) } static defaultProps = { exclusions: [ `` ], room: `none`, shade: `themed`, alignment: `left`, decoration: `none`, font: `themed`, size: `themed`, indentation: 0, uppercased: false, lowercased: false, color: `themed`, initialAnimation: `themed` } static getDerivedStateFromProps (props, state) { const { shade, alignment, decoration, font, indentation, color, style } = props; const { Theme } = state.context; return { adjustedStyle: readjustStyle({ shade, alignment, decoration, font, indentation, color, style }, state.adjustedStyle, Theme) }; } constructor (props) { super(props); const component = this; component.refCache = {}; component.state = { context: { Theme: DefaultTheme }, adjustedStyle: DEFAULT_INFO_TEXT_STYLE }; } animate (animation = { onTransitionBegin: () => null, onTransitionEnd: () => null, onAnimationBegin: () => null, onAnimationEnd: () => null }) { const component = this; const { Theme } = component.context; if (typeof animation === `string` && animation !== `none`) { const animationName = animation.replace(/-([a-z])/g, (match, word) => word.toUpperCase()); if (Theme.text.animation.info.hasOwnProperty(animationName)) { animation = Theme.text.animation.info[animationName]; } } if (typeof animation === `object`) { const { refName, transitions, onTransitionBegin, onTransitionEnd, onAnimationBegin, onAnimationEnd } = animation; const componentRef = component.refCache[refName]; if (componentRef !== undefined && Array.isArray(transitions)) { let transitionDuration = 0; const transitionPromises = transitions.map((transition, transitionIndex) => { let transitionBeginPromise; let transitionEndPromise; if (typeof transition === `object`) { let transitionType; let componentRefTransition = { from: {}, to: {} }; let componentRefTransitionOption = { duration: DEFAULT_ANIMATION_DURATION_MS, delay: 0, easing: `linear` }; if (transition.hasOwnProperty(`from`)) { let from = typeof transition.from === `function` ? transition.from(component.props, component.state, component.context) : transition.from; componentRefTransition.from = typeof from === `object` ? from : {}; transitionType = `from`; } if (transition.hasOwnProperty(`to`)) { let to = typeof transition.to === `function` ? transition.to(component.props, component.state, component.context) : transition.to; componentRefTransition.to = typeof to === `object` ? to : {}; transitionType = transitionType === `from` ? `from-to` : `to`; } if (transition.hasOwnProperty(`option`) && typeof transition.option === `object`) { componentRefTransitionOption = { ...componentRefTransitionOption, ...transition.option }; } transitionBeginPromise = new Promise((resolve) => { setTimeout(() => { if (transitionType === `to`) { componentRef.transitionTo( componentRefTransition.to, componentRefTransitionOption.duration, componentRefTransitionOption.easing, componentRefTransitionOption.delay ); } else if (transitionType === `from-to`) { setTimeout(() => { componentRef.transition( componentRefTransition.from, componentRefTransition.to, componentRefTransitionOption.duration, componentRefTransitionOption.easing ); }, componentRefTransitionOption.delay); } (typeof onTransitionBegin === `function` ? onTransitionBegin : () => null)(transitionIndex); resolve((_onTransitionBegin) => (typeof _onTransitionBegin === `function` ? _onTransitionBegin : () => null)(_onTransitionBegin)); }, transitionDuration + 5); }); transitionDuration += componentRefTransitionOption.duration + componentRefTransitionOption.delay; transitionEndPromise = new Promise((resolve) => { setTimeout(() => { (typeof onTransitionEnd === `function` ? onTransitionEnd : () => null)(transitionIndex); resolve((_onTransitionEnd) => (typeof _onTransitionEnd === `function` ? _onTransitionEnd : () => null)(transitionIndex)); }, transitionDuration); }); } return [ transitionBeginPromise, transitionEndPromise ]; }); const animationBeginPromise = new Promise((resolve) => { (typeof onAnimationBegin === `function` ? onAnimationBegin : () => null)(); resolve((_onAnimationBegin) => (typeof _onAnimationBegin === `function` ? _onAnimationBegin : () => null)()); }); const animationEndPromise = new Promise((resolve) => { setTimeout(() => { (typeof onAnimationEnd === `function` ? onAnimationEnd : () => null)(); resolve((_onAnimationEnd) => (typeof _onAnimationEnd === `function` ? _onAnimationEnd : () => null)()); }, transitionDuration + 5); }); return Promise.all([ animationBeginPromise, ...transitionPromises.flat(), animationEndPromise ].filter((animationPromise) => animationPromise !== undefined)); } } } componentDidMount () { const component = this; const { shade, alignment, decoration, font, indentation, color, initialAnimation, style } = component.props; const { Theme } = component.context; component.setState((prevState) => { return { context: { Theme }, adjustedStyle: readjustStyle({ shade, alignment, decoration, font, indentation, color, style }, prevState.adjustedStyle, Theme) }; }, () => { if ((typeof initialAnimation === `string` && initialAnimation !== `none`) || typeof initialAnimation === `object`) { component.animate(initialAnimation); } }); } componentWillUnMount () { const component = this; component.refCache = {}; } render () { const component = this; const { size, uppercased, lowercased, children } = component.props; const { adjustedStyle } = component.state; const { Theme } = component.context; const themedSize = size === `themed` ? Theme.text.info.size : size; let contentChildren = null; if (React.Children.count(children) > 0) { contentChildren = React.Children.toArray(React.Children.map(children, (child) => { if (uppercased) { return child.toUpperCase(); } else if (lowercased) { return child.toLowerCase(); } return child; })); } return ( <AnimatedText ref = {(componentRef) => { component.refCache[`animated-text`] = componentRef; }} style = { adjustedStyle[themedSize] } ellipsizeMode = 'tail' numberOfLines = { 1028 } useNativeDriver = { true } > { contentChildren } </AnimatedText> ); } }
js/Details.js
jelliotartz/FEM-react-intro
import React from 'react' import { connect } from 'react-redux' import { getOMDBDetails } from './actionCreators' import Header from './Header' const { shape, string, func } = React.PropTypes const Details = React.createClass({ propTypes: { show: shape({ title: string, year: string, poster: string, trailer: string, description: string, imdbID: string }), omdbData: shape({ imdbID: string }), dispatch: func }, componentDidMount () { if (!this.props.omdbData.imdbRating) { this.props.dispatch(getOMDBDetails(this.props.show.imdbID)) } }, render () { const { title, description, year, poster, trailer } = this.props.show let rating if (this.props.omdbData.imdbRating) { rating = <h3>{this.props.omdbData.imdbRating}</h3> } else { rating = <img src='/public/img/loading.png' alt='loading indicator' /> } return ( <div className='details'> <Header /> <section> <h1>{title}</h1> <h2>({year})</h2> {rating} <img src={`/public/img/posters/${poster}`} /> <p>{description}</p> </section> <div> <iframe src={`https://www.youtube-nocookie.com/embed/${trailer}?rel=0&amp;controls=0&amp;showinfo=0`} frameBorder='0' allowFullScreen /> </div> </div> ) } }) Details.propTypes = { params: React.PropTypes.object } // ownProps are the properties coming in from the react component (here, Details) - we need the imdbID from show to select the correct show to provide to Details const mapStateToProps = (state, ownProps) => { const omdbData = state.omdbData[ownProps.show.imdbID] ? state.omdbData[ownProps.show.imdbID] : {} return { omdbData } } export default connect(mapStateToProps)(Details)
test/regressions/tests/Button/MultilineButton.js
cherniavskii/material-ui
// @flow import React from 'react'; import Button from 'material-ui/Button'; export default function MultilineButton() { return ( <Button variant="raised" style={{ width: 400 }}> {[ 'Raised buttons are rectangular-shaped buttons.', 'They may be used inline.', 'They lift and display ink reactions on press.', ].join(' ')} </Button> ); }
docs/src/app/components/pages/components/List/Page.js
igorbt/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import listReadmeText from './README'; import listExampleSimpleCode from '!raw!./ExampleSimple'; import ListExampleSimple from './ExampleSimple'; import listExampleChatCode from '!raw!./ExampleChat'; import ListExampleChat from './ExampleChat'; import listExampleContactsCode from '!raw!./ExampleContacts'; import ListExampleContacts from './ExampleContacts'; import listExampleFoldersCode from '!raw!./ExampleFolders'; import ListExampleFolders from './ExampleFolders'; import listExampleNestedCode from '!raw!./ExampleNested'; import ListExampleNested from './ExampleNested'; import listExampleSettingsCode from '!raw!./ExampleSettings'; import ListExampleSettings from './ExampleSettings'; import listExamplePhoneCode from '!raw!./ExamplePhone'; import ListExamplePhone from './ExamplePhone'; import listExampleMessagesCode from '!raw!./ExampleMessages'; import ListExampleMessages from './ExampleMessages'; import listExampleSelectableCode from '!raw!./ExampleSelectable'; import ListExampleSelectable from './ExampleSelectable'; import listCode from '!raw!material-ui/List/List'; import listItemCode from '!raw!material-ui/List/ListItem'; const descriptions = { simple: 'A simple `List` with left and right [SVG icons](/#/components/svg-icon).', chat: 'A chat list with Image [Avatars](/#/components/avatar) and [Subheader](/#/components/subheader).', contacts: 'Similar to the Chat List example, but with Text [Avatars](/#/components/avatar) ' + '(with transparent background) for section labeling, and an inset Divider. ', folders: 'The folder list uses Icon [Avatars](/#/components/avatar), and introduces `secondaryText`.', nested: 'This example introduces the ListItem `nestedItems` property. "Sent Mail" is `disabled`.', settings: 'ListItem supports [Checkbox](/#/components/checkbox) and [Toggle](/#/components/toggle) switches.', phone: '', messages: 'Two examples showing formatted secondary text. The second example demonstrates an ' + '[IconButton](/#/components/icon-button) with `tooltip`.', selectable: 'The selectable list wraps List in a Higher Order Component.', }; const ListPage = () => ( <div> <Title render={(previousTitle) => `List - ${previousTitle}`} /> <MarkdownElement text={listReadmeText} /> <CodeExample title="Simple list" description={descriptions.simple} code={listExampleSimpleCode} > <ListExampleSimple /> </CodeExample> <CodeExample title="Chat list" description={descriptions.chat} code={listExampleChatCode} > <ListExampleChat /> </CodeExample> <CodeExample title="Contact list" description={descriptions.contacts} code={listExampleContactsCode} > <ListExampleContacts /> </CodeExample> <CodeExample title="Folder list" description={descriptions.folder} code={listExampleFoldersCode} > <ListExampleFolders /> </CodeExample> <CodeExample title="Nested list" description={descriptions.nested} code={listExampleNestedCode} > <ListExampleNested /> </CodeExample> <CodeExample title="Settings list" description={descriptions.settings} code={listExampleSettingsCode} > <ListExampleSettings /> </CodeExample> <CodeExample title="Phone list" description={descriptions.phone} code={listExamplePhoneCode} > <ListExamplePhone /> </CodeExample> <CodeExample title="Messages list" description={descriptions.messages} code={listExampleMessagesCode} > <ListExampleMessages /> </CodeExample> <CodeExample title="Selectable list" description={descriptions.selectable} code={listExampleSelectableCode} > <ListExampleSelectable /> </CodeExample> <PropTypeDescription header="### List Properties" code={listCode} /> <PropTypeDescription header="### ListItem Properties" code={listItemCode} /> </div> ); export default ListPage;
server/server.js
CODEINAE/todoy
import Express from 'express'; import compression from 'compression'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import path from 'path'; import IntlWrapper from '../client/modules/Intl/IntlWrapper'; // Webpack Requirements import webpack from 'webpack'; import config from '../webpack.config.dev'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; // Initialize the Express App const app = new Express(); // Run Webpack dev server in development mode if (process.env.NODE_ENV === 'development') { const compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); } // React And Redux Setup import { configureStore } from '../client/store'; import { Provider } from 'react-redux'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import Helmet from 'react-helmet'; // Import required modules import routes from '../client/routes'; import { fetchComponentData } from './util/fetchData'; import posts from './routes/post.routes'; import dummyData from './dummyData'; import serverConfig from './config'; // Set native promises as mongoose promise mongoose.Promise = global.Promise; // MongoDB Connection mongoose.connect(serverConfig.mongoURL, (error) => { if (error) { console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console throw error; } // feed some dummy data in DB. dummyData(); }); // Apply body Parser and server public assets and routes app.use(compression()); app.use(bodyParser.json({ limit: '20mb' })); app.use(bodyParser.urlencoded({ limit: '20mb', extended: false })); app.use(Express.static(path.resolve(__dirname, '../dist'))); app.use('/api', posts); // Render Initial HTML const renderFullPage = (html, initialState) => { const head = Helmet.rewind(); // Import Manifests const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets); const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets); return ` <!doctype html> <html> <head> ${head.base.toString()} ${head.title.toString()} ${head.meta.toString()} ${head.link.toString()} ${head.script.toString()} ${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''} <link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/> <link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" /> </head> <body> <div id="root">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; ${process.env.NODE_ENV === 'production' ? `//<![CDATA[ window.webpackManifest = ${JSON.stringify(chunkManifest)}; //]]>` : ''} </script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script> </body> </html> `; }; const renderError = err => { const softTab = '&#32;&#32;&#32;&#32;'; const errTrace = process.env.NODE_ENV !== 'production' ? `:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : ''; return renderFullPage(`Server Error${errTrace}`, {}); }; // Server Side Rendering based on routes matched by React-router. app.use((req, res, next) => { match({ routes, location: req.url }, (err, redirectLocation, renderProps) => { if (err) { return res.status(500).end(renderError(err)); } if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search); } if (!renderProps) { return next(); } const store = configureStore(); return fetchComponentData(store, renderProps.components, renderProps.params) .then(() => { const initialView = renderToString( <Provider store={store}> <IntlWrapper> <RouterContext {...renderProps} /> </IntlWrapper> </Provider> ); const finalState = store.getState(); res .set('Content-Type', 'text/html') .status(200) .end(renderFullPage(initialView, finalState)); }) .catch((error) => next(error)); }); }); // start app app.listen(serverConfig.port, (error) => { if (!error) { console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line } }); export default app;
src/index.js
muiradams/plantogo
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import reduxThunk from 'redux-thunk'; import App from './components/App'; import Welcome from './components/Welcome'; import Signin from './components/authentication/Signin'; import Signup from './components/authentication/Signup'; import Forgot from './components/authentication/Forgot'; import Reset from './components/authentication/Reset'; import ShowUser from './components/ShowUser'; import TripList from './components/TripList'; import TripDetail from './components/TripDetail'; import ShowActivity from './components/ShowActivity'; import RequireAuthentication from './components/authentication/RequireAuthentication'; import { AUTH_USER } from './actions/types'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore); const store = createStoreWithMiddleware(reducers) const token = localStorage.getItem('token'); // If we have a token then consider the user to be signed in already if (token) { store.dispatch({ type: AUTH_USER }); } ReactDOM.render( <Provider store={store}> <Router history={browserHistory}> <Route component={App}> <Route path="/" component={Welcome}> <IndexRoute component={Signin} /> <Route path="/signup" component={Signup} /> <Route path="/forgot" component={Forgot} /> <Route path="/reset/:token" component={Reset} /> </Route> <Route path="/user/:username" component={RequireAuthentication(ShowUser)}> <IndexRoute component={TripList} /> <Route path="/user/:username/trip/:tripId" component={TripDetail} /> <Route path="/user/:username/trip/:tripId/activity/" component={ShowActivity} /> <Route path="/user/:username/trip/:tripId/activity/:activityId" component={ShowActivity} /> </Route> </Route> </Router> </Provider> , document.querySelector('.container'));
src/routes/general/confirmation/index.js
chunkiat82/rarebeauty-ui
/* eslint-disable jsx-a11y/alt-text */ /** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import moment from 'moment-timezone'; import Layout from '../../../components/PublicLayout'; import MapAndMessage from '../common/mapAndMessage'; // eslint-disable-next-line css-modules/no-unused-class import s from '../common/mapAndMessage.css'; async function action({ store }) { const { event, workAddress, oldWorkAddress, oldSafeEntryLink, safeEntryLink, } = store.getState(); const startDateTime = moment(event.start.dateTime); const address = startDateTime.isBefore('2020-07-01') ? oldWorkAddress : workAddress; const seLink = startDateTime.isBefore('2020-07-01') ? oldSafeEntryLink : safeEntryLink; const src = startDateTime.isBefore('2020-07-01') ? 'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d7977.465154156651!2d103.69033662836527!3d1.3367016720327713!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x31da0f8ffc39bba3%3A0x86c5239af2cbccd7!2sSingapore%20642987!5e0!3m2!1sen!2ssg!4v1571484005118!5m2!1sen!2ssg' : 'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d15954.921969560013!2d103.68922277989016!3d1.3379843862102117!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x31da0f91b8b821c7%3A0xc05561d22390b4e0!2sSingapore%20642649!5e0!3m2!1sen!2ssg!4v1593248847700!5m2!1sen!2ssg'; return { chunks: ['general-confirmation'], title: 'Rare Beauty Professional', component: ( <Layout> <div className={s.confirmation}> <div style={{ width: '20%', float: 'left' }}> <a href={seLink}> <img src="https://rarebeautysg.s3.amazonaws.com/clickhere_50.png" /> </a> </div> <div style={{ width: '80%', float: 'right' }}> <a href={seLink}> <img src="https://www.safeentry-qr.gov.sg/assets/images/safe_entry_banner.svg" /> </a> </div> </div> <MapAndMessage address={address} src={src} message={`Appointment is confirmed! See you on ${moment( event.start.dateTime, ) .tz('Asia/Singapore') .format('LLLL')}`} /> </Layout> ), }; } export default action;
src/components/google/original/GoogleOriginal.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './GoogleOriginal.svg' /** GoogleOriginal */ function GoogleOriginal({ width, height, className }) { return ( <SVGDeviconInline className={'GoogleOriginal' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } GoogleOriginal.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default GoogleOriginal
src/components/slide2-jsx.js
lucky3mvp/react-demo
import React from 'react' export default React.createClass({ render () { return ( <div className="m-code-dis no-border"> <img src="../img/jsx.jpg" height="400" width="500" /> </div> ) } })
client/admin/components/navbar.js
kirinami/portfolio
import moment from 'moment'; import React, { Component } from 'react'; import { Link, Route, withRouter } from 'react-router-dom'; import { inject, observer } from 'mobx-react'; import { UncontrolledTooltip } from 'reactstrap'; @withRouter @inject('alertStore', 'authStore', 'contactStore') @observer export default class Navbar extends Component { componentDidMount() { const { alertStore, contactStore } = this.props; contactStore.loadContacts() .then(() => alertStore.showSuccess('"Contacts" loaded successfully')) .catch(err => alertStore.showDanger(err.message)); } async handleLogout() { const { alertStore, authStore, location, history } = this.props; try { const response = await authStore.logout(); if (response.success) { history.replace({ pathname: '/login', state: { from: location, }, }); } alertStore.showSuccess(response.message); } catch (err) { alertStore.showDanger(err.message); } } render() { const { contactStore } = this.props; return ( <div className="navbar-component"> <nav id="main-nav" className="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <Link className="navbar-brand" to="/">KIRINAMI</Link> <button type="button" className="navbar-toggler navbar-toggler-right"> <span className="navbar-toggler-icon"/> </button> <div id="navbar-responsive" className="collapse navbar-collapse"> <ul id="accordion" className="navbar-nav navbar-sidenav"> <Route exact path="/" children={({ match }) => ( <li className={`nav-item ${match ? ' active' : ''}`}> <Link className="nav-link" to="/"> <i className="fa fa-fw fa-dashboard"/> <span className="nav-link-text">Dashboard</span> </Link> </li> )}/> <Route exact path="/technology" children={({ match }) => ( <li className={`nav-item ${match ? ' active' : ''}`}> <Link className="nav-link" to="/technology"> <i className="fa fa-fw fa-sitemap"/> <span className="nav-link-text">Technologies</span> </Link> </li> )}/> <Route exact path="/project" children={({ match }) => ( <li className={`nav-item ${match ? ' active' : ''}`}> <Link className="nav-link" to="/project"> <i className="fa fa-fw fa-tasks"/> <span className="nav-link-text">Projects</span> </Link> </li> )}/> <Route exact path="/contacts" children={({ match }) => ( <li className={`nav-item ${match ? ' active' : ''}`}> <Link className="nav-link" to="/contacts"> <i className="fa fa-fw fa-envelope"/> <span className="nav-link-text">Contacts</span> </Link> </li> )}/> <Route exact path="/settings" children={({ match }) => ( <li className={`nav-item ${match ? ' active' : ''}`}> <Link className="nav-link" to="/settings"> <i className="fa fa-fw fa-cogs"/> <span className="nav-link-text">Settings</span> </Link> </li> )}/> </ul> <ul className="navbar-nav sidenav-toggler"> <li className="nav-item"> <a id="sidenav-toggler" className="nav-link text-center"> <i className="fa fa-fw fa-angle-left"/> </a> </li> </ul> <ul className="navbar-nav ml-auto"> <li className="nav-item dropdown"> <a id="messages-dropdown" className="nav-link dropdown-toggle mr-lg-2" href="#" data-toggle="dropdown"> <i className="fa fa-fw fa-envelope"/> <span className="d-lg-none">Messages <span className="badge badge-pill badge-primary">{contactStore.contacts.length} New</span></span> <span className="indicator text-primary d-none d-lg-block"><i className="fa fa-fw fa-circle"/></span> </a> <div className="dropdown-menu dropdown-menu-right"> <h6 className="dropdown-header">New Contact:</h6> <div className="dropdown-divider"/> {contactStore.contacts.map(contact => <div key={contact._id}> <Link className="dropdown-item" to="/contacts"> <strong>{contact.name}</strong> <span className="small float-right text-muted" style={{ marginTop: '1px' }}> {moment(contact.createdAt).format('YYYY-MM-DD hh:mm:ss')} </span> <div className="dropdown-message small">{contact.message}</div> </Link> <div className="dropdown-divider"/> </div>, )} <Link className="dropdown-item small" to="/contacts">View all contacts</Link> </div> </li> <li className="nav-item"> <a className="nav-link" href="javascript:void(0)" onClick={() => this.handleLogout()}> <i className="fa fa-fw fa-sign-out"/> Logout </a> </li> </ul> </div> </nav> </div> ); } }
examples/01 Dustbin/Multiple Targets/index.js
globexdesigns/react-dnd
import React, { Component } from 'react'; import Container from './Container'; export default class DustbinMultipleTargets extends Component { render() { return ( <div> <p> <b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/01%20Dustbin/Multiple%20Targets'>Browse the Source</a></b> </p> <p> This is a slightly more interesting example. </p> <p> It demonstrates how a single drop target may accept multiple types, and how those types may be derived from props. It also demonstrates the handling of native files and URLs (try dropping them onto the last two dustbins). </p> <Container /> </div> ); } }
01_webstack/03Wk02/conFusion_Gulp/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
allenmodroid/webstack
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
pages/product.js
dwest-teo/wattos-spaceship-emporium
import React from 'react'; import PropTypes from 'prop-types'; import withRedux from 'next-redux-wrapper'; import initStore from '../lib/store'; import serverSideInit from '../lib/server-side-init'; import { openSidebar, toggleDropdown } from '../actions/menu'; import { addToCart, removeFromCart } from '../actions/cart'; import App from '../components/app'; import { Container, Text, Flex, Box, DefinitionList, } from '../components/base'; import TopContainer from '../components/product-page/top-container'; import DetailsPane from '../components/product-page/details-pane'; import Carousel from '../components/carousel'; const Product = ({ activeProduct, addToCart, ...props }) => ( <App title={activeProduct.name} activeLink={activeProduct.slug} {...props}> <Container> <Text mb2 is="h1" fontSize={[ 3, 2, 2, 2 ]}> {activeProduct.name} </Text> <TopContainer> <Flex width={[ 1, 0.7, 1, 0.7 ]} pb={[ 2, 0, 2, 0 ]}> <Carousel key={activeProduct.slug} productId={activeProduct.slug} images={activeProduct.images} /> </Flex> <DetailsPane manufacturer={activeProduct.manufacturer} type={activeProduct.class} price={activeProduct.price} slug={activeProduct.slug} name={activeProduct.name} thumbnail={activeProduct.thumbnail} addToCart={addToCart} /> </TopContainer> <Box my3> <Text caps mb1 is="h3" fontSize={4}>About this ship:</Text> <Text is="p"> {activeProduct.description} </Text> </Box> <Box my3> <Text caps mb1 is="h3" fontSize={4}>Specifications:</Text> {activeProduct.techspecs.map((spec, i) => ( <DefinitionList key={i} entry={spec} /> ))} </Box> </Container> </App> ); Product.getInitialProps = async ({ store, isServer, query }) => { const { slug } = await query; const init = await serverSideInit(store, isServer); const productFeed = await store.getState().Products; const activeProduct = await productFeed.find(p => p.slug === slug); return { activeProduct, init }; }; Product.propTypes = { activeProduct: PropTypes.shape({ name: PropTypes.string, manufacturer: PropTypes.string, class: PropTypes.string, price: PropTypes.string, techspecs: PropTypes.array, slug: PropTypes.string, description: PropTypes.string, images: PropTypes.arrayOf(PropTypes.string), }), addToCart: PropTypes.func, }; export default withRedux(initStore, state => ({ products: state.Products, cartProducts: state.Cart, isLarge: state.browser.greaterThan.medium, isSidebarOpen: state.Menu.sidebarOpen, isDropdownOpen: state.Menu.dropdownOpen, }), { openSidebar, toggleDropdown, addToCart, removeFromCart })(Product);
src/index.js
yuhaogo/study-mk-photos
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/svg-icons/hardware/keyboard-arrow-up.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardArrowUp = (props) => ( <SvgIcon {...props}> <path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"/> </SvgIcon> ); HardwareKeyboardArrowUp = pure(HardwareKeyboardArrowUp); HardwareKeyboardArrowUp.displayName = 'HardwareKeyboardArrowUp'; export default HardwareKeyboardArrowUp;
packages/generator-react-redux-template/generators/component/templates/Component.js
abouthiroppy/dish
import React from 'react';<% if (style) { %> import styles from './style.css';<% } %> <% if (isStateless) { %> const <%= componentname %> = () => (<% if (style) { %> <div className={styles.container}>hello</div><% } else { %> <div>hello</div><% } %> );<% } else { %> class <%= componentname %> extends React.Component { constructor() { super(); this.state = {}; } render() { return (<% if (style) { %> <div className={styles.container}>hello</div><% } else { %> <div>hello</div><% } %> ); } }<% } %> export default <%= componentname %>;
src/Interests.js
pebutler3/new-site
import React, { Component } from 'react'; class Interests extends Component { render() { return ( <ul className="col-3"> <h2>Interests</h2> <li>JavaScript</li> <li>ReactJS</li> <li>NodeJs</li> <li>SCSS</li> <li>Static Sites</li> <li>Performance</li> <li>Semantic Markup</li> </ul> ); } } export default Interests;
scripts/benchmarks/src/app/Text.js
tkh44/emotion
/* eslint-disable react/prop-types */ import { bool } from 'prop-types' import React from 'react' import { StyleSheet, Text } from 'react-native' import { colors } from './theme' class AppText extends React.Component { static displayName = '@app/Text' static contextTypes = { isInAParentText: bool } render() { const { style, ...rest } = this.props const { isInAParentText } = this.context return ( <Text {...rest} style={[!isInAParentText && styles.baseText, style]} /> ) } } const styles = StyleSheet.create({ baseText: { color: colors.textBlack, fontSize: '1rem', lineHeight: '1.3125em' } }) export default AppText
code/workspaces/web-app/src/components/common/PromisedContentWrapper.js
NERC-CEH/datalab
import React from 'react'; import PropTypes from 'prop-types'; import { makeStyles } from '@material-ui/core'; import CircularProgress from '@material-ui/core/CircularProgress'; const useStyles = makeStyles(() => ({ fullSizeBase: { display: 'flex', alignItems: 'center', justifyContent: 'center', }, fullWidth: { width: '100%', }, fullHeight: { height: '100%', }, })); const PromisedContentWrapper = ({ children, promise, className, fetchingClassName, fullWidth = true, fullHeight = false, loadingSize = 40 }) => { const isFetching = isPromiseFetching(promise); const content = isFetching ? <CircularProgress size={loadingSize}/> : children; const classWrapper = getClassWrappedContent(content, isFetching, className, fetchingClassName); return getSizeWrappedContent(classWrapper, isFetching, fullWidth, fullHeight); }; export const ClassWrapper = ({ isFetching, className, fetchingClassName, children }) => { const finalClassName = createClassName( className, isFetching && fetchingClassName, ); return ( <div className={finalClassName}> {children} </div> ); }; export const SizeWrapper = ({ fullWidth, fullHeight, children }) => { const classes = useStyles(); const sizeClassName = createClassName( fullWidth || fullHeight ? classes.fullSizeBase : undefined, fullWidth ? classes.fullWidth : undefined, fullHeight ? classes.fullHeight : undefined, ); return <div className={sizeClassName}>{children}</div>; }; export const createClassName = (...names) => names.filter(item => !!item).join(' '); const isPromiseFetching = (promise) => { if (Array.isArray(promise)) { return promise.map(item => item.fetching).includes(true); } return promise.fetching; }; const getClassWrappedContent = (content, isFetching, className, fetchingClassName) => ( className || (isFetching && fetchingClassName) ? ( <ClassWrapper isFetching={isFetching} className={className} fetchingClassName={fetchingClassName}> {content} </ClassWrapper> ) : content ); const getSizeWrappedContent = (content, isFetching, fullWidth, fullHeight) => ( isFetching && (fullWidth || fullHeight) ? ( <SizeWrapper fullWidth={fullWidth} fullHeight={fullHeight}> {content} </SizeWrapper> ) : content ); const promiseType = PropTypes.shape({ error: PropTypes.shape({ message: PropTypes.string, }), fetching: PropTypes.bool.isRequired, value: PropTypes.any, }); PromisedContentWrapper.propTypes = { children: PropTypes.element.isRequired, promise: PropTypes.oneOfType([ PropTypes.arrayOf(promiseType), promiseType, ]).isRequired, className: PropTypes.string, fetchingClassName: PropTypes.string, fullWidth: PropTypes.bool, fullHeight: PropTypes.bool, loadingSize: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), }; export default PromisedContentWrapper;
src/components/AudioPlayer.js
erwaiyang/aup-to-srt-for-NTUPDS
import React, { Component } from 'react'; class AudioPlayer extends Component { constructor(props){ super(props); this.state = { audio: null }; } handleFile(e){ let file = e.target.files[0]; const URL = window.URL || window.webkitURL; const fileURL = URL.createObjectURL(file); this.state.audio.src = fileURL; } componentDidMount(){ this.state.audio = document.getElementById('audio'); const { audio } = this.state; let self = this; audio.addEventListener('timeupdate', () => { if (self.props.endTime && audio.currentTime >= self.props.endTime) { audio.pause(); } }); } componentWillReceiveProps(nextProps){ if(nextProps.startTime !== this.props.startTime || nextProps.endTime !== this.props.endTime){ this.state.audio.currentTime = nextProps.startTime; this.state.audio.play(); } } handlePlayAll(){ this.props.setPlayTime(0, this.state.audio.duration); } render(){ return( <div> <audio id="audio" controls> 這位社員大大,(空一格)貴瀏覽器不支援HTML5 AUDIO QQ 該不會是用IE吧?!請愛用Chrome或Firefox~ </audio> <button className="positive small ui button" onClick={this.handlePlayAll.bind(this)}>播放全部</button> <input accept="audio/*" type="file" onChange={this.handleFile.bind(this)} /> </div> ); } } AudioPlayer.propTypes = { }; export default AudioPlayer;
application/js/Components/Home/HomeNavigation.js
cfrank/React-Reddit
import React from 'react' import { Link, IndexLink } from 'react-router' const ACTIVE_CLASS = "active-home-link" export default class HomeNavigation extends React.Component{ render(){ return( <nav className="home-navigation"> <ul> <li><IndexLink to="/" activeClassName={ACTIVE_CLASS}>Home</IndexLink></li> <li><Link to="/info" activeClassName={ACTIVE_CLASS}>Info</Link></li> </ul> </nav> ) } }
src/svg-icons/action/bug-report.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBugReport = (props) => ( <SvgIcon {...props}> <path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/> </SvgIcon> ); ActionBugReport = pure(ActionBugReport); ActionBugReport.displayName = 'ActionBugReport'; ActionBugReport.muiName = 'SvgIcon'; export default ActionBugReport;
client/app/scripts/components/nodes-resources.js
paulbellamy/scope
import React from 'react'; import { connect } from 'react-redux'; import Logo from './logo'; import ZoomWrapper from './zoom-wrapper'; import NodesResourcesLayer from './nodes-resources/node-resources-layer'; import { layersTopologyIdsSelector } from '../selectors/resource-view/layout'; import { resourcesZoomLimitsSelector, resourcesZoomStateSelector, } from '../selectors/resource-view/zoom'; class NodesResources extends React.Component { renderLayers(transform) { return this.props.layersTopologyIds.map((topologyId, index) => ( <NodesResourcesLayer key={topologyId} topologyId={topologyId} transform={transform} slot={index} /> )); } render() { return ( <div className="nodes-resources"> <svg id="canvas" width="100%" height="100%"> <Logo transform="translate(24,24) scale(0.25)" /> <ZoomWrapper svg="canvas" bounded forwardTransform fixVertical zoomLimitsSelector={resourcesZoomLimitsSelector} zoomStateSelector={resourcesZoomStateSelector}> {transform => this.renderLayers(transform)} </ZoomWrapper> </svg> </div> ); } } function mapStateToProps(state) { return { layersTopologyIds: layersTopologyIdsSelector(state), }; } export default connect( mapStateToProps )(NodesResources);
src/svg-icons/image/wb-sunny.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageWbSunny = (props) => ( <SvgIcon {...props}> <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/> </SvgIcon> ); ImageWbSunny = pure(ImageWbSunny); ImageWbSunny.displayName = 'ImageWbSunny'; ImageWbSunny.muiName = 'SvgIcon'; export default ImageWbSunny;
app/javascript/mastodon/components/admin/Dimension.js
yi0713/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import api from 'mastodon/api'; import { FormattedNumber } from 'react-intl'; import { roundTo10 } from 'mastodon/utils/numbers'; import Skeleton from 'mastodon/components/skeleton'; export default class Dimension extends React.PureComponent { static propTypes = { dimension: PropTypes.string.isRequired, start_at: PropTypes.string.isRequired, end_at: PropTypes.string.isRequired, limit: PropTypes.number.isRequired, label: PropTypes.string.isRequired, params: PropTypes.object, }; state = { loading: true, data: null, }; componentDidMount () { const { start_at, end_at, dimension, limit, params } = this.props; api().post('/api/v1/admin/dimensions', { keys: [dimension], start_at, end_at, limit, [dimension]: params }).then(res => { this.setState({ loading: false, data: res.data, }); }).catch(err => { console.error(err); }); } render () { const { label, limit } = this.props; const { loading, data } = this.state; let content; if (loading) { content = ( <table> <tbody> {Array.from(Array(limit)).map((_, i) => ( <tr className='dimension__item' key={i}> <td className='dimension__item__key'> <Skeleton width={100} /> </td> <td className='dimension__item__value'> <Skeleton width={60} /> </td> </tr> ))} </tbody> </table> ); } else { const sum = data[0].data.reduce((sum, cur) => sum + (cur.value * 1), 0); content = ( <table> <tbody> {data[0].data.map(item => ( <tr className='dimension__item' key={item.key}> <td className='dimension__item__key'> <span className={`dimension__item__indicator dimension__item__indicator--${roundTo10(((item.value * 1) / sum) * 100)}`} /> <span title={item.key}>{item.human_key}</span> </td> <td className='dimension__item__value'> {typeof item.human_value !== 'undefined' ? item.human_value : <FormattedNumber value={item.value} />} </td> </tr> ))} </tbody> </table> ); } return ( <div className='dimension'> <h4>{label}</h4> {content} </div> ); } }
packages/vx-gradient/src/gradients/DarkgreenGreen.js
Flaque/vx
import React from 'react'; import LinearGradient from './LinearGradient'; export default (props) => { return ( <LinearGradient from='#184E86' to='#57CA85' {...props} /> ); }
src/js/components/ui/CardContent.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { ORIGIN_CONTEXT } from '../../constants/Constants'; import ProgressBar from './ProgressBar'; import CardIcons from './CardIcons'; import Image from './Image'; import UserStore from '../../stores/UserStore'; import * as UserActionCreators from '../../actions/UserActionCreators' import translate from '../../i18n/Translate'; import ShareService from '../../services/ShareService'; import LinkImageService from '../../services/LinkImageService'; import Framework7Service from '../../services/Framework7Service'; @translate('CardContent') export default class CardContent extends Component { static propTypes = { contentId : PropTypes.number.isRequired, title : PropTypes.string, description : PropTypes.string, types : PropTypes.array.isRequired, url : PropTypes.string.isRequired, embed_id : PropTypes.string, embed_type : PropTypes.string, thumbnail : PropTypes.string, synonymous : PropTypes.array.isRequired, matching : PropTypes.number, rate : PropTypes.oneOfType([PropTypes.number, PropTypes.bool]), hideLikeButton: PropTypes.bool.isRequired, fixedHeight : PropTypes.bool, loggedUserId : PropTypes.number.isRequired, onReport : PropTypes.func, otherUserId : PropTypes.number, // Injected by @translate: strings : PropTypes.object }; constructor(props) { super(props); this.onDropDown = this.onDropDown.bind(this); this.onRate = this.onRate.bind(this); this.onShare = this.onShare.bind(this); this.onReport = this.onReport.bind(this); this.handleClick = this.handleClick.bind(this); this.onShareSuccess = this.onShareSuccess.bind(this); this.onShareError = this.onShareError.bind(this); this.state = { embedHtml: null } } componentDidMount() { if (!window.cordova && this.state.embedHtml && this.props.embed_type === 'facebook') { FB.XFBML.parse(); } } componentDidUpdate() { if (!window.cordova && this.state.embedHtml && this.props.embed_type === 'facebook') { FB.XFBML.parse(); } } onDropDown() { const {rate, title, strings} = this.props; const likeText = rate ? strings.unlike : strings.like; let buttons = [ { text: title, label: true }, { color: 'gray', text: '<span class="icon-star"></span> ' + likeText, onClick: this.onRate }, { color: 'gray', text: '<span class="icon-share"></span> ' + strings.share, onClick: this.onShare } ]; if (this.props.onReport) { buttons.push( { color: 'gray', text: '<span class="icon-warning"></span> ' + strings.report, onClick: this.onReport } ); } buttons.push( { color: 'red', text: strings.cancel } ); Framework7Service.nekunoApp().actions(buttons); } onRate() { const {loggedUserId, otherUserId, contentId, rate} = this.props; if (!rate) { const originContext = otherUserId ? ORIGIN_CONTEXT.OTHER_INTERESTS_PAGE : ORIGIN_CONTEXT.OWN_INTERESTS_PAGE; const originName = otherUserId && UserStore.get(otherUserId) ? UserStore.get(otherUserId).username : null; UserActionCreators.likeContent(loggedUserId, contentId, originContext, originName); } else { UserActionCreators.deleteRateContent(loggedUserId, contentId); } } onShare() { const {title, url, strings} = this.props; ShareService.share(title, url, this.onShareSuccess, this.onShareError, strings.copiedToClipboard); } onShareSuccess() { const {loggedUserId, otherUserId, contentId, rate} = this.props; if (!rate) { const originContext = otherUserId ? ORIGIN_CONTEXT.OTHER_INTERESTS_PAGE : ORIGIN_CONTEXT.OWN_INTERESTS_PAGE; const originName = otherUserId ? otherUserId : null; UserActionCreators.likeContent(loggedUserId, contentId, originContext, originName); } } onShareError() { Framework7Service.nekunoApp().alert(this.props.strings.shareError) } onReport() { const {strings} = this.props; const buttons = [ { color: 'gray', text: strings.notInteresting, onClick: this.onReportReason.bind(this, 'not interesting') }, { color: 'gray', text: strings.harmful, onClick: this.onReportReason.bind(this, 'harmful') }, { color: 'gray', text: strings.spam, onClick: this.onReportReason.bind(this, 'spam') }, { color: 'gray', text: strings.otherReasons, onClick: this.onReportReason.bind(this, 'other') }, { color: 'red', text: strings.cancel } ]; Framework7Service.nekunoApp().actions(buttons); } onReportReason(reason) { const {loggedUserId, contentId, rate} = this.props; if (rate) { UserActionCreators.deleteRateContent(loggedUserId, contentId); } setTimeout(() => this.props.onReport(contentId, reason), 0); } handleClick() { const {url, types, embed_type, embed_id} = this.props; const isVideo = types.indexOf('Video') > -1; if (isVideo && !window.cordova && window.screen.width > 320) { this.preVisualizeVideo(embed_type, embed_id, url); } else { window.cordova ? document.location = url : window.open(url); } } preVisualizeVideo = function (embed_type, embed_id, url) { let html = null; switch (embed_type) { case 'youtube': html = <iframe className="discover-video" src={'https://www.youtube.com/embed/' + embed_id + '?autoplay=1'} frameBorder="0" allowFullScreen></iframe>; break; case 'facebook': html = <div className="fb-video" data-href={url} data-show-text="false" data-autoplay="true"></div>; break; case 'tumblr': html = <div dangerouslySetInnerHTML={{__html: embed_id.replace('<video', '<video controls style="width: 100%"')}}></div>; break; default: break; } this.setState({ embedHtml: html }); }; preventDefault(e) { e.preventDefault(); } render() { const {title, description, types, rate, hideLikeButton, fixedHeight, thumbnail, url, matching, strings} = this.props; const cardTitle = title ? title.length > 20 ? title.substr(0, 20) + '...' : title : strings.emptyTitle; const subTitle = description ? <div>{description.substr(0, 20)}{description.length > 20 ? '...' : ''}</div> : fixedHeight ? <div>&nbsp;</div> : ''; const imageClass = fixedHeight ? 'image fixed-max-height-image' : 'image'; const isImage = types.indexOf('Image') > -1; const defaultSrc = 'img/default-content-image.jpg'; let imgSrc = defaultSrc; if (thumbnail) { imgSrc = thumbnail; } else if (isImage) { imgSrc = url; } imgSrc = LinkImageService.getThumbnail(imgSrc, 'medium'); return ( <div className="card content-card"> {isImage ? <div className={"card-drop-down-menu"} onClick={this.onDropDown}> <span className="icon-angle-down"></span> </div> : <div className="card-header"> <div className={"card-drop-down-menu"} onClick={this.onDropDown}> <span className="icon-angle-down"></span> </div> <div className="card-title" onClick={this.handleClick}> <a href={url} onClick={this.preventDefault}> {cardTitle} </a> </div> <div className="card-sub-title" onClick={this.handleClick}> {subTitle} </div> </div> } <div className="card-icons" onClick={this.handleClick}> <CardIcons types={types}/> </div> <div className="card-content" onClick={this.handleClick}> <div className="card-content-inner"> {this.state.embedHtml ? this.state.embedHtml : <a href={url} onClick={this.preventDefault}> <div className={imageClass}> <Image src={imgSrc} defaultSrc={defaultSrc}/> </div> </a> } {!this.state.embedHtml && typeof matching !== 'undefined' ? <div className="matching"> <div className="matching-value">{strings.compatibility} {matching ? matching + '%' : '?'}</div> <ProgressBar percentage={matching}/> </div> : null } </div> </div> {!hideLikeButton ? <div className="card-footer"> <div className="like-button icon-wrapper" onClick={rate !== null ? this.onRate : null}> <span className={rate === null ? 'icon-spinner rotation-animation' : rate && rate !== -1 ? 'icon-star yellow' : 'icon-star'}></span> </div> <div className="icon-wrapper" onClick={this.onShare}> <span className="icon-share"></span> </div> </div> : '' } </div> ); } } CardContent.defaultProps = { strings: { like : 'Like', unlike : 'Remove like', share : 'Share', report : 'Report', cancel : 'Cancel', compatibility : 'Compatibility', emptyTitle : 'Title', copiedToClipboard: 'Copied to clipboard', shareError : 'An error occurred sharing the content', saving : 'Saving...', notInteresting : 'I’m not interested in this content', harmful : 'This content is abusive or harmful', spam : 'This content is spam', otherReasons : 'Other reasons', } };
src/svg-icons/action/pets.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPets = (props) => ( <SvgIcon {...props}> <circle cx="4.5" cy="9.5" r="2.5"/><circle cx="9" cy="5.5" r="2.5"/><circle cx="15" cy="5.5" r="2.5"/><circle cx="19.5" cy="9.5" r="2.5"/><path d="M17.34 14.86c-.87-1.02-1.6-1.89-2.48-2.91-.46-.54-1.05-1.08-1.75-1.32-.11-.04-.22-.07-.33-.09-.25-.04-.52-.04-.78-.04s-.53 0-.79.05c-.11.02-.22.05-.33.09-.7.24-1.28.78-1.75 1.32-.87 1.02-1.6 1.89-2.48 2.91-1.31 1.31-2.92 2.76-2.62 4.79.29 1.02 1.02 2.03 2.33 2.32.73.15 3.06-.44 5.54-.44h.18c2.48 0 4.81.58 5.54.44 1.31-.29 2.04-1.31 2.33-2.32.31-2.04-1.3-3.49-2.61-4.8z"/> </SvgIcon> ); ActionPets = pure(ActionPets); ActionPets.displayName = 'ActionPets'; export default ActionPets;
src/components/Chat/NotificationMessages/SkipMessage.js
u-wave/web
import React from 'react'; import PropTypes from 'prop-types'; import { useTranslator } from '@u-wave/react-translate'; import Username from '../../Username'; import UserNotificationMessage from './UserNotificationMessage'; const toUsername = (user) => ( <Username user={user} /> ); const getLangKey = (hasModerator, hasReason) => { if (hasReason) { return hasModerator ? 'chat.modSkipReason' : 'chat.selfSkipReason'; } return hasModerator ? 'chat.modSkip' : 'chat.selfSkip'; }; function SkipMessage({ user, moderator, reason, timestamp, }) { const { t } = useTranslator(); return ( <UserNotificationMessage type="skip" className="ChatMessage--skip" i18nKey={getLangKey(!!moderator, !!reason)} user={moderator ?? user} djName={toUsername(user)} reason={reason ? t(`booth.skip.reasons.${reason}`) : undefined} timestamp={timestamp} /> ); } SkipMessage.propTypes = { user: PropTypes.object.isRequired, moderator: PropTypes.object, timestamp: PropTypes.number.isRequired, reason: PropTypes.string, }; export default SkipMessage;
weather-app/src/App.js
plotly/academy
import React from 'react'; import './App.css'; import { connect } from 'react-redux'; import Plot from './Plot'; import { changeLocation, setSelectedDate, setSelectedTemp, fetchData } from './actions'; export class App extends React.Component { fetchData = (evt) => { evt.preventDefault(); var location = encodeURIComponent(this.props.redux.get('location')); var urlPrefix = 'http://api.openweathermap.org/data/2.5/forecast?q='; var urlSuffix = '&APPID=dbe69e56e7ee5f981d76c3e77bbb45c0&units=metric'; var url = urlPrefix + location + urlSuffix; this.props.dispatch(fetchData(url)); }; onPlotClick = (data) => { if (data.points) { this.props.dispatch(setSelectedDate(data.points[0].x)); this.props.dispatch(setSelectedTemp(data.points[0].y)) } }; changeLocation = (evt) => { this.props.dispatch(changeLocation(evt.target.value)); }; render() { var currentTemp = 'not loaded yet'; if (this.props.redux.getIn(['data', 'list'])) { currentTemp = this.props.redux.getIn(['data', 'list', '0', 'main', 'temp']); } return ( <div> <h1>Weather</h1> <form onSubmit={this.fetchData}> <label>I want to know the weather for <input placeholder={"City, Country"} type="text" value={this.props.redux.get('location')} onChange={this.changeLocation} /> </label> </form> {/* Render the current temperature and the forecast if we have data otherwise return null */} {(this.props.redux.getIn(['data', 'list'])) ? ( <div className="wrapper"> {/* Render the current temperature if no specific date is selected */} <p className="temp-wrapper"> <span className="temp"> { this.props.redux.getIn(['selected', 'temp']) ? this.props.redux.getIn(['selected', 'temp']) : currentTemp } </span> <span className="temp-symbol">°C</span> <span className="temp-date"> { this.props.redux.getIn(['selected', 'temp']) ? this.props.redux.getIn(['selected', 'date']) : ''} </span> </p> <h2>Forecast</h2> <Plot xData={this.props.redux.get('dates')} yData={this.props.redux.get('temps')} onPlotClick={this.onPlotClick} type="scatter" /> </div> ) : null} </div> ); } } // Since we want to have the entire state anyway, we can simply return it as is! function mapStateToProps(state) { return { redux: state }; } export default connect(mapStateToProps)(App);
app/HomeAutomation/components/Loading/Loading.js
tomatrocho/auto-door
import React from 'react'; import { Text, View, ActivityIndicator } from 'react-native'; import Style from './style'; export default class Loading extends React.Component { constructor(props) { super(props); } render() { return ( <View style = { Style.container }> <ActivityIndicator size = "large" /> <Text>{ this.props.text }</Text> </View> ); } }
src/components/app.js
JeremyWeisener/Test
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import axios from 'axios'; import CamperList from './camper_list.js'; export default class FetchComp extends Component { constructor(props) { super(props); this.state = { requestFailed: false, recentCampers: [], allTimeCampers: [], currentDisplay: 'recentCampers' } } componentWillMount() { axios.all([this.fetchRecentCampers(), this.fetchTopCampers()]) .then(axios.spread((recentCampers, allTimeCampers) => { this.setState({ recentCampers: recentCampers.data, allTimeCampers: allTimeCampers.data }); })); } fetchRecentCampers(){ return axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/recent'); } fetchTopCampers(){ return axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/alltime'); } changeDisplay(currentDisplay){ this.setState({ currentDisplay }); } render() { return( <div> <h2>{`Displaying the ${this.state.currentDisplay}`}</h2> <button onClick={() => this.changeDisplay('recentCampers')} className="btn btn-primary" > Recent Campers </button> <button onClick={() => this.changeDisplay('allTimeCampers')} className="btn btn-primary" > All Time Campers </button> <CamperList campers={this.state[this.state.currentDisplay]} /> </div> ); } }
packages/ringcentral-widgets-docs/src/app/pages/Components/SpinnerOverlay/index.js
ringcentral/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/SpinnerOverlay'; const SpinnerOverlayPage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="SpinnerOverlay" description={info.description} /> <CodeExample code={demoCode} title="SpinnerOverlay Example"> <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default SpinnerOverlayPage;
app/components/UploadButton/index.js
cerebral/cerebral-reference-app
import React from 'react'; import styles from './styles.css'; import ToolbarButton from 'common/components/ToolbarButton'; import icons from 'common/icons.css'; function UploadButton(props) { const className = styles.wrapper; return ( <div className={className}> <ToolbarButton disabled={props.disabled} icon={props.recorder.isUploading ? icons.loading : icons.uploadFile} onClick={() => props.onClick()}/> </div> ); } export default UploadButton;
src/components/Tag/index.js
andywillis/uws
// Dependencies import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; // Style import './style.css'; /** * @function Tag * @param {object} props Component properties * @return {jsx} Component */ const Tag = ({ txt }) => { return ( <Link to={{ pathname: `/tag/${txt}` }}> <li className="Tag">{txt}</li> </Link> ); }; export default Tag; // Function proptypes Tag.propTypes = { txt: PropTypes.string.isRequired };
src/containers/weather_list.js
gui-santos/exp-redux
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Chart from '../components/chart'; class WeatherList extends Component { renderWeather(cityData) { const name = cityData.city.name; const temps = cityData.list.map(weather => weather.main.temp); const pressures = cityData.list.map(weather => weather.main.pressure); const humidities = cityData.list.map(weather => weather.main.humidity); return ( <tr key={name}> <td>{name}</td> <td><Chart data={temps} color="orange" unit="K" /></td> <td><Chart data={pressures} color="green" unit="hPa" /></td> <td><Chart data={humidities} color="blue" unit="%" /></td> </tr> ); } render() { return ( <table className="table table-hover"> <thead> <tr> <th>City</th> <th>Temperature (K)</th> <th>Pressure (hPa)</th> <th>Humidity (%)</th> </tr> </thead> <tbody> {this.props.weather.map(this.renderWeather)} </tbody> </table> ); } } // getting the "global" state function mapStateToProps({ weather }) { //doing { weather } is the same as defining a const weather = state.weather return { weather };// in es6, this is the same as { weather: weather } } export default connect(mapStateToProps) (WeatherList);
java-script/12-webpack-demo/src/components/VideoPlayer.js
ruslan2k/public-files
import React, { Component } from 'react'; import videojs from 'video.js' class VideoPlayer extends Component { componentDidMount() { // instantiate Video.js this.player = videojs(this.videoNode, this.props, () => { console.log('onPlayerReady', this); }); } // destroy player on unmount componentwillUnmount() { if (this.player) { this.player.dispose(); } } // wrap the player in a div with a `data-vjs-player` attribute // so videojs won't create additional wrapper in the DOM // see https://github.com/videojs/video.js/pull/3856 render() { return ( <div> <div data-vjs-player> <video ref={ node => this.videoNode = node } className="video-js"></video> </div> </div> ) } } export default VideoPlayer;
src/components/ReplOutputChartViewer.js
princejwesley/Mancy
import React from 'react'; import _ from 'lodash'; import ReplCommon from '../common/ReplCommon'; import ReplOutputHTML from './ReplOutputHTML'; import c3 from 'c3'; export default class ReplOutputChartViewer extends React.Component { constructor(props) { super(props); this.state = { type: 'bar', flip: false, rotate: false, spline: false, chartCollapse: true, }; _.each([ 'generateChart', 'generateFlippedData', 'onToggleSpline', 'onToggleFlip', 'onToggleRotate', 'onClickBarChart', 'onClickLineChart', 'onClickAreaChart', 'onClickPieChart', 'isLineChart', 'isAreaChart', 'isSplineChart', 'generateColumnData', 'onToggleChartCollapse' ], (field) => { this[field] = this[field].bind(this); }); this.init(); } init() { this.chartViewable = this.props.chartViewable || ReplCommon.candidateForChart(this.props.chart); if(this.chartViewable) { this.id = `chart-${_.uniqueId()}-${Date.now()}`; let keys = _.keys(this.props.chart); this.columns = this.generateColumnData(this.props.chart); this.flippedData = this.generateFlippedData(this.columns); } } shouldComponentUpdate(nextProps, nextState) { return this.chartViewable && !(_.isEqual(nextState, this.state) && _.isEqual(nextProps, this.props)); } componentDidMount() { } onToggleChartCollapse() { this.setState({ chartCollapse: !this.state.chartCollapse }); } generateColumnData(source) { let size = _.reduce(source, (o, arr) => { return Math.max(o, arr.length); }, 0); let range = new Array(size).fill(0); return _.map(source, (v, k) => ([k].concat(v).concat(range)).slice(0, size + 1)); } generateFlippedData(cols) { let categories = _.reduce(cols, (o, col) => o.concat(col[0]), []); let range = _.range(cols[0].length - 1); let columns = _.reduce(range, (o, r) => { let record = _.reduce(cols, (out, col) => { out.push(col[r + 1] || 0); return out; }, [`${r}`]); o.push(record); return o; }, []); return { categories: categories, columns: columns }; } generateChart() { let obj = { bindto: `#${this.id}`, data: { columns: this.state.flip ? this.flippedData.columns : this.columns }, axis: { rotated: this.state.rotate }, zoom: { enabled: true } }; if(this.state.flip) { obj.axis.x = { type: 'category', categories: this.flippedData.categories } } if(this.state.type) { obj.data.type = this.state.type; } this.chart = c3.generate(obj); } onToggleSpline(e) { this.setState({ spline: !this.state.spline }); setTimeout(() => { if(this.isLineChart()) { this.onClickLineChart(); } else if(this.isAreaChart()) { this.onClickAreaChart(); } }, 100); } onToggleFlip(e) { this.setState({ flip: !this.state.flip }); setTimeout(() => this.generateChart(), 100); } onToggleRotate(e) { this.setState({ rotate: !this.state.rotate }); setTimeout(() => this.generateChart(), 100); } onChangeChartType(type) { this.setState({ type: type }); this.chart.transform(type); } onClickBarChart(e) { this.onChangeChartType('bar'); } onClickLineChart(e) { let type = this.state.spline ? 'spline' : 'line'; this.onChangeChartType(type); } onClickPieChart(e) { this.onChangeChartType('pie'); } onClickAreaChart(e) { let type = this.state.spline ? 'area-spline' : 'area'; this.onChangeChartType(type); } isLineChart() { return this.state.type === 'line' || this.state.type === 'spline'; } isAreaChart() { return this.state.type === 'area' || this.state.type === 'area-spline'; } isSplineChart() { return this.isLineChart() || this.isAreaChart(); } renderChart() { let barClazz = `fa fa-bar-chart ${this.state.type === 'bar' ? 'selected' : ''}`; let areaClazz = `fa fa-area-chart ${this.isAreaChart() ? 'selected' : ''}`; let lineClazz = `fa fa-line-chart ${this.isLineChart() ? 'selected' : ''}`; let pieClazz = `fa fa-pie-chart ${this.state.type === 'pie' ? 'selected' : ''}`; // render graph setTimeout(() => this.generateChart(), 100); return ( <span className='repl-output-data-chart-viewer'> <span id={this.id} className='chart-viewer'> </span> <span className='chart-viewer-preferences'> <span className='placeholder'></span> <i className={barClazz} title="Bar Chart" onClick={this.onClickBarChart}></i> <i className={lineClazz} title="Line Chart" onClick={this.onClickLineChart}></i> <i className={pieClazz} title="Pie Chart" onClick={this.onClickPieChart}></i> <i className={areaClazz} title="Area Chart" onClick={this.onClickAreaChart}></i> <span className="checkbox-group"> <input type="checkbox" name="flip" title='flip category and data' checked={this.state.flip} value="" onClick={this.onToggleFlip} /> flip </span> <span className="checkbox-group"> <input type="checkbox" title='rotate category and data' name="rotate" checked={this.state.rotate} value="" onClick={this.onToggleRotate} /> rotate </span> <span className="checkbox-group"> <input type="checkbox" title='spline curve' name="spline" disabled={!this.isSplineChart()} checked={this.state.spline} value="" onClick={this.onToggleSpline} /> spline </span> <span className='placeholder'></span> </span> </span> ); } render() { if(!this.chartViewable) { return null; } return ( this.state.chartCollapse ? <span className='repl-output-chart-viewer-container'> <i className='fa fa-plus-square-o' onClick={this.onToggleChartCollapse}></i> <span className='data-explorer-label'>Chart Viewer</span> </span> : <span className='repl-output-chart-viewer-container'> <i className='fa fa-minus-square-o' onClick={this.onToggleChartCollapse}></i> <span className='data-explorer-label'>Chart Viewer</span> {this.renderChart()} </span> ); } }
examples/huge-apps/routes/Course/routes/Assignments/components/Assignments.js
frankleng/react-router
import React from 'react'; class Assignments extends React.Component { render () { return ( <div> <h3>Assignments</h3> {this.props.children || <p>Choose an assignment from the sidebar.</p>} </div> ); } } export default Assignments;
src/giraffe-ui/footer/text.js
MoveOnOrg/mop-frontend
import React from 'react' import CaretRightSvg from '../svgs/caret-right.svg' export const Text = () => ( <div className='footer__text'> <div className='footer__text__item'> A joint website of MoveOn.org Civic Action and MoveOn.org Political Action. MoveOn.org Political Action and MoveOn.org Civic Action and are separate organizations. </div> <div className='footer__text__item'> <a href='http://civic.moveon.org/'>MoveOn.org Civic Action</a> is a 501(c)(4) organization which primarily focuses on nonpartisan education and advocacy on important national issues. <a href='https://civic.moveon.org/donatec4/creditcard.html?cpn_id=511' className='footer__text__cta' > Donate to MoveOn Civic Action <CaretRightSvg /> </a> </div> <div className='footer__text__item'> <a href='http://pol.moveon.org/'>MoveOn.org Political Action</a> is a federal political committee which primarily helps members elect candidates who reflect our values through a variety of activities aimed at influencing the outcome of the next election. <a href='https://act.moveon.org/donate/pac-donation' className='footer__text__cta' > Donate to MoveOn Political Action <CaretRightSvg /> </a> </div> </div> )
client/src/app/routes/smartadmin-intel/index.js
zraees/sms-project
import React from 'react'; import HtmlRender from '../../components/utils/HtmlRender' export default { path: 'smartadmin', component: require('../../components/common/Layout').default, childRoutes: [ { path: 'app-layouts', getComponent(nextState, cb){ System.import('html-loader?-attrs!./content/app-layouts.html').then((html)=> { cb(null, () => (<HtmlRender html={html}/>) ) }) } }, { path: 'skins', getComponent(nextState, cb){ System.import('html-loader?-attrs!./content/skins.html').then((html)=> { cb(null, () => (<HtmlRender html={html}/>) ) }) } }, ] };
src/components/Picker/PointerCircle.js
claus/react-dat-gui
import React from 'react'; const PointerCircle = () => <div className="pointer-circle" />; export default PointerCircle;
src/svg-icons/social/poll.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPoll = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z"/> </SvgIcon> ); SocialPoll = pure(SocialPoll); SocialPoll.displayName = 'SocialPoll'; SocialPoll.muiName = 'SvgIcon'; export default SocialPoll;
uiexplorer/examples/Carousel.js
tipsi/tipsi-ui-kit
import React from 'react' import { View, Text } from 'react-native' import Icon from 'react-native-vector-icons/FontAwesome' import register from '../core/utils/register' import { Carousel } from '../../src' /* eslint react/prop-types: 0 */ const Wrapper = ({ children }) => ( <View style={{ borderRadius: 5, backgroundColor: '#f3f5f7' }}> {children} </View> ) const Spacer = ({ icon, title }) => ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', width: 100, height: 50, }}> {icon && <Icon name={icon} size={35} />} {title && <Text>{title}</Text>} </View> ) const Separator = () => ( <View style={{ height: 1, marginHorizontal: 5, backgroundColor: '#c7d1dc' }} /> ) register.addExample({ type: 'components', title: '<Carousel />', description: 'Carousel component', examples: [{ title: 'Default', description: 'Use Carousel as contaner for Carousel.Item`s. ' + 'You can pass your own content as children in Carousel.Item.', render: () => ( <Wrapper> <Carousel> <Carousel.Item> <Spacer icon="facebook" /> <Separator /> <Spacer title="Facebook" /> </Carousel.Item> <Carousel.Item> <Spacer icon="twitter" /> <Separator /> <Spacer title="Twitter" /> </Carousel.Item> <Carousel.Item> <Spacer icon="instagram" /> <Separator /> <Spacer title="Instagram" /> </Carousel.Item> <Carousel.Item> <Spacer icon="youtube" /> <Separator /> <Spacer title="YouTube" /> </Carousel.Item> <Carousel.Item> <Spacer icon="tumblr" /> <Separator /> <Spacer title="Tumblr" /> </Carousel.Item> </Carousel> </Wrapper> ), }, { title: 'Active', description: 'Carousel.Item Prop: active (Boolean)', render: () => ( <Wrapper> <Carousel> <Carousel.Item active> <Spacer icon="facebook" /> <Separator /> <Spacer title="Facebook" /> </Carousel.Item> <Carousel.Item> <Spacer icon="twitter" /> <Separator /> <Spacer title="Twitter" /> </Carousel.Item> <Carousel.Item active> <Spacer icon="instagram" /> <Separator /> <Spacer title="Instagram" /> </Carousel.Item> <Carousel.Item> <Spacer icon="youtube" /> <Separator /> <Spacer title="YouTube" /> </Carousel.Item> <Carousel.Item> <Spacer icon="tumblr" /> <Separator /> <Spacer title="Tumblr" /> </Carousel.Item> </Carousel> </Wrapper> ), }, { title: 'Handle Remove', description: 'Carousel.Item Prop: onRemove (Function)', render: ({ action }) => ( <Wrapper> <Carousel> <Carousel.Item onRemove={action('onRemove: facebook')}> <Spacer icon="facebook" /> <Separator /> <Spacer title="Facebook" /> </Carousel.Item> <Carousel.Item onRemove={action('onRemove: twitter')}> <Spacer icon="twitter" /> <Separator /> <Spacer title="Twitter" /> </Carousel.Item> <Carousel.Item onRemove={action('onRemove: instagram')}> <Spacer icon="instagram" /> <Separator /> <Spacer title="Instagram" /> </Carousel.Item> <Carousel.Item onRemove={action('onRemove: youtube')}> <Spacer icon="youtube" /> <Separator /> <Spacer title="YouTube" /> </Carousel.Item> <Carousel.Item onRemove={action('onRemove: tumblr')}> <Spacer icon="tumblr" /> <Separator /> <Spacer title="Tumblr" /> </Carousel.Item> </Carousel> </Wrapper> ), }, { title: 'Spacer', description: 'Carousel Prop: spacer (Number), space between last item and right side.', render: () => ( <Wrapper> <Carousel spacer={200}> <Carousel.Item> <Spacer icon="facebook" /> <Separator /> <Spacer title="Facebook" /> </Carousel.Item> <Carousel.Item> <Spacer icon="twitter" /> <Separator /> <Spacer title="Twitter" /> </Carousel.Item> <Carousel.Item> <Spacer icon="instagram" /> <Separator /> <Spacer title="Instagram" /> </Carousel.Item> <Carousel.Item> <Spacer icon="youtube" /> <Separator /> <Spacer title="YouTube" /> </Carousel.Item> <Carousel.Item> <Spacer icon="tumblr" /> <Separator /> <Spacer title="Tumblr" /> </Carousel.Item> </Carousel> </Wrapper> ), }, { title: 'Active and Remove', description: 'Press on item to set active or press on remove to remove item', state: { active: [], items: [{ icon: 'facebook', name: 'Facebook', }, { icon: 'twitter', name: 'Twitter', }, { icon: 'instagram', name: 'Instagram', }, { icon: 'youtube', name: 'YouTube', }, { icon: 'tumblr', name: 'Tumblr', }], }, render: ({ state, setState }) => { const { active, items } = state const isActive = name => active.includes(name) const onPress = name => () => { const nextActive = isActive(name) ? active.filter(item => item !== name) : [...active, name] setState({ active: nextActive }) } const onRemove = name => () => { const nextItems = items.filter(item => item.name !== name) const nextActive = active.filter(item => item !== name) setState({ items: nextItems, active: nextActive }) } return ( <Wrapper> <Carousel spacer={200}> {items.map(item => ( <Carousel.Item key={item.name} active={isActive(item.name)} onPress={onPress(item.name)} onRemove={onRemove(item.name)}> <Spacer icon={item.icon} /> <Separator /> <Spacer title={item.name} /> </Carousel.Item> ))} </Carousel> </Wrapper> ) }, }], })
src/components/views/SmartForm.js
huang6349/react-dva
import React, { Component } from 'react'; import { Form, Input, Radio, Select, Switch, DatePicker, } from 'antd'; import PropTypes from 'prop-types'; import styles from './SmartForm.css'; export const ItemType = { TEXT: 'text', PASSWORD: 'password', RADIO: 'radio', TEXTAREA: 'textarea', SELECT: 'select', SWITCH: 'switch', DATEPICKER: 'DatePicker', MONTHPICKER: 'MonthPicker', RANGEPICKER: 'RangePicker', }; class SmartForm extends React.Component { static propTypes = { /** 表单对象 */ form: PropTypes.object.isRequired, /** 表单序列化模式 */ schema: PropTypes.shape({ /** 表单列的标识 */ key: PropTypes.string.isRequired, /** 表单列的名称 */ label: PropTypes.string.isRequired, /** 表单列的提示信息 */ placeholder: PropTypes.string, /** 表单列的值 */ value: PropTypes.any, /** 表单列的验证规则 */ rules: PropTypes.array, /** 表单列的类型 */ itemType: PropTypes.string, /** 表单列为“radio”、“select”的选项 */ options: PropTypes.arrayOf(PropTypes.shape({ /** 选项 */ label: PropTypes.any.isRequired, /** 值 */ value: PropTypes.any.isRequired, })), /** 表单列为开关时的显示选项['开','关'] */ switchLabel: PropTypes.arrayOf(PropTypes.string), /** 表单列为日期选项 */ moment: PropTypes.any, /** 表单列是否禁用 */ disabled: PropTypes.bool, }).isRequired, labelCol: PropTypes.object, wrapperCol: PropTypes.object, } static defaultProps = { labelCol: { span: 6, }, wrapperCol: { span: 6, }, } state = { schema: { rules: [], itemType: ItemType.TEXT, switchLabel: [ '开', '关', ], }, } constructor(props) { super(props); this.getFieldDecorator = this.props.form.getFieldDecorator; this.schema = Object.assign({}, this.state.schema, this.props.schema); } /** * 表单元素包装域 * * @param {*} formItem * @param {*} field */ wrapper(formItem, field) { return <Form.Item key={field.key} label={field.label} labelCol={this.props.labelCol} wrapperCol={this.props.wrapperCol} children={formItem} />; } /** * 将schema转换成错误的提示 * * @param {*} field */ transformNormal(field) { return this.wrapper(<span>请指定正确的itemType类型</span>, Object.assign({}, field, { label: '错误提示' })); } /** * 将schema转换成普通文本框 * * @param {*} field */ transformInput(field) { return this.wrapper(this.getFieldDecorator(field.key, { initialValue: field.value ? (field.value).toString() : field.value, rules: field.rules, })(<Input type={field.itemType} placeholder={field.placeholder} />), field); } /** * 将schema转换成文本域 * * @param {*} field */ transformTextArea(field) { return this.wrapper(this.getFieldDecorator(field.key, { initialValue: field.value ? (field.value).toString() : field.value, rules: field.rules, })(<Input.TextArea placeholder={field.placeholder} autosize={{ minRows: 4, maxRows: 6 }} />), field); } /** * 将schema转换成单选框 * * @param {*} field */ transformRadio(field) { return this.wrapper(this.getFieldDecorator(field.key, { valuePropName: 'checked', rules: field.rules, })(<Radio.Group defaultValue={field.value}>{field.options.map((item) => <Radio key={`radio_${item.value}`} value={item.value}>{item.label}</Radio>)}</Radio.Group>), field); } /** * 将schema转换成选择器 * * @param {*} field */ transformSelect(field) { return this.wrapper(this.getFieldDecorator(field.key, { initialValue: field.value, rules: field.rules, })(<Select allowClear={true} placeholder={field.placeholder} >{field.options.map((item) => <Select.Option key={`select_${item.value}`} value={item.value}>{item.label}</Select.Option>)}</Select>), field); } /** * 将schema转换成开关 * * @param {*} field */ transformSwitch(field) { return this.wrapper(this.getFieldDecorator(field.key, { valuePropName: 'checked', initialValue: field.value, rules: field.rules, })(<Switch checkedChildren={field.switchLabel[0]} unCheckedChildren={field.switchLabel[1]} />), field); } /** * 将schema转换成日期选择框 * * @param {*} field */ transformDatePicker(field) { return this.wrapper(this.getFieldDecorator(field.key, { initialValue: field.value, rules: field.rules, })(<DatePicker format='YYYY-MM-DD' />), field); } /** * 将schema转换成日期选择框[年月] * * @param {*} field */ transformMonthPicker(field) { return this.wrapper(this.getFieldDecorator(field.key, { initialValue: field.value, rules: field.rules, })(<DatePicker.MonthPicker format='YYYY-MM' />), field); } /** * 将schema转换成日期选择框[范围] * * @param {*} field */ transformRangePicker(field) { return this.wrapper(this.getFieldDecorator(field.key, { initialValue: field.value, rules: field.rules, })(<DatePicker.RangePicker format='YYYY-MM-DD' />), field); } render() { switch (this.schema.itemType) { case ItemType.TEXT: return this.transformInput.bind(this)(this.schema); break; case ItemType.PASSWORD: return this.transformInput.bind(this)(this.schema); break; case ItemType.TEXTAREA: return this.transformTextArea.bind(this)(this.schema); break; case ItemType.RADIO: return this.transformRadio.bind(this)(this.schema); break; case ItemType.SELECT: return this.transformSelect.bind(this)(this.schema); break; case ItemType.SWITCH: return this.transformSwitch.bind(this)(this.schema); break; case ItemType.DATEPICKER: return this.transformDatePicker.bind(this)(this.schema); break; case ItemType.MONTHPICKER: return this.transformMonthPicker.bind(this)(this.schema); break; case ItemType.RANGEPICKER: return this.transformRangePicker.bind(this)(this.schema); break; default: return this.transformNormal.bind(this)(this.schema); } } } export default SmartForm;
app/containers/Login/LoginContainer.js
klpdotorg/tada-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { LoginPageWrapper } from '../../components/Login'; import { sendLoginToServer, fetchStates, selectState } from '../../actions/'; class Login extends Component { constructor(prop) { super(prop); this.handleSubmit = this.handleSubmit.bind(this); } componentDidMount() { this.props.fetchStates(); } handleSubmit(event) { event.preventDefault(); const email = this.email.value; const pass = this.pass.value; this.props.sendLoginToServer(email, pass); } render() { const { loginIn, error, states, selectedState } = this.props; return ( <LoginPageWrapper error={error}> <div className="row"> <div className="col-sm-12 col-md-10 col-md-offset-1"> <form id="loginForm"> <div className="form-group input-group"> <span className="input-group-addon"> <i className="glyphicon glyphicon-user" /> </span> <input ref={(input) => { this.email = input; }} className="form-control" type="text" name="email" placeholder="email id or username" defaultValue="" /> </div> <div className="form-group input-group"> <span className="input-group-addon"> <i className="glyphicon glyphicon-lock" /> </span> <input ref={(input) => { this.pass = input; }} className="form-control" type="password" name="password" placeholder="(HINT: tada)" /> </div> <div className="form-group input-group"> <span className="input-group-addon"> <i className="glyphicon glyphicon-globe" /> </span> <select className="form-control" id="sel1" onChange={(e) => { this.props.selectState(e.target.value); }} value={selectedState} > {states.map((state) => { return ( <option key={state.char_id} value={state.char_id}> {state.state_name} </option> ); })} </select> </div> {loginIn ? ( <div className="text-center"> <i className="fa fa-cog fa-spin fa-lg fa-fw" /> <span>Logging...</span> </div> ) : ( <div /> )} <div className="form-group text-center"> <button type="submit" className="btn btn-primary" onClick={this.handleSubmit}> Submit </button> </div> <div className="form-group text-center"> <Link to="/password/reset">Forgot Password</Link>&nbsp;|&nbsp;<a href="mailto:dev@klp.org.in">Support</a> </div> </form> </div> </div> </LoginPageWrapper> ); } } const mapStateToProps = (state) => { const { selectedState, states, loading } = state.states; return { error: state.login.error, loginIn: state.login.isLoggingIn, states, selectedState, loading, }; }; Login.propTypes = { error: PropTypes.bool.isRequired, loginIn: PropTypes.bool, sendLoginToServer: PropTypes.func, selectedState: PropTypes.string, states: PropTypes.array, fetchStates: PropTypes.func, selectState: PropTypes.func, }; const LoginContainer = connect(mapStateToProps, { sendLoginToServer, fetchStates, selectState, })(Login); export default LoginContainer;
src/components/Tagline/Tagline.js
kdrabek/exchange_rates_frontend
import React from 'react'; import { Row, Col, PageHeader } from 'react-bootstrap'; const Tagline = (props) => { return ( <Row> <Col xs={12} md={12}> <PageHeader> Kursy walut NBP <br /><small>Według tabeli A</small> </PageHeader> </Col> </Row> ); }; export default Tagline;
components/playerlist/BarList.js
nvbf/pepper
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Bar from './Bar'; const Container = styled.div` width: 600px; min-height: 48px; `; function BarList(props) { return ( <Container> {props.isShowing && props.team.players.map((player, index) => (<Bar key={player.number} animDelay={index * 100} number={player.number} name={player.name} position={player.position} active={index === props.selectedIndex} />), )} </Container> ); } BarList.propTypes = { isShowing: PropTypes.bool.isRequired, selectedIndex: PropTypes.number.isRequired, team: PropTypes.shape({ players: PropTypes.array, }).isRequired, }; export default BarList;
release/darwin-x64/shokushu-darwin-x64/shokushu.app/Contents/Resources/app/app/components/Sidebar.js
y-takey/shokushu
import _ from 'lodash'; import React, { Component } from 'react'; import LeftNav from 'material-ui/lib/left-nav'; import MenuItem from 'material-ui/lib/menus/menu-item'; import Divider from 'material-ui/lib/divider'; import FontIcon from 'material-ui/lib/font-icon'; import Color from 'material-ui/lib/styles/colors' import FavStars from './FavStars'; const NavStyle = { backgroundColor: Color.lightBlue900, padding: 10 } const headerStyle = { color: Color.lightBlue300 } const itemStyle = { color: Color.lightBlue50, lineHeight: "30px", paddingLeft: 10 } const budgeStyle = { color: Color.white, margin: 0, marginTop: 3, backgroundColor: Color.lightBlue800, textAlign: "center", borderRadius: 8 } const selectedItemStyle = _.assign({}, itemStyle, { backgroundColor: Color.lightBlue800 }) export default class Sidebar extends Component { sortItem() { let sorter = this.props.sorter; return ["name", "fav", "registered_at"].map((column) => { let icon = null; let style = itemStyle; if (sorter.colName === column) { style = selectedItemStyle icon = sorter.order === "asc" ? "caret-up" : "caret-down" icon = <i className={`fa fa-${icon}`} /> } let item = <span>{column} {icon}</span> return <MenuItem primaryText={item} innerDivStyle={ style } key={column} value={column} onClick={ this.props.sortBy.bind(null, column) } /> }) } filterItem() { const { filter, filterBy, tags } = this.props; let items = [] let favstar = <FavStars fav={filter.fav} onClick={ (i) => filterBy("fav", i + 1) } /> items.push(<MenuItem key="_filter" children={favstar} innerDivStyle={ itemStyle } />) return items.concat(_.map(tags, (num, tag) => { let style = itemStyle; if (filter.tag === tag) { style = selectedItemStyle } return <MenuItem key={tag} primaryText={`#${tag}`} innerDivStyle={ style } rightIcon={<span style={ budgeStyle }>{ num }</span>} onClick={ filterBy.bind(null, "tag", tag) } /> })) } render() { return ( <LeftNav open={true} width={this.props.width} style={NavStyle} > <span style={headerStyle}><i className="fa fa-sort-amount-asc" /> SORT</span> { this.sortItem() } <Divider style={ {marginTop: 10, marginBottom: 10} } /> <span style={headerStyle}><i className="fa fa-filter" /> FILTER</span> { this.filterItem() } </LeftNav> ); } }
app/components/service/ServiceDetail.js
jendela/jendela
import React from 'react' import Parse from 'parse' import { Link } from 'react-router' import Loading from '../template/Loading' import ServiceSummary from './ServiceSummary' import ServiceDetailRow from './ServiceDetailRow' const styles = { content: { paddingTop: "25px", paddingBottom: "25px" } } class ServiceDetail extends React.Component { constructor(props) { super(props) this.state = { "services": [] } this.componentWillMount.bind(this); } componentWillMount() { new Parse.Query('Service').get(this.props.params.serviceId).then((service) => { this.setState({"service": service}); }) } render() { const { service } = this.state if (!service) { return <Loading /> } const fee = formatFee(service.get("fee")) const requirement = service.get("procedures").requirement const steps = service.get("procedures").steps return ( <div> <ServiceSummary iconPath={`img/${service.get('iconPath')}`} title={service.get("name")} summary={service.get("description")} /> <div style={styles.content}> <ServiceDetailRow title={"Lokasi Pembuatan"} > { service.get("location") } </ServiceDetailRow> <ServiceDetailRow title={"Biaya"} > { (fee.length <= 0) ? "-" : fee } </ServiceDetailRow> { (requirement.length <= 0) ? undefined : <ServiceDetailRow title={"Persyaratan"} > { requirement.map((e)=> <li>{e}</li> ) } </ServiceDetailRow> } { (steps.length <= 0) ? undefined : <ServiceDetailRow title={"Prosedur"} > { steps.map((e)=> <li>{e}</li> ) } </ServiceDetailRow> } <ServiceDetailRow title={"Durasi Pembuatan"} > { service.get("duration") } </ServiceDetailRow> </div> </div> ) } } ServiceDetail.defaultProps = { params: { "serviceId": undefined } } function formatFee(inputFee) { if (Object.keys(inputFee).length == 1) return getPriceString(inputFee[1]) else { let fee = []; for (var temp in inputFee) { fee.push(<div><strong>{temp}</strong>: {getPriceString(inputFee[temp])}</div>); } return fee } } function getPriceString(price) { return price ? "Rp. " + price : "GRATIS"; } export default ServiceDetail
src/components/Todos/components/TodoFetchError/index.js
dominicfallows/todo-app-react-redux-aws
import React from 'react'; import PropTypes from 'prop-types' const TodoFetchError = ({ message, onRetry }) => ( <div> <p>Could not fetch todos. {message}</p> <button onClick={onRetry}>Retry</button> </div> ); TodoFetchError.propTypes = { message: PropTypes.string.isRequired, onRetry: PropTypes.func.isRequired, }; export default TodoFetchError;
app/javascript/mastodon/features/following/index.js
theoria24/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import LoadingIndicator from '../../components/loading_indicator'; import { lookupAccount, fetchAccount, fetchFollowing, expandFollowing, } from '../../actions/accounts'; import { FormattedMessage } from 'react-intl'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import HeaderContainer from '../account_timeline/containers/header_container'; import ColumnBackButton from '../../components/column_back_button'; import ScrollableList from '../../components/scrollable_list'; import MissingIndicator from 'mastodon/components/missing_indicator'; import TimelineHint from 'mastodon/components/timeline_hint'; const mapStateToProps = (state, { params: { acct, id } }) => { const accountId = id || state.getIn(['accounts_map', acct]); if (!accountId) { return { isLoading: true, }; } return { accountId, remote: !!(state.getIn(['accounts', accountId, 'acct']) !== state.getIn(['accounts', accountId, 'username'])), remoteUrl: state.getIn(['accounts', accountId, 'url']), isAccount: !!state.getIn(['accounts', accountId]), accountIds: state.getIn(['user_lists', 'following', accountId, 'items']), hasMore: !!state.getIn(['user_lists', 'following', accountId, 'next']), isLoading: state.getIn(['user_lists', 'following', accountId, 'isLoading'], true), blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false), }; }; const RemoteHint = ({ url }) => ( <TimelineHint url={url} resource={<FormattedMessage id='timeline_hint.resources.follows' defaultMessage='Follows' />} /> ); RemoteHint.propTypes = { url: PropTypes.string.isRequired, }; export default @connect(mapStateToProps) class Following extends ImmutablePureComponent { static propTypes = { params: PropTypes.shape({ acct: PropTypes.string, id: PropTypes.string, }).isRequired, accountId: PropTypes.string, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, hasMore: PropTypes.bool, isLoading: PropTypes.bool, blockedBy: PropTypes.bool, isAccount: PropTypes.bool, remote: PropTypes.bool, remoteUrl: PropTypes.string, multiColumn: PropTypes.bool, }; _load () { const { accountId, isAccount, dispatch } = this.props; if (!isAccount) dispatch(fetchAccount(accountId)); dispatch(fetchFollowing(accountId)); } componentDidMount () { const { params: { acct }, accountId, dispatch } = this.props; if (accountId) { this._load(); } else { dispatch(lookupAccount(acct)); } } componentDidUpdate (prevProps) { const { params: { acct }, accountId, dispatch } = this.props; if (prevProps.accountId !== accountId && accountId) { this._load(); } else if (prevProps.params.acct !== acct) { dispatch(lookupAccount(acct)); } } handleLoadMore = debounce(() => { this.props.dispatch(expandFollowing(this.props.accountId)); }, 300, { leading: true }); render () { const { accountIds, hasMore, blockedBy, isAccount, multiColumn, isLoading, remote, remoteUrl } = this.props; if (!isAccount) { return ( <Column> <MissingIndicator /> </Column> ); } if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } let emptyMessage; if (blockedBy) { emptyMessage = <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' />; } else if (remote && accountIds.isEmpty()) { emptyMessage = <RemoteHint url={remoteUrl} />; } else { emptyMessage = <FormattedMessage id='account.follows.empty' defaultMessage="This user doesn't follow anyone yet." />; } const remoteMessage = remote ? <RemoteHint url={remoteUrl} /> : null; return ( <Column> <ColumnBackButton multiColumn={multiColumn} /> <ScrollableList scrollKey='following' hasMore={hasMore} isLoading={isLoading} onLoadMore={this.handleLoadMore} prepend={<HeaderContainer accountId={this.props.accountId} hideTabs />} alwaysPrepend append={remoteMessage} emptyMessage={emptyMessage} bindToDocument={!multiColumn} > {blockedBy ? [] : accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />, )} </ScrollableList> </Column> ); } }
components/Footer.js
jkupcho/eri-blog
import React from 'react' import Title from './Title' import Icon from './Icon' import ContactForm from '../containers/ContactForm' export default () => { return ( <footer className="footer" style={{borderTop: '1px solid #cfcfcf'}}> <div className="container"> <div className="content has-text-centered"> <Title size={1}>Contact Us</Title> <Title isSubtitle={true} size={5}>How to get a hold of us</Title> </div> <div className="columns"> <div className="column is-one-third"> <div className="columns"> <div className="column is-one-quarter has-text-right"> <Icon name="map-marker" /> </div> <div className="column"> <address> Enhanced Interiors Remodeling<br/> 1505 Sherwood Rd.<br/> Shoreview MN, 55126<br/> </address> </div> </div> <div className="columns"> <div className="column is-one-quarter has-text-right"> <Icon name="phone" /> </div> <div className="column"> <a href="tel:651-786-6607">651-786-6607</a> </div> </div> </div> <div className="column"> <ContactForm /> </div> </div> </div> </footer> ); }
client/portfolio2017/src/Components/AppSnackBar/AppSnackBar.js
corrortiz/portafolio2017
import React, { Component } from 'react'; import PropTypes from 'prop-types'; //MUI Components import Button from 'material-ui/Button'; import Snackbar from 'material-ui/Snackbar'; import Slide from 'material-ui/transitions/Slide'; import { withStyles } from 'material-ui/styles'; //HOC for connect to Redux import GlobalsConnect from '../../HOC/GlobalsConnect/GlobalsConnect'; //locale neds of global connect to work import { lenguajeSelector } from '../../Store/Actions/globals'; import { Close } from '../../Assets/diccionary'; //Func for deside te type of transiton to the sbackbar function TypeOfTransition(props) { return <Slide direction="up" {...props} />; } //CSS in JS style const styles = theme => ({ snackbar: { margin: theme.spacing.unit } }); /** * SnackBar component with auto hide and animation */ export class AppSnackBar extends Component { state = { transition: TypeOfTransition }; handleClick = transition => () => { this.props.showSnackBar(); this.setState({ transition }); }; handleClose = () => { this.props.showSnackBar(); }; render() { const { transition } = this.state; const { openSnackBar, messageSnackBar, lenguaje } = this.props.globals; const { classes } = this.props; return ( <div className="footer__appSnackBar"> {/*This button is necesary for adding the custom transition and is hidden with css*/} <Button className="hide" onClick={this.handleClick(TypeOfTransition)}> Down </Button> <Snackbar open={openSnackBar} onClose={this.handleClose} autoHideDuration={3500} transition={transition} className={classes.snackbar} SnackbarContentProps={{ 'aria-describedby': 'message-id' }} message={<span id="message-id">{messageSnackBar}</span>} action={[ <Button key="close" aria-label="Close" color="secondary" onClick={this.handleClose} > {lenguajeSelector(lenguaje, Close)} </Button> ]} /> </div> ); } } AppSnackBar.propTypes = { globals: PropTypes.shape({ openSnackBar: PropTypes.bool.isRequired, messageSnackBar: PropTypes.string.isRequired, lenguaje: PropTypes.string.isRequired }) }; AppSnackBar = withStyles(styles)(AppSnackBar); export default GlobalsConnect(AppSnackBar);
src/svg-icons/image/crop-16-9.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCrop169 = (props) => ( <SvgIcon {...props}> <path d="M19 6H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H5V8h14v8z"/> </SvgIcon> ); ImageCrop169 = pure(ImageCrop169); ImageCrop169.displayName = 'ImageCrop169'; ImageCrop169.muiName = 'SvgIcon'; export default ImageCrop169;
src/client/components/CircleImageWidget/CircleImageWidget.js
trippian/trippian
import log from '../../log' import React from 'react' import { Link } from 'react-router' import { CircleImageWidget as appConfig } from '../../config/appConfig' const renderImage = (imageSrc, link, title) => { const imageHTML = <img src={imageSrc} alt={title} /> if (link) { return ( <Link to={link}>{imageHTML}</Link> ) } return imageHTML } const CircleImageWidget = ({ link = appConfig.link, imageSrc = appConfig.imageSrc, title = appConfig.imageAlt }) => { log.info('--inside CircleImageWidget', link, imageSrc, title) return ( <div className="avatar circle-image"> {renderImage(imageSrc, link, title)} </div> ) } CircleImageWidget.displayName = 'CircleImageWidget' export default CircleImageWidget
src/svg-icons/device/signal-wifi-3-bar-lock.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalWifi3BarLock = (props) => ( <SvgIcon {...props}> <path opacity=".3" d="M12 3C5.3 3 .8 6.7.4 7l3.2 3.9L12 21.5l3.5-4.3v-2.6c0-2.2 1.4-4 3.3-4.7.3-.1.5-.2.8-.2.3-.1.6-.1.9-.1.4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4z"/><path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16zm-10 5.5l3.5-4.3v-2.6c0-2.2 1.4-4 3.3-4.7C17.3 9 14.9 8 12 8c-4.8 0-8 2.6-8.5 2.9"/> </SvgIcon> ); DeviceSignalWifi3BarLock = pure(DeviceSignalWifi3BarLock); DeviceSignalWifi3BarLock.displayName = 'DeviceSignalWifi3BarLock'; DeviceSignalWifi3BarLock.muiName = 'SvgIcon'; export default DeviceSignalWifi3BarLock;
node_modules/laravel-elixir/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
Jerrrrry/gxw
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/components/AdminPage.js
OR13/car2go
import React from 'react' import { Card, CardTitle, CardText } from 'material-ui/Card' import Page from 'layouts/Page' import MeshPointTableContainer from 'containers/MeshPointTableContainer' export default class AdminPage extends React.Component { render() { return ( <Page renderParticles={true}> <MeshPointTableContainer /> </Page> ) } }
node_modules/react-bootstrap/es/utils/ValidComponentChildren.js
superKaigon/TheCave
// TODO: This module should be ElementChildren, and should use named exports. import React from 'react'; /** * Iterates through children that are typically specified as `props.children`, * but only maps over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @return {object} Object containing the ordered map of results. */ function map(children, func, context) { var index = 0; return React.Children.map(children, function (child) { if (!React.isValidElement(child)) { return child; } return func.call(context, child, index++); }); } /** * Iterates through children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for context. */ function forEach(children, func, context) { var index = 0; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } func.call(context, child, index++); }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function count(children) { var result = 0; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } ++result; }); return result; } /** * Finds children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @returns {array} of children that meet the func return statement */ function filter(children, func, context) { var index = 0; var result = []; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result.push(child); } }); return result; } function find(children, func, context) { var index = 0; var result = undefined; React.Children.forEach(children, function (child) { if (result) { return; } if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = child; } }); return result; } function every(children, func, context) { var index = 0; var result = true; React.Children.forEach(children, function (child) { if (!result) { return; } if (!React.isValidElement(child)) { return; } if (!func.call(context, child, index++)) { result = false; } }); return result; } function some(children, func, context) { var index = 0; var result = false; React.Children.forEach(children, function (child) { if (result) { return; } if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = true; } }); return result; } function toArray(children) { var result = []; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } result.push(child); }); return result; } export default { map: map, forEach: forEach, count: count, find: find, filter: filter, every: every, some: some, toArray: toArray };
src/routes/RequestPayment/components/CostsForSpecialist.js
vijayasankar/ML2.0
import Col from 'react-bootstrap/lib/Col' import DollarTextField from 'components/DollarTextWithTwoDecimalsField' import RadioGroupField from 'components/RadioGroupField' import React from 'react' import Row from 'react-bootstrap/lib/Row' import TypeaheadField from 'components/TypeaheadField' import classnames from 'classnames' import { Field, FieldArray, arrayRemoveAll, reduxForm } from 'redux-form' import { calculateTotalIncludingGst, calculateGst, roundTwoDecimal } from 'utils/helpers' export class CostsForSpecialist extends React.Component { constructor (props) { super(props) this.renderOtherCosts = this.renderOtherCosts.bind(this) this.renderOtherProcedures = this.renderOtherProcedures.bind(this) this.state = { otherCosts: [], otherProcedures: [] } } componentDidMount () { this.props.change('location', 'NotApplicable') this.props.loadRequestPaymentCostList() } renderOtherCosts ({ fields, meta: { touched, error, submitFailed }, ...rest }) { return ( <div> { fields.map((member, index) => ( <div key={index}> <Row> <Col xs={12} md={6}> <span className={`${this.props.cssName}-label`}> {`${this.state.otherCosts[index].key}`} </span> </Col> <Col xs={12} md={3}> <div className={`${this.props.cssName}-form-group`}> <div className={classnames( `${this.props.cssName}-form-group-trigger`, 'form-link-icon', 'is-remove' )} title='Remove' onClick={(event) => { this.setState({ otherCosts: [ ...this.state.otherCosts.slice(0, index), ...this.state.otherCosts.slice(index + 1) ] }) return fields.remove(index) }} /> </div> </Col> <Col xs={12} md={3}> <DollarTextField cssName={this.props.cssName} fieldName='otherCost' member={member} name='other-cost' placeholderText='$ 0.00' /> </Col> </Row> <hr className='form-section-repeat-divider' /> </div> ))} <Row className='pb-4'> <Col xs={12} md={6}> <div className={classnames( 'select-wrapper', `${this.props.cssName}-select-wrapper`, 'is-cost' )} > <select value={`${this.state.otherCosts}`} onChange={(event) => { this.setState({ otherCosts: [...this.state.otherCosts, { key: event.target.options[event.target.selectedIndex].text, claimCostTypeId: event.target.value }] }) return fields.push({ // id: this.state.otherCosts.length, key: event.target.options[event.target.selectedIndex].text, claimCostTypeId: event.target.value }) }} > <option value=''>Add another cost</option> { this.props.list.length > 0 && this.props.list.map((item, index) => { return ( <option key={item.id} value={item.id}>{item.name}</option> ) }) } </select> </div> {(touched || submitFailed) && error && <span>{error}</span>} </Col> </Row> </div> ) } renderOtherProcedures ({ fields, meta: { touched, error, submitFailed } }) { console.log( 'renderOtherProcedures', this.state, (this.state.otherProcedures[0] && this.state.otherProcedures[0].name) || '' ) return ( <div> { fields.map((member, index) => { const aRow = fields.get(index) console.log('##### ', index, aRow) /* deal with other procedure field */ const currentProcedure = aRow.otherProcedure console.log('##### currentProcedure', currentProcedure) const currentProcedureOpts = {} if (currentProcedure && currentProcedure.length === 1) { currentProcedureOpts['default'] = currentProcedure } this.procedureElement || (this.procedureElement = []) if (this.procedureElement[index]) { console.log('~~~~~', `Other Procedure ${index + 1}`, this.procedureElement[index]) } /* deal with specialist field */ const currentSpecialist = aRow.nameOfSpecialist console.log('##### currentSpecialist', currentSpecialist) this.specialistElement || (this.specialistElement = []) if (this.specialistElement[index]) { console.log('~~~~~', `Specialist ${index + 1}`, this.specialistElement[index]) } const currentSpecialistOpts = {} if (currentSpecialist) { if (currentSpecialist.length === 1) { currentSpecialistOpts['default'] = currentSpecialist } } else { currentSpecialistOpts['default'] = [this.props.currentProvider] setTimeout(() => { if (this.specialistElement[index]) { this.specialistElement[index].getInstance()._handleTextChange( this.props.currentProvider.name) } }, 10) } console.log('>>> this.props.primaryProcedure', this.props.primaryProcedure) return ( <div key={index}> <Row> <Col xs={12} md={6}> <TypeaheadField {...currentProcedureOpts} {...this.props} cssName={this.props.cssName} fieldName='otherProcedure' links={( Array.isArray(this.props.primaryProcedure) && this.props.primaryProcedure.length > 0 && this.props.primaryProcedure[0].links ) || []} member={member} name='other-procedure' placeholderText={`Other procedure ${index + 1}`} section='otherProcedure' inputRef={(el) => { this.procedureElement[index] = el }} /> </Col> <Col xs={12} md={3}> <div className={`${this.props.cssName}-form-group`}> <div className={classnames( `${this.props.cssName}-form-group-trigger`, 'form-link-icon', 'is-remove' )} title='Remove' onClick={(event) => { this.setState({ otherProcedures: [ ...this.state.otherProcedures.slice(0, index), ...this.state.otherProcedures.slice(index + 1) ] }) return fields.remove(index) }} /> </div> </Col> <Col xs={12} md={3}> <DollarTextField cssName={this.props.cssName} fieldName='specialistCost' member={member} name='specialist-cost' placeholderText='$ Specialist cost' /> </Col> </Row> <hr className='form-section-repeat-divider' /> </div> ) })} <Row> <Col xs={12} md={6}> <a href='#' className={`form-link-plus ${this.props.cssName}-form-link is-add-another-procedure`} onClick={(event) => { event.preventDefault() this.setState({ otherProcedures: [...this.state.otherProcedures, ''] }) return fields.push({}) }} >Add another procedure</a> {(touched || submitFailed) && error && <span>{error}</span>} </Col> </Row> </div> ) } render () { return ( <div className={`${this.props.cssName}`}> <Row> <Col xs={12} md={3}> <h3 className={`${this.props.cssName}-form-title`}>Costs</h3> </Col> <Col xs={12} md={9}> <Row> <Col xs={12} md={12}> <h4 className={`${this.props.cssName}-form-section-title`}> Primary procedure </h4> </Col> </Row> <Row className='pb-4'> <Col xs={12} md={6}> <TypeaheadField cssName={this.props.cssName} fieldName='primaryProcedure' links={this.props.links} name='primary-procedure' onInputChange={() => { return this.props.dispatch( arrayRemoveAll('requestPayment', 'otherProcedures') ) }} placeholderText='Primary procedure' section='primaryProcedure' /> </Col> <Col xs={12} md={3}> <div className={`${this.props.cssName}-form-group`}> <RadioGroupField cssName={`${this.props.cssName}`} fieldName='location' name='location' radioList={[ { text: 'Left', value: 'Left' }, { text: 'Right', value: 'Right' }, { text: 'n/a', value: 'NotApplicable' } ]} /> </div> </Col> </Row> </Col> </Row> <Row> <Col xs={12} md={3} /> <Col xs={12} md={9}> <Row> <Col xs={12} md={12}> <h4 className={`${this.props.cssName}-form-section-title`}> Cost (Excluding GST) </h4> </Col> </Row> <Row> <Col xs={9} md={9}><span className={`${this.props.cssName}-label`}>Specialist</span> </Col> <Col xs={3} md={3}> <DollarTextField cssName={this.props.cssName} fieldName='specialistCost' name='specialist-cost' placeholderText='$ 0.00' /> </Col> </Row> <hr className='form-section-repeat-divider' /> <Row> <Col xs={9} md={9}><span className={`${this.props.cssName}-label`}>Consultation</span></Col> <Col xs={3} md={3}> <DollarTextField cssName={this.props.cssName} fieldName='consultationCost' name='consultation-cost' placeholderText='$ 0.00' /> </Col> </Row> <hr className='form-section-repeat-divider' /> <Row> <Col xs={4} md={4}><span className={`${this.props.cssName}-label`}>Prosthesis</span></Col> <Col xs={5} md={5}> <TypeaheadField cssName={this.props.cssName} fieldName='prosthesisDescr' links={this.props.links} name='prosthesis-description' placeholderText='Prosthesis description' section='prosthesisDescr' /> </Col> <Col xs={3} md={3}> <DollarTextField cssName={`${this.props.cssName}-prosthesis-cost`} fieldName='prosthesisCost' name='prosthesisCost' placeholderText='$ 0.00' /> </Col> </Row> <hr className='form-section-repeat-divider' /> {/* Repeating - Start */} <FieldArray name='otherCosts' component={this.renderOtherCosts} /> {/* Repeating - End */} <Row> <Col xs={12} md={12}> <h4 className={`${this.props.cssName}-form-section-title`}> Other procedures (Excluding GST) </h4> </Col> </Row> {/* Repeating - Start */} <FieldArray name='otherProcedures' component={this.renderOtherProcedures} /> {/* Repeating - End */} <hr className='form-section-repeat-divider' /> <Row> <Col xs={12} md={12} className='text-right'> <span className={`${this.props.cssName}-gst-label`}>GST</span> <span className={`${this.props.cssName}-gst-cost`}>$ {calculateGst(parseFloat(this.props.totalCost)).toFixed(2)}</span> </Col> </Row> <Row> <Col xs={12} md={12} className='text-right'> <span className={`${this.props.cssName}-total-label`}>Total</span> <span className={`${this.props.cssName}-total-cost`}> $ { calculateTotalIncludingGst(this.props.totalCost).toFixed(2) || '0.00'} </span> <Field name='totalCostErr' component={totalCost => { return (<div> { totalCost.meta.invalid && <span className='error-message'>{totalCost.meta.error}</span> } </div>) }} /> </Col> </Row> </Col> </Row> </div> ) } } CostsForSpecialist.propTypes = { change: React.PropTypes.func, cssName: React.PropTypes.string, currentProvider: React.PropTypes.shape({ name: React.PropTypes.string }), dispatch: React.PropTypes.func, links: React.PropTypes.array, list: React.PropTypes.array, loadRequestPaymentCostList: React.PropTypes.func, primaryProcedure: React.PropTypes.object, totalCost: React.PropTypes.number } CostsForSpecialist.defaultProps = { // cssName: 'associated-costs' } const CostsForSpecialistReduxForm = reduxForm({ form: 'requestPayment' })(CostsForSpecialist) export default CostsForSpecialistReduxForm
src/svg-icons/notification/time-to-leave.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationTimeToLeave = (props) => ( <SvgIcon {...props}> <path d="M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01L3 11v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.5-4.5h11L19 10H5z"/> </SvgIcon> ); NotificationTimeToLeave = pure(NotificationTimeToLeave); NotificationTimeToLeave.displayName = 'NotificationTimeToLeave'; NotificationTimeToLeave.muiName = 'SvgIcon'; export default NotificationTimeToLeave;
src/svg-icons/device/battery-charging-20.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryCharging20 = (props) => ( <SvgIcon {...props}> <path d="M11 20v-3H7v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17h-4.4L11 20z"/><path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h4v-2.5H9L13 7v5.5h2L12.6 17H17V5.33C17 4.6 16.4 4 15.67 4z"/> </SvgIcon> ); DeviceBatteryCharging20 = pure(DeviceBatteryCharging20); DeviceBatteryCharging20.displayName = 'DeviceBatteryCharging20'; DeviceBatteryCharging20.muiName = 'SvgIcon'; export default DeviceBatteryCharging20;
src/app/components/project/Project.js
meedan/check-web
import React from 'react'; import PropTypes from 'prop-types'; import { browserHistory } from 'react-router'; import Relay from 'react-relay/classic'; import { graphql } from 'react-relay/compat'; import { FormattedMessage } from 'react-intl'; import FolderOpenIcon from '@material-ui/icons/FolderOpen'; import VisibilityIcon from '@material-ui/icons/Visibility'; import ErrorBoundary from '../error/ErrorBoundary'; import ProjectRoute from '../../relay/ProjectRoute'; import CheckContext from '../../CheckContext'; import MediasLoading from '../media/MediasLoading'; import Search from '../search/Search'; import { safelyParseJSON } from '../../helpers'; import NotFound from '../NotFound'; import ProjectActions from '../drawer/Projects/ProjectActions'; import { units, black32 } from '../../styles/js/shared'; class ProjectComponent extends React.PureComponent { componentDidMount() { this.setContextProject(); } componentDidUpdate() { this.setContextProject(); } getContext() { return new CheckContext(this); } setContextProject() { if (!this.props.project) { return false; } const context = this.getContext(); const currentContext = this.currentContext(); const newContext = {}; newContext.project = this.props.project; let notFound = false; if (!currentContext.team || currentContext.team.slug !== this.props.project.team.slug) { newContext.team = this.props.project.team; notFound = true; } if (currentContext.team && !currentContext.team.projects) { newContext.team = this.props.project.team; } context.setContextStore(newContext); if (notFound) { browserHistory.push('/check/not-found'); } return true; } currentContext() { return this.getContext().getContextStore(); } render() { const { project, routeParams } = this.props; if (!project) { return null; } const query = { ...safelyParseJSON(routeParams.query, {}), projects: [project.dbid], }; const privacyLabels = [ null, <FormattedMessage id="project.onlyAdminsAndEditors" defaultMessage="Only Admins and Editors" />, <FormattedMessage id="project.onlyAdmins" defaultMessage="Only Admins" />, ]; const privacyLabel = privacyLabels[project.privacy]; return ( <div className="project"> <Search searchUrlPrefix={`/${routeParams.team}/project/${routeParams.projectId}`} mediaUrlPrefix={`/${routeParams.team}/project/${routeParams.projectId}/media`} title={project.title} icon={<FolderOpenIcon />} listDescription={project.description} listActions={ <React.Fragment> { project.privacy > 0 ? <div style={{ color: black32, display: 'flex', alignItems: 'center', fontSize: 14, marginLeft: units(2), gap: '8px', }} > <VisibilityIcon /> {privacyLabel} </div> : null } <ProjectActions isMoveable hasPrivacySettings object={project} objectType="Project" name={<FormattedMessage id="project.name" defaultMessage="folder" />} updateMutation={graphql` mutation ProjectUpdateProjectMutation($input: UpdateProjectInput!) { updateProject(input: $input) { project { id title description } } } `} deleteMessage={ <FormattedMessage id="project.deleteMessage" defaultMessage="{mediasCount, plural, one {There is 1 item in {folderTitle}. Please choose a destination folder:} other {There are # items in {folderTitle}. Please choose a destination folder:}}" values={{ mediasCount: project.medias_count, folderTitle: project.title, }} /> } deleteMutation={graphql` mutation ProjectDestroyProjectMutation($input: DestroyProjectInput!) { destroyProject(input: $input) { deletedId team { id } } } `} /> </React.Fragment> } teamSlug={routeParams.team} project={project} query={query} page="folder" hideFields={['projects', 'country', 'cluster_teams', 'cluster_published_reports']} /> </div> ); } } ProjectComponent.contextTypes = { store: PropTypes.object, }; const ProjectContainer = Relay.createContainer(ProjectComponent, { initialVariables: { projectId: null, }, fragments: { project: () => Relay.QL` fragment on Project { id, dbid, title, description, permissions, search_id, medias_count, project_group_id, privacy, is_default, team { id, dbid, slug, search_id, medias_count, permissions, verification_statuses, default_folder { id dbid } public_team { id, trash_count, } } } `, }, }); const Project = ({ routeParams, ...props }) => { const route = new ProjectRoute({ projectId: routeParams.projectId }); return ( <ErrorBoundary component="Project"> <Relay.RootContainer Component={ProjectContainer} route={route} renderFetched={data => ( /* TODO make GraphQL Projects query filter by Team * ... in the meantime, we can fake an error by showing "Not Found" when the * Project exists but is in a different Team than the one the user asked for * in the URL. */ (data.project && data.project.team && data.project.team.slug !== routeParams.team) ? <NotFound /> : <ProjectContainer routeParams={routeParams} {...props} {...data} /> )} renderLoading={() => <MediasLoading />} /> </ErrorBoundary> ); }; Project.propTypes = { routeParams: PropTypes.shape({ team: PropTypes.string.isRequired, projectId: PropTypes.string.isRequired, query: PropTypes.string, // JSON-encoded value; can be empty/null/invalid }).isRequired, }; export default Project;
docs/app/Examples/collections/Message/Types/MessageListPropExample.js
ben174/Semantic-UI-React
import React from 'react' import { Message } from 'semantic-ui-react' const list = [ 'You can now have cover images on blog pages', 'Drafts will now auto-save while writing', ] const MessageListPropExample = () => ( <Message header='New Site Features' list={list} /> ) export default MessageListPropExample
app/components/payment/planDetails.js
ritishgumber/dashboard-ui
import React from 'react'; import planList from './plans'; import {paymentCountries} from './config'; import Popover from 'material-ui/Popover'; import ReactTooltip from 'react-tooltip'; class PlanDetails extends React.Component { constructor(props) { super(props); this.state = { openPlanSelector: false }; } handleTouchTap = (event) => { event.preventDefault(); this.setState({openPlanSelector: true, anchorEl: event.currentTarget}) } handleRequestClose = () => { this.setState({openPlanSelector: false}) } selectPlan(plan) { this.props.selectPlan(plan); this.handleRequestClose() } componentWillMount() { this.setState({selectedPlan: this.props.selectedPlan}); } render() { return ( <div className="plans"> <div className="planname" onTouchTap={this.handleTouchTap}> <span className="type">{this.props.selectedPlan.label}</span> <span className="value">{this.props.selectedPlan.price || this.props.selectedPlan.price === 0 ? '$' + this.props.selectedPlan.price + ' ' + this.props.selectedPlan.priceDescription : ''}</span> <i className="icon ion-ios-arrow-down arrow"></i> </div> <Popover open={this.state.openPlanSelector} anchorEl={this.state.anchorEl} anchorOrigin={{ horizontal: 'left', vertical: 'top' }} targetOrigin={{ horizontal: 'left', vertical: 'top' }} onRequestClose={this.handleRequestClose} className="plandetailsdropdown"> {planList.map((plan, i) => { return <div className="plannamepop" key={i} onClick={this.selectPlan.bind(this, plan)}> <span className="type">{plan.label}</span> <span className="value">{plan.price || plan.price === 0 ? '$' + plan.price + ' ' + plan.priceDescription : 'Custom'}</span> </div> }) } </Popover> <p className="divlabel">DATABASE</p> <div className="divdetail"> <span className="type">API Calls</span> {this.props.selectedPlan.id === 3 ? <span className="value" data-tip="PAY AS YOU GO <br/><br/>$10 per GB of storage and $0.15 every 1000 API calls">{this.props.selectedPlan.usage[0].features[0].limit.label}</span> : <span className="value" data-tip="">{this.props.selectedPlan.usage[0].features[0].limit.label}</span>} </div> <ReactTooltip place="top" multiline type="dark" delayShow={100}/> <div className="divdetail"> <span className="type">Storage</span> {this.props.selectedPlan.id === 3 ? <span className="value" data-tip="PAY AS YOU GO <br/><br/>$10 per GB of storage and $0.15 every 1000 API calls">{this.props.selectedPlan.usage[0].features[0].limit.label}</span> : <span className="value" data-tip="">{this.props.selectedPlan.usage[0].features[1].limit.label}</span>} </div> <p className="divlabel">REALTIME</p> <div className="divdetail"> <span className="type">Connections</span> {this.props.selectedPlan.id === 3 ? <span className="value" data-tip="DATABASE CONNECTIONS <br/><br/>By default, we set a quota of 10,000 devices connecting to your database at the same time. You can request to have this limit lifted. See the FAQ below for details.">{this.props.selectedPlan.usage[0].features[0].limit.label}</span> : <span className="value" data-tip="">{this.props.selectedPlan.usage[1].features[0].limit.label}</span>} </div> <p className="divlabel">MISC</p> <div className="divdetail"> <span className="type">MongoDB Access</span> <span className={this.props.selectedPlan.usage[2].features[0].limit.show ? 'value' : 'value disabled'}>{this.props.selectedPlan.usage[2].features[0].limit.show ? 'Available' : 'Not Available'}</span> </div> </div> ) } } export default PlanDetails
src/index.js
kleavjames/SimpleYoutubeSearchApp
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import _ from 'lodash'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/SearchBar'; import VideoList from './components/VideoList'; import VideoDetail from './components/VideoDetail'; const API_KEY = 'AIzaSyBwGKtdqvbScmCz2sH26G8dgg_nozWwk6Q'; class App extends Component { constructor (props) { super (props); this.state = { videos: [], selectedVideo: null }; this.videoSearch('surfboards'); } videoSearch (term) { YTSearch({ key: API_KEY, term: term}, (videos) => { this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render () { const videoSearch = _.debounce( (term) => { this.videoSearch(term) }, 300) return ( <div> <SearchBar onSearchTermChange={ videoSearch } /> <VideoDetail video={ this.state.selectedVideo } /> <VideoList onVideoSelect = { selectedVideo => this.setState({ selectedVideo }) } videos={ this.state.videos } /> </div> ); } }; ReactDOM.render(<App />, document.querySelector('.container')) ;
assets/registration/components/SuccessAlert.js
janta-devs/nyumbani
import React, { Component } from 'react'; const SuccessAlert = (props) => { return( <div className="alert alert-success"> <strong>Success!</strong> Please Continue... </div> ) } export default SuccessAlert;
js/components/Pipe.js
gilesbradshaw/uaQL
// @flow 'use strict'; import React from 'react'; import Relay from 'react-relay'; import LocalizedText from './LocalizedText'; import {createContainer} from 'recompose-relay'; import {compose, doOnReceiveProps} from 'recompose'; import DataValue from './DataValue'; import Component from './Component'; import Components from './Components'; const MyComponents = Components(Component); const Pipe = compose( createContainer( { fragments: { viewer: () => Relay.QL` fragment on UANode { id displayName { text } ${MyComponents.getFragment('viewer')} } ` } } ), )(({viewer, root})=> <div> <div> {viewer.displayName.text} </div> <svg height={200} style={{background: 'pink'}}> <MyComponents viewer={viewer}/> </svg> </div> ); export default Pipe;
frontend/src/components/pages/searchresults.js
wilsonwen/kanmeiju
import React, { Component } from 'react'; import Config from '../../config' import { browserHistory } from 'react-router'; import Spin from '../spin' import { VelocityTransitionGroup } from 'velocity-react'; import SeasonList from './seasonlist' class SearchResults extends Component { constructor(props) { super(props); this.state = { searchDone: false, json: {} } this.config = Config(); this.fetchData = this.fetchData.bind(this); } /* callde first initialize */ componentDidMount() { this.fetchData(this.props.params.keyText); } /* called after props update, before state changed */ /* !Unusd now */ componentWillReceiveProps(nextProps) { this.fetchData(nextProps.params.keyText) } fetchData(keyText) { let url = this.config.server + '/api/search/' + keyText; fetch(url).then((res) => res.json()).then((data) => { this.setState({ searchDone: true, json: data }); }); } render() { let content = null; /* Check search done */ if (this.state.searchDone) { if (this.state.json.data !== undefined && this.state.json.data.results !== undefined && this.state.json.data.results.length !== 0) { let objList = []; let results = this.state.json.data.results; results.sort(function(a, b) { return a.id - b.id; }); for(var i = 0; i < results.length; i++) { let obj = results[i]; objList.push({id: obj.id, cover: obj.cover, title: obj.title, intro: obj.brief}); } content = <div><SeasonList objList={objList} /></div> } else { content = <div className="alert alert-danger" role="alert"> <span className="sr-only">Error:</span> 找不到和您查询的<strong><em>"{this.props.params.keyText}"</em></strong>相符的内容或信息。 <a href="#" onClick={browserHistory.goBack}>返回搜索</a> </div> } } else { content = <Spin /> } return ( <div> { content } </div> ) } } export default SearchResults;
src/svg-icons/editor/border-style.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderStyle = (props) => ( <SvgIcon {...props}> <path d="M15 21h2v-2h-2v2zm4 0h2v-2h-2v2zM7 21h2v-2H7v2zm4 0h2v-2h-2v2zm8-4h2v-2h-2v2zm0-4h2v-2h-2v2zM3 3v18h2V5h16V3H3zm16 6h2V7h-2v2z"/> </SvgIcon> ); EditorBorderStyle = pure(EditorBorderStyle); EditorBorderStyle.displayName = 'EditorBorderStyle'; EditorBorderStyle.muiName = 'SvgIcon'; export default EditorBorderStyle;
packages/react-interactions/events/src/dom/Press.js
flarnie/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {PointerType} from 'shared/ReactDOMTypes'; import React from 'react'; import {useTap} from 'react-interactions/events/tap'; import {useKeyboard} from 'react-interactions/events/keyboard'; import warning from 'shared/warning'; const emptyObject = {}; type PressProps = $ReadOnly<{| disabled?: boolean, preventDefault?: boolean, onPress?: (e: PressEvent) => void, onPressChange?: boolean => void, onPressEnd?: (e: PressEvent) => void, onPressMove?: (e: PressEvent) => void, onPressStart?: (e: PressEvent) => void, |}>; type PressEventType = | 'pressstart' | 'presschange' | 'pressmove' | 'pressend' | 'press'; type PressEvent = {| altKey: boolean, buttons: null | 1 | 4, ctrlKey: boolean, defaultPrevented: boolean, key: null | string, metaKey: boolean, pageX: number, pageY: number, pointerType: PointerType, shiftKey: boolean, target: null | Element, timeStamp: number, type: PressEventType, x: number, y: number, preventDefault: () => void, stopPropagation: () => void, |}; function createGestureState(e: any, type: PressEventType): PressEvent { return { altKey: e.altKey, buttons: e.type === 'tap:auxiliary' ? 4 : 1, ctrlKey: e.ctrlKey, defaultPrevented: e.defaultPrevented, key: e.key, metaKey: e.metaKey, pageX: e.pageX, pageY: e.pageX, pointerType: e.pointerType, shiftKey: e.shiftKey, target: e.target, timeStamp: e.timeStamp, type, x: e.x, y: e.y, preventDefault() { // NO-OP, we should remove this in the future if (__DEV__) { warning( false, 'preventDefault is not available on event objects created from event responder modules (React Flare). ' + 'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.preventDefault() }`', ); } }, stopPropagation() { // NO-OP, we should remove this in the future if (__DEV__) { warning( false, 'stopPropagation is not available on event objects created from event responder modules (React Flare). ' + 'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.stopPropagation() }`', ); } }, }; } function isValidKey(e): boolean { const {key, target} = e; const {tagName, isContentEditable} = (target: any); return ( (key === 'Enter' || key === ' ' || key === 'Spacebar') && (tagName !== 'INPUT' && tagName !== 'TEXTAREA' && isContentEditable !== true) ); } function handlePreventDefault(preventDefault: ?boolean, e: any): void { const key = e.key; if ( preventDefault !== false && (key === ' ' || key === 'Enter' || key === 'Spacebar') ) { e.preventDefault(); } } /** * The lack of built-in composition for gesture responders means we have to * selectively ignore callbacks from useKeyboard or useTap if the other is * active. */ export function usePress(props: PressProps) { const safeProps = props || emptyObject; const { disabled, preventDefault, onPress, onPressChange, onPressEnd, onPressMove, onPressStart, } = safeProps; const activeResponder = React.useRef(null); const tap = useTap({ disabled: disabled || activeResponder.current === 'keyboard', preventDefault, onAuxiliaryTap(e) { if (onPressStart != null) { onPressStart(createGestureState(e, 'pressstart')); } if (onPressEnd != null) { onPressEnd(createGestureState(e, 'pressend')); } // Here we rely on Tap only calling 'onAuxiliaryTap' with modifiers when // the primary button is pressed if (onPress != null && (e.metaKey || e.shiftKey)) { onPress(createGestureState(e, 'press')); } }, onTapStart(e) { if (activeResponder.current == null) { activeResponder.current = 'tap'; if (onPressStart != null) { onPressStart(createGestureState(e, 'pressstart')); } } }, onTapChange: onPressChange, onTapUpdate(e) { if (activeResponder.current === 'tap') { if (onPressMove != null) { onPressMove(createGestureState(e, 'pressmove')); } } }, onTapEnd(e) { if (activeResponder.current === 'tap') { if (onPressEnd != null) { onPressEnd(createGestureState(e, 'pressend')); } if (onPress != null) { onPress(createGestureState(e, 'press')); } activeResponder.current = null; } }, onTapCancel(e) { if (activeResponder.current === 'tap') { if (onPressEnd != null) { onPressEnd(createGestureState(e, 'pressend')); } activeResponder.current = null; } }, }); const keyboard = useKeyboard({ disabled: disabled || activeResponder.current === 'tap', onClick(e) { if (preventDefault !== false) { e.preventDefault(); } if (activeResponder.current == null && onPress != null) { onPress(createGestureState(e, 'press')); } }, onKeyDown(e) { if (activeResponder.current == null && isValidKey(e)) { handlePreventDefault(preventDefault, e); activeResponder.current = 'keyboard'; if (onPressStart != null) { onPressStart(createGestureState(e, 'pressstart')); } if (onPressChange != null) { onPressChange(true); } } }, onKeyUp(e) { if (activeResponder.current === 'keyboard' && isValidKey(e)) { handlePreventDefault(preventDefault, e); if (onPressChange != null) { onPressChange(false); } if (onPressEnd != null) { onPressEnd(createGestureState(e, 'pressend')); } if (onPress != null) { onPress(createGestureState(e, 'press')); } activeResponder.current = null; } }, }); return [tap, keyboard]; }
src/components/CompanyAndJobTitle/StatusRenderer.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import Loader from 'common/Loader'; import { isUnfetched, isFetching, isError } from '../../constants/status'; const StatusRenderer = ({ status, children, ...props }) => { if (isUnfetched(status)) { return null; } if (isFetching(status)) { return <Loader size="s" />; } if (isError(status)) { return null; } return children; }; StatusRenderer.propTypes = { status: PropTypes.string.isRequired, children: PropTypes.node.isRequired, }; export default StatusRenderer;
src/components/Link.js
hackclub/website
// Based on https://sven-roettering.de/external-gatsby-links/ import React from 'react' import { Link as DSLink } from '@hackclub/design-system' import { Link as GatsbyLink } from 'gatsby' const isExternalLink = path => path.startsWith('http') || path.startsWith('//:') const DSGatsbyLink = DSLink.withComponent(GatsbyLink) const Link = ({ to, children, ...props }) => isExternalLink(to) ? ( <DSLink href={to} {...props}> {children} </DSLink> ) : ( <DSGatsbyLink to={to} {...props}> {children} </DSGatsbyLink> ) export default Link
packages/material-ui-icons/src/GridOn.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let GridOn = props => <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 20H4v-4h4v4zm0-6H4v-4h4v4zm0-6H4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4z" /> </SvgIcon>; GridOn = pure(GridOn); GridOn.muiName = 'SvgIcon'; export default GridOn;
src/routes/indexMyCustom.js
daxiangaikafei/QBGoods
import React from 'react' import { Route, IndexRoute, Router } from 'dva/router' import CoreLayout from '../containers/layout' import Hotgoods from 'views/Hotgoods/page' import MyCustom from 'views/MyCustom/page' import SelfSupport from 'views/SelfSupport/page' import GatherGoods from 'views/GatherGoods/page' import GatherStore from 'views/GatherStore/page' import ShopActivity from 'views/ShopActivity/page' import Order from "views/Order/page" import BannerEntry from "views/Activity/bannerEntry" import Banner01 from "views/Activity/banner01" import ChannelEntry from "views/Activity/channelEntry" export default function (ref) { return ( <Router history={ref.history}> <Route path='/' component={CoreLayout} name="我有好物"> <IndexRoute component={MyCustom} name="我的定制"/> <Route path='/MyCustom' component={MyCustom} name="我的定制" /> </Route> </Router> ) }
maodou/posts/client/components/post.js
ShannChiang/USzhejiang
import React from 'react'; import Loading from 'client/components/common/loading'; import moment from 'moment'; export default (props) => { return ( <div className="container" style={{ paddingTop: '40px'}}> <div className="row"> <div className="col-lg-12"> { props.post ? <div className="hpanel blog-article-box"> <div className="panel-heading"> <h4>[{props.post.category}] {props.post.title}</h4> <div className="text-muted small"> 作者:<span className="font-bold">{props.post.author}</span>&nbsp; 日期:{moment(props.post.createdAt).format('YYYY-MM-DD')} </div> </div> <div className="panel-body" dangerouslySetInnerHTML={{ __html: props.post.content }} /> {/*<div className="panel-footer">*/} {/*<span className="pull-right">*/} {/*<i className="fa fa-comments-o" /> 22 comments*/} {/*</span>*/} {/*<i className="fa fa-eye" /> 142 views*/} {/*</div>*/} </div> : <Loading /> } </div> </div> </div> ); }
frontend/src/javascripts/stores/PostStore.js
funaota/notee
import React from 'react'; import assign from 'object-assign'; import request from 'superagent'; var EventEmitter = require('events').EventEmitter; // notee import NoteeDispatcher from '../dispatcher/NoteeDispatcher'; import Constants from '../constants/NoteeConstants'; // utils import EventUtil from '../utils/EventUtil'; function post_create(content) { request .post("/notee/api/posts") .send(content) .end(function(err, res){ if(err || !res.body){ EventUtil.emitChange(Constants.POST_CREATE_FAILED); return false; } EventUtil.emitChange(Constants.POST_CREATE); }) } function post_update(content) { request .put("/notee/api/posts/" + content.params_id) .send(content.content) .end(function(err, res){ if(err || !res.body){ EventUtil.emitChange(Constants.POST_UPDATE_FAILED); return false; } EventUtil.emitChange(Constants.POST_UPDATE); }) } function post_delete(id){ request .del("/notee/api/posts/" + id) .end(function(err, res){ if(err || !res.body){ EventUtil.emitChange(Constants.POST_DELETE_FAILED); return false; } EventUtil.emitChange(Constants.POST_DELETE); }) } var PostStore = assign({}, EventEmitter.prototype, { loadPost: function(notee_id, callback) { var url = "/notee/api/posts/" + notee_id; request.get(url, (err, res) => { if(err){return;} if(!res.body){return;} callback(res.body.post); }) }, loadPosts: function(callback) { request.get('/notee/api/posts', (err, res) => { if(err){return;} if(!res.body){return;} callback(res.body.posts); }); }, loadStatuses: function(callback) { var url = "/notee/api/statuses"; request.get(url, (err, res) => { if(err){return;} if(!res.body){return;} callback(res.body.statuses); }) }, loadStatus: function(status_value, callback) { var url = "/notee/api/statuses/0"; request .get(url) .query({status: status_value}) .end(function(err, res){ if(err){return;} if(!res.body){return;} callback(res.body.name); }); } }); NoteeDispatcher.register(function(action) { switch(action.type) { case Constants.POST_CREATE: post_create(action.content); break; case Constants.POST_UPDATE: post_update(action.content); break; case Constants.POST_DELETE: post_delete(action.post_id); break; } }); module.exports = PostStore;
app/components/Feed.js
Atamas1llya/Flerse
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { getFeed, getSubscribedFeed } from '../actions/feed'; import { Grid, Row, Col, Tabs, Tab } from 'react-bootstrap'; import Story from './Story'; class Feed extends Component { componentDidMount() { this.props.getFeed(); if (this.props.token) { this.props.getSubscribedFeed(this.props.token); } } render() { const { feed, token } = this.props; return( <Grid className='grid'> <Row className="show-grid"> <Col xs={0} md={3} /> <Col xs={12} md={6}> <Tabs defaultActiveKey={1} id="feed-tabs"> <Tab eventKey={1} title="Home"> <main> { feed.common.map(story => <Story {...story} key={story._id} />) } </main> </Tab> { token ? <Tab eventKey={2} title="Subscribes"> <main> { feed.subscribed.map(story => <Story {...story} key={story._id} />) } </main> </Tab> : null } </Tabs> </Col> <Col xs={0} md={3} /> </Row> </Grid> ) } } const mapState = ({ feed, token }) => ({ feed, token }); const mapDispatch = dispatch => ({ getFeed: () => dispatch(getFeed()), getSubscribedFeed: token => dispatch(getSubscribedFeed(token)) }); export default connect(mapState, mapDispatch)(Feed);
src/parser/shaman/restoration/modules/azerite/BaseHealerAzerite.js
sMteX/WoWAnalyzer
import { calculateAzeriteEffects } from 'common/stats'; import { formatNumber, formatPercentage } from 'common/format'; import SpellLink from 'common/SpellLink'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events from 'parser/core/Events'; import React from 'react'; import ItemHealingDone from 'interface/others/ItemHealingDone'; import Statistic from 'interface/statistics/Statistic'; import { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY'; /** * A class to deal with (hopefully) any healing Azerite i throw at it. * Extend and overwrite the static properties. */ class BaseHealerAzerite extends Analyzer { static TRAIT; static HEAL; hasTrait; azerite = []; trait = (factor, raw, ilvl) => ({ healing: 0, overhealing: 0, healingFactor: factor, rawHealing: raw, itemlevel: ilvl, }); constructor(...args) { super(...args); this.active = !!this.constructor.TRAIT; if (!this.active) { return; } this.hasTrait = this.selectedCombatant.hasTrait(this.constructor.TRAIT.id); const ranks = this.selectedCombatant.traitRanks(this.constructor.TRAIT.id) || []; const healingPerTrait = ranks.map((rank) => calculateAzeriteEffects(this.constructor.TRAIT.id, rank)[0]); const totalHealingPotential = healingPerTrait.reduce((total, bonus) => total + bonus, 0); this.azerite = ranks.map((rank, index) => { return this.trait((healingPerTrait[index] / totalHealingPotential), healingPerTrait[index], rank); }); // as we can't find out which azerite piece a trait belongs to, might as well sort it by itemlevel this.azerite.sort((a, b) => a.itemlevel - b.itemlevel); this.addEventListener(Events.heal.by(SELECTED_PLAYER).spell(this.constructor.HEAL), this._processHealing); } _processHealing(event, traitComponent = undefined) { let heal = event.amount + (event.absorbed || 0); let overheal = (event.overheal || 0); // Override the healing with the part which the trait contributed, // as some traits are baked into a different spell if (traitComponent) { const raw = heal + overheal; const relativeHealingFactor = 1 + traitComponent; const relativeHealing = raw - raw / relativeHealingFactor; heal = Math.max(0, relativeHealing - overheal); overheal = Math.max(0, relativeHealing - heal); } // https://github.com/WoWAnalyzer/WoWAnalyzer/issues/2009#issuecomment-412253156 // Iterating through the traits, always in the same order // This way its easier to see if stacking them was a bad idea or if it didn't matter. const healPerTrait = this.azerite.map((trait) => (heal + overheal) * trait.healingFactor); for (const [index, trait] of Object.entries(this.azerite)) { const healingValue = Math.max(0, healPerTrait[index] - overheal); const overhealingValue = Math.max(0, healPerTrait[index] - healingValue); trait.healing += healingValue; trait.overhealing += overhealingValue; heal -= healingValue; overheal -= overhealingValue; } } get totalHealing() { return this.azerite.reduce((total, trait) => total + trait.healing, 0); } moreInformation = null; statistic() { const nth = (number) => ["st", "nd", "rd"][((number + 90) % 100 - 10) % 10 - 1] || "th"; const numTraits = this.azerite.length; if (!this.disableStatistic) { return ( <Statistic size="flexible" position={STATISTIC_ORDER.CORE()} category={STATISTIC_CATEGORY.ITEMS} tooltip={this.moreInformation} > <> <h4 style={{ textAlign: 'center' }}> <SpellLink id={this.constructor.TRAIT.id} /> </h4> <div className="flex" style={{ borderBottom: '1px solid #fab700', fontWeight: 'bold', fontSize: '14px', padding: '6px 22px 5px' }}> <div className="flex-main"> {`Total`} </div> <div className="flex-sub text-right"> <ItemHealingDone amount={this.totalHealing} /> </div> </div> <table className="data-table compact" style={{ textAlign: 'center', marginBottom: 0 }}> <thead> <tr> {numTraits > 1 && (<th style={{ width: '25%', textAlign: 'center' }}><b>Trait</b></th>)} <th style={{ width: '25%', textAlign: 'center' }}><b>ilvl</b></th> <th style={{ width: '25%', textAlign: 'center' }}><b>Healing</b></th> <th style={{ width: '25%', textAlign: 'center' }}><b>Overhealing</b></th> </tr> </thead> <tbody> {this.azerite.slice().reverse().map((trait, index) => { return ( <tr key={index}> {numTraits > 1 && (<td>{index + 1}{nth(index + 1)}</td>)} <td>{trait.itemlevel}</td> <td>{formatNumber(trait.healing)}</td> <td>{formatPercentage(trait.overhealing / (trait.healing + trait.overhealing))}%</td> </tr> ); })} </tbody> </table> </> </Statistic> ); } else { return null; } } } export default BaseHealerAzerite;
imports/ui/components/files/NewDirectoryModal.js
hwillson/file-metadata-manager
import React, { Component } from 'react'; import { Modal, Button, FormGroup, ControlLabel, FormControl, HelpBlock, } from 'react-bootstrap'; import { css } from 'aphrodite'; import UtilityStyles from '../../styles/utility'; import { createDirectory } from '../../../api/fs_files/methods'; class NewDirectoryModal extends Component { constructor(props) { super(props); this.callCreateDirectory = this.callCreateDirectory.bind(this); this.directoryInput = null; } componentDidUpdate() { if (this.directoryInput) { this.directoryInput.focus(); } } callCreateDirectory(event) { event.preventDefault(); const directoryName = this.directoryInput.value; if (directoryName) { createDirectory.call({ currentDirectory: this.props.currentPath, directoryName, }, (error) => { if (!error) { this.props.closeModal(null, true); } }); } } render() { const path = this.props.currentPath || '/'; return ( <Modal show={this.props.showModal} onHide={this.props.closeModal} animation={false} > <Modal.Header closeButton> <Modal.Title> <span className={css(UtilityStyles.marginRight10)}> <i className="fa fa-folder-open-o" /> </span> Create a New Directory </Modal.Title> </Modal.Header> <form onSubmit={this.callCreateDirectory}> <Modal.Body> <FormGroup controlId="newDirectoryForm"> <ControlLabel>New Directory Name</ControlLabel> <FormControl type="text" inputRef={(ref) => { this.directoryInput = ref; }} /> <HelpBlock> New directory will be created in: <strong>{path}</strong> </HelpBlock> </FormGroup> </Modal.Body> <Modal.Footer> <Button className="btn-fill" onClick={this.props.closeModal}> Cancel </Button> <Button type="submit" bsStyle="info" className="btn-fill"> Create </Button> </Modal.Footer> </form> </Modal> ); } } NewDirectoryModal.propTypes = { showModal: React.PropTypes.bool.isRequired, closeModal: React.PropTypes.func.isRequired, currentPath: React.PropTypes.string.isRequired, }; NewDirectoryModal.defaultProps = { showModal: false, }; export default NewDirectoryModal;
Frontend/src/index/user_center.js
zsefvlol/threedegrees
"use strict"; import React from 'react'; import { render } from 'react-dom'; import { Link } from 'react-router' import WeUI from 'react-weui'; import UserList from './user_list' import InviteList from './invite_list' const {Cells, CellsTitle, CellBody, Cell, Button, CellFooter, ButtonArea} = WeUI; export default class UserCenter extends React.Component { state = { profile : window.pageData.profile }; render() { return (<section> <Cell className="list_item"> <CellBody> <h2 className="title">欢迎 {this.state.profile.user_info.truename}</h2> <div className="clearfix pd1"> <Link to="/users" className="fl"> <Button>三度列表</Button> </Link> <Link to="/join" className="fr"> <Button type="default">我的资料</Button> </Link> </div> </CellBody> </Cell> <UserList list_title="我喜欢的" empty_notice="" user_list={this.state.profile.i_like} disable_return={true} /> <UserList list_title="互相喜欢" empty_notice="" user_list={this.state.profile.like_each_other} disable_return={true} /> <InviteList user_info={this.state.profile} /> </section>); } }
src/components/RadioButtonGroup/RadioButtonGroup.js
jzhang300/carbon-components-react
import PropTypes from 'prop-types'; import React from 'react'; import RadioButton from '../RadioButton'; import warning from 'warning'; export default class RadioButtonGroup extends React.Component { static propTypes = { children: PropTypes.node, className: PropTypes.string, defaultSelected: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), name: PropTypes.string.isRequired, disabled: PropTypes.bool, onChange: PropTypes.func, valueSelected: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; static defaultProps = { onChange: /* istanbul ignore next */ () => {}, className: 'bx--radio-button-group', }; state = { selected: null, }; componentWillMount() { this.setState({ selected: this.props.valueSelected || this.props.defaultSelected || null, }); } componentWillReceiveProps(nextProps) { if (nextProps.hasOwnProperty('valueSelected')) { this.setState({ selected: nextProps.valueSelected, }); } } getRadioButtons = () => { const children = React.Children.map(this.props.children, radioButton => { const { value, ...other } = radioButton.props; /* istanbul ignore if */ if (radioButton.props.hasOwnProperty('checked')) { warning( false, `Instead of using the checked property on the RadioButton, set the defaultSelected property or valueSelected property on the RadioButtonGroup.` ); } return ( <RadioButton {...other} name={this.props.name} key={value} value={value} onChange={this.handleChange} checked={value === this.state.selected} /> ); }); return children; }; handleChange = (newSelection, value, evt) => { if (newSelection !== this.state.selected) { this.setState({ selected: newSelection }); this.props.onChange(newSelection, this.props.name, evt); } }; render() { const { disabled, className } = this.props; return ( <div className="bx--form-item"> <div className={className} disabled={disabled}> {this.getRadioButtons()} </div> </div> ); } }