path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/Downlinks.js
connectordb/connectordb-android
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as Actions from './actions'; import styles from './styles'; import { ScrollView, View, Text, RefreshControl } from 'react-native'; import mapInputs from './components/inputs'; const Render = ({state, actions}) => ( <ScrollView style={styles.tabView} contentContainerStyle={styles.tabViewRefreshContainer} refreshControl={ <RefreshControl refreshing={state.downlinks.refreshing} onRefresh={actions.refreshDownlinks} /> } > {state.downlinks.streams.length === 0 ? ( <View style={styles.card}> <Text style={styles.h1}> Downlinks </Text> <Text style={styles.p}> Looks like you don't have any downlinks set up. </Text> <Text style={styles.p}> With Downlinks, you can control things with ConnectorDB, such as your lights or thermostat. </Text> </View> ) : ( <View> {mapInputs(state.downlinks.streams, actions.insert, state.main.user)} </View> )} </ScrollView> ); export default connect( (state) => ({ state: state }), (dispatch) => ({ actions: bindActionCreators(Actions, dispatch) }) )(Render);
node_modules/react-router/es6/IndexLink.js
cylcharles/webpack
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React, { Component } from 'react'; import Link from './Link'; /** * An <IndexLink> is used to link to an <IndexRoute>. */ var IndexLink = (function (_Component) { _inherits(IndexLink, _Component); function IndexLink() { _classCallCheck(this, IndexLink); _Component.apply(this, arguments); } IndexLink.prototype.render = function render() { return React.createElement(Link, _extends({}, this.props, { onlyActiveOnIndex: true })); }; return IndexLink; })(Component); export default IndexLink;
src/svg-icons/action/autorenew.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAutorenew = (props) => ( <SvgIcon {...props}> <path d="M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6zm6.76 1.74L17.3 9.2c.44.84.7 1.79.7 2.8 0 3.31-2.69 6-6 6v-3l-4 4 4 4v-3c4.42 0 8-3.58 8-8 0-1.57-.46-3.03-1.24-4.26z"/> </SvgIcon> ); ActionAutorenew = pure(ActionAutorenew); ActionAutorenew.displayName = 'ActionAutorenew'; ActionAutorenew.muiName = 'SvgIcon'; export default ActionAutorenew;
src/shared/components/Alert/index.js
CharlesMangwa/Chloe
/* @flow */ import React from 'react' import { Image, Text, TouchableWithoutFeedback, View } from 'react-native' import Icon from '@components/Icon' import styles from './styles' type Props = { color: string, onPress: Function, type: 'lamp' | 'server' | null, } const Alert = (props: Props): React$Element<any> => { const { color, onPress, type } = props return ( <View style={styles.container}> <Image resizeMode="cover" source={require('../../theme/assets/pattern.png')} style={styles.wrapper} > <View style={[styles.imageContainer, { justifyContent: type === 'lamp' ? 'flex-start' : 'center' }]}> <Icon name={type} defaultColor={color} size={type === 'lamp' ? 130 : 65} /> </View> <View style={styles.textContainer}> <Text style={styles.title}>OUPS !</Text> {type === 'lamp' && <Text style={styles.text}> Il semblerait que la lampe soit déconnectée. Eteignez et rallumez la à nouveau pour la reconnecter. </Text> } {type === 'server' && <Text style={styles.text}> Il semblerait que les serveurs soient coupés. Essayez de relancer l’application. </Text> } </View> <View style={styles.buttonContainer}> <TouchableWithoutFeedback onPress={onPress}> <View><Text style={[styles.continue, { color }]}>CONTINUER</Text></View> </TouchableWithoutFeedback> </View> </Image> </View> ) } export default Alert
src/js/pages/words/WordAdd.js
mikka22pl/glossa
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from "react-redux"; import { Field, reduxForm } from 'redux-form'; //import AutosuggestWord from '../../components/forms/AutosuggestWord'; import * as wordActions from '../../actions/word'; import WordAddForm from '../../components/forms/WordAddForm'; import WordsList from '../../components/words/WordsList'; class WordAdd extends React.Component { constructor(props) { super(props); } componentWillMount() { this.props.fetchWords(this.props.language.id, 'top10'); } handleSubmit = (values) => { this.props.saveWord(null, values.word, this.props.language.id) .then((response) => { this.props.fetchWords(this.props.language.id, 'top10'); }); this.refs.wordAddForm.reset(); } render() { const words = this.props.words.list || []; return ( <div> <WordAddForm ref="wordAddForm" onSubmit={this.handleSubmit} /> <WordsList list={words}/> </div> ) } } function mapStateToProps(state) { return ({ language: state.language, words: state.words }); } function mapDispatchToProps(dispatch) { return bindActionCreators(wordActions, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(WordAdd);
public/js/materialize-css/CollectionItem.js
Morton/pixelDailiesGallery
/** * Created by morton on 26/11/15. */ import React from 'react'; var CollectionItem = React.createClass({ render: function() { return <li className={['collection-item', (this.props.active?'active':'')].join(' ')} {...this.props}> {this.props.children} </li>; } }); export default CollectionItem;
app/react/components/create-app.js
NikaBuligini/git-auto-deploy
import React from 'react' export default React.createClass({ render () { return ( <div className="card"> <form action="/create" method="post" className="create-form"> <div className="form-group"> <label htmlFor="name">Project name</label> <input id="name" type="text" name="name" className="form-control" placeholder="my-project-name" autoComplete="false" /> </div> <div className="form-group"> <label htmlFor="description">Project description</label> <textarea id="description" name="description" className="form-control" placeholder="brief description" /> </div> <button type="submit" className="btn btn-default">Submit</button> </form> </div> ) } })
app/javascript/mastodon/features/direct_timeline/components/conversations_list.js
danhunsaker/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ConversationContainer from '../containers/conversation_container'; import ScrollableList from '../../../components/scrollable_list'; import { debounce } from 'lodash'; export default class ConversationsList extends ImmutablePureComponent { static propTypes = { conversations: ImmutablePropTypes.list.isRequired, scrollKey: PropTypes.string.isRequired, hasMore: PropTypes.bool, isLoading: PropTypes.bool, onLoadMore: PropTypes.func, shouldUpdateScroll: PropTypes.func, }; getCurrentIndex = id => this.props.conversations.findIndex(x => x.get('id') === id) handleMoveUp = id => { const elementIndex = this.getCurrentIndex(id) - 1; this._selectChild(elementIndex, true); } handleMoveDown = id => { const elementIndex = this.getCurrentIndex(id) + 1; this._selectChild(elementIndex, false); } _selectChild (index, align_top) { const container = this.node.node; const element = container.querySelector(`article:nth-of-type(${index + 1}) .focusable`); if (element) { if (align_top && container.scrollTop > element.offsetTop) { element.scrollIntoView(true); } else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) { element.scrollIntoView(false); } element.focus(); } } setRef = c => { this.node = c; } handleLoadOlder = debounce(() => { const last = this.props.conversations.last(); if (last && last.get('last_status')) { this.props.onLoadMore(last.get('last_status')); } }, 300, { leading: true }) render () { const { conversations, onLoadMore, ...other } = this.props; return ( <ScrollableList {...other} onLoadMore={onLoadMore && this.handleLoadOlder} ref={this.setRef}> {conversations.map(item => ( <ConversationContainer key={item.get('id')} conversationId={item.get('id')} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} scrollKey={this.props.scrollKey} /> ))} </ScrollableList> ); } }
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/TabContext.js
GoogleCloudPlatform/prometheus-engine
import React from 'react'; /** * TabContext * { * activeTabId: PropTypes.any * } */ export const TabContext = React.createContext({});
src/icons/Icon.js
ericyd/surfplotjs
/** * A base class for icons. * The outer svg is set to 1em x 1em. * The inner svg is 75% of that for proper visual weight. */ import React from 'react'; import './icon.scss'; const Icon = props => ( <svg viewBox='0 0 100 100' className={['icon', props.className].join(' ')}> <svg x='12.5' y='12.5' width='75' height='75' viewBox='0 0 100 100' strokeWidth='10' strokeLinecap='round' strokeLinejoin='round'> {props.children} </svg> </svg> ); Icon.propTypes = { className: React.PropTypes.string }; export default Icon;
vendor/laravel/framework/src/Illuminate/Foundation/Console/Presets/react-stubs/Example.js
akhilerm/Castle
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; export default class Example extends Component { render() { return ( <div className="container"> <div className="row"> <div className="col-md-8 col-md-offset-2"> <div className="panel panel-default"> <div className="panel-heading">Example Component</div> <div className="panel-body"> I'm an example component! </div> </div> </div> </div> </div> ); } } if (document.getElementById('example')) { ReactDOM.render(<Example />, document.getElementById('example')); }
src/routes/Help/Components/Help.js
PetrosGit/poker-experiment
import React from 'react'; const Help = () => ( <div style={ Style.container }> <h3 style={ Style.header }>Game Rules:</h3> <ul style={ Style.list }> <li>You can select cards from your hand in order to change them with new ones from the deck.</li> <li>The winner of the round is determined from the rules of the poker game Five Card Draw. See rules <a href="https://en.wikipedia.org/wiki/Five-card_draw#House_rules">here</a></li> </ul> </div> ); const Style = { container: { }, header: { textAlign: 'center', fontFamily: 'Arial', fontSize: 30, margin: 30, }, list: { textAlign: 'left', fontFamily: 'Arial', fontSize: 16, color: 'black', }, }; export default Help;
client/main.js
TobyEalden/komposer-weirdness
import React from 'react'; import { Meteor } from 'meteor/meteor'; import { render } from 'react-dom'; import App from '../imports/ui/App'; Meteor.startup(() => { render(<App />, document.getElementById('render-target')); });
openex-front/src/private/components/settings/users/Users.js
Luatix/OpenEx
import React from 'react'; import { useDispatch } from 'react-redux'; import List from '@mui/material/List'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import ListItemSecondaryAction from '@mui/material/ListItemSecondaryAction'; import { makeStyles } from '@mui/styles'; import { CheckCircleOutlined, PersonOutlined } from '@mui/icons-material'; import { fetchUsers } from '../../../../actions/User'; import { fetchOrganizations } from '../../../../actions/Organization'; import ItemTags from '../../../../components/ItemTags'; import SearchFilter from '../../../../components/SearchFilter'; import CreateUser from './CreateUser'; import { fetchTags } from '../../../../actions/Tag'; import TagsFilter from '../../../../components/TagsFilter'; import useSearchAnFilter from '../../../../utils/SortingFiltering'; import useDataLoader from '../../../../utils/ServerSideEvent'; import { useHelper } from '../../../../store'; import UserPopover from './UserPopover'; const useStyles = makeStyles((theme) => ({ parameters: { float: 'left', marginTop: -10, }, container: { marginTop: 10, }, itemHead: { paddingLeft: 10, textTransform: 'uppercase', cursor: 'pointer', }, item: { paddingLeft: 10, height: 50, }, bodyItem: { height: '100%', fontSize: 13, }, itemIcon: { color: theme.palette.primary.main, }, goIcon: { position: 'absolute', right: -10, }, inputLabel: { float: 'left', }, sortIcon: { float: 'left', margin: '-5px 0 0 15px', }, icon: { color: theme.palette.primary.main, }, })); const headerStyles = { iconSort: { position: 'absolute', margin: '0 0 0 5px', padding: 0, top: '0px', }, user_email: { float: 'left', width: '25%', fontSize: 12, fontWeight: '700', }, user_firstname: { float: 'left', width: '15%', fontSize: 12, fontWeight: '700', }, user_lastname: { float: 'left', width: '15%', fontSize: 12, fontWeight: '700', }, user_organization: { float: 'left', width: '20%', fontSize: 12, fontWeight: '700', }, user_admin: { float: 'left', width: '10%', fontSize: 12, fontWeight: '700', }, user_tags: { float: 'left', fontSize: 12, fontWeight: '700', }, }; const inlineStyles = { user_email: { float: 'left', width: '25%', height: 20, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', }, user_firstname: { float: 'left', width: '15%', height: 20, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', }, user_lastname: { float: 'left', width: '15%', height: 20, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', }, user_organization: { float: 'left', width: '20%', height: 20, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', }, user_admin: { float: 'left', width: '10%', height: 20, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', }, user_tags: { float: 'left', height: 20, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', }, }; const Users = () => { const classes = useStyles(); const dispatch = useDispatch(); const searchColumns = [ 'email', 'firstname', 'lastname', 'phone', 'organization', ]; const filtering = useSearchAnFilter('user', 'email', searchColumns); const { users, tagsMap, organizationsMap } = useHelper((helper) => ({ users: helper.getUsers(), organizationsMap: helper.getOrganizationsMap(), tagsMap: helper.getTagsMap(), })); useDataLoader(() => { dispatch(fetchTags()); dispatch(fetchOrganizations()); dispatch(fetchUsers()); }); return ( <div> <div className={classes.parameters}> <div style={{ float: 'left', marginRight: 20 }}> <SearchFilter small={true} onChange={filtering.handleSearch} keyword={filtering.keyword} /> </div> <div style={{ float: 'left', marginRight: 20 }}> <TagsFilter onAddTag={filtering.handleAddTag} onRemoveTag={filtering.handleRemoveTag} currentTags={filtering.tags} /> </div> </div> <div className="clearfix" /> <List classes={{ root: classes.container }}> <ListItem classes={{ root: classes.itemHead }} divider={false} style={{ paddingTop: 0 }} > <ListItemIcon> <span style={{ padding: '0 8px 0 8px', fontWeight: 700, fontSize: 12, }} > &nbsp; </span> </ListItemIcon> <ListItemText primary={ <div> {filtering.buildHeader( 'user_email', 'Email address', true, headerStyles, )} {filtering.buildHeader( 'user_firstname', 'Firstname', true, headerStyles, )} {filtering.buildHeader( 'user_lastname', 'Lastname', true, headerStyles, )} {filtering.buildHeader( 'user_organization', 'Organization', true, headerStyles, )} {filtering.buildHeader( 'user_admin', 'Administrator', true, headerStyles, )} {filtering.buildHeader('user_tags', 'Tags', true, headerStyles)} </div> } /> <ListItemSecondaryAction> &nbsp; </ListItemSecondaryAction> </ListItem> {filtering.filterAndSort(users ?? []).map((user) => ( <ListItem key={user.user_id} classes={{ root: classes.item }} divider={true} > <ListItemIcon> <PersonOutlined color="primary" /> </ListItemIcon> <ListItemText primary={ <div> <div className={classes.bodyItem} style={inlineStyles.user_email} > {user.user_email} </div> <div className={classes.bodyItem} style={inlineStyles.user_firstname} > {user.user_firstname} </div> <div className={classes.bodyItem} style={inlineStyles.user_lastname} > {user.user_lastname} </div> <div className={classes.bodyItem} style={inlineStyles.user_organization} > { organizationsMap[user.user_organization] ?.organization_name } </div> <div className={classes.bodyItem} style={inlineStyles.user_admin} > {user.user_admin ? ( <CheckCircleOutlined fontSize="small" /> ) : ( '-' )} </div> <div className={classes.bodyItem} style={inlineStyles.user_tags} > <ItemTags variant="list" tags={user.user_tags} /> </div> </div> } /> <ListItemSecondaryAction> <UserPopover user={user} tagsMap={tagsMap} organizationsMap={organizationsMap} /> </ListItemSecondaryAction> </ListItem> ))} </List> <CreateUser /> </div> ); }; export default Users;
src/svg-icons/notification/airline-seat-legroom-reduced.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatLegroomReduced = (props) => ( <SvgIcon {...props}> <path d="M19.97 19.2c.18.96-.55 1.8-1.47 1.8H14v-3l1-4H9c-1.65 0-3-1.35-3-3V3h6v6h5c1.1 0 2 .9 2 2l-2 7h1.44c.73 0 1.39.49 1.53 1.2zM5 12V3H3v9c0 2.76 2.24 5 5 5h4v-2H8c-1.66 0-3-1.34-3-3z"/> </SvgIcon> ); NotificationAirlineSeatLegroomReduced = pure(NotificationAirlineSeatLegroomReduced); NotificationAirlineSeatLegroomReduced.displayName = 'NotificationAirlineSeatLegroomReduced'; NotificationAirlineSeatLegroomReduced.muiName = 'SvgIcon'; export default NotificationAirlineSeatLegroomReduced;
UI/src/components/common/Card.js
ssvictorlin/PI
import React from 'react'; import { View } from 'react-native'; const Card = (props) => { return ( <View style={ styles.containerStyle }> { props.children } </View> ); }; const styles = { containerStyle: { shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 2, elevation: 1, marginLeft: 5, marginRight: 5, marginTop: 10 } }; export { Card };
src/modules/mapping/components/CwpDialog/Loader.js
devteamreims/4me.react
import React, { Component } from 'react'; import RefreshIndicator from 'material-ui/RefreshIndicator'; const styles = { container: { textAlign: 'center', }, refresh: { display: 'inline-block', position: 'relative', }, }; class Loader extends Component { render() { const { hidden, } = this.props; if(hidden) { return null; } return ( <div style={styles.container}> <RefreshIndicator left={0} top={0} status="loading" style={styles.refresh} /> </div> ); } } Loader.propTypes = { hidden: React.PropTypes.bool, }; Loader.defaultProps = { hidden: false, }; export default Loader;
ui/src/containers/NewExperiment/NewExperiment.js
vlad-doru/experimento
import React from 'react' import {connect} from 'react-redux'; import { Step, Stepper, StepLabel, StepContent, } from 'material-ui/Stepper'; import RaisedButton from 'material-ui/RaisedButton'; import FlatButton from 'material-ui/FlatButton'; import ExperimentInfo from '../../components/ExperimentInfo' import VariableInfo from '../../components/VariableInfo' import GroupsInfo from '../../components/GroupsInfo' import Whitelist from '../../components/Whitelist' import * as createActions from '../../redux/modules/create'; import * as repositoryActions from '../../redux/modules/repository'; const actions = { ...createActions, ...repositoryActions, } @connect( state => ({ info: state.create.info, validInfo: state.create.validInfo, variables: state.create.variables, validVariables: state.create.validVariables, variableInput: state.create.variableInput, groups: state.create.groups, values: state.create.values, validGroups: state.create.validGroups, groupInput: state.create.groupInput, whitelist: state.create.whitelist, whitelistInput: state.create.whitelistInput, whitelistGroup: state.create.whitelistGroup, stepIndex: state.create.stepIndex, }), actions) class NewExperiment extends React.Component { constructor(props) { super(); } renderStepActions(step, valid) { return ( <div style={{margin: '12px 0'}}> <RaisedButton disabled={!valid} label={this.props.stepIndex === 3 ? 'Finish' : 'Next'} disableTouchRipple={true} disableFocusRipple={true} primary={true} onTouchTap={() => { if (this.props.stepIndex < 3) { this.props.setStep(this.props.stepIndex + 1) } else { this.props.saveExperiment({ info: this.props.info, variables: this.props.variables, groups: this.props.groups, whitelist: this.props.whitelist, }) } }} style={{marginRight: 12}} /> {step > 0 && ( <FlatButton label="Back" disableTouchRipple={true} disableFocusRipple={true} onTouchTap={() => this.props.setStep(this.props.stepIndex - 1)} /> )} </div> ); } render () { return ( <div> <Stepper activeStep={this.props.stepIndex} orientation="vertical"> <Step> <StepLabel>Experiment Info</StepLabel> <StepContent> <ExperimentInfo info={this.props.info} onChange={(data) => this.props.setExperiment(data) }/> {this.renderStepActions(0, this.props.validInfo)} </StepContent> </Step> <Step> <StepLabel>Variables Info</StepLabel> <StepContent> <VariableInfo variables={this.props.variables} variableInput={this.props.variableInput} onChange={(data) => { this.props.setVariables(data) this.props.setGroups({}) this.props.setWhitelist({}) }}/> {this.renderStepActions(1, this.props.validVariables)} </StepContent> </Step> <Step> <StepLabel>Group Info</StepLabel> <StepContent> <GroupsInfo variables={this.props.variables} values={this.props.values} groups={this.props.groups} groupInput={this.props.groupInput} onChange={(data) => { this.props.setGroups(data) this.props.setWhitelist({}) }}/> {this.renderStepActions(1, this.props.validGroups)} </StepContent> </Step> <Step> <StepLabel>Whitelist</StepLabel> <StepContent> <Whitelist whitelist={this.props.whitelist} whitelistInput={this.props.whitelistInput} whitelistGroup={this.props.whitelistGroup} groups={this.props.groups} onChange={(data) => { this.props.setWhitelist(data) }}/> {this.renderStepActions(1, true)} </StepContent> </Step> </Stepper> </div> ) } } export default NewExperiment
actor-apps/app-web/src/app/components/common/ConnectionState.react.js
liruqi/actor-platform
import React from 'react'; import classnames from 'classnames'; import ConnectionStateStore from 'stores/ConnectionStateStore'; const getStateFromStore = () => { return { connectionState: ConnectionStateStore.getState() }; }; class ConnectionState extends React.Component { constructor(props) { super(props); this.state = getStateFromStore(); ConnectionStateStore.addChangeListener(this.onStateChange); } componentWillUnmount() { ConnectionStateStore.removeChangeListener(this.onStateChange); } onStateChange = () => { this.setState(getStateFromStore); }; render() { const { connectionState } = this.state; const className = classnames('connection-state', { 'connection-state--online': connectionState === 'online', 'connection-state--connection': connectionState === 'connecting' }); switch (connectionState) { case 'online': return ( <div className={className}>'You're back online!'</div> ); case 'connecting': return ( <div className={className}> Houston, we have a problem! Connection to Actor server is lost. Trying to reconnect now... </div> ); default: return null; } } } export default ConnectionState;
src/routes/PlayingView/Containers/EndButton.js
PetrosGit/poker-experiment
import { connect } from 'react-redux'; import React from 'react'; let EndGame = ({ onEndGame }) => ( <button onClick={onEndGame}>END GAME</button> ); EndGame = connect( null, (dispatch) => ({ onEndGame: () => dispatch({ type: 'END_GAME' }), }), )(EndGame); export { EndGame };
app/javascript/mastodon/features/following/index.js
Ryanaka/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import LoadingIndicator from '../../components/loading_indicator'; import { lookupAccount, fetchAccount, fetchFollowing, expandFollowing, } from '../../actions/accounts'; import { FormattedMessage } from 'react-intl'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import HeaderContainer from '../account_timeline/containers/header_container'; import ColumnBackButton from '../../components/column_back_button'; import ScrollableList from '../../components/scrollable_list'; import MissingIndicator from 'mastodon/components/missing_indicator'; import TimelineHint from 'mastodon/components/timeline_hint'; const mapStateToProps = (state, { params: { acct, id } }) => { const accountId = id || state.getIn(['accounts_map', acct]); if (!accountId) { return { isLoading: true, }; } return { accountId, remote: !!(state.getIn(['accounts', accountId, 'acct']) !== state.getIn(['accounts', accountId, 'username'])), remoteUrl: state.getIn(['accounts', accountId, 'url']), isAccount: !!state.getIn(['accounts', accountId]), accountIds: state.getIn(['user_lists', 'following', accountId, 'items']), hasMore: !!state.getIn(['user_lists', 'following', accountId, 'next']), isLoading: state.getIn(['user_lists', 'following', accountId, 'isLoading'], true), blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false), }; }; const RemoteHint = ({ url }) => ( <TimelineHint url={url} resource={<FormattedMessage id='timeline_hint.resources.follows' defaultMessage='Follows' />} /> ); RemoteHint.propTypes = { url: PropTypes.string.isRequired, }; export default @connect(mapStateToProps) class Following extends ImmutablePureComponent { static propTypes = { params: PropTypes.shape({ acct: PropTypes.string, id: PropTypes.string, }).isRequired, accountId: PropTypes.string, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list, hasMore: PropTypes.bool, isLoading: PropTypes.bool, blockedBy: PropTypes.bool, isAccount: PropTypes.bool, remote: PropTypes.bool, remoteUrl: PropTypes.string, multiColumn: PropTypes.bool, }; _load () { const { accountId, isAccount, dispatch } = this.props; if (!isAccount) dispatch(fetchAccount(accountId)); dispatch(fetchFollowing(accountId)); } componentDidMount () { const { params: { acct }, accountId, dispatch } = this.props; if (accountId) { this._load(); } else { dispatch(lookupAccount(acct)); } } componentDidUpdate (prevProps) { const { params: { acct }, accountId, dispatch } = this.props; if (prevProps.accountId !== accountId && accountId) { this._load(); } else if (prevProps.params.acct !== acct) { dispatch(lookupAccount(acct)); } } handleLoadMore = debounce(() => { this.props.dispatch(expandFollowing(this.props.accountId)); }, 300, { leading: true }); render () { const { accountIds, hasMore, blockedBy, isAccount, multiColumn, isLoading, remote, remoteUrl } = this.props; if (!isAccount) { return ( <Column> <MissingIndicator /> </Column> ); } if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } let emptyMessage; if (blockedBy) { emptyMessage = <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' />; } else if (remote && accountIds.isEmpty()) { emptyMessage = <RemoteHint url={remoteUrl} />; } else { emptyMessage = <FormattedMessage id='account.follows.empty' defaultMessage="This user doesn't follow anyone yet." />; } const remoteMessage = remote ? <RemoteHint url={remoteUrl} /> : null; return ( <Column> <ColumnBackButton multiColumn={multiColumn} /> <ScrollableList scrollKey='following' hasMore={hasMore} isLoading={isLoading} onLoadMore={this.handleLoadMore} prepend={<HeaderContainer accountId={this.props.accountId} hideTabs />} alwaysPrepend append={remoteMessage} emptyMessage={emptyMessage} bindToDocument={!multiColumn} > {blockedBy ? [] : accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />, )} </ScrollableList> </Column> ); } }
packages/mineral-ui-icons/src/IconDeveloperBoard.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 IconDeveloperBoard(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M22 9V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14zM6 13h5v4H6zm6-6h4v3h-4zM6 7h5v5H6zm6 4h4v6h-4z"/> </g> </Icon> ); } IconDeveloperBoard.displayName = 'IconDeveloperBoard'; IconDeveloperBoard.category = 'hardware';
lib/components/Voter.js
kern/puddin
import React from 'react' export default class Voter extends React.Component { onUpvote(e) { this.props.onVote(1) } onDownvote(e) { this.props.onVote(-1) } render() { return <div className="voter"> {this.props.vote > 0 ? <div className="up-vote" /> : null} {this.props.vote === 0 ? <div className="up-vote clickable" onClick={this.onUpvote.bind(this)} /> : null} <div className="count">{this.props.count}</div> {this.props.vote === 0 ? <div className="down-vote clickable" onClick={this.onDownvote.bind(this)} /> : null} {this.props.vote < 0 ? <div className="down-vote" /> : null} </div> } }
src/app/components/pages/MainView/MainView.js
tvarner/PortfolioApp
import React from 'react'; import _ from 'lodash'; import Sidebar from './../../utilComponents/react-sidebar/src/index'; import MaterialTitlePanel from './MaterialTitlePanel'; import SidebarContentContainer from './SidebarContentContainer'; import HomePageContainer from '../HomePage/HomePageContainer'; import AboutPage from '../AboutPage/AboutPage'; import ContactPageContainer from '../ContactPage/ContactPageContainer'; import ContentPageContainer from '../ContentPage/ContentPageContainer'; import SortCollectionsModalContainer from '../../modals/SortCollectionsModal/SortCollectionsModalContainer'; import FullScreenContentModalContainer from '../../modals/FullScreenContentModal/FullScreenContentModalContainer'; import contentFileIndex from './../../../../content/_contentFileIndex'; import './styles.css'; const styles = { contentHeaderMenuLink: { textDecoration: 'none', color: 'white', padding: '8px', backgroundGolor: '#00FF00', margin: '2vh' }, content: {} }; const Application = React.createClass({ _renderActiveModal() { // Modals: // ADD ACTIVE MODAL LOGIC (one MODAL at a time) if (this.props.modals.activeModal !== null) { if (this.props.modals.activeModal === 'SORT_COLLECTIONS_MODAL') { return ( <SortCollectionsModalContainer data={this.props.modals.activeModalProps} /> ); } if (this.props.modals.activeModal === 'FULL_SCREEN_CONTENT_MODAL') { return ( <FullScreenContentModalContainer data={this.props.modals.activeModalProps} /> ); } /* if (this.props.modals.activeModal === 'LOAD_SIMULATION_MODAL') { return ( <LoadSimulationModalContainer /> ) } else if (this.props.modals.activeModal === 'SAVE_SIMULATION_MODAL') { return ( <SaveSimulationModalContainer /> ) } */ } }, _renderPage(page) { return ( <div style={{ height: '90vh', width: '100vw'}}> {page} {this._renderActiveModal()} </div> ); }, renderView() { // Views if (this.props.view === "HOME_PAGE") { return ( this._renderPage(<HomePageContainer />) ); } else if (this.props.view === "ABOUT_PAGE") { return ( this._renderPage(<AboutPage />) ); } else if (this.props.view === "CONTACT_PAGE") { return ( this._renderPage(<ContactPageContainer />) ); } else if (this.props.view === "PHOTOGRAPHY_PAGE") { return ( this._renderPage(<ContentPageContainer category={'photography'} header={'PHOTOGRAPHY'} />) ); } else if (this.props.view === "FILM_PAGE") { return ( this._renderPage(<ContentPageContainer category={'film'} header={'FILM'}/>) ); } else if (this.props.view === "FEATURE_PAGE") { return ( this._renderPage(<ContentPageContainer category={'feature'} header={'FEATURE'}/>) ); } else if (this.props.view === "REEL_PAGE") { return ( this._renderPage(<ContentPageContainer category={'reel'} header={'REEL'} />) ); } }, render() { const contentMonolith = require('./../../../../content/_content.json'); const cornerIconUrl = contentFileIndex[contentMonolith.cornerIcon]; const sidebarProps = this.props.sidebar; _.extend(sidebarProps, { onSetOpen: this.props.setSidebarOpen, sidebar: <SidebarContentContainer view={this.props.view}/> }); // TODO: rename contentHeader to toolbar const contentHeader = ( <div style={{height: '100%', display: 'flex', alignItems: 'center'}}> <div className={'main-view-logo'} onClick={this.props.logoButtonClick}> <img role={"presentation"} className={'logo-image'} src={cornerIconUrl} /> </div> {!this.props.sidebar.docked && <div className="main-menu-icon" onClick={this.props.menuButtonClick}> <div className="main-menu-icon-one" /> <div className="main-menu-icon-two" /> </div>} </div> ); return ( <Sidebar {...sidebarProps}> <MaterialTitlePanel title={contentHeader}> <div className="view" style={styles.content}> {this.renderView()} </div> </MaterialTitlePanel> </Sidebar> ); } }); export default Application;
src/InputArea/Exclamation.js
nirhart/wix-style-react
import React from 'react'; import SvgExclamation from '../svg/Exclamation.js'; import styles from './InputArea.scss'; const exclamation = () => <div className={styles.suffix + ' ' + styles.exclamation}> <SvgExclamation width={2} height={11}/> </div>; export default exclamation;
Web-Platform/1.0/react入门操作/index-fb.js
ShareTeam/Platform
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; // Render the main component into the dom ReactDOM.render(<Router />, document.getElementById('app'));
app/javascript/mastodon/components/status_list.js
imomix/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { ScrollContainer } from 'react-router-scroll'; import PropTypes from 'prop-types'; import StatusContainer from '../containers/status_container'; import LoadMore from './load_more'; import ImmutablePureComponent from 'react-immutable-pure-component'; import IntersectionObserverWrapper from '../features/ui/util/intersection_observer_wrapper'; import { debounce } from 'lodash'; class StatusList extends ImmutablePureComponent { static propTypes = { scrollKey: PropTypes.string.isRequired, statusIds: ImmutablePropTypes.list.isRequired, onScrollToBottom: PropTypes.func, onScrollToTop: PropTypes.func, onScroll: PropTypes.func, trackScroll: PropTypes.bool, shouldUpdateScroll: PropTypes.func, isLoading: PropTypes.bool, hasMore: PropTypes.bool, prepend: PropTypes.node, emptyMessage: PropTypes.node, }; static defaultProps = { trackScroll: true, }; intersectionObserverWrapper = new IntersectionObserverWrapper(); handleScroll = debounce((e) => { const { scrollTop, scrollHeight, clientHeight } = e.target; const offset = scrollHeight - scrollTop - clientHeight; this._oldScrollPosition = scrollHeight - scrollTop; if (250 > offset && this.props.onScrollToBottom && !this.props.isLoading) { this.props.onScrollToBottom(); } else if (scrollTop < 100 && this.props.onScrollToTop) { this.props.onScrollToTop(); } else if (this.props.onScroll) { this.props.onScroll(); } }, 200, { trailing: true, }); componentDidMount () { this.attachScrollListener(); this.attachIntersectionObserver(); } componentDidUpdate (prevProps) { // Reset the scroll position when a new toot comes in in order not to // jerk the scrollbar around if you're already scrolled down the page. if (prevProps.statusIds.size < this.props.statusIds.size && prevProps.statusIds.first() !== this.props.statusIds.first() && this._oldScrollPosition && this.node.scrollTop > 0) { let newScrollTop = this.node.scrollHeight - this._oldScrollPosition; if (this.node.scrollTop !== newScrollTop) { this.node.scrollTop = newScrollTop; } } } componentWillUnmount () { this.detachScrollListener(); this.detachIntersectionObserver(); } attachIntersectionObserver () { this.intersectionObserverWrapper.connect({ root: this.node, rootMargin: '300% 0px', }); } detachIntersectionObserver () { this.intersectionObserverWrapper.disconnect(); } attachScrollListener () { this.node.addEventListener('scroll', this.handleScroll); } detachScrollListener () { this.node.removeEventListener('scroll', this.handleScroll); } setRef = (c) => { this.node = c; } handleLoadMore = (e) => { e.preventDefault(); this.props.onScrollToBottom(); } render () { const { statusIds, scrollKey, trackScroll, shouldUpdateScroll, isLoading, hasMore, prepend, emptyMessage } = this.props; let loadMore = null; let scrollableArea = null; if (!isLoading && statusIds.size > 0 && hasMore) { loadMore = <LoadMore onClick={this.handleLoadMore} />; } if (isLoading || statusIds.size > 0 || !emptyMessage) { scrollableArea = ( <div className='scrollable' ref={this.setRef}> <div className='status-list'> {prepend} {statusIds.map((statusId) => { return <StatusContainer key={statusId} id={statusId} intersectionObserverWrapper={this.intersectionObserverWrapper} />; })} {loadMore} </div> </div> ); } else { scrollableArea = ( <div className='empty-column-indicator' ref={this.setRef}> {emptyMessage} </div> ); } if (trackScroll) { return ( <ScrollContainer scrollKey={scrollKey} shouldUpdateScroll={shouldUpdateScroll}> {scrollableArea} </ScrollContainer> ); } else { return scrollableArea; } } } export default StatusList;
src/svg-icons/communication/dialer-sip.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationDialerSip = (props) => ( <SvgIcon {...props}> <path d="M17 3h-1v5h1V3zm-2 2h-2V4h2V3h-3v3h2v1h-2v1h3V5zm3-2v5h1V6h2V3h-3zm2 2h-1V4h1v1zm0 10.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.01.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.27-.26.35-.65.24-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1z"/> </SvgIcon> ); CommunicationDialerSip = pure(CommunicationDialerSip); CommunicationDialerSip.displayName = 'CommunicationDialerSip'; CommunicationDialerSip.muiName = 'SvgIcon'; export default CommunicationDialerSip;
misc/webgui/src/containers/ServicesList.js
ChainsAutomation/chains
import React from 'react'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import { loadServicesData } from '../actions/index'; import ServiceDetail from '../components/ServiceDetail'; class ServicesList extends React.Component { componentDidMount() { /* console.log("ServiceList"); console.log(this.props); */ if(Object.keys(this.props.services).length === 0) { this.props.loadServicesData(); } } render() { /* var serviceNodes = this.props.services.map(function(service, index) { return ( <ServiceDetail name={service.name} status={service.online} key={index}> {service.id} </ServiceDetail> ); }); */ // var serviceNodes = this.props.services; let serviceNodes = []; var scount = 0; for (var srv in this.props.services) { const sid = this.props.services[srv]['id']; const sname = this.props.services[srv]['name']; const sonline = this.props.services[srv]['online']; const sclass = this.props.services[srv]['class']; const sautostart = this.props.services[srv]['autostart']; const smanager = this.props.services[srv]['manager']; let heartdate = "offline"; if (this.props.services[srv]['heartbeat'] !== 0) { const d = new Date(this.props.services[srv]['heartbeat'] * 1000); heartdate = d.toLocaleTimeString() + ' - ' + d.toLocaleDateString(); } const srvdet = ( <div className="column"> <ServiceDetail key={sid} name={sname} status={sonline} sclass={sclass} autostart={sautostart} manager={smanager} heartbeat={heartdate}/> </div> ) if(sonline) { serviceNodes.unshift(srvdet); } else { serviceNodes.push(srvdet); } scount++; } return ( <div className="ui three column stackable grid"> {serviceNodes} </div> ); } } function mapStateToProps(state) { return { services: state.services }; } function mapDispatchToProps(dispatch){ return bindActionCreators({loadServicesData: loadServicesData}, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(ServicesList);
client/src/lib/castStringToElement.js
silverstripe/silverstripe-admin
import React from 'react'; /** * Searches the given string and highlights/marks instances of needle found * with the given tag * * @param {string} haystack * @param {string} needle * @param {React|string} Tag * @return {Array} */ export function mapHighlight(haystack, needle, Tag) { let index = 0; let search = haystack; const results = []; const part = needle.toLocaleLowerCase(); while (index !== -1) { index = search.toLocaleLowerCase().indexOf(part); if (index !== -1) { const next = index + needle.length; const start = search.substring(0, index); const found = search.substring(index, next); const end = search.substring(next); if (start.length) { results.push(start); } results.push((Tag) ? <Tag key={results.length / 2}>{found}</Tag> : found); search = end; } } results.push(search); return results; } /** * Safely cast string to container element. Supports custom HTML values. * * See DBField::getSchemaValue() * * @param {String|Component} Container Container type * @param {*} value Form schema value * @param {object} props container props */ export default function castStringToElement(Container, value, props = {}) { if (value && typeof value.react !== 'undefined') { return <Container {...props}>{value.react}</Container>; } // HTML value if (value && typeof value.html !== 'undefined') { if (value.html !== null) { const html = { __html: value.html }; return <Container {...props} dangerouslySetInnerHTML={html} />; } return null; } // Plain value let body = null; if (value && typeof value.text !== 'undefined') { body = value.text; } else { body = value; } if (body && typeof body === 'object') { throw new Error(`Unsupported string value ${JSON.stringify(body)}`); } if (body !== null && typeof body !== 'undefined') { return <Container {...props}>{body}</Container>; } return null; }
src/app/Components/UploadImage.js
isaacjoh/foreseehome-test
import React from 'react'; import ReactDOM from 'react-dom'; import RaisedButton from 'material-ui/RaisedButton'; import newId from '../utils/NewId'; import Webcam from 'react-webcam'; class UploadImage extends React.Component { constructor(props) { super(props); this.state = { file: '', imagePreviewUrl: props.imagePreviewUrl || '', mobileImagePreviewUrl: null, reset: props.imagePreviewUrl ? false : true, resetPreviews: null, ready: false }; } _handleImageChange(e) { e.preventDefault(); let reader = this.props.reader; let file = e.target.files[0]; reader.onloadend = () => { if (this.props.getScreenshotSrc) { this.props.getScreenshotSrc(reader.result); } let URL = window.URL || window.webkitURL; let urlSrc = URL.createObjectURL(file); this.setState({ file: file, imagePreviewUrl: urlSrc }); } reader.readAsDataURL(file); } setRef = (webcam) => { this.webcam = webcam; } capture = () => { const imageSrc = this.webcam.getScreenshot(); this.setState({ reset: false, mobileImagePreviewUrl: imageSrc }); if (this.props.getScreenshotSrc) { this.props.getScreenshotSrc(imageSrc); } }; onReset = () => { this.setState({ reset: true, mobileImagePreviewUrl: null, imagePreviewUrl: null }); this.props.getScreenshotSrc(null); } componentWillUpdate(nextProps, nextState) { let resetPreviews = this.state.resetPreviews || nextProps.resetPreviews; if (resetPreviews !== 'completed' && resetPreviews) { this.setState({ resetPreviews: 'completed' }); this.onReset(); } } componentWillMount() { this.id = newId(); if (this.props.imagePreviewUrl) { this.props.onUploadComplete(); } } componentDidMount() { // setTimeout because clicking on yes overlapped with clicking on taking picture setTimeout(() => { this.setState({ ready: true }); }, 250); } render() { const isMobile = window.innerWidth <= 1025; const iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; let hide = this.state.reset || !(this.props.imagePreviewUrl) ? '' : 'hide'; let {imagePreviewUrl} = this.state; let $imagePreview = null; if (imagePreviewUrl) { $imagePreview = (<div className={'img-preview text-center'}><div className="preview-text"><img src={imagePreviewUrl} /></div></div> ); } else { $imagePreview = (<div className="preview-text"></div>); } if (!isMobile) { return ( <div className="preview-component"> <label htmlFor={this.id} className="custom-file-upload"> Choose File </label> <input id={this.id} type="file" onChange={(e) => this._handleImageChange(e)} /> <div className={this.state.file ? 'img-preview text-center' : ''}> {$imagePreview} </div> </div> ) } if (isMobile) { return ( <div className="webcam-container" key={this.id}> <label htmlFor={this.id} className="custom-file-upload"> Take picture </label> <input type="file" accept="image/*" id={this.id} capture="camera" disabled={!this.state.ready} onChange={(e) => this._handleImageChange(e)} /> <div className={this.state.file ? 'img-preview text-center' : ''}> {$imagePreview} </div> </div> ) } // if (isMobile && !iOS) { // return ( // <div className="webcam-container" key={this.id}> // <div className={`webcam-component ${hide}`}> // <Webcam audio={false} // onUserMedia={() => this.onCapture} // ref={this.setRef} // screenshotFormat="image/jpeg" /> // </div> // <div className={this.state.file ? 'img-preview text-center' : 'hide'}> // {$imagePreview} // </div> // {!this.state.reset && ( // <div className="webcam-preview"> // <img src={this.state.mobileImagePreviewUrl || this.props.imagePreviewUrl} alt="Preview"/> // </div> // )} // <RaisedButton label="Retake" // className="retake-btn" // labelStyle={{fontSize: '18px'}} // style={{height: '48px'}} // onClick={() => this.onReset()} // primary={true} /> // <button style={{marginTop: '10px'}} onClick={() => this.capture()} disabled={!this.state.reset}> // <i className="material-icons">photo_camera</i> // </button> // </div> // ) // } } } export default UploadImage;
src/routes/contact/index.js
jimmykobe1171/chatbotta
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import Contact from './Contact'; const title = 'Contact Us'; export default { path: '/contact', action() { return { title, component: <Layout><Contact title={title} /></Layout>, }; }, };
Rosa_Madeira/Cliente/src/components/screens/CompraScreen.js
victorditadi/IQApp
import React, { Component } from 'react'; import { Text, View, AsyncStorage } from 'react-native'; import CompraLista from '../compra/CompraLista'; class CompraScreen extends Component { render() { return( <View style={{flex: 1, backgroundColor: '#f6f2ef'}}> <View style={{marginTop: 20, marginBottom: 60, flex: 1}}> <CompraLista /> </View> </View> ); } } export default CompraScreen;
src/entry.js
lixiaoyang1992/react-native-starter-kit
import React from 'react'; import { Provider } from 'react-redux'; import codePush from 'react-native-code-push'; import Storage from 'react-native-storage'; import { AsyncStorage } from 'react-native'; import { default as configureStore } from './store/createStore'; import Index from './router/App'; const store = configureStore(); class App extends React.Component { componentDidMount() { codePush.sync(); } render() { return ( <Provider store={store}> <Index /> </Provider> ); } } const codePushOptions = { checkFrequency: codePush.CheckFrequency.ON_APP_RESUME }; export default codePush(codePushOptions)(App); const storage = new Storage({ // 最大容量,默认值1000条数据循环存储 size: 1000, // 存储引擎:对于RN使用AsyncStorage,对于web使用window.localStorage // 如果不指定则数据只会保存在内存中,重启后即丢失 storageBackend: AsyncStorage, // 数据过期时间,默认一整天(1000 * 3600 * 24 毫秒),设为null则永不过期 defaultExpires: null, // 读写时在内存中缓存数据。默认启用。 enableCache: true, // 如果storage中没有相应数据,或数据已过期, // 则会调用相应的sync方法,无缝返回最新数据。 // sync方法的具体说明会在后文提到 // 你可以在构造函数这里就写好sync的方法 // 或是写到另一个文件里,这里require引入 // 或是在任何时候,直接对storage.sync进行赋值修改 // sync: require('./sync'), }); global.storage = storage;
src/js/components/Scroll/InfiniteScroll.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { ScrollContainer } from 'react-router-scroll'; import ReactInfinite from 'react-infinite'; export default class InfiniteScroll extends Component { static propTypes = { containerId : PropTypes.string.isRequired, firstItems : PropTypes.array, items : PropTypes.array, itemHeight : PropTypes.number, onResize : PropTypes.func, columns : PropTypes.number, onInfiniteLoad: PropTypes.func, loading : PropTypes.bool, }; static contextTypes = { scrollBehavior: PropTypes.object }; constructor(props) { super(props); this.onInfiniteLoad = this.onInfiniteLoad.bind(this); this.getHeight = this.getHeight.bind(this); this.getHeightList = this.getHeightList.bind(this); this.getScrollContainer = this.getScrollContainer.bind(this); this.getLoadingGif = this.getLoadingGif.bind(this); this.applyScroll = this.applyScroll.bind(this); this.handleScroll = this.handleScroll.bind(this); this.renderScroll = this.renderScroll.bind(this); this.state = { mustRender: null, } } componentDidMount() { this.checkMustRender(); window.addEventListener('resize', this.props.onResize); this.applyScroll(); } componentWillUnmount() { window.removeEventListener('resize', this.props.onResize); } componentDidUpdate() { this.checkMustRender(); this.applyScroll(); } applyScroll() { const scrollBehavior = this.context.scrollBehavior.scrollBehavior; setTimeout(() => scrollBehavior.updateScroll(this.context, this.context), 0); } checkMustRender() { if (!this.state.mustRender && this.getScrollContainer()) { this._setMustRender(); } } _setMustRender() { this.setState({ mustRender: true }) } onInfiniteLoad() { this.props.onInfiniteLoad(); } getLoadingGif() { return this.props.loading ? <div className="loading-gif"></div> : ''; } handleScroll() { const scrollBehavior = this.context.scrollBehavior.scrollBehavior; const containerId = this.props.containerId; scrollBehavior._saveElementPosition(containerId); } getHeight() { const topMargin = this.getTopMargin(); const toolbarHeight = this.getToolbarHeight(); const scrollContainerHeight = this.getScrollContainerHeight.bind(this)(); return parseInt(scrollContainerHeight - (topMargin + toolbarHeight)); } getHeightList() { const {firstItems, items, columns, itemHeight} = this.props; const topMargin = this.getTopMargin(); const firstItemsHeight = topMargin / firstItems.length; let itemsHeights = firstItems.map(item => firstItemsHeight); const scrollItemsLength = Math.ceil(items.length/columns); for (let i=0; i<scrollItemsLength; i++) { itemsHeights.push(itemHeight); } return itemsHeights; } getTopMargin() { const pageContent = document.getElementById('scroll-wrapper'); if (!pageContent) { return 0; } const style = window.getComputedStyle(pageContent); const property = style.getPropertyValue('margin-top'); return parseInt(property.slice(0, -2)); } getToolbarHeight() { const toolbars = document.getElementsByClassName('toolbar'); if (toolbars.length === 0) { return null; } const style = window.getComputedStyle(toolbars[0]); const property = style.getPropertyValue('height'); return parseInt(property.slice(0, -2)); } getScrollContainer() { return document.getElementById(this.props.containerId); } getScrollContainerHeight() { const scrollContainer = this.getScrollContainer(); return !scrollContainer ? null : scrollContainer.clientHeight ? scrollContainer.clientHeight : scrollContainer.offsetHeight ? scrollContainer.offsetHeight : null; } wrap(items, columns) { let wrappedItems = []; let index = 0; while (index < items.length) { const wrappedItemsNextIndex = index + columns; wrappedItems.push(items.slice(index, wrappedItemsNextIndex)); index = wrappedItemsNextIndex; } return wrappedItems.map((wrappedItem, index) => { return ( <div key={index}> {wrappedItem} </div> ); }); } getList() { const {firstItems, items, columns} = this.props; const wrappedItems = this.wrap(items, columns); const list = [...firstItems, ...wrappedItems]; return list.slice(0); } renderScroll() { const height = this.getHeight(); const containerId = this.props.containerId; return <ScrollContainer scrollKey={containerId}> <ReactInfinite elementHeight={this.getHeightList()} isInfiniteLoading={this.props.loading} infiniteLoadBeginEdgeOffset={700} loadingSpinnerDelegate={this.getLoadingGif()} handleScroll={this.handleScroll} containerHeight={height} className='react-infinite-div' onInfiniteLoad={this.onInfiniteLoad} preloadBatchSize={100} //small values can cause infinite loop https://github.com/seatgeek/react-infinite/pull/48 preloadAdditionalHeight={ReactInfinite.containerHeightScaleFactor(5)} > {this.getList()} </ReactInfinite> </ScrollContainer> } render() { const {mustRender} = this.state; return mustRender ? <div id="infinite-scroll"> {this.renderScroll()} </div> : null; } } InfiniteScroll.defaultProps = { onInfiniteLoad: () => {}, firstItems : [], items : [], itemHeight : 360, columns : 1, loading : false, };
src/js/admin/articles/table-nav-link/table-nav-link.js
ucev/blog
import React from 'react' import { connect } from 'react-redux' import { handlePageChange } from '$actions/articles' import TableNavLink from '$components/table-foot-nav' const ArticleTableNavLink = ({ page, total, pageChange }) => ( <TableNavLink page={page} total={total} pagechange={pageChange} /> ) const mapStateToProps = state => ({ page: state.current, total: state.total, }) const mapDispatchToProps = dispatch => ({ pageChange: page => { dispatch(handlePageChange(page)) }, }) const _ArticleTableNavLink = connect( mapStateToProps, mapDispatchToProps )(ArticleTableNavLink) export default _ArticleTableNavLink
app/javascript/mastodon/features/public_timeline/index.js
haleyashleypraesent/ProjectPrionosuchus
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { refreshPublicTimeline, expandPublicTimeline, updateTimeline, deleteFromTimelines, connectTimeline, disconnectTimeline, } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import ColumnSettingsContainer from './containers/column_settings_container'; import createStream from '../../stream'; const messages = defineMessages({ title: { id: 'column.public', defaultMessage: 'Federated timeline' }, }); const mapStateToProps = state => ({ hasUnread: state.getIn(['timelines', 'public', 'unread']) > 0, streamingAPIBaseURL: state.getIn(['meta', 'streaming_api_base_url']), accessToken: state.getIn(['meta', 'access_token']), }); class PublicTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, multiColumn: PropTypes.bool, streamingAPIBaseURL: PropTypes.string.isRequired, accessToken: PropTypes.string.isRequired, hasUnread: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('PUBLIC', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch, streamingAPIBaseURL, accessToken } = this.props; dispatch(refreshPublicTimeline()); if (typeof this._subscription !== 'undefined') { return; } this._subscription = createStream(streamingAPIBaseURL, accessToken, 'public', { connected () { dispatch(connectTimeline('public')); }, reconnected () { dispatch(connectTimeline('public')); }, disconnected () { dispatch(disconnectTimeline('public')); }, received (data) { switch(data.event) { case 'update': dispatch(updateTimeline('public', JSON.parse(data.payload))); break; case 'delete': dispatch(deleteFromTimelines(data.payload)); break; } }, }); } componentWillUnmount () { if (typeof this._subscription !== 'undefined') { this._subscription.close(); this._subscription = null; } } setRef = c => { this.column = c; } handleLoadMore = () => { this.props.dispatch(expandPublicTimeline()); } render () { const { intl, columnId, hasUnread, multiColumn } = this.props; const pinned = !!columnId; return ( <Column ref={this.setRef}> <ColumnHeader icon='globe' active={hasUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer /> </ColumnHeader> <StatusListContainer timelineId='public' loadMore={this.handleLoadMore} trackScroll={!pinned} scrollKey={`public_timeline-${columnId}`} emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other instances to fill it up' />} /> </Column> ); } } export default connect(mapStateToProps)(injectIntl(PublicTimeline));
demos/buttons/demos/flat-default.js
isogon/styled-mdl-website
import React from 'react' import { Button } from 'styled-mdl' const demo = () => <Button>Default</Button> const caption = 'Default Button' const code = '<Button>Default</Button>' export default { demo, caption, code }
src/components/CommonComponent/FeedCard/feedCard.js
sourabh-garg/react-starter-kit
import React from 'react'; import './feedCard_mobile.scss'; import FeedImages from './feedImages'; class FeedCard extends React.Component{ constructor(props) { super(props); } componentDidMount() { } render () { let data = this.props.data; let photoCollection = data.photoUrls; if(data.feedType === 1){ photoCollection = data.collectionDetail; } if(data.feedType === 3){ photoCollection = data.productDetail; } return ( <div className="feed-card-div"> <a href=""></a> <h4>{data.title}</h4> <h6>{data.description}</h6> <FeedImages feedType={data.feedType} photoCollection ={photoCollection} /> <div className="flex action_btn"> <button onClick={this.props.add}>ADD</button> <button onClick={this.props.share}>SHARE</button> </div> </div> ); } } export default FeedCard;
app/components/elements/Pagination.js
tidepool-org/blip
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import map from 'lodash/map'; import remove from 'lodash/remove'; import includes from 'lodash/includes'; import capitalize from 'lodash/capitalize'; import { Box, Text, BoxProps } from 'rebass/styled-components'; import FirstPageRoundedIcon from '@material-ui/icons/FirstPageRounded'; import LastPageRoundedIcon from '@material-ui/icons/LastPageRounded'; import NavigateBeforeRoundedIcon from '@material-ui/icons/NavigateBeforeRounded'; import NavigateNextRoundedIcon from '@material-ui/icons/NavigateNextRounded'; import MoreHorizRoundedIcon from '@material-ui/icons/MoreHorizRounded'; import { usePagination, PaginationProps } from '@material-ui/lab/Pagination'; import i18next from '../../core/language'; import Button from './Button'; import Icon from './Icon'; import baseTheme from '../../themes/baseTheme'; const t = i18next.t.bind(i18next); export const Pagination = props => { const { id, variant, buttonVariant, controlLabels, ...paginationProps } = props; const classNames = cx({ condensed: variant === 'condensed', }); const { items } = usePagination(paginationProps); const prevControls = remove(items, ({ type }) => includes(['first', 'previous'], type)); const nextControls = remove(items, ({ type }) => includes(['next', 'last'], type)); return ( <Box as="nav" variant={`paginators.${variant}`} {...paginationProps}> <ul className={classNames}> <li> <ul className="prev-controls"> {map(prevControls, ({ type, ...item }) => ( <li id={`${id}-${type}`} key={`${id}-${type}`}> <Button px={2} variant={buttonVariant} {...item}> {type === 'first' && <Icon variant="static" theme={baseTheme} label="Go to first page" icon={FirstPageRoundedIcon} />} {type === 'previous' && <Icon variant="static" theme={baseTheme} label="Go to previous page" icon={NavigateBeforeRoundedIcon} />} {variant === 'default' && <Text pl={1}>{capitalize(controlLabels[type])}</Text>} </Button> </li> ))} </ul> </li> <li> <ul className="pages"> {map(items, ({ page, type, selected, ...item }) => { const pageClassNames = cx({ selected, }); const itemId = type === 'page' ? `${id}-${page}` : `${id}-${type}`; let children; if (type === 'start-ellipsis' || type === 'end-ellipsis') { children = ( <Button disabled className="ellipsis" variant="pagination"> <Icon variant="static" theme={baseTheme} label="Ellipsis for skipped pages" icon={MoreHorizRoundedIcon} /> </Button> ); } else if (type === 'page') { children = ( <Button className={pageClassNames} variant={buttonVariant} {...item}> {page} </Button> ); } return <li id={itemId} key={itemId}>{children}</li>; })} </ul> </li> <li> <ul className="next-controls"> {map(nextControls, ({ type, ...item }) => ( <li id={`${id}-${type}`} key={`${id}-${type}`}> <Button px={2} variant={buttonVariant} {...item}> {variant === 'default' && <Text pr={1}>{capitalize(controlLabels[type])}</Text>} {type === 'next' && <Icon variant="static" theme={baseTheme} label="Go to next page" icon={NavigateNextRoundedIcon} />} {type === 'last' && <Icon variant="static" theme={baseTheme} label="Go to last page" icon={LastPageRoundedIcon} />} </Button> </li> ))} </ul> </li> </ul> </Box> ); }; Pagination.propTypes = { id: PropTypes.string.isRequired, ...PaginationProps, ...BoxProps, controlLabels: PropTypes.shape({ first: PropTypes.string.isRequired, last: PropTypes.string.isRequired, previous: PropTypes.string.isRequired, next: PropTypes.string.isRequired, }), variant: PropTypes.oneOf(['default', 'condensed']), buttonVariant: PropTypes.oneOf(['pagination', 'paginationLight']), }; Pagination.defaultProps = { variant: 'default', buttonVariant: 'pagination', controlLabels: { first: t('First'), last: t('Last'), previous: t('Previous'), next: t('Next'), }, }; export default Pagination;
app/components/ContainerContent.js
pbillerot/reacteur
'use strict'; import React from 'react'; import { Link } from 'react-router'; // W3 const {Button, Card, Content, Footer, Header, IconButton , Menubar, Nav, Navbar, NavGroup, Sidebar, Table, Window} = require('./w3.jsx') export default class ContainerContent extends React.Component { constructor(props) { super(props); } render() { return ( <div className="w3-main w3-padding-64" style={{ marginLeft: '250px' }}> {this.props.children} </div> ) } }
src/containers/common/NoMatch.js
vivaxy/react-scaffold
/** * @since 2016-09-01 08:18 * @author vivaxy */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; class NoMatch extends Component { static propTypes = { params: PropTypes.object.isRequired, location: PropTypes.object.isRequired, }; render() { const { params, location, } = this.props; return ( <div> {JSON.stringify(params)} {JSON.stringify(location)} </div> ); } } export default connect(null, {})(NoMatch);
packages/material-ui-icons/src/SignalWifi0Bar.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SignalWifi0Bar = props => <SvgIcon {...props}> <path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z" /> </SvgIcon>; SignalWifi0Bar = pure(SignalWifi0Bar); SignalWifi0Bar.muiName = 'SvgIcon'; export default SignalWifi0Bar;
src/components/home.js
cynthiacd/capstone-factoring-app
import React from 'react'; import { Link } from 'react-router'; const Home = () => { return ( <div className="instruction-info-patterns"> <h1>Welcome</h1> <p>You have found yourself at an <a href="https://adadevelopersacademy.org/" target="_blank">ADA </a> developer’s capstone project.</p> <p>This site was a self-directed project that I took from concept to production. I built this app with React and Redux on the frontend and a Rails API for the backend. This app was inspired by my previous career as a math and science teacher/tutor. 5 years of teaching students one-on-one, taught me that many students struggle with specific patterns within one type of problem. </p> <p>For example quadratic factoring. While the overall strategies to factoring are the same for all problems, it is common for students to struggle with the signs. The signs of the expression can be catorigized by patterns and identifiying these patterns can help you solve the problem. As a tutor, I observed this over and over again and found providing students with extra practice on the specific patterns they struggled with lead to the biggest improvements. </p> <p>But I always wanted a way to serve unlimited targeted practice ... </p> <p>Click on <Link to="/signup">sign up</Link> to start to see more and start factoring</p> </div> ); } export default Home; // could import a picture of factoring process ... // could have your flow chart and example // and box
actor-apps/app-web/src/app/components/DialogSection.react.js
shaunstanislaus/actor-platform
import _ from 'lodash'; import React from 'react'; import { PeerTypes } from 'constants/ActorAppConstants'; import MessagesSection from 'components/dialog/MessagesSection.react'; import TypingSection from 'components/dialog/TypingSection.react'; import ComposeSection from 'components/dialog/ComposeSection.react'; import DialogStore from 'stores/DialogStore'; import MessageStore from 'stores/MessageStore'; import GroupStore from 'stores/GroupStore'; import DialogActionCreators from 'actions/DialogActionCreators'; // On which scrollTop value start loading older messages const LoadMessagesScrollTop = 100; const initialRenderMessagesCount = 20; const renderMessagesStep = 20; let renderMessagesCount = initialRenderMessagesCount; let lastPeer = null; let lastScrolledFromBottom = 0; const getStateFromStores = () => { const messages = MessageStore.getAll(); let messagesToRender; if (messages.length > renderMessagesCount) { messagesToRender = messages.slice(messages.length - renderMessagesCount); } else { messagesToRender = messages; } return { peer: DialogStore.getSelectedDialogPeer(), messages: messages, messagesToRender: messagesToRender }; }; class DialogSection extends React.Component { constructor() { super(); this.state = getStateFromStores(); DialogStore.addSelectListener(this.onSelectedDialogChange); MessageStore.addChangeListener(this.onMessagesChange); } componentWillUnmount() { DialogStore.removeSelectListener(this.onSelectedDialogChange); MessageStore.removeChangeListener(this.onMessagesChange); } componentDidUpdate() { this.fixScroll(); this.loadMessagesByScroll(); } render() { const peer = this.state.peer; if (peer) { let isMember = true; let memberArea; if (peer.type === PeerTypes.GROUP) { const group = GroupStore.getGroup(peer.id); isMember = DialogStore.isGroupMember(group); } if (isMember) { memberArea = ( <div> <TypingSection/> <ComposeSection peer={this.state.peer}/> </div> ); } else { memberArea = ( <section className="compose compose--disabled row center-xs middle-xs"> <h3>You are not member</h3> </section> ); } return ( <section className="dialog" onScroll={this.loadMessagesByScroll}> <MessagesSection messages={this.state.messagesToRender} peer={this.state.peer} ref="MessagesSection"/> {memberArea} </section> ); } else { return ( <section className="dialog row middle-xs center-xs" ref="MessagesSection"> Select dialog or start a new one. </section> ); } } fixScroll = () => { let node = React.findDOMNode(this.refs.MessagesSection); node.scrollTop = node.scrollHeight - lastScrolledFromBottom; } onSelectedDialogChange = () => { renderMessagesCount = initialRenderMessagesCount; if (lastPeer != null) { DialogActionCreators.onConversationClosed(lastPeer); } lastPeer = DialogStore.getSelectedDialogPeer(); DialogActionCreators.onConversationOpen(lastPeer); } onMessagesChange = _.debounce(() => { this.setState(getStateFromStores()); }, 10, {maxWait: 50, leading: true}); loadMessagesByScroll = _.debounce(() => { let node = React.findDOMNode(this.refs.MessagesSection); var scrollTop = node.scrollTop; lastScrolledFromBottom = node.scrollHeight - scrollTop; if (node.scrollTop < LoadMessagesScrollTop) { DialogActionCreators.onChatEnd(this.state.peer); if (this.state.messages.length > this.state.messagesToRender.length) { renderMessagesCount += renderMessagesStep; if (renderMessagesCount > this.state.messages.length) { renderMessagesCount = this.state.messages.length; } this.setState(getStateFromStores()); } } }, 5, {maxWait: 30}) } export default DialogSection;
src/components/Footer.js
toannhu/React-Pokedex
import React, { Component } from 'react'; import { Icon, Segment } from 'semantic-ui-react'; export default class Footer extends Component { render() { return ( <Segment.Group> <Segment padded='very' textAlign='center'> <div style={{fontSize: '14px'}}> <Icon color='red' name='copyright' size='large'/> 2017 Nhu Dinh Toan, BK University </div> <div style={{fontSize: '14px'}}> <a href='https://www.facebook.com/dinhtoan.nhu.9' target='_blank' rel="noopener noreferrer"><Icon name='facebook square' size='large' link/></a> <a href='https://github.com/toannhu' target='_blank' rel="noopener noreferrer"><Icon name='github' size='large' color = "black" link/></a> <a href='https://www.linkedin.com/in/toannhu/' target='_blank' rel="noopener noreferrer"><Icon name='linkedin' size='large' link/></a> </div> </Segment> </Segment.Group> ); } }
src/components/feed/filters.js
Hommasoft/wappuapp-adminpanel
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { DropdownButton, MenuItem, Row, Modal, Button, FormControl, FormGroup, ControlLabel } from 'react-bootstrap'; import * as Filt from '../../actions/filters'; class Filters extends Component { constructor(props) { super(props); this.changeCity = this.changeCity.bind(this); this.changeSort = this.changeSort.bind(this); this.changeType = this.changeType.bind(this); this.changeReports = this.changeReports.bind(this); this.closeMsgBox = this.closeMsgBox.bind(this); this.showMsgBox = this.showMsgBox.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.state = { showModal: false, reportSelect: 'Feed' }; } changeSort(sortType) { this.props.changeSort(sortType); this.props.fetchFeed(); } changeType(feedType) { this.props.changeType(feedType); this.props.fetchFeed(); } changeCity(city) { this.props.changeCity(city); this.props.fetchFeed(); } changeReports(feedType) { if (feedType === 'Reports') { this.props.fetchReports(); } else { this.props.changeToFeed(); } this.setState({ reportSelect: feedType }); } showMsgBox() { this.setState({ showModal: true }); } closeMsgBox() { this.setState({ showModal: false }); } handleSubmit(event) { event.preventDefault(); this.props.sendSystemMsg(event.target[0].value, event.target[1].value); this.setState({ showModal: false }); this.props.fetchFeed(); } render() { return ( <Row className="filters"> <DropdownButton title={this.props.city.name} id="city"> <MenuItem key="all" eventKey={{ id: 0, name: 'All' }} onSelect={this.changeCity}> All </MenuItem> {this.props.cities.map(city => ( <MenuItem key={city.id} eventKey={city} onSelect={this.changeCity}> {city.name} </MenuItem> ))} </DropdownButton> <DropdownButton title={this.props.sort} id="sort"> <MenuItem key="new" eventKey="New" onSelect={this.changeSort}> New </MenuItem> <MenuItem key="hot" eventKey="Hot" onSelect={this.changeSort}> Hot </MenuItem> </DropdownButton> <DropdownButton title={this.props.type} id="type"> <MenuItem key="all" eventKey="Type" onSelect={this.changeType}> All </MenuItem> <MenuItem key="text" eventKey="TEXT" onSelect={this.changeType}> Text </MenuItem> <MenuItem key="image" eventKey="IMAGE" onSelect={this.changeType}> Image </MenuItem> </DropdownButton> <DropdownButton title={this.state.reportSelect} id="reportselect"> <MenuItem eventKey="Feed" onSelect={this.changeReports}> Feed </MenuItem> <MenuItem eventKey="Reports" onSelect={this.changeReports}> Reports </MenuItem> </DropdownButton> <Button onClick={this.showMsgBox}>Send message</Button> <Modal show={this.state.showModal} onHide={this.closeMsgBox}> <Modal.Header closeButton> <Modal.Title>Send system message</Modal.Title> </Modal.Header> <Modal.Body> <form onSubmit={this.handleSubmit}> <FormGroup> <ControlLabel>Text</ControlLabel> <FormControl type="text" placeholder="Hello World!" /> </FormGroup> <FormGroup> <ControlLabel>City</ControlLabel> <FormControl componentClass="select"> {this.props.cities.map(city => ( <option key={city.id} value={city.id}> {city.name} </option> ))} </FormControl> </FormGroup> <FormGroup> <Button type="submit">Submit</Button> </FormGroup> </form> </Modal.Body> </Modal> </Row> ); } } const mapStateToProps = state => { return { city: state.filters.city, sort: state.filters.sort, type: state.filters.type }; }; export default connect(mapStateToProps, Filt)(Filters);
src/svg-icons/editor/attach-file.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorAttachFile = (props) => ( <SvgIcon {...props}> <path d="M16.5 6v11.5c0 2.21-1.79 4-4 4s-4-1.79-4-4V5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6H10v9.5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V5c0-2.21-1.79-4-4-4S7 2.79 7 5v12.5c0 3.04 2.46 5.5 5.5 5.5s5.5-2.46 5.5-5.5V6h-1.5z"/> </SvgIcon> ); EditorAttachFile = pure(EditorAttachFile); EditorAttachFile.displayName = 'EditorAttachFile'; EditorAttachFile.muiName = 'SvgIcon'; export default EditorAttachFile;
src/components/Header/Header.js
piu130/react-redux-gpa-app
import React from 'react' import { browserHistory } from 'react-router' import { Navbar, Nav, NavItem } from 'react-bootstrap' import FontAwesome from 'react-fontawesome' import './Header.scss' export const Header = (props) => ( <Navbar fluid> <Navbar.Header> <Navbar.Brand> <Navbar.Link onClick={() => browserHistory.push('/')} style={{ cursor: 'pointer' }}><FontAwesome name='home' /> GPA-App</Navbar.Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> {props.loggedIn ? ( <Navbar.Collapse> <Nav> {props.user ? (<NavItem disabled>Signed in as: {props.user.firstName} {props.user.surname}</NavItem>) : ''} <NavItem onClick={() => browserHistory.push('/profile')}><FontAwesome name='user' /> Profile</NavItem> <NavItem onClick={() => browserHistory.push('/about')}><FontAwesome name='question-circle' /> About</NavItem> <NavItem onClick={() => browserHistory.push('/settings')}><FontAwesome name='gear' /> Settings</NavItem> </Nav> <Nav pullRight> <NavItem onClick={() => browserHistory.push('/logout')}><FontAwesome name='sign-out' /> Sign out</NavItem> </Nav> </Navbar.Collapse> ) : ''} </Navbar> ) export default Header
src/containers/app-shell.js
twreporter/twreporter-react
import { connect } from 'react-redux' import ErrorBoundary from '../components/ErrorBoundary' import Footer from '@twreporter/react-components/lib/footer' import Header from '@twreporter/universal-header/lib/containers/header' import PropTypes from 'prop-types' import React from 'react' // comment out WebPush for live blog banners to occupy the space for the time being // import WebPush from '../components/web-push' import styled from 'styled-components' import twreporterRedux from '@twreporter/redux' import uiConst from '../constants/ui' import uiManager from '../managers/ui-manager' // lodash import get from 'lodash/get' import values from 'lodash/values' const _ = { get, values, } const { reduxStateFields } = twreporterRedux const AppBox = styled.div` background-color: ${props => props.backgroundColor}; ` const ContentBlock = styled.div` position: relative; ` const HeaderContainer = styled.div` position: sticky; top: 0; z-index: 1000; // other components in twreporter-react has z-index 999 ` const TransparentHeader = styled.div` position: fixed; top: 0; width: 100%; z-index: 1000; // other component has z-index 999 ` // TODO add `pink` theme to universal-header const PinkBackgroundHeader = styled.div` position: relative; background-color: #fabcf0; ` const renderFooter = (footerType, pathname = '', host = '', releaseBranch) => { switch (footerType) { case uiConst.footer.none: { return null } case uiConst.footer.default: default: { return ( <Footer host={host} pathname={pathname} releaseBranch={releaseBranch} /> ) } } } const renderHeader = (headerType, releaseBranch) => { let headerTheme switch (headerType) { case uiConst.header.none: return null case uiConst.header.transparent: case uiConst.header.pink: headerTheme = 'transparent' break case uiConst.header.photo: headerTheme = 'photography' break default: headerTheme = 'normal' break } let headerElement = ( <Header theme={headerTheme} releaseBranch={releaseBranch} isLinkExternal={false} /> ) if (headerType === uiConst.header.transparent) { headerElement = <TransparentHeader>{headerElement}</TransparentHeader> } else if (headerType === uiConst.header.pink) { headerElement = <PinkBackgroundHeader>{headerElement}</PinkBackgroundHeader> } return ( <HeaderContainer className="hidden-print">{headerElement}</HeaderContainer> ) } class AppShell extends React.PureComponent { static propTypes = { apiOrigin: PropTypes.string, backgroundColor: PropTypes.string, footerType: PropTypes.oneOf(_.values(uiConst.footer)), headerType: PropTypes.oneOf(_.values(uiConst.header)), releaseBranch: PropTypes.string.isRequired, userId: PropTypes.string, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), pathname: PropTypes.string.isRequired, host: PropTypes.string.isRequired, } static defaultProps = { headerType: uiConst.header.default, footerType: uiConst.footer.default, backgroundColor: '#f1f1f1', } render() { const { // apiOrigin, headerType, footerType, backgroundColor, releaseBranch, children, // userId, pathname, host, } = this.props return ( <ErrorBoundary> <AppBox backgroundColor={backgroundColor}> <ContentBlock> {/* <WebPush apiOrigin={apiOrigin} userId={userId} /> */} {renderHeader(headerType, releaseBranch)} {children} {renderFooter(footerType, pathname, host, releaseBranch)} </ContentBlock> </AppBox> </ErrorBoundary> ) } } function mapStateToProps(state, ownProps) { return Object.assign( { apiOrigin: _.get(state, [reduxStateFields.origins, 'api'], ''), userId: _.get(state, [reduxStateFields.auth, 'userInfo.id']), pathname: _.get(ownProps.location, 'pathname', ''), host: _.get(ownProps.location, 'host', ''), }, uiManager.getLayoutObj(state, ownProps.location) ) } export default connect(mapStateToProps)(AppShell)
Libraries/Image/ImageBackground.js
mironiasty/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 ImageBackground * @flow * @format */ 'use strict'; const Image = require('Image'); const React = require('React'); const StyleSheet = require('StyleSheet'); const View = require('View'); /** * Very simple drop-in replacement for <Image> which supports nesting views. * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, ImageBackground, Text } from 'react-native'; * * class DisplayAnImageBackground extends Component { * render() { * return ( * <ImageBackground * style={{width: 50, height: 50}} * source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} * > * <Text>React</Text> * </ImageBackground> * ); * } * } * * // App registration and rendering * AppRegistry.registerComponent('DisplayAnImageBackground', () => DisplayAnImageBackground); * ``` */ class ImageBackground extends React.Component { render() { const {children, style, imageStyle, imageRef, ...props} = this.props; return ( <View style={style}> <Image {...props} style={[ StyleSheet.absoluteFill, { // Temporary Workaround: // Current (imperfect yet) implementation of <Image> overwrites width and height styles // (which is not quite correct), and these styles conflict with explicitly set styles // of <ImageBackground> and with our internal layout model here. // So, we have to proxy/reapply these styles explicitly for actual <Image> component. // This workaround should be removed after implementing proper support of // intrinsic content size of the <Image>. width: style.width, height: style.height, }, imageStyle, ]} ref={imageRef} /> {children} </View> ); } } module.exports = ImageBackground;
webapp/src/app/App.js
cpollet/itinerants
import React from 'react'; import MenuContainer from './menu/containers/MenuContainer'; import InfoStaleState from './availability/containers/InfoStaleState'; import AlertSyncFail from './availability/containers/AlertSyncFail'; import styles from './App.less'; import Alert from '../widgets/Alert'; class App extends React.Component { render() { return ( <div className={styles.component}> <h1>Itinérants</h1> {this.props.fetchError && <Alert type="error">Une erreur est survenue, réessaie plus tard</Alert>} <div className={styles.container}> <div className={styles.menuContainer}> <MenuContainer location={this.props.location}/> </div> <div className={styles.contentContainer}> <InfoStaleState text="Sauvegarde en cours..."/> <AlertSyncFail title="Erreur" text="impossible de sauvegarder"/> {this.props.children} </div> </div> </div> ); } } App.propTypes = { children: React.PropTypes.node, location: React.PropTypes.object, fetchError: React.PropTypes.bool.isRequired, }; App.defaultProps = { fetchError: false, }; export default App;
src/Link/Link.js
ctco/rosemary-ui
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; const PROPERTY_TYPES = { value: PropTypes.any, testId: PropTypes.any }; class Link extends React.Component { render() { const className = classNames('ros-link', this.props.className); const props = { ...this.props, className }; return ( <a data-test-id={this.props.testId} {...props}> {this.props.value || this.props.children} </a> ); } } Link.propTypes = PROPERTY_TYPES; export default Link;
example/examples/PanController.js
zigbang/react-native-maps
/* eslint-disable */ import React from 'react'; import PropTypes from 'prop-types'; import { View, Animated, PanResponder, } from 'react-native'; const ModePropType = PropTypes.oneOf(['decay', 'snap', 'spring-origin']); const OvershootPropType = PropTypes.oneOf(['spring', 'clamp']); const AnimatedPropType = PropTypes.any; class PanController extends React.Component{ static propTypes = { // Component Config lockDirection: PropTypes.bool, horizontal: PropTypes.bool, vertical: PropTypes.bool, overshootX: OvershootPropType, overshootY: OvershootPropType, xBounds: PropTypes.arrayOf(PropTypes.number), yBounds: PropTypes.arrayOf(PropTypes.number), xMode: ModePropType, yMode: ModePropType, snapSpacingX: PropTypes.number, // TODO: also allow an array of values? snapSpacingY: PropTypes.number, // Animated Values panX: AnimatedPropType, panY: AnimatedPropType, // Animation Config overshootSpringConfig: PropTypes.any, momentumDecayConfig: PropTypes.any, springOriginConfig: PropTypes.any, directionLockDistance: PropTypes.number, overshootReductionFactor: PropTypes.number, // Events onOvershoot: PropTypes.func, onDirectionChange: PropTypes.func, onReleaseX: PropTypes.func, onReleaseY: PropTypes.func, onRelease: PropTypes.func, //...PanResponderPropTypes, } // getInitialState() { // //TODO: // // it's possible we want to move some props over to state. // // For example, xBounds/yBounds might need to be // // calculated/updated automatically // // // // This could also be done with a higher-order component // // that just massages props passed in... // return { // // }; // }, _responder = null _listener = null _direction = null constructor(props) { super(props) this.deceleration = 0.997; if (props.momentumDecayConfig && this.props.momentumDecayConfig.deceleration) { this.deceleration = this.props.momentumDecayConfig.deceleration; } } componentWillMount() { this._responder = PanResponder.create({ onStartShouldSetPanResponder: this.props.onStartShouldSetPanResponder, onMoveShouldSetPanResponder: this.props.onMoveShouldSetPanResponder, onPanResponderGrant: (...args) => { if (this.props.onPanResponderGrant) { this.props.onPanResponderGrant(...args); } let { panX, panY, horizontal, vertical, xMode, yMode } = this.props; this.handleResponderGrant(panX, xMode); this.handleResponderGrant(panY, yMode); this._direction = horizontal && !vertical ? 'x' : (vertical && !horizontal ? 'y' : null); }, onPanResponderMove: (_, { dx, dy, x0, y0 }) => { let { panX, panY, xBounds, yBounds, overshootX, overshootY, horizontal, vertical, lockDirection, directionLockDistance, } = this.props; if (!this._direction) { const dx2 = dx * dx; const dy2 = dy * dy; if (dx2 + dy2 > directionLockDistance) { this._direction = dx2 > dy2 ? 'x' : 'y'; if (this.props.onDirectionChange) { this.props.onDirectionChange(this._direction, { dx, dy, x0, y0 }); } } } const dir = this._direction; if (this.props.onPanResponderMove) { this.props.onPanResponderMove(_, { dx, dy, x0, y0 }); } if (horizontal && (!lockDirection || dir === 'x')) { let [xMin, xMax] = xBounds; this.handleResponderMove(panX, dx, xMin, xMax, overshootX); } if (vertical && (!lockDirection || dir === 'y')) { let [yMin, yMax] = yBounds; this.handleResponderMove(panY, dy, yMin, yMax, overshootY); } }, onPanResponderRelease: (_, { vx, vy, dx, dy }) => { let { panX, panY, xBounds, yBounds, overshootX, overshootY, horizontal, vertical, lockDirection, xMode, yMode, snapSpacingX, snapSpacingY, } = this.props; let cancel = false; const dir = this._direction; if (this.props.onRelease) { cancel = false === this.props.onRelease({ vx, vy, dx, dy }); } if (!cancel && horizontal && (!lockDirection || dir === 'x')) { let [xMin, xMax] = xBounds; if (this.props.onReleaseX) { cancel = false === this.props.onReleaseX({ vx, vy, dx, dy }); } !cancel && this.handleResponderRelease(panX, xMin, xMax, vx, overshootX, xMode, snapSpacingX); } if (!cancel && vertical && (!lockDirection || dir === 'y')) { let [yMin, yMax] = yBounds; if (this.props.onReleaseY) { cancel = false === this.props.onReleaseY({ vx, vy, dx, dy }); } !cancel && this.handleResponderRelease(panY, yMin, yMax, vy, overshootY, yMode, snapSpacingY); } this._direction = horizontal && !vertical ? 'x' : (vertical && !horizontal ? 'y' : null); }, }); } handleResponderMove(anim, delta, min, max, overshoot) { let val = anim._offset + delta; if (val > max) { switch (overshoot) { case 'spring': val = max + (val - max) / this.props.overshootReductionFactor; break; case 'clamp': val = max; break; } } if (val < min) { switch (overshoot) { case 'spring': val = min - (min - val) / this.props.overshootReductionFactor; break; case 'clamp': val = min; break; } } val = val - anim._offset; anim.setValue(val); } handleResponderRelease(anim, min, max, velocity, overshoot, mode, snapSpacing) { anim.flattenOffset(); if (anim._value < min) { if (this.props.onOvershoot) { this.props.onOvershoot(); // TODO: what args should we pass to this } switch (overshoot) { case 'spring': Animated.spring(anim, { ...this.props.overshootSpringConfig, toValue: min, velocity, }).start(); break; case 'clamp': anim.setValue(min); break; } } else if (anim._value > max) { if (this.props.onOvershoot) { this.props.onOvershoot(); // TODO: what args should we pass to this } switch (overshoot) { case 'spring': Animated.spring(anim, { ...this.props.overshootSpringConfig, toValue: max, velocity, }).start(); break; case 'clamp': anim.setValue(min); break; } } else { switch (mode) { case 'snap': this.handleSnappedScroll(anim, min, max, velocity, snapSpacing, overshoot); break; case 'decay': this.handleMomentumScroll(anim, min, max, velocity, overshoot); break; case 'spring-origin': Animated.spring(anim, { ...this.props.springOriginConfig, toValue: 0, velocity, }).start(); break; } } } handleResponderGrant(anim, mode) { switch (mode) { case 'spring-origin': anim.setValue(0); break; case 'snap': case 'decay': anim.setOffset(anim._value + anim._offset); anim.setValue(0); break; } } handleMomentumScroll(anim, min, max, velocity, overshoot) { Animated.decay(anim, { ...this.props.momentumDecayConfig, velocity, }).start(() => { anim.removeListener(this._listener); }); this._listener = anim.addListener(({ value }) => { if (value < min) { anim.removeListener(this._listener); if (this.props.onOvershoot) { this.props.onOvershoot(); // TODO: what args should we pass to this } switch (overshoot) { case 'spring': Animated.spring(anim, { ...this.props.overshootSpringConfig, toValue: min, velocity, }).start(); break; case 'clamp': anim.setValue(min); break; } } else if (value > max) { anim.removeListener(this._listener); if (this.props.onOvershoot) { this.props.onOvershoot(); // TODO: what args should we pass to this } switch (overshoot) { case 'spring': Animated.spring(anim, { ...this.props.overshootSpringConfig, toValue: max, velocity, }).start(); break; case 'clamp': anim.setValue(min); break; } } }); } handleSnappedScroll(anim, min, max, velocity, spacing) { let endX = this.momentumCenter(anim._value, velocity, spacing); endX = Math.max(endX, min); endX = Math.min(endX, max); const bounds = [endX - spacing / 2, endX + spacing / 2]; const endV = this.velocityAtBounds(anim._value, velocity, bounds); this._listener = anim.addListener(({ value }) => { if (value > bounds[0] && value < bounds[1]) { Animated.spring(anim, { toValue: endX, velocity: endV, }).start(); } }); Animated.decay(anim, { ...this.props.momentumDecayConfig, velocity, }).start(() => { anim.removeListener(this._listener); }); } closestCenter(x, spacing) { const plus = (x % spacing) < spacing / 2 ? 0 : spacing; return Math.round(x / spacing) * spacing + plus; } momentumCenter(x0, vx, spacing) { let t = 0; let x1 = x0; let x = x1; while (true) { t += 16; x = x0 + (vx / (1 - this.deceleration)) * (1 - Math.exp(-(1 - this.deceleration) * t)); if (Math.abs(x - x1) < 0.1) { x1 = x; break; } x1 = x; } return this.closestCenter(x1, spacing); } velocityAtBounds(x0, vx, bounds) { let t = 0; let x1 = x0; let x = x1; let vf; while (true) { t += 16; x = x0 + (vx / (1 - this.deceleration)) * (1 - Math.exp(-(1 - this.deceleration) * t)); vf = (x - x1) / 16; if (x > bounds[0] && x < bounds[1]) { break; } if (Math.abs(vf) < 0.1) { break; } x1 = x; } return vf; } // componentDidMount() { // //TODO: we may need to measure the children width/height here? // }, // // componentWillUnmount() { // // }, // // componentDidUnmount() { // // }, render() { return <View {...this.props} {...this._responder.panHandlers} />; } }; export default PanController;
admin/client/components/PopoutPane.js
kumo/keystone
import blacklist from 'blacklist'; import classnames from 'classnames'; import React from 'react'; var PopoutPane = React.createClass({ displayName: 'PopoutPane', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, onLayout: React.PropTypes.func }, componentDidMount () { this.props.onLayout && this.props.onLayout(this.getDOMNode().offsetHeight); }, render () { let className = classnames('Popout__pane', this.props.className); let props = blacklist(this.props, 'className', 'onLayout'); return <div className={className} {...props} />; } }); module.exports = PopoutPane;
src/components/Dashboard/Dashboard.js
wundery/wundery-ui-react
import React from 'react'; import classnames from 'classnames'; function Dashboard({ children }) { return ( <div className={classnames('ui-dashboard')}> <div className={classnames('ui-dashboard-items')}> {children} </div> </div> ); } Dashboard.propTypes = { children: React.PropTypes.node, }; Dashboard.defaultProps = { }; export default Dashboard;
src/components/Radial.react.js
agup006/kitematic
import React from 'react'; import classNames from 'classnames'; var Radial = React.createClass({ render: function () { var percentage; if ((this.props.progress !== null && this.props.progress !== undefined) && !this.props.spin && !this.props.error) { percentage = ( <div className="percentage"></div> ); } else { percentage = <div></div>; } var classes = classNames({ 'radial-progress': true, 'radial-spinner': this.props.spin, 'radial-negative': this.props.error, 'radial-thick': this.props.thick || false, 'radial-gray': this.props.gray || false, 'radial-transparent': this.props.transparent || false }); return ( <div className={classes} data-progress={this.props.progress}> <div className="circle"> <div className="mask full"> <div className="fill"></div> </div> <div className="mask half"> <div className="fill"></div> <div className="fill fix"></div> </div> <div className="shadow"></div> </div> <div className="inset"> {percentage} </div> </div> ); } }); module.exports = Radial;
react-flux-mui/js/material-ui/src/svg-icons/maps/local-grocery-store.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalGroceryStore = (props) => ( <SvgIcon {...props}> <path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); MapsLocalGroceryStore = pure(MapsLocalGroceryStore); MapsLocalGroceryStore.displayName = 'MapsLocalGroceryStore'; MapsLocalGroceryStore.muiName = 'SvgIcon'; export default MapsLocalGroceryStore;
docs/app/Examples/modules/Rating/Types/RatingExampleClearable.js
shengnian/shengnian-ui-react
import React from 'react' import { Rating } from 'shengnian-ui-react' const RatingExampleClearable = () => ( <Rating maxRating={5} clearable /> ) export default RatingExampleClearable
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
ConnorFieldUser/ConnorFieldUser.github.io
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
classic/src/scenes/wbfa/generated/FARServer.free.js
wavebox/waveboxapp
import React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faServer } from '@fortawesome/free-solid-svg-icons/faServer' export default class FARServer extends React.Component { render () { return (<FontAwesomeIcon {...this.props} icon={faServer} />) } }
src/components/navlink.js
netlify/staticgen
import React from 'react' import { Link } from 'gatsby' import styled from '@emotion/styled' const NavLink = styled(Link)` color: #fff; text-decoration: none; padding: 10px; display: block; text-align: center; &:active, &:focus, &:hover { color: #00c7b7; } ` const NavAnchor = NavLink.withComponent('a') export { NavLink as default, NavAnchor }
src/components/Header/Header.js
deboraduarte/starter
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; // eslint-disable-line no-unused-vars import styles from './Header.less'; // eslint-disable-line no-unused-vars import withStyles from '../../decorators/withStyles'; // eslint-disable-line no-unused-vars import Link from '../../utils/Link'; import Navigation from '../Navigation'; @withStyles(styles) class Header { render() { return ( <div className="Header"> <div className="Header-container"> <a className="Header-brand" href="/" onClick={Link.handleClick}> <img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" /> <span className="Header-brandTxt">Your Company</span> </a> <Navigation className="Header-nav" /> <div className="Header-banner"> <h1 className="Header-bannerTitle">React</h1> <p className="Header-bannerDesc">Complex web apps made easy</p> </div> </div> </div> ); } } export default Header;
src/app.js
fima23/car-rent-react-flux-graphql
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import Cars from './components/cars'; ReactDOM.render( <Cars></Cars>, document.getElementById('app') );
server/sonar-web/src/main/js/apps/projects/components/AllProjects.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import ProjectsListContainer from './ProjectsListContainer'; import ProjectsListFooterContainer from './ProjectsListFooterContainer'; import PageSidebar from './PageSidebar'; import { parseUrlQuery } from '../store/utils'; export default class AllProjects extends React.Component { static propTypes = { isFavorite: React.PropTypes.bool.isRequired, fetchProjects: React.PropTypes.func.isRequired, organization: React.PropTypes.object }; state = { query: {} }; componentDidMount () { this.handleQueryChange(); } componentDidUpdate (prevProps) { if (prevProps.location.query !== this.props.location.query) { this.handleQueryChange(); } } handleQueryChange () { const query = parseUrlQuery(this.props.location.query); this.setState({ query }); this.props.fetchProjects(query, this.props.isFavorite, this.props.organization); } render () { const isFiltered = Object.keys(this.state.query).some(key => this.state.query[key] != null); return ( <div className="page-with-sidebar page-with-left-sidebar projects-page"> <aside className="page-sidebar-fixed projects-sidebar"> <PageSidebar query={this.state.query} isFavorite={this.props.isFavorite} organization={this.props.organization}/> </aside> <div className="page-main"> <ProjectsListContainer isFavorite={this.props.isFavorite} isFiltered={isFiltered} organization={this.props.organization}/> <ProjectsListFooterContainer query={this.state.query} isFavorite={this.props.isFavorite} organization={this.props.organization}/> </div> </div> ); } }
server/priv/js/components/BenchSummary.react.js
bks7/mzbench
import React from 'react'; import MZBenchRouter from '../utils/MZBenchRouter'; import moment from 'moment'; import 'moment-duration-format'; class BenchSummary extends React.Component { _labelCssClass(status) { switch (status) { case "complete": return "label-success"; case "failed": return "label-danger"; case "stopped": return "label-default"; } return "label-info"; } render() { let bench = this.props.bench; let labelClass = this._labelCssClass(bench.status); return ( <div className="fluid-container"> <div className="row bench-details"> <div className="col-xs-6"> <table className="table"> <tbody> <tr> <th scope="row" className="col-xs-2">Scenario</th> <td>#{bench.id} {bench.scenario}</td> </tr> <tr> <th scope="row">Duration</th> <td>{moment.duration(this.props.duration).format("h [hrs], m [min], s [sec]")}</td> </tr> <tr> <th scope="row">Date</th> <td>{moment(bench.start_time).format("lll")}</td> </tr> <tr> <th scope="row">Status</th> <td><span className={`label ${labelClass}`}>{bench.status}</span></td> </tr> </tbody> </table> </div> <div className="bench-actions col-xs-offset-2 col-xs-4"> <div className="text-right"> <a type="button" ref="stop" className="btn btn-sm btn-danger" href={MZBenchRouter.buildLink("/stop", {id: this.props.bench.id})} disabled={!this.props.bench.isRunning()} onClick={this._onClick}> <span className="glyphicon glyphicon-minus-sign"></span> Stop </a> </div> <div className="text-right"> <a type="button" ref="restart" className="btn btn-sm btn-primary" href={MZBenchRouter.buildLink("/restart", {id: this.props.bench.id})} disabled={this.props.bench.isRunning()} onClick={this._onClick}> <span className="glyphicon glyphicon-refresh"></span> Restart </a> </div> </div> </div> </div> ); } _onClick(event) { event.preventDefault(); let anchor = $(event.target).closest('a'); if (!anchor.attr('disabled')) { $.ajax({url: anchor.attr('href')}); } } }; BenchSummary.propTypes = { bench: React.PropTypes.object.isRequired }; export default BenchSummary;
client/src/app/components/employer/Contact.js
lefnire/jobs
import React from 'react'; import { FlatButton, } from 'material-ui'; import _ from 'lodash'; import {_fetch, _ga, IS_SMALL} from '../../helpers'; import Formsy from 'formsy-react' import { FormsyText } from 'formsy-material-ui/lib'; import { Modal } from 'react-bootstrap'; export default class Contact extends React.Component { constructor(props) { super(props); this.state = { open: false, canSubmit: false }; } render() { return ( <Modal show={this.state.open} onHide={this.close} bsSize="large" animation={!IS_SMALL} > <Modal.Header> <Modal.Title>Contact</Modal.Title> </Modal.Header> <Modal.Body> <Formsy.Form ref="form" onValid={() => this.setState({canSubmit: true})} onInvalid={() => this.setState({canSubmit: false})} onValidSubmit={this.submitForm}> <FormsyText hintText="Subject" name="subject" required validationError="required" fullWidth={true}/> <FormsyText hintText="Message" name="body" required validationError="required" fullWidth={true} multiLine={true} /> </Formsy.Form> </Modal.Body> <Modal.Footer> <FlatButton label="Cancel" secondary={true} onTouchTap={this.close}/>, <FlatButton label="Submit" primary={true} onTouchTap={() => this.refs.form.submit()}/>, </Modal.Footer> </Modal> ); } open = () => { _ga.pageview('modal:contact-prospect'); this.setState({open: true}); }; close = () => { _ga.pageview(); this.setState({open: false}); }; submitForm = (body) => { _fetch(`messages/contact/${this.props.prospect.id}`, {method:"POST", body}).then(() => { global.jobpig.alerts.alert('Message sent.'); this.close(); }).catch(global.jobpig.alerts.alert); } }
frontend/components/loading.js
yograterol/viperid
import React from 'react'; export default () => <div> <h3>Loading...</h3> <style jsx>{` div { align-items: center; display: flex; height: 50vh; justify-content: center; } `}</style> </div>;
src/components/content-editable.js
marcusdarmstrong/cloth-io
// @flow import React from 'react'; import ReactDOM from 'react-dom'; type Props = { html?: string, onChange?: (event: { target: { value: string } }) => void, autoFocus?: boolean, }; export default class ContentEditable extends React.Component { componentDidMount() { if (this.props.autoFocus && (typeof window.orientation) === 'undefined') { // We use orientation as a proxy for devices with an on-screen keyboard. // They don't respond well to auto-focusing, so disabling it for now. ReactDOM.findDOMNode(this).focus(); } } shouldComponentUpdate(nextProps: Props) { return nextProps.html !== ReactDOM.findDOMNode(this).innerHTML; } componentDidUpdate() { if (this.props.html !== ReactDOM.findDOMNode(this).innerHTML) { ReactDOM.findDOMNode(this).innerHTML = this.props.html; } } props: Props; lastHtml: string; emitChange: () => void = () => { const html = ReactDOM.findDOMNode(this).innerHTML; if (this.props.onChange && html !== this.lastHtml) { this.props.onChange({ target: { value: html, }, }); } this.lastHtml = html; }; render() { return ( <div id="contenteditable" className="textarea" onInput={this.emitChange} onBlur={this.emitChange} contentEditable dangerouslySetInnerHTML={{ __html: this.props.html }} > </div> ); } }
src/parser/druid/feral/modules/azeritetraits/UntamedFerocity.js
sMteX/WoWAnalyzer
import React from 'react'; import { formatNumber } from 'common/format'; import SPELLS from 'common/SPELLS'; import { calculateAzeriteEffects } from 'common/stats'; import HIT_TYPES from 'game/HIT_TYPES'; import Analyzer from 'parser/core/Analyzer'; import Enemies from 'parser/shared/modules/Enemies'; import StatTracker from 'parser/shared/modules/StatTracker'; import SpellUsable from 'parser/shared/modules/SpellUsable'; import calculateBonusAzeriteDamage from 'parser/core/calculateBonusAzeriteDamage'; import ItemStatistic from 'interface/statistics/ItemStatistic'; import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText'; import ItemDamageDone from 'interface/others/ItemDamageDone'; import { calcShredBonus, calcSwipeBonus, isAffectedByWildFleshrending } from '../azeritetraits/WildFleshrending'; import Abilities from '../Abilities.js'; const debug = false; export const AFFECTED_SPELLS = [ SPELLS.RAKE.id, SPELLS.SHRED.id, SPELLS.MOONFIRE_FERAL.id, SPELLS.THRASH_FERAL.id, SPELLS.SWIPE_CAT.id, SPELLS.BRUTAL_SLASH_TALENT.id, ]; const HIT_TYPES_TO_IGNORE = [ HIT_TYPES.MISS, HIT_TYPES.DODGE, HIT_TYPES.PARRY, ]; const COOLDOWN_REDUCTION_BERSERK = 300; const COOLDOWN_REDUCTION_INCARNATION = 200; export function calcBonus(combatant) { if (!combatant.hasTrait(SPELLS.UNTAMED_FEROCITY.id)) { return 0; } return combatant.traitsBySpellId[SPELLS.UNTAMED_FEROCITY.id] .reduce((sum, rank) => sum + calculateAzeriteEffects(SPELLS.UNTAMED_FEROCITY.id, rank)[0], 0); } /** * Untamed Ferocity * Combo-point generating abilities deal X additional instant damage and reduce the cooldown of * Berserk by 0.3 sec [or Incarnation: King of the Jungle by 0.2 sec] * * Test Log: /report/ABH7D8W1Qaqv96mt/2-Mythic+Taloc+-+Kill+(4:12)/Enicat/statistics */ class UntamedFerocity extends Analyzer { static dependencies = { abilities: Abilities, enemies: Enemies, statTracker: StatTracker, spellUsable: SpellUsable, }; hasWildFleshrending = false; shredBonus = 0; swipeBonus = 0; untamedBonus = 0; untamedDamage = 0; hasIncarnation = false; cooldownId = 0; cooldownReduction = 0; // Only cast events (not damage events) give attack power values, so have to temporarily store it. As we're dealing with instant damage abilites there's no problem with that. attackPower = 0; constructor(...args) { super(...args); if(!this.selectedCombatant.hasTrait(SPELLS.UNTAMED_FEROCITY.id)) { this.active = false; return; } this.untamedBonus = calcBonus(this.selectedCombatant); this.hasWildFleshrending = this.selectedCombatant.hasTrait(SPELLS.WILD_FLESHRENDING.id); if (this.hasWildFleshrending) { this.shredBonus = calcShredBonus(this.selectedCombatant); this.swipeBonus = calcSwipeBonus(this.selectedCombatant); } debug && this.log(`untamedBonus: ${this.untamedBonus}, shredBonus: ${this.shredBonus}, swipeBonus: ${this.swipeBonus}`); this.hasIncarnation = this.selectedCombatant.hasTalent(SPELLS.INCARNATION_KING_OF_THE_JUNGLE_TALENT.id); this.cooldownId = this.hasIncarnation ? SPELLS.INCARNATION_KING_OF_THE_JUNGLE_TALENT.id : SPELLS.BERSERK.id; this.cooldownReductionPerHit = this.hasIncarnation ? COOLDOWN_REDUCTION_INCARNATION : COOLDOWN_REDUCTION_BERSERK; } on_byPlayer_cast(event) { if (!AFFECTED_SPELLS.includes(event.ability.guid)) { return; } this.attackPower = event.attackPower; } on_byPlayer_damage(event) { if (!AFFECTED_SPELLS.includes(event.ability.guid) || event.tick || HIT_TYPES_TO_IGNORE.includes(event.hitType)) { // only interested in direct damage from whitelisted spells which hit the target return; } if (this.hasWildFleshrending && isAffectedByWildFleshrending(event, this.owner, this.enemies)) { // if the ability was given bonus damage from both Wild Fleshrending and Untamed Ferocity need to account for that to accurately attribute damage to each. const fleshrendingBonus = (event.ability.guid === SPELLS.SHRED.id) ? this.shredBonus : this.swipeBonus; const coefficient = this.abilities.getAbility(event.ability.guid).primaryCoefficient; const [traitDamageContribution] = calculateBonusAzeriteDamage(event, [this.untamedBonus, fleshrendingBonus], this.attackPower, coefficient); this.untamedDamage += traitDamageContribution; debug && this.log(`Affected ability including Wild Fleshrending, damage from Untamed Ferocity: ${traitDamageContribution}`); } else { const coefficient = this.abilities.getAbility(event.ability.guid).primaryCoefficient; const [traitDamageContribution] = calculateBonusAzeriteDamage(event, [this.untamedBonus], this.attackPower, coefficient); this.untamedDamage += traitDamageContribution; debug && this.log(`Affected ability damage from Untamed Ferocity: ${traitDamageContribution}`); } if (this.spellUsable.isOnCooldown(this.cooldownId)) { this.cooldownReduction += this.cooldownReductionPerHit; this.spellUsable.reduceCooldown(this.cooldownId, this.cooldownReductionPerHit); } } statistic() { const cooldownName = this.hasIncarnation ? 'Incarnation' : 'Berserk'; const cooldownDuration = this.abilities.getExpectedCooldownDuration(this.cooldownId); const basePossibleCasts = Math.floor(this.owner.fightDuration / cooldownDuration) + 1; const improvedPossibleCasts = Math.floor((this.owner.fightDuration + this.cooldownReduction) / cooldownDuration) + 1; const extraCastsPossible = improvedPossibleCasts - basePossibleCasts; const extraCastsComment = (improvedPossibleCasts === basePossibleCasts) ? `This wasn't enough to allow any extra casts during the fight, but may have given you more freedom in timing those casts.` : <>This gave you the opportunity over the duration of the fight to use {cooldownName} <b>{extraCastsPossible}</b> extra time{extraCastsPossible === 1 ? '' : 's'}.</>; return ( <ItemStatistic size="flexible" tooltip={( <> Increased the damage of your combo point generators by a total of <b>{formatNumber(this.untamedDamage)}</b><br /> The cooldown on your {cooldownName} was reduced by a total of <b>{(this.cooldownReduction / 1000).toFixed(1)}</b> seconds.<br /> {extraCastsComment} </> )} > <BoringSpellValueText spell={SPELLS.UNTAMED_FEROCITY}> <ItemDamageDone amount={this.untamedDamage} /><br /> {(this.cooldownReduction / 1000).toFixed(1)}s <small>cooldown reduction</small> </BoringSpellValueText> </ItemStatistic> ); } } export default UntamedFerocity;
js/components/button/disabled.js
ChiragHindocha/stay_fit
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { View } from 'react-native'; import { Container, Header, Title, Content, Button, Icon, Left, Right, Body, Text, H3 } from 'native-base'; import { Actions } from 'react-native-router-flux'; import { actions } from 'react-native-navigation-redux-helpers'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; const { popRoute, } = actions; class Disabled extends Component { // eslint-disable-line static propTypes = { openDrawer: React.PropTypes.func, popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title>Disabled</Title> </Body> <Right /> </Header> <Content> <View style={{ paddingHorizontal: 20, paddingTop: 20 }}> <Button disabled style={styles.mb15}><Text>Solid</Text></Button> <Button bordered disabled style={styles.mb15}><Text>Bordered</Text></Button> <Button rounded disabled style={styles.mb15}><Text>rounded</Text></Button> <Button large disabled style={styles.mb15}><Text>Custom</Text></Button> <Button disabled iconRight style={styles.mb15}> <Text>Icon Button</Text> <Icon name="home" /> </Button> <Button block disabled style={styles.mb15}><Text>Block</Text></Button> </View> <Button full disabled style={styles.mb15}><Text>Block</Text></Button> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(Disabled);
projeto/fatec/src/Eventos.js
frbaroni/curso_react
import React, { Component } from 'react'; class Eventos extends Component { state = { em_cima: false } quandoMouseEntrar = (evento) => { this.setState({ em_cima: true }) } quandoMouseSair = (evento) => { this.setState({ em_cima: false }) } render() { const quadradoEstilo = { backgroundColor: (this.state.em_cima ? 'green' : 'red'), width: '40px', height: '40px', } return ( <div> <p>O mouse está {this.state.em_cima ? 'em cima do quadrado' : 'fora do quadrado'}</p> <div style={quadradoEstilo} onMouseOver={this.quandoMouseEntrar} onMouseOut={this.quandoMouseSair} ></div> </div> ) } } export default Eventos;
client/src/components/auth/Signin.js
victorlcm/full-stack-react
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { reduxForm, Field } from 'redux-form'; import * as actions from '../../actions'; class Signin extends Component { constructor () { super(); this.handleFormSubmit = this.handleFormSubmit.bind(this) } handleFormSubmit({ email, password }) { // Need to do something to log user in this.props.signinUser({ email, password }, () => { this.props.history.push('/feature') }); } renderAlert() { if (this.props.errorMessage) { return ( <div className="alert alert-danger"> <strong>Oops!</strong> {this.props.errorMessage} </div> ); } } render() { const { handleSubmit, pristine, submitting } = this.props; return ( <form onSubmit={handleSubmit(this.handleFormSubmit)}> <div> <label>Email</label> <div> <Field name="email" component="input" type="email" placeholder="Email" /> </div> </div> <div> <label>Password</label> <div> <Field name="password" component="input" type="password" placeholder="Password" /> </div> </div> {this.renderAlert()} <button className="btn btn-primary" type="submit" label="Submit" disabled={pristine || submitting}> Sign in! </button> </form> ); } } function mapStateToProps(state) { return { errorMessage: state.auth.error }; } Signin = reduxForm({ form: 'signin' } )(Signin); Signin = connect(mapStateToProps, actions)(Signin); export default Signin;
src/svg-icons/device/bluetooth-connected.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBluetoothConnected = (props) => ( <SvgIcon {...props}> <path d="M7 12l-2-2-2 2 2 2 2-2zm10.71-4.29L12 2h-1v7.59L6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 5.83l1.88 1.88L13 9.59V5.83zm1.88 10.46L13 18.17v-3.76l1.88 1.88zM19 10l-2 2 2 2 2-2-2-2z"/> </SvgIcon> ); DeviceBluetoothConnected = pure(DeviceBluetoothConnected); DeviceBluetoothConnected.displayName = 'DeviceBluetoothConnected'; export default DeviceBluetoothConnected;
docs/src/app/components/pages/components/Tabs/ExampleSwipeable.js
rhaedes/material-ui
import React from 'react'; import {Tabs, Tab} from 'material-ui/Tabs'; // From https://github.com/oliviertassinari/react-swipeable-views import SwipeableViews from 'react-swipeable-views'; const styles = { headline: { fontSize: 24, paddingTop: 16, marginBottom: 12, fontWeight: 400, }, slide: { padding: 10, }, }; export default class TabsExampleSwipeable extends React.Component { constructor(props) { super(props); this.state = { slideIndex: 0, }; } handleChange = (value) => { this.setState({ slideIndex: value, }); }; render() { return ( <div> <Tabs onChange={this.handleChange} value={this.state.slideIndex} > <Tab label="Tab One" value={0} /> <Tab label="Tab Two" value={1} /> <Tab label="Tab Three" value={2} /> </Tabs> <SwipeableViews index={this.state.slideIndex} onChangeIndex={this.handleChange} > <div> <h2 style={styles.headline}>Tabs with slide effect</h2> Swipe to see the next slide.<br /> </div> <div style={styles.slide}> slide n°2 </div> <div style={styles.slide}> slide n°3 </div> </SwipeableViews> </div> ); } }
src/svg-icons/notification/phone-bluetooth-speaker.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationPhoneBluetoothSpeaker = (props) => ( <SvgIcon {...props}> <path d="M14.71 9.5L17 7.21V11h.5l2.85-2.85L18.21 6l2.15-2.15L17.5 1H17v3.79L14.71 2.5l-.71.71L16.79 6 14 8.79l.71.71zM18 2.91l.94.94-.94.94V2.91zm0 4.3l.94.94-.94.94V7.21zm2 8.29c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1z"/> </SvgIcon> ); NotificationPhoneBluetoothSpeaker = pure(NotificationPhoneBluetoothSpeaker); NotificationPhoneBluetoothSpeaker.displayName = 'NotificationPhoneBluetoothSpeaker'; export default NotificationPhoneBluetoothSpeaker;
app/javascript/mastodon/features/mutes/index.js
rainyday/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import AccountContainer from '../../containers/account_container'; import { fetchMutes, expandMutes } from '../../actions/mutes'; import ScrollableList from '../../components/scrollable_list'; const messages = defineMessages({ heading: { id: 'column.mutes', defaultMessage: 'Muted users' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'mutes', 'items']), hasMore: !!state.getIn(['user_lists', 'mutes', 'next']), isLoading: state.getIn(['user_lists', 'mutes', 'isLoading'], true), }); export default @connect(mapStateToProps) @injectIntl class Mutes extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, hasMore: PropTypes.bool, isLoading: PropTypes.bool, accountIds: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchMutes()); } handleLoadMore = debounce(() => { this.props.dispatch(expandMutes()); }, 300, { leading: true }); render () { const { intl, shouldUpdateScroll, hasMore, accountIds, multiColumn, isLoading } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.mutes' defaultMessage="You haven't muted any users yet." />; return ( <Column bindToDocument={!multiColumn} icon='volume-off' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollableList scrollKey='mutes' onLoadMore={this.handleLoadMore} hasMore={hasMore} isLoading={isLoading} shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} bindToDocument={!multiColumn} > {accountIds.map(id => <AccountContainer key={id} id={id} />, )} </ScrollableList> </Column> ); } }
js-old/src/playground/playground.js
destenson/ethcore--parity
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import { observer } from 'mobx-react'; import React, { Component } from 'react'; import AccountCard from '~/ui/AccountCard/accountCard.example'; import CurrencySymbol from '~/ui/CurrencySymbol/currencySymbol.example'; import QrCode from '~/ui/QrCode/qrCode.example'; import SectionList from '~/ui/SectionList/sectionList.example'; import Portal from '~/ui/Portal/portal.example'; import PlaygroundStore from './store'; import styles from './playground.css'; PlaygroundStore.register(<AccountCard />); PlaygroundStore.register(<CurrencySymbol />); PlaygroundStore.register(<QrCode />); PlaygroundStore.register(<SectionList />); PlaygroundStore.register(<Portal />); @observer export default class Playground extends Component { state = { selectedIndex: 0 }; store = PlaygroundStore.get(); render () { return ( <div className={ styles.container }> <div className={ styles.title }> <span>Playground > </span> <select className={ styles.select } onChange={ this.handleChange } > { this.renderOptions() } </select> </div> <div className={ styles.examples }> { this.renderComponent() } </div> </div> ); } renderOptions () { const { components } = this.store; return components.map((element, index) => { const name = element.type.displayName || element.type.name; return ( <option key={ `${name}_${index}` } value={ index } > { name } </option> ); }); } renderComponent () { const { components } = this.store; const { selectedIndex } = this.state; return components[selectedIndex]; } handleChange = (event) => { const { value } = event.target; this.setState({ selectedIndex: value }); } }
src/app/utils/SlateEditor/Align.js
TimCliff/steemit.com
import React from 'react'; export default class Align extends React.Component { getAlignClass = () => { const { node } = this.props; switch (node.data.get('align')) { case 'text-right': return 'text-right'; case 'text-left': return 'text-left'; case 'text-center': return 'text-center'; case 'pull-right': return 'pull-right'; case 'pull-left': return 'pull-left'; } }; render = () => { const { node, attributes, children } = this.props; const className = this.getAlignClass(); return ( <div {...attributes} className={className}> {children} </div> ); }; }
src/server.js
pvijeh/sull-isom2
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; const server = global.server = express(); const port = process.env.PORT || 5000; server.set('port', port); // // Register Node.js middleware // ----------------------------------------------------------------------------- server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '' }; const css = []; const context = { onInsertCss: value => css.push(value), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(port, () => { /* eslint-disable no-console */ console.log(`The server is running at http://localhost:${port}/`); });
test/fixtures/webpack-message-formatting/src/AppNoDefault.js
GreenGremlin/create-react-app
import React, { Component } from 'react'; import myImport from './ExportNoDefault'; class App extends Component { render() { return <div className="App">{myImport}</div>; } } export default App;
js/src/views/RpcCalls/components/RpcDocs/RpcDocs.js
nipunn1313/parity
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { FormattedMessage } from 'react-intl'; import { sortBy } from 'lodash'; import List from 'material-ui/List/List'; import ListItem from 'material-ui/List/ListItem'; import AutoComplete from '../AutoComplete'; import { formatRpcMd } from '../../util/rpc-md'; import ScrollTopButton from '../ScrollTopButton'; import styles from './RpcDocs.css'; import Markdown from '../Markdown'; import rpcData from '../../data/rpc.json'; import RpcNav from '../RpcNav'; const rpcMethods = sortBy(rpcData.methods, 'name'); class RpcDocs extends Component { render () { return ( <div className='dapp-flex-content'> <main className='dapp-content'> <div className='dapp-container'> <div className='row'> <div className='col col-6'> <h1> <FormattedMessage id='status.rpcDocs.title' defaultMessage='RPC Docs' /> </h1> </div> <div className='col col-6'> <RpcNav /> </div> </div> </div> <div style={ { clear: 'both' } } /> <div className='dapp-container'> <div className='row'> <div className='col col-12'> <AutoComplete floatingLabelText={ <FormattedMessage id='status.rpcDocs.methodName' defaultMessage='Method name' /> } className={ styles.autocomplete } dataSource={ rpcMethods.map(m => m.name) } onNewRequest={ this.handleMethodChange } { ...this._test('autocomplete') } /> { this.renderData() } </div> </div> </div> <ScrollTopButton /> </main> </div> ); } renderData () { const methods = rpcMethods.map((m, idx) => { const setMethod = el => { this[`_method-${m.name}`] = el; }; return ( <ListItem key={ m.name } disabled ref={ setMethod } > <h3 className={ styles.headline }>{ m.name }</h3> <Markdown val={ m.desc } /> <p> <FormattedMessage id='status.rpcDocs.params' defaultMessage='Params {params}' vaules={ { params: !m.params.length ? ( <FormattedMessage id='status.rpcDocs.paramsNone' defaultMessage=' - none' /> ) : '' } } /> </p> { m.params.map((p, idx) => { return ( <Markdown key={ `${m.name}-${idx}` } val={ formatRpcMd(p) } /> ); }) } <p className={ styles.returnsTitle }> <FormattedMessage id='status.rpcDocs.returns' defaultMessage='Returns - ' /> </p> <Markdown className={ styles.returnsDesc } val={ formatRpcMd(m.returns) } /> { idx !== rpcMethods.length - 1 ? <hr /> : '' } </ListItem> ); }); return ( <List> { methods } </List> ); } handleMethodChange = name => { ReactDOM.findDOMNode(this[`_method-${name}`]).scrollIntoViewIfNeeded(); } } export default RpcDocs;
client/src/pages/payment/payments/transactions/index.js
csleary/nemp3
import { faBomb, faListOl } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import PropTypes from 'prop-types'; import React from 'react'; import Transaction from './transaction'; import nem from 'nem-sdk'; import styles from './transactions.module.css'; const Transactions = ({ error, transactions }) => { if (error) { return ( <div className={styles.root}> <div className="alert alert-danger text-center" role="alert"> <FontAwesomeIcon icon={faBomb} className="mr-2" /> We encountered an error processing your payment. {error} </div> </div> ); } if (transactions.length) { return ( <div className={styles.root}> <h5 className={styles.heading}> <FontAwesomeIcon icon={faListOl} className="yellow mr-3" /> {transactions.length} transaction{transactions.length > 1 ? 's' : null}: </h5> <div className={styles.grid}> <div className={styles.index}>#</div> <div>Payment Date</div> <div className={styles.amount}>Amount</div> {transactions.map(({ meta, transaction }, index) => ( <Transaction amount={(transaction.amount / 10 ** 6).toFixed(6)} date={nem.utils.format.nemDate(transaction.timeStamp)} index={String(index + 1)} key={meta.hash.data} meta={meta} /> ))} </div> <p>Note: Very recent transactions may not yet be visible on the explorer.</p> </div> ); } return null; }; Transactions.propTypes = { error: PropTypes.string, transactions: PropTypes.array }; export default Transactions;
modules/plugins/link/LinkButton.js
devrieda/arc-reactor
import React from 'react'; import MenuButton from '../../components/MenuButton'; import ToggleMarkup from '../../helpers/Manipulation/ToggleMarkup'; import EditorStore from '../../stores/EditorStore'; const LinkButton = React.createClass({ statics: { getName: () => "link", isVisible: () => true, }, propTypes: MenuButton.propTypes, getDefaultProps() { return { type: "a", text: "Link", icon: "fa-link", hasValue: true }; }, setValue(value) { const { content } = this.handlePress(value || ""); EditorStore.set({content: content}); }, handlePress(value) { value = value || ""; const guids = this.props.selection.guids(); const offsets = this.props.selection.offsets(); const position = this.props.selection.position(); if (value && !value.match(/^http/)) { value = "http://" + value; } const options = { type: this.props.type, value: value }; const result = this._toggleMarkup().execute(guids, offsets, options); return { content: result.content, position: position }; }, _toggleMarkup() { return new ToggleMarkup(this.props.content); }, render() { return ( <MenuButton {...this.props} onPress={this.handlePress} onSetValue={this.props.onSetValue} /> ); } }); export default LinkButton;
src/index.js
hellofresh/janus-dashboard
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { store } from './store/configuration' import Root from './modules/Root/Root' import './index.css' ReactDOM.render( <Provider store={store}> <Root /> </Provider>, document.getElementById('root'))
src/svg-icons/notification/live-tv.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationLiveTv = (props) => ( <SvgIcon {...props}> <path d="M21 6h-7.59l3.29-3.29L16 2l-4 4-4-4-.71.71L10.59 6H3c-1.1 0-2 .89-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.11-.9-2-2-2zm0 14H3V8h18v12zM9 10v8l7-4z"/> </SvgIcon> ); NotificationLiveTv = pure(NotificationLiveTv); NotificationLiveTv.displayName = 'NotificationLiveTv'; NotificationLiveTv.muiName = 'SvgIcon'; export default NotificationLiveTv;
client/verification-portal/components/services-group.js
HelpAssistHer/help-assist-her
import React from 'react' import injectSheet from 'react-jss' import Spacer from '../../components/spacer' import ServiceFields from './service-fields' const ServicesGroup = ({ classes, heading, listOfServices }) => { return ( <div className={classes.group}> <div className={classes.heading}>{heading}</div> <Spacer height="20px" /> <ServiceFields listOfServices={listOfServices} /> </div> ) } const styles = { group: { padding: '0 20px 40px 0', }, heading: { color: '#000000', 'font-size': '18px', 'font-weight': 'bold', 'letter-spacing': '1px', 'line-height': '22px', }, } export default injectSheet(styles)(ServicesGroup)
client/src/components/dashboard/messaging/reply-message.js
WebTalentTop/newsfere-mern
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));
src/containers/Departure.js
osoken/project-train-2016
import React from 'react' import { connect } from 'react-redux' import { Link } from 'react-router' let Departure = ( {dispatch, departure} ) => ( <div> <div> <input type="text" placeholder="どこから出発しますか?"/> </div> <div> map </div> <div> <button type="button"><Link to={`way`}>道のりをみる</Link></button> </div> </div> ) let mapStateToProps = (state) => { return state } Departure = connect( mapStateToProps )(Departure) export default Departure
docs/src/app/components/pages/components/Badge/ExampleContent.js
kasra-co/material-ui
import React from 'react'; import Badge from 'material-ui/Badge'; import IconButton from 'material-ui/IconButton'; import UploadIcon from 'material-ui/svg-icons/file/cloud-upload'; import FolderIcon from 'material-ui/svg-icons/file/folder-open'; const BadgeExampleContent = () => ( <div> <Badge badgeContent={<IconButton tooltip="Backup"><UploadIcon /></IconButton>} > <FolderIcon /> </Badge> <Badge badgeContent="&copy;" badgeStyle={{fontSize: 20}} > Company Name </Badge> </div> ); export default BadgeExampleContent;
packages/storyboard-extension-chrome/src/components/030-coloredText.js
guigrpa/storyboard
import { merge } from 'timm'; import React from 'react'; import { ansiColors } from 'storyboard-core'; class ColoredText extends React.PureComponent { static propTypes = { text: React.PropTypes.string.isRequired, onClick: React.PropTypes.func, style: React.PropTypes.object, }; // ----------------------------------------------------- render() { const segments = ansiColors.getStyledSegments(this.props.text); if (segments.length === 1) { const segment = segments[0]; const extraProps = { onClick: this.props.onClick, style: merge(segment.style, this.props.style), }; return this.renderMsgSegment(segment, 0, extraProps); } return ( <span onClick={this.props.onClick} style={this.props.style}> {segments.map((segment, idx) => this.renderMsgSegment(segment, idx))} </span> ); } renderMsgSegment(segment, idx, extraProps = {}) { return ( <span key={idx} style={segment.style} {...extraProps}> {segment.text} </span> ); } } // ----------------------------------------------------- export default ColoredText;
.storybook/mocks/providers.js
Sing-Li/Rocket.Chat
import i18next from 'i18next'; import React from 'react'; import { TranslationContext } from '../../client/contexts/TranslationContext'; let contextValue; const getContextValue = () => { if (contextValue) { return contextValue; } i18next.init({ fallbackLng: 'en', defaultNS: 'project', resources: { en: { project: require('../../packages/rocketchat-i18n/i18n/en.i18n.json'), }, }, interpolation: { prefix: '__', suffix: '__', }, initImmediate: false, }); const translate = (key, ...replaces) => { if (typeof replaces[0] === 'object') { const [options] = replaces; return i18next.t(key, options); } if (replaces.length === 0) { return i18next.t(key); } return i18next.t(key, { postProcess: 'sprintf', sprintf: replaces, }); }; translate.has = (key) => key && i18next.exists(key); contextValue = { languages: [{ name: 'English', en: 'English', key: 'en', }], language: 'en', translate, }; return contextValue; }; function TranslationProviderMock({ children }) { return <TranslationContext.Provider children={children} value={getContextValue()} />; } export function MeteorProviderMock({ children }) { return <TranslationProviderMock> {children} </TranslationProviderMock>; }
public/client/routes/shell/components/header.js
nearform/concorda-dashboard
'use strict' import React from 'react' import {Link} from 'react-router' import Menu from './menu' export default React.createClass({ render () { const {showProfile, handleEditUserProfile} = this.props return ( <header className="header" role="banner"> <div className="container-fluid"> <div className="row middle-xs"> {(showProfile ? <Menu handleEditUserProfile={handleEditUserProfile}/> : null)} <div className="col-xs-12"> <Link to={'/'} className='logo logo-concorda'><h2 className="m0">Concorda: Dashboard</h2></Link> </div> </div> </div> </header> ) } })
carbon-page/src/index.js
ShotaOd/Carbon
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/About.js
rsproule/rsproule.github.io
import React, { Component } from 'react'; import './about.css'; import './animations.css'; class About extends Component{ /* Needs to contain: -quick info about me -interests hobbies(soccer/sports) -basically the info from the previous site */ render(){ return( <div className="pullDown"> <div className="about-container"> <h2> About </h2> <p> I am a computer science student who has a passion for building and learning about cool software. I formally got into software development when I was a Freshman at Washington University in St. Louis but my enthusiasm for working with computers goes all the way back to when I was a kid. Around my house, I have become a DE facto computer repair/assistance man for any and all tech problems that arise with my parents or siblings. As the result of this and my general curiosity towards technology I have been able to teach myself a good bit about computer hardware and software. </p> <br/> <p> In addition to developing software, I have grown up playing sports and have remained very active. Throughout high school I played baseball, basketball, and soccer while juggling a demanding academic curriculum. This taught me early on how to prioritize my activities and manage my time wisely. This has carried on to my college experience where I play on the varsity soccer team and remain a Dean's List student. </p> <br/> <h2> Education </h2> <ul> <li> BS Computer Science, Washington University in St. Louis (2019) </li> <li> Pittsburgh Central Catholic High School (2015) </li> </ul> <br/> <h2> Skills </h2> <h3> General Development </h3> <ul> <li> Java </li> <li> Python </li> <li> Dart </li> <li> C </li> <li> Arduino </li> <li> Swift/X code </li> <li> Flutter </li> <li> Amazon Web Services </li> <li> Linux </li> </ul> <h3> Front-End Development </h3> <ul> <li> HTML </li> <li> CSS + Frameworks (Bootstrap) </li> <li> JavaScript </li> <li> ReactJS </li> <li> AngularJS </li> </ul> <h3> Back-End Development </h3> <ul> <li> PHP </li> <li> MySQL </li> <li> JavaScript </li> <li> Firebase </li> <li> Socket.io </li> <li> Node.JS </li> <li> Web-pack </li> </ul> </div> </div> ) } } export default About;
docs/app/Examples/views/Card/Types/CardExampleGroupProps.js
aabustamante/Semantic-UI-React
import React from 'react' import { Card } from 'semantic-ui-react' const items = [ { header: 'Project Report - April', description: 'Leverage agile frameworks to provide a robust synopsis for high level overviews.', meta: 'ROI: 30%', }, { header: 'Project Report - May', description: 'Bring to the table win-win survival strategies to ensure proactive domination.', meta: 'ROI: 34%', }, { header: 'Project Report - June', description: 'Capitalise on low hanging fruit to identify a ballpark value added activity to beta test.', meta: 'ROI: 27%', }, ] const CardExampleGroupProps = () => ( <Card.Group items={items} /> ) export default CardExampleGroupProps
index.js
BowenTH/helloreact
import React from 'react'; import ReactDOM from 'react-dom'; import './style/index.css'; import {Hello,App} from './App'; // import imgJson from 'data/img.json'; // import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render( <div> <Hello/><App/> </div>, document.getElementById('root')); registerServiceWorker();
src/svg-icons/device/battery-50.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery50 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z"/><path d="M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z"/> </SvgIcon> ); DeviceBattery50 = pure(DeviceBattery50); DeviceBattery50.displayName = 'DeviceBattery50'; DeviceBattery50.muiName = 'SvgIcon'; export default DeviceBattery50;
src/alloyeditor.js
ipeychev/alloyeditor-react-component
import React from 'react'; import AlloyEditor from 'alloyeditor'; class AlloyEditorComponent extends React.Component { componentDidMount() { const {container, alloyEditorConfig} = this.props; this._editor = AlloyEditor.editable(container, alloyEditorConfig); } componentWillUnmount() { this._editor.destroy(); } render() { return ( <div id={this.props.container}> <h1>AlloyEditor will make this content editable</h1> <p> To install React, follow the instructions on <a href="https://github.com/facebook/react/">GitHub</a>. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vel metus nunc. Maecenas rhoncus congue faucibus. Sed finibus ultrices turpis. Mauris nulla ante, aliquam a euismod ut, scelerisque nec sem. Nam dapibus ac nulla non ullamcorper. Sed vestibulum a velit non lobortis. Proin sit amet imperdiet urna. Aenean interdum urna augue, vel mollis tortor dictum vitae. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris vitae suscipit magna. </p> </div> ); } } export default AlloyEditorComponent;
app/javascript/mastodon/features/status/components/detailed_status.js
haleyashleypraesent/ProjectPrionosuchus
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import StatusContent from '../../../components/status_content'; import MediaGallery from '../../../components/media_gallery'; import VideoPlayer from '../../../components/video_player'; import AttachmentList from '../../../components/attachment_list'; import Link from 'react-router-dom/Link'; import { FormattedDate, FormattedNumber } from 'react-intl'; import CardContainer from '../containers/card_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; class DetailedStatus extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, onOpenMedia: PropTypes.func.isRequired, onOpenVideo: PropTypes.func.isRequired, autoPlayGif: PropTypes.bool, }; handleAccountClick = (e) => { if (e.button === 0) { e.preventDefault(); this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`); } e.stopPropagation(); } render () { const status = this.props.status.get('reblog') ? this.props.status.get('reblog') : this.props.status; let media = ''; let applicationLink = ''; if (status.get('media_attachments').size > 0) { if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) { media = <AttachmentList media={status.get('media_attachments')} />; } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') { media = <VideoPlayer sensitive={status.get('sensitive')} media={status.getIn(['media_attachments', 0])} width={300} height={150} onOpenVideo={this.props.onOpenVideo} autoplay />; } else { media = <MediaGallery sensitive={status.get('sensitive')} media={status.get('media_attachments')} height={300} onOpenMedia={this.props.onOpenMedia} autoPlayGif={this.props.autoPlayGif} />; } } else if (status.get('spoiler_text').length === 0) { media = <CardContainer statusId={status.get('id')} />; } if (status.get('application')) { applicationLink = <span> · <a className='detailed-status__application' href={status.getIn(['application', 'website'])} target='_blank' rel='noopener'>{status.getIn(['application', 'name'])}</a></span>; } return ( <div className='detailed-status'> <a href={status.getIn(['account', 'url'])} onClick={this.handleAccountClick} className='detailed-status__display-name'> <div className='detailed-status__display-avatar'><Avatar src={status.getIn(['account', 'avatar'])} staticSrc={status.getIn(['account', 'avatar_static'])} size={48} /></div> <DisplayName account={status.get('account')} /> </a> <StatusContent status={status} /> {media} <div className='detailed-status__meta'> <a className='detailed-status__datetime' href={status.get('url')} target='_blank' rel='noopener'> <FormattedDate value={new Date(status.get('created_at'))} hour12={false} year='numeric' month='short' day='2-digit' hour='2-digit' minute='2-digit' /> </a>{applicationLink} · <Link to={`/statuses/${status.get('id')}/reblogs`} className='detailed-status__link'> <i className='fa fa-retweet' /> <span className='detailed-status__reblogs'> <FormattedNumber value={status.get('reblogs_count')} /> </span> </Link> · <Link to={`/statuses/${status.get('id')}/favourites`} className='detailed-status__link'> <i className='fa fa-star' /> <span className='detailed-status__favorites'> <FormattedNumber value={status.get('favourites_count')} /> </span> </Link> </div> </div> ); } } export default DetailedStatus;