path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/components/AppraisalFormat.js
wiserl/appraisal-frontend
import React from 'react'; const styles = { border: '4px #545454', margin: '90px', padding: '40px', }; export default appraisal => ( <div style={{...styles}}> <h4> Requester Email: {appraisal._email}</h4> <p>Type: {appraisal._type}</p> <div><em>Start Date: {appraisal._start}</em></div> <div><p> End Date: {appraisal._end}</p></div> <div><p> Region: {appraisal._address}</p></div> </div> )
app/javascript/mastodon/features/follow_requests/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 AccountAuthorizeContainer from './containers/account_authorize_container'; import { fetchFollowRequests, expandFollowRequests } from '../../actions/accounts'; import ScrollableList from '../../components/scrollable_list'; import { me } from '../../initial_state'; const messages = defineMessages({ heading: { id: 'column.follow_requests', defaultMessage: 'Follow requests' }, }); const mapStateToProps = state => ({ accountIds: state.getIn(['user_lists', 'follow_requests', 'items']), isLoading: state.getIn(['user_lists', 'follow_requests', 'isLoading'], true), hasMore: !!state.getIn(['user_lists', 'follow_requests', 'next']), locked: !!state.getIn(['accounts', me, 'locked']), domain: state.getIn(['meta', 'domain']), }); export default @connect(mapStateToProps) @injectIntl class FollowRequests extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, hasMore: PropTypes.bool, isLoading: PropTypes.bool, accountIds: ImmutablePropTypes.list, locked: PropTypes.bool, domain: PropTypes.string, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchFollowRequests()); } handleLoadMore = debounce(() => { this.props.dispatch(expandFollowRequests()); }, 300, { leading: true }); render () { const { intl, shouldUpdateScroll, accountIds, hasMore, multiColumn, locked, domain, isLoading } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.follow_requests' defaultMessage="You don't have any follow requests yet. When you receive one, it will show up here." />; const unlockedPrependMessage = locked ? null : ( <div className='follow_requests-unlocked_explanation'> <FormattedMessage id='follow_requests.unlocked_explanation' defaultMessage='Even though your account is not locked, the {domain} staff thought you might want to review follow requests from these accounts manually.' values={{ domain: domain }} /> </div> ); return ( <Column bindToDocument={!multiColumn} icon='user-plus' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollableList scrollKey='follow_requests' onLoadMore={this.handleLoadMore} hasMore={hasMore} isLoading={isLoading} shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} bindToDocument={!multiColumn} prepend={unlockedPrependMessage} > {accountIds.map(id => <AccountAuthorizeContainer key={id} id={id} />, )} </ScrollableList> </Column> ); } }
src/components/UserRegistration.js
dkadrios/zendrum-stompblock-client
import React from 'react' import PropTypes from 'prop-types' import { withStyles, Button, DialogActions, DialogContent, DialogContentText, DialogTitle, SvgIcon, } from '@material-ui/core' import UserRegistrationForm from './UserRegistrationForm' import GravatarIcon from '../images/Gravatar.svg' import Dialog from './Dialog' const styles = { icon: { width: 36, height: 36, marginRight: 7, }, link: { color: 'black', }, gravatarNotice: { display: 'flex', maxWidth: 330, }, } const GravatarLink = ({ content }) => ( <a href="https://en.gravatar.com/" target="_blank" rel="noopener noreferrer" > {content} </a> ) GravatarLink.propTypes = { content: PropTypes.node.isRequired } const UserRegistration = ({ active, hideDialog, submitRegistrationForm, serialNumber, classes }) => ( <Dialog open={active} onClose={hideDialog} > <DialogTitle>STOMPBLOCK Registration</DialogTitle> <DialogContent> <DialogContentText> Register yourself as the owner of this STOMPBLOCK <br /> Serial number:<strong> {serialNumber}</strong> </DialogContentText> <UserRegistrationForm /> <div className={classes.gravatarNotice}> <GravatarLink content={( <SvgIcon className={classes.icon}> <GravatarIcon /> </SvgIcon> )} /> <GravatarLink className={classes.link} content="We use Gravatar for displaying profile images, based on your email address" /> </div> </DialogContent> <DialogActions> <Button onClick={hideDialog}>Cancel</Button> <Button variant="contained" onClick={submitRegistrationForm} color="primary" autoFocus > Register </Button> </DialogActions> </Dialog> ) UserRegistration.propTypes = { active: PropTypes.bool.isRequired, hideDialog: PropTypes.func.isRequired, submitRegistrationForm: PropTypes.func.isRequired, serialNumber: PropTypes.string.isRequired, classes: PropTypes.object.isRequired, } export default withStyles(styles)(UserRegistration)
app/components/BaseComponent.js
timothyvanderaerden/React-TMDb
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router-dom'; class BaseComponent extends Component { componentDidUpdate(prevProps) { if (this.props.location !== prevProps.location) { window.scrollTo(0, 0); } } render() { return ( <div>{this.props.children}</div> ); } } BaseComponent.propTypes = { location: PropTypes.object.isRequired, children: PropTypes.object.isRequired }; export default withRouter(BaseComponent);
src/containers/NoteDialogContainer.js
dggriffin/noteworthee
import React from 'react'; import NoteDialog from 'components/NoteDialog'; import Rebase from 're-base'; const base = Rebase.createClass('https://noteworthyapp.firebaseio.com'); class NoteDialogContainer extends React.Component { constructor(props) { super(props); } addNote(newNote) { let noteKey = base.push(`teams/${this.props.teamName}/${this.props.boardName}`, { data: { message: newNote.messageValue, dateCreated: new Date().getTime(), likes: 0, comments: [], mood: newNote.moodState, urlList: newNote.urlList, imageUrl: newNote.imageUrl, tags: newNote.tagList, name: newNote.name } }); newNote.tagList.forEach((tag) => { base.push(`tags/${this.props.teamName}/${this.props.boardName}/${tag}`, { data: noteKey.key() }); }); this.props.handleDialogClose(); } render() { return ( <NoteDialog handleAddNote={this.addNote.bind(this)} {...this.props} /> ); } } export default NoteDialogContainer;
packages/material-ui/src/GridList/GridList.js
cherniavskii/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; export const styles = { root: { display: 'flex', flexWrap: 'wrap', overflowY: 'auto', listStyle: 'none', padding: 0, WebkitOverflowScrolling: 'touch', // Add iOS momentum scrolling. }, }; function GridList(props) { const { cellHeight, children, classes, className: classNameProp, cols, component: Component, spacing, style, ...other } = props; return ( <Component className={classNames(classes.root, classNameProp)} style={{ margin: -spacing / 2, ...style }} {...other} > {React.Children.map(children, currentChild => { if (!React.isValidElement(currentChild)) { return null; } const childCols = currentChild.props.cols || 1; const childRows = currentChild.props.rows || 1; return React.cloneElement(currentChild, { style: Object.assign( { width: `${100 / cols * childCols}%`, height: cellHeight === 'auto' ? 'auto' : cellHeight * childRows + spacing, padding: spacing / 2, }, currentChild.props.style, ), }); })} </Component> ); } GridList.propTypes = { /** * Number of px for one cell height. * You can set `'auto'` if you want to let the children determine the height. */ cellHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf(['auto'])]), /** * Grid Tiles that will be in Grid List. */ children: PropTypes.node.isRequired, /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * Number of columns. */ cols: PropTypes.number, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), /** * Number of px for the spacing between tiles. */ spacing: PropTypes.number, /** * @ignore */ style: PropTypes.object, }; GridList.defaultProps = { cellHeight: 180, cols: 2, component: 'ul', spacing: 4, }; export default withStyles(styles, { name: 'MuiGridList' })(GridList);
docs/src/modules/components/GoogleTag.js
cherniavskii/material-ui
import React from 'react'; import config from 'docs/src/config'; class GoogleTag extends React.Component { componentDidMount() { // Wait for the title to be updated. this.googleTimer = setTimeout(() => { window.gtag('config', config.google.id, { page_path: window.location.pathname, }); }); } componentWillUnmount() { clearTimeout(this.googleTimer); } googleTimer = null; render() { return null; } } export default GoogleTag;
lib/carbon-fields/vendor/htmlburger/carbon-fields/assets/js/containers/components/container/tabs.js
boquiabierto/wherever-content
/** * The external dependencies. */ import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; /** * The internal dependencies. */ import ContainerBase from 'containers/components/container/base'; /** * Render the tabs of the container. * * @param {Object} props * @param {Object} prop.container * @param {Array} prop.tabs * @return {React.Element} */ const ContainerTabs = ({ container, tabs }) => { return <div className="carbon-tabs-body"> { tabs.map(({ id, active, fields }) => ( <div key={id} className={cx('carbon-fields-collection', 'carbon-tab', { active })}> <ContainerBase container={container} fields={fields} /> </div> )) } </div>; }; /** * Validate the props. * * @type {Object} */ ContainerTabs.propTypes = { container: PropTypes.object, tabs: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, active: PropTypes.bool, fields: PropTypes.array, })), }; export default ContainerTabs;
test/connect/batch-force-update.js
nofluxjs/noflux-react
import test from 'ava'; import '../helpers/setup-test-env'; import React, { Component } from 'react'; import { mount } from 'enzyme'; import { connect, state } from '../../src'; test('should batch forceUpdate', t => { state.set({ name: 'Ssnau' }); let forceUpdateCallTimes = 0; let renderCallTimes = 0; @connect class App extends Component { onClick() { for (let i = 0; i < 10; i++) { state.set('name', `Malash${i}`); } } forceUpdate(...args) { super.forceUpdate(...args); forceUpdateCallTimes++; } render() { renderCallTimes++; return ( <button type="button" onClick={() => this.onClick()}> {state.get('name')} </button> ); } } const wrapper = mount(<App />); wrapper.find('button').simulate('click'); t.is(forceUpdateCallTimes, 1); t.is(renderCallTimes, 2); t.is(wrapper.find('button').text(), 'Malash9'); });
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js
allengaller/actor-platform
import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import ActorClient from 'utils/ActorClient'; import { Styles, FlatButton } from 'material-ui'; import { KeyCodes } from 'constants/ActorAppConstants'; import ActorTheme from 'constants/ActorTheme'; import MessageActionCreators from 'actions/MessageActionCreators'; import TypingActionCreators from 'actions/TypingActionCreators'; import DraftActionCreators from 'actions/DraftActionCreators'; import DraftStore from 'stores/DraftStore'; import AvatarItem from 'components/common/AvatarItem.react'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return { text: DraftStore.getDraft(), profile: ActorClient.getUser(ActorClient.getUid()) }; }; var ComposeSection = React.createClass({ displayName: 'ComposeSection', propTypes: { peer: React.PropTypes.object.isRequired }, childContextTypes: { muiTheme: React.PropTypes.object }, mixins: [PureRenderMixin], getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; }, componentWillMount() { ThemeManager.setTheme(ActorTheme); DraftStore.addLoadDraftListener(this.onDraftLoad); }, componentWillUnmount() { DraftStore.removeLoadDraftListener(this.onDraftLoad); }, getInitialState: function() { return getStateFromStores(); }, onDraftLoad() { this.setState(getStateFromStores()); }, _onChange: function(event) { TypingActionCreators.onTyping(this.props.peer); this.setState({text: event.target.value}); }, _onKeyDown: function(event) { if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) { event.preventDefault(); this._sendTextMessage(); } else if (event.keyCode === 50 && event.shiftKey) { console.warn('Mention should show now.'); } }, onKeyUp() { DraftActionCreators.saveDraft(this.state.text); }, _sendTextMessage() { const text = this.state.text; if (text) { MessageActionCreators.sendTextMessage(this.props.peer, text); } this.setState({text: ''}); DraftActionCreators.saveDraft('', true); }, _onSendFileClick: function() { const fileInput = document.getElementById('composeFileInput'); fileInput.click(); }, _onSendPhotoClick: function() { const photoInput = document.getElementById('composePhotoInput'); photoInput.accept = 'image/*'; photoInput.click(); }, _onFileInputChange: function() { const files = document.getElementById('composeFileInput').files; MessageActionCreators.sendFileMessage(this.props.peer, files[0]); }, _onPhotoInputChange: function() { const photos = document.getElementById('composePhotoInput').files; MessageActionCreators.sendPhotoMessage(this.props.peer, photos[0]); }, _onPaste: function(event) { let preventDefault = false; _.forEach(event.clipboardData.items, function(item) { if (item.type.indexOf('image') !== -1) { preventDefault = true; MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile()); } }, this); if (preventDefault) { event.preventDefault(); } }, render: function() { const text = this.state.text; const profile = this.state.profile; return ( <section className="compose" onPaste={this._onPaste}> <AvatarItem image={profile.avatar} placeholder={profile.placeholder} title={profile.name}/> <textarea className="compose__message" onChange={this._onChange} onKeyDown={this._onKeyDown} onKeyUp={this.onKeyUp} value={text}> </textarea> <footer className="compose__footer row"> <button className="button" onClick={this._onSendFileClick}> <i className="material-icons">attachment</i> Send file </button> <button className="button" onClick={this._onSendPhotoClick}> <i className="material-icons">photo_camera</i> Send photo </button> <span className="col-xs"></span> <FlatButton label="Send" onClick={this._sendTextMessage} secondary={true}/> </footer> <div className="compose__hidden"> <input id="composeFileInput" onChange={this._onFileInputChange} type="file"/> <input id="composePhotoInput" onChange={this._onPhotoInputChange} type="file"/> </div> </section> ); } }); export default ComposeSection;
src/svg-icons/hardware/security.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareSecurity = (props) => ( <SvgIcon {...props}> <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8z"/> </SvgIcon> ); HardwareSecurity = pure(HardwareSecurity); HardwareSecurity.displayName = 'HardwareSecurity'; HardwareSecurity.muiName = 'SvgIcon'; export default HardwareSecurity;
playground/client/src/index.js
JHerrickII/NewsTree
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; import './index.css'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/components/VideoPlayer/HLS/Stream.js
matmoi/react-adaptive-streaming
import React from 'react' import PropTypes from 'prop-types' import DropdownPanel from '../../utils/DropdownPanel.js' export default class HLSStream extends React.Component { render() { const { mediaPlayer } = this.props return ( <DropdownPanel title={"HLS Stream"} data={{ url: mediaPlayer.url, video: mediaPlayer.levels, audio: mediaPlayer.audioTracks, subtitles: mediaPlayer.subtitleTracks }} /> ) } } HLSStream.propTypes = { mediaPlayer: PropTypes.object.isRequired };
packages/wix-style-react/src/TableActionCell/docs/examples/PrimarySecondaryRTLExample.js
wix/wix-style-react
import React from 'react'; import Star from 'wix-ui-icons-common/Star'; import Download from 'wix-ui-icons-common/Download'; import Duplicate from 'wix-ui-icons-common/Duplicate'; import Print from 'wix-ui-icons-common/Print'; import { classes } from '../TableActionCell.story.st.css'; import { TableActionCell } from 'wix-style-react'; const Example = () => ( <div className="rtl" dir="rtl"> <div className={classes.exampleRow}> <TableActionCell dataHook="story-primary-secondary-rtl" primaryAction={{ text: 'Edit', skin: 'inverted', onClick: () => window.alert('Primary action was triggered!'), }} secondaryActions={[ { text: 'Star', icon: <Star />, onClick: () => window.alert('Star action was triggered.'), }, { text: 'Download', icon: <Download />, onClick: () => window.alert('Download action was triggered.'), }, { text: 'Duplicate', icon: <Duplicate />, onClick: () => window.alert('Duplicate action was triggered.'), }, { text: 'Print', icon: <Print />, onClick: () => window.alert('Print action was triggered.'), }, ]} numOfVisibleSecondaryActions={1} /> </div> </div> ); export default Example;
src/svg-icons/action/favorite.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionFavorite = (props) => ( <SvgIcon {...props}> <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/> </SvgIcon> ); ActionFavorite = pure(ActionFavorite); ActionFavorite.displayName = 'ActionFavorite'; ActionFavorite.muiName = 'SvgIcon'; export default ActionFavorite;
pages/index.js
nickroberts404/meadowlab
import React from 'react' import { Link } from 'react-router' import { prefixLink } from 'gatsby-helpers' import Helmet from 'react-helmet' import { config } from 'config' import PhotoCollage from '../components/PhotoCollage' export default class Index extends React.Component { render () { return ( <div> <Helmet title={config.siteTitle} meta={[ {"name": "description", "content": "The home of software engineer and climber, Nick Roberts"}, {"name": "keywords", "content": "meadowlab"}, {"property": "og:title", "content": "meadowlab"}, {"property": "og:url", "content": "http://meadowlab.io"}, {"property": "og:description", "content": "The home of software engineer and climber, Nick Roberts"}, ]} /> <div className="page-header home-page-header"> <h2 className="page-header-title">Hi, I'm Nick!</h2> <div className="intro"> <p>I'm a software engineer from Austin that has a passion for creating modern web apps.</p> <p>When I'm not programming, you'll find me outdoors climbing, hiking, or playing my synthesizers.</p> <p>Find me on <a href="https://github.com/nickroberts404">GitHub</a>, <a href="https://www.linkedin.com/in/nickroberts404/">LinkedIn</a>, or send me an <a href="mailto:nickroberts404@gmail.com">email</a>!</p> <p className="intro-emojis"><img alt="Outdoor and Piano Emojis" src="./img/emojis.png"/></p> </div> </div> <PhotoCollage photos={[ './img/mexico.jpg', './img/halfdome.jpg', './img/meadow.jpg', './img/jtree.jpg', './img/shadow.jpg' ]} /> </div> ) } } // I'm a software engineer from Austin, TX, that has a passion for creating modern web apps. When I'm not programming, you'll find me outdoors climbing or tickling my synthesizers.
src/svg-icons/device/access-time.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAccessTime = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/> </SvgIcon> ); DeviceAccessTime = pure(DeviceAccessTime); DeviceAccessTime.displayName = 'DeviceAccessTime'; DeviceAccessTime.muiName = 'SvgIcon'; export default DeviceAccessTime;
examples/js/expandRow/manage-expanding.js
rolandsusans/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i, expand: [ { fieldA: 'test1', fieldB: (i + 1) * 99, fieldC: (i + 1) * Math.random() * 100, fieldD: '123eedd' + i }, { fieldA: 'test2', fieldB: i * 99, fieldC: i * Math.random() * 100, fieldD: '123eedd' + i } ] }); } } addProducts(5); class BSTable extends React.Component { render() { if (this.props.data) { return ( <BootstrapTable data={ this.props.data }> <TableHeaderColumn dataField='fieldA' isKey={ true }>Field A</TableHeaderColumn> <TableHeaderColumn dataField='fieldB'>Field B</TableHeaderColumn> <TableHeaderColumn dataField='fieldC'>Field C</TableHeaderColumn> <TableHeaderColumn dataField='fieldD'>Field D</TableHeaderColumn> </BootstrapTable>); } else { return (<p>?</p>); } } } export default class ExpandRow extends React.Component { constructor(props) { super(props); this.state = { // Default expanding row expanding: [ 2 ] }; } isExpandableRow() { return true; } expandComponent(row) { return ( <BSTable data={ row.expand } /> ); } render() { const options = { expandRowBgColor: 'rgb(66, 134, 244)', expanding: this.state.expanding }; return ( <BootstrapTable data={ products } options={ options } expandableRow={ this.isExpandableRow } expandComponent={ this.expandComponent } search> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name' expandable={ false }>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price' expandable={ false }>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/parser/priest/shadow/modules/spells/ShadowWordPain.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import Enemies from 'parser/shared/modules/Enemies'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage } from 'common/format'; import SmallStatisticBox, { STATISTIC_ORDER } from 'interface/others/SmallStatisticBox'; import AbilityTracker from 'parser/priest/shadow/modules/core/AbilityTracker'; const MS_BUFFER = 100; /* Shadow word pain can be created by: Hard casting Misery Dark Void Shadow Word pain can be refreshed by: Hard casting Misery Dark Void Void Bolt */ class ShadowWordPain extends Analyzer { static dependencies = { enemies: Enemies, abilityTracker: AbilityTracker, }; castedShadowWordPains = 0; appliedShadowWordPains = 0; refreshedShadowWordPains = 0; // Dark Void lastDarkVoidCastTimestamp = 0; darkVoidShadowWordPainApplications = 0; darkVoidShadowWordPainRefreshes = 0; get uptime() { return this.enemies.getBuffUptime(SPELLS.SHADOW_WORD_PAIN.id) / this.owner.fightDuration; } get damage() { const spell = this.abilityTracker.getAbility(SPELLS.SHADOW_WORD_PAIN.id); return spell.damageEffective + spell.damageAbsorbed; } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId === SPELLS.SHADOW_WORD_PAIN.id) { this.castedShadowWordPains += 1; } if (spellId === SPELLS.DARK_VOID_TALENT.id) { this.lastCastTimestamp = event.timestamp; } } on_byPlayer_applydebuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.SHADOW_WORD_PAIN.id) { return; } this.appliedShadowWordPains += 1; if (this.lastCastTimestamp !== 0 && event.timestamp < this.lastCastTimestamp + MS_BUFFER) { this.darkVoidShadowWordPainApplications += 1; } } on_byPlayer_refreshdebuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.SHADOW_WORD_PAIN.id) { return; } this.refreshedShadowWordPains += 1; if (this.lastCastTimestamp !== 0 && event.timestamp < this.lastCastTimestamp + MS_BUFFER) { this.darkVoidShadowWordPainRefreshes += 1; } } get suggestionThresholds() { return { actual: this.uptime, isLessThan: { minor: 0.95, average: 0.90, major: 0.8, }, style: 'percentage', }; } suggestions(when) { const { isLessThan: { minor, average, major, }, } = this.suggestionThresholds; when(this.uptime).isLessThan(minor) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>Your <SpellLink id={SPELLS.SHADOW_WORD_PAIN.id} /> uptime can be improved. Try to pay more attention to your <SpellLink id={SPELLS.SHADOW_WORD_PAIN.id} /> on the boss.</span>) .icon(SPELLS.SHADOW_WORD_PAIN.icon) .actual(`${formatPercentage(actual)}% Shadow Word: Pain uptime`) .recommended(`>${formatPercentage(recommended)}% is recommended`) .regular(average).major(major); }); } statistic() { return ( <SmallStatisticBox position={STATISTIC_ORDER.CORE(4)} icon={<SpellIcon id={SPELLS.SHADOW_WORD_PAIN.id} />} value={`${formatPercentage(this.uptime)} %`} label="Shadow Word: Pain uptime" /> ); } } export default ShadowWordPain;
site/pages/ExamplePage.js
tomulin1/react-dnd
import React from 'react'; import Header from '../components/Header'; import PageBody from '../components/PageBody'; import SideBar from '../components/SideBar'; import { ExamplePages } from '../Constants'; export default class ExamplesPage { render() { return ( <div> <Header/> <PageBody hasSidebar> <SideBar groups={ExamplePages} example={this.props.example} /> {this.props.children} </PageBody> </div> ); } }
client/node_modules/react-router/es6/RouteContext.js
Discounty/Discounty
'use strict'; import React from 'react'; var object = React.PropTypes.object; /** * The RouteContext mixin provides a convenient way for route * components to set the route in context. This is needed for * routes that render elements that want to use the Lifecycle * mixin to prevent transitions. */ var RouteContext = { propTypes: { route: object.isRequired }, childContextTypes: { route: object.isRequired }, getChildContext: function getChildContext() { return { route: this.props.route }; } }; export default RouteContext;
app/javascript/mastodon/features/compose/components/autosuggest_account.js
8796n/mastodon
import React from 'react'; import Avatar from '../../../components/avatar'; import DisplayName from '../../../components/display_name'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; class AutosuggestAccount extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired }; render () { const { account } = this.props; return ( <div className='autosuggest-account'> <div className='autosuggest-account-icon'><Avatar src={account.get('avatar')} staticSrc={account.get('avatar_static')} size={18} /></div> <DisplayName account={account} /> </div> ); } } export default AutosuggestAccount;
client/src/javascript/components/modals/torrent-details-modal/TorrentFiles.js
stephdewit/flood
import _ from 'lodash'; import {Button, Checkbox, Form, FormRow, FormRowItem, Select, SelectItem} from 'flood-ui-kit'; import classnames from 'classnames'; import {FormattedMessage, injectIntl} from 'react-intl'; import React from 'react'; import ConfigStore from '../../../stores/ConfigStore'; import Disk from '../../icons/Disk'; import DirectoryTree from '../../general/filesystem/DirectoryTree'; import TorrentActions from '../../../actions/TorrentActions'; const TORRENT_PROPS_TO_CHECK = ['bytesDone']; const METHODS_TO_BIND = ['handleItemSelect', 'handlePriorityChange', 'handleSelectAllClick']; class TorrentFiles extends React.Component { constructor() { super(); this.hasSelectionChanged = false; this.hasPriorityChanged = false; this.state = { allSelected: false, selectedItems: {}, selectedFiles: [], }; METHODS_TO_BIND.forEach(method => { this[method] = this[method].bind(this); }); } shouldComponentUpdate(nextProps) { if (this.hasSelectionChanged) { this.hasSelectionChanged = false; return true; } // If we know that the user changed a file's priority, we deeply check the // file tree to render when the priority change is detected. if (this.hasPriorityChanged) { const shouldUpdate = !_.isEqual(nextProps.fileTree, this.props.fileTree); // Reset the flag so we don't deeply check the next file tree. if (shouldUpdate) { this.hasPriorityChanged = false; } return shouldUpdate; } // Update when the previous props weren't defined and the next are. if ((!this.props.torrent && nextProps.torrent) || (!this.props.fileTree && nextProps.fileTree)) { return true; } // Check specific properties to re-render when the torrent is active. if (nextProps.torrent) { return TORRENT_PROPS_TO_CHECK.some(property => this.props.torrent[property] !== nextProps.torrent[property]); } return true; } getSelectedFiles(selectionTree, selectedFiles = []) { if (selectionTree.files) { selectedFiles = [ ...selectedFiles, ...Object.keys(selectionTree.files).reduce((previousValue, filename) => { const file = selectionTree.files[filename]; if (file.isSelected) { previousValue.push(file.index); } return previousValue; }, []), ]; } if (selectionTree.directories) { Object.keys(selectionTree.directories).forEach(directory => { selectedFiles = [...selectedFiles, ...this.getSelectedFiles(selectionTree.directories[directory])]; }); } return selectedFiles; } handleDownloadButtonClick = event => { event.preventDefault(); const baseURI = ConfigStore.getBaseURI(); const link = document.createElement('a'); link.download = `${this.props.torrent.name}.tar`; link.href = `${baseURI}api/download?hash=${this.props.torrent.hash}&files=${this.state.selectedFiles.join(',')}`; link.style.display = 'none'; document.body.appendChild(link); // Fix for Firefox 58+ link.click(); }; handleFormChange = ({event}) => { if (event.target.name === 'file-priority') { this.handlePriorityChange(); TorrentActions.setFilePriority(this.props.hash, this.state.selectedFiles, event.target.value); } }; handleItemSelect(selectedItem) { this.hasSelectionChanged = true; this.setState(state => { const selectedItems = this.mergeSelection(selectedItem, state.selectedItems, 0, this.props.fileTree); const selectedFiles = this.getSelectedFiles(selectedItems); return { selectedItems, allSelected: false, selectedFiles, }; }); } handlePriorityChange() { this.hasPriorityChanged = true; } handleSelectAllClick() { this.hasSelectionChanged = true; this.setState((state, props) => { const selectedItems = this.selectAll(state.selectedItems, props.fileTree, state.allSelected); const selectedFiles = this.getSelectedFiles(selectedItems); return { selectedItems, allSelected: !state.allSelected, selectedFiles, }; }); } isLoaded() { return this.props.fileTree != null; } mergeSelection(item, tree = {}, depth = 0, fileTree = {}) { const {path} = item; const pathSegment = path[depth]; const selectionSubTree = item.type === 'file' ? 'files' : 'directories'; if (!tree[selectionSubTree]) { tree[selectionSubTree] = {}; } if (!tree[selectionSubTree][pathSegment]) { tree[selectionSubTree][pathSegment] = {}; } // If we are not at the clicked depth, then recurse over the path segments. if (depth++ < path.length - 1) { if (!tree.directories) { tree.directories = {[pathSegment]: {}}; } else if (!tree.directories[pathSegment]) { tree.directories[pathSegment] = {}; } // Deselect all parent directories if the item in question is being // de-selected. if (item.isSelected) { delete tree.isSelected; } tree.directories[pathSegment] = this.mergeSelection( item, tree.directories[pathSegment], depth, fileTree.directories[pathSegment], ); } else if (item.isSelected) { delete tree.isSelected; delete tree[selectionSubTree][pathSegment]; } else { let value; // If a directory was checked, recursively check all its children. if (item.type === 'directory') { value = this.selectAll(tree[selectionSubTree][pathSegment], fileTree[selectionSubTree][pathSegment]); } else { value = {...item, isSelected: true}; } tree[selectionSubTree][pathSegment] = value; } return tree; } selectAll(selectionTree = {}, fileTree = {}, deselect = false) { if (fileTree.files) { fileTree.files.forEach(file => { if (!selectionTree.files) { selectionTree.files = {}; } if (!deselect) { selectionTree.files[file.filename] = {...file, isSelected: true}; } else { delete selectionTree.files[file.filename]; } }); } if (fileTree.directories) { Object.keys(fileTree.directories).forEach(directory => { if (!selectionTree.directories) { selectionTree.directories = {}; } if (deselect && selectionTree.directories[directory]) { delete selectionTree.directories[directory].isSelected; } selectionTree.directories[directory] = this.selectAll( selectionTree.directories[directory], fileTree.directories[directory], deselect, ); }); } selectionTree.isSelected = !deselect; return selectionTree; } render() { const {fileTree, torrent} = this.props; let directoryHeadingIconContent = null; let fileDetailContent = null; if (this.isLoaded()) { directoryHeadingIconContent = ( <div className="file__checkbox directory-tree__checkbox"> <div className="directory-tree__checkbox__item directory-tree__checkbox__item--checkbox"> <FormRow> <Checkbox checked={this.state.allSelected} onChange={this.handleSelectAllClick} useProps /> </FormRow> </div> <div className="directory-tree__checkbox__item directory-tree__checkbox__item--icon"> <Disk /> </div> </div> ); fileDetailContent = ( <DirectoryTree depth={0} onItemSelect={this.handleItemSelect} onPriorityChange={this.handlePriorityChange} hash={this.props.torrent.hash} selectedItems={this.state.selectedItems} tree={fileTree} /> ); } else { directoryHeadingIconContent = <Disk />; fileDetailContent = ( <div className="directory-tree__node directory-tree__node--file"> <FormattedMessage id="torrents.details.files.loading" defaultMessage="Loading file detail..." /> </div> ); } const directoryHeadingClasses = classnames( 'directory-tree__node', 'directory-tree__parent-directory torrent-details__section__heading', { 'directory-tree__node--selected': this.state.allSelected, }, ); const directoryHeading = ( <div className={directoryHeadingClasses}> <div className="file__label"> {directoryHeadingIconContent} <div className="file__name">{torrent.directory}</div> </div> </div> ); const wrapperClasses = classnames('inverse directory-tree__wrapper', { 'directory-tree__wrapper--toolbar-visible': this.state.selectedFiles.length > 0, }); return ( <Form className={wrapperClasses} onChange={this.handleFormChange}> <div className="directory-tree__selection-toolbar"> <FormRow align="center"> <FormRowItem width="one-quarter" grow={false} shrink={false}> <FormattedMessage id="torrents.details.selected.files" defaultMessage="{count, plural, =1 {{countElement} selected file} other {{countElement} selected files}}" values={{ count: this.state.selectedFiles.length, countElement: ( <span className="directory-tree__selection-toolbar__item-count"> {this.state.selectedFiles.length} </span> ), }} /> </FormRowItem> <Button onClick={this.handleDownloadButtonClick} grow={false} shrink={false}> <FormattedMessage id="torrents.details.files.download.file" defaultMessage="{count, plural, =1 {Download File} other {Download Files}}" values={{ count: this.state.selectedFiles.length, }} /> </Button> <Select id="file-priority" persistentPlaceholder shrink={false}> <SelectItem placeholder> <FormattedMessage id="torrents.details.selected.files.set.priority" defaultMessage="Set Priority" /> </SelectItem> <SelectItem id={0}> {this.props.intl.formatMessage({ id: 'priority.dont.download', defaultMessage: "Don't Download", })} </SelectItem> <SelectItem id={1}> {this.props.intl.formatMessage({ id: 'priority.normal', defaultMessage: 'Normal', })} </SelectItem> <SelectItem id={2}> {this.props.intl.formatMessage({ id: 'priority.high', defaultMessage: 'High', })} </SelectItem> </Select> </FormRow> </div> <div className="directory-tree torrent-details__section torrent-details__section--file-tree modal__content--nested-scroll__content"> {directoryHeading} {fileDetailContent} </div> </Form> ); } } export default injectIntl(TorrentFiles);
src/svg-icons/image/camera.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCamera = (props) => ( <SvgIcon {...props}> <path d="M9.4 10.5l4.77-8.26C13.47 2.09 12.75 2 12 2c-2.4 0-4.6.85-6.32 2.25l3.66 6.35.06-.1zM21.54 9c-.92-2.92-3.15-5.26-6-6.34L11.88 9h9.66zm.26 1h-7.49l.29.5 4.76 8.25C21 16.97 22 14.61 22 12c0-.69-.07-1.35-.2-2zM8.54 12l-3.9-6.75C3.01 7.03 2 9.39 2 12c0 .69.07 1.35.2 2h7.49l-1.15-2zm-6.08 3c.92 2.92 3.15 5.26 6 6.34L12.12 15H2.46zm11.27 0l-3.9 6.76c.7.15 1.42.24 2.17.24 2.4 0 4.6-.85 6.32-2.25l-3.66-6.35-.93 1.6z"/> </SvgIcon> ); ImageCamera = pure(ImageCamera); ImageCamera.displayName = 'ImageCamera'; ImageCamera.muiName = 'SvgIcon'; export default ImageCamera;
docs/src/app/components/pages/components/CircularProgress/ExampleDeterminate.js
w01fgang/material-ui
import React from 'react'; import CircularProgress from 'material-ui/CircularProgress'; export default class CircularProgressExampleDeterminate extends React.Component { constructor(props) { super(props); this.state = { completed: 0, }; } componentDidMount() { this.timer = setTimeout(() => this.progress(5), 1000); } componentWillUnmount() { clearTimeout(this.timer); } progress(completed) { if (completed > 100) { this.setState({completed: 100}); } else { this.setState({completed}); const diff = Math.random() * 10; this.timer = setTimeout(() => this.progress(completed + diff), 1000); } } render() { return ( <div> <CircularProgress mode="determinate" value={this.state.completed} /> <CircularProgress mode="determinate" value={this.state.completed} size={60} thickness={7} /> <CircularProgress mode="determinate" value={this.state.completed} size={80} thickness={5} /> </div> ); } }
admin/client/App/shared/Popout/PopoutHeader.js
frontyard/keystone
/** * Render a header for a popout */ import React from 'react'; import Transition from 'react-addons-css-transition-group'; const PopoutHeader = React.createClass({ displayName: 'PopoutHeader', propTypes: { leftAction: React.PropTypes.func, leftIcon: React.PropTypes.string, title: React.PropTypes.string.isRequired, transitionDirection: React.PropTypes.oneOf(['next', 'prev']), }, render () { // If we have a left action and a left icon, render a header button var headerButton = (this.props.leftAction && this.props.leftIcon) ? ( <button key={'button_' + this.props.transitionDirection} type="button" className={'Popout__header__button octicon octicon-' + this.props.leftIcon} onClick={this.props.leftAction} /> ) : null; // If we have a title, render it var headerTitle = this.props.title ? ( <span key={'title_' + this.props.transitionDirection} className="Popout__header__label" > {this.props.title} </span> ) : null; return ( <div className="Popout__header"> <Transition transitionName="Popout__header__button" transitionEnterTimeout={200} transitionLeaveTimeout={200} > {headerButton} </Transition> <Transition transitionName={'Popout__pane-' + this.props.transitionDirection} transitionEnterTimeout={360} transitionLeaveTimeout={360} > {headerTitle} </Transition> </div> ); }, }); module.exports = PopoutHeader;
src/components/typography/caption.js
mattmischuk/m1x
// @flow import React from 'react' import type { Node } from 'react' import styled from 'styled-components' import cx from 'classnames' import { myTheme } from '../../styles' const { fontSize } = myTheme const StyledCaption = styled.h6` font-size: ${fontSize.seven}; text-transform: uppercase; ` const styles = { base: 'mb0' } type Props = { children: Node, className: string, } const Caption = ({ children, className }: Props) => ( <StyledCaption className={cx(styles.base, className)}> {children} </StyledCaption> ) export default Caption
src/components/ProjectPostEditor.js
Hylozoic/hylo-redux
/* eslint-disable camelcase */ import React from 'react' import { connect } from 'react-redux' import Icon from './Icon' import DatetimePicker from 'react-datetime' import { debounce } from 'lodash' import { get, map, pick, filter } from 'lodash/fp' import { getPost, getVideo } from '../models/post' const { array, func, object } = React.PropTypes const random = () => Math.random().toString().slice(2, 8) const getSimplePost = state => id => pick(['id', 'name', 'description', 'is_project_request'], getPost(id, state)) @connect((state, { postEdit }) => { if (postEdit.requests) return {requests: postEdit.requests} const children = map(getSimplePost(state), postEdit.children) const requests = filter(p => p.is_project_request, children) return {requests} }, null, null, {withRef: true}) export default class ProjectPostEditor extends React.Component { static propTypes = { postEdit: object, post: object, update: func.isRequired, requests: array } static contextTypes = {dispatch: func} componentDidMount () { // we update the store as soon as the component is mounted in order to load // data from the existing requests into the postEdit. otherwise, if we // didn't change them and then saved the post, they would be removed. const { update, requests } = this.props update({requests}) } addRequest = () => { const { update, requests } = this.props update({requests: [...requests, {id: `new-${random()}`}]}) } updateRequest = index => (key, value) => { const updatedRequest = {...this.props.requests[index], [key]: value} const requests = this.props.requests.slice() requests.splice(index, 1, updatedRequest) this.props.update({requests}) } render () { const { postEdit, update, requests } = this.props const { ends_at, type } = postEdit const endsAt = ends_at ? new Date(ends_at) : null const videoUrl = get('url', getVideo(postEdit)) || '' if (type !== 'project') setTimeout(() => update({type: 'project'})) return <div className='project-editor'> <h3> Requests <span className='soft normal'>&nbsp;&mdash; what you need to make it happen</span> </h3> <div className='requests'> {requests.map((p, i) => <ProjectRequestEditor post={p} key={p.id} update={this.updateRequest(i)} />)} <a className='add-request' onClick={this.addRequest}>+ Add request</a> </div> <div className='more-fields'> <div className='video'> <Icon name='VideoCamera' /> <input type='text' placeholder='youtube or vimeo url' value={videoUrl} onChange={event => update({video: event.target.value})} /> </div> <div className='deadline'> <Icon name='Calendar' /> <DatetimePicker inputProps={{placeholder: 'deadline'}} value={endsAt} onChange={m => update({ends_at: m.toISOString()})} /> </div> <div className='location'> <Icon name='Pin-1' /> <input type='text' placeholder='location' defaultValue={postEdit.location} onChange={event => update({location: event.target.value})} /> </div> </div> </div> } } import AutosizingTextarea from './AutosizingTextarea' import RichTextEditor from './RichTextEditor' import cx from 'classnames' class ProjectRequestEditor extends React.Component { static propTypes = { post: object, update: func } constructor (props) { super(props) this.state = pick(['name', 'description'], props.post) } goToDetails = () => { this.setState({showDetails: true}) this.refs.details.focus() } delayedUpdate = debounce(function (attr, value) { return this.props.update(attr, value) }, 100) render () { const { post: { id } } = this.props const { name, description } = this.state const handleChange = attr => event => { const { value } = event.target this.setState({[attr]: value}) this.delayedUpdate(attr, value) } const showDetails = this.state.showDetails || !!description const editorClass = cx('details', {empty: !showDetails}) const onBlur = () => { // we have to update description here because RichTextEditor doesn't always // send onChange events this.props.update('description', this.refs.details.getContent()) this.setState({showDetails: false}) } return <div> <div className='title-wrapper'> <AutosizingTextarea type='text' ref='title' className='title' value={name} placeholder='What do you need help with?' onChange={handleChange('name')} /> </div> <RichTextEditor className={editorClass} ref='details' name={`post-${id}`} content={description} onChange={handleChange('description')} onBlur={onBlur} /> {!showDetails && <div className='details-placeholder' onClick={this.goToDetails}> More details </div>} </div> } }
__tests__/index.android.js
aksharora/ReactNativeDemoBasic
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
app/containers/HomePage/index.js
Illyism/sample-dashboard
/* * HomePage * * This is the first thing users see of our App, at the '/' route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a neccessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import TextField from 'material-ui/TextField'; import FlatButton from 'material-ui/FlatButton'; import TextWidget from 'components/TextWidget'; import styles from './styles.css'; import { selectGrid, } from './selectors'; import { addWidget, deleteWidget } from './actions'; /* eslint-disable react/prefer-stateless-function */ export class HomePage extends React.Component { constructor() { super(); this.state = { value: '', }; } addCard = () => { this.props.addWidget(this.state.value); this.setState({ value: '', }); this.refs.input.focus(); } deleteCard = (key) => { this.props.deleteWidget(key); } handleChange = (event) => { this.setState({ value: event.target.value, }); }; renderGrid() { return this.props.grid.map((x, i) => <div className={`${styles.gridCell}`}> <TextWidget key={i} text={x.text} html={x.html} onDelete={() => this.deleteCard(i)} /> </div> ).toArray(); } render() { return ( <div className={`${styles.home}`}> <div className={`${styles.input}`}> <TextField ref="input" hintText="Write something..." fullWidth onChange={this.handleChange} value={this.state.value} multiLine /> <FlatButton label="Add" primary onClick={this.addCard} /> </div> <div className={`${styles.grid}`}> {this.renderGrid()} </div> </div> ); } } HomePage.propTypes = { addWidget: React.PropTypes.func, deleteWidget: React.PropTypes.func, grid: React.PropTypes.object, }; function mapDispatchToProps(dispatch) { return { addWidget: (text) => dispatch(addWidget(text)), deleteWidget: (key) => dispatch(deleteWidget(key)), dispatch, }; } export default connect(createSelector( selectGrid(), (grid) => ({ grid }) ), mapDispatchToProps)(HomePage);
src/index.js
nsipplswezey/iifym
import React from 'react'; import { render } from 'react-dom'; import { App } from './App'; render(<App />, document.getElementById('root'));
src/svg-icons/device/nfc.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceNfc = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 18H4V4h16v16zM18 6h-5c-1.1 0-2 .9-2 2v2.28c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V8h3v8H8V8h2V6H6v12h12V6z"/> </SvgIcon> ); DeviceNfc = pure(DeviceNfc); DeviceNfc.displayName = 'DeviceNfc'; DeviceNfc.muiName = 'SvgIcon'; export default DeviceNfc;
client/source/js/models/t_groups_m.js
Vladimir37/Planshark
import React from 'react'; import ReactDOM from 'react-dom'; import $ from 'jquery'; import {submitting, getData} from '../submitting.js'; import {Waiting, Error, Empty, Menu, Forbidden} from './templates.js'; import toast from '../toaster.js'; import {colorpick} from '../picker.js'; //responses var actions_r = ['Success!', 'Server error' , 'Required fields are empty', 'Incorrect color']; //RegExp var re_color = new RegExp("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"); //refresh groups list var refresh; var Creating = React.createClass({ getInitialState() { return null }, componentDidMount() { setTimeout(colorpick, 100); }, submit(elem) { var ajax_data = getData(elem.target); if(!ajax_data) { toast(actions_r[2]); } else if(!re_color.test(ajax_data.color)) { toast(actions_r[3]); $(elem.target).parent().find('input[name="color"]').val(''); } else { submitting(ajax_data, '/api/task_manage/create', 'POST', function(data) { var response_status = +data; if(isNaN(response_status)) { response_status = 1; } if(response_status == 0) { toast(actions_r[0]); $(elem.target).parent().find('input[type="text"]').val(''); refresh(); } else { toast(actions_r[response_status]); } }, function(err) { toast(actions_r[1]); }); } }, switching() { $('.creatingFormBody').slideToggle(); }, render() { return <section className="creatingForm"> <article className="creatingFormHead" onClick={this.switching}>Creating task group</article> <article className="creatingFormBody"> <input type="text" name="name" placeholder="Name" data-req="true" /> <input type="text" name="color" placeholder="Color" className="color_field" data-req="true" /> <button className="sub" onClick={this.submit}>Create</button> </article> </section>; } }); var TasksGroup = React.createClass({ getInitialState() { var data = this.props.data; return { id: data.id, name: data.name, color: data.color, tasks: data.tasks, tasks_count: data.tasks.length, created: data.createdAt } }, expand(elem) { var target = $(elem.target).closest('.task'); target.find('.task_additional').slideToggle(); }, actions(type) { return function(elem) { var target = $(elem.target).closest('.task'); target.find('.task_action:not(.task_' + type + ')').hide(); target.find('.task_' + type).slideToggle(); } }, submitting(type) { var self = this; return function(elem) { var target = elem.target; var ajax_data = {}; ajax_data = getData(target); ajax_data.id = self.state.id; if(ajax_data) { submitting(ajax_data, '/api/task_manage/' + type, 'POST', function (data) { var response_status = +data; if (isNaN(response_status)) { response_status = 1; } toast(actions_r[response_status]); refresh(); }, function (err) { toast(actions_r[1]); }); } else if(!re_color.test(ajax_data.color)) { toast(actions_r[3]); $(elem.target).parent().find('input[name="color"]').val(''); } else { toast(actions_r[2]); } } }, selectBoxes(elem) { var target = $(elem.target); var elemParent = target.closest('.select_box'); elemParent.find('label').removeClass('active_elem'); target.parent().addClass('active_elem'); }, render() { var self = this; var group_classes = 'task task_group_color task_group_color_' + this.state.id; //all tasks in groups var tasks_list = []; this.state.tasks.forEach(function(task) { tasks_list.push(<article className="item_list">{task.name}</article>); }); //all groups var groups_list = []; groups_list.push(<label className='active_elem'>No group<input type="radio" name="t_group" defaultChecked onChange={self.selectBoxes} value=''/></label>); this.props.all_groups.forEach(function(group) { if(group.id != self.state.id) { groups_list.push(<label>{group.name}<input type="radio" name="t_group" onChange={self.selectBoxes} value={group.id}/></label>); } }); var group_list_block = <article className="select_box"> {groups_list} </article>; return <article className={group_classes}> <article className="task_top"> <article className="task_head"> <span className="task_name">{this.state.name}</span><br/> <span className="task_group">Tasks: {this.state.tasks_count}</span> </article> <article className="task_expand" onClick={this.expand}></article> </article> <article className="task_additional"> <h3>Tasks</h3> <article className="select_box"> {tasks_list} </article> <article className="task_bottom"> <button className="solve_but" onClick={this.actions('edit')}>Edit</button> <button onClick={this.actions('delete')}>Delete</button> </article> <article className="task_action task_edit hidden"> <form> <input type="text" name="name" placeholder="Name" data-req="true" defaultValue={this.state.name} /><br/> <input type="text" name="color" placeholder="Color" defaultValue={this.state.color} className="color_field" data-req="true" /><br/> </form> <button onClick={this.submitting('edit')}>Edit</button> </article> <article className="task_action task_delete hidden"> <form> <h3>Move all tasks in {this.state.name} to other group?</h3> {group_list_block} Are you sure you want to delete "{this.state.name}" tasks group? </form> <button onClick={this.submitting('deleting')}>Delete</button> </article> </article> </article>; } }); var TasksGroupsList = React.createClass({ getInitialState() { return { received: false, error: false, status: null, groups: null } }, receive() { var self = this; submitting(null, '/api/account/status', 'GET', function(status) { if (typeof status == 'string') { status = JSON.parse(status); } submitting(null, '/api/manage_data/tasks_group', 'GET', function (data) { if (typeof data == 'string') { data = JSON.parse(data); } if(data.status == 0) { data.body.reverse(); self.setState({ received: true, error: false, status, groups: data.body }); } else { self.setState({ error: true }); } }, function (err) { self.setState({ error: true }); }); }, function(err) { self.setState({ error: true }); }); }, render() { var self = this; refresh = this.receive; //first load if(!this.state.received && !this.state.error) { this.receive(); return <Waiting />; } else if(!this.state.received && this.state.error) { return <Error />; } else if(!Boolean(this.state.t_manage || !this.state.room)) { return <Forbidden />; } //render else { var groups = []; if(!this.state.groups.length) { groups = <Empty />; } else { this.state.groups.forEach(function(group) { groups.push(<TasksGroup key={group.id + new Date().getTime()} data={group} all_groups={self.state.groups} />); }); } return <article className="task_group_page_inner"> <Menu active="t_groups" data={this.state.status} /> <Creating /> {groups} </article>; } } }); export default TasksGroupsList;
src/routing/routes.js
dopry/netlify-cms
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from '../containers/App'; import DashboardPage from '../containers/DashboardPage'; import CollectionPage from '../containers/CollectionPage'; import EntryPage from '../containers/EntryPage'; import SearchPage from '../containers/SearchPage'; import NotFoundPage from '../containers/NotFoundPage'; export default ( <Route path="/" component={App}> <IndexRoute component={DashboardPage} /> <Route path="/collections/:name" component={CollectionPage} /> <Route path="/collections/:name/entries/new" component={EntryPage} newRecord /> <Route path="/collections/:name/entries/:slug" component={EntryPage} /> <Route path="/search/:searchTerm" component={SearchPage} /> <Route path="*" component={NotFoundPage} /> </Route> );
test/integration/scss-fixtures/multi-page/pages/_app.js
azukaru/next.js
import React from 'react' import App from 'next/app' import '../styles/global1.scss' import '../styles/global2.scss' class MyApp extends App { render() { const { Component, pageProps } = this.props return <Component {...pageProps} /> } } export default MyApp
packages/playground/src/createDevModeAttachmentMiddleware.js
billba/botchat
import React from 'react'; import DebugAdaptiveCardAttachment from './DebugAdaptiveCardAttachment'; import JSONDebugView from './JSONDebugView'; export default function () { return () => next => ({ activity, attachment }) => attachment.contentType === 'application/vnd.microsoft.card.adaptive' ? ( <DebugAdaptiveCardAttachment activity={activity} attachment={attachment}> <JSONDebugView debug={attachment}>{next({ activity, attachment })}</JSONDebugView> </DebugAdaptiveCardAttachment> ) : ( <JSONDebugView debug={attachment}>{next({ activity, attachment })}</JSONDebugView> ); }
src/components/operations/operations-by-series.js
FranckCo/Operation-Explorer
import React from 'react'; import { sparqlConnect } from 'sparql-connect'; import OperationList from './operation-list'; import Spinner from 'components/shared/spinner' import D, { getLang } from 'i18n' /** * Builds the query that retrieves the series of a given family. */ const queryBuilder = series => ` PREFIX dcterms: <http://purl.org/dc/terms/> PREFIX skos: <http://www.w3.org/2004/02/skos/core#> SELECT ?operation ?label FROM <http://rdf.insee.fr/graphes/operations> WHERE { <${series}> dcterms:hasPart ?operation . ?operation skos:prefLabel ?label . FILTER(lang(?label) = '${getLang()}') } ORDER BY ?operation ` const connector = sparqlConnect(queryBuilder, { queryName: 'operationsBySeries', params: ['series'] }) function OperationsBySeries({ operationsBySeries, title }) { if (operationsBySeries.length === 0) { return <div>{D.serieHoldsNoOperation}</div> } return <OperationList operations={operationsBySeries} title={title} /> } export default connector(OperationsBySeries, { loading: () => <Spinner text={D.loadingOperations}/> })
actor-apps/app-web/src/app/components/ActivitySection.react.js
jamesbond12/actor-platform
import React from 'react'; import classNames from 'classnames'; import { ActivityTypes } from 'constants/ActorAppConstants'; import ActivityStore from 'stores/ActivityStore'; import UserProfile from 'components/activity/UserProfile.react'; import GroupProfile from 'components/activity/GroupProfile.react'; const getStateFromStores = () => { return { activity: ActivityStore.getActivity(), isOpen: ActivityStore.isOpen() }; }; class ActivitySection extends React.Component { constructor(props) { super(props); this.state = getStateFromStores(); ActivityStore.addChangeListener(this.onChange); } componentWillUnmount() { ActivityStore.removeChangeListener(this.onChange); } render() { const { activity, isOpen } = this.state; if (activity !== null) { const activityClassName = classNames('activity', { 'activity--shown': isOpen }); let activityBody; switch (activity.type) { case ActivityTypes.USER_PROFILE: activityBody = <UserProfile user={activity.user}/>; break; case ActivityTypes.GROUP_PROFILE: activityBody = <GroupProfile group={activity.group}/>; break; default: } return ( <section className={activityClassName}> {activityBody} </section> ); } else { return null; } } onChange = () => { this.setState(getStateFromStores()); }; } export default ActivitySection;
blueprints/layout/files/__test__/layouts/__name__Layout.spec.js
ashelkov/hexa
import React from 'react' describe('(Layout) <%= pascalEntityName %>', () => { it('should exist', () => { }) })
packages/fyndiq-icons/src/bubbles.js
fyndiq/fyndiq-ui
import React from 'react' import SvgWrapper from './svg-wrapper' const Bubbles = ({ className, color }) => ( <SvgWrapper className={className} viewBox="0 0 37 32"> <path d="m22.92 0.81055a4.6385 4.6385 0 1 0 0.001953 9.2773 4.6385 4.6385 0 0 0 -0.001953 -9.2773zm0 1.2656a3.376 3.376 0 0 1 3.373 3.373 3.376 3.376 0 0 1 -3.373 3.373 3.375 3.375 0 0 1 -3.373 -3.373 3.376 3.376 0 0 1 3.373 -3.373zm-9.0332 4.2637a4.639 4.639 0 1 0 0 9.2773 4.639 4.639 0 0 0 0 -9.2773zm0 1.2656a3.376 3.376 0 0 1 3.373 3.373 3.375 3.375 0 0 1 -3.373 3.3711 3.376 3.376 0 0 1 -3.373 -3.3711 3.376 3.376 0 0 1 3.373 -3.373zm9.0605 4.0293a4.6385 4.6385 0 0 0 0.001953 9.2773 4.6385 4.6385 0 0 0 -0.001953 -9.2773zm0 1.2656a3.376 3.376 0 0 1 3.373 3.373 3.376 3.376 0 0 1 -3.373 3.373 3.375 3.375 0 0 1 -3.373 -3.373 3.376 3.376 0 0 1 3.373 -3.373zm-9.0605 3.9395a4.639 4.639 0 1 0 0 9.2754 4.639 4.639 0 0 0 0 -9.2754zm18.213 0.10352a4.635 4.635 0 0 0 -3.8262 7.25 4.628 4.628 0 0 0 3.8359 2.0273 4.6385 4.6385 0 0 0 -0.009766 -9.2773zm-18.213 1.1602a3.376 3.376 0 0 1 3.373 3.373 3.375 3.375 0 0 1 -3.373 3.373 3.376 3.376 0 0 1 -3.373 -3.373 3.376 3.376 0 0 1 3.373 -3.373zm18.203 0.10547a3.341 3.341 0 0 1 0.009765 0c1.119 0 2.162 0.55066 2.791 1.4727 0.507 0.744 0.69534 1.6413 0.52734 2.5273a3.345 3.345 0 0 1 -1.4141 2.1602 3.37 3.37 0 0 1 -4.6855 -0.88672 3.34 3.34 0 0 1 -0.52734 -2.5273 3.342 3.342 0 0 1 1.4141 -2.1602 3.341 3.341 0 0 1 1.8848 -0.58594zm-27.303 3.8672a4.638 4.638 0 0 0 0 9.2754 4.638 4.638 0 0 0 0 -9.2754zm18.176 0.1582a4.639 4.639 0 1 0 0 9.2773 4.639 4.639 0 0 0 0 -9.2773zm-18.176 1.1074a3.375 3.375 0 0 1 3.3711 3.3711 3.376 3.376 0 0 1 -3.3711 3.373 3.376 3.376 0 0 1 -3.373 -3.373 3.376 3.376 0 0 1 3.373 -3.3711zm18.176 0.16016a3.376 3.376 0 0 1 3.3691 3.3711 3.375 3.375 0 0 1 -3.3691 3.3711 3.376 3.376 0 0 1 -3.373 -3.3711 3.376 3.376 0 0 1 3.373 -3.3711z" fill={color} fillRule="evenodd" stroke="none" /> </SvgWrapper> ) Bubbles.propTypes = SvgWrapper.propTypes Bubbles.defaultProps = SvgWrapper.defaultProps export default Bubbles
packages/rmw-shell/src/providers/Firebase/Paths/with.js
TarikHuber/react-most-wanted
import Context from './Context' import React from 'react' const withContainer = (Component) => { const ChildComponent = (props) => { return ( <Context.Consumer> {(value) => { return <Component {...value} {...props} /> }} </Context.Consumer> ) } return ChildComponent } export default withContainer
src/Hello/Hello.js
kashjs/muszoo-react
import React from 'react'; export class Hello extends React.Component { render() { return <h1>Hello React! yey</h1>; } }
app/javascript/mastodon/features/hashtag_timeline/components/column_settings.js
ikuradon/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Toggle from 'react-toggle'; import AsyncSelect from 'react-select/async'; import { NonceProvider } from 'react-select'; import SettingToggle from '../../notifications/components/setting_toggle'; const messages = defineMessages({ placeholder: { id: 'hashtag.column_settings.select.placeholder', defaultMessage: 'Enter hashtags…' }, noOptions: { id: 'hashtag.column_settings.select.no_options_message', defaultMessage: 'No suggestions found' }, }); export default @injectIntl class ColumnSettings extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, onChange: PropTypes.func.isRequired, onLoad: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { open: this.hasTags(), }; hasTags () { return ['all', 'any', 'none'].map(mode => this.tags(mode).length > 0).includes(true); } tags (mode) { let tags = this.props.settings.getIn(['tags', mode]) || []; if (tags.toJSON) { return tags.toJSON(); } else { return tags; } }; onSelect = mode => value => this.props.onChange(['tags', mode], value); onToggle = () => { if (this.state.open && this.hasTags()) { this.props.onChange('tags', {}); } this.setState({ open: !this.state.open }); }; noOptionsMessage = () => this.props.intl.formatMessage(messages.noOptions); modeSelect (mode) { return ( <div className='column-settings__row'> <span className='column-settings__section'> {this.modeLabel(mode)} </span> <NonceProvider nonce={document.querySelector('meta[name=style-nonce]').content} cacheKey='tags'> <AsyncSelect isMulti autoFocus value={this.tags(mode)} onChange={this.onSelect(mode)} loadOptions={this.props.onLoad} className='column-select__container' classNamePrefix='column-select' name='tags' placeholder={this.props.intl.formatMessage(messages.placeholder)} noOptionsMessage={this.noOptionsMessage} /> </NonceProvider> </div> ); } modeLabel (mode) { switch(mode) { case 'any': return <FormattedMessage id='hashtag.column_settings.tag_mode.any' defaultMessage='Any of these' />; case 'all': return <FormattedMessage id='hashtag.column_settings.tag_mode.all' defaultMessage='All of these' />; case 'none': return <FormattedMessage id='hashtag.column_settings.tag_mode.none' defaultMessage='None of these' />; default: return ''; } }; render () { const { settings, onChange } = this.props; return ( <div> <div className='column-settings__row'> <div className='setting-toggle'> <Toggle id='hashtag.column_settings.tag_toggle' onChange={this.onToggle} checked={this.state.open} /> <span className='setting-toggle__label'> <FormattedMessage id='hashtag.column_settings.tag_toggle' defaultMessage='Include additional tags in this column' /> </span> </div> </div> {this.state.open && ( <div className='column-settings__hashtags'> {this.modeSelect('any')} {this.modeSelect('all')} {this.modeSelect('none')} </div> )} <div className='column-settings__row'> <SettingToggle settings={settings} settingPath={['local']} onChange={onChange} label={<FormattedMessage id='community.column_settings.local_only' defaultMessage='Local only' />} /> </div> </div> ); } }
app/components/elements/TimeAgoWrapper.js
enisey14/platform
/* eslint react/prop-types: 0 */ import React from 'react'; import { FormattedRelative } from 'react-intl'; export default class TimeAgoWrapper extends React.Component { render() { let {date} = this.props if(date && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d$/.test(date)) { date = date + 'Z' // Firefox really wants this Z (Zulu) } return <FormattedRelative {...this.props} value={date} /> } }
ui/src/components/IssueProviderList/index.js
denniss17/status-dashboard
import React, { Component } from 'react'; import IssueProvider from './IssueProvider'; import PropTypes from 'prop-types'; class IssueProviderList extends Component { render() { const { issueProviders, statusesForIssues } = this.props; return ( <div> {issueProviders && Object.keys(issueProviders).map(id => <IssueProvider key={id} issueProvider={issueProviders[id]} statusesForIssues={statusesForIssues}/>)} </div> ); } } IssueProviderList.propTypes = { issueProviders: PropTypes.object, statusesForIssues: PropTypes.object }; export default IssueProviderList;
app/config/routes.js
cshutchinson/sk
import React, { Component } from 'react'; import Main from '../components/Main'; import Home from '../components/Home'; import { Router, Route, IndexRoute, Link } from 'react-router' module.exports = ( <Route path="/" component={Main}> <IndexRoute component={Home} /> </Route> );
packages/react-static/src/browser/components/SiteData.js
nozzle/react-static
import React from 'react' import useSiteData from '../hooks/useSiteData' export function SiteData({ children }) { return children(useSiteData()) } export function withSiteData(Comp) { return function componentWithSiteData(props) { const routeData = useSiteData() return <Comp {...props} {...routeData} /> } }
src/components/common/Button.js
amir5000/react-native-manager-app
import React from 'react'; import { Text, TouchableOpacity } from 'react-native'; const Button = ({ onPress, children }) => { const { buttonStyle, buttonTextStyle } = styles; return ( <TouchableOpacity onPress={onPress} style={buttonStyle}> <Text style={buttonTextStyle}>{children}</Text> </TouchableOpacity> ); }; const styles = { buttonStyle: { flex: 1, alignSelf: 'stretch', backgroundColor: '#FFF', borderRadius: 5, borderWidth: 1, borderColor: '#007AFF', marginLeft: 5, marginRight: 5 }, buttonTextStyle: { alignSelf: 'center', color: '#007AFF', fontWeight: '600', paddingTop: 10, paddingBottom: 10 } }; export { Button };
packages/material-ui-icons/src/ArrowForward.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let ArrowForward = props => <SvgIcon {...props}> <path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" /> </SvgIcon>; ArrowForward = pure(ArrowForward); ArrowForward.muiName = 'SvgIcon'; export default ArrowForward;
src/svg-icons/notification/folder-special.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationFolderSpecial = (props) => ( <SvgIcon {...props}> <path d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-2.06 11L15 15.28 12.06 17l.78-3.33-2.59-2.24 3.41-.29L15 8l1.34 3.14 3.41.29-2.59 2.24.78 3.33z"/> </SvgIcon> ); NotificationFolderSpecial = pure(NotificationFolderSpecial); NotificationFolderSpecial.displayName = 'NotificationFolderSpecial'; NotificationFolderSpecial.muiName = 'SvgIcon'; export default NotificationFolderSpecial;
client/android/app/src/pages/SignUp.js
blusclips/zonaster
import React, { Component } from 'react'; import {Image, StyleSheet, AsyncStorage} from 'react-native'; import { StackNavigator } from 'react-navigation'; import { Container, Content, Text, H1, H3, Button, Item, Input, Grid, Col} from 'native-base'; import general from '../styles/general'; import Icon from 'react-native-vector-icons/FontAwesome'; import SplashScreen from 'react-native-splash-screen'; import { SocialIcon } from 'react-native-elements'; import progressDialog from '../../../../src/progressDialog.js'; import {action, observable} from 'mobx'; import {observer} from 'mobx-react/native'; import {autobind} from 'core-decorators'; @observer @autobind export default class SignUpScreen extends Component { static navigationOptions = { header:null }; constructor(props) { super(props); this.state = {error:'', email:'', password:'', re_password:''}; this.store = this.props.screenProps.store; this.createAccount = this.createAccount.bind(this); changeState = (text) =>{ this.setState({error:text}); } } createAccount = () =>{ this.store.isError = ""; let email = this.state.email; let pass = this.state.password; let re_pass = this.state.re_password; let fullnames = ""; if (email !== "") { if (pass !== "" && pass == re_pass) { progressDialog.show("Creating account, Please wait."); this.store.createAccount(this.props.navigation, email, pass, fullnames); }else{ this.store.isError = "Passwords don't match.."; } }else{ this.store.isError = "Enter Email address or Phone Number"; } } render(){ const { navigate } = this.props.navigation; return( <Container style={{backgroundColor:'#fff'}}> <Content style={{padding:30}}> <H1 style={{textAlign:'center', marginTop:55, marginBottom:35, fontWeight:'bold', color:'#B71C1C'}}>Zonaster</H1> <Text style={{textAlign:'center', fontWeight:'bold', color:'#B71C1C'}}> { this.store.isError } </Text> <Item style={general.pad}> <Icon active name='user-circle' size={20} /> <Input placeholder='Email or Phone' onChangeText={(email) => this.setState({email})}/> </Item> <Item style={general.pad}> <Icon active name='lock' size={25} /> <Input placeholder='Password' onChangeText={(password) => this.setState({password})} /> </Item> <Item style={general.pad}> <Icon active name='lock' size={25} /> <Input placeholder='Re Enter Password' onChangeText={(re_password) => this.setState({re_password})}/> </Item> <Button full rounded style={general.pad, general.primaryColorDark} onPress={this.createAccount}> <Text>Create Account</Text> </Button> <Text style={{marginTop:35, marginBottom:50, textAlign:'center'}}> By creating an account, you agree to our terms of use and privacy policies. </Text> </Content> </Container> ) } }
docs/src/app/components/pages/components/SelectField/ExampleFloatingLabel.js
rhaedes/material-ui
import React from 'react'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; const items = [ <MenuItem key={1} value={1} primaryText="Never" />, <MenuItem key={2} value={2} primaryText="Every Night" />, <MenuItem key={3} value={3} primaryText="Weeknights" />, <MenuItem key={4} value={4} primaryText="Weekends" />, <MenuItem key={5} value={5} primaryText="Weekly" />, ]; export default class SelectFieldExampleFloatingLabel extends React.Component { constructor(props) { super(props); this.state = {value: null}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <div> <SelectField value={this.state.value} onChange={this.handleChange} floatingLabelText="Floating Label Text" > {items} </SelectField> <br /> <SelectField value={this.state.value} onChange={this.handleChange} floatingLabelText="Styled Floating Label Text" floatingLabelStyle={{color: 'red'}} > {items} </SelectField> </div> ); } }
src/components/js/Contacts.js
ucev/chatroom
import React, { Component } from 'react'; import UserItem from './UserItem'; import MyAction from '../../state/action'; class Contacts extends Component { render() { var state = MyAction.getState(); var userid = state.userid; var users = state.users.filter((user) => { return user.id != userid; }); var users = users.map((user) => { return ( <UserItem key={user.id} user={user} history={this.props.history} /> ) }) return ( <div> <div>{users}</div> </div> ); } } export default Contacts;
source/src/components/App.js
mondalamit/mondalamit.github.io
import React, { Component } from 'react'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ); } } export default App;
packages/react-scripts/fixtures/kitchensink/src/features/webpack/ImageInclusion.js
GreenGremlin/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import tiniestCat from './assets/tiniest-cat.jpg'; export default () => ( <img id="feature-image-inclusion" src={tiniestCat} alt="tiniest cat" /> );
src/hucha.web/test/helpers/shallowRenderHelper.js
jparaya/hucha
/** * Function to get the shallow output for a given component * As we are using phantom.js, we also need to include the fn.proto.bind shim! * * @see http://simonsmith.io/unit-testing-react-components-without-a-dom/ * @author somonsmith */ import React from 'react'; import TestUtils from 'react-addons-test-utils'; /** * Get the shallow rendered component * * @param {Object} component The component to return the output for * @param {Object} props [optional] The components properties * @param {Mixed} ...children [optional] List of children * @return {Object} Shallow rendered output */ export default function createComponent(component, props = {}, ...children) { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0])); return shallowRenderer.getRenderOutput(); }
docs/src/PageFooter.js
nickuraltsev/react-bootstrap
import React from 'react'; import packageJSON from '../../package.json'; let version = packageJSON.version; if (/docs/.test(version)) { version = version.split('-')[0]; } const PageHeader = React.createClass({ render() { return ( <footer className="bs-docs-footer" role="contentinfo"> <div className="container"> <div className="bs-docs-social"> <ul className="bs-docs-social-buttons"> <li> <iframe className="github-btn" src="https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=watch&count=true" width={95} height={20} title="Star on GitHub" /> </li> <li> <iframe className="github-btn" src="https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=fork&count=true" width={92} height={20} title="Fork on GitHub" /> </li> <li> <iframe src="https://platform.twitter.com/widgets/follow_button.html?screen_name=react_bootstrap&show_screen_name=true" width={230} height={20} allowTransparency="true" frameBorder="0" scrolling="no"> </iframe> </li> </ul> </div> <p>Code licensed under <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/LICENSE" target="_blank">MIT</a>.</p> <ul className="bs-docs-footer-links muted"> <li>Currently v{version}</li> <li>·</li> <li><a href="https://github.com/react-bootstrap/react-bootstrap/">GitHub</a></li> <li>·</li> <li><a href="https://github.com/react-bootstrap/react-bootstrap/issues?state=open">Issues</a></li> <li>·</li> <li><a href="https://github.com/react-bootstrap/react-bootstrap/releases">Releases</a></li> </ul> </div> </footer> ); } }); export default PageHeader;
demo/src/demo-components/indicators.js
Strikersoft/striker-store
import React from 'react'; import { shape, func, string } from 'prop-types'; import { observer } from 'mobx-react'; const IndicatorComponent = observer(({ indicator, type }) => { if (indicator.get()) { return <span>({type})</span>; } return null; }); IndicatorComponent.propTypes = { indicator: shape({ get: func }).isRequired, type: string }; IndicatorComponent.defaultProps = { type: 'Loading' }; IndicatorComponent.displayName = 'StatusIndicator'; export default IndicatorComponent;
src/__tests__/component-for-fields-test.js
Uber5/u5-forms
import React from 'react' import { Provider } from 'react-redux' import { reduxForm } from 'redux-form' import { componentForFields } from '../' import configureMockStore from 'redux-mock-store' describe('componentForFields', () => { it('constructs fields for each field type', () => { const fields = [ { name: 'someText', label: 'Label for multiline', type: 'multiline' }, { name: 'someDate', label: 'Label for a date', type: 'date' }, { name: 'someField', label: 'Some field without type' }, { name: 'someTextField', label: 'Label for text field', type: 'text' }, { name: 'someNameField', label: 'Label for name field', type: 'name' }, { name: 'someEmailField', label: 'Label for email field', type: 'email' }, { name: 'someIdnoField', label: 'Label for idno field', type: 'idno' }, { name: 'someBooleanField', label: 'Label for boolean field', type: 'boolean' }, ] const Component = componentForFields(fields) const mockStore = configureMockStore([]) const store = { subscribe: f => f, dispatch: f => f, getState: () => ({}) } const Form = reduxForm({ form: 'test', store: mockStore({}) })(() => <Component />) const render2 = el => render(<Provider store={mockStore({})} >{el}</Provider>) // const rendered = render(<Provider store={mockStore({})} ><Form /></Provider>) const rendered = render2(<Form />) expect(rendered).toMatchSnapshot() }) })
node_modules/react-router/es/MemoryRouter.js
AngeliaGong/AngeliaGong.github.io
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } 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 warning from 'warning'; import React from 'react'; import PropTypes from 'prop-types'; import createHistory from 'history/createMemoryHistory'; import Router from './Router'; /** * The public API for a <Router> that stores location in memory. */ var MemoryRouter = function (_React$Component) { _inherits(MemoryRouter, _React$Component); function MemoryRouter() { var _temp, _this, _ret; _classCallCheck(this, MemoryRouter); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret); } MemoryRouter.prototype.componentWillMount = function componentWillMount() { warning(!this.props.history, '<MemoryRouter> ignores the history prop. To use a custom history, ' + 'use `import { Router }` instead of `import { MemoryRouter as Router }`.'); }; MemoryRouter.prototype.render = function render() { return React.createElement(Router, { history: this.history, children: this.props.children }); }; return MemoryRouter; }(React.Component); MemoryRouter.propTypes = { initialEntries: PropTypes.array, initialIndex: PropTypes.number, getUserConfirmation: PropTypes.func, keyLength: PropTypes.number, children: PropTypes.node }; export default MemoryRouter;
src/icons/ViewModuleIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class ViewModuleIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M8 22h10V10H8v12zm0 14h10V24H8v12zm12 0h10V24H20v12zm12 0h10V24H32v12zM20 22h10V10H20v12zm12-12v12h10V10H32z"/></svg>;} };
app/components/Button.js
RogerZZZZZ/widget_electron
import React from 'react' import { Component } from 'react' let assetsPrefix = process.env.DEV? '..': '.' class Button extends Component{ constructor(props){ super(props); let picName = (this.props.status === false || this.props.status === undefined? this.props.name: this.props.name+"-done"); this.state = { picName: assetsPrefix + "/assets/" + picName+ ".png", originName: this.props.name } } _hoverInListener(){ this.setState({ picName : assetsPrefix + "/assets/" + this.state.originName + "-on.png" }) } _hoverOutListener(){ this.setState({ picName: assetsPrefix + "/assets/" + this.state.originName + ".png" }) } _buttonClick(){ let picName; if(this.props.status){ picName = this.props.name }else{ picName = this.props.name + '-done'; } this.setState({ picName: assetsPrefix + "/assets/" + picName + ".png" }) this.props.buttonClick(); } render(){ return ( <div className={this.props.align == "left"? "left-button circle-button": "right-button circle-button"} onMouseOver={this.props.static?null:this._hoverInListener.bind(this)} onClick={this._buttonClick.bind(this)} onMouseLeave={this.props.static?null:this._hoverOutListener.bind(this)}> <img src={this.state.picName} className="circle-button-img" ref="buttonImg"/> </div> ) } } export default Button
tilapp/src/containers/Scenes/Capture/Index/index.js
tilap/tilapp
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import merge from 'deep-assign'; import { Container } from 'native-base'; import processBarcode from './services/processBarcode'; import { ReverseCameraIcon, ReverseCameraActiveIcon, FlashCameraIcon, FlashCameraActiveIcon } from '~/components/Icons'; import BarCodeScannerPlus from '~/components/BareCodeScannerPlus'; import SimpleMessage from '~/components/SimpleMessage/'; import { OfflineIcon } from '~/components/Icons/'; import NavigationButton from '~/components/NavigationButton'; class CaptureScene extends Component { handleBarCodeRead = async ({ data: barcode }) => { if (!this.props.scanEnabled) { return false; } const wordings = { start: this.props.wordingStartScanning, waiting: this.props.wordingSearchingWait, }; const book = await processBarcode({ ean: barcode, wordings }); if (book) { this.props.navigation.navigate('Book', { bookScreenType: 'sell' }); } } render() { if (!this.props.connected) { return ( <SimpleMessage Icon={OfflineIcon} text="You need to be connected to Internet to add a book." /> ); } return this.props.displayScanner ? ( <Container> <BarCodeScannerPlus onBarCodeRead={this.handleBarCodeRead} adviseText={this.props.scanEnabled ? "Scan a book bar code" : "Scanner disabled"} paused={!this.props.scanEnabled} IconReverseCamera={ReverseCameraIcon} IconReverseCameraActive={ReverseCameraActiveIcon} IconFlashCamera={FlashCameraIcon} IconFlashCameraActive={FlashCameraActiveIcon} /> </Container> ) : null; } } CaptureScene.propTypes = { navigation: PropTypes.any.isRequired, scanEnabled: PropTypes.bool.isRequired, displayScanner: PropTypes.bool.isRequired, scannerEnabled: PropTypes.bool.isRequired, wordingStartScanning: PropTypes.string, wordingSearchingWait: PropTypes.arrayOf(PropTypes.string), connected: PropTypes.bool.isRequired, }; CaptureScene.defaultProps = { wordingStartScanning: 'Analyzing the barcode...', wordingSearchingWait: [ 'Searching the book...', 'You are the first one looking for this book...', 'We are digging to find that book...', 'Seems it is not a common book hu?', ], }; CaptureScene.navigationOptions = (props) => { console.log(props.navigationOptions) return merge({}, (props.navigationOptions || {}), { title: 'Add a book', headerRight: ( <NavigationButton icon="help" onPress={() => props.navigation.navigate('CaptureHelp')} /> ), }); } const mapStateToProps = ({ scenes: { barcodescanner: { enabled } }, services: { navigation: { current }, api: { connected }, }, }) => ({ scanEnabled: enabled, displayScanner: current.startsWith('Capture'), scannerEnabled: current === 'CaptureIndex', connected, }); export default connect(mapStateToProps)(CaptureScene);
src/modules/settings/components/Feedback.js
CaronaBoard/caronaboard-native
import React from 'react' import { WebView } from 'react-native' export const Feedback = () => { return ( <WebView source={{uri: 'https://goo.gl/forms/IxVqYmchYVrHkNLq2'}} style={{flex: 1}} /> ) }
packages/benchmarks-utils/src/index.js
A-gambit/CSS-IN-JS-Benchmarks
import React from 'react'; function getTable(max = 30) { let table = []; for (let i = 0; i < max; i++) { table[i] = [1]; for (let j = 1; j < max; j++) { const next = table[i][j - 1] - Math.random() * table[i][j - 1] / 10; table[i].push(next.toFixed(4)); } } return table; } function getUniqueSize(table) { let set = new Set(); table.forEach(row => row.forEach(x => set.add(x))); return set.size; } function toPercent(x) { return (x * 100).toFixed(2).toString() + '%'; } async function runTestRerender() { const input = document.querySelector('input'); for (let i = 0; i < 10; i++) { await new Promise(resolve => { performance.mark('startRerender' + i); input.click(); setTimeout(() => { setTimeout(() => { performance.mark('endRerender' + i); performance.measure( 'measureRerender' + i, 'startRerender' + i, 'endRerender' + i ); resolve(); }, 0); }, 0); }); } } function willMount() { if (document.location.search.includes('test=true')) { performance.mark('startMount'); } } function didMount() { if (!document.location.search.includes('test=true')) { return; } performance.mark('endMount'); performance.measure('measureMount', 'startMount', 'endMount'); if (document.location.search.includes('butch=true')) { return runTestRerender(); } const input = document.querySelector('input'); performance.mark('startRerender'); input.click(); setTimeout(() => { performance.mark('endRerender'); performance.measure('measureRerender', 'startRerender', 'endRerender'); }, 0); } export default class App extends React.Component { constructor(props) { super(props); this.state = { table: getTable(), }; } componentWillMount() { willMount(); } componentDidMount() { didMount(); } handleClick = () => { this.setState({ table: getTable() }); }; render() { const { table: Table } = this.props; return ( <div> <div> <input type="submit" value="Generate" onClick={this.handleClick} /> {' '} <span>{getUniqueSize(this.state.table)} unique cells</span> </div> <Table table={this.state.table} toPercent={toPercent} /> </div> ); } }
src/MessageBox/__tests__/MessageBox.js
Detaysoft/react-chat-elements
import React, { Component } from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import MessageBox from '../MessageBox'; describe('MessageBox component', () => { it('should render without issues', () => { const component = shallow(<MessageBox status='read'/>); expect(component.length).toBe(1); expect(toJson(component)).toMatchSnapshot(); }); });
src/App.js
one19/hourmon
import React, { Component } from 'react'; import { GOLD, BLACK } from './colors'; class Counter extends Component { constructor(props) { super(props); this.state = { counter: 0 }; this.interval = setInterval(() => this.tick(), 2000); } tick() { this.setState({ counter: this.state.counter + this.props.increment }); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <h1 style={{ color: this.props.color }}> Counter ({this.props.increment}): {this.state.counter} </h1> ); } } export class App extends Component { render() { return ( <div> <Counter increment={1} color={GOLD} /> <Counter increment={2} color={BLACK} /> </div> ); } }
pages/nosotros.js
markhker/newCyK
import React, { Component } from 'react'; import './scss/about.scss'; import Paper from 'material-ui/lib/paper'; import CardTitle from 'material-ui/lib/card/card-title'; import CardText from 'material-ui/lib/card/card-text'; import Link from '../components/Link'; import MyRawTheme from '../components/theme'; import ThemeManager from 'material-ui/lib/styles/theme-manager'; import ThemeDecorator from 'material-ui/lib/styles/theme-decorator'; const style = { fontSize: 1.5+'rem', fontWeight: 200, }; @ThemeDecorator(ThemeManager.getMuiTheme(MyRawTheme)) export default class extends Component { render() { return ( <div> <header className="about-header"> <div className="main-logo"> <a href="/"><img src="https://storage.googleapis.com/cykloud.appspot.com/static/img/tech/logo.png" alt="Logo C&K" /></a> </div> <h1>Nosotros</h1> </header> <section className="col-1 about-section-1"> <div className="col-1 col-s-20-24 col-m-22-24 col-l-20-24"> <h1 className="col-20-24">"We are your conection with the Cloud Technologies"</h1> <Paper className="col-20-24 col-m-10-24 col-l-7-24 paper" zDepth={1}> <CardTitle title="Quiénes" subtitle="Expertos" /> <CardText style={style}> Cloud & Kloud, somos un equipo de expertos en cloud computing. Nuestros compañeros trabajan por nuestro Qué y nuestro Por qué. Nos apasiona trabajar con gente emprendedora y organizaciones que produzcan trabajos excepcionales. </CardText> </Paper> <Paper className="col-20-24 col-m-10-24 col-l-7-24 paper" zDepth={1}> <CardTitle title="Qué" subtitle="Creamos" /> <CardText style={style}> Diseñamos las mejores soluciones de Cloud Computing a la medida de tu empresa. Ayudamos a tu organización a adaptarse a las nuevas tecnologías de la información, llegar más lejos y obtener todos los beneficios que la nube te ofrece. </CardText> </Paper> <Paper className="col-20-24 col-m-10-24 col-l-7-24 paper" zDepth={1}> <CardTitle title="Por qué" subtitle="Resultados" /> <CardText style={style}> Es simple. Nosotros existimos para enriquecer la calidad de vida de organizaciones y empresas. No se trata solo de hacer algo que se vea bien. Nos esforzamos y enfocamos en la acción, que genera resultados y se convierte en un cambio efectivo. </CardText> </Paper> </div> </section> <section className="col-1 standards"> <article className="col-1"> <div className="col-20-24 col-m-10-24 col-l-8-24 first"> <h2>Nuestras<br />Normas</h2> <div className="standard"> <h3>Personas sobre Ganancias</h3> <h4>No se trata de dinero</h4> <p>Nuestra norma de oro son las relaciones. Queremos trabajar con personas increíbles. Porque, para nosotros, el éxito se mide en experiencias positivas, no en la línea de fondo. Por eso, nos esforzamos en rodearnos de ambos inteligentes y apasionados miembros de equipo y clientes, esos que harán crecer nuestras mentes y corazones y no sólo nuestras carteras.</p> </div> <div className="standard"> <h3>KISS</h3> <h4>Por que es simple</h4> <p>Nuestras prácticas y soluciones son sencillas, porque sencillo = limpio = comprensible y ejecutable. Nosotros aplicamos este concepto a todos los aspectos del negocio, desde nuestro espacio de trabajo hasta los servicios que ofrecemos. También nos adherimos a la fuerza de la simplicidad cuando diseñamos y codificamos.</p> </div> <div className="standard"> <h3>Calidad sobre Cantidad</h3> <h4>Menos es más.</h4> <p>La energía mental tiene un ancho de banda agotable, por lo que concentramos nuestro tiempo y talento en un menor número de proyectos/clientes. Una mayor inversión de nuestra parte ,pero no estamos creando una pequeña fábrica de servicios de IT. Además priorizar la calidad sobre la cantidad apoya nuestros otros valores fundamentales.</p> </div> <div className="standard"> <h3>Haz más Preguntas</h3> <h4>Exige mejores respuestas</h4> <p>Creemos que empujar el sobre ayuda a consolidar y defender pensamientos/conceptos, y da nueva forma a la razón. Una idea o concepto fuerte resiste la prueba de estrés o será mejor en la línea de meta por haber sido objeto de escrutinio.</p> </div> </div> <div className="col-20-24 col-m-10-24 col-l-8-24 second"> <div className="standard"> <h3>Haz lo Mejor</h3> <h4>Siempre hay espacio para mejorar.</h4> <p>Este valor se mantiene constante en nuestras mentes, una intención definida en todos los puntos de contacto de nuestra organización. La llave que impulsa nuestra toma de decisiones y, en última instancia, nuestro producto final. Debido a que cada uno de nosotros acepta el reto de seguir subiendo la escalera de la grandeza.</p> </div> <div className="standard"> <h3>Mantenlo Real</h3> <h4>Las personas son personas</h4> <p>Y así es como los tratamos, independientemente de su rango o asociación. Todo el mundo merece respeto, transparencia y honestidad - los tres pilares de cada interacción que tenemos con colegas y clientes. Bono: el trabajo, y la vida en general, se vuelven más fáciles y productivas.</p> </div> <div className="standard"> <h3>Nunca Dejes de Aprender</h3> <h4>Rétate a ti mismo.</h4> <p>Cuando niños, éramos alimentados de educación a la fuerza, pero a medida que crecemos, nuestras interacciones académicas son menos frecuentes. A menos que las busques. Animamos a nuestro equipo a aprender: para perseguir sus pasiones, escucharnos unos a otros y acceder a nuevos conocimientos en conferencias, la biblioteca, los blogs y a través de otros medios. Ah, y para hacer más preguntas.</p> </div> <div className="standard"> <h3>Trabaja para Vivir</h3> <h4>La vida es primero.</h4> <p>El trabajo en sólo una pieza en el gráfico circular de la vida, y nuestro objetivo es que siga siendo así. Ya que somos tan fuertes como nuestro equipo, les animamos a trabajar duro, jugar duro y descansar duro. Siempre que podemos, les ayudamos a cultivar sus pasiones. Y tenemos en cuenta sus intereses y fortalezas cuando nos ponemos a trabajar. Después de todo, si amas lo que haces, en realidad nunca trabajas.</p> </div> </div> </article> </section> </div> ); } }
generators/app/templates/src/components/hello-world.js
trigun539/generator-ep-react-simple
import React, { Component } from 'react'; export default class HelloWorld extends Component { render () { return <h1>Hello World</h1>; } }
src/pages/Bookmarks/index.js
bogas04/SikhJS
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import styled from 'react-emotion'; import { BOOKMARK_TYPES } from '../../constants'; import { clearAllBookmarks, getAllBookmarks, updateBookmarkTitle } from '../../bookmarks'; import { Textfield, Button, Toolbar, Loader } from '../../components'; import { Card, CardText, CardActions, CardTitle } from '../../components/Card'; const { SGGS, SHABAD } = BOOKMARK_TYPES; const SearchCardWrapper = styled.div` display: flex; flex-wrap: wrap; justify-content: center; flex-direction: column; width: 100%; align-items: center; `; const StyledLink = styled(Link)` text-decoration: none; color: teal; cursor: pointer; `; const SearchCard = ({ data: { title, key, value }, onTitleChange }) => ( <Card style={{ width: '30vw' }}> <CardTitle style={{ textTransform: 'capitalize' }}>{title}</CardTitle> <CardText> Edit Title <Textfield className="input" label={title} onChange={onTitleChange} type="text" defaultValue={title} /> </CardText> <CardActions> {key === SHABAD && <StyledLink to={`/shabads/${value}`}>Open Shabad</StyledLink>} {key === SGGS && <StyledLink to={`/SGGS/${value}`}>Open Ang {value}</StyledLink>} </CardActions> </Card> ); SearchCard.propTypes = { data: PropTypes.object, onTitleChange: PropTypes.func, }; const SearchCards = ({ items, onTitleChange }) => ( <SearchCardWrapper> { items .map(b => ( <SearchCard key={b.id} data={b} onTitleChange={({ currentTarget: { value: title = b.title } }) => onTitleChange({ ...b, title })} /> )) } </SearchCardWrapper> ); export default class Bookmarks extends Component { constructor (p) { super(p); this.state = { bookmarks: [], loading: true, keyword: '', }; getAllBookmarks() .then(bookmarks => this.setState({ bookmarks, loading: false })) .catch(err => console.error(err)); this.handleUpdateBookmark = this.handleUpdateBookmark.bind(this); this.handleClearAllBookmarks = this.handleClearAllBookmarks.bind(this); this.handleUpdateKeyword = this.handleUpdateKeyword.bind(this); } render () { let { loading, bookmarks, keyword } = this.state; if (keyword !== '') { bookmarks = bookmarks.filter(e => e.title.toLowerCase().indexOf(keyword.toLowerCase()) > -1); } return ( <div> <Toolbar title={`Bookmarks`}> <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}> <Textfield onChange={this.handleUpdateKeyword} placeholder="Search" /> <Button noBorder onClick={this.handleClearAllBookmarks}>Clear All Bookmarks</Button> </div> </Toolbar> <Loader loading={loading}>{ bookmarks.length === 0 ? <h1 style={{ textAlign: 'center' }}>No Bookmarks Found</h1> : <SearchCards items={bookmarks} onTitleChange={this.handleUpdateBookmark} /> } </Loader> </div> ); } handleUpdateBookmark ({ key, value, id, timestamp, title }) { updateBookmarkTitle({ key, value, id, timestamp, title }) .then(e => console.log(e)) .catch(err => console.error(err)); } handleClearAllBookmarks () { clearAllBookmarks() .then(() => this.setState({ bookmarks: [] })) .catch(err => console.error(err)); } handleUpdateKeyword ({ currentTarget: { value: keyword } }) { this.setState({ keyword }); } }
src/routes/Dashboard/View.js
cesine/rickshaw-react-sample
import React from 'react'; import PropTypes from 'prop-types'; import ChartByDayOfTheWeek from '../../components/ChartByDayOfTheWeek'; import ChartByHour from '../../components/ChartByHour'; import ChartDaysWithout from '../../components/ChartDaysWithout'; import ChartHistogram from '../../components/ChartHistogram'; import ChartPerDay from '../../components/ChartPerDay'; import ChartPerWeek from '../../components/ChartPerWeek'; import './Dashboard.css'; export default function Dashboard(props) { const { match: { params, }, history, deploysByHour, deploysPerDay, deploysPerWeek, deploysByDayOfTheWeek, deploysPerDayHistogram, } = props; function onDragZoom({ start, end }) { console.log('onDragZoom', start, end); history.push(`/start/${start.year}/${start.week}/${start.weekday}/end/${end.year}/${end.week}/${end.weekday}`); props.filterByStartAndEnd({ start, end }); } const style = { // eslint-disable-next-line no-undef height: window.innerHeight, }; const rows = 3; const columns = 2; return ( <div className="dashboard" style={style} > <div className="row"> <ChartByHour className="column" rowCount={rows} colCount={columns} title="Deploys by Hour" data={deploysByHour} params={params} /> <ChartPerDay className="column" rowCount={rows} colCount={columns} title="Deploys per Day" onDragZoom={onDragZoom} data={deploysPerDay} params={params} /> </div> <div className="row"> <ChartByDayOfTheWeek className="column" rowCount={rows} colCount={columns} title="Deploys by Day of the Week" data={deploysByDayOfTheWeek} params={params} /> <ChartPerWeek className="column" rowCount={rows} colCount={columns} title="Deploys per Week" onDragZoom={onDragZoom} data={deploysPerWeek} params={params} /> </div> <div className="row"> <ChartDaysWithout className="column" rowCount={rows} colCount={columns} title="Monday-Friday without Deploys" onDragZoom={onDragZoom} data={deploysPerDay} params={params} /> <ChartHistogram className="column" rowCount={rows} colCount={columns} title="Monday-Friday deploy frequency" data={deploysPerDayHistogram} params={params} /> </div> </div>); } Dashboard.propTypes = { history: PropTypes.shape({}).isRequired, match: PropTypes.shape({ parmams: PropTypes.shape({}), }).isRequired, filterByStartAndEnd: PropTypes.func.isRequired, deploysByHour: PropTypes.arrayOf(PropTypes.shape({})).isRequired, deploysPerDay: PropTypes.arrayOf(PropTypes.shape({})).isRequired, deploysByDayOfTheWeek: PropTypes.arrayOf(PropTypes.shape({})).isRequired, deploysPerWeek: PropTypes.arrayOf(PropTypes.shape({})).isRequired, deploysPerDayHistogram: PropTypes.arrayOf(PropTypes.shape({})).isRequired, };
src/front-end/js/pages/Registration.js
aleksey-gonchar/emmofret
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import _ from 'lodash' import * as AppActions from '../actions/AppActions.js' import FullNameInput from '../components/inputs/FullNameInput.js' import EmailInput from '../components/inputs/EmailInput.js' import PasswordInput from '../components/inputs/PasswordInput.js' import { Modal, Button } from 'react-bootstrap' const { Header, Body, Title, Footer, Dialog } = Modal function actions (dispatch) { return { actions: { signUp: bindActionCreators(AppActions.signUp, dispatch) } } } @connect(null, actions) export default class SignUpModal extends React.Component { static propTypes = { actions: React.PropTypes.object } constructor (props) { super(props) this.state = { form: { fullName: '', email: '', password: '' }, isFormCompleted: false } this.signUp = this.signUp.bind(this) this.checkSubmitBtnState = _.debounce(this.checkSubmitBtnState, 200) this.onChangeFormState = this.onChangeFormState.bind(this) this.submitOnReturn = this.submitOnReturn.bind(this) } checkSubmitBtnState () { let isAllValid = _.every(this.state.form, (prop, key) => { if (_.isObject(prop)) { return prop.isValid } else { return false } }) this.setState({ isFormCompleted: isAllValid }) } onChangeFormState (propName) { return (newValue) => { let state = { form: this.state.form } state.form[propName] = newValue this.setState(state) this.checkSubmitBtnState() } } signUp () { const payload = { user: { firstName: this.state.form.fullName.firstName, lastName: this.state.form.fullName.lastName, email: this.state.form.email.value, password: this.state.form.password.value }, shake: { selector: '[data-class="Registration"]', style: 'horizontal' } } this.props.actions.signUp(payload) } submitOnReturn (e) { if (e.charCode === 13 && this.state.isFormCompleted) { this.signUp() } } render () { let btnProps = {} if (this.state.isFormCompleted) { btnProps.disabled = false } else { btnProps.disabled = true } let inputProps = { onKeyPress: this.submitOnReturn } return ( <div className='modal-static'> <Dialog onHide={ () => {} } bsSize='sm' data-class='Registration'> <Header> <Title>Sign up</Title> </Header> <Body> <FullNameInput onSave={this.onChangeFormState('fullName')} {...inputProps}/> <EmailInput onSave={this.onChangeFormState('email')} {...inputProps}/> <PasswordInput onSave={this.onChangeFormState('password')} {...inputProps}/> </Body> <Footer> <Button bsStyle='primary' onClick={this.signUp} {...btnProps}>Sign up</Button> </Footer> </Dialog> </div> ) } }
test/ButtonGroupSpec.js
mcraiganthony/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ButtonGroup from '../src/ButtonGroup'; import Button from '../src/Button'; import { shouldWarn } from './helpers'; describe('ButtonGroup', function () { it('Should output a button group', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup> <Button> Title </Button> </ButtonGroup> ); assert.equal(React.findDOMNode(instance).nodeName, 'DIV'); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group\b/)); }); it('Should add size', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup bsSize='large'> <Button> Title </Button> </ButtonGroup> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-lg\b/)); }); it('Should add vertical variation', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup vertical> <Button> Title </Button> </ButtonGroup> ); assert.equal(React.findDOMNode(instance).className.trim(), 'btn-group-vertical'); }); it('Should add block variation', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup vertical block> <Button> Title </Button> </ButtonGroup> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-block\b/)); }); it('Should warn about block without vertical', function () { ReactTestUtils.renderIntoDocument( <ButtonGroup block> <Button> Title </Button> </ButtonGroup> ); shouldWarn('The block property requires the vertical property to be set to have any effect'); }); it('Should add justified variation', function () { let instance = ReactTestUtils.renderIntoDocument( <ButtonGroup justified> <Button> Title </Button> </ButtonGroup> ); assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-justified\b/)); }); });
src/Stepper/StepConnector.spec.js
hai-cea/material-ui
/* eslint-env mocha */ import React from 'react'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import {PlainStepConnector as StepConnector} from './StepConnector'; import getMuiTheme from '../styles/getMuiTheme'; describe('<StepConnector />', () => { const muiTheme = getMuiTheme(); const themedShallow = (node) => { const context = {muiTheme, stepper: {orientation: 'horizontal'}}; return shallow(node, {context}); }; describe('rendering', () => { const wrapper = themedShallow( <StepConnector /> ); it('renders a div containing a span', () => { assert.ok(wrapper.is('div')); const line = wrapper.find('span'); assert.ok(line.length); }); it('has a top border when horizontal', () => { const line = wrapper.find('span'); assert.strictEqual(line.prop('style').borderTopWidth, 1); assert.notOk(line.prop('style').borderLeftWidth); }); it('has a left border when vertical', () => { wrapper.setContext({muiTheme, stepper: {orientation: 'vertical'}}); const line = wrapper.find('span'); assert.strictEqual(line.prop('style').borderLeftWidth, 1); assert.notOk(line.prop('style').borderTopWidth); }); }); });
src/assets/js/react/components/FontManager/FontVariantLabel.js
GravityPDF/gravity-forms-pdf-extended
/* Dependencies */ import React from 'react' import PropTypes from 'prop-types' import { sprintf } from 'sprintf-js' /** * @package Gravity PDF * @copyright Copyright (c) 2021, Blue Liquid Designs * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 6.0 */ /** * Display information for drop box font variant label * * @param label * @param font * * @since 6.0 */ const FontVariantLabel = ({ label, font }) => ( <div data-test='component-FontVariantLabel' htmlFor={'gfpdf-font-variant-' + label}> {(label === 'regular' && font === 'false') && ( <span dangerouslySetInnerHTML={{ __html: sprintf(GFPDF.fontListRegularRequired, '' + "<span class='required'>", '</span>') }} /> )} {(label === 'regular' && font === 'true') && GFPDF.fontListRegular} {label === 'italics' && GFPDF.fontListItalics} {label === 'bold' && GFPDF.fontListBold} {label === 'bolditalics' && GFPDF.fontListBoldItalics} </div> ) /** * PropTypes * * @since 6.0 */ FontVariantLabel.propTypes = { label: PropTypes.string.isRequired, font: PropTypes.string } export default FontVariantLabel
src/svg-icons/maps/local-play.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalPlay = (props) => ( <SvgIcon {...props}> <path d="M20 12c0-1.1.9-2 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-1.99.9-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2zm-4.42 4.8L12 14.5l-3.58 2.3 1.08-4.12-3.29-2.69 4.24-.25L12 5.8l1.54 3.95 4.24.25-3.29 2.69 1.09 4.11z"/> </SvgIcon> ); MapsLocalPlay = pure(MapsLocalPlay); MapsLocalPlay.displayName = 'MapsLocalPlay'; MapsLocalPlay.muiName = 'SvgIcon'; export default MapsLocalPlay;
jenkins-design-language/src/js/components/material-ui/svg-icons/maps/directions-bus.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsDirectionsBus = (props) => ( <SvgIcon {...props}> <path d="M4 16c0 .88.39 1.67 1 2.22V20c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h8v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1.78c.61-.55 1-1.34 1-2.22V6c0-3.5-3.58-4-8-4s-8 .5-8 4v10zm3.5 1c-.83 0-1.5-.67-1.5-1.5S6.67 14 7.5 14s1.5.67 1.5 1.5S8.33 17 7.5 17zm9 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm1.5-6H6V6h12v5z"/> </SvgIcon> ); MapsDirectionsBus.displayName = 'MapsDirectionsBus'; MapsDirectionsBus.muiName = 'SvgIcon'; export default MapsDirectionsBus;
kit/entry/browser.js
Mahi22/MedTantra
// Browser entry point, for Webpack. We'll grab the browser-flavoured // versions of React mounting, routing etc to hook into the DOM // ---------------------- // IMPORTS /* NPM */ // Enable async/await and generators, cross-browser import 'regenerator-runtime/runtime'; // Patch global.`fetch` so that Apollo calls to GraphQL work import 'isomorphic-fetch'; // React parts import React from 'react'; import ReactDOM from 'react-dom'; // Browser routing import { BrowserRouter } from 'react-router-dom'; // Apollo Provider. This HOC will 'wrap' our React component chain // and handle injecting data down to any listening component import { ApolloProvider } from 'react-apollo'; /* MedTantra */ // Root component. This is our 'entrypoint' into the app. If you're using // the MedTantra starter kit for the first time, `src/app.js` is where // you can start editing to add your own code. Note: This first is imported // first, since it sets up our app's settings import App from 'src/app'; // Grab the shared Apollo Client import { browserClient } from 'kit/lib/apollo'; // Custom redux store creator. This will allow us to create a store 'outside' // of Apollo, so we can apply our own reducers and make use of the Redux dev // tools in the browser import createNewStore from 'kit/lib/redux'; // ---------------------- // Create a new browser Apollo client const client = browserClient(); // Create a new Redux store const store = createNewStore(client); // Create the 'root' entry point into the app. If we have React hot loading // (i.e. if we're in development), then we'll wrap the whole thing in an // <AppContainer>. Otherwise, we'll jump straight to the browser router function doRender() { ReactDOM.hydrate( <Root />, document.getElementById('main'), ); } // The <Root> component. We'll run this as a self-contained function since // we're using a bunch of temporary vars that we can safely discard. // // If we have hot reloading enabled (i.e. if we're in development), then // we'll wrap the whole thing in <AppContainer> so that our views can respond // to code changes as needed const Root = (() => { // Wrap the component hierarchy in <BrowserRouter>, so that our children // can respond to route changes const Chain = () => ( <ApolloProvider store={store} client={client}> <BrowserRouter> <App /> </BrowserRouter> </ApolloProvider> ); // React hot reloading -- only enabled in development. This branch will // be shook from production, so we can run a `require` statement here // without fear that it'll inflate the bundle size if (module.hot) { // <AppContainer> will respond to our Hot Module Reload (HMR) changes // back from WebPack, and handle re-rendering the chain as needed const AppContainer = require('react-hot-loader').AppContainer; // Start our 'listener' at the root component, so that any changes that // occur in the hierarchy can be captured module.hot.accept('src/app', () => { // Refresh the entry point of our app, to get the changes. // eslint-disable-next-line require('src/app').default; // Re-render the hierarchy doRender(); }); return () => ( <AppContainer> <Chain /> </AppContainer> ); } return Chain; })(); doRender();
app/src/scripts/widgets/UserProfile/UserProfile.js
vyorkin/assignment
import React from 'react'; export default class UserProfile { render() { return ( <dl> <dt>Фамилия:</dt><dd>{this.props.lastName}</dd> <dt>Имя:</dt><dd>{this.props.firstName}</dd> <dt>Отчество:</dt><dd>{this.props.middleName}</dd> </dl> ); } }
src/Affix.js
pandoraui/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import AffixMixin from './AffixMixin'; const Affix = React.createClass({ mixins: [AffixMixin], render() { let holderStyle = { top: this.state.affixPositionTop, // we don't want to expose the `style` property ...this.props.style // eslint-disable-line react/prop-types }; return ( <div {...this.props} className={classNames(this.props.className, this.state.affixClass)} style={holderStyle}> {this.props.children} </div> ); } }); export default Affix;
test/test_helper.js
rickywid/micdb
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/svg-icons/av/web.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvWeb = (props) => ( <SvgIcon {...props}> <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-5 14H4v-4h11v4zm0-5H4V9h11v4zm5 5h-4V9h4v9z"/> </SvgIcon> ); AvWeb = pure(AvWeb); AvWeb.displayName = 'AvWeb'; AvWeb.muiName = 'SvgIcon'; export default AvWeb;
React-Youtube/src/components/videoDetail.js
vivekbharatha/ModernReactWithReduxCourseUdemy
import React from 'react'; const VideoDetail = ({ video }) => { if (!video) { return <div>Started the Engine, hold you sugar !</div> } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9 video-player"> <iframe src={ url } className="embed-responsive-item"> </iframe> </div> <div className="video-details"> <div>{ video.snippet.title }</div> <div>{ video.snippet.description }</div> </div> </div> ); } export default VideoDetail;
src/components/gameTimerComponent/gameTimerComponent.js
craigbilner/quizapp
'use strict'; import React from 'react'; import radium from 'radium'; class GameTimerComponent extends React.Component { constructor(props) { super(props); } timeFunc() { this.props.onTimeChange(this.props.gameTime - (this.props.timeInterval / 1000)); if (this.props.gameTime !== 0) { this.startTimer(); } } startTimer() { if (!this.props.isPaused) { this.timer = setTimeout(this.timeFunc.bind(this), this.props.timeInterval); } } clearTimer() { clearTimeout(this.timer); this.timer = 0; } componentDidMount() { this.startTimer(); } componentWillUnmount() { this.clearTimer(); } render() { if (this.props.isReset) { this.clearTimer(); this.startTimer(); } const compStyle = [ { color: this.props.baseStyles.colours.dark.primary } ]; return ( <span style={compStyle}>{this.props.gameTime}</span> ); } } GameTimerComponent.propTypes = { gameTime: React.PropTypes.number.isRequired, isPaused: React.PropTypes.bool.isRequired, isReset: React.PropTypes.bool.isRequired, onTimeChange: React.PropTypes.func, timeInterval: React.PropTypes.number.isRequired, baseStyles: React.PropTypes.object.isRequired }; GameTimerComponent.defaultProps = {}; export default radium(GameTimerComponent);
examples/dynamic-segments/app.js
upraised/react-router
import React from 'react'; import { Router, Route, Link, Redirect } from 'react-router'; var App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/user/123">Bob</Link></li> <li><Link to="/user/abc">Sally</Link></li> </ul> {this.props.children} </div> ); } }); var User = React.createClass({ render() { var { userID } = this.props.params; return ( <div className="User"> <h1>User id: {userID}</h1> <ul> <li><Link to={`/user/${userID}/tasks/foo`}>foo task</Link></li> <li><Link to={`/user/${userID}/tasks/bar`}>bar task</Link></li> </ul> {this.props.children} </div> ); } }); var Task = React.createClass({ render() { var { userID, taskID } = this.props.params; return ( <div className="Task"> <h2>User ID: {userID}</h2> <h3>Task ID: {taskID}</h3> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="user/:userID" component={User}> <Route path="tasks/:taskID" component={Task} /> <Redirect from="todos/:taskID" to="/user/:userID/tasks/:taskID" /> </Route> </Route> </Router> ), document.getElementById('example'));
node_modules/react-navigation/src/routers/__tests__/StackRouter-test.js
joan17cast/Enigma
/* @flow */ /* eslint no-shadow:0, react/no-multi-comp:0, react/display-name:0 */ import React from 'react'; import StackRouter from '../StackRouter'; import TabRouter from '../TabRouter'; import NavigationActions from '../../NavigationActions'; const ListScreen = () => <div />; const ProfileNavigator = () => <div />; ProfileNavigator.router = StackRouter({ list: { path: 'list/:id', screen: ListScreen, }, }); const MainNavigator = () => <div />; MainNavigator.router = StackRouter({ profile: { path: 'p/:id', screen: ProfileNavigator, }, }); const LoginScreen = () => <div />; const AuthNavigator = () => <div />; AuthNavigator.router = StackRouter({ login: { screen: LoginScreen, }, }); const BarScreen = () => <div />; class FooNavigator extends React.Component { static router = StackRouter({ bar: { path: 'b/:barThing', screen: BarScreen, }, }); render() { return <div />; } } const PersonScreen = () => <div />; const TestStackRouter = StackRouter({ main: { screen: MainNavigator, }, auth: { screen: AuthNavigator, }, person: { path: 'people/:id', screen: PersonScreen, }, foo: { path: 'fo/:fooThing', screen: FooNavigator, }, }); describe('StackRouter', () => { test('Gets the active screen for a given state', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ foo: { screen: FooScreen, }, bar: { screen: BarScreen, }, }); expect( router.getComponentForState({ index: 0, routes: [ { key: 'a', routeName: 'foo' }, { key: 'b', routeName: 'bar' }, { key: 'c', routeName: 'foo' }, ], }) ).toBe(FooScreen); expect( router.getComponentForState({ index: 1, routes: [ { key: 'a', routeName: 'foo' }, { key: 'b', routeName: 'bar' }, ], }) ).toBe(BarScreen); }); test('Handles getScreen in getComponentForState', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ foo: { getScreen: () => FooScreen, }, bar: { getScreen: () => BarScreen, }, }); expect( router.getComponentForState({ index: 0, routes: [ { key: 'a', routeName: 'foo' }, { key: 'b', routeName: 'bar' }, { key: 'c', routeName: 'foo' }, ], }) ).toBe(FooScreen); expect( router.getComponentForState({ index: 1, routes: [ { key: 'a', routeName: 'foo' }, { key: 'b', routeName: 'bar' }, ], }) ).toBe(BarScreen); }); test('Gets the screen for given route', () => { const FooScreen = () => <div />; const BarScreen = class extends React.Component { render() { return <div />; } }; const BazScreen = class extends React.Component { render() { return <div />; } }; const router = StackRouter({ foo: { screen: FooScreen, }, bar: { screen: BarScreen, }, baz: { screen: BazScreen, }, }); expect(router.getComponentForRouteName('foo')).toBe(FooScreen); expect(router.getComponentForRouteName('bar')).toBe(BarScreen); expect(router.getComponentForRouteName('baz')).toBe(BazScreen); }); test('Handles getScreen in getComponent', () => { const FooScreen = () => <div />; const BarScreen = class extends React.Component { render() { return <div />; } }; const BazScreen = class extends React.Component { render() { return <div />; } }; const router = StackRouter({ foo: { getScreen: () => FooScreen, }, bar: { getScreen: () => BarScreen, }, baz: { getScreen: () => BazScreen, }, }); expect(router.getComponentForRouteName('foo')).toBe(FooScreen); expect(router.getComponentForRouteName('bar')).toBe(BarScreen); expect(router.getComponentForRouteName('baz')).toBe(BazScreen); }); test('Parses simple paths', () => { expect(AuthNavigator.router.getActionForPathAndParams('login')).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'login', }); }); test('Parses paths with a param', () => { expect(TestStackRouter.getActionForPathAndParams('people/foo')).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'person', params: { id: 'foo', }, }); }); test('Parses paths with a query', () => { expect( TestStackRouter.getActionForPathAndParams('people/foo?code=test&foo=bar') ).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'person', params: { id: 'foo', code: 'test', foo: 'bar', }, }); }); test('Parses paths with an empty query value', () => { expect( TestStackRouter.getActionForPathAndParams('people/foo?code=&foo=bar') ).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'person', params: { id: 'foo', code: '', foo: 'bar', }, }); }); test('Correctly parses a path without arguments into an action chain', () => { const uri = 'auth/login'; const action = TestStackRouter.getActionForPathAndParams(uri); expect(action).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'auth', action: { type: NavigationActions.NAVIGATE, routeName: 'login', }, }); }); test('Correctly parses a path with arguments into an action chain', () => { const uri = 'main/p/4/list/10259959195'; const action = TestStackRouter.getActionForPathAndParams(uri); expect(action).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'main', action: { type: NavigationActions.NAVIGATE, routeName: 'profile', params: { id: '4', }, action: { type: NavigationActions.NAVIGATE, routeName: 'list', params: { id: '10259959195', }, }, }, }); }); test('Correctly returns null action for non-existent path', () => { const uri = 'asdf/1234'; const action = TestStackRouter.getActionForPathAndParams(uri); expect(action).toEqual(null); }); test('Correctly returns action chain for partially matched path', () => { const uri = 'auth/login/2'; const action = TestStackRouter.getActionForPathAndParams(uri); expect(action).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'auth', action: { type: NavigationActions.NAVIGATE, routeName: 'login', }, }); }); test('Correctly returns action for path with multiple parameters', () => { const path = 'fo/22/b/hello'; const action = TestStackRouter.getActionForPathAndParams(path); expect(action).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'foo', params: { fooThing: '22', }, action: { type: NavigationActions.NAVIGATE, routeName: 'bar', params: { barThing: 'hello', }, }, }); }); test('Pushes other navigators when navigating to an unopened route name', () => { const Bar = () => <div />; Bar.router = StackRouter({ baz: { screen: () => <div /> }, qux: { screen: () => <div /> }, }); const TestRouter = StackRouter({ foo: { screen: () => <div /> }, bar: { screen: Bar }, }); const initState = TestRouter.getStateForAction(NavigationActions.init()); expect(initState).toEqual({ index: 0, routes: [{ key: 'Init-id-0-0', routeName: 'foo' }], }); const pushedState = TestRouter.getStateForAction( NavigationActions.navigate({ routeName: 'qux' }), initState ); // $FlowFixMe expect(pushedState.index).toEqual(1); // $FlowFixMe expect(pushedState.routes[1].index).toEqual(1); // $FlowFixMe expect(pushedState.routes[1].routes[1].routeName).toEqual('qux'); }); test('Handle basic stack logic for plain components', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ Foo: { screen: FooScreen, }, Bar: { screen: BarScreen, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); expect(state).toEqual({ index: 0, routes: [ { key: 'Init-id-0-4', routeName: 'Foo', }, ], }); const state2 = router.getStateForAction( { type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { name: 'Zoom' }, }, state ); expect(state2 && state2.index).toEqual(1); expect(state2 && state2.routes[1].routeName).toEqual('Bar'); expect(state2 && state2.routes[1].params).toEqual({ name: 'Zoom' }); expect(state2 && state2.routes.length).toEqual(2); const state3 = router.getStateForAction( { type: NavigationActions.BACK }, state2 ); expect(state3).toEqual({ index: 0, routes: [ { key: 'Init-id-0-4', routeName: 'Foo', }, ], }); }); test('Handle basic stack logic for components with router', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; BarScreen.router = StackRouter({ Xyz: { screen: () => null, }, }); const router = StackRouter({ Foo: { screen: FooScreen, }, Bar: { screen: BarScreen, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); expect(state).toEqual({ index: 0, routes: [ { key: 'Init-id-0-6', routeName: 'Foo', }, ], }); const state2 = router.getStateForAction( { type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { name: 'Zoom' }, }, state ); expect(state2 && state2.index).toEqual(1); expect(state2 && state2.routes[1].routeName).toEqual('Bar'); expect(state2 && state2.routes[1].params).toEqual({ name: 'Zoom' }); expect(state2 && state2.routes.length).toEqual(2); const state3 = router.getStateForAction( { type: NavigationActions.BACK }, state2 ); expect(state3).toEqual({ index: 0, routes: [ { key: 'Init-id-0-6', routeName: 'Foo', }, ], }); }); test('Handle goBack identified by key', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ Foo: { screen: FooScreen, }, Bar: { screen: BarScreen, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction( { type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { name: 'Zoom' }, }, state ); const state3 = router.getStateForAction( { type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { name: 'Foo' }, }, state2 ); const state4 = router.getStateForAction( { type: NavigationActions.BACK, key: 'wrongKey' }, state3 ); expect(state3).toEqual(state4); const state5 = router.getStateForAction( { type: NavigationActions.BACK, key: state3 && state3.routes[1].key }, state4 ); expect(state5).toEqual(state); }); test('Handle initial route navigation', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter( { Foo: { screen: FooScreen, }, Bar: { screen: BarScreen, }, }, { initialRouteName: 'Bar' } ); const state = router.getStateForAction({ type: NavigationActions.INIT }); expect(state).toEqual({ index: 0, routes: [ { key: 'Init-id-0-12', routeName: 'Bar', }, ], }); }); test('Initial route params appear in nav state', () => { const FooScreen = () => <div />; const router = StackRouter( { Foo: { screen: FooScreen, }, }, { initialRouteName: 'Bar', initialRouteParams: { foo: 'bar' } } ); const state = router.getStateForAction({ type: NavigationActions.INIT }); expect(state).toEqual({ index: 0, routes: [ { key: 'Init-id-0-13', routeName: 'Bar', params: { foo: 'bar' }, }, ], }); }); test('Action params appear in nav state', () => { const FooScreen = () => <div />; const BarScreen = () => <div />; const router = StackRouter({ Foo: { screen: FooScreen, }, Bar: { screen: BarScreen, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction( { type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { bar: '42' }, }, state ); expect(state2).not.toBeNull(); expect(state2 && state2.index).toEqual(1); expect(state2 && state2.routes[1].params).toEqual({ bar: '42' }); }); test('Handles the SetParams action', () => { const router = StackRouter( { Foo: { screen: () => <div />, }, Bar: { screen: () => <div />, }, }, { initialRouteName: 'Bar', initialRouteParams: { name: 'Zoo' }, } ); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction( { type: NavigationActions.SET_PARAMS, params: { name: 'Qux' }, key: 'Init-id-0-16', }, state ); expect(state2 && state2.index).toEqual(0); expect(state2 && state2.routes[0].params).toEqual({ name: 'Qux' }); }); test('Handles the setParams action with nested routers', () => { const ChildNavigator = () => <div />; const GrandChildNavigator = () => <div />; GrandChildNavigator.router = StackRouter({ Quux: { screen: () => <div /> }, Corge: { screen: () => <div /> }, }); ChildNavigator.router = TabRouter({ Baz: { screen: GrandChildNavigator }, Qux: { screen: () => <div /> }, }); const router = StackRouter({ Foo: { screen: ChildNavigator }, Bar: { screen: () => <div /> }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction( { type: NavigationActions.SET_PARAMS, params: { name: 'foobar' }, key: 'Init-id-0-17', }, state ); expect(state2 && state2.index).toEqual(0); /* $FlowFixMe */ expect(state2 && state2.routes[0].routes[0].routes).toEqual([ { key: 'Init-id-0-17', routeName: 'Quux', params: { name: 'foobar' }, }, ]); }); test('Handles the reset action', () => { const router = StackRouter({ Foo: { screen: () => <div />, }, Bar: { screen: () => <div />, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction( { type: NavigationActions.RESET, actions: [ { type: NavigationActions.NAVIGATE, routeName: 'Foo', params: { bar: '42' }, }, { type: NavigationActions.NAVIGATE, routeName: 'Bar' }, ], index: 1, }, state ); expect(state2 && state2.index).toEqual(1); expect(state2 && state2.routes[0].params).toEqual({ bar: '42' }); expect(state2 && state2.routes[0].routeName).toEqual('Foo'); expect(state2 && state2.routes[1].routeName).toEqual('Bar'); }); test('Handles the reset action with nested Router', () => { const ChildRouter = TabRouter({ baz: { screen: () => <div />, }, }); const ChildNavigator = () => <div />; ChildNavigator.router = ChildRouter; const router = StackRouter({ Foo: { screen: ChildNavigator, }, Bar: { screen: () => <div />, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction( { type: NavigationActions.RESET, actions: [{ type: NavigationActions.NAVIGATE, routeName: 'Foo' }], index: 0, }, state ); expect(state2 && state2.index).toEqual(0); expect(state2 && state2.routes[0].routeName).toEqual('Foo'); /* $FlowFixMe */ expect(state2 && state2.routes[0].routes[0].routeName).toEqual('baz'); }); test('Handles the reset action with a key', () => { const ChildRouter = StackRouter({ baz: { screen: () => <div />, }, }); const ChildNavigator = () => <div />; ChildNavigator.router = ChildRouter; const router = StackRouter({ Foo: { screen: ChildNavigator, }, Bar: { screen: () => <div />, }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction( { type: NavigationActions.NAVIGATE, routeName: 'Foo', action: { type: NavigationActions.NAVIGATE, routeName: 'baz' }, }, state ); const state3 = router.getStateForAction( { type: NavigationActions.RESET, key: 'Init', actions: [{ type: NavigationActions.NAVIGATE, routeName: 'Foo' }], index: 0, }, state2 ); const state4 = router.getStateForAction( { type: NavigationActions.RESET, key: null, actions: [{ type: NavigationActions.NAVIGATE, routeName: 'Bar' }], index: 0, }, state3 ); expect(state4 && state4.index).toEqual(0); expect(state4 && state4.routes[0].routeName).toEqual('Bar'); }); test('Handles the navigate action with params and nested StackRouter', () => { const ChildNavigator = () => <div />; ChildNavigator.router = StackRouter({ Baz: { screen: () => <div /> } }); const router = StackRouter({ Foo: { screen: () => <div /> }, Bar: { screen: ChildNavigator }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction( { type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { foo: '42' }, }, state ); expect(state2 && state2.routes[1].params).toEqual({ foo: '42' }); /* $FlowFixMe */ expect(state2 && state2.routes[1].routes).toEqual([ /* $FlowFixMe */ expect.objectContaining({ routeName: 'Baz', params: { foo: '42' }, }), ]); }); test('Handles the navigate action with params and nested TabRouter', () => { const ChildNavigator = () => <div />; ChildNavigator.router = TabRouter({ Baz: { screen: () => <div /> }, Boo: { screen: () => <div /> }, }); const router = StackRouter({ Foo: { screen: () => <div /> }, Bar: { screen: ChildNavigator }, }); const state = router.getStateForAction({ type: NavigationActions.INIT }); const state2 = router.getStateForAction( { type: NavigationActions.NAVIGATE, routeName: 'Bar', params: { foo: '42' }, }, state ); expect(state2 && state2.routes[1].params).toEqual({ foo: '42' }); /* $FlowFixMe */ expect(state2 && state2.routes[1].routes).toEqual([ { key: 'Baz', routeName: 'Baz', params: { foo: '42' }, }, { key: 'Boo', routeName: 'Boo', params: { foo: '42' }, }, ]); }); test('Handles empty URIs', () => { const router = StackRouter( { Foo: { screen: () => <div />, }, Bar: { screen: () => <div />, }, }, { initialRouteName: 'Bar' } ); const action = router.getActionForPathAndParams(''); expect(action).toEqual({ type: NavigationActions.NAVIGATE, routeName: 'Bar', }); let state = null; if (action) { state = router.getStateForAction(action); } expect(state && state.index).toEqual(0); expect(state && state.routes[0]).toEqual( // $FlowFixMe expect.objectContaining({ routeName: 'Bar', type: undefined, }) ); }); test('Gets deep path', () => { const ScreenA = () => <div />; const ScreenB = () => <div />; ScreenA.router = StackRouter({ Boo: { path: 'boo', screen: ScreenB }, Baz: { path: 'baz/:bazId', screen: ScreenB }, }); const router = StackRouter({ Foo: { path: 'f/:id', screen: ScreenA, }, Bar: { screen: ScreenB, }, }); const state = { index: 0, routes: [ { index: 1, key: 'Foo', routeName: 'Foo', params: { id: '123', }, routes: [ { key: 'Boo', routeName: 'Boo' }, { key: 'Baz', routeName: 'Baz', params: { bazId: '321' } }, ], }, { key: 'Bar', routeName: 'Bar' }, ], }; const { path, params } = router.getPathAndParamsForState(state); expect(path).toEqual('f/123/baz/321'); /* $FlowFixMe: params.id has to exist */ expect(params.id).toEqual('123'); /* $FlowFixMe: params.bazId has to exist */ expect(params.bazId).toEqual('321'); }); test('Maps old actions (uses "Handles the reset action" test)', () => { const router = StackRouter({ Foo: { screen: () => <div />, }, Bar: { screen: () => <div />, }, }); /* $FlowFixMe: these are for deprecated action names */ const state = router.getStateForAction({ type: 'Init' }); /* $FlowFixMe: these are for deprecated action names */ const state2 = router.getStateForAction( { type: 'Reset', actions: [ { type: 'Navigate', routeName: 'Foo', params: { bar: '42' } }, { type: 'Navigate', routeName: 'Bar' }, ], index: 1, }, state ); expect(state2 && state2.index).toEqual(1); expect(state2 && state2.routes[0].params).toEqual({ bar: '42' }); expect(state2 && state2.routes[0].routeName).toEqual('Foo'); expect(state2 && state2.routes[1].routeName).toEqual('Bar'); }); });
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ObjectDestructuring.js
GreenGremlin/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load() { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-object-destructuring"> {this.state.users.map(user => { const { id, ...rest } = user; // eslint-disable-next-line no-unused-vars const [{ name, ...innerRest }] = [{ ...rest }]; return <div key={id}>{name}</div>; })} </div> ); } }
src/components/Image/Image.js
dialogs/dialog-web-components
/* * Copyright 2019 dialog LLC <info@dlg.im> * @flow */ import React from 'react'; import classNames from 'classnames'; import getImageSize from '../../utils/getImageSize'; import ImagePreloader, { type ImagePreloaderState, STATE_SUCCESS, } from '../ImagePreloader/ImagePreloader'; import styles from './Image.css'; export type ImageProps = { className?: string, src: ?string, id?: string, alt?: ?string, preview?: ?string, width: number, height: number, maxWidth: number, maxHeight: number, onClick?: (event: SyntheticMouseEvent<>) => mixed, }; function Image(props: ImageProps) { return ( <ImagePreloader src={props.src}> {({ state, src }: ImagePreloaderState) => { const { width, height } = getImageSize( props.width, props.height, props.maxWidth, props.maxHeight, ); const className = classNames( styles.container, { [styles.loaded]: state === STATE_SUCCESS, }, props.className, ); const source = state === STATE_SUCCESS ? src : props.preview; return ( <div className={className} title={props.alt} style={{ width, height }} > {source ? ( <img id={props.id} src={source} width={width} height={height} alt={props.alt} onClick={props.onClick} className={styles.image} /> ) : null} </div> ); }} </ImagePreloader> ); } Image.defaultProps = { maxWidth: 400, maxHeight: 400, }; export default Image;
src/svg-icons/device/settings-system-daydream.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSettingsSystemDaydream = (props) => ( <SvgIcon {...props}> <path d="M9 16h6.5c1.38 0 2.5-1.12 2.5-2.5S16.88 11 15.5 11h-.05c-.24-1.69-1.69-3-3.45-3-1.4 0-2.6.83-3.16 2.02h-.16C7.17 10.18 6 11.45 6 13c0 1.66 1.34 3 3 3zM21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02z"/> </SvgIcon> ); DeviceSettingsSystemDaydream = pure(DeviceSettingsSystemDaydream); DeviceSettingsSystemDaydream.displayName = 'DeviceSettingsSystemDaydream'; DeviceSettingsSystemDaydream.muiName = 'SvgIcon'; export default DeviceSettingsSystemDaydream;
src/containers/Home/Home.js
trueter/react-redux-universal-hot-example
import React, { Component } from 'react'; import { Link } from 'react-router'; import { CounterButton, GithubButton } from 'components'; import config from '../../config'; import Helmet from 'react-helmet'; export default class Home extends Component { render() { const styles = require('./Home.scss'); // require the logo image both from client and server const logoImage = require('./logo.png'); return ( <div className={styles.home}> <Helmet title="Home"/> <div className={styles.masthead}> <div className="container"> <div className={styles.logo}> <p> <img src={logoImage}/> </p> </div> <h1>{config.app.title}</h1> <h2>{config.app.description}</h2> <p> <a className={styles.github} href="https://github.com/erikras/react-redux-universal-hot-example" target="_blank"> <i className="fa fa-github"/> View on Github </a> </p> <GithubButton user="erikras" repo="react-redux-universal-hot-example" type="star" width={160} height={30} count large/> <GithubButton user="erikras" repo="react-redux-universal-hot-example" type="fork" width={160} height={30} count large/> <p className={styles.humility}> Created and maintained by <a href="https://twitter.com/erikras" target="_blank">@erikras</a>. </p> </div> </div> <div className="container"> <div className={styles.counterContainer}> <CounterButton multireducerKey="counter1"/> <CounterButton multireducerKey="counter2"/> <CounterButton multireducerKey="counter3"/> </div> <p>This starter boilerplate app uses the following technologies:</p> <ul> <li> <del>Isomorphic</del> {' '} <a href="https://medium.com/@mjackson/universal-javascript-4761051b7ae9">Universal</a> rendering </li> <li>Both client and server make calls to load data from separate API server</li> <li><a href="https://github.com/facebook/react" target="_blank">React</a></li> <li><a href="https://github.com/rackt/react-router" target="_blank">React Router</a></li> <li><a href="http://expressjs.com" target="_blank">Express</a></li> <li><a href="http://babeljs.io" target="_blank">Babel</a> for ES6 and ES7 magic</li> <li><a href="http://webpack.github.io" target="_blank">Webpack</a> for bundling</li> <li><a href="http://webpack.github.io/docs/webpack-dev-middleware.html" target="_blank">Webpack Dev Middleware</a> </li> <li><a href="https://github.com/glenjamin/webpack-hot-middleware" target="_blank">Webpack Hot Middleware</a></li> <li><a href="https://github.com/rackt/redux" target="_blank">Redux</a>'s futuristic <a href="https://facebook.github.io/react/blog/2014/05/06/flux.html" target="_blank">Flux</a> implementation </li> <li><a href="https://github.com/gaearon/redux-devtools" target="_blank">Redux Dev Tools</a> for next generation DX (developer experience). Watch <a href="https://www.youtube.com/watch?v=xsSnOQynTHs" target="_blank">Dan Abramov's talk</a>. </li> <li><a href="https://github.com/rackt/redux-router" target="_blank">Redux Router</a> Keep your router state in your Redux store </li> <li><a href="http://eslint.org" target="_blank">ESLint</a> to maintain a consistent code style</li> <li><a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state in Redux </li> <li><a href="https://github.com/erikras/multireducer" target="_blank">multireducer</a> combine several identical reducer states into one key-based reducer</li> <li><a href="https://github.com/webpack/style-loader" target="_blank">style-loader</a> and <a href="https://github.com/jtangelder/sass-loader" target="_blank">sass-loader</a> to allow import of stylesheets </li> <li><a href="https://github.com/shakacode/bootstrap-sass-loader" target="_blank">bootstrap-sass-loader</a> and <a href="https://github.com/gowravshekar/font-awesome-webpack" target="_blank">font-awesome-webpack</a> to customize Bootstrap and FontAwesome </li> <li><a href="http://socket.io/">socket.io</a> for real-time communication</li> </ul> <h3>Features demonstrated in this project</h3> <dl> <dt>Multiple components subscribing to same redux store slice</dt> <dd> The <code>App.js</code> that wraps all the pages contains an <code>InfoBar</code> component that fetches data from the server initially, but allows for the user to refresh the data from the client. <code>About.js</code> contains a <code>MiniInfoBar</code> that displays the same data. </dd> <dt>Server-side data loading</dt> <dd> The <Link to="/widgets">Widgets page</Link> demonstrates how to fetch data asynchronously from some source that is needed to complete the server-side rendering. <code>Widgets.js</code>'s <code>asyncConnect()</code> function is called before the widgets page is loaded, on either the server or the client, allowing all the widget data to be loaded and ready for the page to render. </dd> <dt>Data loading errors</dt> <dd> The <Link to="/widgets">Widgets page</Link> also demonstrates how to deal with data loading errors in Redux. The API endpoint that delivers the widget data intentionally fails 33% of the time to highlight this. The <code>clientMiddleware</code> sends an error action which the <code>widgets</code> reducer picks up and saves to the Redux state for presenting to the user. </dd> <dt>Session based login</dt> <dd> On the <Link to="/login">Login page</Link> you can submit a username which will be sent to the server and stored in the session. Subsequent refreshes will show that you are still logged in. </dd> <dt>Redirect after state change</dt> <dd> After you log in, you will be redirected to a Login Success page. This <strike>magic</strike> logic is performed in <code>componentWillReceiveProps()</code> in <code>App.js</code>, but it could be done in any component that listens to the appropriate store slice, via Redux's <code>@connect</code>, and pulls the router from the context. </dd> <dt>Auth-required views</dt> <dd> The aforementioned Login Success page is only visible to you if you are logged in. If you try to <Link to="/loginSuccess">go there</Link> when you are not logged in, you will be forwarded back to this home page. This <strike>magic</strike> logic is performed by the <code>onEnter</code> hook within <code>routes.js</code>. </dd> <dt>Forms</dt> <dd> The <Link to="/survey">Survey page</Link> uses the still-experimental <a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state inside the Redux store. This includes immediate client-side validation. </dd> <dt>WebSockets / socket.io</dt> <dd> The <Link to="/chat">Chat</Link> uses the socket.io technology for real-time communication between clients. You need to <Link to="/login">login</Link> first. </dd> </dl> <h3>From the author</h3> <p> I cobbled this together from a wide variety of similar "starter" repositories. As I post this in June 2015, all of these libraries are right at the bleeding edge of web development. They may fall out of fashion as quickly as they have come into it, but I personally believe that this stack is the future of web development and will survive for several years. I'm building my new projects like this, and I recommend that you do, too. </p> <p>Thanks for taking the time to check this out.</p> <p>– Erik Rasmussen</p> </div> </div> ); } }
app/routes.js
ndnhat/te-starter
'use strict'; import React from 'react'; import Router from 'react-router'; let { Route, DefaultRoute, NotFoundRoute } = Router; // -- Import base components import Layout from './components/layout'; import Login from './components/auth/login'; export default ( <Route handler={Layout} path='/'> <Route name='login' handler={Login} /> </Route> );
app/javascript/flavours/glitch/features/getting_started_misc/index.js
im-in-space/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Column from 'flavours/glitch/features/ui/components/column'; import ColumnBackButtonSlim from 'flavours/glitch/components/column_back_button_slim'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ColumnLink from 'flavours/glitch/features/ui/components/column_link'; import ColumnSubheading from 'flavours/glitch/features/ui/components/column_subheading'; import { openModal } from 'flavours/glitch/actions/modal'; import { connect } from 'react-redux'; const messages = defineMessages({ heading: { id: 'column.heading', defaultMessage: 'Misc' }, subheading: { id: 'column.subheading', defaultMessage: 'Miscellaneous options' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, info: { id: 'navigation_bar.info', defaultMessage: 'Extended information' }, show_me_around: { id: 'getting_started.onboarding', defaultMessage: 'Show me around' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned posts' }, info: { id: 'navigation_bar.info', defaultMessage: 'Extended information' }, keyboard_shortcuts: { id: 'navigation_bar.keyboard_shortcuts', defaultMessage: 'Keyboard shortcuts' }, featured_users: { id: 'navigation_bar.featured_users', defaultMessage: 'Featured users' }, }); export default @connect() @injectIntl class gettingStartedMisc extends ImmutablePureComponent { static propTypes = { intl: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, }; openOnboardingModal = (e) => { this.props.dispatch(openModal('ONBOARDING')); } openFeaturedAccountsModal = (e) => { this.props.dispatch(openModal('PINNED_ACCOUNTS_EDITOR')); } render () { const { intl } = this.props; let i = 1; return ( <Column icon='ellipsis-h' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <div className='scrollable'> <ColumnSubheading text={intl.formatMessage(messages.subheading)} /> <ColumnLink key='{i++}' icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' /> <ColumnLink key='{i++}' icon='thumb-tack' text={intl.formatMessage(messages.pins)} to='/pinned' /> <ColumnLink key='{i++}' icon='users' text={intl.formatMessage(messages.featured_users)} onClick={this.openFeaturedAccountsModal} /> <ColumnLink key='{i++}' icon='volume-off' text={intl.formatMessage(messages.mutes)} to='/mutes' /> <ColumnLink key='{i++}' icon='ban' text={intl.formatMessage(messages.blocks)} to='/blocks' /> <ColumnLink key='{i++}' icon='minus-circle' text={intl.formatMessage(messages.domain_blocks)} to='/domain_blocks' /> <ColumnLink key='{i++}' icon='question' text={intl.formatMessage(messages.keyboard_shortcuts)} to='/keyboard-shortcuts' /> <ColumnLink key='{i++}' icon='book' text={intl.formatMessage(messages.info)} href='/about/more' /> <ColumnLink key='{i++}' icon='hand-o-right' text={intl.formatMessage(messages.show_me_around)} onClick={this.openOnboardingModal} /> </div> </Column> ); } }
lib/index.js
thatPamIAm/weathrly
import React from 'react'; import ReactDOM from 'react-dom'; import App from './containers/App'; import reset from '../css/reset'; import styles from '../css/styles'; ReactDOM.render(<App />, document.getElementById('application'));
docs/app/Examples/modules/Progress/Content/ProgressExampleProgress.js
vageeshb/Semantic-UI-React
import React from 'react' import { Progress } from 'semantic-ui-react' const ProgressExampleProgress = () => ( <Progress percent={44} progress /> ) export default ProgressExampleProgress
examples/real-world/containers/Root.js
Lucifier129/redux
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { Router, Route } from 'react-router'; import configureStore from '../store/configureStore'; import App from './App'; import UserPage from './UserPage'; import RepoPage from './RepoPage'; const store = configureStore(); export default class Root extends Component { render() { return ( <div> <Provider store={store}> {() => <Router history={this.props.history}> <Route path='/' component={App}> <Route path='/:login/:name' component={RepoPage} /> <Route path='/:login' component={UserPage} /> </Route> </Router> } </Provider> </div> ); } }
Realization/frontend/czechidm-acc/src/content/system/SystemRoles.js
bcvsolutions/CzechIdMng
import React from 'react'; import _ from 'lodash'; // import { Basic, Domain } from 'czechidm-core'; import RoleSystemTableComponent, { RoleSystemTable } from '../role/RoleSystemTable'; const uiKey = 'system-roles-table'; /** * Table to display roles, assigned to system * * @author Petr Hanák * @author Radek Tomiška */ export default class SystemRoles extends Basic.AbstractContent { getUiKey() { return uiKey; } getContentKey() { return 'acc:content.system.roles'; } getNavigationKey() { return 'system-roles'; } render() { const { entityId } = this.props.match.params; const forceSearchParameters = new Domain.SearchParameters().setFilter('systemId', entityId); // return ( <div className="tab-pane-table-body"> { this.renderContentHeader({ style: { marginBottom: 0 }}) } <Basic.Panel className="no-border last"> <RoleSystemTableComponent columns={ _.difference(RoleSystemTable.defaultProps.columns, ['system']) } showRowSelection uiKey={ `${this.getUiKey()}-${entityId}` } forceSearchParameters={ forceSearchParameters } menu="system" match={ this.props.match } className="no-margin"/> </Basic.Panel> </div> ); } }
react-flux-mui/js/material-ui/src/svg-icons/device/battery-90.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery90 = (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.33V8h10V5.33z"/><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z"/> </SvgIcon> ); DeviceBattery90 = pure(DeviceBattery90); DeviceBattery90.displayName = 'DeviceBattery90'; DeviceBattery90.muiName = 'SvgIcon'; export default DeviceBattery90;
app/javascript/mastodon/features/compose/containers/warning_container.js
kibousoft/mastodon
import React from 'react'; import { connect } from 'react-redux'; import Warning from '../components/warning'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { me } from '../../../initial_state'; const APPROX_HASHTAG_RE = /(?:^|[^\/\)\w])#(\S+)/i; const mapStateToProps = state => ({ needsLockWarning: state.getIn(['compose', 'privacy']) === 'private' && !state.getIn(['accounts', me, 'locked']), hashtagWarning: state.getIn(['compose', 'privacy']) !== 'public' && APPROX_HASHTAG_RE.test(state.getIn(['compose', 'text'])), }); const WarningWrapper = ({ needsLockWarning, hashtagWarning }) => { if (needsLockWarning) { return <Warning message={<FormattedMessage id='compose_form.lock_disclaimer' defaultMessage='Your account is not {locked}. Anyone can follow you to view your follower-only posts.' values={{ locked: <a href='/settings/profile'><FormattedMessage id='compose_form.lock_disclaimer.lock' defaultMessage='locked' /></a> }} />} />; } if (hashtagWarning) { return <Warning message={<FormattedMessage id='compose_form.hashtag_warning' defaultMessage="This toot won't be listed under any hashtag as it is unlisted. Only public toots can be searched by hashtag." />} />; } return null; }; WarningWrapper.propTypes = { needsLockWarning: PropTypes.bool, hashtagWarning: PropTypes.bool, }; export default connect(mapStateToProps)(WarningWrapper);
app/components/Home.js
rondobley/meal-planner
import React from 'react'; import ReactDOM from 'react-dom'; import HomeStore from '../stores/HomeStore'; import HomeActions from '../actions/HomeActions'; class Home extends React.Component { constructor(props) { super(props); this.state = HomeStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { HomeStore.listen(this.onChange); } componentWillUnmount() { HomeStore.unlisten(this.onChange); } componentDidUpdate() { if(this.state.isLoggedIn) { window.location.href = "/dishes"; } } onChange(state) { this.setState(state); } resetValidationState() { this.state.emailHelpBlock = ''; this.state.passwordHelpBlock = ''; this.state.formHelpBlock = ''; this.state.formValidationState = ''; } handleSubmit(e) { e.preventDefault(); this.resetValidationState(); var email = this.state.email.trim(); var password = this.state.password.trim(); if(!email) { HomeActions.invalidEmail(); ReactDOM.findDOMNode(this.refs.emailInput).focus(); } else if(!password) { HomeActions.invalidPassword(); ReactDOM.findDOMNode(this.refs.passwordInput).focus(); } else { HomeActions.login(email, password); } } render() { let button = <button type='submit' className='btn btn-primary'>Login</button>; return ( <div className='container'> <div className='row'> <div className='col-md-3'></div> <div className='col-sm-12 col-md-6'> <form className='login-form' onSubmit={this.handleSubmit.bind(this)}> <div className={'form-group ' + this.state.formValidationState}> <label className='control-label'>Login</label> <input type='text' className='form-control' ref='emailInput' name="email" value={this.state.email} onChange={HomeActions.updateEmailInput} autoFocus/> <span className='help-block'>{this.state.emailHelpBlock}</span> <input type='password' className='form-control' ref='passwordInput' name="password" value={this.state.password} onChange={HomeActions.updatePasswordInput} /> <span className='help-block'>{this.state.passwordHelpBlock}</span> <span className='help-block'>{this.state.formHelpBlock}</span> </div> <div className="text-right">{button}</div> </form> </div> <div className='col-md-3'></div> </div> </div> ); } } export default Home;
src/svg-icons/social/people-outline.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPeopleOutline = (props) => ( <SvgIcon {...props}> <path d="M16.5 13c-1.2 0-3.07.34-4.5 1-1.43-.67-3.3-1-4.5-1C5.33 13 1 14.08 1 16.25V19h22v-2.75c0-2.17-4.33-3.25-6.5-3.25zm-4 4.5h-10v-1.25c0-.54 2.56-1.75 5-1.75s5 1.21 5 1.75v1.25zm9 0H14v-1.25c0-.46-.2-.86-.52-1.22.88-.3 1.96-.53 3.02-.53 2.44 0 5 1.21 5 1.75v1.25zM7.5 12c1.93 0 3.5-1.57 3.5-3.5S9.43 5 7.5 5 4 6.57 4 8.5 5.57 12 7.5 12zm0-5.5c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 5.5c1.93 0 3.5-1.57 3.5-3.5S18.43 5 16.5 5 13 6.57 13 8.5s1.57 3.5 3.5 3.5zm0-5.5c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2z"/> </SvgIcon> ); SocialPeopleOutline = pure(SocialPeopleOutline); SocialPeopleOutline.displayName = 'SocialPeopleOutline'; SocialPeopleOutline.muiName = 'SvgIcon'; export default SocialPeopleOutline;