path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
my-app/src/pages/manager/index.js
father-wei/tutitu
import React from 'react' import ServiceList from '../../components/list/serviceList' import MemberList from '../../components/list/memberList' import ProviderList from '../../components/list/providerList' import List from '../../components/loggingService/list' import { loggingServices } from '../../core/domain/loggingServices' import { services } from '../../core/domain/services' var ManagerPage =React.createClass({ getInitialState: function() { return { loggingServices: [], sum : 0 }; }, componentWillMount: function() { var items = []; loggingServices.on("value", (snapshot) => { snapshot.forEach( (childSnapshot) => { var item = childSnapshot.val(); item['.key'] = childSnapshot.key; services.orderByChild("code") .equalTo(item.serviceId) .on("value", (childsnapshot) => { if(childsnapshot.val() && Object.values(childsnapshot.val())[0]){ item.price = Object.values(childsnapshot.val())[0].price; item.serviceName = Object.values(childsnapshot.val())[0].name; if( new Date().getTime() - new Date(item.date).getTime() < 86400000 * 7 ){ items.push(item); this.setState({ loggingServices: items, sum: this.state.sum + item.price }); items.sort(function(a, b){ if(a.serviceName < b.serviceName) return -1; if(a.serviceName > b.serviceName) return 1; return 0; }) } } }); }) }) }, render: function() { return ( <div> <div className="well"> <div className="row"> <div className="col-md-6"><ServiceList /></div> <div className="col-md-6"><MemberList /></div> </div> <div className="row"> <div className="col-md-6"><ProviderList /></div> </div> </div> <div className="well"> <h2>Weekly Report </h2> <List items={ this.state.loggingServices } sum= {this.state.sum}/> </div> </div> ) } }) export default ManagerPage;
client/src/components/PublicationStatus/PublicationStatus.js
mikedingjan/wagtail
import PropTypes from 'prop-types'; import React from 'react'; /** * Displays the publication status of a page in a pill. */ const PublicationStatus = ({ status }) => ( <span className={`o-pill c-status${status.live ? ' c-status--live' : ''}`}> {status.status} </span> ); PublicationStatus.propTypes = { status: PropTypes.shape({ live: PropTypes.bool.isRequired, status: PropTypes.string.isRequired, }).isRequired, }; export default PublicationStatus;
examples/webpack/src/components/Button.js
sapegin/react-styleguidist
import React from 'react'; import PropTypes from 'prop-types'; import './Button.css'; /** * The only true button. */ export default function Button({ color, size, children }) { const styles = { color, fontSize: Button.sizes[size], }; return ( <button className="button" style={styles}> {children} </button> ); } Button.propTypes = { /** * Button label. */ children: PropTypes.string.isRequired, color: PropTypes.string, size: PropTypes.oneOf(['small', 'normal', 'large']), }; Button.defaultProps = { color: '#333', size: 'normal', }; Button.sizes = { small: '10px', normal: '14px', large: '18px', };
mobile/src/components/status.js
sradevski/homeAutomate
import React, { Component } from 'react'; import { Text, View, StyleSheet } from 'react-native'; import { connect } from 'react-redux'; import {makeServerCall, generateRequestBody} from '../shared/utils'; const mapStateToProps = (state) => ({ appState: state.appState, location: state.location, }); class Status extends Component { render() { const {appState, location, style} = this.props; return ( <View style={[style, {justifyContent: 'center', alignItems: 'center'}]}> <Text style={styles.textTitle}>Status:</Text> <Text style={styles.textValue}>{appState.connectionStatus}</Text> <Text style={styles.textTitle}>Location:</Text> <Text style={styles.textValue}>{location.isHome ? 'Home' : 'Away'} </Text> <Text style={styles.textTitle}>Notification:</Text> <Text style={styles.textValue}>{appState.notification || 'None'} </Text> </View> ); } } const styles = StyleSheet.create({ textTitle: { fontSize: 14, textDecorationLine: 'underline', fontWeight: 'bold', marginTop: 5, }, textValue: { textAlign: 'center', } }); export default connect(mapStateToProps, null)(Status);
Realization/frontend/czechidm-core/src/content/scheduler/LongRunningTaskItems.js
bcvsolutions/CzechIdMng
import React from 'react'; import { connect } from 'react-redux'; // import * as Basic from '../../components/basic'; import * as Advanced from '../../components/advanced'; import * as Utils from '../../utils'; import { LongRunningTaskItemManager } from '../../redux'; import SearchParameters from '../../domain/SearchParameters'; import OperationStateEnum from '../../enums/OperationStateEnum'; // const UIKEY = 'long-running-task-item-table'; const manager = new LongRunningTaskItemManager(); /** * Queue(list) of processed items. * * @author Marek Klement * @author Radek Tomiška */ class LongRunningTaskItems extends Advanced.AbstractTableContent { constructor(props, context) { super(props, context); // this.state = { ...this.state, filterOpened: false }; } getManager() { return manager; } getNavigationKey() { return 'long-running-task-items'; } getContentKey() { return 'content.scheduler.all-tasks'; } useFilter(event) { if (event) { event.preventDefault(); } this.refs.table.useFilterForm(this.refs.filterForm); } cancelFilter(event) { if (event) { event.preventDefault(); } this.refs.table.cancelFilter(this.refs.filterForm); } render() { const { entityId } = this.props.match.params; const { filterOpened, detail } = this.state; const forceSearchParameters = new SearchParameters().setFilter('longRunningTaskId', entityId); // return ( <Basic.Panel className="no-border last"> <Advanced.Table ref="table" uiKey={ UIKEY } manager={ manager } forceSearchParameters={ forceSearchParameters } rowClass={({rowIndex, data}) => { return Utils.Ui.getRowClass(data[rowIndex]); }} className="no-margin" filter={ <Advanced.Filter onSubmit={this.useFilter.bind(this)}> <Basic.AbstractForm ref="filterForm"> <Basic.Row className="last"> <Basic.Col lg={ 4 }> <Advanced.Filter.EnumSelectBox ref="operationState" placeholder={ this.i18n('entity.LongRunningTaskItem.result.state') } enum={ OperationStateEnum }/> </Basic.Col> <Basic.Col lg={ 4 }> <Advanced.Filter.TextField ref="referencedEntityId" placeholder={ this.i18n('entity.LongRunningTaskItem.referencedEntityId.placeholder') }/> </Basic.Col> <Basic.Col lg={ 4 } className="text-right"> <Advanced.Filter.FilterButtons cancelFilter={this.cancelFilter.bind(this)}/> </Basic.Col> </Basic.Row> </Basic.AbstractForm> </Advanced.Filter> } filterOpened={ filterOpened } _searchParameters={ this.getSearchParameters() }> <Advanced.Column className="detail-button" cell={ ({ rowIndex, data }) => { return ( <Advanced.DetailButton title={ this.i18n('button.detail') } onClick={ this.showDetail.bind(this, data[rowIndex], null) }/> ); } }/> <Advanced.Column property="operationResult.state" header={ this.i18n('entity.LongRunningTaskItem.result.state') } width={ 75 } sort cell={ ({ data, rowIndex }) => { const entity = data[rowIndex]; // return ( <Advanced.OperationResult value={ entity.operationResult } detailLink={ () => this.showDetail(data[rowIndex], null) } level={ entity.operationResult && entity.operationResult.state === 'CREATED' ? 'success' : null }/> ); } } /> <Advanced.Column property="referencedEntityId" header={ this.i18n('entity.LongRunningTaskItem.referencedEntityId.label') } cell={ ({ rowIndex, data, property }) => { if (!data[rowIndex]._embedded || !data[rowIndex]._embedded[property]) { return ( <Advanced.UuidInfo value={ data[rowIndex][property] } /> ); } // return ( <Advanced.EntityInfo entityType={ Utils.Ui.getSimpleJavaType(data[rowIndex].referencedDtoType) } entityIdentifier={ data[rowIndex][property] } entity={ data[rowIndex]._embedded[property] } face="popover" showEntityType={ false } showIcon showLink={ !data[rowIndex].deleted } deleted={ data[rowIndex].deleted }/> ); } } sort face="text" /> <Advanced.Column property="referencedDtoType" header={ this.i18n('entity.LongRunningTaskItem.referencedEntityType.label') } width={ 75 } face="text" cell={ ({ rowIndex, data, property }) => { const javaType = data[rowIndex][property]; return ( <span title={ javaType }>{ Utils.Ui.getSimpleJavaType(javaType) }</span> ); } } /> <Advanced.Column property="created" header={ this.i18n('entity.created') } width={ 75 } sort face="datetime" /> </Advanced.Table> <Basic.Modal show={ detail.show } onHide={ this.closeDetail.bind(this) } backdrop="static"> <Basic.Modal.Header text={ this.i18n('detail.header') }/> <Basic.Modal.Body> <Advanced.OperationResult value={ detail.entity ? detail.entity.operationResult : null } level={ detail.entity && detail.entity.operationResult && detail.entity.operationResult.state === 'CREATED' ? 'success' : null } face="full"/> </Basic.Modal.Body> <Basic.Modal.Footer> <Basic.Button level="link" onClick={ this.closeDetail.bind(this) }> { this.i18n('button.close') } </Basic.Button> </Basic.Modal.Footer> </Basic.Modal> </Basic.Panel> ); } } function select(state) { return { _searchParameters: Utils.Ui.getSearchParameters(state, UIKEY) }; } export default connect(select, null, null, { forwardRef: true })(LongRunningTaskItems);
src/components/product-detail/product-detail-content.js
SupasitC/Pricetrolley
import React from 'react' import { Row, Col } from 'react-bootstrap' import FontAwesome from 'react-fontawesome' import PriceList from './price-list' export default class ProductDetailContent extends React.Component { render() { const style = require('./product-detail-content.scss'); return ( <Col md={8}> <div className={style.product}> <FontAwesome className={style.fav} name='heart-o' /> <h2>Product Name</h2> </div> <div className={style.rate}> <div className={style.ratingBlock}> <FontAwesome className={style.star} name='star' /> <FontAwesome className={style.star} name='star' /> <FontAwesome className={style.star} name='star' /> <FontAwesome className={style.star} name='star' /> <FontAwesome className={style.star} name='star-o' /> </div> <h4>rating 4</h4> </div> <div> <PriceList /> <PriceList /> <PriceList /> <PriceList /> </div> </Col> ) } }
src/Parser/VengeanceDemonHunter/TALENT_DESCRIPTIONS.js
Yuyz0112/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; export default { descriptions: { // lvl 99 [SPELLS.ABYSSAL_STRIKE_TALENT.id]: <span>Default talent for mobility build, giving you two extra <SpellLink id={SPELLS.INFERNAL_STRIKE.id} /> per minute. Increasing mobility by reducing the cooldown and increasing the range of Infernal Strike. Works perfectly with <SpellLink id={SPELLS.FLAME_CRASH_TALENT.id} />. </span>, [SPELLS.AGONIZING_FLAMES_TALENT.id]: <span>Should only be chosen if you need to spam <SpellLink id={SPELLS.IMMOLATION_AURA.id} /> for <SpellLink id={SPELLS.FALLOUT_TALENT.id} /> talent procs. It is a very weak choice when compared against <SpellLink id={SPELLS.ABYSSAL_STRIKE_TALENT.id} /> and <SpellLink id={SPELLS.FLAME_CRASH_TALENT.id} /> talents combo. </span>, [SPELLS.RAZOR_SPIKES_TALENT.id]: <span>Default talent for damage build. However, this talent is not recommended for new players, as you need a very good pain and buff uptime management while you manage your defensive cooldowns. </span>, // lvl 100 [SPELLS.FEAST_OF_SOULS_TALENT.id]: <span>Very weak choice against all others in this talent level. It provides just a small amount of healing, which will not save you from a death (and possibilly a wipe). </span>, [SPELLS.FALLOUT_TALENT.id]: <span>Default choice in this tier. It provides a very strong AoE healing burst against multiple targets and works very well with <SpellLink id={SPELLS.SPIRIT_BOMB_TALENT.id} /> talent. </span>, [SPELLS.BURNING_ALIVE_TALENT.id]: <span>Only choose this talent for fights that does a heavy AoE burst damage to you. </span>, // lvl 102 [SPELLS.FELBLADE_TALENT.id]: <span>Default talent for survivability due to the Pain generation. Also good as a charge skill, when you need extra mobility. </span>, [SPELLS.FLAME_CRASH_TALENT.id]: <span>Very good combo when chosen with <SpellLink id={SPELLS.ABYSSAL_STRIKE_TALENT.id} />. It provides a very good AoE passive damage. </span>, [SPELLS.FEL_ERUPTION_TALENT.id]: <span>Very good choice when dealing with single-target damage all fight. It sacrifices survivability for DPS so, as a tank, usually that is not a wise choice. </span>, // lvl 104 [SPELLS.FEED_THE_DEMON_TALENT.id]: <span>Almost not a valid choice, being easily overshadowed by <SpellLink id={SPELLS.FRACTURE_TALENT.id} /> damage or <SpellLink id={SPELLS.SOUL_RENDING_TALENT_VENGEANCE.id} /> survivability. </span>, [SPELLS.FRACTURE_TALENT.id]: <span>Default talent is this talent tier. It provides a great single-target damage, as well as AoE damage with <SpellLink id={SPELLS.SPIRIT_BOMB_TALENT.id}/> and great burst healing. </span>, [SPELLS.SOUL_RENDING_TALENT_VENGEANCE.id]: <span>Great choice for dungeons and Mythic + contents. Not very used in raid contents.</span>, // lvl 106 [SPELLS.CONCENTRATED_SIGILS_TALENT.id]: <span>Default choice is this tier when chosen with <SpellLink id={SPELLS.FLAME_CRASH_TALENT.id} /> talent. </span>, [SPELLS.SIGIL_OF_CHAINS_TALENT.id]: <span>Usually a good talent for easier AoE damage. It is very strong in dungeons contents.</span>, [SPELLS.QUICKENED_SIGILS_TALENT.id]: <span>Only choose this talent if you want to spam your sigils all fight, by lowering the cooldowns of all your sigils. </span>, // lvl 108 [SPELLS.FEL_DEVASTATION_TALENT.id]: <span>Provides burst healing and damage, but it is a very weak choice when compared with the others talents in this tier. </span>, [SPELLS.BLADE_TURNING_TALENT.id]: <span>Almost not a valid choice. </span>, [SPELLS.SPIRIT_BOMB_TALENT.id]: <span>Core talent. It provides a very good 20% damage healing debuff in all enemies in AoE or single-target fights. The go-to talent for raids, dungeons, soloing or leveling. </span>, // lvl 110 [SPELLS.LAST_RESORT_TALENT.id]: <span>Very strong choice for raid content. It may save a battle ressurection spell and maybe a wipe. </span>, [SPELLS.DEMONIC_INFUSION_TALENT.id]: <span>This talent provides a very good damage increase when chosen with <SpellLink id={SPELLS.RAZOR_SPIKES_TALENT.id} /> talent and also a great physical damage reduction talent.</span>, [SPELLS.SOUL_BARRIER_TALENT.id]: <span>This talent is viable just in heavy magical damage fights. Maximize its value using after a <SpellLink id={SPELLS.SOUL_CARVER.id}/>, <SpellLink id={SPELLS.FALLOUT_TALENT.id}/> or <SpellLink id={SPELLS.FRACTURE_TALENT.id} /> .</span>, }, };
src/client/lobby/Lobby.js
ThomasBrekelmans/stratego
import React from 'react'; import User from '../user/User'; import localLobby from './localLobby'; class Lobby extends React.Component { constructor (props) { super(props); this.state = { lobby: [] }; this._lobbySubscription = localLobby.observe('lobby') .subscribe((lobby) => { this.setState({ lobby: lobby }); }); } componentWillUnmount () { this._lobbySubscription.dispose(); } render () { const users = this.state.lobby.map((user) => <User key={ user.id } user={ user }/>); return ( <div> <p>Online:</p> <ul>{ users }</ul> </div> ); } } Lobby.displayName = 'Lobby'; export default Lobby;
src/buttons/ButtonGroup.js
fengshanjian/react-native-komect-uikit
import PropTypes from 'prop-types'; import React from 'react'; import { View, Text as NativeText, StyleSheet, TouchableHighlight, Platform, } from 'react-native'; import colors from '../config/colors'; import Text from '../text/Text'; import normalize from '../helpers/normalizeText'; const ButtonGroup = props => { const { component, buttons, onPress, selectedIndex, containerStyle, innerBorderStyle, lastBorderStyle, buttonStyle, textStyle, selectedTextStyle, selectedBackgroundColor, underlayColor, activeOpacity, onHideUnderlay, onShowUnderlay, setOpacityTo, containerBorderRadius, ...attributes } = props; const Component = component || TouchableHighlight; return ( <View style={[styles.container, containerStyle && containerStyle]} {...attributes} > {buttons.map((button, i) => { return ( <Component activeOpacity={activeOpacity} setOpacityTo={setOpacityTo} onHideUnderlay={onHideUnderlay} onShowUnderlay={onShowUnderlay} underlayColor={underlayColor || '#ffffff'} onPress={onPress ? () => onPress(i) : () => {}} key={i} style={[ styles.button, // FIXME: This is a workaround to the borderColor and borderRadius bug // react-native ref: https://github.com/facebook/react-native/issues/8236 i < buttons.length - 1 && { borderRightWidth: i === 0 ? 0 : (innerBorderStyle && innerBorderStyle.width) || 1, borderRightColor: (innerBorderStyle && innerBorderStyle.color) || colors.grey4, }, i === 1 && { borderLeftWidth: (innerBorderStyle && innerBorderStyle.width) || 1, borderLeftColor: (innerBorderStyle && innerBorderStyle.color) || colors.grey4, }, i === buttons.length - 1 && { ...lastBorderStyle, borderTopRightRadius: containerBorderRadius || 3, borderBottomRightRadius: containerBorderRadius || 3, }, i === 0 && { borderTopLeftRadius: containerBorderRadius || 3, borderBottomLeftRadius: containerBorderRadius || 3, }, selectedIndex === i && { backgroundColor: selectedBackgroundColor || 'white', }, ]} > <View style={[styles.textContainer, buttonStyle && buttonStyle]}> {button.element ? <button.element /> : <Text style={[ styles.buttonText, textStyle && textStyle, selectedIndex === i && { color: colors.grey1 }, selectedIndex === i && selectedTextStyle, ]} > {button} </Text>} </View> </Component> ); })} </View> ); }; const styles = StyleSheet.create({ button: { flex: 1, }, textContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', }, container: { marginLeft: 10, marginRight: 10, marginBottom: 5, marginTop: 5, borderColor: '#e3e3e3', borderWidth: 1, flexDirection: 'row', borderRadius: 3, overflow: 'hidden', backgroundColor: '#f5f5f5', height: 40, }, buttonText: { fontSize: normalize(13), color: colors.grey2, ...Platform.select({ ios: { fontWeight: '500', }, }), }, }); ButtonGroup.propTypes = { button: PropTypes.object, component: PropTypes.any, onPress: PropTypes.func, buttons: PropTypes.array, containerStyle: View.propTypes.style, textStyle: NativeText.propTypes.style, selectedTextStyle: NativeText.propTypes.style, underlayColor: PropTypes.string, selectedIndex: PropTypes.number, activeOpacity: PropTypes.number, onHideUnderlay: PropTypes.func, onShowUnderlay: PropTypes.func, setOpacityTo: PropTypes.any, innerBorderStyle: PropTypes.shape({ color: PropTypes.string, width: PropTypes.number, }), lastBorderStyle: PropTypes.oneOfType([ View.propTypes.style, NativeText.propTypes.style, ]), buttonStyle: View.propTypes.style, selectedBackgroundColor: PropTypes.string, containerBorderRadius: PropTypes.number, }; export default ButtonGroup;
pootle/static/js/editor/components/plurr/CaretIcon.js
evernote/zing
/* * Copyright (C) Zing contributors. * * This file is a part of the Zing project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; const CaretIcon = React.createClass({ propTypes: { direction: React.PropTypes.oneOf(['up', 'down']).isRequired, style: React.PropTypes.object, }, renderUp() { return ( <g id="Core" transform="translate(-553.000000, -9.000000)" {...this.props.style} > <g id="arrow-drop-up" transform="translate(553.000000, 9.500000)"> <path d="M0,5 L5,0 L10,5 L0,5 Z" id="Shape" /> </g> </g> ); }, renderDown() { return ( <g id="Core" transform="translate(-469.000000, -9.000000)" {...this.props.style} > <g id="arrow-drop-down" transform="translate(469.000000, 9.500000)"> <path d="M0,0 L5,5 L10,0 L0,0 Z" id="Shape" /> </g> </g> ); }, render() { return ( <svg version="1.1" viewBox="0 0 10 7" height="6px" width="8px" xmlns="http://www.w3.org/2000/svg" style={{ display: 'block' }} > <g fill="none" fill-rule="evenodd" id="CaretIcon" stroke="none" strokeWidth="1" > {this.props.direction === 'up' ? this.renderUp() : this.renderDown()} </g> </svg> ); }, }); export default CaretIcon;
docs/media/flex-video/index.js
valzav/react-foundation-components
import React from 'react'; import { FlexVideo } from '../../../src/flex-video'; const FlexVideoPage = () => ( <div> <h1>Flex Video</h1> <p> Wrap embedded videos from YouTube, Vimeo, and others in a flex video container to ensure they maintain the correct aspect ratio regardless of screen size. </p> <hr /> <h2>Basics</h2> <p>Importing the FlexVideo component:</p> <pre> <code> { `// Import with local scoped class names (via CSS Modules) import { FlexVideo } from 'react-foundation-components/lib/flex-video'; or // Import with global scoped class names import { FlexVideo } from 'react-foundation-components/lib/global/flex-video';` } </code> </pre> <p> All the props you can set on iframe can also be set on the FlexVideo component. </p> <pre> <code> { `<FlexVideo allowFullScreen frameBorder="0" height="315" src="https://www.youtube.com/embed/V9gkYw35Vws" width="420" />` } </code> </pre> <FlexVideo allowFullScreen frameBorder="0" height="315" src="https://www.youtube.com/embed/V9gkYw35Vws" width="420" /> <p> The default ratio is 4:3. Set the <code>widescreen</code> prop to change it to 16:9. </p> <pre> <code> { `<FlexVideo allowFullScreen frameBorder="0" height="315" src="https://www.youtube.com/embed/aiBt44rrslw" widescreen width="420" />` } </code> </pre> <FlexVideo allowFullScreen frameBorder="0" height="315" src="https://www.youtube.com/embed/aiBt44rrslw" widescreen width="420" /> <p> Embedded Vimeo videos are special snowflakes of their own. Set the <code>vimeo</code> prop to display a Vimeo video. </p> <pre> <code> { `<FlexVideo allowFullScreen frameBorder="0" height="225" src="http://player.vimeo.com/video/60122989" vimeo widescreen width="400" />` } </code> </pre> <FlexVideo allowFullScreen frameBorder="0" height="225" src="http://player.vimeo.com/video/60122989" vimeo widescreen width="400" /> </div> ); export default FlexVideoPage;
app/javascript/flavours/glitch/features/ui/components/actions_modal.js
vahnj/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import StatusContent from 'flavours/glitch/components/status_content'; import Avatar from 'flavours/glitch/components/avatar'; import RelativeTimestamp from 'flavours/glitch/components/relative_timestamp'; import DisplayName from 'flavours/glitch/components/display_name'; import classNames from 'classnames'; import Icon from 'flavours/glitch/components/icon'; import Link from 'flavours/glitch/components/link'; import Toggle from 'react-toggle'; export default class ActionsModal extends ImmutablePureComponent { static propTypes = { status: ImmutablePropTypes.map, actions: PropTypes.arrayOf(PropTypes.shape({ active: PropTypes.bool, href: PropTypes.string, icon: PropTypes.string, meta: PropTypes.node, name: PropTypes.string, on: PropTypes.bool, onClick: PropTypes.func, onPassiveClick: PropTypes.func, text: PropTypes.node, })), }; renderAction = (action, i) => { if (action === null) { return <li key={`sep-${i}`} className='dropdown-menu__separator' />; } const { active, href, icon, meta, name, on, onClick, onPassiveClick, text, } = action; return ( <li key={name || i}> <Link className={classNames('link', { active })} href={href} onClick={on !== null && typeof on !== 'undefined' && onPassiveClick || onClick} role={onClick ? 'button' : null} > {function () { // We render a `<Toggle>` if we were provided an `on` // property, and otherwise show an `<Icon>` if available. switch (true) { case on !== null && typeof on !== 'undefined': return ( <Toggle checked={on} onChange={onPassiveClick || onClick} /> ); case !!icon: return ( <Icon className='icon' fullwidth icon={icon} /> ); default: return null; } }()} {meta ? ( <div> <strong>{text}</strong> {meta} </div> ) : <div>{text}</div>} </Link> </li> ); } render () { const status = this.props.status && ( <div className='status light'> <div className='boost-modal__status-header'> <div className='boost-modal__status-time'> <a href={this.props.status.get('url')} className='status__relative-time' target='_blank' rel='noopener'> <RelativeTimestamp timestamp={this.props.status.get('created_at')} /> </a> </div> <a href={this.props.status.getIn(['account', 'url'])} className='status__display-name'> <div className='status__avatar'> <Avatar account={this.props.status.get('account')} size={48} /> </div> <DisplayName account={this.props.status.get('account')} /> </a> </div> <StatusContent status={this.props.status} /> </div> ); return ( <div className='modal-root__modal actions-modal'> {status} <ul> {this.props.actions.map(this.renderAction)} </ul> </div> ); } }
tests/site3/code2/components/globalProp.js
dominikwilkowski/cuttlebelle
import PropTypes from 'prop-types'; import React from 'react'; /** * The GlobalProp component for section text */ const GlobalProp = ({ _globalProp }) => ( <div> <h2>_globalProp</h2> <dl> <dt>_globalProp.foo:</dt> <dd>{ _globalProp.foo }</dd> <dt>_globalProp.enabled:</dt> <dd>{ _globalProp.enabled ? 'enabled' : 'disabled' }</dd> <dt>_globalProp.howmuch:</dt> <dd>{ _globalProp.howmuch }</dd> </dl> </div> ); GlobalProp.propTypes = {}; GlobalProp.defaultProps = {}; export default GlobalProp;
packages/material-ui-icons/src/CropLandscape.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let CropLandscape = props => <SvgIcon {...props}> <path d="M19 5H5c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 12H5V7h14v10z" /> </SvgIcon>; CropLandscape = pure(CropLandscape); CropLandscape.muiName = 'SvgIcon'; export default CropLandscape;
src/components/ItemList.js
literarymachine/crg-ui
import React from 'react' import PropTypes from 'prop-types' import Icon from './Icon' import Link from './Link' import '../styles/ItemList.pcss' import translate from './translate' const ItemList = ({ translate, listItems }) => ( <ul className="ItemList" > {listItems.map(listItem => ( <li key={listItem.about['@id']}> <Link to={listItem.about['@id']}> <Icon type={listItem.about['@type']} />&nbsp; <span dangerouslySetInnerHTML={{__html: listItem.about.customer ? translate(listItem.about.customer[0].name) || listItem.about['@id'] : translate(listItem.about.name) || listItem.about['@id'] }} /> </Link> </li> ) )} </ul> ) ItemList.propTypes = { translate: PropTypes.func.isRequired, listItems: PropTypes.arrayOf(PropTypes.any).isRequired } export default translate(ItemList)
docs/src/examples/addons/TransitionablePortal/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import Types from './Types' import Usage from './Usage' const TransitionablePortalExamples = () => ( <div> <Types /> <Usage /> </div> ) export default TransitionablePortalExamples
src/components/ChallengeListPage.js
forkhacker/webapp-react
import React from 'react'; import ChallengeCardList from './ChallengeCardList'; import ChallengePageFilter from './ChallengePageFilter'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as challengeActions from '../actions/challengeActions' class ChallengeListPage extends React.Component { constructor(props) { super(props); } componentDidMount() { this.props.actions.listChallenges(); } render() { return ( <div> <ChallengePageFilter/> <ChallengeCardList challenges={this.props.challenges}/> </div> ); } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(challengeActions, dispatch) }; } function mapStateToProps(state) { return { challenges : state.challenge.list, }; } export default connect(mapStateToProps, mapDispatchToProps)(ChallengeListPage);
src/App.js
yberg/react-store
import React from 'react'; import ReactDOM from 'react-dom'; import StoreItem from './StoreItem'; import SearchForm from './SearchForm'; import Cart from './Cart'; import ReactCSSTransitionGroup from 'react-addons-transition-group'; var fields = [ { label: "Product", type: "text", name: "product" }, { label: "Price", type: "text", name: "price", min: "From", max: "To", unit: "kr" }, { label: "Stock", type: "text", name: "stock", min: "From", max: "To", unit: "st" } ]; class App extends React.Component { constructor(props) { super(props); this.state = { filter: '', products: [], cart: [] } this.products = this.state.products; this.cart = this.state.cart; this.search = this.search.bind(this); this.buy = this.buy.bind(this); this.checkout = this.checkout.bind(this); } componentWillMount() { this.firebaseRef = new Firebase("https://react-grocery-store.firebaseio.com/products"); this.firebaseRef.on("child_added", function(dataSnapshot) { this.products.push(dataSnapshot.val()); this.setState({ products: this.products }); }.bind(this)); } componentWillUnmount() { this.firebaseRef.off(); } search(filter) { this.setState({ filter: filter }); } buy(product, fbref) { let found = false; this.cart.map(function(cartItem) { if (cartItem.name === product.name) { cartItem.amount = cartItem.amount + 1; found = true; } }); if (!found) { this.cart.push({ name: product.name, price: product.price, amount: 1 }); } this.setState({ cart: this.cart }); fbref.update({ stock: product.stock - 1 }); } checkout() { this.cart = []; this.setState({ cart: [] }); } render() { var filter = this.state.filter; var buy = this.buy; var firebase = "https://react-grocery-store.firebaseio.com/products/"; return( <div> <ReactCSSTransitionGroup transitionName="animation"> <div id="main"> <div id="form"> <SearchForm search={this.search} title="Search products" fields={fields} value="Search" /> </div> <div id="results"> <h3><span className="glyphicon glyphicon-ok"></span> Results</h3> { this.state.products.map(function(product, i) { if (filter.name === undefined || product.name.toLowerCase().replace(/ /g,'').indexOf(filter.name.toLowerCase().replace(/ /g,'')) !== -1) { if (filter.minPrice === undefined || filter.minPrice <= product.price) { if ((filter.maxPrice === "" || filter.maxPrice === undefined) || filter.maxPrice >= product.price) { if (filter.minStock === undefined || filter.minStock <= product.stock) { if ((filter.maxStock === "" || filter.maxStock === undefined) || filter.maxStock >= product.stock) { return <StoreItem buy={buy} fbref={new Firebase(firebase + product.name)} key={i} product={product} /> } } } } } }) } </div> <div id="cart"> <Cart products={this.state.cart} checkout={this.checkout} /> </div> </div> </ReactCSSTransitionGroup> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
src/web/client/src/components/groups/group.js
devmynd/cloud-access-manager
import React from 'react' import graphqlApi from '../../graphql-api' import lodash from 'lodash' import MessagesContainer from '../shared/messages-container' import DropdownButton from '../shared/dropdown-button' export default class Group extends React.Component { state = { group: null, services: [] } componentWillMount = async () => { const query = `{ group(name: "${this.props.name}") { name serviceAccessRules { service { id displayName roles } accessRules { asset role } } } services(isConfigured: true) { id displayName roles } }` const response = await graphqlApi.request(query) this.setState(response.data) } removeService = (serviceId) => { const group = this.state.group lodash.remove(group.serviceAccessRules, (sar) => sar.service.id === serviceId) this.save(group) } isRoleEnabled = (role, accessRules) => { return !!lodash.find(accessRules, (rule) => rule.asset === '*' && (rule.role === role)) } onRoleClicked = (event, role, serviceId) => { event.target.blur() const group = this.state.group const serviceAccessRule = lodash.find(group.serviceAccessRules, (sar) => sar.service.id === serviceId) const accessRules = serviceAccessRule.accessRules if (this.isRoleEnabled(role, accessRules)) { lodash.remove(accessRules, (rule) => rule.role === role) } else { accessRules.push({asset: '*', role: role}) } this.save(group) } mapGroupToMutation = (group) => { return `mutation { setGroupAccessRules( name:"${group.name}", serviceAccessRules:[${group.serviceAccessRules.map(this.mapServiceAccessRuleToMutation).join(',')}] ) }` } mapServiceAccessRuleToMutation = (serviceAccessRule) => { return `{ serviceId:"${serviceAccessRule.service.id}", accessRules: [${serviceAccessRule.accessRules.map(this.mapAccessRuleToMutation).join(',')}] }` } mapAccessRuleToMutation = (accessRule) => { return `{ asset: "${accessRule.asset}", role: "${accessRule.role}" }` } serviceOptions = () => { const servicesWithoutAccessRules = this.state.services.filter((service) => { const hasAccessRule = !!lodash.find(this.state.group.serviceAccessRules, (sar) => sar.service.id === service.id) return !hasAccessRule }) return servicesWithoutAccessRules.map((s) => { return { text: s.displayName, value: s.id } }) } addService = (serviceId) => { const group = this.state.group const service = lodash.find(this.state.services, (s) => s.id === serviceId) const roles = service.roles.length > 0 ? service.roles : ['*'] const serviceAccessRule = { service, accessRules: roles.map((r) => { return { asset: '*', role: r } }) } group.serviceAccessRules.push(serviceAccessRule) this.save(group) } save = async (group) => { const query = this.mapGroupToMutation(group) let response = await graphqlApi.request(query) if (response.error) { this.messagesContainer.push({ title: 'Error Saving Group', body: response.error.message }) } else { this.setState({ group: group }) } } render () { const servicesWithoutAccessRules = this.state.services.filter((service) => { const hasAccessRule = !!lodash.find(this.state.group.serviceAccessRules, (sar) => sar.service.id === service.id) return !hasAccessRule }) const serviceOptions = servicesWithoutAccessRules.map((s) => { return { text: s.displayName, value: s.id } }) return ( <div> <h1 className='title'>{this.props.name}</h1> { this.state.group && <div> { serviceOptions.length > 0 && <DropdownButton className='is-pulled-right' title='Add Service' options={serviceOptions} onValueSelected={this.addService} /> } <h2 className='subtitle'>Access Rules</h2> <table className='table'> <thead> <tr> <th>Service</th> <th>Roles</th> <th className='has-text-right'>Options</th> </tr> </thead> <tbody> { this.state.group.serviceAccessRules.map((serviceAccessRule) => ( <tr key={serviceAccessRule.service.id}> <td>{serviceAccessRule.service.displayName}</td> <td> <div className='field is-grouped'> {serviceAccessRule.service.roles.map((role) => ( <div key={role} className='control'> <button className={`button is-primary ${this.isRoleEnabled(role, serviceAccessRule.accessRules) ? '' : 'is-outlined'}`} onClick={(e) => this.onRoleClicked(e, role, serviceAccessRule.service.id)}> {role} </button> </div> ))} </div> </td> <td> <div className='field is-grouped is-grouped-right'> <div className='control'> <button className='button is-small is-danger' onClick={() => this.removeService(serviceAccessRule.service.id)}> Remove Service </button> </div> </div> </td> </tr> )) } </tbody> </table> </div> } <MessagesContainer ref={(container) => { this.messagesContainer = container }} /> </div> ) } }
actor-apps/app-web/src/app/components/activity/UserProfileContactInfo.react.js
zomeelee/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class UserProfileContactInfo extends React.Component { static propTypes = { phones: React.PropTypes.array }; constructor(props) { super(props); } render() { let phones = this.props.phones; let contactPhones = _.map(phones, (phone, i) => { return ( <li className="profile__list__item row" key={i}> <i className="material-icons">call</i> <div className="col-xs"> <span className="contact">+{phone.number}</span> <span className="title">{phone.title}</span> </div> </li> ); }); return ( <ul className="profile__list profile__list--contacts"> {contactPhones} </ul> ); } } export default UserProfileContactInfo;
example/components/Row.js
travelbird/react-native-navigation
import React from 'react'; import PropTypes from 'prop-types'; import { View, Text, Image, StyleSheet, } from 'react-native'; import BaseRow from './BaseRow'; import theme from '../util/theme'; const propTypes = { title: PropTypes.string.isRequired, subtitle: PropTypes.string, onPress: PropTypes.func, }; const defaultProps = { }; export default class Row extends React.Component { render() { const { title, subtitle, onPress, } = this.props; return ( <BaseRow onPress={onPress}> <View style={styles.content}> <View style={styles.titleContainer}> <Text style={styles.title}> {title} </Text> {!!subtitle && ( <Text style={styles.subtitle}> {subtitle} </Text> )} </View> {onPress && ( <Image source={require('../icons/chevron_right.png')} style={{ width: 24, height: 24, opacity: 0.5, }} /> )} </View> </BaseRow> ); } } Row.defaultProps = defaultProps; Row.propTypes = propTypes; const styles = StyleSheet.create({ content: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', marginVertical: 8, }, contentTween: { marginVertical: 24, }, loadingContainer: { flex: 0, }, titleContainer: { flex: 1, }, title: theme.font.large, subtitle: { ...theme.font.small, marginTop: 4, }, icon: { marginTop: 0.4 * 8, }, });
src/pages/work/ostmodern.js
jcmnunes/josenunesxyz
import React from 'react'; import { graphql } from 'gatsby'; import Img from 'gatsby-image'; import SingleLayout from '../../components/layouts/singleLayout'; import { Anchor } from '../../components/Anchor'; export default ({ data }) => ( <SingleLayout title="Ostmodern / Formula 1" subTitle="Frontend developer" auxInfo="Jan 2019 - Mar 2019" techs={[ 'React', 'Redux', 'RxJS/redux-observable', 'Sass', 'CSS Modules', 'Jest', 'Enzyme', 'ESLint', 'Webpack', ]} > <p> Ostmodern (<Anchor href="https://www.ostmodern.co.uk/">www.ostmodern.co.uk</Anchor>), a London based company, are digital product designers and content delivery experts specializing in video-centric products. Ostmodern’s client list includes big names, such as Arsenal FC, BBC and Formula 1. </p> <figure> <Img fluid={data.f1tvApp.childImageSharp.fluid} /> <figcaption>Homepage of F1TV web app.</figcaption> </figure> <p> At Ostmodern, I worked as a frontend web developer, integrated into the web team (a multidisciplinary Scrum team) responsible for developing and maintaining the{' '} <Anchor href="https://f1tv.formula1.com">F1TV web app</Anchor>. </p> <figure> <Img fluid={data.f1tvAppLeaderboard.childImageSharp.fluid} /> <figcaption> F1TV web app leaderboard. The leaderboard updates in real-time, even for replays. </figcaption> </figure> <p> On the Frontend side, the F1TV app is a React/Redux SPA. The app uses the redux-observable package to handle async actions. Most of the code is covered by unit-tests, using Jest and Enzyme. CSS Modules and SASS are responsible for the styling. </p> </SingleLayout> ); export const query = graphql` query ostmodernPage { f1tvApp: file(relativePath: { eq: "f1tv-app.png" }) { childImageSharp { fluid(maxWidth: 716) { ...GatsbyImageSharpFluid } } } f1tvAppLeaderboard: file(relativePath: { eq: "f1tvapp-leaderboard.png" }) { childImageSharp { fluid(maxWidth: 716) { ...GatsbyImageSharpFluid } } } } `;
src/client/components/message/chatSendShortcut.js
uuchat/uuchat
import React, { Component } from 'react'; import '../../static/css/shortcut.css'; let Shortcut = { data: [], newScObj: {}, init: function () { if (this.data.length > 0) { let newSc = localStorage.getItem("newShortcut"); if (newSc){ this.newScObj = JSON.parse(newSc); switch (this.newScObj.action) { case "INSERT": this.insert(); break; case "UPDATE": this.update(); break; case "DELETE": this.delete(); break; default: break; } localStorage.setItem('newShortcut', ""); localStorage.setItem("shortcutList", JSON.stringify(Shortcut.data)); } } }, get: function(){ return this.data; }, set: function(data){ this.data = data; localStorage.setItem("shortcutList", JSON.stringify(data)); }, insert: function(){ this.data.unshift(this.newScObj); }, update: function(){ for (let i = 0, l = this.data.length; i < l; i++) { if (this.data[i].id === this.newScObj.id) { this.data[i] = this.newScObj; } } }, delete: function(){ let index = 0; for (let i = 0, l = this.data.length; i < l; i++) { if (this.data[i].id === this.newScObj.id) { index = i; } } this.data.splice(index, 1); } }; class ShortList extends Component{ selectClick = (e) => { e.stopPropagation(); this.props.shortCutSelecterClick(document.querySelector('.s-'+this.props.num+' .key-value').innerHTML); }; mouseoverHandle = (e) => { let shortcutList = document.querySelectorAll('.shortListUl li'); let tg = e.target; for (let i = 0, l = shortcutList.length; i < l; i++) { shortcutList[i].className = 's-'+i; } if (tg.tagName.toLowerCase() === 'li') { tg.className += ' on'; this.props.shortcutMouseover(tg.getAttribute('data-num')); } }; render(){ let {num, name, value} = this.props; return ( <li className={'s-'+num+(num === 0 ? ' on' : '')} onClick={this.selectClick} data-num={num} onMouseOver={this.mouseoverHandle}> <span className="key-name">{';'+name}</span> <span className="key-value">{value.replace(/(^\s*)/g, '')}</span> </li> ); } } class ShortEmpty extends Component{ render(){ return ( <div className="short-empty"> You have not setting Shortcuts, you can setting some on the settings tab. </div> ); } } class ChatShortcut extends Component{ constructor(){ super(); this.state = { fetchList: [] }; } componentDidMount(){ this.getShortCutsList(); } getShortCutsList = () => { let _self = this; let shortcutData = []; Shortcut.init(); shortcutData = Shortcut.get(); if (shortcutData.length > 0) { this.setState({ fetchList: shortcutData }); return false; } fetch('/shortcuts/cs/'+this.props.csid+'/all') .then((d)=>d.json()) .then((data)=>{ if (data.code === 200) { Shortcut.set(data.msg); _self.setState({ fetchList: data.msg }); } }) .catch((e)=>{}); }; render(){ let {fetchList} = this.state; let {matchText, shortcutSelectClick, shortcutMouseover} = this.props; let shortListArr = []; for (let i = 0, l = fetchList.length; i < l; i++) { let matchReg= new RegExp(matchText.slice(1), 'ig'), s = fetchList[i]; if (matchReg.test(s.shortcut)) { shortListArr.push(s); } } return ( <div className="shortcut"> <div className="short-head"> <span className="navigate-shortcuts">Navigate ↑ and ↓</span> <span className="hotkey-shortcuts"> &nbsp; &nbsp;<strong>Enter</strong> or <strong>Tab</strong> to select </span> </div> <div className="short-list"> <ul className="shortListUl"> {shortListArr.map((s, i)=> <ShortList key={i} num={i} name={s.shortcut} value={s.msg} shortCutSelecterClick={shortcutSelectClick} shortcutMouseover={shortcutMouseover} /> )} </ul> </div> {(shortListArr.length === 0) && <ShortEmpty />} </div> ); } } export default ChatShortcut;
src/parser/monk/brewmaster/modules/core/MasteryValue.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import HIT_TYPES from 'game/HIT_TYPES'; import Analyzer from 'parser/core/Analyzer'; import { EventType } from 'parser/core/Events'; import StatTracker from 'parser/shared/modules/StatTracker'; import LazyLoadStatisticBox from 'interface/others/LazyLoadStatisticBox'; import SpellIcon from 'common/SpellIcon'; import { formatNumber, formatPercentage } from 'common/format'; import OneVariableBinomialChart from 'interface/others/charts/OneVariableBinomialChart'; import DamageTaken from './DamageTaken'; import GiftOfTheOx from '../spells/GiftOfTheOx'; // coefficients to calculate dodge chance from agility const MONK_DODGE_COEFFS = { base_dodge: 3, base_agi: 1468, // names of individual coefficients are taken from ancient lore, err, // formulae P: 452.27, D: 80, v: 0.01, h: 1.06382978723, }; function _clampProb(prob) { if (prob > 1.0) { return 1.0; } else if (prob < 0.0) { return 0.0; } else { return prob; } } /** * This class represents the Markov Chain with which the Mastery stacks * are modeled. The transition probabilities are defined by two * potential operations: * * 1. Guaranteed Addition: from using an ability that generates a stack * 100% of the time (e.g. BoS, BoF). The probability of having i stacks * afterward is equal to the probability of having i-1 stacks before * (the probability of having 0 stacks afterward is 0). * * 2. Attack: The probability of having i > 0 stacks afterward is equal to * the probability of being hit with i - 1 stacks. The probability of * having 0 stacks afterward is the sum of the probabilities of dodging * with each number of stacks. Note that there is a natural cap on the * number of stacks you can reach, since after that point every hit will * be a dodge. * * The expected number of stacks you have is just the sum of the indices * weighted by the values. */ class StackMarkovChain { _stackProbs = [1.0]; _assertSum() { const sum = this._stackProbs.reduce((sum, p) => p + sum, 0); if (Math.abs(sum - 1.0) > 1e-6) { const err = new Error('probabilities do not sum to 1 in StackMarkovChain'); err.data = { sum: sum, probs: this._stackProbs, }; console.log(err.data); throw err; } } // add a stack with guaranteed probability guaranteeStack() { this._stackProbs.unshift(0.0); this._assertSum(); } processAttack(baseDodgeProb, masteryValue) { this._stackProbs.push(0); const n = this._stackProbs.length - 1; // probability of ending at 0 stacks. initial let zeroProb = 0; // didn't dodge, gain a stack for (let stacks = n - 1; stacks >= 0; stacks--) { const prob = _clampProb(baseDodgeProb + masteryValue * stacks); zeroProb += prob * this._stackProbs[stacks]; // dodge -> go to 0 const hitProb = 1 - prob; this._stackProbs[stacks + 1] = hitProb * this._stackProbs[stacks]; // hit -> go to stacks + 1 } // did dodge, reset stacks this._stackProbs[0] = zeroProb; this._assertSum(); } get expected() { return this._stackProbs.reduce((sum, prob, index) => sum + prob * index, 0); } } export function baseDodge(agility, dodgeRating = 0) { const base = MONK_DODGE_COEFFS.base_dodge + MONK_DODGE_COEFFS.base_agi / MONK_DODGE_COEFFS.P; const chance = (agility - MONK_DODGE_COEFFS.base_agi) / MONK_DODGE_COEFFS.P + dodgeRating / MONK_DODGE_COEFFS.D; // the x / (x + k) formula is commonly used by the wow team to // implement diminishing returns return (base + chance / (chance * MONK_DODGE_COEFFS.v + MONK_DODGE_COEFFS.h)) / 100; } /** * Estimate the expected value of mastery on this fight. The *actual* * estimated value is subject to greater variance. * On the other hand, the expected value averages over all * possible outcomes and gives a better sense of how valuable mastery is * if you were to do this fight again. This values more stable over * repeated attempts or kills and reflects the value of mastery (and the * execution of the rotation) more closely than how well-favored you * were on this particular attempt. * * We calculate the expected value by applying the Markov Chain above to * the timeline to calculate the expected number of stacks at each * dodgeable event. This is then combined with information about the * expected damage of each dodged hit (dodge events have amount: 0, * absorbed: 0, etc.) to provide a best-guess estimate of the damage * you'll mitigate on average. The actual estimate (shown in the * tooltip) may be over or under this, but is unlikely to be far from * it. * * This madness was authored by emallson. If you need further explanation of * the theory behind it, find me on discord. */ class MasteryValue extends Analyzer { static dependencies = { dmg: DamageTaken, stats: StatTracker, gotox: GiftOfTheOx, }; _loaded = false; _dodgeableSpells = {}; _timeline = []; _hitCounts = {}; _dodgeCounts = {}; dodgePenalty(_source) { return 0.045; // 1.5% per level, bosses are three levels over players. not sure how to get trash levels yet -- may not matter } // returns the current chance to dodge a damage event assuming the // event is dodgeable dodgeChance(masteryStacks, masteryRating, agility, sourceID, timestamp = null) { const masteryPercentage = this.stats.masteryPercentage(masteryRating, true); return _clampProb(masteryPercentage * masteryStacks + baseDodge(agility) - this.dodgePenalty(sourceID)); } on_byPlayer_cast(event) { if (this._stacksApplied(event) > 0) { this._timeline.push(event); } } on_toPlayer_damage(event) { event._masteryRating = this.stats.currentMasteryRating; event._agility = this.stats.currentAgilityRating; if (event.hitType === HIT_TYPES.DODGE) { this._addDodge(event); } else { this._addHit(event); } } _addDodge(event) { const spellId = event.ability.guid; this._dodgeableSpells[spellId] = true; if (this._dodgeCounts[spellId] === undefined) { this._dodgeCounts[spellId] = 0; } this._dodgeCounts[spellId] += 1; this._timeline.push(event); } _addHit(event) { const spellId = event.ability.guid; if (this._hitCounts[spellId] === undefined) { this._hitCounts[spellId] = 0; } this._hitCounts[spellId] += 1; this._timeline.push(event); } // returns true of the event represents a cast that applies a stack of // mastery _stacksApplied(event) { if(event.ability.guid !== SPELLS.BLACKOUT_STRIKE.id) { return 0; } let stacks = 1; // account for elusive footwork if(this.selectedCombatant.hasTrait(SPELLS.ELUSIVE_FOOTWORK.id) && event.hitType === HIT_TYPES.CRIT) { stacks += 1; } return stacks; } meanHitByAbility(spellId) { if (this._hitCounts[spellId] !== undefined) { return (this.dmg.byAbility(spellId).effective + this.dmg.staggeredByAbility(spellId)) / this._hitCounts[spellId]; } return 0; } // events that either (a) add a stack or (b) can be dodged according // to the data we have get relevantTimeline() { return this._timeline.filter(event => event.type === EventType.Cast || this._dodgeableSpells[event.ability.guid]); } _expectedValues = { expectedDamageMitigated: 0, estimatedDamageMitigated: 0, meanExpectedDodge: 0, noMasteryExpectedDamageMitigated: 0, noMasteryMeanExpectedDodge: 0, noAgiExpectedDamageMitigated: 0, }; _calculateExpectedValues() { // expected damage mitigated according to the markov chain let expectedDamageMitigated = 0; let noMasteryExpectedDamageMitigated = 0; let noAgiExpectedDamageMitigated = 0; // estimate of the damage that was actually dodged in this log let estimatedDamageMitigated = 0; // average dodge % across each event that could be dodged let meanExpectedDodge = 0; let noMasteryMeanExpectedDodge = 0; let dodgeableEvents = 0; const stacks = new StackMarkovChain(); // mutating a const object irks me to no end const noMasteryStacks = new StackMarkovChain(); const noAgiStacks = new StackMarkovChain(); // timeline replay is expensive, compute several things here and // provide individual getters for each of the values this.relevantTimeline.forEach(event => { if (event.type === EventType.Cast) { const eventStacks = this._stacksApplied(event); for(let i = 0; i < eventStacks; i++) { stacks.guaranteeStack(); noMasteryStacks.guaranteeStack(); noAgiStacks.guaranteeStack(); } } else if (event.type === EventType.Damage) { const noMasteryDodgeChance = this.dodgeChance(noMasteryStacks.expected, 0, event._agility, event.sourceID, event.timestamp); const noAgiDodgeChance = this.dodgeChance(noAgiStacks.expected, event._masteryRating, MONK_DODGE_COEFFS.base_agi, event.sourceID, event.timestamp); const expectedDodgeChance = this.dodgeChance(stacks.expected, event._masteryRating, event._agility, event.sourceID, event.timestamp); const baseDodgeChance = this.dodgeChance(0, 0, event._agility, event.sourceID, event.timestamp); const noAgiBaseDodgeChance = this.dodgeChance(0, 0, MONK_DODGE_COEFFS.base_agi, event.sourceID, event.timestamp); const damage = (event.amount + event.absorbed) || this.meanHitByAbility(event.ability.guid); expectedDamageMitigated += expectedDodgeChance * damage; noMasteryExpectedDamageMitigated += noMasteryDodgeChance * damage; noAgiExpectedDamageMitigated += noAgiDodgeChance * damage; estimatedDamageMitigated += (event.hitType === HIT_TYPES.DODGE) * damage; meanExpectedDodge += expectedDodgeChance; noMasteryMeanExpectedDodge += noMasteryDodgeChance; dodgeableEvents += 1; stacks.processAttack(baseDodgeChance, this.stats.masteryPercentage(event._masteryRating, true)); noAgiStacks.processAttack(noAgiBaseDodgeChance, this.stats.masteryPercentage(event._masteryRating, true)); noMasteryStacks.processAttack(baseDodgeChance, this.stats.masteryPercentage(0, true)); } }); meanExpectedDodge /= dodgeableEvents; noMasteryMeanExpectedDodge /= dodgeableEvents; return { expectedDamageMitigated, estimatedDamageMitigated, meanExpectedDodge, noMasteryExpectedDamageMitigated, noMasteryMeanExpectedDodge, noAgiExpectedDamageMitigated, }; } get expectedMitigation() { return this._expectedValues.expectedDamageMitigated; } get expectedMeanDodge() { return this._expectedValues.meanExpectedDodge; } get noMasteryExpectedMeanDodge() { return this._expectedValues.noMasteryMeanExpectedDodge; } get totalDodges() { return Object.keys(this._dodgeableSpells).reduce((sum, spellId) => sum + this._dodgeCounts[spellId], 0); } get totalDodgeableHits() { return Object.keys(this._dodgeableSpells).reduce((sum, spellId) => sum + (this._hitCounts[spellId] || 0), 0) + this.totalDodges; } get actualDodgeRate() { return this.totalDodges / this.totalDodgeableHits; } get estimatedActualMitigation() { return this._expectedValues.estimatedDamageMitigated; } get averageMasteryRating() { return this.relevantTimeline.reduce((sum, event) => { if (event.type === EventType.Damage) { return event._masteryRating + sum; } else { return sum; } }, 0) / this.relevantTimeline.filter(event => event.type === EventType.Damage).length; } get noMasteryExpectedMitigation() { return this._expectedValues.noMasteryExpectedDamageMitigated; } get noAgiExpectedDamageMitigated() { return this._expectedValues.noAgiExpectedDamageMitigated; } get expectedMitigationPerSecond() { return this.expectedMitigation / this.owner.fightDuration * 1000; } get noMasteryExpectedMitigationPerSecond() { return this.noMasteryExpectedMitigation / this.owner.fightDuration * 1000; } get totalMasteryHealing() { return this.gotox.masteryBonusHealing; } get plot() { // not the most efficient, but close enough and pretty safe function binom(n, k) { if(k > n) { return null; } if(k === 0) { return 1; } return n / k * binom(n-1, k-1); } // pmf of the binomial distribution with n = totalDodgeableHits and // p = expectedMeanDodge const dodgeProb = (i) => binom(this.totalDodgeableHits, i) * Math.pow(this.expectedMeanDodge, i) * Math.pow(1 - this.expectedMeanDodge, this.totalDodgeableHits - i); // probability of having dodge exactly k of the n incoming hits // assuming the expected mean dodge % is the true mean dodge % const dodgeProbs = Array.from({length: this.totalDodgeableHits}, (_x, i) => { return { x: i, y: dodgeProb(i) }; }); const actualDodge = { x: this.totalDodges, y: dodgeProb(this.totalDodges), }; return ( <OneVariableBinomialChart probabilities={dodgeProbs} actualEvent={actualDodge} yDomain={[0, 0.4]} xAxis={{ title: 'Dodge %', tickFormat: (value) => `${formatPercentage(value / this.totalDodgeableHits, 0)}%`, }} tooltip={(point) => `Actual Dodge: ${formatPercentage(point.x / this.totalDodgeableHits, 2)}%`} /> ); } load() { this._loaded = true; this._expectedValues = this._calculateExpectedValues(); return Promise.resolve(this._expectedValues); } statistic() { return ( <LazyLoadStatisticBox loader={this.load.bind(this)} icon={<SpellIcon id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} />} value={`${formatNumber(this.expectedMitigationPerSecond - this.noMasteryExpectedMitigationPerSecond)} DTPS`} label="Expected Mitigation by Mastery" tooltip={this._loaded ? ( <> On average, you would dodge about <strong>{formatNumber(this.expectedMitigation)}</strong> damage on this fight. This value was increased by about <strong>{formatNumber(this.expectedMitigation - this.noMasteryExpectedMitigation)}</strong> due to Mastery. You had an average expected dodge chance of <strong>{formatPercentage(this.expectedMeanDodge)}%</strong> and actually dodged about <strong>{formatNumber(this.estimatedActualMitigation)}</strong> damage with an overall rate of <strong>{formatPercentage(this.actualDodgeRate)}%</strong>. This amounts to an expected reduction of <strong>{formatNumber((this.expectedMitigationPerSecond - this.noMasteryExpectedMitigationPerSecond) / this.averageMasteryRating)} DTPS per 1 Mastery</strong> <em>on this fight</em>.<br /><br /> <em>Technical Information:</em><br /> <strong>Estimated Actual Damage</strong> is calculated by calculating the average damage per hit of an ability, then multiplying that by the number of times you dodged each ability.<br /> <strong>Expected</strong> values are calculated by computing the expected number of mastery stacks each time you <em>could</em> dodge an ability.<br /> An ability is considered <strong>dodgeable</strong> if you dodged it at least once. </> ) : null} > <div style={{padding: '8px'}}> {this._loaded ? this.plot : null} <p>Likelihood of dodging <em>exactly</em> as much as you did with your level of Mastery.</p> </div> </LazyLoadStatisticBox> ); } } export default MasteryValue;
src/components/Box.js
hbuchel/heather-buchel.com
import React from 'react'; import PropTypes from 'prop-types'; import { css } from '@emotion/core'; const Box = ({children, padding, as, className}) => { let El = as; const box = css` padding: calc(var(--gap) * ${padding}); & > *:first-child { margin-top: 0; } & > *:last-child { margin-bottom: 0; } ` return( <El css={box} className={className}> { children } </El> ) } Box.propTypes = { padding: PropTypes.string, as: PropTypes.oneOf([ 'header', 'div', 'footer', 'aside' ]) } Box.defaultProps = { padding: "0", as: "div" } export default Box;
client/components/Main.js
kmrigendra/think-analytics-app
import React from 'react'; import { Link } from 'react-router'; import Header from './Header'; const Main = React.createClass({ render() { // Then we go ahead and return some JSX return ( <div> <Header /> {/* We use cloneElement here so we can auto pass down props */} { React.cloneElement(this.props.children, this.props) } </div> ); } }); export default Main;
packages/material-ui-icons/src/ImageAspectRatio.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let ImageAspectRatio = props => <SvgIcon {...props}> <path d="M16 10h-2v2h2v-2zm0 4h-2v2h2v-2zm-8-4H6v2h2v-2zm4 0h-2v2h2v-2zm8-6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h16v12z" /> </SvgIcon>; ImageAspectRatio = pure(ImageAspectRatio); ImageAspectRatio.muiName = 'SvgIcon'; export default ImageAspectRatio;
src/components/common/svg-icons/action/all-out.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAllOut = (props) => ( <SvgIcon {...props}> <path d="M16.21 4.16l4 4v-4zm4 12l-4 4h4zm-12 4l-4-4v4zm-4-12l4-4h-4zm12.95-.95c-2.73-2.73-7.17-2.73-9.9 0s-2.73 7.17 0 9.9 7.17 2.73 9.9 0 2.73-7.16 0-9.9zm-1.1 8.8c-2.13 2.13-5.57 2.13-7.7 0s-2.13-5.57 0-7.7 5.57-2.13 7.7 0 2.13 5.57 0 7.7z"/> </SvgIcon> ); ActionAllOut = pure(ActionAllOut); ActionAllOut.displayName = 'ActionAllOut'; ActionAllOut.muiName = 'SvgIcon'; export default ActionAllOut;
packages/react-server-examples/bike-share/pages/index.js
emecell/react-server
import React from 'react'; import {ReactServerAgent, RootElement, TheFold, logging} from 'react-server'; import NetworkList from '../components/network-list'; import Header from '../components/header'; import Footer from '../components/footer'; import '../styles/index.scss'; const logger = logging.getLogger(__LOGGER__); export default class IndexPage { handleRoute(next) { logger.info('handling index'); this.data = ReactServerAgent.get('/api/networks').then(d => d.body); return next(); } getTitle() { return 'React Server Bike Share'; } getElements() { return [ <RootElement key={0}> <Header/> </RootElement>, <RootElement when={this.data} key={1}> <NetworkList/> </RootElement>, <TheFold key={2}/>, <RootElement key={3}> <Footer/> </RootElement>, ]; } getMetaTags() { return [ {charset: 'utf8'}, {name: 'description', content: 'Bike share availability by city, powered by React Server'}, {generator: 'React Server'}, {keywords: 'React Server bike share'}, ]; } getBodyClasses() { return ['page-body']; } }
ui/components/LogicForm.js
yih-en/data-triangulation-tool
import React, { Component } from 'react'; import { reduxForm } from 'redux-form'; import fieldComponent from './FieldComponent'; import * as Input from './Input'; import brace from 'brace'; import AceEditor from 'react-ace'; import 'brace/mode/sql'; import 'brace/theme/monokai'; var _ = require('lodash'); const TextField = fieldComponent(Input.TextInput); const SelectField = fieldComponent(Input.SelectInput); export default class LogicForm extends Component { generateOptionList(info) { let result = [] _.map(info.connectionInfo, (el, index) => { result.push([el[0], el[1]]) }) return result } renderQueryType() { const { logic_type, connection_name, name, description, query, transforms, changeLogicType } = this.props return ( <div> <TextField label="Name" className="inline-form form-input" {...name}></TextField> <TextField label="Description" className="inline-form" {...description}></TextField> { this.props.connectionInfo && <SelectField label="Database" className="form-input" optionList={this.generateOptionList(this.props.connectionInfo)} {...connection_name}> </SelectField> } <div className="editor"> <AceEditor mode="sql" theme="monokai" name="query" editorProps={{$blockScrolling: true}} showPrintMargin={true} {...query} /> </div> </div> ) } renderTransformType() { const { transform, name } = this.props return ( <div className="form-input"> <div> <TextField label="Name" className="inline-form" {...name} > </TextField> <TextField label="Transform" className="inline-form" {...transform}> </TextField> </div> </div> ) } render() { return( <div> { this.props.logic_type.value == 'sql' && this.renderQueryType() } { this.props.logic_type.value == 'transformation' && this.renderTransformType() } </div> ) } }
docs/src/pages/customization/components/ClassNames.js
lgollut/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import Button from '@material-ui/core/Button'; import { withStyles } from '@material-ui/core/styles'; // We can inject some CSS into the DOM. const styles = { root: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }, }; function ClassNames(props) { const { classes, children, className, ...other } = props; return ( <Button className={clsx(classes.root, className)} {...other}> {children || 'class names'} </Button> ); } ClassNames.propTypes = { children: PropTypes.node, classes: PropTypes.object.isRequired, className: PropTypes.string, }; export default withStyles(styles)(ClassNames);
src/widgets/EmailSubscriber/DefaultLayout/ActiveView.js
mydearxym/mastani
import React from 'react' import { ICON } from '@/config' import { Wrapper, SignIcon, Title, Desc, SubscribeInput, SubscribeBtnWrapper, SubscribeBtn, Cancel, } from '../styles/default_layout/active_view' const ActiveView = ({ title, desc, onCancel }) => { return ( <Wrapper> <SignIcon src={`${ICON}/subscribe/email-envelope.svg`} /> <Title>{title}</Title> <Desc>{desc}</Desc> <SubscribeInput placeholder="邮件地址" /> <SubscribeBtnWrapper> <Cancel onClick={() => { onCancel() }} > 以后再说 </Cancel> <SubscribeBtn size="tiny" disabled> 订&nbsp;阅 </SubscribeBtn> </SubscribeBtnWrapper> </Wrapper> ) } export default ActiveView
src/modules/depth/index.js
fanfanlala/ZUO-React
import React from 'react' import ReactDom from 'react-dom' import App from './App' ReactDom.render( <App />, document.getElementById('depth') )
src/svg-icons/action/find-replace.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionFindReplace = (props) => ( <SvgIcon {...props}> <path d="M11 6c1.38 0 2.63.56 3.54 1.46L12 10h6V4l-2.05 2.05C14.68 4.78 12.93 4 11 4c-3.53 0-6.43 2.61-6.92 6H6.1c.46-2.28 2.48-4 4.9-4zm5.64 9.14c.66-.9 1.12-1.97 1.28-3.14H15.9c-.46 2.28-2.48 4-4.9 4-1.38 0-2.63-.56-3.54-1.46L10 12H4v6l2.05-2.05C7.32 17.22 9.07 18 11 18c1.55 0 2.98-.51 4.14-1.36L20 21.49 21.49 20l-4.85-4.86z"/> </SvgIcon> ); ActionFindReplace = pure(ActionFindReplace); ActionFindReplace.displayName = 'ActionFindReplace'; ActionFindReplace.muiName = 'SvgIcon'; export default ActionFindReplace;
resources/src/js/sections/Top/index.js
aberon10/thermomusic.com
'use strict'; import React from 'react'; import Ajax from '../../Libs/Ajax'; import {Link} from 'react-router-dom'; import Notification from '../../components/Notification/index'; import inFavorites from '../Explorer/components/util'; import ContentSpacing from '../../components/Containers/ContentSpacing'; import MainContent from '../../components/Main/index'; import TrackList from '../components/TrackList'; import { checkXMLHTTPResponse } from '../../app/utils/Utils'; class Top extends React.Component { constructor(props) { super(props); this.state = { element: <h1>Top 10</h1> }; Top.createContent = Top.createContent.bind(this); } componentDidMount() { Ajax.post({ url: '/music/top', responseType: 'json', data: null }).then((response) => { checkXMLHTTPResponse(response); this.setState({ element: Top.createContent(response) }); }).catch((error) => { console.log(error); }); } static createContent(response) { let element = <Notification message={ <Link to='/user' style={{color: '#fff'}}> No hay datos disponibles. </Link> } classes='blue' />; if (response.data && response.data.length) { let data = response.data; let favorites = response.favorites; let tracks = []; data.forEach((item) => { tracks.push({ id: item.id_cancion, src: item.src_audio, trackName: item.nombre_cancion, duration: item.duracion, counter: item.contador, srcAlbum: encodeURI(item.src_img), artist: `por ${item.nombre_artista}`, playlist: false, idPlaylist: false, favorite: inFavorites(favorites, item.id_cancion), inFavoritePage: false }); }); element = ( <MainContent> <ContentSpacing title="Top 10"> <div className="album-container"> <div className="album-container__content"> <TrackList data={tracks} /> </div> </div> </ContentSpacing> </MainContent> ); } return element; } render() { return ( <div>{this.state.element}</div> ); } } export default Top;
client/src/components/dashboard/messaging/reply-message.js
ronniehedrick/scapeshift
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Field, reduxForm } from 'redux-form'; import { sendReply } from '../../../actions/messaging'; const form = reduxForm({ form: 'replyMessage', }); const renderField = field => ( <div> <input className="form-control" autoComplete="off" {...field.input} /> </div> ); class ReplyMessage extends Component { handleFormSubmit(formProps) { this.props.sendReply(this.props.replyTo, formProps); } renderAlert() { if (this.props.errorMessage) { return ( <div className="alert alert-danger"> <strong>Oops!</strong> {this.props.errorMessage} </div> ); } else if (this.props.message) { return ( <div className="alert alert-success"> <strong>Success!</strong> {this.props.message} </div> ); } } render() { const { handleSubmit } = this.props; return ( <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}> {this.renderAlert()} <Field name="composedMessage" className="form-control" component={renderField} type="text" placeholder="Type here to chat..." /> <button action="submit" className="btn btn-primary">Send</button> </form> ); } } function mapStateToProps(state) { return { recipients: state.communication.recipients, errorMessage: state.communication.error, }; } export default connect(mapStateToProps, { sendReply })(form(ReplyMessage));
public/js/components/trends/TrendContainer.react.js
IsuruDilhan/Coupley
import React from 'react'; import List from 'material-ui/lib/lists/list'; import Divider from 'material-ui/lib/divider'; import TextField from 'material-ui/lib/text-field'; import TrendsStore from '../../stores/TrendsStore'; import TrendsAction from '../../actions/TrendsAction'; import Trend from './trendbox.react'; import TrendPost from './trendactivityListComp.react'; var SearchCeck = true; var listClick = true; const style1={ width:200, height:300, }; const searchconvo = { marginTop:'-18', paddingLeft:10, paddingRight:50, width:150, }; function validateStatusText(textStatus) { if (textStatus.length > 250) { return { error: '*search is too long', }; } else if (textStatus.length == 0) { console.log('empty'); return { error: '*search cannot be empty', }; } else { return true; } }; const TrendContainer = React.createClass({ getInitialState: function() { return { trendsResult:TrendsStore.gettrendslist(), statusText: '', value:'', trendsPostResult:TrendsStore.getFirstTrendsSearchPost(), } }, componentDidMount: function() { TrendsStore.addChangeListener(this._onChange); TrendsAction.getTrendsList(); TrendsAction.getTrendsInitialSearchPosts(); }, _onChange: function () { if (SearchCeck) { this.setState({trendsResult:TrendsStore.gettrendslist()}); } else if (!SearchCeck) { this.setState({ trendsResult:TrendsStore.getTrendsSearchList()}); } this.setState({ trendsPostResult:TrendsStore. getFirstTrendsSearchPost()}); }, trendItem: function () { return this.state.trendsResult.map((result) => { return (<Trend abc={this.getHashtag} trends={result.trend} tid={result.id}/>); }); }, SearchTren:function () { var trd=this.refs.SearchT.getValue(); let ThisTrend ={ trend:trd, } console.log(ThisTrend.trend); if (validateStatusText(ThisTrend).error) { console.log('menna error'); this.setState({ statusText: validateStatusText(ThisTrend).error, }); val = false; } else { console.log('error na'); TrendsAction.getTrendsSearchList(ThisTrend); SearchCeck = false; this.setState({ statusText: '', }); } {this.trendSearchItem();} {this.clearText();} }, getHashtag:function (e) { console.log('clicked'); var E= e.substr(1); let trend={ strend:E, }; console.log(E); TrendsAction.getTrendsSearchPosts(trend); }, trendSearchItem: function () { this.setState({ trendsResult:TrendsStore.getTrendsSearchList()}); console.log('menna result'); console.log(this.state.trendsResult); return this.state.trendsResult.map((result) => { return (<Trend trends={result.trend} tid={result.id}/>); }); }, trendPostItem: function () { return this.state.trendsPostResult.map((result) => { return (<TrendPost firstName={result.firstname} postText={result.post_text} created_at={result.created_at}/>); }); }, clearText:function () { document.getElementById('SearchField').value = ''; }, EnterKey(e) { if (e.key === 'Enter') { console.log('enter una'); {this.SearchTren();} } }, render:function(){ return( <div> <div style={style1} className="col-xs-4"> <List zDepth={1}> <div><h4>Trends</h4></div> <Divider/> <div> <TextField hintText="#Trends" floatingLabelText="Search Trends" style={searchconvo} errorText={this.state.statusText} onKeyPress={this.EnterKey} ref="SearchT" id="SearchField"/> </div> <Divider/> {this.trendItem()} </List> </div> <div className="col-xs-8"> {this.trendPostItem()} </div> </div> ); } }); export default TrendContainer;
src/App.js
Jalissa/rss-feed-client
import React, { Component } from 'react'; import Header from './components/Header'; class App extends Component { render() { return ( <div> <Header/> <div className="container"> {this.props.children} </div> </div> ); } } export default App;
definitions/npm/react-css-collapse_v3.x.x/flow_v0.54.1-/test_react-css-collapse_v3.x.x.js
doberkofler/flow-typed
//@flow import React from 'react'; import Collapse from 'react-css-collapse'; { // $ExpectError <Collapse isOpen="a" /> } { // $ExpectError <Collapse onRest={1} /> } { // $ExpectError <Collapse onRest={() => true} /> } { <Collapse isOpen onRest={() => {}}><div/></Collapse> }
frontend/src/settings.js
miurahr/seahub
import React from 'react'; import ReactDOM from 'react-dom'; import { navigate } from '@reach/router'; import { Utils } from './utils/utils'; import { isPro, gettext, siteRoot, mediaUrl, logoPath, logoWidth, logoHeight, siteTitle } from './utils/constants'; import { seafileAPI } from './utils/seafile-api'; import toaster from './components/toast'; import CommonToolbar from './components/toolbar/common-toolbar'; import SideNav from './components/user-settings/side-nav'; import UserAvatarForm from './components/user-settings/user-avatar-form'; import UserBasicInfoForm from './components/user-settings/user-basic-info-form'; import WebAPIAuthToken from './components/user-settings/web-api-auth-token'; import WebdavPassword from './components/user-settings/webdav-password'; import LanguageSetting from './components/user-settings/language-setting'; import ListInAddressBook from './components/user-settings/list-in-address-book'; import EmailNotice from './components/user-settings/email-notice'; import TwoFactorAuthentication from './components/user-settings/two-factor-auth'; import SocialLogin from './components/user-settings/social-login'; import SocialLoginDingtalk from './components/user-settings/social-login-dingtalk'; import DeleteAccount from './components/user-settings/delete-account'; import './css/toolbar.css'; import './css/search.css'; import './css/user-settings.css'; const { canUpdatePassword, passwordOperationText, enableGetAuthToken, enableWebdavSecret, enableAddressBook, twoFactorAuthEnabled, enableWechatWork, enableDingtalk, enableDeleteAccount } = window.app.pageOptions; class Settings extends React.Component { constructor(props) { super(props); this.sideNavItems = [ {show: true, href: '#user-basic-info', text: gettext('Profile')}, {show: canUpdatePassword, href: '#update-user-passwd', text: gettext('Password')}, {show: enableGetAuthToken, href: '#get-auth-token', text: gettext('Web API Auth Token')}, {show: enableWebdavSecret, href: '#update-webdav-passwd', text: gettext('WebDav Password')}, {show: enableAddressBook, href: '#list-in-address-book', text: gettext('Global Address Book')}, {show: true, href: '#lang-setting', text: gettext('Language')}, {show: isPro, href: '#email-notice', text: gettext('Email Notification')}, {show: twoFactorAuthEnabled, href: '#two-factor-auth', text: gettext('Two-Factor Authentication')}, {show: enableWechatWork, href: '#social-auth', text: gettext('Social Login')}, {show: enableDingtalk, href: '#social-auth', text: gettext('Social Login')}, {show: enableDeleteAccount, href: '#del-account', text: gettext('Delete Account')}, ]; this.state = { curItemID: this.sideNavItems[0].href.substr(1) }; } componentDidMount() { seafileAPI.getUserInfo().then((res) => { this.setState({ userInfo: res.data }); }).catch(error => { let errMessage = Utils.getErrorMsg(error); toaster.danger(errMessage); }); } updateUserInfo = (data) => { seafileAPI.updateUserInfo(data).then((res) => { this.setState({ userInfo: res.data }); toaster.success(gettext('Success')); }).catch((error) => { let errMessage = Utils.getErrorMsg(error); toaster.danger(errMessage); }); } onSearchedClick = (selectedItem) => { if (selectedItem.is_dir === true) { let url = siteRoot + 'library/' + selectedItem.repo_id + '/' + selectedItem.repo_name + selectedItem.path; navigate(url, {repalce: true}); } else { let url = siteRoot + 'lib/' + selectedItem.repo_id + '/file' + Utils.encodePath(selectedItem.path); let newWindow = window.open('about:blank'); newWindow.location.href = url; } } handleContentScroll = (e) => { const scrollTop = e.target.scrollTop; const scrolled = this.sideNavItems.filter((item, index) => { return item.show && document.getElementById(item.href.substr(1)).offsetTop - 45 < scrollTop; }); if (scrolled.length) { this.setState({ curItemID: scrolled[scrolled.length -1].href.substr(1) }); } } render() { return ( <React.Fragment> <div className="h-100 d-flex flex-column"> <div className="top-header d-flex justify-content-between"> <a href={siteRoot}> <img src={mediaUrl + logoPath} height={logoHeight} width={logoWidth} title={siteTitle} alt="logo" /> </a> <CommonToolbar onSearchedClick={this.onSearchedClick} /> </div> <div className="flex-auto d-flex o-hidden"> <div className="side-panel o-auto"> <SideNav data={this.sideNavItems} curItemID={this.state.curItemID} /> </div> <div className="main-panel d-flex flex-column"> <h2 className="heading">{gettext('Settings')}</h2> <div className="content position-relative" onScroll={this.handleContentScroll}> <div id="user-basic-info" className="setting-item"> <h3 className="setting-item-heading">{gettext('Profile Setting')}</h3> <UserAvatarForm /> {this.state.userInfo && <UserBasicInfoForm userInfo={this.state.userInfo} updateUserInfo={this.updateUserInfo} />} </div> {canUpdatePassword && <div id="update-user-passwd" className="setting-item"> <h3 className="setting-item-heading">{gettext('Password')}</h3> <a href={`${siteRoot}accounts/password/change/`} className="btn btn-outline-primary">{passwordOperationText}</a> </div> } {enableGetAuthToken && <WebAPIAuthToken />} {enableWebdavSecret && <WebdavPassword />} {enableAddressBook && this.state.userInfo && <ListInAddressBook userInfo={this.state.userInfo} updateUserInfo={this.updateUserInfo} />} <LanguageSetting /> {isPro && <EmailNotice />} {twoFactorAuthEnabled && <TwoFactorAuthentication />} {enableWechatWork && <SocialLogin />} {enableDingtalk && <SocialLoginDingtalk />} {enableDeleteAccount && <DeleteAccount />} </div> </div> </div> </div> </React.Fragment> ); } } ReactDOM.render( <Settings />, document.getElementById('wrapper') );
src/components/DataTable/TableToolbarMenu.js
carbon-design-system/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import cx from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import { settings } from 'carbon-components'; import OverflowMenu from '../OverflowMenu'; import Settings16 from '@carbon/icons-react/lib/settings/16'; const { prefix } = settings; const TableToolbarMenu = ({ className, renderIcon, iconDescription, children, ...rest }) => { const toolbarActionClasses = cx( className, `${prefix}--toolbar-action ${prefix}--overflow-menu` ); return ( <OverflowMenu renderIcon={renderIcon} className={toolbarActionClasses} title={iconDescription} flipped {...rest}> {children} </OverflowMenu> ); }; TableToolbarMenu.defaultProps = { renderIcon: Settings16, iconDescription: 'Settings', }; TableToolbarMenu.propTypes = { children: PropTypes.node.isRequired, /** * Provide an optional class name for the toolbar menu */ className: PropTypes.string, /** * Optional prop to allow overriding the default menu icon */ renderIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), /** * The description of the menu icon. */ iconDescription: PropTypes.string.isRequired, }; export default TableToolbarMenu;
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestParameters.js
peopleticker/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load({ id = 0, ...rest }) { return [ { id: id + 1, name: '1' }, { id: id + 2, name: '2' }, { id: id + 3, name: '3' }, rest.user, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load({ id: 0, user: { id: 42, name: '42' } }); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-rest-parameters"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
examples/LeftAlignedNavbar.js
jareth/react-materialize
import React from 'react'; import Navbar from '../src/Navbar'; import NavItem from '../src/NavItem'; export default <Navbar brand='logo' left> <NavItem href='get-started.html'>Getting started</NavItem> <NavItem href='components.html'>Components</NavItem> </Navbar>;
packages/wix-style-react/src/InputWithLabel/InputWithLabel.js
wix/wix-style-react
import React from 'react'; import StatusAlertSmall from 'wix-ui-icons-common/StatusAlertSmall'; import LabelledElement from '../LabelledElement'; import Input from '../Input'; import Text from '../Text'; import PropTypes from 'prop-types'; import { classes } from './InputWithLabel.st.css'; import dataHooks from './dataHooks'; const getSuffixContainer = suffix => suffix.map((item, index) => { return ( <div data-hook={`suffix-container`} key={`suffix-container-${index}`} className={classes.groupIcon} > {item} </div> ); }); class InputWithLabel extends React.Component { static propTypes = { /** Applied as data-hook HTML attribute that can be used in the tests */ dataHook: PropTypes.string, /** Array of suffix icons */ suffix: PropTypes.arrayOf(PropTypes.element), /** Text of rendered label */ label: PropTypes.string, /** Input value */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** Input status - use to display an status indication for the user. for example: 'error', 'warning' or 'loading' */ status: PropTypes.oneOf([ Input.StatusError, Input.StatusWarning, Input.StatusLoading, ]), /** The status (error/loading) message to display when hovering the status icon, if not given or empty there will be no tooltip */ statusMessage: PropTypes.node, /** Standard input onFocus callback */ onFocus: PropTypes.func, /** Standard input onBlur callback */ onBlur: PropTypes.func, /** Standard input onChange callback */ onChange: PropTypes.func, name: PropTypes.string, type: PropTypes.string, /** Used to define a string that labels the current element in case where a text label is not visible on the screen. */ ariaLabel: PropTypes.string, /** Standard React Input autoFocus (focus the element on mount) */ autoFocus: PropTypes.bool, /** Sets value of autocomplete attribute (consult the [HTML spec](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-autocomplete) for possible values */ autocomplete: PropTypes.string, /** when set to true this component is disabled */ disabled: PropTypes.bool, /** A single CSS class name to be passed to the Input element. */ className: PropTypes.string, /** Input max length */ maxLength: PropTypes.number, /** Placeholder to display */ placeholder: PropTypes.string, /** Use a customized input component instead of the default html input tag */ customInput: PropTypes.elementType ? PropTypes.oneOfType([ PropTypes.func, PropTypes.node, PropTypes.elementType, ]) : PropTypes.oneOfType([PropTypes.func, PropTypes.node]), }; static defaultProps = { statusMessage: '', }; render() { const { label, suffix, value, dataHook, status, statusMessage, onChange, onFocus, onBlur, name, type, ariaLabel, autoFocus, autocomplete, disabled, className, maxLength, placeholder, customInput, } = this.props; return ( <div data-hook={dataHook} className={status ? undefined : classes.statusMessagePlaceholder} > <LabelledElement value={value} label={label} dataHook={dataHooks.labelledElement} > <Input name={name} type={type} ariaLabel={ariaLabel} autoFocus={autoFocus} autocomplete={autocomplete} disabled={disabled} maxLength={maxLength} placeholder={placeholder} onChange={onChange} onFocus={onFocus} onBlur={onBlur} dataHook={dataHooks.input} className={className} size="large" value={value} suffix={suffix ? getSuffixContainer(suffix) : []} status={status} customInput={customInput} hideStatusSuffix /> </LabelledElement> {status === Input.StatusError && statusMessage && ( <Text skin="error" size="small" weight="normal" className={classes.statusMessage} > <span className={classes.statusMessageIcon}> <StatusAlertSmall /> </span> <span data-hook={dataHooks.errorMessage} className={classes.errorMessageContent} > {statusMessage} </span> </Text> )} </div> ); } } export default InputWithLabel;
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/StateUninitialized.js
samwgoldman/flow
// @flow import React from 'react'; class MyComponent extends React.Component { props: Props; state: State; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { props: Props; state: State; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
node_modules/react-select/examples/src/components/States.js
Alex-Shilman/Drupal8Node
import React from 'react'; import Select from 'react-select'; const STATES = require('../data/states'); var StatesField = React.createClass({ displayName: 'StatesField', propTypes: { label: React.PropTypes.string, searchable: React.PropTypes.bool, }, getDefaultProps () { return { label: 'States:', searchable: true, }; }, getInitialState () { return { country: 'AU', disabled: false, searchable: this.props.searchable, selectValue: 'new-south-wales', clearable: true, }; }, switchCountry (e) { var newCountry = e.target.value; console.log('Country changed to ' + newCountry); this.setState({ country: newCountry, selectValue: null }); }, updateValue (newValue) { console.log('State changed to ' + newValue); this.setState({ selectValue: newValue }); }, focusStateSelect () { this.refs.stateSelect.focus(); }, toggleCheckbox (e) { let newState = {}; newState[e.target.name] = e.target.checked; this.setState(newState); }, render () { var options = STATES[this.state.country]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select ref="stateSelect" autofocus options={options} simpleValue clearable={this.state.clearable} name="selected-state" disabled={this.state.disabled} value={this.state.selectValue} onChange={this.updateValue} searchable={this.state.searchable} /> <div style={{ marginTop: 14 }}> <button type="button" onClick={this.focusStateSelect}>Focus Select</button> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="searchable" checked={this.state.searchable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Searchable</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="disabled" checked={this.state.disabled} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Disabled</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="clearable" checked={this.state.clearable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Clearable</span> </label> </div> <div className="checkbox-list"> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'AU'} value="AU" onChange={this.switchCountry}/> <span className="checkbox-label">Australia</span> </label> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'US'} value="US" onChange={this.switchCountry}/> <span className="checkbox-label">United States</span> </label> </div> </div> ); } }); module.exports = StatesField;
docs/public/static/examples/v35.0.0/web-browser.js
exponent/exponent
import React, { Component } from 'react'; import { Button, Text, View, StyleSheet } from 'react-native'; import * as WebBrowser from 'expo-web-browser'; import Constants from 'expo-constants'; export default class App extends Component { state = { result: null, }; render() { return ( <View style={styles.container}> <Button title="Open WebBrowser" onPress={this._handlePressButtonAsync} /> <Text>{this.state.result && JSON.stringify(this.state.result)}</Text> </View> ); } _handlePressButtonAsync = async () => { let result = await WebBrowser.openBrowserAsync('https://expo.io'); this.setState({ result }); }; } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', }, });
public/js/cat_source/es6/components/header/ActionMenu.js
riccio82/MateCat
import React from 'react' import Icon3Dots from '../icons/Icon3Dots' class ActionMenu extends React.Component { componentDidMount() { this.initDropdowns() } initDropdowns = () => { // 3Dots if (!_.isUndefined(this.dropdownThreeDots)) { let dropdownThreeDots = $(this.dropdownThreeDots) dropdownThreeDots.dropdown() } } getTranslateUrl() {} getThreeDotsMenu = () => { const {jobUrls} = this.props return ( <div className={'action-submenu ui pointing top center floating dropdown'} id={'action-three-dots'} ref={(dropdownThreeDots) => (this.dropdownThreeDots = dropdownThreeDots) } > <Icon3Dots /> <ul className="menu"> <li className="item" title="Revise" data-value="revise"> <a href={jobUrls.revise_urls[0].url}>Revise</a> </li> <li className="item" title="Translate" data-value="translate"> <a href={jobUrls.translate_url}>Translate</a> </li> </ul> </div> ) } render = () => { const {getThreeDotsMenu} = this const threeDotsMenu = getThreeDotsMenu() return <div className={'action-menu qr-element'}>{threeDotsMenu}</div> } } ActionMenu.defaultProps = {} export default ActionMenu
client/src/components/ToggleButton.js
banderson/reactive-stock-ticker-demo
import React from 'react'; import {Button} from 'elemental'; export default class ToggleButton extends React.Component { static propTypes = { recording: React.PropTypes.bool } static defaultProps = { recording: false } render() { const {recording, ...other} = this.props; const icon = recording ? 'x' : 'triangle-right'; const type = recording ? 'danger' : 'primary'; return ( <Button block type={type} {...other}> <span className={'octicon octicon-'+ icon} /> {recording ? 'Stop' : 'Start/Resume'} </Button> ); } }
app/components/GeometryCanvasUuid/index.js
mhoffman/CatAppBrowser
/** * * GeometryCanvasUuid * */ import React from 'react'; import Button from 'material-ui/Button'; import { withStyles } from 'material-ui/styles'; import axios from 'axios'; import { graphQLRoot } from 'utils/constants'; import PropTypes from 'prop-types'; import { download } from 'utils'; import { MdFileDownload } from 'react-icons/lib/md'; const styles = (xtheme) => ({ MuiButton: { margin: '12px', [xtheme.breakpoints.down('sm')]: { visibility: 'hidden', }, }, }); class GeometryCanvasUuid extends React.Component { // eslint-disable-line react/prefer-stateless-function componentDidUpdate() { if (this.props.uuid !== '') { const query = { query: `query{systems(uniqueId: "${this.props.uuid}") { edges { node { Cifdata } } }}`, }; axios.post(graphQLRoot, query) .then((res) => { const cifdata = res.data.data.systems.edges[0].node.Cifdata; this.cifdata = cifdata; const script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.innerHTML = ` function _load_lib(url, callback){ id = 'load_' + url; var s = document.createElement('script'); s.src = url; s.id = id; s.async = true; s.onreadystatechange = s.onload = callback; s.onerror = function(){console.warn("failed to load library " + url);}; document.getElementsByTagName("head")[0].appendChild(s); } // Load Libraries _load_lib("https://code.jquery.com/jquery-3.2.1.min.js", function(){ _load_lib("https://hub.chemdoodle.com/cwc/8.0.0/ChemDoodleWeb.js", function(){ var rotationMatrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] //Code let tfcanvas = new ChemDoodle.TransformCanvas3D('${this.props.id}_view'); let cif = ChemDoodle.readCIF(\`${cifdata}\`, ${this.props.x}, ${this.props.y}, ${this.props.z}); tfcanvas.specs.set3DRepresentation('Ball and Stick'); tfcanvas.specs.backgroundColor = '${this.props.color}'; tfcanvas.specs.projectionPerspective_3D = true; tfcanvas.specs.atoms_displayLabels_3D = ${this.props.showLabels}; tfcanvas.specs.crystals_unitCellLineWidth = 5; tfcanvas.specs.shapes_color = 'black'; tfcanvas.specs.shapes_lineWidth = 1; tfcanvas.specs.fog_mode_3D = 0; tfcanvas.specs.shadow_3D = false; tfcanvas.specs.atoms_useJMOLColors = true; tfcanvas.specs.compass_display = ${this.props.showCompass}; tfcanvas.loadContent([cif.molecule], [cif.unitCell]); }); });`; document.getElementById(`${this.props.id}_view`).appendChild(script); }); } } render() { return ( <div style={{ float: 'left', marginRight: 80 }}> { /* this.state.loading ? <LinearProgress color="primary" /> : null */ } <p id={`${this.props.id}_script`} /> <canvas id={`${this.props.id}_view`} height={this.props.height} width={this.props.width} style={{ borderWidth: this.props.borderWidth, borderColor: '#000000', borderStyle: 'solid', }} /> <br /> {this.props.showDownload === false ? null : <Button className={this.props.classes.MuiButton} raised onClick={() => { download(`structure_${this.props.id}.cif`, this.cifdata); }} > <MdFileDownload /> Download CIF </Button> } </div> ); } } GeometryCanvasUuid.defaultProps = { height: Math.max(Math.min(window.innerWidth * 0.5, 600), 300), width: Math.max(Math.min(window.innerWidth * 0.5, 600), 300), color: '#fff', uuid: '', showDownload: true, showCompass: true, showLabels: true, x: 2, y: 2, z: 1, borderWidth: 0.1, }; GeometryCanvasUuid.propTypes = { id: PropTypes.string.isRequired, uuid: PropTypes.string, height: PropTypes.number, width: PropTypes.number, color: PropTypes.string, showDownload: PropTypes.bool, showCompass: PropTypes.bool, showLabels: PropTypes.bool, x: PropTypes.number, y: PropTypes.number, z: PropTypes.number, borderWidth: PropTypes.number, classes: PropTypes.object, }; export default (withStyles(styles, { withTheme: true }))(GeometryCanvasUuid);
examples/query-params/app.js
axross/react-router
import React from 'react' import { createHistory, useBasename } from 'history' import { Router, Route, Link } from 'react-router' const history = useBasename(createHistory)({ basename: '/query-params' }) class User extends React.Component { render() { let { userID } = this.props.params let { query } = this.props.location let age = query && query.showAge ? '33' : '' return ( <div className="User"> <h1>User id: {userID}</h1> {age} </div> ) } } class App extends React.Component { render() { return ( <div> <ul> <li><Link to="/user/bob" activeClassName="active">Bob</Link></li> <li><Link to="/user/bob" query={{ showAge: true }} activeClassName="active">Bob With Query Params</Link></li> <li><Link to="/user/sally" activeClassName="active">Sally</Link></li> </ul> {this.props.children} </div> ) } } React.render(( <Router history={history}> <Route path="/" component={App}> <Route path="user/:userID" component={User} /> </Route> </Router> ), document.getElementById('example'))
src/js/components/sidebarComponents/Sprite.js
levadadenys/graphic-designer-portfolio-react
import React from 'react'; class Sprite extends React.PureComponent { static defaultProps = { herf: '#', target: '_blank', title: 'Contact', icon: 'socicon-mail socicons ' }; render () { return ( <div className="sidebar-nav-item"> <a href={this.props.href} target={this.props.target} title={this.props.title}> <span className={this.props.icon} /> </a> </div> ); } } export default Sprite;
packages/xo-web/src/common/json-schema-input/string-input.js
vatesfr/xo-web
import PropTypes from 'prop-types' import React from 'react' import uncontrollableInput from 'uncontrollable-input' import Combobox from '../combobox' import Component from '../base-component' import getEventValue from '../get-event-value' import { PrimitiveInputWrapper } from './helpers' // =================================================================== @uncontrollableInput() export default class StringInput extends Component { static propTypes = { password: PropTypes.bool, } // the value of this input is undefined not '' when empty to make // it homogenous with when the user has never touched this input _onChange = event => { const value = getEventValue(event) this.props.onChange(value !== '' ? value : undefined) } render() { const { required, schema } = this.props const { disabled, password, placeholder = schema.default, value, ...props } = this.props delete props.onChange return ( <PrimitiveInputWrapper {...props}> <Combobox value={value !== undefined ? value : ''} disabled={disabled} onChange={this._onChange} options={schema.defaults} placeholder={placeholder || schema.default} required={required} type={password && 'password'} /> </PrimitiveInputWrapper> ) } }
src/app/components/team/SmoochBot/SmoochBotSettings.js
meedan/check-web
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import Box from '@material-ui/core/Box'; import Typography from '@material-ui/core/Typography'; import SmoochBotIntegrations from './SmoochBotIntegrations'; import SmoochBotSetting from './SmoochBotSetting'; const SmoochBotSettings = (props) => { const fields = props.schema; return ( <React.Fragment> <SmoochBotIntegrations settings={props.settings} schema={props.schema} enabledIntegrations={props.enabledIntegrations} installationId={props.installationId} /> {['smooch_urls_to_ignore', 'smooch_time_to_send_request', 'smooch_disabled'].map(field => ( <SmoochBotSetting field={field} value={props.settings[field]} schema={fields[field]} onChange={props.onChange} /> ))} { props.currentUser.is_admin ? <Box mt={2}> <Typography variant="h6" component="div"> <FormattedMessage id="smoochBotSettings.internalSettings" defaultMessage="Internal settings" description="Title of Internal Settings section in the tipline settings page" /> </Typography> <Typography variant="subtitle1" component="div"> <FormattedMessage id="smoochBotSettings.internalSettingsDescription" defaultMessage="Meedan employees see these settings, but users don't." description="Description of Internal Settings section in the tipline settings page. The word Meedan does not need to be translated." /> </Typography> { props.settings.smooch_version === 'v2' ? <Box mt={1}> <Typography variant="subtitle1" component="div"> <FormattedMessage id="smoochBotSettings.searchSettings" defaultMessage="Search settings" description="Title of Search settings section in the tipline settings page." /> </Typography> {['smooch_search_text_similarity_threshold', 'smooch_search_max_keyword'].map(field => ( <SmoochBotSetting field={field} value={props.settings[field]} schema={fields[field]} onChange={props.onChange} currentUser={props.currentUser} /> ))} </Box> : null } <Box mt={1}> <Typography variant="subtitle1" component="div"> <FormattedMessage id="smoochBotSettings.sunshineSettings" defaultMessage="Sunshine integration settings" description="Title of Sunshine settings section in the tipline settings page. The word Sunshine does not need to be translated." /> </Typography> {['smooch_app_id', 'smooch_secret_key_key_id', 'smooch_secret_key_secret', 'smooch_webhook_secret'].map(field => ( <SmoochBotSetting field={field} value={props.settings[field]} schema={fields[field]} onChange={props.onChange} currentUser={props.currentUser} /> ))} </Box> <Box mt={1}> <Typography variant="subtitle1" component="div"> <FormattedMessage id="smoochBotSettings.templatesSettings" defaultMessage="Templates settings" description="Title of templates settings section in the tipline settings page." /> </Typography> {['smooch_template_namespace', 'smooch_template_locales'].map(field => ( <SmoochBotSetting field={field} value={props.settings[field]} schema={fields[field]} onChange={props.onChange} currentUser={props.currentUser} /> ))} {Object.keys(fields).filter(f => /^smooch_template_name_for_/.test(f)).map(field => ( <SmoochBotSetting field={field} value={props.settings[field]} schema={fields[field]} onChange={props.onChange} currentUser={props.currentUser} /> ))} </Box> <Box mt={1}> <Typography variant="subtitle1" component="div"> <FormattedMessage id="smoochBotSettings.bspSettings" defaultMessage="WhatsApp BSP settings" description="Title of 'WhatsApp BSP' settings section in the tipline settings page. The words WhatsApp BSP do not need to be translated." /> </Typography> {Object.keys(fields).filter(f => /^turnio_/.test(f)).map(field => ( <SmoochBotSetting field={field} value={props.settings[field]} schema={fields[field]} onChange={props.onChange} currentUser={props.currentUser} /> ))} </Box> </Box> : null } </React.Fragment> ); }; SmoochBotSettings.propTypes = { settings: PropTypes.object.isRequired, schema: PropTypes.object.isRequired, currentUser: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, enabledIntegrations: PropTypes.object.isRequired, installationId: PropTypes.string.isRequired, }; export default SmoochBotSettings;
src/components/Login.js
ohmyjersh/sso-component
import React from 'react'; import TextField from './common/TextField'; const LoginShell = (props) => { const currentState = props.state.getIn(['login','currentState']); const {components} = props; if(currentState === 'LOGGEDIN') { console.log('go to....'); window.location.href = props.redirect; } return ( <div> <components.Card.Content> {currentState === 'LOGIN' ? <Login {...props}/> : null } {currentState === '2FA' ? <TwoFactor {...props} /> : null } </components.Card.Content> <components.Card.Footer> <components.Link to="forgotPassword">Forgot password</components.Link> <components.Link to="signup">Sign up</components.Link> </components.Card.Footer> </div> ) } const Login = (props) => { const {components, actions} = props; const username = props.state.getIn(['login','username']); const password = props.state.getIn(['login', 'password']); const loginError = props.state.getIn(['login', 'error']); return ( <div> <TextField {...{...props.components, label:'Username', update: actions.login.updateUsername, value: username}}/> <TextField {...{...props.components, label:'Password', update: actions.login.updatePassword, value: password}} /> {loginError? <components.Error>{loginError}</components.Error> : null } <components.Button onClick={() => actions.login.submitLogin({username, password})} >Login</components.Button> </div> ) } const TwoFactor = (props) => { const {components, actions} = props; const token = props.state.getIn(['login', 'token']); const tokenError = props.state.getIn(['login', 'error']); return ( <div> <TextField {...{...props.components, label:'Send Token', update: actions.login.updateToken, value: token}} /> {tokenError ? <components.Error>{tokenError}</components.Error> : null } <components.Button onClick={() => actions.login.submitToken({token})} >Submit</components.Button> </div> ) } export default LoginShell;
src/App.js
gom3s/math4Kids
import './App.css'; import injectTapEventPlugin from 'react-tap-event-plugin'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import React, { Component } from 'react'; import Route from './components/app/Route'; injectTapEventPlugin(); class App extends Component { render() { return ( <MuiThemeProvider > <Route/> </MuiThemeProvider> ); } } export default App;
node_modules/react-bootstrap/es/MenuItem.js
acalabano/get-committed
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import all from 'prop-types-extra/lib/all'; import SafeAnchor from './SafeAnchor'; import { bsClass, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { /** * Highlight the menu item as active. */ active: PropTypes.bool, /** * Disable the menu item, making it unselectable. */ disabled: PropTypes.bool, /** * Styles the menu item as a horizontal rule, providing visual separation between * groups of menu items. */ divider: all(PropTypes.bool, function (_ref) { var divider = _ref.divider, children = _ref.children; return divider && children ? new Error('Children will not be rendered for dividers') : null; }), /** * Value passed to the `onSelect` handler, useful for identifying the selected menu item. */ eventKey: PropTypes.any, /** * Styles the menu item as a header label, useful for describing a group of menu items. */ header: PropTypes.bool, /** * HTML `href` attribute corresponding to `a.href`. */ href: PropTypes.string, /** * Callback fired when the menu item is clicked. */ onClick: PropTypes.func, /** * Callback fired when the menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: PropTypes.func }; var defaultProps = { divider: false, disabled: false, header: false }; var MenuItem = function (_React$Component) { _inherits(MenuItem, _React$Component); function MenuItem(props, context) { _classCallCheck(this, MenuItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } MenuItem.prototype.handleClick = function handleClick(event) { var _props = this.props, href = _props.href, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (!href || disabled) { event.preventDefault(); } if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; MenuItem.prototype.render = function render() { var _props2 = this.props, active = _props2.active, disabled = _props2.disabled, divider = _props2.divider, header = _props2.header, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = _objectWithoutProperties(_props2, ['active', 'disabled', 'divider', 'header', 'onClick', 'className', 'style']); var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['eventKey', 'onSelect']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; if (divider) { // Forcibly blank out the children; separators shouldn't render any. elementProps.children = undefined; return React.createElement('li', _extends({}, elementProps, { role: 'separator', className: classNames(className, 'divider'), style: style })); } if (header) { return React.createElement('li', _extends({}, elementProps, { role: 'heading', className: classNames(className, prefix(bsProps, 'header')), style: style })); } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, elementProps, { role: 'menuitem', tabIndex: '-1', onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return MenuItem; }(React.Component); MenuItem.propTypes = propTypes; MenuItem.defaultProps = defaultProps; export default bsClass('dropdown', MenuItem);
docs/app/Examples/elements/Segment/Variations/SegmentExampleClearing.js
aabustamante/Semantic-UI-React
import React from 'react' import { Button, Segment } from 'semantic-ui-react' const SegmentExampleClearing = () => ( <Segment clearing> <Button floated='right'> floated </Button> </Segment> ) export default SegmentExampleClearing
src/svg-icons/maps/layers-clear.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLayersClear = (props) => ( <SvgIcon {...props}> <path d="M19.81 14.99l1.19-.92-1.43-1.43-1.19.92 1.43 1.43zm-.45-4.72L21 9l-9-7-2.91 2.27 7.87 7.88 2.4-1.88zM3.27 1L2 2.27l4.22 4.22L3 9l1.63 1.27L12 16l2.1-1.63 1.43 1.43L12 18.54l-7.37-5.73L3 14.07l9 7 4.95-3.85L20.73 21 22 19.73 3.27 1z"/> </SvgIcon> ); MapsLayersClear = pure(MapsLayersClear); MapsLayersClear.displayName = 'MapsLayersClear'; MapsLayersClear.muiName = 'SvgIcon'; export default MapsLayersClear;
src/routes/User/User.js
townmi/ReactExamples
/** * */ import React, { Component } from 'react'; import axios from 'axios'; import { Link } from 'react-router'; import ListCell from '../../components/ListCell'; import './user.scss'; class User extends Component { constructor(props) { super(props); this.state = { userInfo: null } let self = this; this.getUserMember() .then((response) => { self.setState({ userInfo: response.data }); }) .catch((error) => { console.error(error); }); } getUserMember() { let self = this; return new Promise((resolve, reject) => { axios.get('https://cnodejs.org/api/v1/user/' + self.props.params.username) .then((response) => { resolve({ status: "success", data: response.data.data }); }) .catch((error) => { resolve({ status: "fail", data: error }); }); }); } render() { let replyHtml = ""; let topicHtml = ""; let avatorHtml = ""; let githubUrl = ""; const userInfo = this.state.userInfo; if(this.state.userInfo) { const replies = userInfo.recent_replies; const topics = userInfo.recent_topics; replyHtml = replies && replies.map(function (cell, index) { return ( <ListCell key={index} listInfo={cell} /> ) }); topicHtml = topics && topics.map(function (cell, index) { return ( <ListCell key={index} listInfo={cell} /> ) }) avatorHtml = ( <img src={userInfo.avatar_url}/> ) githubUrl = "https://github.com/"+userInfo.githubUsername; } return ( <div className="member"> <br/> <div className="row"> <div className="col s10 m9"> <ul className="collapsible" data-collapsible="accordion"> <li className="block_title"> <div className="collapsible-header"> 最近创建的话题 </div> </li> {replyHtml} <li className="more"> <div className="collapsible-header"> <a>查看更多 &nbsp;<em className="fa fa-angle-right" aria-hidden="true"></em></a> </div> </li> </ul> <br/> <ul className="collapsible" data-collapsible="accordion"> <li className="block_title"> <div className="collapsible-header"> 最近创建的话题 </div> </li> {topicHtml} <li className="more"> <div className="collapsible-header"> <a>查看更多 &nbsp;<em className="fa fa-angle-right" aria-hidden="true"></em></a> </div> </li> </ul> <br/> </div> <div className="col s2 m3"> <div className="card blue-grey darken-1"> <div className="card-content white-text"> <span className="card-title">名片</span> <p className="body"> {avatorHtml} </p> </div> <div className="card-action"> <a href={githubUrl}> <i className="fa fa-github" aria-hidden="true"></i> </a> </div> </div> </div> </div> </div> ) } } export default User;
docs/src/utils/DemoPageLayout.js
gocreating/react-tocas
import React from 'react'; import PageLayout from './PageLayout'; import './DemoPageLayout.css'; let DemoPageLayout = ({ title, description, children }) => ( <PageLayout> <div className="ts huge heading padded slate bottom margined"> <span className="header">{title}</span> <span className="description">{description}</span> </div> {children} </PageLayout> ); export default DemoPageLayout;
pathfinder/vtables/decommissioningcommissioningapplications/src/common/TableUtilities.js
leanix/leanix-custom-reports
import React from 'react'; import Utilities from './Utilities'; import Link from './Link'; import LinkList from './LinkList'; /* formatting functions for the table */ const OVERFLOW_CELL_STYLE = { maxHeight: '100px', overflow: 'auto' }; function formatLinkFactsheet(setup) { const baseUrl = Utilities.getFrom(setup, 'settings.baseUrl'); return (cell, row, extraData) => { if (!cell || !baseUrl) { return ''; } return ( <Link link={baseUrl + '/factsheet/' + extraData.type + '/' + row[extraData.id]} target='_blank' text={cell} /> ); }; } function formatLinkArrayFactsheets(setup) { const baseUrl = Utilities.getFrom(setup, 'settings.baseUrl'); return (cell, row, extraData) => { if (!cell || !baseUrl) { return ''; } return ( <div style={OVERFLOW_CELL_STYLE}> <LinkList links={ cell.reduce((arr, e, i) => { arr.push({ link: baseUrl + '/factsheet/' + extraData.type + '/' + row[extraData.id][i], target: '_blank', text: e }); return arr; }, [])} delimiter={extraData.delimiter} /> </div> ); }; } function formatEnum(cell, row, enums) { if (!cell && cell !== 0) { return ''; } return enums[cell] ? enums[cell] : ''; } function formatEnumArray(cell, row, extraData) { let result = ''; if (!cell || !extraData || !extraData.delimiter || !extraData.enums) { return result; } let first = false; cell.forEach((e) => { const formatted = formatEnum(e, row, extraData.enums); if (formatted === '') { return; } if (first) { result += extraData.delimiter; } else { first = true; } result += formatted; }); if (extraData.delimiter === '<br/>') { return ( <div style={OVERFLOW_CELL_STYLE} dangerouslySetInnerHTML={{ __html: result }} /> ); } return result; } function formatOptionalText(cell, row, formatRaw) { if (!cell) { return ''; } return formatRaw ? cell : ( <div style={OVERFLOW_CELL_STYLE}>{cell}</div> ); } function formatDate(cell, row) { if (!cell) { return ''; } return ( <span style={{ paddingRight: '10%' }}> {_formatDate(cell, '-', false)} </span> ); } function _formatDate(date, delimiter, reverse) { if (reverse) { return date.getFullYear() + delimiter + _formatDateNumber(date.getMonth() + 1) + delimiter + _formatDateNumber(date.getDate()); } return _formatDateNumber(date.getDate()) + delimiter + _formatDateNumber(date.getMonth() + 1) + delimiter + date.getFullYear(); } function _formatDateNumber(n) { return n < 10 ? '0' + n : n; } function formatArray(cell, row, delimiter) { let result = ''; if (!cell || !delimiter) { return result; } cell.forEach((e) => { if (result.length) { result += delimiter; } result += e; }); if (delimiter === '<br/>') { return ( <div style={OVERFLOW_CELL_STYLE} dangerouslySetInnerHTML={{ __html: result }} /> ); } return result; } /* formatting functions for the csv export */ function csvFormatDate(cell, row) { if (!cell) { return ''; } return _formatDate(cell, '-', true); } /* pre-defined filter objects */ const textFilter = { type: 'TextFilter', condition: 'like', placeholder: 'Please enter a value' }; function selectFilter(options) { return { type: 'SelectFilter', condition: 'eq', placeholder: 'Please choose', options: options }; } const dateFilter = { type: 'DateFilter' }; const numberFilter = { type: 'NumberFilter', placeholder: 'Please enter a value', defaultValue: { comparator: '<=' } }; /* custom PropTypes */ function options(props, propName, componentName) { const options = props[propName]; if (options !== null && typeof options === 'object' && checkKeysAndValues(options)) { // test passes successfully return; } return new Error( 'Invalid prop "' + propName + '" supplied to "' + componentName + '". Validation failed.' ); } const intRegExp = /^\d+$/; function checkKeysAndValues(options) { for (let key in options) { if (!intRegExp.test(key)) { return false; } const value = options[key]; if (typeof value !== 'string' && !(value instanceof String)) { return false; } } return true; } function idArray(namesPropName) { return (props, propName, componentName) => { const ids = props[propName]; const names = props[namesPropName]; if (names && ids && Array.isArray(names) && Array.isArray(ids) && names.length === ids.length && isStringArray(ids)) { // test passes successfully return; } return new Error( 'Invalid prop "' + propName + '" supplied to "' + componentName + '". Validation failed.' ); }; } function isStringArray(arr) { for (let i = 0; i < arr.length; i++) { const e = arr[i]; if (typeof e !== 'string' && !(e instanceof String)) { return false; } } return true; } export default { OVERFLOW_CELL_STYLE: OVERFLOW_CELL_STYLE, formatLinkFactsheet: formatLinkFactsheet, formatLinkArrayFactsheets: formatLinkArrayFactsheets, formatEnum: formatEnum, formatEnumArray: formatEnumArray, formatOptionalText: formatOptionalText, formatDate: formatDate, formatArray: formatArray, csvFormatDate: csvFormatDate, textFilter: textFilter, selectFilter: selectFilter, dateFilter: dateFilter, numberFilter: numberFilter, PropTypes: { options: options, idArray: idArray } };
ui/button.js
jamen/neta
import React, { Component } from 'react'; import { Link } from 'react-router'; class Button extends Component { render() { const btn = (<div className="button">{this.props.name}</div>); if (typeof this.props.to !== 'undefined') { return (<Link to={this.props.to}>{btn}</Link>); } return btn; } } export default Button;
client/index.js
derektliu/reddit-reader
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; ReactDOM.render( <App />, document.getElementById('app') );
src/svg-icons/action/history.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionHistory = (props) => ( <SvgIcon {...props}> <path d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"/> </SvgIcon> ); ActionHistory = pure(ActionHistory); ActionHistory.displayName = 'ActionHistory'; ActionHistory.muiName = 'SvgIcon'; export default ActionHistory;
renderer/components/Icon/Filter.js
LN-Zap/zap-desktop
import React from 'react' const SvgFilter = props => ( <svg height="1em" viewBox="0 0 14 13" width="1em" {...props}> <g fill="none" fillRule="evenodd" transform="translate(1)"> <circle cx={9} cy={6.5} fill="currentColor" r={1.5} /> <circle cx={6} cy={1.5} fill="currentColor" r={1.5} /> <circle cx={3} cy={11.5} fill="currentColor" r={1.5} /> <path d="M0 1.5h12m-12 5h12m-12 5h12" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={0.813} /> </g> </svg> ) export default SvgFilter
src/scenes/bookRanking.js
Seeingu/borrow-book
/* 排行榜 */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Text, Image, View, StyleSheet, TouchableNativeFeedback, } from 'react-native'; import LinearGradient from 'react-native-linear-gradient'; import TopBar from '../components/topBar'; import { CommonStyles, ComponentStyles } from '../assets/styles/index'; import { color } from '../assets/styles/color'; const styles = StyleSheet.create({ title: { color: 'black', paddingHorizontal: 20, paddingTop: 15, }, }); const rankTitle = ['借阅飙升榜', '新书榜', '好评榜']; { /* <View style={{backgroundColor, justifyContent: 'center', alignItems: 'center', width: 110, height: 110}}> <Text style={{fontFamily: 'Entypo', fontSize: 20}}>飙升榜</Text> </View>*/ } const renderRanking = (backgroundColor, text, top3) => ( <View style={{ flexDirection: 'row' }}> <LinearGradient start={{ x: 0.0, y: 0.25 }} end={{ x: 0.8, y: 1.0 }} style={{ justifyContent: 'center', marginVertical: 5, alignItems: 'center', width: 110, height: 110 }} colors={backgroundColor} > <Text style={{ color: 'white', fontFamily: 'Entypo', fontSize: 20 }}>{text}</Text> </LinearGradient> <View style={{ paddingLeft: 10, paddingTop: 10 }}> {top3.map((item, index) => ( <Text key={index} style={{ marginBottom: 15 }}>{index + 1}. {item}</Text> ))} </View> </View> ); export default class extends Component { constructor(props) { super(props); } static propTypes = { title: PropTypes.string.isRequired, } render() { const { title, router } = this.props; return ( <View style={[ComponentStyles.container]}> <TopBar router={router} showTitle title={title} /> <View style={{ flexDirection: 'row', padding: 10 }}> <View style={{ width: 4, height: 20, marginRight: 5, backgroundColor: color.blue }} /> <Text style={{ fontSize: 16 }}>每天更新</Text> </View> <View style={CommonStyles.p_y_1}> {renderRanking([color.gra1Top, color.gra1Bottom], '飙升榜', ['平凡的世界', '人类简史', '围城'])} {renderRanking([color.gra2Top, color.gra2Bottom], '新书榜', ['未来简史', '沙丘', '人民的名义'])} {renderRanking([color.gra4Center, color.gra4Bottom], '好评榜', ['平凡的世界', '围城', '三体'])} </View> </View> ); } }
src/layouts/PageLayout/ScrollToTop.js
yoshiyoshi7/react2chv2
import React, { Component } from 'react'; import { withRouter } from 'react-router'; class ScrollToTop extends Component { componentDidUpdate(prevProps) { if (this.props.location !== prevProps.location) { window.scrollTo(0, 0) } } render() { return this.props.children } } export default withRouter(ScrollToTop)
app/components/state.js
MadaraUchiha/isomorphic-react-app
import React from 'react'; export default class State extends React.Component { constructor(props) { super(props); this.state = props; this.changeState = this.changeState.bind(this); // Because apparently, I need to do that now. } render() { return ( <div> <div>{this.state.text}</div> <input onChange={this.changeState} /> </div> ); } changeState(event) { let text = event.target.value; this.setState({text}); } }
src/index.js
ankushjamdagani/portfolio
import React from 'react'; import ReactDOM from 'react-dom'; import configureStore from './store'; import './scss/main.scss'; import App from './app'; const store = configureStore(); ReactDOM.render( <App store={store} />, document.getElementById('root') ); console.info('Hello User!!', 'color: red')
src/components/item/view/ReservationList/ReservationList.js
katima-g33k/blu-react-desktop
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Button, Glyphicon } from 'react-bootstrap'; import { formatShortDate } from '../../../../lib/dateHelper'; import i18n from '../../../../lib/i18n'; import { link } from '../../../../lib/link'; import { Reservation } from '../../../../lib/models'; import { TableLayout } from '../../../general'; const styles = { button: { backgroundColor: '#00C73E', cursor: 'default', }, }; // TODO: Fix copy reservations export default class ReservationList extends Component { static propTypes = { onDelete: PropTypes.func.isRequired, reservations: PropTypes.arrayOf(PropTypes.instanceOf(Reservation)), }; static defaultProps = { reservations: [], }; columns = [ { dataField: 'id', isKey: true, hidden: true, }, { dataField: 'parent', label: i18n('ReservationList.table.parent'), dataFormat(parent, { copy }) { const member = copy ? copy.reservee : parent; return link(`/member/view/${member.no}`, member.name); }, }, { dataField: 'date', label: i18n('ReservationList.table.date'), width: '150px', dataFormat: date => formatShortDate(date), }, { dataField: 'received', label: i18n('ReservationList.table.received'), width: '70px', dataAlign: 'center', dataFormat: (cell, { copy }) => copy && ( <Button bsStyle="success" disabled style={styles.button}> <Glyphicon glyph="ok-sign" /> </Button> ), }, ]; rowActions = [{ bsStyle: 'danger', glyph: 'trash', help: 'Supprimer', onClick: this.props.onDelete, }]; render() { return ( <TableLayout columns={this.columns} data={this.props.reservations} rowActions={this.rowActions} title={i18n('ReservationList.title')} /> ); } }
src/components/Sun/Sun.js
vanbujm/react-css-animation-practice
/* eslint-disable react/forbid-prop-types */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Sun.css'; class Sun extends React.Component { static propTypes = { width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, className: PropTypes.string, }; // className={this.props.className} width={this.props.width} height={this.props.height} render() { return ( <svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg" className={this.props.className} width={this.props.width} height={this.props.height}> <defs> <pattern id="pattern-0" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse" viewBox="0 0 100 100"> <path d="M 0 0 L 50 0 L 50 100 L 0 100 Z" style={{ fill: 'black' }} /> </pattern> <radialGradient id="gradient-2" gradientUnits="userSpaceOnUse" cx="750.1" cy="246.7" r="194.4" gradientTransform="matrix(0.70129, -0.00058, 0.00056, 0.66914, -288.07928, 79.72377)"> <stop offset="0" style={{ stopColor: 'rgb(255, 255, 255)' }} /> <stop offset="1" style={{ stopColor: 'rgb(255, 136, 0)' }} /> </radialGradient> <radialGradient id="gradient-1" gradientUnits="userSpaceOnUse" cx="750.1" cy="246.7" r="194.4" gradientTransform="matrix(1.15882, -0.00483, 0.00463, 1.11173, -630.70203, -24.15555)"> <stop offset="0" style={{ stopColor: 'rgb(255, 136, 0)' }} /> <stop offset="1" style={{ stopColor: 'rgba(255, 136, 0, 0)' }} /> </radialGradient> </defs> <ellipse style={{ fill: 'url(#gradient-1)', strokeWidth: 70 }} cx="247.7" cy="251.4" rx="239.3" ry="239.3" /> <ellipse style={{ fill: 'url(#gradient-2)', strokeWidth: 70 }} cx="243" cy="247.4" rx="146.5" ry="146.5" /> { this.props.children } </svg> ); } } Sun.defaultProps = { className: '', }; export default withStyles(s)(Sun);
src/Deck.js
spudly/react-deck
import Card from 'react-card'; import React from 'react'; import validateChildren from './validateChildren'; const Deck = ({children}) => <ul className="deck"> {React.Children.map(children, child => <li>{child}</li>)} </ul>; Deck.displayName = 'Deck'; Deck.Card = Card; Deck.propTypes = { children: validateChildren, }; export default Deck;
src/svg-icons/action/view-column.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewColumn = (props) => ( <SvgIcon {...props}> <path d="M10 18h5V5h-5v13zm-6 0h5V5H4v13zM16 5v13h5V5h-5z"/> </SvgIcon> ); ActionViewColumn = pure(ActionViewColumn); ActionViewColumn.displayName = 'ActionViewColumn'; ActionViewColumn.muiName = 'SvgIcon'; export default ActionViewColumn;
weekdays/App.js
rsperberg/react-native-exercises
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View } from 'react-native'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', }); export default class App extends Component<{}> { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! The home of the itcheegucci! </Text> <Text style={styles.instructions}> To get started, edit App.js </Text> <Text style={styles.instructions}> {instructions} </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
src/svg-icons/action/settings-bluetooth.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsBluetooth = (props) => ( <SvgIcon {...props}> <path d="M11 24h2v-2h-2v2zm-4 0h2v-2H7v2zm8 0h2v-2h-2v2zm2.71-18.29L12 0h-1v7.59L6.41 3 5 4.41 10.59 10 5 15.59 6.41 17 11 12.41V20h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 3.83l1.88 1.88L13 7.59V3.83zm1.88 10.46L13 16.17v-3.76l1.88 1.88z"/> </SvgIcon> ); ActionSettingsBluetooth = pure(ActionSettingsBluetooth); ActionSettingsBluetooth.displayName = 'ActionSettingsBluetooth'; ActionSettingsBluetooth.muiName = 'SvgIcon'; export default ActionSettingsBluetooth;
client/client/containers/Modal/ModalRoot.js
funkyOne/facts
import React from 'react' import {connect} from 'react-redux' import DeletePostModal from './edit-fact-modal' import Modal from 'react-bootstrap/lib/Modal'; const MODAL_COMPONENTS = { 'EDIT_FACT': DeletePostModal /* other modals */ } const ModalRoot = ({ modalType, modalProps }) => { if (!modalType) { return null } const SpecificModal = MODAL_COMPONENTS[modalType] return <SpecificModal {...modalProps} /> } export default connect( state => state.modal )(ModalRoot)
Libraries/Components/TextInput/TextInput.js
chnfeeeeeef/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 TextInput * @flow */ 'use strict'; const ColorPropType = require('ColorPropType'); const DocumentSelectionState = require('DocumentSelectionState'); const EventEmitter = require('EventEmitter'); const NativeMethodsMixin = require('NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const PropTypes = require('prop-types'); const ReactNative = require('ReactNative'); const StyleSheet = require('StyleSheet'); const Text = require('Text'); const TextInputState = require('TextInputState'); const TimerMixin = require('react-timer-mixin'); const TouchableWithoutFeedback = require('TouchableWithoutFeedback'); const UIManager = require('UIManager'); const ViewPropTypes = require('ViewPropTypes'); const emptyFunction = require('fbjs/lib/emptyFunction'); const invariant = require('fbjs/lib/invariant'); const requireNativeComponent = require('requireNativeComponent'); const warning = require('fbjs/lib/warning'); const onlyMultiline = { onTextInput: true, children: true, }; if (Platform.OS === 'android') { var AndroidTextInput = requireNativeComponent('AndroidTextInput', null); } else if (Platform.OS === 'ios') { var RCTTextView = requireNativeComponent('RCTTextView', null); var RCTTextField = requireNativeComponent('RCTTextField', null); } type Event = Object; type Selection = { start: number, end?: number, }; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; /** * A foundational component for inputting text into the app via a * keyboard. Props provide configurability for several features, such as * auto-correction, auto-capitalization, placeholder text, and different keyboard * types, such as a numeric keypad. * * The simplest use case is to plop down a `TextInput` and subscribe to the * `onChangeText` events to read the user input. There are also other events, * such as `onSubmitEditing` and `onFocus` that can be subscribed to. A simple * example: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, TextInput } from 'react-native'; * * export default class UselessTextInput extends Component { * constructor(props) { * super(props); * this.state = { text: 'Useless Placeholder' }; * } * * render() { * return ( * <TextInput * style={{height: 40, borderColor: 'gray', borderWidth: 1}} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * ); * } * } * * // skip this line if using Create React Native App * AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput); * ``` * * Note that some props are only available with `multiline={true/false}`. * Additionally, border styles that apply to only one side of the element * (e.g., `borderBottomColor`, `borderLeftWidth`, etc.) will not be applied if * `multiline=false`. To achieve the same effect, you can wrap your `TextInput` * in a `View`: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, TextInput } from 'react-native'; * * class UselessTextInput extends Component { * render() { * return ( * <TextInput * {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below * editable = {true} * maxLength = {40} * /> * ); * } * } * * export default class UselessTextInputMultiline extends Component { * constructor(props) { * super(props); * this.state = { * text: 'Useless Multiline Placeholder', * }; * } * * // If you type something in the text box that is a color, the background will change to that * // color. * render() { * return ( * <View style={{ * backgroundColor: this.state.text, * borderBottomColor: '#000000', * borderBottomWidth: 1 }} * > * <UselessTextInput * multiline = {true} * numberOfLines = {4} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * </View> * ); * } * } * * // skip these lines if using Create React Native App * AppRegistry.registerComponent( * 'AwesomeProject', * () => UselessTextInputMultiline * ); * ``` * * `TextInput` has by default a border at the bottom of its view. This border * has its padding set by the background image provided by the system, and it * cannot be changed. Solutions to avoid this is to either not set height * explicitly, case in which the system will take care of displaying the border * in the correct position, or to not display the border by setting * `underlineColorAndroid` to transparent. * * Note that on Android performing text selection in input can change * app's activity `windowSoftInputMode` param to `adjustResize`. * This may cause issues with components that have position: 'absolute' * while keyboard is active. To avoid this behavior either specify `windowSoftInputMode` * in AndroidManifest.xml ( https://developer.android.com/guide/topics/manifest/activity-element.html ) * or control this param programmatically with native code. * */ // $FlowFixMe(>=0.41.0) const TextInput = React.createClass({ statics: { /* TODO(brentvatne) docs are needed for this */ State: TextInputState, }, propTypes: { ...ViewPropTypes, /** * Can tell `TextInput` to automatically capitalize certain characters. * * - `characters`: all characters. * - `words`: first letter of each word. * - `sentences`: first letter of each sentence (*default*). * - `none`: don't auto capitalize anything. */ autoCapitalize: PropTypes.oneOf([ 'none', 'sentences', 'words', 'characters', ]), /** * If `false`, disables auto-correct. The default value is `true`. */ autoCorrect: PropTypes.bool, /** * If `false`, disables spell-check style (i.e. red underlines). * The default value is inherited from `autoCorrect`. * @platform ios */ spellCheck: PropTypes.bool, /** * If `true`, focuses the input on `componentDidMount`. * The default value is `false`. */ autoFocus: PropTypes.bool, /** * If `false`, text is not editable. The default value is `true`. */ editable: PropTypes.bool, /** * Determines which keyboard to open, e.g.`numeric`. * * The following values work across platforms: * * - `default` * - `numeric` * - `email-address` * - `phone-pad` */ keyboardType: PropTypes.oneOf([ // Cross-platform 'default', 'email-address', 'numeric', 'phone-pad', // iOS-only 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search', ]), /** * Determines the color of the keyboard. * @platform ios */ keyboardAppearance: PropTypes.oneOf([ 'default', 'light', 'dark', ]), /** * Determines how the return key should look. On Android you can also use * `returnKeyLabel`. * * *Cross platform* * * The following values work across platforms: * * - `done` * - `go` * - `next` * - `search` * - `send` * * *Android Only* * * The following values work on Android only: * * - `none` * - `previous` * * *iOS Only* * * The following values work on iOS only: * * - `default` * - `emergency-call` * - `google` * - `join` * - `route` * - `yahoo` */ returnKeyType: PropTypes.oneOf([ // Cross-platform 'done', 'go', 'next', 'search', 'send', // Android-only 'none', 'previous', // iOS-only 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo', ]), /** * Sets the return key to the label. Use it instead of `returnKeyType`. * @platform android */ returnKeyLabel: PropTypes.string, /** * Limits the maximum number of characters that can be entered. Use this * instead of implementing the logic in JS to avoid flicker. */ maxLength: PropTypes.number, /** * Sets the number of lines for a `TextInput`. Use it with multiline set to * `true` to be able to fill the lines. * @platform android */ numberOfLines: PropTypes.number, /** * When `false`, if there is a small amount of space available around a text input * (e.g. landscape orientation on a phone), the OS may choose to have the user edit * the text inside of a full screen text input mode. When `true`, this feature is * disabled and users will always edit the text directly inside of the text input. * Defaults to `false`. * @platform android */ disableFullscreenUI: PropTypes.bool, /** * If `true`, the keyboard disables the return key when there is no text and * automatically enables it when there is text. The default value is `false`. * @platform ios */ enablesReturnKeyAutomatically: PropTypes.bool, /** * If `true`, the text input can be multiple lines. * The default value is `false`. */ multiline: PropTypes.bool, /** * Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced` * The default value is `simple`. * @platform android */ textBreakStrategy: PropTypes.oneOf(['simple', 'highQuality', 'balanced']), /** * Callback that is called when the text input is blurred. */ onBlur: PropTypes.func, /** * Callback that is called when the text input is focused. */ onFocus: PropTypes.func, /** * Callback that is called when the text input's text changes. */ onChange: PropTypes.func, /** * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ onChangeText: PropTypes.func, /** * Callback that is called when the text input's content size changes. * This will be called with * `{ nativeEvent: { contentSize: { width, height } } }`. * * Only called for multiline text inputs. */ onContentSizeChange: PropTypes.func, /** * Callback that is called when text input ends. */ onEndEditing: PropTypes.func, /** * Callback that is called when the text input selection is changed. * This will be called with * `{ nativeEvent: { selection: { start, end } } }`. */ onSelectionChange: PropTypes.func, /** * Callback that is called when the text input's submit button is pressed. * Invalid if `multiline={true}` is specified. */ onSubmitEditing: PropTypes.func, /** * Callback that is called when a key is pressed. * This will be called with `{ nativeEvent: { key: keyValue } }` * where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and * the typed-in character otherwise including `' '` for space. * Fires before `onChange` callbacks. * @platform ios */ onKeyPress: PropTypes.func, /** * Invoked on mount and layout changes with `{x, y, width, height}`. */ onLayout: PropTypes.func, /** * Invoked on content scroll with `{ nativeEvent: { contentOffset: { x, y } } }`. * May also contain other properties from ScrollEvent but on Android contentSize * is not provided for performance reasons. */ onScroll: PropTypes.func, /** * The string that will be rendered before text input has been entered. */ placeholder: PropTypes.node, /** * The text color of the placeholder string. */ placeholderTextColor: ColorPropType, /** * If `true`, the text input obscures the text entered so that sensitive text * like passwords stay secure. The default value is `false`. */ secureTextEntry: PropTypes.bool, /** * The highlight and cursor color of the text input. */ selectionColor: ColorPropType, /** * An instance of `DocumentSelectionState`, this is some state that is responsible for * maintaining selection information for a document. * * Some functionality that can be performed with this instance is: * * - `blur()` * - `focus()` * - `update()` * * > You can reference `DocumentSelectionState` in * > [`vendor/document/selection/DocumentSelectionState.js`](https://github.com/facebook/react-native/blob/master/Libraries/vendor/document/selection/DocumentSelectionState.js) * * @platform ios */ selectionState: PropTypes.instanceOf(DocumentSelectionState), /** * The start and end of the text input's selection. Set start and end to * the same value to position the cursor. */ selection: PropTypes.shape({ start: PropTypes.number.isRequired, end: PropTypes.number, }), /** * The value to show for the text input. `TextInput` is a controlled * component, which means the native value will be forced to match this * value prop if provided. For most uses, this works great, but in some * cases this may cause flickering - one common cause is preventing edits * by keeping value the same. In addition to simply setting the same value, * either set `editable={false}`, or set/update `maxLength` to prevent * unwanted edits without flicker. */ value: PropTypes.string, /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you do not want to deal with listening * to events and updating the value prop to keep the controlled state in sync. */ defaultValue: PropTypes.string, /** * When the clear button should appear on the right side of the text view. * @platform ios */ clearButtonMode: PropTypes.oneOf([ 'never', 'while-editing', 'unless-editing', 'always', ]), /** * If `true`, clears the text field automatically when editing begins. * @platform ios */ clearTextOnFocus: PropTypes.bool, /** * If `true`, all text will automatically be selected on focus. */ selectTextOnFocus: PropTypes.bool, /** * If `true`, the text field will blur when submitted. * The default value is true for single-line fields and false for * multiline fields. Note that for multiline fields, setting `blurOnSubmit` * to `true` means that pressing return will blur the field and trigger the * `onSubmitEditing` event instead of inserting a newline into the field. */ blurOnSubmit: PropTypes.bool, /** * Note that not all Text styles are supported, * see [Issue#7070](https://github.com/facebook/react-native/issues/7070) * for more detail. * * [Styles](docs/style.html) */ style: Text.propTypes.style, /** * The color of the `TextInput` underline. * @platform android */ underlineColorAndroid: ColorPropType, /** * If defined, the provided image resource will be rendered on the left. * @platform android */ inlineImageLeft: PropTypes.string, /** * Padding between the inline image, if any, and the text input itself. * @platform android */ inlineImagePadding: PropTypes.number, /** * Determines the types of data converted to clickable URLs in the text input. * Only valid if `multiline={true}` and `editable={false}`. * By default no data types are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * If `true`, caret is hidden. The default value is `false`. */ caretHidden: PropTypes.bool, }, /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ mixins: [NativeMethodsMixin, TimerMixin], /** * Returns `true` if the input is currently focused; `false` otherwise. */ isFocused: function(): boolean { return TextInputState.currentlyFocusedField() === ReactNative.findNodeHandle(this._inputRef); }, contextTypes: { onFocusRequested: PropTypes.func, focusEmitter: PropTypes.instanceOf(EventEmitter), }, _inputRef: (undefined: any), _focusSubscription: (undefined: ?Function), _lastNativeText: (undefined: ?string), _lastNativeSelection: (undefined: ?Selection), componentDidMount: function() { this._lastNativeText = this.props.value; if (!this.context.focusEmitter) { if (this.props.autoFocus) { this.requestAnimationFrame(this.focus); } return; } this._focusSubscription = this.context.focusEmitter.addListener( 'focus', (el) => { if (this === el) { this.requestAnimationFrame(this.focus); } else if (this.isFocused()) { this.blur(); } } ); if (this.props.autoFocus) { this.context.onFocusRequested(this); } }, componentWillUnmount: function() { this._focusSubscription && this._focusSubscription.remove(); if (this.isFocused()) { this.blur(); } }, getChildContext: function(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: PropTypes.bool }, /** * Removes all text from the `TextInput`. */ clear: function() { this.setNativeProps({text: ''}); }, render: function() { if (Platform.OS === 'ios') { return this._renderIOS(); } else if (Platform.OS === 'android') { return this._renderAndroid(); } }, _getText: function(): ?string { return typeof this.props.value === 'string' ? this.props.value : ( typeof this.props.defaultValue === 'string' ? this.props.defaultValue : '' ); }, _setNativeRef: function(ref: any) { this._inputRef = ref; }, _renderIOS: function() { var textContainer; var props = Object.assign({}, this.props); props.style = [styles.input, this.props.style]; if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } if (!props.multiline) { if (__DEV__) { for (var propKey in onlyMultiline) { if (props[propKey]) { const error = new Error( 'TextInput prop `' + propKey + '` is only supported with multiline.' ); warning(false, '%s', error.stack); } } } textContainer = <RCTTextField ref={this._setNativeRef} {...props} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} />; } else { var children = props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(props.value && childCount), 'Cannot specify both value and children.' ); if (childCount >= 1) { children = <Text style={props.style}>{children}</Text>; } if (props.inputView) { children = [children, props.inputView]; } props.style.unshift(styles.multilineInput); textContainer = <RCTTextView ref={this._setNativeRef} {...props} children={children} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onContentSizeChange={this.props.onContentSizeChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} dataDetectorTypes={this.props.dataDetectorTypes} onScroll={this._onScroll} />; } return ( <TouchableWithoutFeedback onLayout={props.onLayout} onPress={this._onPress} rejectResponderTermination={true} accessible={props.accessible} accessibilityLabel={props.accessibilityLabel} accessibilityTraits={props.accessibilityTraits} nativeID={this.props.nativeID} testID={props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _renderAndroid: function() { const props = Object.assign({}, this.props); props.style = [this.props.style]; props.autoCapitalize = UIManager.AndroidTextInput.Constants.AutoCapitalizationType[this.props.autoCapitalize]; var children = this.props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(this.props.value && childCount), 'Cannot specify both value and children.' ); if (childCount > 1) { children = <Text>{children}</Text>; } if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } const textContainer = <AndroidTextInput ref={this._setNativeRef} {...props} mostRecentEventCount={0} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} text={this._getText()} children={children} disableFullscreenUI={this.props.disableFullscreenUI} textBreakStrategy={this.props.textBreakStrategy} onScroll={this._onScroll} />; return ( <TouchableWithoutFeedback onLayout={this.props.onLayout} onPress={this._onPress} accessible={this.props.accessible} accessibilityLabel={this.props.accessibilityLabel} accessibilityComponentType={this.props.accessibilityComponentType} nativeID={this.props.nativeID} testID={this.props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _onFocus: function(event: Event) { if (this.props.onFocus) { this.props.onFocus(event); } if (this.props.selectionState) { this.props.selectionState.focus(); } }, _onPress: function(event: Event) { if (this.props.editable || this.props.editable === undefined) { this.focus(); } }, _onChange: function(event: Event) { // Make sure to fire the mostRecentEventCount first so it is already set on // native when the text value is set. if (this._inputRef) { this._inputRef.setNativeProps({ mostRecentEventCount: event.nativeEvent.eventCount, }); } var text = event.nativeEvent.text; this.props.onChange && this.props.onChange(event); this.props.onChangeText && this.props.onChangeText(text); if (!this._inputRef) { // calling `this.props.onChange` or `this.props.onChangeText` // may clean up the input itself. Exits here. return; } this._lastNativeText = text; this.forceUpdate(); }, _onSelectionChange: function(event: Event) { this.props.onSelectionChange && this.props.onSelectionChange(event); if (!this._inputRef) { // calling `this.props.onSelectionChange` // may clean up the input itself. Exits here. return; } this._lastNativeSelection = event.nativeEvent.selection; if (this.props.selection || this.props.selectionState) { this.forceUpdate(); } }, componentDidUpdate: function () { // This is necessary in case native updates the text and JS decides // that the update should be ignored and we should stick with the value // that we have in JS. const nativeProps = {}; if (this._lastNativeText !== this.props.value && typeof this.props.value === 'string') { nativeProps.text = this.props.value; } // Selection is also a controlled prop, if the native value doesn't match // JS, update to the JS value. const {selection} = this.props; if (this._lastNativeSelection && selection && (this._lastNativeSelection.start !== selection.start || this._lastNativeSelection.end !== selection.end)) { nativeProps.selection = this.props.selection; } if (Object.keys(nativeProps).length > 0 && this._inputRef) { this._inputRef.setNativeProps(nativeProps); } if (this.props.selectionState && selection) { this.props.selectionState.update(selection.start, selection.end); } }, _onBlur: function(event: Event) { this.blur(); if (this.props.onBlur) { this.props.onBlur(event); } if (this.props.selectionState) { this.props.selectionState.blur(); } }, _onTextInput: function(event: Event) { this.props.onTextInput && this.props.onTextInput(event); }, _onScroll: function(event: Event) { this.props.onScroll && this.props.onScroll(event); }, }); var styles = StyleSheet.create({ input: { alignSelf: 'stretch', }, multilineInput: { // This default top inset makes RCTTextView seem as close as possible // to single-line RCTTextField defaults, using the system defaults // of font size 17 and a height of 31 points. paddingTop: 5, }, }); module.exports = TextInput;
app/components/DropdownFontSelector.js
googlefonts/korean
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { FONTS, BODY_600 } from '../constants/defaults'; import { changeDescFontDropdownOpened } from '../actions'; import { getCurrentDescFont } from '../utils'; const Fragment = React.Fragment; class DropdownFontSelector extends Component { handleDropdownClick(e){ e.stopPropagation(); if (!this.props.descFontDropdownOpened) { this.props.dispatch(changeDescFontDropdownOpened(true)); } } render() { let { currentDescFontSelected, locale, backgroundMode, screenWidth } = this.props; let currentDescFont = getCurrentDescFont(this.props.currentDescFont, currentDescFontSelected); return ( <div className="dropdown-font-selector"> <a href="javascript:void(0);" onClick={this.handleDropdownClick.bind(this)} className="dropdown-font-selector__selected"> { locale == "ko" ? <Fragment> <div className="dropdown-font-selector__ko ko-black" style={{ fontSize: screenWidth > BODY_600 ? '14px' : '14px' }}>{ currentDescFont.nameKo }</div> { // screenWidth > BODY_600 ? // <div className="dropdown-font-selector__en en-regular">{ currentDescFont.nameEn }</div> // : null } <div style={{ marginTop: -2 }}><img src={`./public/assets/arrow_down_${backgroundMode}.svg`} alt="arrow_down" /></div> </Fragment> : <Fragment> <div className="dropdown-font-selector__en en-black" style={{ fontSize: screenWidth > BODY_600 ? '14px' : '14px' }}>{ currentDescFont.nameEn }</div> { // screenWidth > BODY_600 ? // <div className="dropdown-font-selector__ko">{ currentDescFont.nameKo }</div> // : null } <div style={{ marginTop: -2 }}><img src={`./public/assets/arrow_down_${backgroundMode}.svg`} alt="arrow_down" /></div> </Fragment> } </a> </div> ); } } let mapStateToProps = state => { return { currentDescFont: state.currentDescFont, screenWidth: state.screenWidth, backgroundMode: state.backgroundMode == "black" ? "white" : "black", locale: state.locale, currentDescFontSelected: state.currentDescFontSelected } } export default connect(mapStateToProps)(DropdownFontSelector); //<div style={{ marginTop: screenWidth > BODY_600 ? -6 : 0 }}><img src={`./public/assets/arrow_down_${backgroundMode}.svg`} alt="arrow_down" /></div>
src/components/HomePage/CardGroup.js
KidsFirstProject/KidsFirstProject.github.io
import React from 'react'; import { Button, Card, Col, Row } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; import styles from './CardGroup.module.css'; import aboutImage from '../../assets/images/shelter/shelter005.jpg'; import teamImage from '../../assets/images/shelter/shelter020.jpg'; import programImage from '../../assets/images/shelter/shelter001.jpg'; const cards = [ { imageUrl: aboutImage, title: 'What is Kids First Project?', text: 'Kids First Project is a 501(c)(3) non-profit organization that brings programs and services to homeless youth living in shelters.', ctaLink: '/about', ctaText: 'Learn More' }, { imageUrl: teamImage, title: 'Mission Statement', text: 'Our mission is to empower youth experiencing homelessness to reach their full potential and help break the generational cycle of poverty.', ctaLink: '/team', ctaText: 'Meet the Team' }, { imageUrl: programImage, title: 'What We Do', text: 'We offer in-shelter educational and recreational programs, a Scholarship Program, and additional service and advocacy opportunities.', ctaLink: '/programs/inshelter', ctaText: 'Find Programs' } ]; const CardGroup = () => ( <Row className={styles.groupContainer}> {cards.map(({ imageUrl, title, text, ctaLink, ctaText }, index) => ( <Col lg key={`card-${index}`}> <Card style={{ border: 'none' }}> <Card.Img variant="top" src={imageUrl} /> <Card.Body> <Card.Title>{title}</Card.Title> <Card.Text>{text}</Card.Text> <LinkContainer to={ctaLink}> <Button variant="primary">{ctaText}</Button> </LinkContainer> </Card.Body> </Card> </Col> ))} </Row> ); export default CardGroup;
src/esm/components/graphics/icons-next/lock-outline-icon/index.js
KissKissBankBank/kitten
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["color", "title"]; import React from 'react'; import PropTypes from 'prop-types'; export var LockOutlineIcon = function LockOutlineIcon(_ref) { var color = _ref.color, title = _ref.title, props = _objectWithoutPropertiesLoose(_ref, _excluded); return /*#__PURE__*/React.createElement("svg", _extends({ width: "21", height: "25", viewBox: "0 0 21 25", xmlns: "http://www.w3.org/2000/svg", fill: "none" }, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", { fill: color, d: "M10.5 14c-.642 0-1.162.52-1.162 1.161v3.94a1.16 1.16 0 102.323 0v-3.94c0-.641-.52-1.161-1.161-1.161z" }), /*#__PURE__*/React.createElement("path", { fill: color, d: "M10.5.4a5.806 5.806 0 00-5.806 5.806V9.69h-.388a4.258 4.258 0 00-4.258 4.258v6.194A4.258 4.258 0 004.306 24.4h12.387a4.258 4.258 0 004.259-4.258v-6.194a4.258 4.258 0 00-4.259-4.258h-.387V6.206A5.806 5.806 0 0010.5.4zM7.016 6.206a3.484 3.484 0 116.968 0V9.69H7.016V6.206zm9.678 5.807a1.935 1.935 0 011.935 1.935v6.194a1.935 1.935 0 01-1.936 1.935H4.306a1.935 1.935 0 01-1.935-1.935v-6.194a1.936 1.936 0 011.935-1.935h12.387z" })); }; LockOutlineIcon.propTypes = { color: PropTypes.string, title: PropTypes.string }; LockOutlineIcon.defaultProps = { color: '#222', title: '' };
src/components/Header/Header.js
sbiliaiev/transport-kharkiv
import React from 'react'; import './Header.css'; export default function Header() { return( <div className="header-logo"> <h1>Transport_KH</h1> <h3>Administration Panel</h3> </div> ); }
demo08/src/routes/IndexPage.js
lxlneo/reactdemo
import React, { Component } from 'react'; import { connect } from 'dva'; import { Layout, Row, Col, Tabs, Button, Spin, Icon } from 'antd'; import { Link } from 'dva/router'; import Topics from '../components/Topics/Topics'; import styles from './IndexPage.css'; import transformDate from '../utils/transformDate'; import getSize from '../utils/getSize'; const { Header, Content } = Layout; const TabPane = Tabs.TabPane; class IndexPage extends Component { constructor(props) { super(props); this.state = { sideShow: false, scrollT: 0, }; } componentWillMount() { // } componentDidMount() { const { dispatch, tab } = this.props; dispatch({ type: 'IndexPage/fetchTopics', payload: { tab } }); // if (scrollT) { // widnow.scrollTo(0, scrollT); // } } componentWillReceiveProps(nextProps) { const { loginData, tab, profile, dispatch, loading2 } = nextProps; if (!loading2 && loginData.loginName && loginData.loginName !== profile.loginName) { dispatch({ type: 'profile/fetchProfile', payload: loginData.loginName }); } // 去除刷新时记住的滚动条位置 if (this.props.scrollT === 0) { window.scrollTo(0, 0); } window.onscroll = () => { const { windowH, contentH, scrollT } = getSize(); if (windowH + scrollT + 100 > contentH) { //这里dispatch recordScroll会执行两次,一次得到的scrollT是正常值,另一次为0; if (scrollT > 0) { this.setState({ scrollT: parseInt(scrollT, 10) }); } dispatch({ type: 'IndexPage/recordScrollT', payload: { tab, scrollT: this.state.scrollT } }); this.loadMore(); } // 由于下面的操作比较费cpu,所以进行判断是否为手机端 // const ua = navigator.userAgent; // if (ua.indexOf('Mobile') === -1) { // if (!lastScrollY || !scrollT) { // lastScrollY = scrollT; // } // const diff = scrollT - lastScrollY; // if (diff >= 0) { // if (scrollT > 64 && this.state.fixedTop !== 64) { // this.setState({ // fixedTop: 64, // }); // } // if (scrollT <= 64) { // this.setState({ // fixedTop: scrollT, // }); // } // } else { // this.setState({ // scrollT: 0, // }); // if (scrollT > 64 && this.state.fixedTop !== 0) { // this.setState({ // fixedTop: 0, // }); // } // } // lastScrollY = scrollT; // } }; } componentDidUpdate() { // let { windowH, contentH, scrollT } = getSize(); const { currentTopicT } = this.props; // 根据不同的tab决定滚动条的位置 if (currentTopicT) { window.scrollTo(0, currentTopicT); } else { window.scrollTo(0, 0); } } componentWillUnmount() { let { scrollT } = getSize(); const { tab, dispatch } = this.props; // dispatch({ type: 'IndexPage/recordScrollT', payload: { tab, scrollT } }); // 必须解绑事件,否则当组件再次被加载时,该事件会监听两个组件 window.onscroll = null; } tabs = [ { title: '全部', filter: 'all', }, { title: '精华', filter: 'good', }, { title: '分享', filter: 'share', }, { title: '问答', filter: 'ask', }, { title: '招聘', filter: 'job', }, ] loadMore = () => { const { tab, page, dispatch, loading } = this.props; let ipage = page; if (!loading) { dispatch({ type: 'IndexPage/fetchTopics', payload: { tab, page: ++ipage } }); } } handlerTabClick(activeKey) { const { dispatch } = this.props; const tab = this.tabs[activeKey].filter; dispatch({ type: 'IndexPage/fetchTopics', payload: { tab } }); dispatch({ type: 'IndexPage/selectTab', payload: { tab, activeKey: activeKey.toString() } }); } handleClick() { this.setState({ sideShow: true }); } handleClose() { this.setState({ sideShow: false }); } handleLoginOut() { const { dispatch } = this.props; this.setState({ sideShow: false }); window.localStorage.removeItem('loginInfo'); window.sessionStorage.removeItem('loginInfo'); dispatch({ type: 'login/loginOut' }); } render() { const { data, loading, loading2, dispatch, tab, profile, loginData, message, activeKey } = this.props; const succeed = loginData.succeed; if (!loading2 && succeed) { var { avatar_url, create_at, loginname, score } = profile.profile;// 不能用const或者let,因为他们形成了块级作用域 } const tabs = this.tabs; function tabpane() { return tabs.map((v, k) => ( <TabPane tab={v.title} key={k}> { v.filter === tab && <Topics loading={loading} data={data} dispatch={dispatch} />} </TabPane> )); } return ( <div className={styles.normal}> <Header style={{ background: '#108EE9', color: '#fff' }}> <Row> <Col span={4} style={{ textAlign: 'left' }}> <Button type="primary" shape="circle" icon="bars" onClick={this.handleClick.bind(this)} /> </Col> <Col span={16} className={styles.title}>NodeJs</Col> <Col span={4} style={{ textAlign: 'right' }}> <Link to="message" style={{ position: 'relative' }}> <Button type="primary" shape="circle" icon="bell" /> <span className={styles.message}>{ message.hasReadMessage ? message.hasReadMessage.length + message.hasNotReadMessage.length : 0 }</span> </Link> </Col> </Row> <div className={styles.mask} style={{ display: this.state.sideShow ? 'block' : 'none' }} onClick={this.handleClose.bind(this)} ></div> <div className={styles.sideBar} style={{ display: this.state.sideShow ? 'block' : 'none' }}> { !loading2 && succeed && <div> <div className={styles.profile}> <Link to={`profile/${loginname}`}><img src={avatar_url} alt={loginname} /></Link> <p>{loginname}</p> <p>积分:{score}</p> <p>注册于:{transformDate(create_at)}</p> <p><Button onClick={this.handleLoginOut.bind(this)}>注销登录</Button></p> </div> <ul className={styles.funcList}> <li> <Link to={`profile/${loginname}`}><Icon type="user" style={{ marginRight: '10px' }} />个人中心</Link> </li> <li> <Link to={`profile/${loginname}`}><Icon type="mail" style={{ marginRight: '10px' }} />未读信息</Link> </li> </ul> </div> } {!succeed && <div className={styles.profile}> <Link to="login"> <b><Icon type="user" style={{ fontSize: '24px', color: '#fff' }} /></b> </Link> <p>点击头像登录</p> </div> } </div> </Header> <Content> <Tabs type="line" defaultActiveKey={activeKey || '0'} onTabClick={this.handlerTabClick.bind(this)}> { tabpane() } </Tabs> </Content> </div> ); } } const mapStateToProps = (state) => { const { data, tab, page, scrollT, activeKey } = state.IndexPage; return { loading: state.loading.models.IndexPage, loading2: state.loading.models.profile, profile: state.profile, loginData: state.login, message: state.message, currentTopicT: state.IndexPage[tab], data, tab, page, scrollT, activeKey, }; }; export default connect(mapStateToProps)(IndexPage);
node_modules/react-bootstrap/es/FormControlFeedback.js
hsavit1/gosofi_webpage
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import Glyphicon from './Glyphicon'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var defaultProps = { bsRole: 'feedback' }; var contextTypes = { $bs_formGroup: PropTypes.object }; var FormControlFeedback = function (_React$Component) { _inherits(FormControlFeedback, _React$Component); function FormControlFeedback() { _classCallCheck(this, FormControlFeedback); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } FormControlFeedback.prototype.getGlyph = function getGlyph(validationState) { switch (validationState) { case 'success': return 'ok'; case 'warning': return 'warning-sign'; case 'error': return 'remove'; default: return null; } }; FormControlFeedback.prototype.renderDefaultFeedback = function renderDefaultFeedback(formGroup, className, classes, elementProps) { var glyph = this.getGlyph(formGroup && formGroup.validationState); if (!glyph) { return null; } return React.createElement(Glyphicon, _extends({}, elementProps, { glyph: glyph, className: classNames(className, classes) })); }; FormControlFeedback.prototype.render = function render() { var _props = this.props, className = _props.className, children = _props.children, props = _objectWithoutProperties(_props, ['className', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); if (!children) { return this.renderDefaultFeedback(this.context.$bs_formGroup, className, classes, elementProps); } var child = React.Children.only(children); return React.cloneElement(child, _extends({}, elementProps, { className: classNames(child.props.className, className, classes) })); }; return FormControlFeedback; }(React.Component); FormControlFeedback.defaultProps = defaultProps; FormControlFeedback.contextTypes = contextTypes; export default bsClass('form-control-feedback', FormControlFeedback);
packages/mcs-lite-admin-web/src/containers/Data/Data.js
MCS-Lite/mcs-lite
import React from 'react'; import PropTypes from 'prop-types'; import * as R from 'ramda'; import { Observable } from 'rxjs/Observable'; import Helmet from 'react-helmet'; import A from 'mcs-lite-ui/lib/A'; import P from 'mcs-lite-ui/lib/P'; import DashboardTitle from '../../components/DashboardTitle'; import DashboardDesc from '../../components/DashboardDesc'; import DialogConfirm from '../../components/DialogConfirm'; import { componentFromStream, createEventHandler, } from '../../utils/recomposeHelper'; const Data = componentFromStream(props$ => { const { handler: onResetClick, stream: onResetClick$ } = createEventHandler(); const { handler: onCancel, stream: onCancel$ } = createEventHandler(); const { handler: onSubmit, stream: onSubmit$ } = createEventHandler(); const isDialogShow$ = Observable.merge( onResetClick$.mapTo(true), onCancel$.mapTo(false), onSubmit$.mapTo(false), ).startWith(false); // Remind: delete Side-effects. onSubmit$ .withLatestFrom(props$, (e, { deleteData, getMessages: t }) => deleteData.bind(null, t('reset.success')), ) .subscribe(R.call); return props$.combineLatest( isDialogShow$, ({ getMessages: t }, isDialogShow) => ( <div> <Helmet> <title>{t('dataManagement')}</title> </Helmet> <DialogConfirm show={isDialogShow} onCancel={onCancel} onSubmit={onSubmit} > <P>{t('reset.confirm1')}</P> <P>{t('reset.confirm2')}</P> </DialogConfirm> <DashboardTitle title={t('dataManagement')}> <A onClick={onResetClick}>{t('reset')}</A> </DashboardTitle> <DashboardDesc>{t('description')}</DashboardDesc> </div> ), ); }); Data.displayName = 'Data'; Data.propTypes = { // Redux Action deleteData: PropTypes.func.isRequired, // React-intl I18n getMessages: PropTypes.func.isRequired, }; export default Data;
src/library/Icon/IconRadioButtonCheck.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconRadioButtonCheck(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <circle cx="12" cy="12" r="3.43" /> </g> </Icon> ); } IconRadioButtonCheck.displayName = 'IconRadioButtonCheck'; IconRadioButtonCheck.category = 'toggle';
frontend/src/admin/networkManagement/networkAdminsView/EditNetworkAdminForm.js
rabblerouser/core
import React from 'react'; import { connect } from 'react-redux'; import { Field, reduxForm } from 'redux-form'; import { InputField, FormHeaderWithSave } from '../../common/forms'; import { getSelectedNetworkAdmin, getSelectedNetworkAdminEmail, getIsCreating } from './reducers'; import { networkAdminUpdateRequested as update, networkAdminCreateRequested as create, finishEditNetworkAdmin, } from './actions'; import validate from './networkAdminValidator'; const onSubmit = (data, dispatch) => ( dispatch(data.id ? update(data) : create(data)) .then(() => dispatch(finishEditNetworkAdmin())) ); export const EditNetworkAdminForm = ({ handleSubmit, isCreating, email }) => ( <form onSubmit={handleSubmit}> <section> <FormHeaderWithSave> Network Admin details </FormHeaderWithSave> {isCreating ? <Field component={InputField} name="email" label="Email" type="email" /> : email } <Field component={InputField} name="name" label="Name" type="text" /> <Field component={InputField} name="phoneNumber" label="Contact number" type="text" /> {!isCreating && <aside>Leave blank to keep existing password</aside>} <Field component={InputField} name="password" label="Password" type="password" placeholder="••••••••••••" /> <Field component={InputField} name="confirmPassword" label="Confirm Password" type="password" /> </section> </form> ); const mapStateToProps = state => ({ initialValues: getIsCreating(state) ? {} : getSelectedNetworkAdmin(state), email: getIsCreating(state) ? '' : getSelectedNetworkAdminEmail(state), isCreating: getIsCreating(state), }); export default connect(mapStateToProps)(reduxForm({ form: 'networkAdmin', validate, onSubmit, })(EditNetworkAdminForm));
example/RNApp/app/routes/Profile/Profile.js
DesignmanIO/react-native-meteor-redux
import React from 'react'; import { Text, View, Image } from 'react-native'; import Button from '../../components/Button'; import Avatar from '../../components/Avatar'; import images from '../../config/images'; import { capitalize } from '../../lib/string'; import styles from './styles'; const Profile = (props) => { const { user, signOut } = props; let email; if (user) { email = user.emails[0].address; } return ( <View style={styles.container}> <Image style={styles.header} source={images.profileHeader} /> <View style={styles.body}> <Avatar email={email} /> <Text>{capitalize(email)}</Text> <Button text="Sign Out" onPress={signOut} /> </View> </View> ); }; Profile.propTypes = { user: React.PropTypes.object, signOut: React.PropTypes.func, }; export default Profile;
webpack/scenes/Subscriptions/Manifest/ManageManifestModal.js
tstrachota/katello
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Col, Tabs, Tab, Form, FormGroup, FormControl, ControlLabel, Row } from 'react-bootstrap'; import { bindMethods, Button, Icon, Modal, Spinner, OverlayTrigger, Tooltip } from 'patternfly-react'; import { isEqual } from 'lodash'; import TooltipButton from 'react-bootstrap-tooltip-button'; import { LoadingState } from '../../../move_to_pf/LoadingState'; import { Table } from '../../../move_to_foreman/components/common/table'; import ConfirmDialog from '../../../move_to_foreman/components/common/ConfirmDialog'; import { manifestExists } from '../SubscriptionHelpers'; import { columns } from './ManifestHistoryTableSchema'; import { renderTaskStartedToast } from '../../Tasks/helpers'; import DeleteManifestModalText from './DeleteManifestModalText'; import { BLOCKING_FOREMAN_TASK_TYPES, MANIFEST_TASKS_BULK_SEARCH_ID, } from '../SubscriptionConstants'; class ManageManifestModal extends Component { constructor(props) { super(props); this.state = { showModal: props.showModal, actionInProgress: props.taskInProgress, showDeleteManifestModalDialog: false, }; bindMethods(this, [ 'hideModal', 'saveOrganization', 'uploadManifest', 'refreshManifest', 'deleteManifest', 'disabledTooltipText', 'updateRepositoryUrl', ]); } static getDerivedStateFromProps(newProps, prevState) { if ( !isEqual(newProps.showModal, prevState.showModal) || !isEqual(newProps.taskInProgress, prevState.actionInProgress) ) { return { showModal: newProps.showModal, actionInProgress: newProps.taskInProgress, }; } return null; } componentDidMount() { this.loadData(); } componentDidUpdate(prevProp, prevState) { const { actionInProgress } = this.state; if (prevState.actionInProgress && !actionInProgress) { this.props.loadOrganization(); } } loadData() { this.props.loadManifestHistory(); } hideModal() { this.setState({ showModal: false, showDeleteManifestModalDialog: false }); this.props.onClose(); } updateRepositoryUrl(event) { this.setState({ redhat_repository_url: event.target.value }); } saveOrganization() { this.props.saveOrganization({ redhat_repository_url: this.state.redhat_repository_url }); } uploadManifest(fileList) { this.setState({ actionInProgress: true }); if (fileList.length > 0) { this.props .uploadManifest(fileList[0]) .then(() => this.props.bulkSearch({ search_id: MANIFEST_TASKS_BULK_SEARCH_ID, type: 'all', active_only: true, action_types: BLOCKING_FOREMAN_TASK_TYPES, })) .then(() => renderTaskStartedToast(this.props.taskDetails)); } } refreshManifest() { this.props.refreshManifest(); this.setState({ actionInProgress: true }); } deleteManifest() { this.setState({ actionInProgress: true }); this.props .deleteManifest() .then(() => this.props.bulkSearch({ search_id: MANIFEST_TASKS_BULK_SEARCH_ID, type: 'all', active_only: true, action_types: BLOCKING_FOREMAN_TASK_TYPES, })) .then(() => renderTaskStartedToast(this.props.taskDetails)); this.showDeleteManifestModal(false); } showDeleteManifestModal(show) { this.setState({ showDeleteManifestModalDialog: show, }); } disabledTooltipText() { if (this.state.actionInProgress) { return __('This is disabled because a manifest task is in progress'); } return __('This is disabled because no manifest exists'); } render() { const { manifestHistory, organization, disableManifestActions, disabledReason, } = this.props; const { actionInProgress } = this.state; const emptyStateData = () => ({ header: __('There is no Manifest History to display.'), description: __('Import a Manifest using the manifest tab above.'), documentation: { title: __('Learn more about adding Subscription Manifests'), url: 'http://redhat.com', }, }); const buttonLoading = ( <span> {__('Updating...')} <span className="fa fa-spinner fa-spin" /> </span>); const getManifestName = () => { let name = __('No Manifest Uploaded'); if ( organization.owner_details && organization.owner_details.upstreamConsumer ) { const link = [ 'https://', organization.owner_details.upstreamConsumer.webUrl, organization.owner_details.upstreamConsumer.uuid, ].join('/'); name = ( <a href={link}>{organization.owner_details.upstreamConsumer.name}</a> ); } return name; }; return ( <Modal show={this.state.showModal} onHide={this.hideModal}> <Modal.Header> <button className="close" onClick={this.hideModal} aria-label={__('Close')} > <Icon type="pf" name="close" /> </button> <Modal.Title>{__('Manage Manifest')}</Modal.Title> </Modal.Header> <Modal.Body> <Tabs id="manifest-history-tabs"> <Tab eventKey={1} title={__('Manifest')}> <Form className="form-horizontal"> <h5>{__('Red Hat Provider Details')}</h5> <hr /> <FormGroup> <Col sm={3}> <ControlLabel htmlFor="cdnUrl"> {__('Red Hat CDN URL')} </ControlLabel> </Col> <Col sm={9}> <FormControl id="cdnUrl" type="text" value={this.state.redhat_repository_url || organization.redhat_repository_url || ''} onChange={this.updateRepositoryUrl} /> </Col> </FormGroup> <FormGroup> <Col smOffset={3} sm={3}> <Button onClick={this.saveOrganization} disabled={organization.loading}> {organization.loading ? buttonLoading : __('Update')} </Button> </Col> </FormGroup> <br /> <h5>{__('Subscription Manifest')}</h5> <hr /> <FormGroup> <ControlLabel className="col-sm-3 control-label" htmlFor="usmaFile" > <OverlayTrigger overlay={ <Tooltip id="usma-tooltip"> {__('Upstream Subscription Management Application')} </Tooltip> } placement="bottom" trigger={['hover', 'focus']} rootClose={false} > <span>{__('USMA')}</span> </OverlayTrigger> </ControlLabel> <Col sm={9} className="manifest-actions"> <Spinner loading={actionInProgress} inline /> {getManifestName()} <FormControl id="usmaFile" type="file" accept=".zip" disabled={actionInProgress} onChange={e => this.uploadManifest(e.target.files)} /> <TooltipButton onClick={this.refreshManifest} tooltipId="refresh-manifest-button-tooltip" tooltipText={disabledReason} tooltipPlacement="top" title={__('Refresh')} disabled={!manifestExists(organization) || actionInProgress || disableManifestActions} /> <TooltipButton renderedButton={( <Button disabled={!manifestExists(organization) || actionInProgress} bsStyle="danger" onClick={() => this.showDeleteManifestModal(true)} > {__('Delete')} </Button> )} tooltipId="delete-manifest-button-tooltip" tooltipText={this.disabledTooltipText()} tooltipPlacement="top" /> <ConfirmDialog show={this.state.showDeleteManifestModalDialog} title={__('Confirm delete manifest')} dangerouslySetInnerHTML={{ __html: DeleteManifestModalText, }} confirmLabel={__('Delete')} confirmStyle="danger" onConfirm={() => this.deleteManifest()} onCancel={() => this.showDeleteManifestModal(false)} /> </Col> </FormGroup> </Form> </Tab> <Tab eventKey={2} title={__('Manifest History')}> <LoadingState loading={manifestHistory.loading} loadingText={__('Loading')}> <Table rows={manifestHistory.results} columns={columns} emptyState={emptyStateData()} /> </LoadingState> </Tab> </Tabs> </Modal.Body> <Modal.Footer> <Button bsStyle="primary" onClick={this.hideModal}> {__('Close')} </Button> </Modal.Footer> </Modal> ); } } ManageManifestModal.propTypes = { uploadManifest: PropTypes.func.isRequired, refreshManifest: PropTypes.func.isRequired, deleteManifest: PropTypes.func.isRequired, loadManifestHistory: PropTypes.func.isRequired, organization: PropTypes.shape({}).isRequired, disableManifestActions: PropTypes.bool, disabledReason: PropTypes.string, loadOrganization: PropTypes.func.isRequired, saveOrganization: PropTypes.func.isRequired, taskInProgress: PropTypes.bool.isRequired, manifestHistory: PropTypes.shape({}).isRequired, showModal: PropTypes.bool.isRequired, onClose: PropTypes.func, bulkSearch: PropTypes.func.isRequired, taskDetails: PropTypes.shape({}), }; ManageManifestModal.defaultProps = { taskDetails: undefined, disableManifestActions: false, disabledReason: '', onClose() {}, }; export default ManageManifestModal;
examples/todomvc/containers/Root.js
glifchits/redux
import React, { Component } from 'react'; import TodoApp from './TodoApp'; import { createStore, combineReducers } from 'redux'; import { Provider } from 'react-redux'; import rootReducer from '../reducers'; const store = createStore(rootReducer); export default class Root extends Component { render() { return ( <Provider store={store}> {() => <TodoApp /> } </Provider> ); } }
src/stories/layerSettings.js
Artsdatabanken/ecomap
import React from 'react' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' import { muiTheme } from 'storybook-addon-material-ui' import { Paper } from 'material-ui' import ActiveLayers from '../viewer/layer/ActiveLayers' import HexagonLayerSettings from '../viewer/layer/settings/layer/HexagonLayerSettings' import ScatterplotLayerSettings from '../viewer/layer/settings/layer/ScatterplotLayerSettings' import HeatmapLayerSettings from '../viewer/layer/settings/layer/HeatmapLayerSettings' import TemporalHeatmapLayerSettings from '../viewer/layer/settings/layer/TemporalHeatmapLayerSettings' import {VisualizationHexagon, VisualizationHeatmap, VisualizationScatterplot} from '../viewer/layer/settings/visualization/' class ActiveLayersTest extends React.Component { state = { layers: { '31241': { id: 31241, title: 'Alces alces', subTitle: 'elk', imageUrl: 'https://farm5.staticflickr.com/4107/4839886016_d11b6d2cdf.jpg', dataUrl: 'http://webtjenester.artsdatabanken.no/Artskart/api/listhelper/31241/observations?&fromYear=1981&toYear=2012&fromMonth=1&toMonth=12&type=all&region=all&scientificNameId=48103', source: 'geojson', visible: true, raster: false, paint: { visualizationMode: 'heatmap', fillColor: '#ff0000', fillOpacity: 1, blendMode: 'multiply' } } } }; handleUpdateLayerProp = (o, key, value) => { const layers = this.state.layers layers[o.id].paint[key] = value this.setState({ layers }) }; handleDeleteLayer = (layer) => { const layers = this.state.layers delete layers[layer.id] this.setState({ layers }) }; render () { return ( <ActiveLayers layers={this.state.layers} paint={{blendMode: 'multiply'}} onUpdateLayerProp={this.handleUpdateLayerProp} onDeleteLayer={(layer) => this.handleDeleteLayer(layer)} /> ) } } const layerSettings = () => storiesOf('Layer Settings', module) .addDecorator(muiTheme()) .add('primary', () => <NeutralBackground style={{ margin: '20px' }}> <ActiveLayersTest /> </NeutralBackground> ) .add('Heatmap', () => { let paint = { fillColor: '#ff0000', coverage: 0.95, fillOpacity: 1.0, radius: 1.0, visualizationMode: 'hexagon', blendMode: 'multiply', colorRamp: 'magma' } return ( <GiftWrap> <HeatmapLayerSettings {...paint} onChange={action('onUpdateLayerProp')} /> </GiftWrap> ) }) .add('Temporal Heatmap', () => { let paint = { fillColor: '#ff0000', coverage: 0.95, fillOpacity: 1.0, radius: 1.0, visualizationMode: 'hexagon', blendMode: 'multiply', colorRamp: 'magma' } return ( <GiftWrap> <TemporalHeatmapLayerSettings {...paint} onChange={action('onUpdateLayerProp')} /> </GiftWrap> ) }) .add('Scatterplot', () => { let paint = { fillColor: '#ff0000', coverage: 0.95, fillOpacity: 1.0, radius: 1.0, visualizationMode: 'hexagon', blendMode: 'multiply' } return ( <GiftWrap> <ScatterplotLayerSettings {...paint} onChange={action('onUpdateLayerProp')} /> </GiftWrap> ) }) .add('Hexagon', () => { let paint = { fillColor: '#ff0000', coverage: 0.95, fillOpacity: 1.0, radius: 1.0, visualizationMode: 'hexagon', blendMode: 'multiply', colorRamp: 'plasma' } return ( <GiftWrap> <HexagonLayerSettings {...paint} onChange={action('onUpdateLayerProp')} /> </GiftWrap> ) }) .add('Visualization Indicators', () => { return ( <GiftWrap> <VisualizationScatterplot colorRamp={['#000000', '#ffffff']} /> <VisualizationHeatmap colorRamp={['#000000', '#ffffff']} /> <VisualizationHexagon colorRamp={['#000000', '#ffffff']} /> </GiftWrap> ) }) const GiftWrap = ({children}) => <NeutralBackground> <div style={{ width: '400px', padding: '20px' }}> <Paper zDepth={4} style={{padding: '20px'}}> {children} </Paper> </div> </NeutralBackground> const NeutralBackground = ({children}) => <div style={{ position: 'absolute', width: '100%', height: '100%', backgroundColor: '#ccc'}}> {children} </div> export default layerSettings
docs/src/app/components/pages/components/Paper/ExampleCircle.js
frnk94/material-ui
import React from 'react'; import Paper from 'material-ui/Paper'; const style = { height: 100, width: 100, margin: 20, textAlign: 'center', display: 'inline-block', }; const PaperExampleCircle = () => ( <div> <Paper style={style} zDepth={1} circle={true} /> <Paper style={style} zDepth={2} circle={true} /> <Paper style={style} zDepth={3} circle={true} /> <Paper style={style} zDepth={4} circle={true} /> <Paper style={style} zDepth={5} circle={true} /> </div> ); export default PaperExampleCircle;
src/parser/rogue/outlaw/modules/spells/RollTheBonesEfficiency.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Analyzer from 'parser/core/Analyzer'; import RollTheBonesCastTracker, { ROLL_THE_BONES_CATEGORIES } from '../features/RollTheBonesCastTracker'; const MID_TIER_REFRESH_TIME = 11000; const HIGH_TIER_REFRESH_TIME = 3000; /** * Roll the Bones is pretty complex with a number of rules around when to use it. I've done my best to break this down into four main suggestions * Ruthless Precision and Grand Melee are the two 'good' buffs. The other four are 'bad' buffs * * 1 - Uptime (handled in separate module, as close to 100% as possible) * 2 - Low value rolls (1 'bad' buff, reroll as soon as you can) * 3 - Mid value rolls (2 'bad' buffs, reroll at the pandemic window) * 4 - High value rolls (1 'good' buff, 2 buffs where at least one is a 'good' buff, or 5 buffs, keep as long as you can, rerolling under 3 seconds is considered fine) */ class RollTheBonesEfficiency extends Analyzer { static dependencies = { rollTheBonesCastTracker: RollTheBonesCastTracker, }; constructor(...args) { super(...args); this.active = !this.selectedCombatant.hasTalent(SPELLS.SLICE_AND_DICE_TALENT.id); } get goodLowValueRolls(){ const delayedRolls = this.rollTheBonesCastTracker.rolltheBonesCastValues[ROLL_THE_BONES_CATEGORIES.LOW_VALUE] .filter(cast => cast.RTB_IsDelayed).length; const totalRolls = this.rollTheBonesCastTracker.rolltheBonesCastValues[ROLL_THE_BONES_CATEGORIES.LOW_VALUE].length; return totalRolls - delayedRolls; } get goodMidValueRolls(){ // todo get the actual pandemic window. it's tricky because it's based on the next cast, and it's not really important that the player is exact anyway return this.rollTheBonesCastTracker.rolltheBonesCastValues[ROLL_THE_BONES_CATEGORIES.MID_VALUE] .filter(cast => this.rollTheBonesCastTracker.castRemainingDuration(cast) > HIGH_TIER_REFRESH_TIME && this.rollTheBonesCastTracker.castRemainingDuration(cast) < MID_TIER_REFRESH_TIME).length; } get goodHighValueRolls(){ return this.rollTheBonesCastTracker.rolltheBonesCastValues[ROLL_THE_BONES_CATEGORIES.HIGH_VALUE] .filter(cast => this.rollTheBonesCastTracker.castRemainingDuration(cast) <= HIGH_TIER_REFRESH_TIME).length; } on_byPlayer_cast(event){ if(event.ability.guid !== SPELLS.DISPATCH.id && event.ability.guid !== SPELLS.BETWEEN_THE_EYES.id){ return; } const lastCast = this.rollTheBonesCastTracker.lastCast; if(lastCast && this.rollTheBonesCastTracker.categorizeCast(lastCast) === ROLL_THE_BONES_CATEGORIES.LOW_VALUE){ lastCast.RTB_IsDelayed = true; } } rollSuggestionThreshold(pass, total){ return { actual: total === 0 ? 1 : pass / total, isLessThan: { minor: 1, average: 0.9, major: 0.8, }, style: 'percentage', }; } get rollSuggestions(){ const rtbCastValues = this.rollTheBonesCastTracker.rolltheBonesCastValues; return [ // Percentage of low rolls that weren't rerolled right away, meaning a different finisher was cast first // Inverted to make all three suggestions consistent { label: 'low value', pass: this.goodLowValueRolls, total: rtbCastValues[ROLL_THE_BONES_CATEGORIES.LOW_VALUE].length, extraSuggestion: <>If you roll a single buff and it's not one of the two highest value, try to reroll it as soon as you can.</>, suggestionThresholds: this.rollSuggestionThreshold(this.goodLowValueRolls, rtbCastValues[ROLL_THE_BONES_CATEGORIES.LOW_VALUE].length), }, // Percentage of mid rolls that were rerolled at or below pandemic, but above 3 seconds { label: 'mid value', pass: this.goodMidValueRolls, total: rtbCastValues[ROLL_THE_BONES_CATEGORIES.MID_VALUE].length, extraSuggestion: <>If you roll two buffs and neither is one of the two highest value, try to reroll them once you reach the pandemic window, at about 9-10 seconds remaining.</>, suggestionThresholds: this.rollSuggestionThreshold(this.goodMidValueRolls, rtbCastValues[ROLL_THE_BONES_CATEGORIES.MID_VALUE].length), }, // Percentage of good rolls that were rerolled below 3 seconds { label: 'high value', pass: this.goodHighValueRolls, total: rtbCastValues[ROLL_THE_BONES_CATEGORIES.HIGH_VALUE].length, extraSuggestion: <>If you ever roll one of the two highest value buffs (especially with a 5 buff roll!), try to leave the buff active as long as possible, refreshing with less than 3 seconds remaining.</>, suggestionThresholds: this.rollSuggestionThreshold(this.goodHighValueRolls, rtbCastValues[ROLL_THE_BONES_CATEGORIES.HIGH_VALUE].length), }, ]; } suggestions(when) { this.rollSuggestions.forEach(suggestion => { when(suggestion.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest(<>Your efficiency with refreshing <SpellLink id={SPELLS.ROLL_THE_BONES.id} /> after a {suggestion.label} roll could be improved. <SpellLink id={SPELLS.RUTHLESS_PRECISION.id} /> and <SpellLink id={SPELLS.GRAND_MELEE.id} /> are your highest value buffs from <SpellLink id={SPELLS.ROLL_THE_BONES.id} />. {suggestion.extraSuggestion || ''}</>) .icon(SPELLS.ROLL_THE_BONES.icon) .actual(`${formatPercentage(actual)}% (${suggestion.pass} out of ${suggestion.total}) efficient rerolls`) .recommended(`${formatPercentage(recommended)}% is recommended`); }); }); } } export default RollTheBonesEfficiency;
src/components/signup.js
asommer70/thehoick-notes-server
import React, { Component } from 'react'; import { Link, browserHistory } from 'react-router' import Store from '../lib/store'; var store = new Store(); class Signup extends Component { constructor(props) { super(props); this.state = { username: '', password: '', confirmPass: '', errorMessage: '', messageVisible: false, }; } signup() { console.log('signing up...'); if (this.state.password !== this.state.confirmPass ) { return this.setState({errorMessage: 'Your passwords do not match', messageVisible: true}); } store.createUser(this.state.username, this.state.password, (error, user) => { if (error) { this.setState({errorMessage: error.message, messageVisible: true}); } else { this.props.history.push('/notes'); } }); } render() { return ( <div> <div className="card"> <div className="card-content"> <div className={this.state.messageVisible ? 'columns' : 'columns hidden'}> <div className="column is-8"> <div className="notification is-danger"> <button className="delete" onClick={event => this.setState({messageVisible: false})}></button> {this.state.errorMessage} </div> </div> </div> <div className="columns"> <div className="column is-4"> <input name="username" id="title" type="text" placeholder="Username" onChange={event => this.setState({username: event.target.value})} /> </div> </div> <div className="columns"> <div className="column is-4"> <input name="password" id="password" type="password" placeholder="Password" onChange={event => this.setState({password: event.target.value})} /> </div> </div> <div className="columns"> <div className="column is-4"> <input name="confirm_pass" id="confirm_pass" type="password" placeholder="Confirm Password" onChange={event => this.setState({confirmPass: event.target.value})} /> </div> </div> <div className="columns"> <div className="column is-4 control"> <input type="submit" className="button is-success" value="Sign Up" onClick={this.signup.bind(this)} /> </div> <div className="column is-4 control"> <Link to="/login">I have an account...</Link> </div> </div> </div> </div> </div> ) } } export default Signup;
src/containers/RespondToPetition.js
iris-dni/iris-frontend
import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import { fetchPetitionByResponseToken } from 'actions/RespondActions'; import settings from 'settings'; import Loading from 'components/Loading'; import RespondToPetition from 'components/RespondToPetition'; import PetitionResponseTokenError from 'components/PetitionResponseTokenError'; import RespondedToPetition from 'components/RespondedToPetition'; import getPetitionForm from 'selectors/petitionForm'; import getPetitionResponseForm from 'selectors/petitionResponseForm'; const RespondToPetitionContainer = React.createClass({ componentWillMount () { const { petition, fetchPetitionByResponseToken, params } = this.props; if (!!petition.found && !petition.id) { fetchPetitionByResponseToken(params.token); } }, render () { const { petition, petitionResponse } = this.props; return ( <div> <Helmet title={settings.respondToPetitionPage.title} /> <Loading isLoading={petition.isLoading || petitionResponse.isLoading}> <div> {!!petition.found && !petitionResponse.saved && !petition.hasCityAnswerAlreadySubmitted && <RespondToPetition petition={petition} petitionResponse={petitionResponse} /> } {!!petition.found && !!petitionResponse.saved && !petition.hasCityAnswerAlreadySubmitted && <RespondedToPetition /> } {(!petition.found || !!petition.found && !!petition.hasCityAnswerAlreadySubmitted) && <PetitionResponseTokenError petition={petition} petitionResponse={petitionResponse} /> } </div> </Loading> </div> ); } }); RespondToPetitionContainer.fetchData = ({ store, params }) => { return store.dispatch(fetchPetitionByResponseToken(params.token)); }; export const mapStateToProps = ({ petition, petitionResponse }) => ({ petition: getPetitionForm(petition), petitionResponse: getPetitionResponseForm(petitionResponse) }); export const mapDispatchToProps = (dispatch) => ({ fetchPetitionByResponseToken: (token) => dispatch(fetchPetitionByResponseToken(token)) }); export default withRouter(connect( mapStateToProps, mapDispatchToProps )(RespondToPetitionContainer));
lib/shared/screens/admin/screens/menus/screens/menu/components/menu-builder/pages/index.js
relax/relax
import Component from 'components/component'; import React from 'react'; import PropTypes from 'prop-types'; import {dataConnect} from 'relate-js'; import Pages from './pages'; @dataConnect( () => ({ fragments: Pages.fragments }) ) export default class MenuBuilderContainer extends Component { static propTypes = { pages: PropTypes.array }; static defaultProps = { pages: [] }; render () { return ( <Pages {...this.props} /> ); } }
src/containers/PlaylistCreate.js
kellhellia/vkReduxLast
import React, { Component } from 'react'; import { connect } from 'react-redux'; import store from '../store'; import { Link } from 'react-router'; import { getNewPlaylistName, createNewPlaylist } from '../actions'; class PlaylistCreate extends Component { constructor(props, context) { super(); this.router = context.router; } handleInputChange(e) { this.props.dispatch(getNewPlaylistName(e.target.value)); } handleBtnCreate() { let playlistName = this.props.newPlaylist.playlistName; let ownerId = this.props.user.value.id; this.props.dispatch(createNewPlaylist(playlistName, ownerId)); this.router.push('/'); } render() { console.log(this.props); let playlistName = this.props.newPlaylist.playlistName; return ( <div className="playlist-create"> <div className="row"> <div className="col-sm-4 col-sm-offset-4"> <input className="form-control form-group" placeholder="Введите имя плейлиста" onChange={::this.handleInputChange} /> <button className="btn btn-primary inline-block" onClick={::this.handleBtnCreate} >Создать плейлист</button> </div> </div> </div> ) } } PlaylistCreate.contextTypes = { router: React.PropTypes.object }; PlaylistCreate = connect(state => state)(PlaylistCreate); export default PlaylistCreate;
src/components/extensions/class-challenges/class-challenge-selection.js
vFujin/HearthLounge
import React from 'react'; import {icon_filters} from "../../../globals/filters"; import Icon from "../../icon"; import {Link, withRouter} from "react-router-dom"; const ClassChallengeSelection = ({location}) => ( <div className="container__classChallenges--selection"> <h2>Select Class</h2> <ul className="classes"> {icon_filters.playerClass.filter(playerClass => playerClass.url !== "neutral").map(playerClass => <li key={playerClass.url} className={playerClass.url} id={playerClass.url}> <Link to={`${location.pathname}/${playerClass.url}`}> <Icon name={playerClass.url}/> <p>{playerClass.name}</p> </Link> </li> )} </ul> </div> ); export default withRouter(ClassChallengeSelection);
app/components/team/Form.js
buildkite/frontend
import React from 'react'; import PropTypes from 'prop-types'; import FormCheckbox from 'app/components/shared/FormCheckbox'; import FormRadioGroup from 'app/components/shared/FormRadioGroup'; import FormTextField from 'app/components/shared/FormTextField'; import Panel from 'app/components/shared/Panel'; import Button from 'app/components/shared/Button'; import ValidationErrors from 'app/lib/ValidationErrors'; import TeamPrivacyConstants from 'app/constants/TeamPrivacyConstants'; class TeamForm extends React.Component { static propTypes = { name: PropTypes.string, description: PropTypes.string, privacy: PropTypes.oneOf(Object.keys(TeamPrivacyConstants)), isDefaultTeam: PropTypes.bool, errors: PropTypes.array, onChange: PropTypes.func, saving: PropTypes.bool, button: PropTypes.string.isRequired, autofocus: PropTypes.bool }; componentDidMount() { if (this.props.autofocus) { this.nameTextField.focus(); } } render() { const errors = new ValidationErrors(this.props.errors); return ( <Panel> <Panel.Section> <FormTextField label="Name" help="The name for the team (supports :emoji:)" errors={errors.findForField("name")} value={this.props.name} onChange={this.handleTeamNameChange} required={true} ref={(nameTextField) => this.nameTextField = nameTextField} /> <FormTextField label="Description" help="The description for the team (supports :emoji:)" errors={errors.findForField("description")} value={this.props.description} onChange={this.handleDescriptionChange} /> </Panel.Section> <Panel.Section> <FormRadioGroup name="team-privacy" label="Visibility" help="Something" value={this.props.privacy} errors={errors.findForField("privacy")} onChange={this.handlePrivacyChange} required={true} options={[ { label: "Visible", value: TeamPrivacyConstants.VISIBLE, help: "Can be seen by all members within the organization", badge: "Recommended" }, { label: "Secret", value: TeamPrivacyConstants.SECRET, help: "Can only only be seen by organization administrators and members of this team" } ]} /> </Panel.Section> <Panel.Section> <FormCheckbox name="team-is-default-team" label="Automatically add new users to this team" help="When new users join this organization, either via email invitation or SSO, they'll be automatically added to this team" checked={this.props.isDefaultTeam} onChange={this.handleIsDefaultTeamChange} /> </Panel.Section> <Panel.Footer> <Button loading={this.props.saving ? this.props.button : false} theme="success">{this.props.button}</Button> </Panel.Footer> </Panel> ); } handleTeamNameChange = (evt) => { this.props.onChange('name', evt.target.value); }; handleDescriptionChange = (evt) => { this.props.onChange('description', evt.target.value); }; handlePrivacyChange = (evt) => { this.props.onChange('privacy', evt.target.value); }; handleIsDefaultTeamChange = (evt) => { this.props.onChange('isDefaultTeam', evt.target.checked); }; } export default TeamForm;
src/test.js
AlecAivazis/react-liftC
// external imports import React from 'react' import { mount } from 'enzyme' import test from 'ava' // local imports import liftC from './liftC' // the configuration for the lift const state = { initialValue: 1, handlers: { increment(prev) { return prev + 1 }, addN(prev, n) { return prev + n } } } // the component to lift const Counter = ({state, increment}) => ( <div onClick={increment}> {state} </div> ) const MultiCounter = ({state, addN, n}) => ( <div onClick={() => addN(n)}> {state} </div> ) // make sure it returns a component test('returns a component', t => { // lift the component with the given state const NewComponent = liftC(state)(Counter) // make sure it returned a component t.is(React.isValidElement(<NewComponent />), true) }) test('state begins at initial value', t => { // lift the component with the given state const StatefulCounter = liftC(state)(Counter) // render the component const component = mount(<StatefulCounter/>) // make sure the content of the article element is the initial value t.is(component.text(), "1") }) test('passes props through', t => { // a component to test prop values const PropComponent = ({hello}) => <article>{hello}</article> // lift the component with the given state const NewComponent = liftC(state)(PropComponent) // check the component content // render the component const component = mount(<NewComponent hello="world"/>) // make sure the content of the article matches the prop we passed t.is(component.text(), "world") }) test('handlers correctly affect the state', t => { // lift the component with the given state const NewComponent = liftC(state)(Counter) // render the component const component = mount(<NewComponent/>) // simulate a click on the component component.find('div').simulate('click') // make sure the content of the article element is the initial value t.is(component.text(), "2") }) test('passes handler arguments through', t => { // lift the component with the given state const NewComponent = liftC(state)(MultiCounter) // render the component const component = mount(<NewComponent n={2}/>) // simulate a click on the component component.find('div').simulate('click') // make sure the content of the article element is the initial value t.is(component.text(), "3") })