path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
.history/src/components/GKM/EtsyProduct_20170624130727.js | oded-soffrin/gkm_viewer | import React from 'react'
import '../../styles/gkm-item.scss';
import ProductItem from './ProductItem'
import Input from '../Common/Input'
import SearchBar from '../SearchBar';
import _ from 'lodash'
class EtsyProduct extends React.Component {
constructor(props, context) {
super(props, context);
this.editables = {
name: {
max: 20,
display: 'Name'
},
shortDescription: {
max: 100,
display: 'Short Description'
},
twitterTitle: {
max: 100,
display: 'Twitter Text'
}
};
}
onUpdateField(update) {
console.log(update)
let product = this.props.product
_.each(update, (v, k) => {
product[k] = v;
})
this.props.updateItem(product);
}
getListingById(id) {
return _.find(this.props.listings, (l) => l.id === id)
}
editableFieldsHtml() {
const { product } = this.props
return (
<div>
{_.map(this.editables, (v, fld) => (
<Input
title={v.display}
fld={fld}
value={product[fld]}
id={product.id}
onUpdate={
(i, update) => this.onUpdateField(update)
}
/>))
}
</div>
)
}
onAddtoCategory(category) {
const { product } = this.props;
addItemtoCategory(product, category)
}
render() {
const { product, listings, addListingToProduct } = this.props;
const loader = (<div>loading...</div >)
const productItems = product.populatedListings.map((listing) => (listing ? < ProductItem key={listing.id} product={listing} inProduct={true} /> : loader))
return (
<div className='gkm-etsy-product' id={product.id}>
<h5>Etsy Product</h5>
<div>
Product Name: {product.name}
<div>Categories:</div>
{_.map(product.hashtags.all(), (hashtag) => (<div>{hashtag}</div>))}
<Input title="add category" fld='category' resetOnClick={true} button={{ text: 'ADD!', action: this.onAddtoCategory }} />
{this.editableFieldsHtml()}
</div>
{productItems}
<div> Add another listing: </div>
<SearchBar products={listings}
onSelect={
(listingId) => {
addListingToProduct(product, this.getListingById(listingId))
}
} />
</div>
)
}
}
/*
Item.propTypes = {
};
*/
export default EtsyProduct
|
app/js/About.js | skratchdot/infinite-gradients | import React from 'react';
import Header from './Header';
var readmeHtml = require('../../lib/readme').getReadme();
module.exports = React.createClass({
render: function () {
return (
<div id="page-about">
<Header />
<div className="well" dangerouslySetInnerHTML={{__html: readmeHtml}}>
</div>
</div>
);
}
});
|
web/src/components/Todo.js | jinghang/react-todo-demo | import React from 'react'
const ReactMotion = require('../lib/react-motion.js')
import '../style/Todo.css';
var TransitionMotion = ReactMotion.TransitionMotion;
var spring = ReactMotion.spring;
var presets = ReactMotion.presets;
const Todo = React.createClass({
getInitialState() {
return {
todos: {
// key is creation date
't1': {text: 'Board the plane'},
't2': {text: 'Sleep'},
't3': {text: 'Try to finish coneference slides'},
't4': {text: 'Eat cheese and drink wine'},
't5': {text: 'Go around in Uber'},
't6': {text: 'Talk with conf attendees'},
't7': {text: 'Show Demo 1'},
't8': {text: 'Show Demo 2'},
't9': {text: 'Lament about the state of animation'},
't10': {text: 'Show Secret Demo'},
't11': {text: 'Go home'},
},
value: '',
};
},
// logic from todo, unrelated to animation
handleChange({target: {value}}) {
this.setState({value});
},
handleSubmit(e) {
e.preventDefault();
const {todos, value} = this.state;
let t = { ['t' + Date.now()]: {text: value},}
for(const key in todos){
t[key]=todos[key]
}
this.setState({
todos: t,
});
},
handleDestroy(date) {
const {todos} = this.state;
delete todos[date];
this.forceUpdate();
},
// actual animation-related logic
getDefaultValue() {
const {todos} = this.state;
return Object.keys(todos)
.reduce((configs, date) => {
configs[date] = {
height: spring(0),
opacity: spring(1),
data: todos[date],
};
return configs;
}, {});
},
getEndValue() {
const {todos, value} = this.state;
return Object.keys(todos)
.filter(date => {
const todo = todos[date];
return todo.text.toUpperCase().indexOf(value.toUpperCase()) >= 0
})
.reduce((configs, date) => {
configs[date] = {
height: spring(60, presets.wobbly),
opacity: spring(1, presets.wobbly),
data: todos[date],
};
return configs;
}, {});
},
willEnter(date) {
return {
height: spring(0),
opacity: spring(2),
data: this.state.todos[date],
};
},
willLeave(date, keyThatJustLeft) {
return {
height: spring(0), //mounting process
opacity: spring(10),
data: keyThatJustLeft.data,
};
},
render() {
const {todos, value} = this.state;
return (
<section className="todoapp" style={{maxWidth:'550px'}}>
<header className="header">
<h1>todos</h1>
<form onSubmit={this.handleSubmit}>
<input
autoFocus={true}
className="new-todo"
placeholder="What needs to be done?"
value={value}
onChange={this.handleChange}
/>
</form>
</header>
<section className="main" style={{maxWidth:'550px'}}>
<input className="toggle-all" type="checkbox" onChange={this.handleToggleAll} />
<TransitionMotion defaultStyles={this.getDefaultValue()} styles={this.getEndValue()} willLeave={this.willLeave}
willEnter={this.willEnter}>
{configs =>
<ul className="todo-list">
{Object.keys(configs).map(date => {
const config = configs[date];
//debugger;
//console.log('config'+config)
const {data: {text}, height,opacity} = config;
//const style={height,opacity}
return (
<li key={date} style={{height,opacity}}>
<div className="view">
<label>{text}</label>
<button
className="destroy"
onClick={this.handleDestroy.bind(null, date)}
/>
</div>
</li>
);
})}
</ul>
}
</TransitionMotion>
</section>
<footer className="footer">
<span className="todo-count">
<strong>
{Object.keys(todos).filter(key => !todos[key].isDone).length}
</strong> item left
</span>
</footer>
</section>
);
},
});
export default Todo
|
examples/with-immutable-redux-wrapper/pages/index.js | BlancheXu/test | import React from 'react'
import { bindActionCreators } from 'redux'
import { startClock, addCount, serverRenderClock } from '../store'
import Page from '../components/Page'
import { connect } from 'react-redux'
class Counter extends React.Component {
static getInitialProps ({ store, isServer }) {
store.dispatch(serverRenderClock(isServer))
store.dispatch(addCount())
return { isServer }
}
componentDidMount () {
this.timer = this.props.startClock()
}
componentWillUnmount () {
clearInterval(this.timer)
}
render () {
return <Page title='Index Page' linkTo='/other' />
}
}
const mapDispatchToProps = dispatch => {
return {
addCount: bindActionCreators(addCount, dispatch),
startClock: bindActionCreators(startClock, dispatch)
}
}
export default connect(
null,
mapDispatchToProps
)(Counter)
|
src/svg-icons/communication/rss-feed.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationRssFeed = (props) => (
<SvgIcon {...props}>
<circle cx="6.18" cy="17.82" r="2.18"/><path d="M4 4.44v2.83c7.03 0 12.73 5.7 12.73 12.73h2.83c0-8.59-6.97-15.56-15.56-15.56zm0 5.66v2.83c3.9 0 7.07 3.17 7.07 7.07h2.83c0-5.47-4.43-9.9-9.9-9.9z"/>
</SvgIcon>
);
CommunicationRssFeed = pure(CommunicationRssFeed);
CommunicationRssFeed.displayName = 'CommunicationRssFeed';
CommunicationRssFeed.muiName = 'SvgIcon';
export default CommunicationRssFeed;
|
src/collections/BootNavs/BootNavDropdown.js | shengnian/shengnian-ui-react | import React from 'react'
import PropTypes from 'prop-types'
import cx from 'classnames'
import { mapToCssModules } from '../../lib/'
import Dropdown from '../../modules/BootDropdown/BootDropdown'
const propTypes = {
children: PropTypes.node,
tag: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
className: PropTypes.string,
cssModule: PropTypes.object,
}
const defaultProps = {
tag: 'li',
}
const NavDropdown = (props) => {
const {
className,
cssModule,
tag: Tag,
...attributes
} = props
const classes = mapToCssModules(cx(
className,
'nav-item',
), cssModule)
return (
<Dropdown {...attributes} tag={Tag} className={classes} />
)
}
NavDropdown.propTypes = propTypes
NavDropdown.defaultProps = defaultProps
export default NavDropdown
|
src/components/source/mediaSource/SourceStatInfo.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import withAsyncData from '../../common/hocs/AsyncDataContainer';
import { fetchSourceStats } from '../../../actions/sourceActions';
import StatBar from '../../common/statbar/StatBar';
import messages from '../../../resources/messages';
import { healthStartDateToMoment } from '../../../lib/dateUtil';
const localMessages = {
nytPct: { id: 'source.summary.statbar.nyt', defaultMessage: 'With Themes' },
geoPct: { id: 'source.summary.statbar.geo', defaultMessage: 'With Entities' },
collections: { id: 'source.summary.statbar.collections', defaultMessage: 'Collections' },
coveredSince: { id: 'source.summary.statbar.coveredSince', defaultMessage: 'Covered Since' },
storyCount: { id: 'source.summary.statbar.storyCount', defaultMessage: 'Total Stories' },
storiesPerDayHelpTitle: { id: 'source.summary.statbar.perDay.title', defaultMessage: 'About Stories per Day' },
storiesPerDayHelpContent: { id: 'source.summary.statbar.perDay.content', defaultMessage: 'This is average of the number of stories per day we have ingested over the last 90 days.' },
};
const SourceStatInfo = (props) => {
const { sourceId, sourceInfo } = props;
const { formatNumber, formatDate, formatMessage } = props.intl;
if ((sourceId === null) || (sourceId === undefined)) {
return null;
}
let formattedDateStr;
if (sourceInfo.start_date) {
const startDate = healthStartDateToMoment(sourceInfo.start_date);
formattedDateStr = formatDate(startDate, { month: 'numeric', year: 'numeric' });
} else {
formattedDateStr = formatMessage(messages.unknown);
}
return (
<StatBar
columnWidth={2}
stats={[
{ message: localMessages.storyCount, data: formatNumber(sourceInfo.story_count) },
{ message: localMessages.coveredSince, data: formattedDateStr },
{ message: localMessages.collections, data: formatNumber(sourceInfo.collection_count) },
{ message: messages.storiesPerDay,
data: formatNumber(Math.round(sourceInfo.num_stories_90)),
helpTitleMsg: localMessages.storiesPerDayHelpTitle,
helpContentMsg: localMessages.storiesPerDayHelpContent,
},
{ message: localMessages.geoPct,
data: formatNumber(sourceInfo.geoPct, { style: 'percent', maximumFractionDigits: 0 }),
helpTitleMsg: messages.entityHelpTitle,
helpContentMsg: messages.entityHelpContent,
},
{ message: localMessages.nytPct,
data: formatNumber(sourceInfo.nytPct, { style: 'percent', maximumFractionDigits: 0 }),
helpTitleMsg: messages.themeHelpTitle,
helpContentMsg: messages.themeHelpContent,
},
]}
/>
);
};
SourceStatInfo.propTypes = {
// from parent
sourceId: PropTypes.number.isRequired,
sourceInfo: PropTypes.object.isRequired,
// from composition chain
intl: PropTypes.object.isRequired,
// from state
fetchStatus: PropTypes.string.isRequired,
};
const mapStateToProps = state => ({
fetchStatus: state.sources.sources.selected.stats.fetchStatus,
sourceInfo: state.sources.sources.selected.stats,
});
const fetchAsyncData = (dispatch, { sourceId }) => dispatch(fetchSourceStats(sourceId));
export default
injectIntl(
connect(mapStateToProps)(
withAsyncData(fetchAsyncData)(
SourceStatInfo
)
)
);
|
test/test_helper.js | johnnyvf24/hellochess-v2 | 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/App/shared/PokemonTable/index.js | wendywill25/node-api-server | /*** @jsx React.DOM */
import React from 'react';
var PokemonTable = React.createClass({
render: function() {
var rows = this.props.pokemon.map(function(pokemon) {
return (
<tr key={pokemon.id}>
<td>{pokemon.id}</td>
<td>{pokemon.name}</td>
<td>{pokemon.level}</td>
</tr>
);
});
return (
<table className="pokemon-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Level</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
);
}
});
export default PokemonTable;
|
src/scripts/pages/FirstProject.page.js | ModuloM/kodokojo-ui | /**
* Kodo Kojo - Software factory done right
* Copyright © 2016 Kodo Kojo ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import { connect } from 'react-redux'
import { compose } from 'redux'
import { intlShape, injectIntl, FormattedMessage } from 'react-intl'
// Component commons
import 'kodokojo-ui-commons/src/styles/_commons.less'
import utilsTheme from 'kodokojo-ui-commons/src/styles/_utils.scss'
import Page from 'kodokojo-ui-commons/src/scripts/components/page/Page.component'
import Paragraph from 'kodokojo-ui-commons/src/scripts/components/page/Paragraph.component'
import Dialog from 'kodokojo-ui-commons/src/scripts/components/dialog/Dialog.component'
// Component
import Account from '../components/auth/Account.component'
import ProjectConfigForm from '../components/projectConfig/ProjectConfigForm.component'
import { setNavVisibility } from '../components/app/app.actions'
import { getBricks } from '../components/brick/brick.actions'
export class FirstProjectPage extends React.Component {
static propTypes = {
account: React.PropTypes.object,
bricks: React.PropTypes.object,
getBricks: React.PropTypes.func.isRequired,
intl: intlShape.isRequired,
setNavVisibility: React.PropTypes.func.isRequired
}
constructor(props) {
super(props)
this.state = { isAccountActive: true }
}
componentWillMount() {
const { getBricks } = this.props // eslint-disable-line no-shadow
this.initNav()
// refresh available bricks
getBricks()
}
componentWillUnmount() {
// TODO dispatch action that clean auth from sensitive infos (password, ssh keys)
}
initNav = () => {
const { setNavVisibility } = this.props // eslint-disable-line no-shadow
setNavVisibility(false)
}
handleClose = () => {
this.setState({
isAccountActive: false
})
}
render() {
const { formatMessage } = this.props.intl
return (
<Page>
<h1 className={ utilsTheme['secondary-color--1'] }>
<FormattedMessage id={'project-create-label'} />
</h1>
<Paragraph>
<Dialog
actions={[
{ label: formatMessage({ id: 'close-label' }), onClick: this.handleClose }
]}
active={ this.state.isAccountActive }
onEscKeyDown={ this.handleClose }
onOverlayClick={ this.handleClose }
title={ formatMessage({ id: 'account-label' }) }
>
<Account />
</Dialog>
<ProjectConfigForm />
</Paragraph>
</Page>
)
}
}
// FirstProjectPage container
const mapStateProps = (state, ownProps) => (
{
location: ownProps.location,
bricks: state.bricks
}
)
const FirstProjectContainer = compose(
connect(
mapStateProps,
{
getBricks,
setNavVisibility
}
),
injectIntl
)(FirstProjectPage)
export default FirstProjectContainer
|
src/svg-icons/maps/local-see.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalSee = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
MapsLocalSee = pure(MapsLocalSee);
MapsLocalSee.displayName = 'MapsLocalSee';
MapsLocalSee.muiName = 'SvgIcon';
export default MapsLocalSee;
|
addons/options/.storybook/stories.js | enjoylife/storybook | import React from 'react';
import { storiesOf } from '@storybook/react';
storiesOf('Hello', module)
.add('Hello World', () => (
<pre>Hello World</pre>
))
.add('Hello Earth', () => (
<pre>Hello Earth</pre>
));
|
src/app/components/media/ItemHistoryDialog.js | meedan/check-web | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import CloseIcon from '@material-ui/icons/Close';
import Dialog from '@material-ui/core/Dialog';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import IconButton from '@material-ui/core/IconButton';
import { makeStyles } from '@material-ui/core/styles';
import MediaLog from './MediaLog';
const useStyles = makeStyles(theme => ({
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
},
}));
const ItemHistoryDialog = ({
open,
projectMedia,
team,
onClose,
}) => {
const classes = useStyles();
return (
<Dialog
open={open}
onClose={onClose}
maxWidth="sm"
fullWidth
>
<DialogTitle>
<FormattedMessage id="ItemHistoryDialog.title" defaultMessage="Item history" />
<IconButton
aria-label="close"
className={classes.closeButton}
id="item-history__close-button"
onClick={onClose}
>
<CloseIcon />
</IconButton>
</DialogTitle>
<DialogContent>
<MediaLog
media={projectMedia}
team={team}
/>
</DialogContent>
</Dialog>
);
};
ItemHistoryDialog.propTypes = {
open: PropTypes.bool.isRequired,
projectMedia: PropTypes.object.isRequired,
team: PropTypes.object.isRequired,
onClose: PropTypes.func.isRequired,
};
export default ItemHistoryDialog;
|
src/components/App.js | jjeffreyma/ID3-React | import React, { Component } from 'react';
import { render } from 'react-dom';
import Header from '../containers/Header';
import { TextEditor, editor } from './editor/textEditor';
import AttributesPanel from '../containers/AttributesPanel';
import Footer from './footer/Footer';
const { ipcRenderer } = require('electron');
export default class App extends Component {
componentDidMount() {
let editorView = document.getElementById('editor-container');
let webview = document.getElementById('webview-container');
let openDataWin = document.getElementById('dataWin');
let popRender = document.getElementById('popRender');
let popEditor = document.getElementById('popEditor');
let resizeView = document.getElementById('resizeView');
let editorH = editorView.style.height;
let webviewH = webview.style.height;
openDataWin.addEventListener('click', (event) => {
ipcRenderer.send('openDataWin');
});
popEditor.addEventListener('click', (event) => {
webview.style.height = 'calc(100% - 8px)';
editorView.style.height = '39px';
ipcRenderer.send('popEditor', editor.getValue());
});
popRender.addEventListener('click', (event) => {
editorView.style.height = 'calc(100% - 8px)';
webview.style.height = '39px';
ipcRenderer.send('popRender');
});
}
render() {
return (
<div className="window">
<Header />
<div className="window-content">
<div className="pane-group">
<TextEditor />
<AttributesPanel />
</div>
</div>
<Footer />
</div>
);
};
}
// Possilbe resize window pane solution
// componentDidMount() {
// let isLeftResizing = false;
// let isRightResizing = false;
// let leftSizer = document.getElementById('left-sizer');
// let rightSizer = document.getElementById('right-sizer');
// let container = document.getElementById('panel-container');
// let left = document.getElementById('left-panel');
// let right = document.getElementById('right-panel');
//
// leftSizer.addEventListener('mousedown', (e) => {
// isLeftResizing = true;
// });
//
// rightSizer.addEventListener('mousedown', (e) => {
// isRightResizing = true;
// });
//
// document.addEventListener('mousemove', (e) => {
// if (isLeftResizing) {
// let leftWidth = e.clientX - container.offsetLeft;
// left.style.width = `${leftWidth}px`;
// }
//
// if (isRightResizing) {
// let rightWidth = e.clientX - container.offsetLeft;
// right.style.width = `${rightWidth}px`;
// }
// });
//
// document.addEventListener('mouseup', () => {
// isLeftResizing = false;
// isRightResizing = false;
// });
// }
|
src/pageComponents/lex/lexForm.js | nai888/langua | import React from 'react'
import PropTypes from 'prop-types'
import Form from '../../components/form'
// import sharedStyles from '../../components/form/sharedForm.module.sass'
const LexForm = () => <Form name='lex-form' />
LexForm.propTypes = {
styles: PropTypes.string
}
export default LexForm
|
src/client/container/quizz/ExportQuizzForm.js | JulienPradet/quizzALJP | import React from 'react'
export default class QuizzForm extends React.Component {
render() {
return <div>
Export a quizz in a JSON format.
</div>
}
}
|
src/components/common/story/StoryImages.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { Row, Col } from 'react-flexbox-grid/lib';
import { fetchStoryImages } from '../../../actions/storyActions';
import withAsyncData from '../hocs/AsyncDataContainer';
import DataCard from '../DataCard';
import { trimToMaxLength } from '../../../lib/stringUtil';
const localMessages = {
title: { id: 'story.images.title', defaultMessage: 'Story Images' },
top: { id: 'story.images.top', defaultMessage: 'Top Image' },
other: { id: 'story.images.other', defaultMessage: 'Other Images' },
};
const StoryImages = ({ topImage, allImages }) => (
<DataCard className="story-images-container">
<h2><FormattedMessage {...localMessages.title} /></h2>
<Row>
<Col lg={6}>
<h3><FormattedMessage {...localMessages.top} /></h3>
{topImage && (
<a href={topImage}><img alt="top" src={topImage} width="100%" /></a>
)}
</Col>
<Col lg={6}>
<h3><FormattedMessage {...localMessages.other} /></h3>
<ul>
{allImages && allImages.map((imageUrl, idx) => (
<li key={idx}><a href={imageUrl}>{trimToMaxLength(imageUrl, 70)}</a></li>
))}
</ul>
</Col>
</Row>
</DataCard>
);
StoryImages.propTypes = {
// from compositional chain
intl: PropTypes.object.isRequired,
// from parent
storyId: PropTypes.number.isRequired,
// from state
fetchStatus: PropTypes.string.isRequired,
allImages: PropTypes.array,
topImage: PropTypes.string,
};
const mapStateToProps = state => ({
fetchStatus: state.story.images.fetchStatus,
allImages: state.story.images.all,
topImage: state.story.images.top,
});
const fetchAsyncData = (dispatch, { storyId }) => dispatch(fetchStoryImages(storyId));
export default
injectIntl(
connect(mapStateToProps)(
withAsyncData(fetchAsyncData, ['storyId'])(
StoryImages
)
)
);
|
src/routes.js | Kgiberson/welp | import React from 'react';
import { browserHistory, Router, Route, Redirect } from 'react-router';
import makeMainRoutes from './views/Main/routes';
export const makeRoutes = () => {
const main = makeMainRoutes();
return (
<Route path=''>
{main}
</Route>
)
}
export default makeRoutes; |
app/imports/ui/components/ItemEditor.js | ericvrp/GameCollie | /* eslint-disable max-len, no-return-assign */
import React from 'react';
import PropTypes from 'prop-types';
import { FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap';
import itemEditor from '../../modules/item-editor.js';
export default class ItemEditor extends React.Component {
componentDidMount() {
itemEditor({ component: this });
setTimeout(() => { document.querySelector('[name="title"]').focus(); }, 0);
}
render() {
const { item } = this.props;
return (<form
ref={ form => (this.itemEditorForm = form) }
onSubmit={ event => event.preventDefault() }
>
<FormGroup>
<ControlLabel>Title</ControlLabel>
<FormControl
type="text"
name="title"
defaultValue={ item && item.title }
placeholder="Name of a fantastic game!"
/>
</FormGroup>
<Button type="submit" bsStyle="success">
{ item && item._id ? 'Save Changes' : 'Add Item' }
</Button>
</form>);
}
}
ItemEditor.propTypes = {
item: PropTypes.object,
};
// <FormGroup>
// <ControlLabel>Body</ControlLabel>
// <FormControl
// componentClass="textarea"
// name="body"
// defaultValue={ item && item.body }
// placeholder="Congratulations! Today is your day. You're off to Great Places! You're off and away!"
// />
// </FormGroup>
|
node_modules/react-bootstrap/src/OverlayMixin.js | gitoneman/react-home | import React from 'react';
import CustomPropTypes from './utils/CustomPropTypes';
import domUtils from './utils/domUtils';
export default {
propTypes: {
container: CustomPropTypes.mountable
},
componentWillUnmount() {
this._unrenderOverlay();
if (this._overlayTarget) {
this.getContainerDOMNode()
.removeChild(this._overlayTarget);
this._overlayTarget = null;
}
},
componentDidUpdate() {
this._renderOverlay();
},
componentDidMount() {
this._renderOverlay();
},
_mountOverlayTarget() {
this._overlayTarget = document.createElement('div');
this.getContainerDOMNode()
.appendChild(this._overlayTarget);
},
_renderOverlay() {
if (!this._overlayTarget) {
this._mountOverlayTarget();
}
let overlay = this.renderOverlay();
// Save reference to help testing
if (overlay !== null) {
this._overlayInstance = React.render(overlay, this._overlayTarget);
} else {
// Unrender if the component is null for transitions to null
this._unrenderOverlay();
}
},
_unrenderOverlay() {
React.unmountComponentAtNode(this._overlayTarget);
this._overlayInstance = null;
},
getOverlayDOMNode() {
if (!this.isMounted()) {
throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');
}
if (this._overlayInstance) {
return React.findDOMNode(this._overlayInstance);
}
return null;
},
getContainerDOMNode() {
return React.findDOMNode(this.props.container) || domUtils.ownerDocument(this).body;
}
};
|
src/components/common/ratingStar/ratingStar.js | dejour/react-elm | import React, { Component } from 'react';
import './ratingStar.css'
class RatingStar extends Component {
constructor (props) {
super(props)
}
render() {
const num = [0,0,0,0,0]
return (
<div className="rating_container">
<section className="star_container">
{
num.map((item,index)=> (
<svg className="grey_fill" key={index}>
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#star"></use>
</svg>
))
}
</section>
<div style={{width: this.props.rating*2/5 +'rem'}} className="star_overflow">
<section className='star_container'>
{
num.map((item, index) => (
<svg className='orange_fill' key={index}>
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#star"></use>
</svg>
))
}
</section>
</div>
</div>
)
}
}
export default RatingStar |
src/slider.js | hangarlabs/hangar-react-slick | 'use strict';
import React from 'react';
import {InnerSlider} from './inner-slider';
import assign from 'object-assign';
import json2mq from 'json2mq';
import ResponsiveMixin from 'react-responsive-mixin';
import defaultProps from './default-props';
var Slider = React.createClass({
mixins: [ResponsiveMixin],
innerSlider: null,
innerSliderRefHandler: function (ref) {
this.innerSlider = ref;
},
getInitialState: function () {
return {
breakpoint: null
};
},
componentWillMount: function () {
if (this.props.responsive) {
var breakpoints = this.props.responsive.map(breakpt => breakpt.breakpoint);
breakpoints.sort((x, y) => x - y);
breakpoints.forEach((breakpoint, index) => {
var bQuery;
if (index === 0) {
bQuery = json2mq({minWidth: 0, maxWidth: breakpoint});
} else {
bQuery = json2mq({minWidth: breakpoints[index-1], maxWidth: breakpoint});
}
this.media(bQuery, () => {
this.setState({breakpoint: breakpoint});
});
});
// Register media query for full screen. Need to support resize from small to large
var query = json2mq({minWidth: breakpoints.slice(-1)[0]});
this.media(query, () => {
this.setState({breakpoint: null});
});
}
},
slickPrev: function () {
this.innerSlider.slickPrev();
},
slickNext: function () {
this.innerSlider.slickNext();
},
slickGoTo: function (slide) {
this.innerSlider.slickGoTo(slide)
},
render: function () {
var settings;
var newProps;
if (this.state.breakpoint) {
newProps = this.props.responsive.filter(resp => resp.breakpoint === this.state.breakpoint);
settings = newProps[0].settings === 'unslick' ? 'unslick' : assign({}, this.props, newProps[0].settings);
} else {
settings = assign({}, defaultProps, this.props);
}
var children = this.props.children;
if(!Array.isArray(children)) {
children = [children]
}
// Children may contain false or null, so we should filter them
children = children.filter(function(child){
return !!child
})
if (settings === 'unslick') {
// if 'unslick' responsive breakpoint setting used, just return the <Slider> tag nested HTML
return (
<div>{children}</div>
);
} else {
return (
<InnerSlider ref={this.innerSliderRefHandler} {...settings}>
{children}
</InnerSlider>
);
}
}
});
module.exports = Slider;
|
src/routes/AuthenticatedLayout.js | gcanti/tcomb-spa-example | import React from 'react'
import { t, props } from 'tcomb-react'
import Header from '../components/Header'
@props({
app: t.Object,
children: t.Any
})
export default class AuthenticatedLayout extends React.Component {
onSignOut = () => {
this.props.app.signOut()
}
render() {
const app = this.props.app
const user = app.getUser()
return (
<div>
<Header user={user} isBusy={app.isBusy()} onSignOut={this.onSignOut} />
{this.props.children}
</div>
)
}
} |
packages/fyndiq-icons/src/cart.js | fyndiq/fyndiq-ui | import React from 'react'
import SvgWrapper from './svg-wrapper'
const Cart = ({ className, color }) => (
<SvgWrapper className={className} viewBox="0 0 25 22">
<path
d="M11 .7a.9.9 0 0 0-.6.3L5.2 7.5a.9.9 0 0 0 .2 1.2.9.9 0 0 0 .5.2.9.9 0 0 0 .7-.4l5.2-6.4.2-.6a.9.9 0 0 0-1-.8zm2.6 0a.9.9 0 0 0-.4.2A.9.9 0 0 0 13 2l5.2 6.4a.9.9 0 0 0 .7.4.9.9 0 0 0 .5-.2.9.9 0 0 0 .2-1.2L14.4 1a.9.9 0 0 0-.8-.3zM.7 6.7a.4.4 0 0 0-.4.4v1.7c0 1.2 1 2.2 2.1 2.2h20a2.2 2.2 0 0 0 2-2.1V7a.4.4 0 0 0-.3-.4h-4l.1.2A1.7 1.7 0 0 1 19 9.7a1.7 1.7 0 0 1-1.4-.7l-1.9-2.3H9.2L7.2 9a1.7 1.7 0 0 1-1.3.7 1.7 1.7 0 0 1-1.7-1.5A1.7 1.7 0 0 1 4.5 7l.2-.3h-4zm.7 5.4l1.5 7.6c0 .9.8 1.6 1.7 1.6h15.6c.8 0 1.6-.7 1.7-1.6l1.5-7.6a3.5 3.5 0 0 1-1 .2h-20a3.5 3.5 0 0 1-1-.2z"
fill={color}
fillRule="evenodd"
stroke="none"
/>
</SvgWrapper>
)
Cart.propTypes = SvgWrapper.propTypes
Cart.defaultProps = SvgWrapper.defaultProps
export default Cart
|
src/components/StartAuction/StartAuctionInfo.js | PhyrexTsai/ens-bid-dapp | import React from 'react';
import {shortFormatHash, momentFromNow} from '../../lib/util';
import Button from 'material-ui/Button';
import Card from 'material-ui/Card';
import Divider from 'material-ui/Divider';
import './StartAuctionInfo.css';
const RevealAuctionOn = (props) =>
<div className="RevealAuctionOn">
<h4>Reveal Auction On:</h4>
<p>{props.unsealStartsAt}</p>
<p>{props.endsMomentFromNow}</p>
<Divider />
</div>;
const InfoItem = (props) => {
let classes = '';
if (props.title === 'ENS') classes = 'eth-item';
if (props.title === 'TxHash') classes = 'eth-txhash';
if (props.title === 'JSON') classes = 'eth-json';
return (
<div className="StartAuctionInfo-info-item">
<p>
<span>{props.title}:</span>
<span className={classes}>{props.children}</span>
</p>
<Divider />
</div>
);
};
export const StartAuctionInfo = (props) => {
const endsMomentFromNow = momentFromNow(props.unsealStartsAt);
const hidden = (props.registratesAt.year() - 1970) <= 0 ;
const ethersacnUrl = process.env.REACT_APP_ETHERSCAN_URL || 'https://ropsten.etherscan.io/tx/';
const txHashUrl = ethersacnUrl + props.auctionTXHash;
const revealAuctionOn = !hidden &&
<RevealAuctionOn
unsealStartsAt={props.unsealStartsAt.toString()}
endsMomentFromNow={endsMomentFromNow.toString()}
/>;
const {ethBid, ethMask, secret} = props.formResult;
const shorterTxHash = shortFormatHash(props.auctionTXHash);
const itemTitleValue = [
{title: 'ENS', value: `${props.searchResult.searchName}.eth`},
{title: 'ETH Bid', value: ethBid},
{title: 'ETH Mask', value: ethMask},
{title: 'Secret', value: secret},
{title: 'TxHash', value: <a target='_blank' href={txHashUrl}>{shorterTxHash}</a>},
{title: 'JSON', value: JSON.parse(props.exportJson)}
];
const infoItems = itemTitleValue.map(({title, value}, index) =>
<InfoItem key={`infoItem-${index}`} title={title}>{value}</InfoItem>
);
return (
<Card raised >
<div className="StartAuctionInfo">
{revealAuctionOn}
{infoItems}
<div className="StartAuctionInfo-actions">
<Button raised onClick={() => props.backToSearch()}>BACK TO SEARCH</Button>
{/*<Button raised>MY ENS LIST</Button>*/}
</div>
</div>
</Card>
);
} |
app/javascript/mastodon/features/account_timeline/components/limited_account_hint.js | im-in-space/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { revealAccount } from 'mastodon/actions/accounts';
import { FormattedMessage } from 'react-intl';
import Button from 'mastodon/components/button';
const mapDispatchToProps = (dispatch, { accountId }) => ({
reveal () {
dispatch(revealAccount(accountId));
},
});
export default @connect(() => {}, mapDispatchToProps)
class LimitedAccountHint extends React.PureComponent {
static propTypes = {
accountId: PropTypes.string.isRequired,
reveal: PropTypes.func,
}
render () {
const { reveal } = this.props;
return (
<div className='limited-account-hint'>
<p><FormattedMessage id='limited_account_hint.title' defaultMessage='This profile has been hidden by the moderators of your server.' /></p>
<Button onClick={reveal}><FormattedMessage id='limited_account_hint.action' defaultMessage='Show profile anyway' /></Button>
</div>
);
}
}
|
codes/chapter05/react-router-official/demo01/app/App.js | atlantis1024/react-step-by-step | import React from 'react';
import { BrowserRouter as Router, Link, Route } from 'react-router-dom';
const BasicExample = () => (
<Router>
<div>
<ul>
<li><Link to="/">首页</Link></li>
<li><Link to="/about">关于</Link></li>
<li><Link to="/topics">主题列表</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/topics" component={Topics}/>
</div>
</Router>
)
const Home = () => (
<div>
<h2>首页</h2>
</div>
)
const About = () => (
<div>
<h2>关于</h2>
</div>
)
const Topics = ({ match }) => (
<div>
<h2>主题列表</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
使用 React 渲染
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
组件
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
属性 v. 状态
</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>请选择一个主题。</h3>
)}/>
</div>
)
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
)
export default BasicExample
|
app/renderer/presentational/generic/Tab.js | AbsoluteZero273/Deezic | import React from 'react'
const Tab = ({ children, tabID, active }) => {
return (
<div className={'mdl-tabs__panel custom-tabs__panel' + (active ? ' is-active' : '')} id={tabID}>
{ children }
</div>
)
}
export default Tab
|
src/components/FormFieldsIterator/index.js | iris-dni/iris-frontend | import React from 'react';
import { get } from 'lodash/object';
import FormField from 'components/FormField';
import styles from './form-field-iterator.scss';
const FormFieldsIterator = ({
reduxFormFields,
fieldsArray = [],
trustedFields = {}
}) => (
<div className={styles.root}>
{fieldsArray.map(field => (
<div key={field.name} className={field.half ? styles['field-half'] : styles.field}>
<FormField
key={field.name}
isTrusted={trustedFields[field.name] || false}
config={field}
helper={get(reduxFormFields, field.name)}
/>
</div>
))}
</div>
);
export default FormFieldsIterator;
|
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/actual.js | IgorKilipenko/KTS_React | import React, { Component } from 'react';
class Foo extends Component {
render() {}
}
|
docs/app/Examples/elements/Icon/Variations/IconExampleFitted.js | clemensw/stardust | import React from 'react'
import { Icon } from 'semantic-ui-react'
const IconExampleFitted = () => (
<div>
<p>Tight spacing</p>
<Icon fitted name='help' />
<p>Tight spacing</p>
</div>
)
export default IconExampleFitted
|
examples/flux-utils-todomvc/js/app.js | jugend/flux | /**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
import React from 'react';
import TodoApp from './components/TodoApp.react';
React.render(<TodoApp />, document.getElementById('todoapp'));
|
src/window/data/view/toolbar/view.js | unkyulee/control-center | /******************************************************************************
Search Element
*******************************************************************************/
import React from 'react'
import { ipcRenderer } from 'electron'
import { ButtonToolbar, Button } from 'react-bootstrap'
///
///
///
export default class ToolbarView extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<ButtonToolbar>
<span className="window_title">
Data Window
</span>
<Button type="submit" bsStyle="success"
onClick={(e) => {
e.preventDefault()
ipcRenderer.send("project.save")
}}>
Save
</Button>
<Button type="submit" bsStyle="info"
onClick={(e) => {
e.preventDefault()
ipcRenderer.send( "source.new", JSON.parse(JSON.stringify(this.props.selected)) )
}}>
New
</Button>
</ButtonToolbar>
)
}
}
|
app/components/ConList.js | Toreant/monster_web | /**
* Created by apache on 15-11-14.
*/
import React from 'react';
import {Link} from 'react-router';
import {isEqual} from 'underscore';
import ConListActions from '../actions/ConListActions';
import ConListStore from '../stores/ConListStore';
class ConList extends React.Component {
constructor(props) {
super(props);
this.state = ConListStore.getState();
this.onChange = this.onChange.bind(this);
}
componentWillUnmount() {
ConListStore.unlisten(this.onChange);
}
componentDidMount() {
ConListStore.listen(this.onChange);
let props = this.props;
ConListActions.getConList(props.tab+'s',props.domain,0);
}
componentDidUpdate(prevProps) {
if(!isEqual(prevProps,this.props)) {
ConListActions.getConList(this.props.tab+'s',this.props.domain,0);
}
}
onChange(state) {
this.setState(state);
}
prevPage() {
let props = this.props;
ConListActions.getConList(props.tab+'s',props.domain,this.state.skip-1);
ConListActions.changeSkip(0);
}
nextPage() {
let props = this.props;
ConListActions.getConList(props.option,props.tab,props.domain,this.state.skip+1);
ConListActions.changeSkip(1);
}
render() {
let option = this.props.tab;
let List,SkipPage,
disabled = '',disabledN = '';
if(this.state.skip === 0) {
disabled = 'disabled';
}
if(this.state.skip >= (this.state.count/5-1) || this.state.count < 4) {
disabledN = 'disabled';
}
if(this.state.contributes.length > 0) {
List = this.state.contributes.map((data,index) => {
return (
<div className="media mon-conlist-item" key={'contribute:'+data.data._id}>
<div className="media-left">
<Link to={'/'+option+'/'+data.data._id}>
<img src={data.data.abbreviations || '/img/abbreviations.png'} alt="loading" width='80'/>
</Link>
</div>
<div className="media-body">
<Link to={'/'+option+'/'+data.data._id} className='text-primary mon-conlist-title'>
{data.data.title}
</Link>
<p className='text-muted mon-conlist-info'>
<span>投稿日期:{new Date(data.data.create_time).toLocaleDateString()}</span>
<span>浏览次数:{data.data.browser_count}</span>
</p>
<p className='text-muted'>
{data.data.summary}
</p>
</div>
<span className='mon-conlist-index'>{index+1}</span>
</div>
);
});
SkipPage = (
<div className='mon-skip'>
<a href="javascript:;" className={'btn mon-page mon-prev-page '+disabled} onClick={this.prevPage.bind(this)}>
<span className='fa fa-arrow-left'></span>
</a>
<a href="javascript:;" className={'btn mon-page mon-next-page '+disabledN} onClick={this.nextPage.bind(this)}>
<span className='fa fa-arrow-right'></span>
</a>
</div>
);
} else {
List = (
<p className="bg-info mon-padding">
尚没有任何投稿
</p>
);
SkipPage = null;
}
return (
<div className='animated flipInX'>
{List}
{SkipPage}
</div>
);
}
}
export default ConList; |
app/components/Message/index.js | Ennovar/clock_it | /**
*
* Message
*
*/
import React from 'react';
// import styled from 'styled-components';
function Message(props) {
return (
<div>
<h3>{props.message}</h3>
</div>
);
}
Message.propTypes = {
message: React.PropTypes.string,
};
export default Message;
|
web/src/server/components/charts/projects-vs-organizations-chart.js | opendaylight/spectrometer | /**
# @License EPL-1.0 <http://spdx.org/licenses/EPL-1.0>
##############################################################################
# Copyright (c) 2016 The Linux Foundation and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
##############################################################################
*/
/**
* React component to display Projects vs Organizations Charts
* Used in ContributorsCard
* Uses ChartLayout
*
* @author: Vasu Srinivasan
* @since: 0.0.1
*/
import React, { Component } from 'react';
import Griddle from 'griddle-react'
import ReactHighcharts from 'react-highcharts'
import * as DataReducers from '../../api/data-reducers'
import ChartLayout from '../chart-layout'
const ChartConfig = require('../../../../config/spectrometer-web.json').chart
const buttonActions = [
{type: 'chartType', option: 'pie', icon: 'pie_chart_outlined', tooltip: 'Show as Pie Chart'},
{type: 'chartType', option: 'table', icon: 'format_list_numbered', tooltip: 'Show as Table'}
]
const columnChart = (dataSeries) => {
const config = {
chart: { type: 'column' },
title: { text: ''},
xAxis: { title: { text: 'Projects' }, categories: _.map(dataSeries, "name") },
yAxis: { title: { text: 'Organizations' } },
series: [{ name: "Organizations", colorByPoint: true, data: _.map(dataSeries, "contributorCount") }],
plotOptions: {
column: {
showInLegend: true
}
}
}
return (<ReactHighcharts config={config} />)
}
const pieChart = (dataSeries, takeRight) => {
const ds = DataReducers.sliceAndGroupOthers(dataSeries, takeRight, 'contributorCount')
const config = {
chart: { type: 'pie' },
title: { text: '' },
tooltip: {
pointFormat: '{series.name}: {point.y}'
},
legend: {
align: 'right',
layout: 'vertical',
verticalAlign: 'top'
},
colors: ChartConfig.pieChartColors,
plotOptions: {
pie: {
allowPointSelect: true, cursor: 'pointer',
dataLabels: {
enabled: true, color: 'black',
formatter: function() { return this.point.name + ' ' + this.point.y + ' (' + (Math.round(this.percentage*100)/100 + ' %)') }
},
showInLegend: true
}
},
series: [{
name: 'Organizations',
colorByPoint: true,
data: _.map(ds, (x) => { return {name: x.name, y: x.contributorCount} })
}]
}
return (<ReactHighcharts config={config} />)
}
const COLUMN_METADATA = [
{ columnName: "name", displayName: "Name" },
{ columnName: "contributorCount", displayName: "No. of Organizations", cssClassName: 'td-values' }
]
const tableChart = (dataSeries, height) => {
return (
<Griddle id="projects-vs-organizations-table"
tableClassName="table-chart"
bodyHeight={height}
results={_.orderBy(dataSeries, ['contributorCount'], ['desc'])}
showFilter={true} showSettings={false}
columnMetadata={COLUMN_METADATA}
filterPlaceholderText="Find..."
useFixedHeader={true}
enableInfiniteScroll={true} />
)
}
export default class ProjectsVsOrganizationsChart extends Component {
constructor(props) {
super(props)
this.state = {
view: _.assign({}, DEFAULT_VIEW, props.view)
}
this.handleButtonActions = this.handleButtonActions.bind(this)
}
handleButtonActions = (type, value) => {
const newView = _.merge(this.state.view, {[type]: value})
this.setState({ view: newView })
}
render() {
if (_.isEmpty(this.props.projects)) return null
const { takeRight, tableHeight, sortBy } = this.state.view
const dataSeries = DataReducers.projectsVsContributorCount(this.props.projects, {contributor: 'organization', sortBy})
// logger.info("projects-vs-organizations", dataSeries)
return (
<ChartLayout id="projects-vs-orgs" title="No. of orgs per project"
buttonActions={buttonActions} currentView={this.state.view}
handleButtonActions={this.handleButtonActions}>
{this.state.view.chartType === 'column' && columnChart(dataSeries, takeRight)}
{this.state.view.chartType === 'pie' && pieChart(dataSeries, takeRight)}
{this.state.view.chartType === 'table' && tableChart(dataSeries, tableHeight)}
</ChartLayout>
)
}
}
const DEFAULT_VIEW = {
chartType: 'pie',
sortBy: 'contributorCount',
tableHeight: 350
}
ProjectsVsOrganizationsChart.propTypes = {
projects: React.PropTypes.array.isRequired,
view: React.PropTypes.object
}
|
src/parser/deathknight/unholy/CONFIG.js | sMteX/WoWAnalyzer | import React from 'react';
import { Khazak } from 'CONTRIBUTORS';
import retryingPromise from 'common/retryingPromise';
import SPECS from 'game/SPECS';
import CHANGELOG from './CHANGELOG';
export default {
// The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
contributors: [Khazak],
// The WoW client patch this spec was last updated to be fully compatible with.
patchCompatibility: '8.1',
// If set to false`, the spec will show up as unsupported.
isSupported: true,
// Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
// If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
description: (
<>
Welcome to the Unholy Death Knight analyzer! We worked hard to provide useful statistics and suggestions. If you have questions or comments feel free to contact Khazak(Khazak#3360) or Bicepspump(<span role="img" aria-label="Muscle">💪</span>Bicepspump<span role="img" aria-label="Muscle">💪</span>#6318) on Discord. We are still working on full support for Battle For Azeroth. If you want to help, check the Github link in the top right corner.
<br /><br />More resources for Unholy:<br />
<a href=" https://discord.gg/acherus" target="_blank" rel="noopener noreferrer">Death Knight Class Discord</a> <br />
<a href="http://www.wowhead.com/unholy-death-knight-guide" target="_blank" rel="noopener noreferrer">Wowhead Guide</a> <br />
<a href="https://www.icy-veins.com/wow/unholy-death-knight-pve-dps-guide" target="_blank" rel="noopener noreferrer">Icy Veins Guide</a> <br />
<a href="https://discord.gg/AyW5RUW" target="_blank" rel="noopener noreferrer">Unholy Spec Discord</a>
</>
),
// A recent example report to see interesting parts of the spec. Will be shown on the homepage.
exampleReport: '/report/DPwyKpWBZ6F947mx/2-Normal+Mekkatorque+-+Kill+(7:19)/24-Ifluffels',
// Don't change anything below this line;
// The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
spec: SPECS.UNHOLY_DEATH_KNIGHT,
// The contents of your changelog.
changelog: CHANGELOG,
// The CombatLogParser class for your spec.
parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "UnholyDeathKnight" */).then(exports => exports.default)),
// The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
path: __dirname,
};
|
src/connect.js | UniversalAvenue/react-compose | import React from 'react';
import _ from 'lodash';
import getDisplayName from './getDisplayName';
const defaultMergeProps = (stateProps, dispatchProps, parentProps) => ({
...parentProps,
...stateProps,
...dispatchProps,
});
function createDispatchProps(dispatchers, dispatch) {
if (_.isFunction(dispatchers)) {
return dispatchers(dispatch);
}
function dispatchHandler(fn) {
const action = _.isString(fn) ? { type: fn } : fn;
return () => dispatch(action);
}
return _.reduce(dispatchers, (sum, fn, key) =>
Object.assign(sum, {
[key]: dispatchHandler(fn),
}),
{});
}
function wrapLifeCycle(fn) {
if (!_.isFunction(fn)) {
const action = _.isString(fn) ? { type: fn } : fn;
return function wrappedStaticLifeCycleMethod() {
this.dispatch(action);
};
}
return fn;
}
export default function connect(reducer,
dispatchers,
lifeCycle = {},
merge = defaultMergeProps,
middlewares = []) {
return (Component) => {
class Connected extends React.Component {
constructor(props) {
super(props);
this.state = reducer(props, {});
this.dispatch = this.dispatch.bind(this);
const middlewareAPI = {
getState: () => this.state,
dispatch: this.dispatch,
};
const chain = middlewares.map(middleware => middleware(middlewareAPI));
this.dispatch = [...chain].reduceRight((a, fn) => fn(a), this.dispatch);
this.dispatchProps = createDispatchProps(dispatchers, this.dispatch);
}
componentWillReceiveProps(nextProps) {
this.setState(_.omitBy(nextProps, (val, key) =>
val === this.state[key]));
}
getProps() {
return merge(this.state, this.dispatchProps, this.props);
}
dispatch(action) {
const nextState = reducer(this.state, action);
if (nextState !== this.state) {
this.setState(nextState);
}
return action;
}
render() {
return <Component {...this.getProps()} />;
}
}
Connected.displayName = `connect(${getDisplayName(Component)})`;
_.each(lifeCycle, (fn, key) => Object.assign(Connected.prototype, {
[key]: wrapLifeCycle(fn),
}));
return Connected;
};
}
export function applyMiddleware(...wares) {
return (...args) => connect.apply(null,
[args[0], args[1], args[2] || {}, args[3] || defaultMergeProps, wares]);
}
|
docs/app/Examples/views/Statistic/Types/TopLabel.js | jcarbo/stardust | import React from 'react'
import { Statistic } from 'stardust'
const TopLabel = () => (
<div>
<Statistic>
<Statistic.Label>Views</Statistic.Label>
<Statistic.Value>40,509</Statistic.Value>
</Statistic>
</div>
)
export default TopLabel
|
js/components/layout/customRow.js | LetsBuildSomething/vmag_mobile |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Button, Icon, Left, Right, Body } from 'native-base';
import { Grid, Row } from 'react-native-easy-grid';
import { Actions } from 'react-native-router-flux';
import { openDrawer } from '../../actions/drawer';
const {
popRoute,
} = actions;
class CustomRow extends Component { // eslint-disable-line
static propTypes = {
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
return (
<Container>
<Header>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Custom Row</Title>
</Body>
<Right />
</Header>
<Grid>
<Row size={1} style={{ backgroundColor: '#635DB7' }} />
<Row size={2} style={{ backgroundColor: '#00CE9F' }} />
<Row size={4} style={{ backgroundColor: '#DD9E2C' }} />
</Grid>
</Container>
);
}
}
function bindAction(dispatch) {
return {
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(CustomRow);
|
app/createuser.js | conveyal/datatools-user-manager | import React from 'react'
import { Button, Modal, Input } from 'react-bootstrap'
import UserSettings from './usersettings'
import { UserPermissions } from 'datatools-common'
export default class CreateUser extends React.Component {
constructor (props) {
super(props)
this.state = {
showModal: false
}
}
close () {
this.setState({
showModal: false
})
this.props.createUser(this.refs.email.getValue(), this.refs.password.getValue(), this.refs.userSettings.getSettings())
}
open () {
console.log('opening..')
this.setState({
showModal: true
})
}
render () {
return (
<div>
<Button
bsStyle='primary'
bsSize='large'
onClick={this.open.bind(this)}
className='pull-right'
>
Create User
</Button>
<Modal show={this.state.showModal} onHide={this.close.bind(this)}>
<Modal.Header closeButton>
<Modal.Title>Create User</Modal.Title>
</Modal.Header>
<Modal.Body>
<Input ref='email' type='email' label='Email Address' placeholder='Enter email' />
<Input ref='password' type='password' label='Password' />
<UserSettings
projects={this.props.projects}
userPermissions={new UserPermissions()}
ref='userSettings'
/>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close.bind(this)}>Create User</Button>
</Modal.Footer>
</Modal>
</div>
)
}
}
|
src/svg-icons/action/help.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionHelp = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"/>
</SvgIcon>
);
ActionHelp = pure(ActionHelp);
ActionHelp.displayName = 'ActionHelp';
ActionHelp.muiName = 'SvgIcon';
export default ActionHelp;
|
src/components/Cart/updateQuantity.js | nikhilfusion/substitutionApp | import React, { Component } from 'react';
import PropTypes from 'prop-types';
require('./updateQuantity.css');
export default class UpdateQuantity extends Component {
constructor(props) {
super(props);
this.updateQty.bind(this);
this.state = {
itemId: '',
quantity: 0
}
}
updateQty(itemId, quantity) {
if(quantity < 0) {
quantity = 0;
}
let localData = JSON.parse(localStorage.getItem("cartData"));
if(!localData) {
localData = [];
}
let index = localData.findIndex((dt) => {
return dt.itemId === itemId
});
if(index < 0) {
localData.push({itemId: itemId, quantity: quantity});
} else {
localData[index].quantity = quantity;
}
localStorage.setItem("cartData", JSON.stringify(localData));
this.props.onChange(itemId, quantity);
}
render() {
const { itemId, quantity } = this.props;
return(
<div className="qtyContainer">
<div className="qtyInnerConainer">
<button className="btn-update-qty" onClick={() => this.updateQty(itemId, quantity - 1 : 0)}>-</button>
<div className="quantity">{quantity || 0}</div>
<button className="btn-update-qty" onClick={() => this.updateQty(itemId , quantity + 1)}>+</button>
</div>
</div>
);
}
}
UpdateQuantity.defaultProps = {
updateQty: () => { throw new Error('updateQuantity is not passed'); },
};
UpdateQuantity.propTypes = {
quantity: PropTypes.number,
updateQty: PropTypes.func,
itemId: PropTypes.number,
};
|
index.ios.js | yamashiro0110/ReactNative | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, View, Navigator, TouchableHighlight, } from 'react-native';
import AwesomeSummary from './components/scenes/awesome_summary_scene';
// import AwesomeNavigationBar from './components/view/awesome_navigation_bar';
// import AwesomeTableView from './components/view/awesome_tableview';
export default class AwesomeProject extends Component {
constructor() {
super();
}
render() {
return (
<AwesomeSummary></AwesomeSummary>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ecf0f1',
},
body: {
backgroundColor: '#607D8B',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
backgroundColor: '#009688',
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
|
app/javascript/mastodon/features/ui/components/actions_modal.js | honpya/taketodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import StatusContent from '../../../components/status_content';
import Avatar from '../../../components/avatar';
import RelativeTimestamp from '../../../components/relative_timestamp';
import DisplayName from '../../../components/display_name';
import IconButton from '../../../components/icon_button';
import classNames from 'classnames';
export default class ActionsModal extends ImmutablePureComponent {
static propTypes = {
status: ImmutablePropTypes.map,
actions: PropTypes.array,
onClick: PropTypes.func,
};
renderAction = (action, i) => {
if (action === null) {
return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
}
const { icon = null, text, meta = null, active = false, href = '#' } = action;
return (
<li key={`${text}-${i}`}>
<a href={href} target='_blank' rel='noopener' onClick={this.props.onClick} data-index={i} className={classNames({ active })}>
{icon && <IconButton title={text} icon={icon} role='presentation' tabIndex='-1' />}
<div>
<div className={classNames({ 'actions-modal__item-label': !!meta })}>{text}</div>
<div>{meta}</div>
</div>
</a>
</li>
);
}
render () {
const status = this.props.status && (
<div className='status light'>
<div className='boost-modal__status-header'>
<div className='boost-modal__status-time'>
<a href={this.props.status.get('url')} className='status__relative-time' target='_blank' rel='noopener'>
<RelativeTimestamp timestamp={this.props.status.get('created_at')} />
</a>
</div>
<a href={this.props.status.getIn(['account', 'url'])} className='status__display-name'>
<div className='status__avatar'>
<Avatar account={this.props.status.get('account')} size={48} />
</div>
<DisplayName account={this.props.status.get('account')} />
</a>
</div>
<StatusContent status={this.props.status} />
</div>
);
return (
<div className='modal-root__modal actions-modal'>
{status}
<ul>
{this.props.actions.map(this.renderAction)}
</ul>
</div>
);
}
}
|
renderer/components/PrefillDialog.js | mjswensen/themer-gui | import React from 'react';
import { connect } from 'react-redux';
import Button from './Button';
import Radio from './Radio';
import Emoji from './Emoji';
import {
closeDialogs,
prefillColorSetSelectionChange,
prefillWithColorSet,
} from '../actions';
import { colors as colorsDefault } from 'themer-colors-default';
import { colors as colorsNightSky } from 'themer-colors-night-sky';
import { colors as colorsOne } from 'themer-colors-one';
import { colors as colorsPolarIce } from 'themer-colors-polar-ice';
import { colors as colorsLucid } from 'themer-colors-lucid';
import { colors as colorsFingerPaint } from 'themer-colors-finger-paint';
import { colors as colorsSolarized } from 'themer-colors-solarized';
import { colors as colorsGitHubUniverse } from 'themer-colors-github-universe';
import { colors as colorsNova } from 'themer-colors-nova';
import formCss from './FormDialogs.css';
import css from './PrefillDialog.css';
const PrefillDialog = ({ prefillColorSetSelection, onClose, onPrefillColorSetSelect, onPrefillWithColorSet }) => (
<div className={ css.container }>
<p>
<Emoji emoji="⚠️" right />
<strong>Warning:</strong> prefilling with a built-in color set will overwrite any existing colors.
</p>
<form>
<fieldset className={ `${formCss.fieldset} ${css.fieldset}` }>
<legend>Built-in Color Sets</legend>
<Radio
value="themer-colors-default"
label="Default"
selected={ prefillColorSetSelection === 'themer-colors-default' }
onSelect={ onPrefillColorSetSelect }
/>
<Radio
value="themer-colors-night-sky"
label="Night Sky"
selected={ prefillColorSetSelection === 'themer-colors-night-sky' }
onSelect={ onPrefillColorSetSelect }
/>
<Radio
value="themer-colors-one"
label="One"
selected={ prefillColorSetSelection === 'themer-colors-one' }
onSelect={ onPrefillColorSetSelect }
/>
<Radio
value="themer-colors-polar-ice"
label="Polar Ice"
selected={ prefillColorSetSelection === 'themer-colors-polar-ice' }
onSelect={ onPrefillColorSetSelect }
/>
<Radio
value="themer-colors-lucid"
label="Lucid"
selected={ prefillColorSetSelection === 'themer-colors-lucid' }
onSelect={ onPrefillColorSetSelect }
/>
<Radio
value="themer-colors-finger-paint"
label="Finger Paint"
selected={ prefillColorSetSelection === 'themer-colors-finger-paint' }
onSelect={ onPrefillColorSetSelect }
/>
<Radio
value="themer-colors-solarized"
label="Solarized"
selected={ prefillColorSetSelection === 'themer-colors-solarized' }
onSelect={ onPrefillColorSetSelect }
/>
<Radio
value="themer-colors-github-universe"
label="GitHub Universe"
selected={ prefillColorSetSelection === 'themer-colors-github-universe' }
onSelect={ onPrefillColorSetSelect }
/>
<Radio
value="themer-colors-nova"
label="Nova"
selected={ prefillColorSetSelection === 'themer-colors-nova' }
onSelect={ onPrefillColorSetSelect }
/>
</fieldset>
</form>
<div className={ formCss.footer }>
<Button onClick={ onClose }>Cancel</Button>
<Button
primary
disabled={ !prefillColorSetSelection }
onClick={ () => onPrefillWithColorSet(prefillColorSetSelection) }
>Prefill</Button>
</div>
</div>
);
const mapStateToProps = state => ({
prefillColorSetSelection: state.prefillColorSetSelection,
});
const mapDispatchToProps = dispatch => ({
onClose: () => {
dispatch(closeDialogs());
},
onPrefillColorSetSelect: (selection) => {
dispatch(prefillColorSetSelectionChange(selection));
},
onPrefillWithColorSet: (selection) => {
switch (selection) {
case 'themer-colors-default':
dispatch(prefillWithColorSet(colorsDefault));
break;
case 'themer-colors-night-sky':
dispatch(prefillWithColorSet(colorsNightSky));
break;
case 'themer-colors-one':
dispatch(prefillWithColorSet(colorsOne));
break;
case 'themer-colors-polar-ice':
dispatch(prefillWithColorSet(colorsPolarIce));
break;
case 'themer-colors-lucid':
dispatch(prefillWithColorSet(colorsLucid));
break;
case 'themer-colors-finger-paint':
dispatch(prefillWithColorSet(colorsFingerPaint));
break;
case 'themer-colors-solarized':
dispatch(prefillWithColorSet(colorsSolarized));
break;
case 'themer-colors-github-universe':
dispatch(prefillWithColorSet(colorsGitHubUniverse));
break;
case 'themer-colors-nova':
dispatch(prefillWithColorSet(colorsNova));
break;
default:
dispatch(prefillWithColorSet(colorsDefault));
break;
}
dispatch(closeDialogs());
},
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(PrefillDialog);
|
components/Home/DisplayAlert.js | k97/node-slasher-app | import React, { Component } from 'react';
class DisplayAlert extends React.Component {
constructor(props) {
super(props);
}
render() {
var alertType = this.props.type.toLowerCase();
if (!this.props.msg) {
var msgVal = (alertType == 'success') ? 'Success' : 'Error';
}
return (
<div>
<section className={`cf br1 ba b--black-20 black-60 ${alertType == 'success' ? 'bg-light-green' : 'bg-light-red'}`}>
<div className="fl w-90 pa2 mt1">
<i className={`ml2 mr3 f3 v-mid ${alertType == 'success' ? 'ion-ios-checkmark-outline' : 'ion-android-warning'}`}></i>
<span className="lh-copy ">{this.props.msg || msgVal}</span>
</div>
{/*<div className="fl w-10">
<span className="db tc f3 mt2 pointer black-70 v-mid pa1">×</span>
</div>*/}
</section>
</div>
);
}
}
export default DisplayAlert;
|
screens/home/components/account-details.js | keuss/react-router-redux-sandbox | /**
* Created by Adrien on 17/04/2016.
*/
import React from 'react'
import Expense from './expense-line'
export default class AccountDetails extends React.Component {
render() {
return (
<div id="accDetails">
{this.props.expenses.map( (expense, i) => (<Expense key={i} data={expense} />))}
</div>
)
}
}
|
src/component/VirtualGrid.js | kavithaLK/react-virtualgrid | import React, { Component } from 'react';
import { Nav, NavbarHeader, Navbar, NavItem, NavDropdown, MenuItem, FormGroup, FormControl,Button } from 'react-bootstrap';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import VerticalScrollbar from './virtual-scrollbar.js';
import {LRUCache} from 'js-lru/lru.js';
//import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
require('./_Scrollbar.sass')
export class VirtualGrid extends React.Component {
constructor(props){
super(props);
this.initialOffset = -this.props.itemHeight;
let cachenew = new LRUCache(1000);
this.numberOfDiv = Math.floor(this.props.height/this.props.itemHeight);
this.numberofColumns = Math.ceil(this.props.width/this.props.itemWidth);
this.numBufferExtraElements = 1; // applies to both ends for the viewPort
this.maxRange = this.props.height;
this.numberofItemsTobeLoadedInAdvance = this.numberOfDiv + (5 * this.numBufferExtraElements);
this.state = {
startIndexRow:0, /* index from which data is to be fetched */
offset: this.initialOffset, /*Amount you have scrolled within a item */
vMovement:0, /* */
scrollAreaHeight: 100, /* Content Height */
scrollWrapperHeight:20, /* Wrapper Height */
getPromise :function (index){},
components : [],
cache:{},
lrucache:cachenew,
maxLoadedElements: (2 * this.numberOfDiv) + 5 * this.numBufferExtraElements
}
}
// from start index to number of rows on screen + buffers
getRangeElements() {
return this.state.startIndexRow + this.numberOfDiv + this.numBufferExtraElements;
}
//
getMaxOffset() {
return 2 * this.numBufferExtraElements * this.props.itemHeight;
}
// pushing button down and virtual scrolling up
getDown(stepIncrementRaw){
let stepIncrement = stepIncrementRaw;
let startIndexNew = this.state.startIndexRow;
if (Math.abs(stepIncrementRaw) > this.props.itemHeight) { // moved too high (end of virtual buffer)
startIndexNew = startIndexNew + Math.floor(stepIncrementRaw/this.props.itemHeight);
stepIncrement = stepIncrementRaw % this.props.itemHeight;
}
//Stop rendering if you hit border, in case server does not return anything do not render
var tt = this.state.offset - stepIncrement; // negative addition: moving higher
if(tt <= -this.getMaxOffset()) {
startIndexNew = startIndexNew + 1;
//console.log('down additioanl offset ' + (tt + this.getMaxOffset()));
tt = this.initialOffset + (tt + this.getMaxOffset() );
}
this.setState({
offset : tt,
startIndexRow: startIndexNew
}, this.chainPromisesRow());
}
getUp(stepIncrementRaw) {
let stepIncrement = stepIncrementRaw;
let startIndexNew = this.state.startIndexRow;
if (Math.abs(stepIncrementRaw) > this.props.itemHeight) {// hit margin going down
startIndexNew = startIndexNew - Math.floor(-stepIncrementRaw/this.props.itemHeight);
stepIncrement = stepIncrementRaw % this.props.itemHeight;
};
var tt = this.state.offset - stepIncrement; // step is already negative, need to push down
//Go up if pixel greater than 0
if(tt >= 0) {
//console.log('additioanl offset ' + tt);
tt = this.initialOffset + tt;
startIndexNew = startIndexNew - 1;
};
this.setState({
offset : tt,
startIndexRow : startIndexNew
}, this.chainPromisesRow());
}
hitMax(){
this.loadMore();
}
handleChangePosition(movement, orientation) {
let virtualHeight=(this.getRangeElements()) * this.props.itemHeight;
if (movement >=0 && movement <= virtualHeight ) {
let newMove = movement - this.state.vMovement;
//console.log(" movement " + movement + "," + newMove);
if (newMove > 0) {
this.getDown(newMove)
} else {
this.getUp(newMove)
}
this.setState({vMovement: movement});
}
}
componentDidMount() {
this.chainPromisesRow();
// this.fetchInitalData();
this.calculateSize()
// Attach The Event for Responsive View~
window.addEventListener('resize', this.calculateSize.bind(this))
}
componentWillUnmount(){
// Remove Event
window.removeEventListener('resize', this.calculateSize.bind(this))
}
handleScrollbarDragging(e){
//console.log("dragging " + e)
}
handleScrollbarStopDrag(e){
//console.log("stop drag " + e)
}
getSize(){
// The Elements
let $scrollArea = this.refs.scrollArea
let $scrollWrapper = this.refs.scrollWrapper
// Get new Elements Size
let elementSize = {
// Scroll Area Height and Width
scrollAreaHeight: this.getRangeElements() * this.props.itemHeight,
// Scroll Wrapper Height and Width
scrollWrapperHeight: this.numberOfDiv * this.props.itemHeight
}
return elementSize
}
calculateSize(cb){
let elementSize = this.getSize()
if( elementSize.scrollWrapperHeight != this.state.scrollWrapperHeight ||
elementSize.scrollAreaHeight != this.state.scrollAreaHeight )
{
// Set the State!
this.setState(elementSize);
}
}
chainPromisesRow() {
var sIndex = this.state.startIndexRow;
_.range(sIndex, sIndex + this.numberofItemsTobeLoadedInAdvance).map((x) => {
let itemIndexList = this.getItemIndexes(x);
for(var itemIndex = 0; itemIndex <= itemIndexList.length; itemIndex++) {
let handlerFunc = ((id) => {
return (result) => {
var temp = this.state.lrucache;
temp.put(id,result);
//console.log(result);
this.setState({lrucache: temp});
}
}) (itemIndexList[itemIndex]);
this.getPromiseWrapper(itemIndexList[itemIndex], handlerFunc);
}
})
}
loadMore() {
let endElement = this.state.startIndexRow + this.numberofItemsTobeLoadedInAdvance;//incrememnting number of loaded elelemnts
if (endElement > this.state.maxLoadedElements) {
this.setState({
maxLoadedElements : endElement
})
}
}
getPromiseWrapper(index, handler){
if(this.state.lrucache.get(index) === null) {
return; //do nothing; promise already kicked off
}
if(this.state.lrucache.get(index) !== undefined) {
return this.state.lrucache.get(index);
} else {
this.state.lrucache.put(index, null);
(this.props.getPromise(index)).then(handler)
}
}
getItemIndexes(rowIndex){
let itemIndexes = [];
let end = this.numberofColumns * (rowIndex +1);
let start = end - this.numberofColumns;
for (var i = start; i < end; i++){
itemIndexes.push(i);
}
return itemIndexes;
}
getItemsForRow(rowIndex) {
let listShow = [];
//if(rowIndex < 0) return ;
var itemStyle ={
position:"relative",
height : this.props.itemHeight,
width: this.props.itemWidth,
flexGrow:0,
flexShrink:0,
}
let listIndexes = this.getItemIndexes(rowIndex);
for (var i=0; i<listIndexes.length; i++) {
if(this.state.lrucache.get(listIndexes[i])) {
listShow.push(
// <ReactCSSTransitionGroup transitionName="example" transitionAppear={true}
// transitionAppearTimeout={100}
// transitionEnterTimeout={10}
// transitionLeaveTimeout={10}
// >
<div style={itemStyle} key={listIndexes[i]}>{this.state.lrucache.get(listIndexes[i])}</div>
//</ReactCSSTransitionGroup>
);
} else {
listShow.push(<div key={listIndexes[i]} style={itemStyle}><div className="loader"></div></div>);
//listShow.push(<div key={listIndexes[i]} style={itemStyle}><h2>Loading...</h2></div>);
}
}
return listShow;
}
render(){
var styleName = {
width : this.props.width,
height : this.props.height,
border : '1px solid black',
backgroundColor :'#f3f3f3',
overflow:'hidden',
};
var contentStyle = {
position:"relative",
marginTop: this.state.offset ,
}
var parentStyle= {
display:'flex',
height:this.props.itemHeight,
}
return (
<div >
<div style={parentStyle}>
<div id="viewPort" style={styleName} ref="scrollWrapper">
<div id="content" ref="scrollArea" style={contentStyle} >
{
_.range(this.state.startIndexRow -1 , this.state.startIndexRow + this.numberOfDiv + this.numBufferExtraElements)
.map((x) => {
return(<div style={parentStyle} key={x}>
{this.getItemsForRow(x)}
</div>)
})
}
</div>
</div>
<VerticalScrollbar
height={this.props.height}
maxRange={this.maxRange}
virtualHeight={this.state.maxLoadedElements * this.props.itemHeight}
area={{ height: this.state.maxLoadedElements * this.props.itemHeight}}
wrapper={{ height: this.numberOfDiv * this.props.itemHeight}}
scrolling={ this.state.vMovement } //int
draggingFromParent={ true }// boolean
onChangePosition={ this.handleChangePosition.bind(this) }
onDragging={ this.handleScrollbarDragging.bind(this) }
onStopDrag={ this.handleScrollbarStopDrag.bind(this) }
onHitMax ={this.hitMax.bind(this)}
/>
</div>
</div>
);
}
}
VirtualGrid.defaultProps = {
speed: 53,
className: ""
}
VirtualGrid.propTypes = {
width : React.PropTypes.number.isRequired,
height : React.PropTypes.number.isRequired,
itemWidth : React.PropTypes.number.isRequired,
itemHeight : React.PropTypes.number.isRequired,
getPromise : React.PropTypes.func.isRequired
}
/**
*
*/
|
examples/huge-apps/routes/Course/routes/Grades/components/Grades.js | cgrossde/react-router | import React from 'react';
class Grades extends React.Component {
render () {
var assignments = COURSES[this.props.params.courseId].assignments;
return (
<div>
<h3>Grades</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>{assignment.grade} - {assignment.title}</li>
))}
</ul>
</div>
);
}
}
export default Grades;
|
src/svg-icons/action/lightbulb-outline.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLightbulbOutline = (props) => (
<SvgIcon {...props}>
<path d="M9 21c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-1H9v1zm3-19C8.14 2 5 5.14 5 9c0 2.38 1.19 4.47 3 5.74V17c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2.26c1.81-1.27 3-3.36 3-5.74 0-3.86-3.14-7-7-7zm2.85 11.1l-.85.6V16h-4v-2.3l-.85-.6C7.8 12.16 7 10.63 7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 1.63-.8 3.16-2.15 4.1z"/>
</SvgIcon>
);
ActionLightbulbOutline = pure(ActionLightbulbOutline);
ActionLightbulbOutline.displayName = 'ActionLightbulbOutline';
ActionLightbulbOutline.muiName = 'SvgIcon';
export default ActionLightbulbOutline;
|
CompositeUi/src/views/component/TaskPreview.js | kreta/kreta | /*
* This file is part of the Kreta package.
*
* (c) Beñat Espiña <[email protected]>
* (c) Gorka Laucirica <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import './../../scss/components/_task-preview.scss';
import classnames from 'classnames';
import React from 'react';
import UserThumbnail from './UserThumbnail';
class TaskPreview extends React.Component {
static propTypes = {
onClick: React.PropTypes.func.isRequired,
task: React.PropTypes.object.isRequired,
};
static TASK_PRIORITIES = {
LOW: '#67b86a',
MEDIUM: '#f07f2c',
HIGH: '#f02c4c',
};
getPriorityColor(priority) {
priority = priority.toUpperCase();
return TaskPreview.TASK_PRIORITIES[priority];
}
render() {
const {onClick, task} = this.props,
priority = task.priority.toLowerCase(),
progress = task.progress.toLowerCase(),
assignee = task.assignee,
classes = classnames({
'task-preview': true,
'task-preview--highlight': this.props.selected,
'task-preview--closed': progress === 'done',
});
return (
<div className={classes} onClick={onClick}>
<a className="task-preview__title">
{task.title}
</a>
<div className="task-preview__icons">
<span>
<svg
className={`task-preview__priority task-preview__priority--${progress}`}
>
<circle
className="task-preview__priority-back"
cx="21"
cy="21"
r="20"
style={{stroke: this.getPriorityColor(priority)}}
/>
<circle
className="task-preview__priority-front"
cx="21"
cy="21"
r="20"
style={{stroke: this.getPriorityColor(priority)}}
transform="rotate(-90, 21, 21)"
/>
</svg>
<UserThumbnail user={assignee} />
</span>
</div>
</div>
);
}
}
export default TaskPreview;
|
src/components/Navigation.js | chrisfitkin/cf-event-planner-3 | import React from 'react'
// import IconButton from 'material-ui/IconButton'
// import IconMenu from 'material-ui/IconMenu'
// import MenuItem from 'material-ui/MenuItem'
import FlatButton from 'material-ui/FlatButton'
// import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'
// import { IndexLink, Link } from 'react-router'
import { Link } from 'react-router'
// import './Navigation.scss'
let styles = {
color: '#ffffff'
}
const Navigation = () => (
<div style={{marginTop: 7}}>
<FlatButton style={styles} label="Add" containerElement={
<Link to="/create" activeClassName='route--active' />
}/>
<FlatButton style={styles} label="Register" containerElement={
<Link to="/register" activeClassName='route--active' />
}/>
</div>
)
// export const Navigation = () => (
// <IconMenu
// iconButtonElement={
// <IconButton iconStyle={styles}><MoreVertIcon /></IconButton>
// }
// targetOrigin={{horizontal: 'right', vertical: 'top'}}
// anchorOrigin={{horizontal: 'right', vertical: 'top'}}
// >
// <MenuItem
// containerElement={<IndexLink to="/" activeClassName='route--active' />}
// primaryText="Events"
// />
// <MenuItem
// containerElement={<Link to="/create" activeClassName='route--active' />}
// primaryText="Create Event"
// />
// <MenuItem
// containerElement={<Link to="/register" activeClassName='route--active' />}
// primaryText="Register"
// />
// </IconMenu>
// )
export default Navigation
|
app/components/Settings.js | mzanini/DeeMemory | import React from 'react'
import TablesSetup from '../containers/TablesSetup'
const Settings = () => (
<TablesSetup/>
)
export default Settings
|
src/components/todoApp.js | mobxjs/mobx-react-todomvc | import React from 'react';
import PropTypes from 'prop-types';
import {observer} from 'mobx-react';
import TodoEntry from './todoEntry';
import TodoOverview from './todoOverview';
import TodoFooter from './todoFooter';
import { ALL_TODOS, ACTIVE_TODOS, COMPLETED_TODOS } from '../constants';
import DevTool from 'mobx-react-devtools';
@observer
export default class TodoApp extends React.Component {
render() {
const {todoStore, viewStore} = this.props;
return (
<div>
<DevTool />
<header className="header">
<h1>todos</h1>
<TodoEntry todoStore={todoStore} />
</header>
<TodoOverview todoStore={todoStore} viewStore={viewStore} />
<TodoFooter todoStore={todoStore} viewStore={viewStore} />
</div>
);
}
componentDidMount() {
if (__CLIENT__) {
var { Router } = require('director/build/director');
var viewStore = this.props.viewStore;
var router = Router({
'/': function() { viewStore.todoFilter = ALL_TODOS; },
'/active': function() { viewStore.todoFilter = ACTIVE_TODOS; },
'/completed': function() { viewStore.todoFilter = COMPLETED_TODOS; }
});
router.init('/');
}
}
}
TodoApp.propTypes = {
viewStore: PropTypes.object.isRequired,
todoStore: PropTypes.object.isRequired
};
|
client/components/navigation/Navigation.js | jkettmann/relay-authentication | import React from 'react'
import PropTypes from 'prop-types'
import { createFragmentContainer, graphql } from 'react-relay'
import Drawer from 'material-ui/Drawer'
import IconButton from 'material-ui/IconButton'
import NavigationClose from 'material-ui/svg-icons/navigation/close'
import MenuItem from 'material-ui/MenuItem'
import Divider from 'material-ui/Divider'
import UserMenu from './NavigationUserMenu'
const Navigation = ({ open, close, viewer, navigateTo }) => (
<Drawer open={open}>
<IconButton onClick={close}>
<NavigationClose />
</IconButton>
<Divider />
<UserMenu viewer={viewer} navigateTo={navigateTo} />
<Divider />
<MenuItem onClick={() => navigateTo('/posts')}>Posts</MenuItem>
</Drawer>
)
Navigation.propTypes = {
open: PropTypes.bool.isRequired,
close: PropTypes.func.isRequired,
navigateTo: PropTypes.func.isRequired,
// eslint-disable-next-line react/forbid-prop-types
viewer: PropTypes.object,
}
Navigation.defaultProps = {
viewer: {},
}
export default createFragmentContainer(
Navigation,
graphql`
fragment Navigation_viewer on Viewer {
...NavigationUserMenu_viewer
}
`,
)
|
src/PerfViewJS/spa/src/App.js | vancem/perfview | import React, { Component } from 'react';
import { Route } from 'react-router';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import { EventList } from './components/EventList';
import { ProcessList } from './components/ProcessList';
import { Hotspots } from './components/Hotspots';
import { Callers } from './components/Callers';
import { EventViewer } from './components/EventViewer';
export default class App extends Component {
static displayName = App.name;
render() {
return (
<Layout>
<Route exact path='/' component={Home} />
<Route path='/ui/events/:dataFile' component={EventViewer} />
<Route path='/ui/eventlist/:dataFile' component={EventList} />
<Route path='/ui/processlist/:dataFile/:stackType' component={ProcessList} />
<Route path='/ui/hotspots/:routeKey' component={Hotspots} />
<Route path='/ui/callers/:routeKey/:callTreeNodeId' component={Callers} />
</Layout>
);
}
}
|
frontend/src/Activity/Blocklist/BlocklistConnector.js | Radarr/Radarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import * as commandNames from 'Commands/commandNames';
import withCurrentPage from 'Components/withCurrentPage';
import * as blocklistActions from 'Store/Actions/blocklistActions';
import { executeCommand } from 'Store/Actions/commandActions';
import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector';
import { registerPagePopulator, unregisterPagePopulator } from 'Utilities/pagePopulator';
import Blocklist from './Blocklist';
function createMapStateToProps() {
return createSelector(
(state) => state.blocklist,
createCommandExecutingSelector(commandNames.CLEAR_BLOCKLIST),
(blocklist, isClearingBlocklistExecuting) => {
return {
isClearingBlocklistExecuting,
...blocklist
};
}
);
}
const mapDispatchToProps = {
...blocklistActions,
executeCommand
};
class BlocklistConnector extends Component {
//
// Lifecycle
componentDidMount() {
const {
useCurrentPage,
fetchBlocklist,
gotoBlocklistFirstPage
} = this.props;
registerPagePopulator(this.repopulate);
if (useCurrentPage) {
fetchBlocklist();
} else {
gotoBlocklistFirstPage();
}
}
componentDidUpdate(prevProps) {
if (prevProps.isClearingBlocklistExecuting && !this.props.isClearingBlocklistExecuting) {
this.props.gotoBlocklistFirstPage();
}
}
componentWillUnmount() {
this.props.clearBlocklist();
unregisterPagePopulator(this.repopulate);
}
//
// Control
repopulate = () => {
this.props.fetchBlocklist();
};
//
// Listeners
onFirstPagePress = () => {
this.props.gotoBlocklistFirstPage();
};
onPreviousPagePress = () => {
this.props.gotoBlocklistPreviousPage();
};
onNextPagePress = () => {
this.props.gotoBlocklistNextPage();
};
onLastPagePress = () => {
this.props.gotoBlocklistLastPage();
};
onPageSelect = (page) => {
this.props.gotoBlocklistPage({ page });
};
onRemoveSelected = (ids) => {
this.props.removeBlocklistItems({ ids });
};
onSortPress = (sortKey) => {
this.props.setBlocklistSort({ sortKey });
};
onTableOptionChange = (payload) => {
this.props.setBlocklistTableOption(payload);
if (payload.pageSize) {
this.props.gotoBlocklistFirstPage();
}
};
onClearBlocklistPress = () => {
this.props.executeCommand({ name: commandNames.CLEAR_BLOCKLIST });
};
//
// Render
render() {
return (
<Blocklist
onFirstPagePress={this.onFirstPagePress}
onPreviousPagePress={this.onPreviousPagePress}
onNextPagePress={this.onNextPagePress}
onLastPagePress={this.onLastPagePress}
onPageSelect={this.onPageSelect}
onRemoveSelected={this.onRemoveSelected}
onSortPress={this.onSortPress}
onTableOptionChange={this.onTableOptionChange}
onClearBlocklistPress={this.onClearBlocklistPress}
{...this.props}
/>
);
}
}
BlocklistConnector.propTypes = {
useCurrentPage: PropTypes.bool.isRequired,
isClearingBlocklistExecuting: PropTypes.bool.isRequired,
items: PropTypes.arrayOf(PropTypes.object).isRequired,
fetchBlocklist: PropTypes.func.isRequired,
gotoBlocklistFirstPage: PropTypes.func.isRequired,
gotoBlocklistPreviousPage: PropTypes.func.isRequired,
gotoBlocklistNextPage: PropTypes.func.isRequired,
gotoBlocklistLastPage: PropTypes.func.isRequired,
gotoBlocklistPage: PropTypes.func.isRequired,
removeBlocklistItems: PropTypes.func.isRequired,
setBlocklistSort: PropTypes.func.isRequired,
setBlocklistTableOption: PropTypes.func.isRequired,
clearBlocklist: PropTypes.func.isRequired,
executeCommand: PropTypes.func.isRequired
};
export default withCurrentPage(
connect(createMapStateToProps, mapDispatchToProps)(BlocklistConnector)
);
|
src/components/Text.js | twhite96/checkyoself | /* jshint ignore: start */
import React from 'react';
import SimpleMDEReact from 'react-simplemde-editor';
import 'simplemde/dist/simplemde.min.css';
import Popup from 'reactjs-popup';
import BurgerIcon from '../components/BurgerIcon';
import Menu from '../components/Menu';
import '../smde-editor.css';
import writeGood from 'write-good';
import Footer from '../components/Footer';
import '../antd.css';
import { Popover } from '../antd.css';
const styles = {
fontFamily: 'sans-serif',
textAlign: 'center',
marginTop: '40px'
};
const contentStyle = {
background: 'rgba(255,255,255,0)',
width: '80%',
border: 'none'
};
const editorStyle = {
margin: '2em 2em'
};
// const WriteGood = ({ text }) => (
// <div>{writeGood(text).map(({ suggestion }) => suggestion)}</div>
// );
class Text extends React.Component {
constructor(props) {
super(props);
this.state = {
textValue: 'Check your markdown here.',
text: {}
};
this.handleWriteGood = this.handleWriteGood.bind(this);
}
extraKeys = () => {
return {
Up: function(cm) {
cm.replaceSelection(' surprise. ');
},
Down: function(cm) {
cm.replaceSelection(' surprise again! ');
}
};
};
handleChange1 = value => {
this.setState({
textValue: value
});
};
handleTextChange = markup => {
this.setState({
text: markup
});
};
handleWriteGood = text => {
writeGood(text).map(({ suggestion }) => suggestion);
}
render() {
return (
<React.Fragment>
<div>
<div style={styles}>
<Popup
modal
overlayStyle={{ background: 'rgba(255,255,255,0.98)' }}
contentStyle={contentStyle}
closeOnDocumentClick={false}
trigger={open => <BurgerIcon open={open} />}
>
{close => <Menu close={close} />}
</Popup>
{/* <button
style={{ display: "inline-block", margin: "10px 0" }}
onClick={this.handleTextChange}
>
Click me to update the textValue outside of the editor
</button> */}
<SimpleMDEReact
className="smde-editor-styles"
editorStyle={editorStyle}
// suggested={this.editorState}
label="Markdown Editor"
onChange={this.handleChange1}
options={{
autofocus: true,
spellChecker: true
// etc.
}}
value={this.state.textValue}
markup={this.state.text}
text={writeGood}
/>
</div>
</div>
<div>
<Footer />
</div>
</React.Fragment>
);
}
}
class SuggestionSpan extends React.Component {
render() {
let {suggestion, offsetKey, children} = this.props;
return (
<Popover content={suggestion.reason}>
<span data-offset-key={offsetKey} className="suggestion">
{children}
</span>
</Popover>
);
}
}
export default Text;
|
src/ui/pages/common/settings/index.js | dhruv-kumar-jha/productivity-frontend | 'use strict';
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
import Heading from 'app/components/common/Heading';
import CommonLayout from 'app/components/layout/Common';
import { FormattedMessage } from 'react-intl';
import GeneralSettings from './General';
import GroupsSettings from './Groups';
import { Tabs, Col } from 'antd';
class Settings extends Component {
constructor(props) {
super(props);
let tab = '';
if ( props.location.pathname.includes("/settings/general") ) { tab = "general"; }
if ( props.location.pathname.includes("/settings/groups") ) { tab = "groups"; }
this.state = {
currentTab: tab,
};
this.onTabChange = this.onTabChange.bind(this);
}
onTabChange(key) {
browserHistory.push(`/settings/${ key }`);
}
render() {
return (
<CommonLayout>
<Heading
title={<FormattedMessage id="settings.title" defaultMessage="Manage your Settings" />}
subtitle={<FormattedMessage id="settings.subtitle" defaultMessage="Manage and update your personal information, login details from here." />}
icon="setting" />
<Col xs={24} sm={{ span: 22, offset: 1 }} md={{ span: 22, offset: 1 }} lg={{ span: 22, offset: 1 }}>
<Tabs type="card" className="m-t-30 m-b-50 component--tabs" onChange={ this.onTabChange } defaultActiveKey={ this.state.currentTab }>
<Tabs.TabPane tab="General Settings" key="general">
{ this.props.children }
</Tabs.TabPane>
<Tabs.TabPane tab="Board Groups" key="groups">
{ this.props.children }
</Tabs.TabPane>
</Tabs>
</Col>
</CommonLayout>
);
}
}
export default Settings;
|
lib/js/apps/genetic-algorithms/Queens/Board.js | jneander/learning | import React from 'react';
import ChessBoard from 'js/apps/genetic-algorithms/shared/ChessBoard';
export default class Board extends React.PureComponent {
render () {
const board = [];
for (let row = 0; row < this.props.size; row++) {
board[row] = [];
for (let col = 0; col < this.props.size; col++) {
board[row].push(' ');
}
}
const positions = [];
if (this.props.chromosome) {
const { genes } = this.props.chromosome;
for (let i = 0; i < this.props.chromosome.genes.length; i += 2) {
positions.push({ row: genes[i], col: genes[i + 1], piece: '♛' });
}
}
return (
<ChessBoard positions={positions} size={this.props.size} />
);
}
}
|
src/svg-icons/notification/disc-full.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationDiscFull = (props) => (
<SvgIcon {...props}>
<path d="M20 16h2v-2h-2v2zm0-9v5h2V7h-2zM10 4c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm0 10c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
</SvgIcon>
);
NotificationDiscFull = pure(NotificationDiscFull);
NotificationDiscFull.displayName = 'NotificationDiscFull';
NotificationDiscFull.muiName = 'SvgIcon';
export default NotificationDiscFull;
|
src/svg-icons/content/redo.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentRedo = (props) => (
<SvgIcon {...props}>
<path d="M18.4 10.6C16.55 8.99 14.15 8 11.5 8c-4.65 0-8.58 3.03-9.96 7.22L3.9 16c1.05-3.19 4.05-5.5 7.6-5.5 1.95 0 3.73.72 5.12 1.88L13 16h9V7l-3.6 3.6z"/>
</SvgIcon>
);
ContentRedo = pure(ContentRedo);
ContentRedo.displayName = 'ContentRedo';
ContentRedo.muiName = 'SvgIcon';
export default ContentRedo;
|
client/portfolio2017/src/Components/TabMenu/TabMenu.js | corrortiz/portafolio2017 | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
//MUI Components
import Tabs, { Tab } from 'material-ui/Tabs';
import { withStyles } from 'material-ui/styles';
//HOC for global state
import GlobalsConnect from '../../HOC/GlobalsConnect/GlobalsConnect';
//locale
import { lenguajeSelector } from '../../Store/Actions/globals';
import { Home, Services, Projects, Contact } from '../../Assets/diccionary';
//Internal components
import HomeIcon from '../../images/SVG/Home';
import CodeIcon from '../../images/SVG/Code';
import ProjectsIcon from '../../images/SVG/Projects';
import ContactIcon from '../../images/SVG/Contact';
//CSS in JS Styles
const styles = theme => ({
root: {}
});
/**
* A component that renders a tab menu with icons
*/
export class TabMenu extends Component {
handleChange = (event, value) => {
this.props.setTabValue(value);
};
render() {
const { lenguaje, tabValue } = this.props.globals;
const { classes } = this.props;
return (
<div className={`header__bottonNavigation ${classes.root}`}>
<Tabs
value={tabValue}
onChange={this.handleChange}
indicatorColor="primary"
textColor="primary"
className="header__bottonNavigation__tabs"
centered
>
<Tab
label={lenguajeSelector(lenguaje, Home)}
icon={<HomeIcon />}
component={Link}
to={'/'}
/>
<Tab
label={lenguajeSelector(lenguaje, Services)}
icon={<CodeIcon />}
component={Link}
to={'/services'}
/>
<Tab
label={lenguajeSelector(lenguaje, Projects)}
icon={<ProjectsIcon />}
component={Link}
to={'/projects'}
/>
<Tab
label={lenguajeSelector(lenguaje, Contact)}
icon={<ContactIcon />}
component={Link}
to={'/contact'}
/>
</Tabs>
</div>
);
}
}
TabMenu.propTypes = {
globals: PropTypes.shape({
tabValue: PropTypes.number.isRequired,
lenguaje: PropTypes.string.isRequired
})
};
TabMenu = withStyles(styles)(TabMenu);
export default GlobalsConnect(TabMenu);
|
src/slides/six/obj-literals.js | brudil/slides-es6andbeyond | import React from 'react';
import Radium from 'radium';
import Snippet from '../../Snippet';
import {bindShowHelper} from '../../utils';
const styles = {
inlinePre: {
display: 'inline'
},
slide: {
textAlign: 'center'
}
};
const sourceSteps = [
`
const obj = {
username: username
};
`,
`
const obj = {
username // username: username
};
`,
`
const obj = {
__proto__: {}
};
`,
`
const obj = {
greet() {
return super.greet();
}
};
`,
`
const key = 'username';
const obj = {
[key]: 'david'; // username: 'david'
};
`
];
@Radium
export default class ObjectLiterals extends React.Component {
static actionCount = 4;
static propTypes = {
actionIndex: React.PropTypes.number.isRequired,
style: React.PropTypes.object.isRequired
}
render() {
const {actionIndex} = this.props;
const show = bindShowHelper(actionIndex);
return (
<div style={[this.props.style, styles.slide]}>
<h1>Object Literals</h1>
<Snippet source={show.withArray(sourceSteps, 0)} />
</div>
);
}
}
|
front_end/front_end_app/src/client/app/header.react.js | Horizon-Framework/horizon | import Component from '../components/component.react';
import React from 'react';
import {FormattedHTMLMessage} from 'react-intl';
import {Link} from 'react-router';
export default class Header extends Component {
static propTypes = {
msg: React.PropTypes.object.isRequired,
viewer: React.PropTypes.object
}
render() {
const {msg: {app: {header}}, viewer} = this.props;
return (
<header>
<h1>
<FormattedHTMLMessage message={header.h1Html} />
</h1>
<ul>
<li><Link to="home">{header.home}</Link></li>
<li><Link to="todos">{header.todos}</Link></li>
{/*<li><Link to="examples">{header.examples}</Link></li>*/}
<li><Link to="me">{header.me}</Link></li>
{!viewer &&
<li><Link to="login">{header.login}</Link></li>
}
</ul>
</header>
);
}
}
|
src/components/Editor/Editor.js | zhangjingge/sse-antd-admin | import React from 'react'
import { Editor } from 'react-draft-wysiwyg'
import styles from './Editor.less'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
const DraftEditor = (props) => {
return (<Editor toolbarClassName={styles.toolbar} wrapperClassName={styles.wrapper} editorClassName={styles.editor} {...props} />)
}
export default DraftEditor
|
src/index.js | nbuechler/studious-display | import 'babel-core/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import Root from './containers/Root';
ReactDOM.render(
<Root />,
document.getElementById('root')
);
|
src/routes/login/index.js | utage2002/mm | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import { defineMessages } from 'react-intl';
import Layout from '../../components/Layout';
import Login from './Login';
const messages = defineMessages({
title: {
id: 'login.title',
description: 'Log in page title',
defaultMessage: 'Log In',
},
});
function action({ intl }) {
const title = intl.formatMessage(messages.title);
return {
chunks: ['login'],
title,
component: (
<Layout>
<Login title={title} />
</Layout>
),
};
}
export default action;
|
actor-apps/app-web/src/app/components/DialogSection.react.js | alihalabyah/actor-platform | import _ from 'lodash';
import React from 'react';
import { PeerTypes } from 'constants/ActorAppConstants';
import MessagesSection from 'components/dialog/MessagesSection.react';
import TypingSection from 'components/dialog/TypingSection.react';
import ComposeSection from 'components/dialog/ComposeSection.react';
import DialogStore from 'stores/DialogStore';
import MessageStore from 'stores/MessageStore';
import GroupStore from 'stores/GroupStore';
import DialogActionCreators from 'actions/DialogActionCreators';
// On which scrollTop value start loading older messages
const LoadMessagesScrollTop = 100;
const initialRenderMessagesCount = 20;
const renderMessagesStep = 20;
let renderMessagesCount = initialRenderMessagesCount;
let lastPeer = null;
let lastScrolledFromBottom = 0;
const getStateFromStores = () => {
const messages = MessageStore.getAll();
let messagesToRender;
if (messages.length > renderMessagesCount) {
messagesToRender = messages.slice(messages.length - renderMessagesCount);
} else {
messagesToRender = messages;
}
return {
peer: DialogStore.getSelectedDialogPeer(),
messages: messages,
messagesToRender: messagesToRender
};
};
class DialogSection extends React.Component {
constructor(props) {
super(props);
this.state = getStateFromStores();
DialogStore.addSelectListener(this.onSelectedDialogChange);
MessageStore.addChangeListener(this.onMessagesChange);
}
componentWillUnmount() {
DialogStore.removeSelectListener(this.onSelectedDialogChange);
MessageStore.removeChangeListener(this.onMessagesChange);
}
componentDidUpdate() {
this.fixScroll();
this.loadMessagesByScroll();
}
render() {
const peer = this.state.peer;
if (peer) {
let isMember = true;
let memberArea;
if (peer.type === PeerTypes.GROUP) {
const group = GroupStore.getGroup(peer.id);
isMember = DialogStore.isGroupMember(group);
}
if (isMember) {
memberArea = (
<div>
<TypingSection/>
<ComposeSection peer={this.state.peer}/>
</div>
);
} else {
memberArea = (
<section className="compose compose--disabled row center-xs middle-xs">
<h3>You are not member</h3>
</section>
);
}
return (
<section className="dialog" onScroll={this.loadMessagesByScroll}>
<MessagesSection messages={this.state.messagesToRender}
peer={this.state.peer}
ref="MessagesSection"/>
{memberArea}
</section>
);
} else {
return (
<section className="dialog dialog--empty row middle-xs center-xs" ref="MessagesSection">
Select dialog or start a new one.
</section>
);
}
}
fixScroll = () => {
let node = React.findDOMNode(this.refs.MessagesSection);
node.scrollTop = node.scrollHeight - lastScrolledFromBottom;
}
onSelectedDialogChange = () => {
renderMessagesCount = initialRenderMessagesCount;
if (lastPeer != null) {
DialogActionCreators.onConversationClosed(lastPeer);
}
lastPeer = DialogStore.getSelectedDialogPeer();
DialogActionCreators.onConversationOpen(lastPeer);
}
onMessagesChange = _.debounce(() => {
this.setState(getStateFromStores());
}, 10, {maxWait: 50, leading: true});
loadMessagesByScroll = _.debounce(() => {
let node = React.findDOMNode(this.refs.MessagesSection);
let scrollTop = node.scrollTop;
lastScrolledFromBottom = node.scrollHeight - scrollTop;
if (node.scrollTop < LoadMessagesScrollTop) {
DialogActionCreators.onChatEnd(this.state.peer);
if (this.state.messages.length > this.state.messagesToRender.length) {
renderMessagesCount += renderMessagesStep;
if (renderMessagesCount > this.state.messages.length) {
renderMessagesCount = this.state.messages.length;
}
this.setState(getStateFromStores());
}
}
}, 5, {maxWait: 30});
}
export default DialogSection;
|
app/components/IssueIcon/index.js | rlagman/raphthelagman | import React from 'react';
import PropTypes from 'prop-types';
function IssueIcon(props) {
return (
<svg height="1em" width="0.875em" className={props.className} {...props}>
<path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" />
</svg>
);
}
IssueIcon.propTypes = {
className: PropTypes.string,
};
export default IssueIcon;
|
src/common/loader/index.js | WhileTruu/peers-against-humanity-frontend | import React from 'react'
import './Loader.scss'
const Loader = () => (
<div className="loader-container d-flex justify-content-center">
<img className="loader-image" src="/boulder1.svg" alt="boulder" />
<div className="loader-text-container">
<h2 className="loader-text text-primary">Loading...</h2>
</div>
</div>
)
export default Loader
|
src/Layout.js | sPyOpenSource/personal-website | import React, { Component } from 'react';
import Header from './components/header';
import Footer from './components/footer';
class Layout extends Component {
render() {
return (
<div>
<Header />
{this.props.children}
<Footer />
</div>
);
}
}
export default Layout;
|
app/containers/App.js | tidepool-org/chrome-uploader | /*
* == BSD2 LICENSE ==
* Copyright (c) 2014-2016, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
import _ from 'lodash';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Route, Switch } from 'react-router-dom';
import dns from 'dns';
import bows from 'bows';
import config from '../../lib/config.js';
import device from '../../lib/core/device.js';
import localStore from '../../lib/core/localStore.js';
import actions from '../actions/';
const asyncActions = actions.async;
const syncActions = actions.sync;
import { urls, pagesMap } from '../constants/otherConstants';
import { checkVersion } from '../utils/drivers';
import debugMode from '../utils/debugMode';
import MainPage from './MainPage';
import Login from '../components/Login';
import Loading from '../components/Loading';
import SettingsPage from './SettingsPage';
import ClinicUserSelectPage from './ClinicUserSelectPage';
import ClinicUserEditPage from './ClinicUserEditPage';
import NoUploadTargetsPage from './NoUploadTargetsPage';
import WorkspacePage from './WorkspacePage';
import UpdatePlease from '../components/UpdatePlease';
import VersionCheckError from '../components/VersionCheckError';
import Footer from '../components/Footer';
import Header from '../components/Header';
import UpdateModal from '../components/UpdateModal';
import UpdateDriverModal from '../components/UpdateDriverModal';
import DeviceTimeModal from '../components/DeviceTimeModal';
import AdHocModal from '../components/AdHocModal';
import styles from '../../styles/components/App.module.less';
const remote = require('@electron/remote');
const serverdata = {
Local: {
API_URL: 'http://localhost:8009',
UPLOAD_URL: 'http://localhost:9122',
DATA_URL: 'http://localhost:9220',
BLIP_URL: 'http://localhost:3000'
},
Development: {
API_URL: 'https://dev-api.tidepool.org',
UPLOAD_URL: 'https://dev-uploads.tidepool.org',
DATA_URL: 'https://dev-api.tidepool.org/dataservices',
BLIP_URL: 'https://dev-app.tidepool.org'
},
Staging: {
API_URL: 'https://stg-api.tidepool.org',
UPLOAD_URL: 'https://stg-uploads.tidepool.org',
DATA_URL: 'https://stg-api.tidepool.org/dataservices',
BLIP_URL: 'https://stg-app.tidepool.org'
},
Integration: {
API_URL: 'https://int-api.tidepool.org',
UPLOAD_URL: 'https://int-uploads.tidepool.org',
DATA_URL: 'https://int-api.tidepool.org/dataservices',
BLIP_URL: 'https://int-app.tidepool.org'
},
Production: {
API_URL: 'https://api.tidepool.org',
UPLOAD_URL: 'https://uploads.tidepool.org',
DATA_URL: 'https://api.tidepool.org/dataservices',
BLIP_URL: 'https://app.tidepool.org'
}
};
export class App extends Component {
static propTypes = {
route: PropTypes.shape({
api: PropTypes.func.isRequired
}).isRequired
};
constructor(props) {
super(props);
this.log = bows('App');
const initial_server = _.findKey(serverdata, (key) => key.BLIP_URL === config.BLIP_URL);
this.state = {
server: initial_server
};
}
UNSAFE_componentWillMount(){
checkVersion(this.props.dispatch);
let { api } = this.props;
this.props.async.doAppInit(
_.assign({ environment: this.state.server }, config), {
api: api,
device,
localStore,
log: this.log
});
const addServers = (servers) => {
if (servers && servers.length && servers.length > 0) {
for (let server of servers) {
const protocol = server.name === 'localhost' ? 'http://' : 'https://';
const url = protocol + server.name + ':' + server.port;
serverdata[server.name] = {
API_URL: url,
UPLOAD_URL: url,
DATA_URL: url + '/dataservices',
BLIP_URL: url,
};
}
} else {
this.log('No servers found');
}
};
dns.resolveSrv('environments-srv.tidepool.org', (err, servers) => {
if (err) {
this.log(`DNS resolver error: ${err}. Retrying...`);
dns.resolveSrv('environments-srv.tidepool.org', (err2, servers2) => {
if (!err2) {
addServers(servers2);
}
});
} else {
addServers(servers);
}
});
window.addEventListener('contextmenu', this.handleContextMenu, false);
}
setServer = info => {
console.log('will use', info.label, 'server');
var serverinfo = serverdata[info.label];
serverinfo.environment = info.label;
this.props.api.setHosts(serverinfo);
this.setState({server: info.label});
};
render() {
return (
<div className={styles.app} onClick={this.handleDismissDropdown}>
<Header location={this.props.location} />
<Switch>
<Route exact strict path="/" component={Loading} />
<Route path="/login" component={Login}/>
<Route path="/main" component={MainPage}/>
<Route path="/settings" component={SettingsPage}/>
<Route path="/clinic_user_select" component={ClinicUserSelectPage}/>
<Route path="/clinic_user_edit" component={ClinicUserEditPage}/>
<Route path="/no_upload_targets" component={NoUploadTargetsPage}/>
<Route path="/workspace_switch" component={WorkspacePage} />
</Switch>
<Footer version={config.version} environment={this.state.server} />
{/* VersionCheck as overlay */}
{this.renderVersionCheck()}
<UpdateModal />
<UpdateDriverModal />
<DeviceTimeModal />
<AdHocModal />
</div>
);
}
handleContextMenu = e => {
e.preventDefault();
const { clientX, clientY } = e;
let template = [];
if (process.env.NODE_ENV === 'development') {
template.push({
label: 'Inspect element',
click() {
remote.getCurrentWindow().inspectElement(clientX, clientY);
}
});
template.push({
type: 'separator'
});
}
if (this.props.location.pathname === pagesMap.LOGIN) {
const submenus = [];
for (let server of _.keys(serverdata)) {
submenus.push({
label: server,
click: this.setServer,
type: 'radio',
checked: this.state.server === server
});
}
template.push({
label: 'Change server',
submenu: submenus,
});
template.push({
label: 'Toggle Debug Mode',
type: 'checkbox',
checked: debugMode.isDebug,
click() {
debugMode.setDebug(!debugMode.isDebug);
}
});
}
const menu = remote.Menu.buildFromTemplate(template);
menu.popup(remote.getCurrentWindow());
};
handleDismissDropdown = () => {
const { dropdown } = this.props;
// only toggle the dropdown by clicking elsewhere if it's open
if (dropdown === true) {
this.props.sync.toggleDropdown(dropdown);
}
};
renderVersionCheck() {
const { readyToRenderVersionCheckOverlay, unsupported } = this.props;
if (readyToRenderVersionCheckOverlay === false || unsupported === false) {
return null;
}
if (unsupported instanceof Error) {
return (
<VersionCheckError errorMessage={unsupported.message || 'Unknown error'}/>
);
}
if (unsupported === true) {
return (
<UpdatePlease knowledgeBaseLink={urls.HOW_TO_UPDATE_KB_ARTICLE} />
);
}
}
}
App.propTypes = {};
export default connect(
(state, ownProps) => {
return {
// plain state
dropdown: state.dropdown,
unsupported: state.unsupported,
// derived state
readyToRenderVersionCheckOverlay: (
!state.working.initializingApp.inProgress && !state.working.checkingVersion.inProgress
)
};
},
(dispatch) => {
return {
async: bindActionCreators(asyncActions, dispatch),
sync: bindActionCreators(syncActions, dispatch),
dispatch: dispatch
};
}
)(App);
|
docs/src/GettingStartedPage.js | yickli/react-bootstrap | import React from 'react';
import CodeExample from './CodeExample';
import NavMain from './NavMain';
import PageHeader from './PageHeader';
import PageFooter from './PageFooter';
export default class Page extends React.Component {
render() {
return (
<div>
<NavMain activePage="getting-started" />
<PageHeader
title="Getting started"
subTitle="An overview of React-Bootstrap and how to install and use." />
<div className="container bs-docs-container">
<div className="row">
<div className="col-md-9" role="main">
<div className="bs-docs-section">
<h2 id="setup" className="page-header">Setup</h2>
<p className="lead">You can import the lib as AMD modules, CommonJS modules, or as a global JS script.</p>
<p>First add the Bootstrap CSS to your project; check <a href="http://getbootstrap.com/getting-started/" name="Bootstrap Docs">here</a> if you have not already done that. Note that:</p>
<ul>
<li>Because many folks use custom Bootstrap themes, we do not directly depend on Bootstrap. It is up to you to to determine how you get and link to the Bootstrap CSS and fonts.</li>
<li>React-Bootstrap doesn't depend on a very precise version of Bootstrap. Just pull the latest and, in case of trouble, take hints on the version used by this documentation page. Then, have Bootstrap in your dependencies and ensure your build can read your Less/Sass/SCSS entry point.</li>
</ul>
<p>Then:</p>
<h3>CommonJS</h3>
<div className="highlight">
<CodeExample
codeText={
`$ npm install react
$ npm install react-bootstrap`
}
/>
<br />
<CodeExample
mode="javascript"
codeText={
`var Alert = require('react-bootstrap/lib/Alert');
// or
var Alert = require('react-bootstrap').Alert;`
}
/>
</div>
<h3>AMD</h3>
<div className="highlight">
<CodeExample
codeText={
`$ bower install react
$ bower install react-bootstrap`
}
/>
<br />
<CodeExample
mode="javascript"
codeText={
`define(['react-bootstrap/lib/Alert'], function(Alert) { ... });
// or
define(['react-bootstrap'], function(ReactBootstrap) { var Alert = ReactBootstrap.Alert; ... });`
}
/>
</div>
<h3>Browser globals</h3>
<p>The bower repo contains <code>react-bootstrap.js</code> and <code>react-bootstrap.min.js</code> with all components exported in the <code>window.ReactBootstrap</code> object.</p>
<div className="highlight">
<CodeExample
mode="htmlmixed"
codeText={
`<script src="https://cdnjs.cloudflare.com/ajax/libs/react/<react-version>/react.js"></script>
<script src="path/to/react-bootstrap-bower/react-bootstrap.min.js"></script>
<script>
var Alert = ReactBootstrap.Alert;
</script>`
}
/>
</div>
<h3>Without JSX</h3>
<p>If you do not use JSX and just call components as functions, you must explicitly <a href="https://facebook.github.io/react/blog/2014/10/14/introducing-react-elements.html#deprecated-auto-generated-factories">create a factory before calling it</a>. React-bootstrap provides factories for you in <code>lib/factories</code>:</p>
<div className="highlight">
<CodeExample
mode="javascript"
codeText={
`var Alert = require('react-bootstrap/lib/factories').Alert;
// or
var Alert = require('react-bootstrap/lib/factories/Alert');`
}
/>
</div>
</div>
<div className="bs-docs-section">
<h2 id="browser-support" className="page-header">Browser support</h2>
<p>We aim to support all browsers supported by both <a href="http://facebook.github.io/react/docs/working-with-the-browser.html#browser-support-and-polyfills">React</a> and <a href="http://getbootstrap.com/getting-started/#support">Bootstrap</a>.</p>
<p>React requires <a href="http://facebook.github.io/react/docs/working-with-the-browser.html#browser-support-and-polyfills">polyfills for non-ES5 capable browsers.</a></p>
<p><a href="http://jquery.com">jQuery</a> is currently required only for IE8 support for components which require reading element positions from the DOM: <code>Popover</code> and <code>Tooltip</code> when launched with <code>OverlayTrigger</code>. We would like to remove this dependency in future versions but for now, including the following snippet in your page should have you covered:</p>
<div className="highlight">
<CodeExample
mode="htmlmixed"
codeText={
`<!--[if lt IE 9]>
<script>
(function(){
var ef = function(){};
window.console = window.console || {log:ef,warn:ef,error:ef,dir:ef};
}());
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv-printshiv.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script>
<![endif]-->`
}
/>
</div>
</div>
</div>
</div>
</div>
<PageFooter />
</div>
);
}
shouldComponentUpdate() {
return false;
}
}
|
src/components/PlayerSignupList.js | mjosh954/mtg-toolbox | import React from 'react';
import moment from 'moment';
export default class PlayerSignupList extends React.Component {
static propTypes = {
players: React.PropTypes.array
}
render () {
const Table = require('material-ui/lib/table/table');
const TableBody = require('material-ui/lib/table/table-body');
const TableRow = require('material-ui/lib/table/table-row');
const TableRowColumn = require('material-ui/lib/table/table-row-column');
const TableHeader = require('material-ui/lib/table/table-header');
const TableHeaderColumn = require('material-ui/lib/table/table-header-column');
const { players } = this.props || [];
const playerRows = players.map((player, i) => {
return (
<TableRow key={i + 1}>
<TableRowColumn>{i + 1}</TableRowColumn>
<TableRowColumn>{player.name}</TableRowColumn>
<TableRowColumn>{moment(player.dateAdded).format('MMMM Do YYYY, h:mm:ss a')}</TableRowColumn>
</TableRow>
);
});
return (
<div>
<Table multiSelectable>
<TableHeader enableSelectAll>
<TableRow>
<TableHeaderColumn>ID</TableHeaderColumn>
<TableHeaderColumn>Player Name</TableHeaderColumn>
<TableHeaderColumn>Time Added</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody stripedRows>
{playerRows}
</TableBody>
</Table>
</div>
);
}
}
|
storybook/config.js | 3846masa/mastodon | import { configure, setAddon } from '@kadira/storybook';
import IntlAddon from 'react-storybook-addon-intl';
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { addLocaleData } from 'react-intl';
import en from 'react-intl/locale-data/en';
import '../app/javascript/styles/application.scss';
import './storybook.scss';
setAddon(IntlAddon);
addLocaleData(en);
let req = require.context('./stories/', true, /.story.js$/);
function loadStories () {
req.keys().forEach((filename) => req(filename));
}
configure(loadStories, module);
|
src/header/AppToolbar.js | corbig/AfterWorkManager | import React from 'react';
import IconButton from 'material-ui/IconButton';
import FontIcon from 'material-ui/FontIcon';
import MenuItem from 'material-ui/MenuItem';
import DropDownMenu from 'material-ui/DropDownMenu';
import RaisedButton from 'material-ui/RaisedButton';
import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar';
import Badge from 'material-ui/Badge';
import MessagePopover from './components/MessagePopover'
import Avatar from 'material-ui/Avatar';
import {cyan500,pink500} from 'material-ui/styles/colors';
import AppMenu from './components/AppMenu'
import AWCurrentUser from './components/AWCurrentUser'
import { connect } from 'react-redux';
import DateRange from 'material-ui/svg-icons/action/date-range';
import AccessTime from 'material-ui/svg-icons/device/access-time';
import ArrowBack from 'material-ui/svg-icons/navigation/arrow-back';
import { push } from 'react-router-redux'
const style={
marginRight : 10,
marginLeft : 10,
}
const toolbarStyle = {
backgroundColor: cyan500,
color : "#FFFFFF",
position: "fixed",
top: 0,
left: 0,
width : "100%",
zIndex: 999,
}
const whiteStyle ={
color : "#FFFFFF"
}
const mapStateToProps = (store) => {
return {
hour : store.mainState.soirees[store.mainState.currentIndex].hour,
date : store.mainState.soirees[store.mainState.currentIndex].date
}
}
const mapDispatchToProps = (dispatch) => {
return {
goBack: ()=>{
dispatch(push('/'));
}
}
}
export class AppToolbar extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 3,
};
}
handleChange = (event, index, value) => this.setState({value});
render() {
return (
<Toolbar style={toolbarStyle}>
<ToolbarGroup firstChild={true}>
{this.props.page === 'board' ?
<IconButton onTouchTap = {()=>this.props.goBack()}>
<ArrowBack color={"#FFFFFF"}/>
</IconButton> :
<div>
<img src={require("../images/Beer.png")} style={{width:38,height:38}}/>
</div>
}
<ToolbarSeparator style={style}/>
<AWCurrentUser/>
</ToolbarGroup>
{this.props.page === 'board' ?
<ToolbarGroup>
<IconButton>
<DateRange color={"#FFFFFF"}/>
</IconButton>
<ToolbarTitle text={this.props.date} style={{color:"#FFFFFF"}}/>
<IconButton>
<AccessTime color={"#FFFFFF"}/>
</IconButton>
<ToolbarTitle text={this.props.hour} style={{color:"#FFFFFF"}}/>
</ToolbarGroup> : null
}
<ToolbarGroup>
<MessagePopover/>
</ToolbarGroup>
</Toolbar>
);
}
}
export default connect(mapStateToProps,mapDispatchToProps)(AppToolbar);
|
src/hoc/EntitysFetchData.js | sk-iv/iva-app | import React from 'react';
import PropTypes from 'prop-types';
import {graphql, compose} from 'react-apollo';
import { branch, renderComponent, withState } from 'recompose';
import Waypoint from 'react-waypoint';
import FETCH_ENTITY_LIST from '../queries/fetchEntityList';
// import queryString from 'query-string';
import StateGlobal from './StateGlobal';
import {MainContext} from '../routes/Root';
import {CHANGE_LOCATION_SEARCH} from '../store';
import {locationParamObject} from '../components/utils/locationParamObject';
import { URIComponentStrToObj } from '../routes/FilterDeductive/utils';
// Higher Order Component принимает данные для вывода списка сущностей
/*
Пробрасываю свойства от роута /private
в дочерние компоненты
*/
const EntityList = (WrappedComponent) => {
const Loading = () => (
<span>Loading Entities...</span>
);
// Define an HoC that displays the Loading component instead of the
// wrapped component when props.data.loading is true
const displayLoadingState = branch(
(props) => props.loading,
renderComponent(Loading),
);
const renderForError = (component, propName = "data") =>
branch(
props => props[propName] && props[propName].error,
renderComponent(component),
);
const ErrorComponent = props =>(
<span>
Something went wrong, you can try to
<button onClick={props.refetch}>refetch</button>
</span>
)
const facetPrj = withState('facetPrj', 'setfacetPrj', []);
const hierarchy = withState('hierarchy', 'setHierarchy', []);
const facetStr = withState('facetStr', 'setFacetStr', []);
const facetNum = withState('facetNum', 'setFacetNum', []);
class ComponentDecorator extends React.Component {
componentDidMount(){
const {
location:{search},
cluster,
items,
facetPrj = [],
setHierarchy,
setfacetPrj,
setFacetStr,
setFacetNum
} = this.props;
//это для вывода списка в каталоге
if(search !== ''){
const select = URIComponentStrToObj(search);
setHierarchy(select.hierarchy);
if(select.facetPrj){
setfacetPrj(select.facetPrj);
}
if(select.facetStr){
setFacetStr(select.facetStr);
}
if(select.facetNum){
setFacetNum(select.facetNum);
}
}
//это для вывода списка внутри сущности
if(items != null){
setfacetPrj([{cluster, items:[items]}]);
}
}
componentDidUpdate(prevProps, prevState) {
const {
location:{search},
cluster,
items,
facetPrj = [],
setHierarchy,
setfacetPrj,
setFacetStr,
setFacetNum
} = this.props;
if(prevProps.location.search !== search){
const select = URIComponentStrToObj(search)
setHierarchy(select.hierarchy)
if(select.facetPrj){
setfacetPrj(select.facetPrj)
}
if(select.facetStr){
setFacetStr(select.facetStr);
}
}
if(prevProps.facetPrj.length !== facetPrj.length){
setfacetPrj([{cluster, items:[items]}])
}
// if(prevProps.facetStr.length !== facetStr.length){
// setFacetStr([{cluster, items:[items]}])
// }
}
render(){
const {
latest,
loadMoreEntries
} = this.props;
const handleWaypointEnter = () => {
if (latest.entitys.length < latest.totalCount){
loadMoreEntries();
}
};
return(
<WrappedComponent
waypoint={handleWaypointEnter}
{...this.props}
/>
);
}
}
const QueryWithData = graphql (FETCH_ENTITY_LIST, {
options: ({
selSearch,
facetNum,
entitiesIdArray,
hierarchy,
facetPrj,
facetStr,
projectionsDonors,
stateGlobalQuery: {
selHierarchy,
selEntitiesLayout
}
}) => ({
variables: {
limit: 12,
cursor: 0,
hierarchy: hierarchy,
search: selSearch,
facetPrj,
projectionsDonors: projectionsDonors,
facetStr,
facetNum,
entitiesIdArray: entitiesIdArray
}
}),
props({ data: { loading, latest, fetchMore} }){
return {
loading,
latest,
loadMoreEntries: () => {
return fetchMore({
query: FETCH_ENTITY_LIST,
variables: {
cursor: latest.cursor + latest.limit,
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.latest.entitys;
const newEntitys = fetchMoreResult.latest.entitys;
const newCursor = fetchMoreResult.latest.cursor;
return {
// By returning `cursor` here, we update the `loadMore` function
// to the new cursor.
latest: {
__typename: previousResult.latest.__typename,
totalCount: previousResult.latest.totalCount,
limit: previousResult.latest.limit,
cursor: newCursor,
hierarchy: previousResult.latest.hierarchy,
search: previousResult.latest.search,
entitys: [...previousEntry, ...newEntitys],
facetNum: previousResult.latest.facetNum,
facetStr: previousResult.latest.facetStr,
facetPrj: previousResult.latest.facetPrj,
facetLayout: previousResult.latest.facetLayout,
},
};
},
});
},
};
},
});
ComponentDecorator.propTypes = {
latest: PropTypes.shape({
entitys: PropTypes.array,
}).isRequired
};
return compose(
facetStr,
facetNum,
hierarchy,
facetPrj,
StateGlobal,
QueryWithData,
displayLoadingState,
renderForError(ErrorComponent),
)(ComponentDecorator);
};
export default EntityList;
|
src/components/HeartsGame.js | tgevaert/react-redux-hearts | import React from 'react';
import { connect } from 'react-redux';
import HeartsPlayer from './HeartsPlayer';
import CurrentTrick from './CurrentTrick';
import Toast from './Toast';
import { getPlayers, getPOVPlayerIndex } from '../reducers';
const HeartsGamePresentation = ({ players, POVindex }) => {
const pnum = players.length;
return (
<div className="game-table">
<HeartsPlayer player={players[(POVindex + 2) % pnum]} position={"north"} cardsHidden={true} />
<div className="row-flex">
<HeartsPlayer player={players[(POVindex + 1) % pnum]} position={"west"} cardsHidden={true} />
<div className="game-board">
<div className="viewport">
<CurrentTrick />
</div>
</div>
<HeartsPlayer player={players[(POVindex + 3) % pnum]} position={"east"} cardsHidden={true} />
</div>
<Toast />
<HeartsPlayer player={players[POVindex]} position={"south"} />
</div>
);
};
export default connect(state => ({ players: getPlayers(state), POVindex: getPOVPlayerIndex(state) }))(
HeartsGamePresentation
);
|
src/routes/post/index.js | Ozaroni/modestLifer | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Post from './Post';
import Layout from '../../components/Layout';
const title = 'Blog Post';
export default {
path: '/post',
children: [
{
path: '/:postName', // www.example.com/admin/users
action: (context) => {
return {
title,
component: <Layout><Post slug={context.params.postName} /></Layout>,
}
},
/*path: '*', // www.example.com/admin/users
action: (context) => {
return {
title,
component: <Layout><Post title={context.params.postName} /></Layout>,
}
},*/
},
]
/* async action({ fetch }) {
const resp = await fetch('/graphql', {
body: JSON.stringify({
query: '{news{title,link,content}}',
}),
});
const { data } = await resp.json();
if (!data || !data.news) throw new Error('Failed to load the news feed.');
return {
title: 'React Starter Kit',
component: <Layout><Home news={data.news} /></Layout>,
};
},*/
};
|
src/js/components/subscribe__page/index.js | Arlefreak/arlefreakClient | import PropTypes from 'prop-types';
import React from 'react';
import Remarkable from 'remarkable';
import Page from '../../containers/page';
import Subscribe from '../subscribe';
import Social from '../social';
const Container = ({
id,
title,
isFetching,
items,
meta_url,
meta_title,
meta_description,
meta_preview,
}) => {
var md = new Remarkable();
var text = items.subscribeDescription ? items.subscribeDescription : '';
var mdr = md.render(text);
return (
<Page
id={id}
title={title}
isFetching={false}
meta_url={meta_url}
meta_title={meta_title}
meta_description={meta_description}
meta_preview={meta_preview}
>
<div className="box shadow">
<div
className="markdown no-margin"
dangerouslySetInnerHTML={{ __html: mdr }}
/>
</div>
<div className="subscribe">
<Subscribe />
<Social config={items} />
</div>
</Page>
);
};
Container.propTypes = {
id: PropTypes.string.isRequired,
title: PropTypes.string,
isFetching: PropTypes.bool.isRequired,
items: PropTypes.shape().isRequired,
meta_description: PropTypes.string,
meta_url: PropTypes.string,
meta_title: PropTypes.string,
meta_preview: PropTypes.string,
};
export default Container;
|
src/components/App.js | simplebee/everyday | import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import MainLayout from './MainLayout';
function App() {
return (
<BrowserRouter>
<MainLayout />
</BrowserRouter>
);
}
export default App;
|
src/client/index.js | BhumiSukhadiya/React_Project_Repo | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import FastClick from 'fastclick';
import queryString from 'query-string';
import { createPath } from 'history/PathUtils';
import history from './core/history';
import App from './components/App';
import configureStore from './store/configureStore';
import { updateMeta } from './core/DOMUtils';
import { ErrorReporter, deepForceUpdate } from './core/devUtils';
import { setToken } from './pages/login/Login.action';
/* eslint-disable global-require */
// Global (context) variables that can be easily accessed from any React component
// https://facebook.github.io/react/docs/context.html
const context = {
// Enables critical path CSS rendering
// https://github.com/kriasoft/isomorphic-style-loader
insertCss: (...styles) => {
const removeCss = styles.map(style => style._insertCss()); // eslint-disable-line no-underscore-dangle, max-len
return () => {
removeCss.forEach(f => f());
};
},
// Initialize a new Redux store
// http://redux.js.org/docs/basics/UsageWithReact.html
store: configureStore(window.APP_STATE, { history }),
};
if (localStorage.getItem('token') !== null) {
context.store.dispatch(setToken(localStorage.getItem('token')));
}
// Switch off the native scroll restoration behavior and handle it manually
// https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration
const scrollPositionsHistory = {};
if (window.history && 'scrollRestoration' in window.history) {
window.history.scrollRestoration = 'manual';
}
let onRenderComplete = function initialRenderComplete() {
const elem = document.getElementById('css');
if (elem) elem.parentNode.removeChild(elem);
onRenderComplete = function renderComplete(route, location) {
document.title = route.title;
updateMeta('description', route.description);
// Update necessary tags in <head> at runtime here, ie:
// updateMeta('keywords', route.keywords);
// updateCustomMeta('og:url', route.canonicalUrl);
// updateCustomMeta('og:image', route.imageUrl);
// updateLink('canonical', route.canonicalUrl);
// etc.
let scrollX = 0;
let scrollY = 0;
const pos = scrollPositionsHistory[location.key];
if (pos) {
scrollX = pos.scrollX;
scrollY = pos.scrollY;
} else {
const targetHash = location.hash.substr(1);
if (targetHash) {
const target = document.getElementById(targetHash);
if (target) {
scrollY = window.pageYOffset + target.getBoundingClientRect().top;
}
}
}
// Restore the scroll position if it was saved into the state
// or scroll to the given #hash anchor
// or scroll to top of the page
window.scrollTo(scrollX, scrollY);
// Google Analytics tracking. Don't send 'pageview' event after
// the initial rendering, as it was already sent
if (window.ga) {
window.ga('send', 'pageview', createPath(location));
}
};
};
// Make taps on links and buttons work fast on mobiles
FastClick.attach(document.body);
const container = document.getElementById('app');
let appInstance;
let currentLocation = history.location;
let router = require('./core/router').default;
// Re-render the app when window.location changes
async function onLocationChange(location, action) {
// Remember the latest scroll position for the previous location
scrollPositionsHistory[currentLocation.key] = {
scrollX: window.pageXOffset,
scrollY: window.pageYOffset,
};
// Delete stored scroll position for next page if any
if (action === 'PUSH') {
delete scrollPositionsHistory[location.key];
}
currentLocation = location;
try {
// Traverses the list of routes in the order they are defined until
// it finds the first route that matches provided URL path string
// and whose action method returns anything other than `undefined`.
const route = await router.resolve({
...context,
path: location.pathname,
query: queryString.parse(location.search),
});
// Prevent multiple page renders during the routing process
if (currentLocation.key !== location.key) {
return;
}
if (route.redirect) {
history.replace(route.redirect);
return;
}
appInstance = ReactDOM.render(
<App context={context}>{route.component}</App>,
container,
() => onRenderComplete(route, location),
);
} catch (error) {
// Display the error in full-screen for development mode
if (__DEV__) {
appInstance = null;
document.title = `Error: ${error.message}`;
ReactDOM.render(<ErrorReporter error={error} />, container);
throw error;
}
console.error(error); // eslint-disable-line no-console
// Do a full page reload if error occurs during client-side navigation
if (action && currentLocation.key === location.key) {
window.location.reload();
}
}
}
// Handle client-side navigation by using HTML5 History API
// For more information visit https://github.com/mjackson/history#readme
history.listen(onLocationChange);
onLocationChange(currentLocation);
// Handle errors that might happen after rendering
// Display the error in full-screen for development mode
if (__DEV__) {
window.addEventListener('error', (event) => {
appInstance = null;
document.title = `Runtime Error: ${event.error.message}`;
ReactDOM.render(<ErrorReporter error={event.error} />, container);
});
}
// Enable Hot Module Replacement (HMR)
if (module.hot) {
module.hot.accept('./core/router', () => {
router = require('./core/router').default;
if (appInstance) {
try {
// Force-update the whole tree, including components that refuse to update
deepForceUpdate(appInstance);
} catch (error) {
appInstance = null;
document.title = `Hot Update Error: ${error.message}`;
ReactDOM.render(<ErrorReporter error={error} />, container);
return;
}
}
onLocationChange(currentLocation);
});
}
|
projects/plane-crashes/viz/src/viz/PlaneAge/index.js | ebemunk/blog | import React from 'react'
import { scaleBand, scaleLinear } from 'd3-scale'
import { max, mean } from 'd3-array'
import FlexPlot from '../../vizlib/FlexPlot'
import Axis from '../../vizlib/Axis'
import GridLines from '../../vizlib/GridLines'
import ChartTitle from '../../vizlib/ChartTitle'
import { blueRed } from '../../vizlib/colors'
import rawData from '../../data/plane-age.json'
const data = rawData
.slice(0, 20)
.map(d => ({ ...d, mean: mean(d.ages) }))
.sort((a, b) => b.mean - a.mean)
import Violin from './Violin'
const color = blueRed()
const PlaneAge = () => {
return (
<>
<ChartTitle
title="How long before planes crash?"
subtitle="Distribution of the years between a plane's first flight and when it crashes, grouped by manufacturer. Red line shows the average."
style={{
marginLeft: 30,
}}
/>
<FlexPlot
height={500}
margin={{ top: 20, left: 30, right: 20, bottom: 20 }}
>
{({ chartHeight, chartWidth }) => {
const x = scaleBand()
.domain(data.map(d => d.type))
.range([0, chartWidth])
.padding(0.2)
const y = scaleLinear()
.domain([0, max(data, d => max(d.ages))])
.range([chartHeight, 0])
return (
<>
<GridLines orientation="horizontal" scale={y} />
<Axis
scale={x}
orientation="bottom"
transform={`translate(0, ${chartHeight})`}
tickFormat={d => (d === 'de' ? 'de Havilland' : d)}
/>
<Axis scale={y} orientation="left" title="Years in service" />
{data.map(d => (
<g key={d.type} transform={`translate(${x(d.type)}, 0)`}>
<Violin
data={d.ages}
bandwidth={x.bandwidth()}
yDomain={y.domain()}
/>
<line
x1={0}
y1={y(d.mean)}
x2={x.bandwidth()}
y2={y(d.mean)}
style={{
fill: 'none',
stroke: color(1),
strokeWidth: 3,
}}
/>
</g>
))}
</>
)
}}
</FlexPlot>
</>
)
}
import { hot } from 'react-hot-loader'
export default hot(module)(PlaneAge)
|
src/common/components/vanilla/table-interactive/body.js | canonical-ols/build.snapcraft.io | import PropTypes from 'prop-types';
import React from 'react';
import styles from './table.css';
export default function Body(props) {
return (
<main className={ styles.body }>
{ props.children }
</main>
);
}
Body.propTypes = {
children: PropTypes.node
};
|
src/parser/hunter/survival/modules/talents/WildfireInfusion/VolatileBomb.js | fyruna/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import { encodeTargetString } from 'parser/shared/modules/EnemyInstances';
import Enemies from 'parser/shared/modules/Enemies';
import StatTracker from 'parser/shared/modules/StatTracker';
import { SERPENT_STING_SV_BASE_DURATION } from 'parser/hunter/survival/constants';
import ItemDamageDone from 'interface/others/ItemDamageDone';
import { formatDuration } from 'common/format';
/**
* Lace your Wildfire Bomb with extra reagents, randomly giving it one of the following enhancements each time you throw it:
*
* Volatile Bomb:
* Reacts violently with poison, causing an extra explosion against enemies suffering from your Serpent Sting and refreshes your Serpent Stings.
*
* Example log: https://www.warcraftlogs.com/reports/n8AHdKCL9k3rtRDb#fight=36&type=damage-done
*/
const SERPENT_STING_FOCUS_COST = 20;
class VolatileBomb extends Analyzer {
static dependencies = {
enemies: Enemies,
statTracker: StatTracker,
};
damage = 0;
casts = 0;
extendedSerpentStings = 0;
extendedInMs = 0;
focusSaved = 0;
activeSerpentStings = {
/*
[encodedTargetString]: {
targetName: name,
cast: timestamp,
expectedEnd: timestamp,
extendStart: timestamp || null,
extendExpectedEnd: timestamp || null,
},
*/
};
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.WILDFIRE_INFUSION_TALENT.id);
}
_serpentApplication(event) {
const enemy = this.enemies.getEntity(event);
if (!enemy) {
return;
}
const target = encodeTargetString(event.targetID, event.targetInstance);
const hastedSerpentStingDuration = SERPENT_STING_SV_BASE_DURATION / (1 + this.statTracker.currentHastePercentage);
this.activeSerpentStings[target] = {
targetName: enemy.name,
cast: event.timestamp,
expectedEnd: event.timestamp + hastedSerpentStingDuration,
extendStart: null,
extendExpectedEnd: null,
};
}
_maybeSerpentStingExtend(event) {
const enemy = this.enemies.getEntity(event);
if (!enemy) {
return;
}
const target = encodeTargetString(event.targetID, event.targetInstance);
if (this.activeSerpentStings[target]) {
this.activeSerpentStings[target].extendStart = event.timestamp;
this.activeSerpentStings[target].extendExpectedEnd = event.timestamp + (this.activeSerpentStings[target].expectedEnd - this.activeSerpentStings[target].cast);
this.extendedInMs += this.activeSerpentStings[target].extendExpectedEnd - this.activeSerpentStings[target].expectedEnd;
this.focusSaved += SERPENT_STING_FOCUS_COST;
this.extendedSerpentStings += 1;
}
}
on_byPlayer_applydebuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.VOLATILE_BOMB_WFI_DOT.id && spellId !== SPELLS.SERPENT_STING_SV.id) {
return;
}
if (spellId === SPELLS.SERPENT_STING_SV.id) {
this._serpentApplication(event);
}
if (spellId === SPELLS.VOLATILE_BOMB_WFI_DOT.id) {
this._maybeSerpentStingExtend(event);
}
}
on_byPlayer_refreshdebuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.VOLATILE_BOMB_WFI_DOT.id && spellId !== SPELLS.SERPENT_STING_SV.id) {
return;
}
if (spellId === SPELLS.SERPENT_STING_SV.id) {
this._serpentApplication(event);
}
}
on_byPlayer_removedebuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.SERPENT_STING_SV.id) {
return;
}
const encoded = encodeTargetString(event.targetID, event.targetInstance);
delete this.activeSerpentStings[encoded];
}
on_byPlayer_damage(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.VOLATILE_BOMB_WFI_DOT.id && spellId !== SPELLS.VOLATILE_BOMB_WFI_IMPACT.id) {
return;
}
this.damage += event.amount + (event.absorbed || 0);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.VOLATILE_BOMB_WFI.id) {
return;
}
this.casts += 1;
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.VOLATILE_BOMB_WFI.id}
value={<ItemDamageDone amount={this.damage} />}
>
<table className="table table-condensed">
<thead>
<tr>
<th>Refreshes</th>
<th>Avg</th>
<th>Total</th>
<th>Focus saved</th>
</tr>
</thead>
<tbody>
<tr>
<td>{this.extendedSerpentStings}</td>
<td>{formatDuration(this.extendedInMs / this.casts / 1000)}</td>
<td>{formatDuration(this.extendedInMs / 1000)}</td>
<td>{this.focusSaved}</td>
</tr>
</tbody>
</table>
</TalentStatisticBox>
);
}
}
export default VolatileBomb;
|
source/components/Application.react.js | argaskins/ThinkReact-Jenkins | var React = require('react');
var logs = require("../utilities/logsMixin.js")
const Section = require('./Section.react.js');
const Banner = require('./Banner.react.js');
const Overview = require('./Overview.react.js');
// const header = require('./textHeader.react.js'); //Stateless (Static) component. Thats why it's lowercase.
const Bullets = require('./Bullets.react.js');
const Header = require('./Header.react.js');
const Images = require('./Images.react.js');
const Tweets = require('./Tweets.react.js')
// Same as import React from 'react'
const Application = React.createClass({
name: "Application",
// mixins: [logs],
render: function() {
return (
<div className='container-fluid'>
<Banner></Banner>
<Section>
<Header>Overview</Header>
<Overview />
</Section>
<Section>
<Header>Bullets</Header>
<Bullets />
</Section>
<Section>
<Header>Photos</Header>
<Images />
</Section>
<Section>
<Header>Tweets</Header>
<Tweets />
</Section>
</div>
);
}
});
module.exports = Application;
|
packages/material-ui-icons/src/FeaturedPlayList.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M21 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-2zm-9 8H3V9h9v2zm0-4H3V5h9v2z" /></g>
, 'FeaturedPlayList');
|
src/parser/warlock/destruction/modules/features/ImmolateUptime.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 SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import StatisticBar from 'interface/statistics/StatisticBar';
import UptimeBar from 'interface/statistics/components/UptimeBar';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
class ImmolateUptime extends Analyzer {
static dependencies = {
enemies: Enemies,
};
get uptime() {
return this.enemies.getBuffUptime(SPELLS.IMMOLATE_DEBUFF.id) / this.owner.fightDuration;
}
get suggestionThresholds() {
return {
actual: this.uptime,
isLessThan: {
minor: 0.9,
average: 0.85,
major: 0.75,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<>Your <SpellLink id={SPELLS.IMMOLATE_DEBUFF.id} /> uptime can be improved. Try to pay more attention to it as it provides a significant amount of Soul Shard Fragments over the fight and is also a big portion of your total damage.</>)
.icon(SPELLS.IMMOLATE_DEBUFF.icon)
.actual(`${formatPercentage(actual)}% Immolate uptime`)
.recommended(`>${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
const history = this.enemies.getDebuffHistory(SPELLS.IMMOLATE_DEBUFF.id);
return (
<StatisticBar
wide
position={STATISTIC_ORDER.CORE(1)}
>
<div className="flex">
<div className="flex-sub icon">
<SpellIcon id={SPELLS.IMMOLATE.id} />
</div>
<div className="flex-sub value">
{formatPercentage(this.uptime, 0)} % <small>uptime</small>
</div>
<div className="flex-main chart" style={{ padding: 15 }}>
<UptimeBar
uptimeHistory={history}
start={this.owner.fight.start_time}
end={this.owner.fight.end_time}
style={{ height: '100%' }}
/>
</div>
</div>
</StatisticBar>
);
}
}
export default ImmolateUptime;
|
src/@ui/Icon/icons/CircleOutlineCheckMark.js | NewSpring/Apollos | import React from 'react';
import PropTypes from 'prop-types';
import { Svg } from '../../Svg';
import makeIcon from './makeIcon';
const Icon = makeIcon(({ size = 32, fill, ...otherProps } = {}) => (
<Svg width={size} height={size} viewBox="0 0 60 61" {...otherProps}>
<Svg.Polygon fill={fill} points="25.9570657 39.7210789 26.6666667 40.4357125 27.3762676 39.7210789 40.709601 26.293183 41.4092427 25.5885792 40.709601 24.8839754 38.0429343 22.1983962 37.3333333 21.4837626 36.6237324 22.1983962 25.9570657 32.940713 27.3762676 32.940713 23.3762676 28.9123442 22.6666667 28.1977106 21.9570657 28.9123442 19.290399 31.5979234 18.5907573 32.3025272 19.290399 33.007131" />
<Svg.Path fill={fill} d="M30,54.903 L30,54.903 C43.254834,54.903 54,44.157834 54,30.903 C54,17.648166 43.254834,6.903 30,6.903 C16.745166,6.903 6,17.648166 6,30.903 C6,44.157834 16.745166,54.903 30,54.903 L30,54.903 Z M30,60.903 L30,60.903 C13.4314575,60.903 0,47.4715425 0,30.903 C0,14.3344575 13.4314575,0.903 30,0.903 C46.5685425,0.903 60,14.3344575 60,30.903 C60,47.4715425 46.5685425,60.903 30,60.903 L30,60.903 Z" />
</Svg>
));
Icon.propTypes = {
size: PropTypes.number,
fill: PropTypes.string,
};
export default Icon;
|
client/src/todos/containers/ToDosView.js | Hypheme/harmonized.js-example | import React from 'react';
import TodoList from '../components/TodoList'
const TodosView = (props) => {
return (
<div>
<h2>TODOS</h2>
<TodoList {...props}/>
</div>
);
};
export default TodosView;
|
frontend/app/js/components/service/details/detailstab.js | serverboards/serverboards | import React from 'react'
import store from 'app/utils/store'
import {goto} from 'app/utils/store'
import {MarkdownPreview} from 'react-marked-markdown';
import {i18n} from 'app/utils/i18n'
import cache from 'app/utils/cache'
import ServiceLink from 'app/components/servicelink'
import {FutureLabel} from 'app/components'
import {map_get} from 'app/utils'
function is_current_project(shortname){
return (store.getState().project.current == shortname)
}
function DataField({field, value}){
let inner = null
switch(field.type){
case "description":
case "html":
return null
case "hidden":
return null
case "button":
return null
case "checkbox":
inner = value ? i18n("yes") : i18n("no")
break
case "password":
inner = "********"
break;
case "service":
inner = (
<ServiceLink service={value}/>
)
break;
default:
if (value)
inner = (
<span className="ui oneline" style={{maxWidth: "30vw", display: "block"}}>{value}</span>
)
else
inner = (
<div className="ui meta">
{field.value || i18n(field.placeholder)}
</div>
)
break;
}
return (
<div className="row">
<label className="four wide column" style={{fontWeight:"bold"}}>{i18n(field.label || field.name)}</label>
<div className="ui twelve wide column with oneline">
{inner}
</div>
</div>
)
}
function DetailsTab(props){
return (
<div className="ui grid" style={{flexGrow:1, margin: 0}}>
<div className="six wide column" style={{borderRight:"1px solid #ddd", paddingLeft: 20}}>
<h3 className="ui header">{i18n("Service Type")}</h3>
{props.template.name}
<h3 className="ui header">{i18n("Description")}</h3>
{props.template.description ? (
<MarkdownPreview className="ui grey text" value={i18n(props.template.description)}/>
) : null}
<h3 className="ui header">{i18n("Related projects")}</h3>
<div className="ui vertical secondary menu" style={{width:"100%"}}>
{props.service.projects.map( (s) => (
<div key={s} className={`item ${is_current_project(s) ? "active" : ""}`} onClick={() => goto(`/project/${s}/`)} style={{cursor: "pointer"}}>
{s} - <FutureLabel promise={() => cache.project(s).then(s => s.name)}/>
<i className="ui chevron right icon"/>
</div>
))}
</div>
</div>
<div className="ten wide column" style={{overflow: "hidden"}}>
<h3 className="ui header">{i18n("Description")}</h3>
<MarkdownPreview className="ui grey text" value={props.service.description || i18n("Not provided")}/>
<h3 className="ui header">{i18n("Config Details")}</h3>
<div className="ui grid">
{map_get(props.template, ["extra", "fields"], []).map( (f, i) => (
<DataField key={f.name || i} field={f} value={props.service.config[f.name]}/>
))}
</div>
</div>
</div>
)
}
export default DetailsTab
|
app/containers/LanguageProvider/index.js | acebusters/ab-web | /*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { makeSelectLocale } from './selectors';
export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: PropTypes.string,
messages: PropTypes.object,
children: PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
(locale) => ({ locale })
);
export default connect(mapStateToProps)(LanguageProvider);
|
src/frontend/components/buttons/GCalendarButton.js | gbgtech/gbgtechWeb | import React from 'react';
const GoogleCalendarButton = () => {
const urlPrefix = "https://calendar.google.com/calendar/embed?src=";
const googleCalendarId = "[email protected]&ctz=Europe/Stockholm#main_7";
return (
<a href={urlPrefix + googleCalendarId} className="main-follow-button calendar-btn" target="_blank" rel="noopener noreferrer" />
);
};
export default GoogleCalendarButton;
|
board/src/components/draft-js-highlight-plugin.js | google-research/fool-me-twice | // Copyright 2019 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import React from 'react';
const findWithRegex = (regex, contentBlock, callback) => {
const text = contentBlock.getText();
if (!regex || !text) return;
let matchArr, start;
while ((matchArr = regex.exec(text)) !== null) {
start = matchArr.index;
callback(start, start + matchArr[0].length);
}
};
const Highlight = props => (
<span data-offset-key={props.offsetKey}>
<mark>{props.children}</mark>
</span>
);
export default config => {
const regexp = config.highlight;
const highlightStrategy = (contentBlock: Object, callback: Function) => {
findWithRegex(regexp, contentBlock, callback);
};
return {
decorators: [
{
strategy: highlightStrategy,
component: Highlight,
},
],
};
};
|
src/Board.js | Codility/swarm | import React from 'react';
import Tile from './Tile';
import EmptyTile from './EmptyTile';
import HexLayout from './HexLayout';
export default class Board extends HexLayout {
getRows(tiles) {
let table = [];
tiles.forEach((tile) => {
if (!table[tile.x]) {
table[tile.x] = [];
}
table[tile.x][tile.y] = (<Tile id={tile.id} color={tile.color} type={tile.type} key={tile.id} x={tile.x} y={tile.y}/>);
});
let rows = [];
for (let j=0; j<Board.SIZE; j+=1) {
let row = [];
for (let i=0; i<Board.SIZE; i+=1) {
if (table[i] === undefined || table[i][j] === undefined) {
row.push(<EmptyTile key={j*Board.SIZE + i} x={i} y={j}/>);
} else {
row.push(table[i][j]);
}
}
rows.push(<div className="c-board-row" key={j}>{row}</div>);
}
return rows;
}
}
Board.SIZE = 12;
|
src/index.js | Deadhood/tepa-complete | import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'mobx-react'
import { AppContainer } from 'react-hot-loader'
import { BrowserRouter as Router } from 'react-router-dom'
import App from './App'
import DataStore from './DataStore'
import 'bootswatch/cosmo/bootstrap.min.css'
import './font.css'
import './index.css'
import './navbar-fixed-side.css'
const stores = {
dataStore: new DataStore()
}
const render = Component => {
ReactDOM.render(
<AppContainer>
<Router basename='/admin'>
<Provider {...stores}>
<Component />
</Provider>
</Router>
</AppContainer>,
document.getElementById('root')
)
}
render(App)
if (module.hot) {
module.hot.accept('./App', () => {
render(App)
})
}
|
client/src/components/city.js | BrunoSalerno/citylines | import React from 'react';
import CityBase from './city-base';
import {Switch, Redirect, Route} from 'react-router-dom';
import PropTypes from 'prop-types';
import {PanelHeader, PanelBody} from './panel';
import {Map, Source, Popup} from './map';
import Translate from 'react-translate-component';
import FeaturePopupContent from './city/feature-popup-content';
import MainStore from '../stores/main-store';
import CityStore from '../stores/city-store';
import CityViewStore from '../stores/city-view-store';
import EditorStore from '../stores/editor-store';
import CityView from './city/city-view';
const Editor = React.lazy(() => import('./editor'));
const Draw = React.lazy(() => import('./map/draw'));
import downloadImgFromMapCanvas from '../lib/map-to-img.js';
class City extends CityBase {
constructor(props, context) {
super(props, context);
this.urlName = this.props.match.params.city_url_name;
this.bindedOnChange = this.onChange.bind(this);
this.bindedOnMapMove = this.onMapMove.bind(this);
this.bindedOnMapLoad = this.onMapLoad.bind(this);
this.bindedOnMouseMove = this.onMouseMove.bind(this);
this.bindedOnMouseClick = this.onMouseClick.bind(this);
this.bindedOnPopupClose = this.onPopupClose.bind(this);
this.bindedOnSelectionChange = this.onSelectionChange.bind(this);
this.bindedOnFeatureUpdate = this.onFeatureUpdate.bind(this);
this.bindedOnFeatureCreate = this.onFeatureCreate.bind(this);
this.bindedOnFeatureDelete = this.onFeatureDelete.bind(this);
this.bindedOnDrawModeChange = this.onDrawModeChange.bind(this);
}
getChildContext() {
return {cityName: this.state && this.state.name};
}
componentWillUnmount() {
CityStore.unload(this.urlName);
MainStore.removeChangeListener(this.bindedOnChange);
CityStore.removeChangeListener(this.bindedOnChange);
CityViewStore.removeChangeListener(this.bindedOnChange);
EditorStore.removeChangeListener(this.bindedOnChange);
}
componentDidMount() {
MainStore.addChangeListener(this.bindedOnChange);
CityStore.addChangeListener(this.bindedOnChange);
CityViewStore.addChangeListener(this.bindedOnChange);
EditorStore.addChangeListener(this.bindedOnChange);
MainStore.setLoading();
CityStore.load(this.urlName, this.params());
}
UNSAFE_componentWillUpdate(nextProps, nextState) {
if (nextState && nextState.error) {
MainStore.unsetLoading();
this.props.history.push(`/error?path=${this.urlName}`);
}
}
onChange() {
this.setState(CityStore.getState(this.urlName));
}
onMapLoad(map) {
const geo = this.getGeoFromMap(map);
CityStore.setGeoData(this.urlName, geo);
}
onMapMove(map) {
if (this.state.playing) return;
const geo = this.getGeoFromMap(map);
CityStore.setGeoData(this.urlName, geo);
const newGeo = `${geo.lat},${geo.lon},${geo.zoom},${geo.bearing},${geo.pitch}`;
this.updateParams({geo: newGeo});
}
getGeoFromMap(map) {
const center = map.getCenter();
return {
lat: center.lat.toFixed(6),
lon: center.lng.toFixed(6),
bounds: map.getBounds().toArray(),
zoom: map.getZoom().toFixed(2),
bearing: map.getBearing().toFixed(2),
pitch: map.getPitch().toFixed(2)
}
}
onMouseMove(point, features) {
CityViewStore.hover(this.urlName, features);
}
onMouseClick(point, features) {
CityViewStore.clickFeatures(this.urlName, point, features);
}
onPopupClose() {
CityViewStore.unClickFeatures(this.urlName);
}
onSatelliteToggle(style) {
const mapStyle = style == 'satellite' ? style : null;
this.updateParams({map: mapStyle});
}
/* Draw Listeners */
onSelectionChange(features) {
EditorStore.changeSelection(this.urlName, features);
}
onFeatureUpdate(features) {
EditorStore.setFeatureGeoChange(this.urlName, features);
}
onFeatureCreate(features) {
EditorStore.setFeatureCreated(this.urlName, features);
}
onFeatureDelete(features) {
EditorStore.setFeatureDeleted(this.urlName, features);
}
onDrawModeChange(mode) {
EditorStore.setMode(this.urlName, mode);
}
onCameraClick(canvas) {
downloadImgFromMapCanvas(this.urlName, canvas);
ga('send', 'event', 'map', 'download_img', this.urlName);
}
/* ------------- */
panelStyle() {
const style = {visibility: this.state.main.displayPanel ? 'visible' : 'hidden'};
if (this.state.main.panelFullWidth) style.width = '100%';
return style;
}
toggleSettings() {
this.setState({displaySettings: !this.state.displaySettings, displayShare: false});
}
toggleShare() {
this.setState({displaySettings: false, displayShare: !this.state.displayShare});
}
render() {
if (!this.state) return null;
return (
<>
<div id="panel" style={this.panelStyle()}>
<PanelHeader
name={this.state.name}
pathName={this.props.location.pathname}
urlName={this.urlName}
loading={this.state.main.loading}
onToggleSettings={this.toggleSettings.bind(this)}
displaySettings={this.state.displaySettings}
onToggleShare={this.toggleShare.bind(this)}
displayShare={this.state.displayShare}
/>
<Switch>
<Route exact path="/:city_url_name"
render={props => <CityView {...props} displaySettings={this.state.displaySettings} displayShare={this.state.displayShare} />} />
<Route path="/:city_url_name/edit">
{ MainStore.userLoggedIn() ? <React.Suspense fallback=''><Editor city_url_name={this.urlName} /></React.Suspense> : <Redirect to="/auth" /> }
</Route>
</Switch>
</div>
<Map
mapboxAccessToken={this.state.mapbox_access_token}
mapboxStyle={this.state.mapbox_style}
mapStyle={this.state.map}
center={this.state.coords}
zoom={this.state.zoom}
bearing={this.state.bearing}
pitch={this.state.pitch}
mouseEventsLayerNames={this.state.mouseEventsLayerNames}
onLoad={this.bindedOnMapLoad}
onMove={this.bindedOnMapMove}
onMouseMove={this.bindedOnMouseMove}
onMouseClick={this.bindedOnMouseClick}
onSatelliteToggle={this.onSatelliteToggle.bind(this)}
onCameraClick={this.onCameraClick.bind(this)}
disableMouseEvents={this.state.playing} >
{ this.state.sources && this.state.sources.map((source) =>
<Source
key={source.name}
name={source.name}
data={source.data}
layers={source.layers}
/>
) }
{ this.state.clickedFeatures && <Popup
point={this.state.clickedFeatures.point}
onClose={this.bindedOnPopupClose}>
{this.state.clickedFeatures.features.map((f,i) =>
<FeaturePopupContent
key={`${f.properties.klass}-${f.properties.id}-${f.properties.line_url_name}`}
feature={f}
index={i} />
)}
</Popup>}
{ this.state.drawFeatures &&
<React.Suspense fallback=''>
<Draw
features={this.state.drawFeatures}
onSelectionChange={this.bindedOnSelectionChange}
onFeatureUpdate={this.bindedOnFeatureUpdate}
onFeatureCreate={this.bindedOnFeatureCreate}
onFeatureDelete={this.bindedOnFeatureDelete}
onModeChange={this.bindedOnDrawModeChange}
selectedFeatureById={this.state.drawSelectedFeatureById}
currentMode={this.state.drawCurrentMode}
/>
</React.Suspense>
}
</Map>
</>
);
}
}
City.childContextTypes = {
cityName: PropTypes.string
}
export default City
|
src/dumb/App.js | jeckhummer/ebidding-commercial | import React from 'react';
import {NotRemovedItemsTable} from '../smart/tables/NotRemovedItemsTable';
import {RemovedItemsTable} from '../smart/tables/RemovedItemsTable';
import DuplicatesNotification from "../smart/common/DuplicatesNotification";
import {ItemsCurrencySelect} from "../smart/common/ItemsCurrencySelect";
import {Floated} from './common/Floated';
import VATPayerToggle from "../smart/common/VATPayerToggle";
import {Space} from "./common/Space";
export const App = () => {
return (
<div>
<DuplicatesNotification/>
<Floated right>
<div style={{marginBottom: "5px"}}>
<VATPayerToggle/>
<Space x={8}/>
<ItemsCurrencySelect/>
</div>
</Floated>
<NotRemovedItemsTable/>
<br/>
<RemovedItemsTable/>
</div>
);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.