path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/components/Pots.js | MicheleV/da-beast | import React from 'react';
import Button from './Button';
import { potDesc } from '../constants/gardeningTypes';
const seedsButtons = (seeds, potId, plantAction) => {
if (seeds.length === 0) {
return (
<span>...but no seeds to plant...</span>
);
}
return seeds.map((seed) => {
const text = `Plant a ${seed.name}`;
return (
<Button
key={seed.key}
text={text}
onClick={() => plantAction(seed.key, potId)}
/>
);
});
};
const interactiveUi = (seeds, pot, potStatus, plantAction, gatherAction) => {
if (pot.seed === null) {
const potId = pot.id;
const seedsUi = seedsButtons(seeds, potId, plantAction);
return (
// TODO add dropdown here or button icons
<span>
{potDesc(pot.type)}{'\u00A0'}
{seedsUi}
</span>
);
}
return (
<span>
{potStatus(pot)}
<Button
text="Gather!"
onClick={() => gatherAction(pot.id)}
/>
</span>
);
};
export const potListUi = (seeds, pots, potStatus, plantAction, gatherAction) => (
pots.map(pot =>
<p key={pot.id}>
{interactiveUi(seeds, pot, potStatus, plantAction, gatherAction)}
</p>,
)
);
|
app/index.js | dkfann/cinesythesia | import React from 'react';
import ReactDOM from 'react-dom';
import routes from '../config/routes';
ReactDOM.render(
routes,
document.getElementById('app')
);
|
src/components/users/Username.js | mg4tv/mg4tv-web | import * as _ from 'lodash'
import React from 'react'
import {compose} from 'recompose'
import {withLoading, withNotFound} from '../hocs'
import LoadingView from '../LoadingView'
import NotFoundView from '../NotFoundView'
const enhance = compose(
withLoading(
({users, userId}) => !(_.has(users, userId)),
LoadingView
),
withNotFound(
({users, userId}) => (userId in users) && users[userId] === null,
NotFoundView
),
)
const Username = ({userId, users}) => (
<span>{_.get(users, `${userId}.username`, '[Not Found]')}</span>
)
export default enhance(Username)
|
src/Results/Beers.js | Jhong098/BeerFinder | import React from 'react';
import Api from '../utils/api.js';
import Slider from '../utils/Slider.js';
import Locator from '../Search/Locator.js';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import Loader from 'react-loaders';
export default class Beers extends React.Component {
constructor(props) {
super(props);
this.state = {clickedBeer: null, clicked: false, mapRendered: false};
}
componentWillReceiveProps(nextProps) {
console.log(nextProps);
}
clickHandler(props) {
this.setState({clickedBeer: props, clicked: true});
}
backHandler(props) {
this.setState({clickedBeer: null, clicked: false, mapRendered: false});
}
renderHandler = (rendered) => {
this.setState({mapRendered: rendered});
console.log(rendered);
}
render() {
console.log(this.state.mapRendered);
return (
<ReactCSSTransitionGroup
transitionName="fade"
transitionEnterTimeout={300}
transitionLeaveTimeout={300}
transitionAppear={true}
transitionAppearTimeout={1500}>
<div>
{!this.state.clicked &&
<div>
<BeerGrid clicked={this.state.clicked} beers={this.props.results} propClickHandler={(id) => this.clickHandler(id)} />
</div>
}
<ReactCSSTransitionGroup
transitionName="fade"
transitionEnterTimeout={300}
transitionLeaveTimeout={300}
transitionAppear={true}
transitionAppearTimeout={1500}>
{ this.state.clicked &&
<div className="beer-map">
<div className="single-beer">
{ this.state.mapRendered &&
<BeerItem className="fixed" clicked={this.state.clicked} item={this.state.clickedBeer} backHandler={(id) => this.backHandler(id)} />
}
</div>
<div className="map-right">
<Locator id={this.state.clickedBeer.id} renderHandler={this.renderHandler}/>
</div>
</div>
}
</ReactCSSTransitionGroup>
</div>
</ReactCSSTransitionGroup>
)
}
}
function BeerGrid (props) {
return (
<ul className="beer-list">
{props.beers.map(function(beer) {
return (
<BeerItem key={beer.id} item={beer} clickHandler={(id) => props.propClickHandler(id)} />
)
})}
</ul>
)
}
function BeerItem (props) {
const defaultImg = "https://thumbs.dreamstime.com/b/glass-translucent-frothy-beer-28540674.jpg";
return (
<div key={props.item.id} className="beer-item mdl-card mdl-shadow--2dp">
<div className="mdl-card__title"><h2 className="mdl-card__title-text">{props.item.name}</h2></div>
<div className="mdl-card__supporting-text info">
<ul className="beer-info">
<li>{props.item.image_url !== null ? <img className="beer-img" src={props.item.image_url} alt={'picture for ' + props.item.name} /> :
<img className="beer-img" src={defaultImg} alt={'picture for ' + props.item.name} />}
</li>
<li>Package: {props.item.package}</li>
<li>Price: {(props.item.price_in_cents / 100).toLocaleString("en-US", {style:"currency", currency:"USD"})}</li>
<li>Producer: {props.item.producer_name}</li>
</ul>
</div>
{!props.clicked &&
<div className="button-center"> <button className="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onClick={() => props.clickHandler(props.item)}>Nearest Store</button></div>
}
{props.clicked &&
<div className="button-center"> <button className="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" onClick={() => props.backHandler(props.item)}>Back</button></div>
}
</div>
)
} |
src/index.js | tkaetzel/sympho.net | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
storybook/config.js | tcitworld/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/assets/stylesheets/components.scss'
import './storybook.scss'
setAddon(IntlAddon);
addLocaleData(en);
window.storiesOf = storiesOf;
window.action = action;
window.React = React;
function loadStories () {
require('./stories/loading_indicator.story.jsx');
require('./stories/button.story.jsx');
require('./stories/autosuggest_textarea.story.jsx');
}
configure(loadStories, module);
|
pages/post.js | victorkane/blog-simple-next | import React from 'react'
import 'isomorphic-fetch'
import Header from '../components/header'
import { apiHost } from '../appconfig.js'
export default class Post extends React.Component {
static async getInitialProps ({pathname, query}) {
// eslint-disable-next-line no-undef
//console.log(query.id)
const res = await fetch(apiHost + '/api/post/' + query.id)
const json = await res.json()
return { post: json }
}
render() {
const post = this.props.post
return(
<div>
<Header />
<h2>{post['title']}</h2>
<p>{post['body']}</p>
</div>
)
}
}
|
examples/hello-world/src/index.js | BrunoAlcides/react-datepicker | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
example/index.android.js | samcorcos/react-native-calendar | import React from 'react';
import { AppRegistry } from 'react-native';
import App from './App';
const CalendarExample = () => {
return <App />;
};
AppRegistry.registerComponent('CalendarExample', () => CalendarExample);
|
src/components/Feedback/Feedback.js | albperezbermejo/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import styles from './Feedback.css';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
class Feedback {
render() {
return (
<div className="Feedback">
<div className="Feedback-container">
<a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a>
<span className="Feedback-spacer">|</span>
<a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a>
</div>
</div>
);
}
}
export default Feedback;
|
fields/types/date/DateColumn.js | qwales1/keystone | import React from 'react';
import moment from 'moment';
import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue';
var DateColumn = React.createClass({
displayName: 'DateColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value) return null;
const format = (this.props.col.type === 'datetime') ? 'MMMM Do YYYY, h:mm:ss a' : 'MMMM Do YYYY';
const formattedValue = moment(value).format(format);
return (
<ItemsTableValue title={formattedValue} field={this.props.col.type}>
{formattedValue}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
},
});
module.exports = DateColumn;
|
src/svg-icons/action/assignment-return.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAssignmentReturn = (props) => (
<SvgIcon {...props}>
<path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm4 12h-4v3l-5-5 5-5v3h4v4z"/>
</SvgIcon>
);
ActionAssignmentReturn = pure(ActionAssignmentReturn);
ActionAssignmentReturn.displayName = 'ActionAssignmentReturn';
export default ActionAssignmentReturn;
|
app/javascript/flavours/glitch/components/notification_purge_buttons.js | Kirishima21/mastodon | /**
* Buttons widget for controlling the notification clearing mode.
* In idle state, the cleaning mode button is shown. When the mode is active,
* a Confirm and Abort buttons are shown in its place.
*/
// Package imports //
import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Icon from 'flavours/glitch/components/icon';
const messages = defineMessages({
btnAll : { id: 'notification_purge.btn_all', defaultMessage: 'Select\nall' },
btnNone : { id: 'notification_purge.btn_none', defaultMessage: 'Select\nnone' },
btnInvert : { id: 'notification_purge.btn_invert', defaultMessage: 'Invert\nselection' },
btnApply : { id: 'notification_purge.btn_apply', defaultMessage: 'Clear\nselected' },
});
export default @injectIntl
class NotificationPurgeButtons extends ImmutablePureComponent {
static propTypes = {
onDeleteMarked : PropTypes.func.isRequired,
onMarkAll : PropTypes.func.isRequired,
onMarkNone : PropTypes.func.isRequired,
onInvert : PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
markNewForDelete: PropTypes.bool,
};
render () {
const { intl, markNewForDelete } = this.props;
//className='active'
return (
<div className='column-header__notif-cleaning-buttons'>
<button onClick={this.props.onMarkAll} className={markNewForDelete ? 'active' : ''}>
<b>∀</b><br />{intl.formatMessage(messages.btnAll)}
</button>
<button onClick={this.props.onMarkNone} className={!markNewForDelete ? 'active' : ''}>
<b>∅</b><br />{intl.formatMessage(messages.btnNone)}
</button>
<button onClick={this.props.onInvert}>
<b>¬</b><br />{intl.formatMessage(messages.btnInvert)}
</button>
<button onClick={this.props.onDeleteMarked}>
<Icon id='trash' /><br />{intl.formatMessage(messages.btnApply)}
</button>
</div>
);
}
}
|
src/components/chart.js | kevinsangnguyen/WeatherAPIReactRedux | import _ from 'lodash';
import React from 'react';
import { Sparklines, SparklinesLine, SparklinesReferenceLine } from 'react-sparklines';
function average(data) {
return _.round(_.sum(data)/data.length)
}
export default (props) => {
return (
<div>
<Sparklines height={120} width={180} data={props.data}>
<SparklinesLine color={props.color} />
<SparklinesReferenceLine type="avg" />
</Sparklines>
<div>{average(props.data)} {props.units}</div>
</div>
);
}
|
examples/todo-react-es6-wo-decorators/src/app/filter.js | rintoj/statex | import React from 'react'
import { SetFilterAction } from '../action/todo-action'
import { State } from 'statex'
export default class Filter extends React.Component {
subscriptions = []
constructor(props) {
super(props)
this.state = { filter: undefined}
}
componentDidMount() {
this.subscriptions.push(
State.select(state => state.filter)
.subscribe(filter => this.setState({ filter }))
)
}
componentWillUnmount() {
this.subscriptions.forEach(subscription => subscription.unsubscribe())
this.subscriptions = []
}
setAllFilter() {
new SetFilterAction('ALL').dispatch()
}
setActiveFilter() {
new SetFilterAction('ACTIVE').dispatch()
}
setCompletedFilter() {
new SetFilterAction('COMPLETED').dispatch()
}
render() {
const { filter } = this.state
return <ul id="filters">
<li>
<a className={filter == null || filter === 'ALL' ? 'selected' : undefined}
onClick={this.setAllFilter.bind(this)}>All</a>
</li>
<li>
<a className={filter === 'ACTIVE' ? 'selected' : undefined}
onClick={this.setActiveFilter.bind(this)}>Active</a>
</li>
<li>
<a className={filter === 'COMPLETED' ? 'selected' : undefined}
onClick={this.setCompletedFilter.bind(this)}>Completed</a>
</li>
</ul>
}
} |
src/svg-icons/image/blur-off.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBlurOff = (props) => (
<SvgIcon {...props}>
<path d="M14 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-.2 4.48l.2.02c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5-1.5.67-1.5 1.5l.02.2c.09.67.61 1.19 1.28 1.28zM14 3.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm-4 0c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm11 7c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM10 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm8 8c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-4c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm-4 13.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM2.5 5.27l3.78 3.78L6 9c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1c0-.1-.03-.19-.06-.28l2.81 2.81c-.71.11-1.25.73-1.25 1.47 0 .83.67 1.5 1.5 1.5.74 0 1.36-.54 1.47-1.25l2.81 2.81c-.09-.03-.18-.06-.28-.06-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1c0-.1-.03-.19-.06-.28l3.78 3.78L20 20.23 3.77 4 2.5 5.27zM10 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm11-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 13c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zM3 9.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm7 11c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-3-3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5z"/>
</SvgIcon>
);
ImageBlurOff = pure(ImageBlurOff);
ImageBlurOff.displayName = 'ImageBlurOff';
ImageBlurOff.muiName = 'SvgIcon';
export default ImageBlurOff;
|
docs/app/Examples/elements/Button/Variations/ButtonExamplePositive.js | shengnian/shengnian-ui-react | import React from 'react'
import { Button } from 'shengnian-ui-react'
const ButtonExamplePositive = () => (
<div>
<Button positive>Positive Button</Button>
</div>
)
export default ButtonExamplePositive
|
src/containers/Asians/TabControls/PreliminaryRounds/EnterRoundResults/Ballots/Instance/InstanceLabel.js | westoncolemanl/tabbr-web | import React from 'react'
import { connect } from 'react-redux'
import withStyles from 'material-ui/styles/withStyles'
import Typography from 'material-ui/Typography'
import returnWinnerStyle from './returnWinnerStyle'
import returnDissentingAdjudicatorStyle from './returnDissentingAdjudicatorStyle'
const styles = theme => ({
indicator: {
backgroundColor: '#ffffff'
}
})
export default connect(mapStateToProps)(withStyles(styles)(({
room,
ballotsThisRoom,
adjudicatorsById,
venuesById,
teamsById,
institutionsById
}) => {
const adjudicatorLabel = (adjudicatorId) =>
`${adjudicatorsById[adjudicatorId].firstName} ${adjudicatorsById[adjudicatorId].lastName} (${institutionsById[adjudicatorsById[adjudicatorId].institution].name})`
const isRoomInformationComplete = Boolean(
room.motion &&
room.pm &&
room.dpm &&
room.gw &&
room.gr &&
room.lo &&
room.dlo &&
room.ow &&
room.or
)
return (
<div
className={'flex flex-row w-100'}
>
<Typography
className={'w-10'}
>
{`Rank ${room.rank + 1}`}
</Typography>
<Typography
className={'w-10'}
>
<span
className={isRoomInformationComplete ? 'b' : 'light-silver fw1 i'}
>
{venuesById[room.venue].name}
</span>
</Typography>
<Typography
className={'w-20'}
>
<span
className={returnWinnerStyle(
ballotsThisRoom,
room,
room.gov
)}
>
{teamsById[room.gov].name}
</span>
<br />
<span
className={returnWinnerStyle(
ballotsThisRoom,
room,
room.opp
)}
>
{teamsById[room.opp].name}
</span>
</Typography>
<Typography
className={'w-20'}
>
<span
className={returnDissentingAdjudicatorStyle(
ballotsThisRoom,
room,
room.chair
)}
>
{adjudicatorLabel(room.chair)}
</span>
</Typography>
<Typography
className={'w-20'}
>
{room.panels.map(panel =>
<span
key={panel}
className={returnDissentingAdjudicatorStyle(
ballotsThisRoom,
room,
panel
)}
>
{adjudicatorLabel(panel)}
<br />
</span>
)}
</Typography>
<Typography
className={'w-20'}
>
{room.trainees.map(trainee =>
<span
key={trainee}
>
{adjudicatorLabel(trainee)}
<br />
</span>)
}
</Typography>
</div>
)
}))
function mapStateToProps (state, ownProps) {
return {
adjudicatorsById: state.adjudicators.data,
teamsById: state.teams.data,
venuesById: state.venues.data,
institutionsById: state.institutions.data
}
}
|
mlflow/server/js/src/model-registry/components/ModelListPage.js | mlflow/mlflow | import React from 'react';
import { ModelListView } from './ModelListView';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import RequestStateWrapper from '../../common/components/RequestStateWrapper';
import { getUUID } from '../../common/utils/ActionUtils';
import Utils from '../../common/utils/Utils';
import { appendTagsFilter, getModelNameFilter } from '../utils/SearchUtils';
import {
AntdTableSortOrder,
REGISTERED_MODELS_PER_PAGE,
REGISTERED_MODELS_SEARCH_NAME_FIELD,
} from '../constants';
import { searchRegisteredModelsApi } from '../actions';
import LocalStorageUtils from '../../common/utils/LocalStorageUtils';
export class ModelListPageImpl extends React.Component {
constructor(props) {
super(props);
this.state = {
orderByKey: REGISTERED_MODELS_SEARCH_NAME_FIELD,
orderByAsc: true,
currentPage: 1,
maxResultsSelection: REGISTERED_MODELS_PER_PAGE,
pageTokens: {},
loading: false,
};
}
static propTypes = {
models: PropTypes.arrayOf(PropTypes.object),
searchRegisteredModelsApi: PropTypes.func.isRequired,
// react-router props
history: PropTypes.object.isRequired,
location: PropTypes.object,
};
modelListPageStoreKey = 'ModelListPageStore';
defaultPersistedPageTokens = { 1: null };
initialSearchRegisteredModelsApiId = getUUID();
searchRegisteredModelsApiId = getUUID();
criticalInitialRequestIds = [this.initialSearchRegisteredModelsApiId];
getUrlState() {
return this.props.location ? Utils.getSearchParamsFromUrl(this.props.location.search) : {};
}
componentDidMount() {
const urlState = this.getUrlState();
const persistedPageTokens = this.getPersistedPageTokens();
const maxResultsForTokens = this.getPersistedMaxResults();
// eslint-disable-next-line react/no-did-mount-set-state
this.setState(
{
orderByKey: urlState.orderByKey === undefined ? this.state.orderByKey : urlState.orderByKey,
orderByAsc:
urlState.orderByAsc === undefined
? this.state.orderByAsc
: urlState.orderByAsc === 'true',
currentPage:
urlState.page !== undefined && urlState.page in persistedPageTokens
? parseInt(urlState.page, 10)
: this.state.currentPage,
maxResultsSelection: maxResultsForTokens,
pageTokens: persistedPageTokens,
},
() => {
this.loadModels(true);
},
);
}
getPersistedPageTokens() {
const store = ModelListPageImpl.getLocalStore(this.modelListPageStoreKey);
if (store && store.getItem('page_tokens')) {
return JSON.parse(store.getItem('page_tokens'));
} else {
return this.defaultPersistedPageTokens;
}
}
setPersistedPageTokens(page_tokens) {
const store = ModelListPageImpl.getLocalStore(this.modelListPageStoreKey);
if (store) {
store.setItem('page_tokens', JSON.stringify(page_tokens));
}
}
getPersistedMaxResults() {
const store = ModelListPageImpl.getLocalStore(this.modelListPageStoreKey);
if (store && store.getItem('max_results')) {
return parseInt(store.getItem('max_results'), 10);
} else {
return REGISTERED_MODELS_PER_PAGE;
}
}
setMaxResultsInStore(max_results) {
const store = ModelListPageImpl.getLocalStore(this.modelListPageStoreKey);
store.setItem('max_results', max_results.toString());
}
/**
* Returns a LocalStorageStore instance that can be used to persist data associated with the
* ModelRegistry component.
*/
static getLocalStore(key) {
return LocalStorageUtils.getSessionScopedStoreForComponent('ModelListPage', key);
}
// Loads the initial set of models.
loadModels(isInitialLoading = false) {
const { orderByKey, orderByAsc } = this.state;
const urlState = this.getUrlState();
this.loadPage(
this.state.currentPage,
urlState.nameSearchInput,
urlState.tagSearchInput,
orderByKey,
orderByAsc,
undefined,
undefined,
isInitialLoading,
);
}
resetHistoryState() {
this.setState((prevState) => ({
currentPage: 1,
pageTokens: this.defaultPersistedPageTokens,
}));
this.setPersistedPageTokens(this.defaultPersistedPageTokens);
}
/**
*
* @param orderByKey column key to sort by
* @param orderByAsc is sort by ascending order
* @returns {string} ex. 'name ASC'
*/
static getOrderByExpr = (orderByKey, orderByAsc) =>
orderByKey ? `${orderByKey} ${orderByAsc ? 'ASC' : 'DESC'}` : '';
isEmptyPageResponse = (value) => {
return !value || !value.registered_models || !value.next_page_token;
};
getNextPageTokenFromResponse(response) {
const { value } = response;
if (this.isEmptyPageResponse(value)) {
// Why we could be here:
// 1. There are no models returned: we went to the previous page but all models after that
// page's token has been deleted.
// 2. If `next_page_token` is not returned, assume there is no next page.
return null;
} else {
return value.next_page_token;
}
}
updatePageState = (page, response = {}) => {
const nextPageToken = this.getNextPageTokenFromResponse(response);
this.setState(
(prevState) => ({
currentPage: page,
pageTokens: {
...prevState.pageTokens,
[page + 1]: nextPageToken,
},
}),
() => {
this.setPersistedPageTokens(this.state.pageTokens);
},
);
};
handleSearch = (nameSearchInput, tagSearchInput, callback, errorCallback) => {
this.resetHistoryState();
const { orderByKey, orderByAsc } = this.state;
this.loadPage(
1,
nameSearchInput,
tagSearchInput,
orderByKey,
orderByAsc,
callback,
errorCallback,
);
};
handleClear = (callback, errorCallback) => {
this.setState({
orderByKey: REGISTERED_MODELS_SEARCH_NAME_FIELD,
orderByAsc: true,
});
this.updateUrlWithSearchFilter('', '', REGISTERED_MODELS_SEARCH_NAME_FIELD, true, 1);
this.loadPage(1, '', '', REGISTERED_MODELS_SEARCH_NAME_FIELD, true, callback, errorCallback);
};
updateUrlWithSearchFilter = (nameSearchInput, tagSearchInput, orderByKey, orderByAsc, page) => {
const urlParams = {};
if (nameSearchInput) {
urlParams['nameSearchInput'] = nameSearchInput;
}
if (tagSearchInput) {
urlParams['tagSearchInput'] = tagSearchInput;
}
if (orderByKey && orderByKey !== REGISTERED_MODELS_SEARCH_NAME_FIELD) {
urlParams['orderByKey'] = orderByKey;
}
if (orderByAsc === false) {
urlParams['orderByAsc'] = orderByAsc;
}
if (page && page !== 1) {
urlParams['page'] = page;
}
const newUrl = `/models?${Utils.getSearchUrlFromState(urlParams)}`;
if (newUrl !== this.props.history.location.pathname + this.props.history.location.search) {
this.props.history.push(newUrl);
}
};
handleMaxResultsChange = (key, callback, errorCallback) => {
this.setState({ maxResultsSelection: parseInt(key, 10) }, () => {
this.resetHistoryState();
const urlState = this.getUrlState();
const { orderByKey, orderByAsc, maxResultsSelection } = this.state;
this.setMaxResultsInStore(maxResultsSelection);
this.loadPage(
1,
urlState.nameSearchInput,
urlState.tagSearchInput,
orderByKey,
orderByAsc,
callback,
errorCallback,
);
});
};
handleClickNext = (callback, errorCallback) => {
const urlState = this.getUrlState();
const { orderByKey, orderByAsc, currentPage } = this.state;
this.loadPage(
currentPage + 1,
urlState.nameSearchInput,
urlState.tagSearchInput,
orderByKey,
orderByAsc,
callback,
errorCallback,
);
};
handleClickPrev = (callback, errorCallback) => {
const urlState = this.getUrlState();
const { orderByKey, orderByAsc, currentPage } = this.state;
this.loadPage(
currentPage - 1,
urlState.nameSearchInput,
urlState.tagSearchInput,
orderByKey,
orderByAsc,
callback,
errorCallback,
);
};
handleClickSortableColumn = (orderByKey, sortOrder, callback, errorCallback) => {
const orderByAsc = sortOrder !== AntdTableSortOrder.DESC; // default to true
this.setState({ orderByKey, orderByAsc });
this.resetHistoryState();
const urlState = this.getUrlState();
this.loadPage(
1,
urlState.nameSearchInput,
urlState.tagSearchInput,
orderByKey,
orderByAsc,
callback,
errorCallback,
);
};
getMaxResultsSelection = () => {
return this.state.maxResultsSelection;
};
loadPage(
page,
nameSearchInput = '',
tagSearchInput = '',
orderByKey,
orderByAsc,
callback,
errorCallback,
isInitialLoading,
) {
const { pageTokens } = this.state;
this.setState({ loading: true });
this.updateUrlWithSearchFilter(nameSearchInput, tagSearchInput, orderByKey, orderByAsc, page);
this.props
.searchRegisteredModelsApi(
appendTagsFilter(getModelNameFilter(nameSearchInput), tagSearchInput),
this.state.maxResultsSelection,
ModelListPageImpl.getOrderByExpr(orderByKey, orderByAsc),
pageTokens[page],
isInitialLoading
? this.initialSearchRegisteredModelsApiId
: this.searchRegisteredModelsApiId,
)
.then((r) => {
this.updatePageState(page, r);
this.setState({ loading: false });
callback && callback();
})
.catch((e) => {
Utils.logErrorAndNotifyUser(e);
this.setState({ currentPage: 1 });
this.resetHistoryState();
errorCallback && errorCallback();
});
}
render() {
const { orderByKey, orderByAsc, currentPage, pageTokens } = this.state;
const { models } = this.props;
const urlState = this.getUrlState();
return (
<RequestStateWrapper requestIds={[this.criticalInitialRequestIds]}>
<ModelListView
models={models}
loading={this.state.loading}
nameSearchInput={urlState.nameSearchInput}
tagSearchInput={urlState.tagSearchInput}
orderByKey={orderByKey}
orderByAsc={orderByAsc}
currentPage={currentPage}
nextPageToken={pageTokens[currentPage + 1]}
onSearch={this.handleSearch}
onClear={this.handleClear}
onClickNext={this.handleClickNext}
onClickPrev={this.handleClickPrev}
onClickSortableColumn={this.handleClickSortableColumn}
onSetMaxResult={this.handleMaxResultsChange}
getMaxResultValue={this.getMaxResultsSelection}
/>
</RequestStateWrapper>
);
}
}
const mapStateToProps = (state) => {
const models = Object.values(state.entities.modelByName);
return {
models,
};
};
const mapDispatchToProps = {
searchRegisteredModelsApi,
};
export const ModelListPage = connect(mapStateToProps, mapDispatchToProps)(ModelListPageImpl);
|
src/pages/GraphQL.js | marktani/react-native-express-1 | import React from 'react'
import markdown from 'markdown-in-js'
import markdownOptions from '../utils/MarkdownOptions'
import Page from './Page'
import { WebPlayer, PageHeader } from '../components'
const simpleQuery = `import React, { Component } from 'react'
import { AppRegistry, Image, View, ActivityIndicator, StyleSheet } from 'react-native'
import ApolloClient, { createNetworkInterface } from 'apollo-client'
import { ApolloProvider, graphql } from 'react-apollo'
import gql from 'graphql-tag'
// Initialize the Apollo Client
const client = new ApolloClient({
networkInterface: createNetworkInterface({
uri: 'https://api.graph.cool/simple/v1/ciwce5xw82kh7017179gwzn7q',
}),
})
// Define query types
const FeedQuery = gql\`
query posts {
allPosts {
id
imageUrl
description
}
}
\`
class Feed extends Component {
renderPost = ({id, imageUrl}) => {
return (
<Image
key={id}
style={styles.image}
source={{uri: imageUrl}}
/>
)
}
render() {
// Apollo injects the \`data\` prop, containing the result of our query,
// and a loading indicator to tell us when the data is ready.
const {data} = this.props
const {loading, allPosts} = data
// If we're loading, show a spinner.
if (loading) {
return <ActivityIndicator />
}
return (
<View style={styles.feed}>
{allPosts.map(this.renderPost)}
</View>
)
}
}
const styles = StyleSheet.create({
feed: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
image: {
width: 150,
height: 150,
margin: 15,
},
})
// Inject query response as \`this.props.data\`
const FeedWithData = graphql(FeedQuery)(Feed)
// ApolloProvider lets us use Apollo Client in descendant components
const App = () => (
<ApolloProvider client={client}>
<FeedWithData />
</ApolloProvider>
)
AppRegistry.registerComponent('App', () => App)
`
const vendorComponents = [
['apollo-client', 'https://cdn.rawgit.com/dabbott/665a982d2de9b7eea22114e266b1474b/raw/e289e526f402989f0c42668dcefe2b15127ca3a1/apollo-client.js'],
['react-apollo', 'https://cdn.rawgit.com/dabbott/c1dcec0ac74dc7d14e5a3a78d5c7fdd3/raw/f20b6af16aac7bff1808fea76eb9f815e41f8e96/react-apollo.js'],
['graphql-tag', 'https://gist.githubusercontent.com/dabbott/bf832015419ee30344ac573705c2cbeb/raw/6bfcd7294d324aeaf117f6b8bde40715bc89ec78/graphql-tag']
]
const content = markdown(markdownOptions)`
[GraphQL](http://graphql.org) is a query language for efficient and expressive fetching of hierarchical data. To use GraphQL, we need both a GraphQL server and a GraphQL client.
GraphQL servers expose a typed API, called the GraphQL schema. It acts as an abstraction layer between the database and clients, exposing available queries (to fetch data) and mutations (to write data), as well as the input and output types for those operations.
Client applications communicate with GraphQL servers using either plain HTTP or a dedicated GraphQL client, such as [Apollo Client](http://dev.apollodata.com). Apollo provides a data cache, along with hooks into the component lifecycle for consistent data across components. We'll use Apollo in the example below. Another popular client is [Relay](https://facebook.github.io/relay/), which has a steeper learning curve and requires more server-side setup, but provides cache consistency and requires less manual effort for the client.
# Getting Started with GraphQL
To get started with GraphQL, we first need to set up a GraphQL server - the easiest way to do this is through [Graphcool](https://graph.cool). Graphcool allows us to set up a powerful, easy-to-use, hosted GraphQL server in minutes. The API provides essential features, such as authentication and realtime subscriptions, allowing us to iterate rapidly on our React Native apps. Find out more in the [five minute getting started tutorial](https://www.youtube.com/watch?v=SooujCyMHe4).
Let's see how that would work for an Instagram clone. We want to display several posts with a description and image url in a feed. So we add a \`Post\` type to our GraphQL schema:
${<pre><code>{
`type Post {
id: ID!
description: String!
imageUrl: String!
}`
}</code></pre>}
Graphcool automatically generates queries and mutations based on the available model types. We can explore the API using [GraphiQL](https://github.com/graphql/graphiql), as demonstrated in the GIF below. You can try it out for yourself [here](https://api.graph.cool/simple/v1/ciwce5xw82kh7017179gwzn7q)!
<div>
<img
width='100%'
src={'graphql-autocompletion.gif'}
/>
</div>
We can use this query to list all \`Posts\`:
${<pre><code>{
`query posts {
allPosts {
imageUrl
description
}
}`
}</code></pre>}
The [GraphQL documentation](http://graphql.org/learn) provides additional info about the query syntax. GraphQL queries are highly flexible: the client decides which fields to include in the response. Query parameters can be used for even more control, e.g the client can specify filtering and ordering parameters, as in [this query](https://api.graph.cool/simple/v1/ciwce5xw82kh7017179gwzn7q?query=query%20%7B%0A%20%20allPosts(filter%3A%20%7B%0A%20%20%20%20description_contains%3A%20%22%23nature%22%0A%20%20%7D)%20%7B%0A%20%20%20%20description%0A%20%20%20%20imageUrl%0A%20%20%20%20comments(orderBy%3A%20text_ASC)%20%7B%0A%09%09%09text%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D):
${<pre><code>{
`query {
allPosts(filter: {
description_contains: "#nature"
}) {
description
imageUrl
comments(orderBy: text_ASC) {
text
}
}
}`
}</code></pre>}
You can read more about GraphQL query parameters [here](https://www.graph.cool/docs/tutorials/designing-powerful-apis-with-graphql-query-parameters-aing7uech3).
# Minimal Example
Let's use this query, along with the Apollo Client, to connect to the GraphQL server from our React Native app. We'll fetch the the \`Posts\`, and render them.
${
<WebPlayer
code={simpleQuery}
vendorComponents={vendorComponents}
/>
}
You might need to disable the Redux DevTools or similar extensions for this example to work, or simply run this page in an incognito window.
For an in-depth GraphQL tutorial for React Native, follow the [Learn Apollo React Native](https://www.learnapollo.com/tutorial-react-native-exponent/rne-01).
`
export default props =>
<Page {...props}>
<PageHeader
title={props.title}
author={"@_marktani"}
authorURL={'https://twitter.com/_marktani'}
/>
{content}
</Page>
|
src/components/common/svg-icons/device/data-usage.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceDataUsage = (props) => (
<SvgIcon {...props}>
<path d="M13 2.05v3.03c3.39.49 6 3.39 6 6.92 0 .9-.18 1.75-.48 2.54l2.6 1.53c.56-1.24.88-2.62.88-4.07 0-5.18-3.95-9.45-9-9.95zM12 19c-3.87 0-7-3.13-7-7 0-3.53 2.61-6.43 6-6.92V2.05c-5.06.5-9 4.76-9 9.95 0 5.52 4.47 10 9.99 10 3.31 0 6.24-1.61 8.06-4.09l-2.6-1.53C16.17 17.98 14.21 19 12 19z"/>
</SvgIcon>
);
DeviceDataUsage = pure(DeviceDataUsage);
DeviceDataUsage.displayName = 'DeviceDataUsage';
DeviceDataUsage.muiName = 'SvgIcon';
export default DeviceDataUsage;
|
src/parser/monk/brewmaster/modules/spells/BlackoutCombo.js | FaideWW/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import { SPELLS_WHICH_REMOVE_BOC } from '../../constants';
const debug = false;
const BOC_DURATION = 15000;
class BlackoutCombo extends Analyzer {
blackoutComboConsumed = 0;
blackoutComboBuffs = 0;
lastBlackoutComboCast = 0;
spellsBOCWasUsedOn = {};
get dpsWasteThreshold() {
if(!this.active) {
return null;
}
return {
actual: this.spellsBOCWasUsedOn[SPELLS.TIGER_PALM.id] / this.blackoutComboBuffs,
isLessThan: {
minor: 0.95,
average: 0.9,
major: 0.85,
},
style: 'percentage',
};
}
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.BLACKOUT_COMBO_TALENT.id);
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.BLACKOUT_COMBO_BUFF.id) {
debug && console.log('Blackout combo applied');
this.blackoutComboBuffs += 1;
this.lastBlackoutComboCast = event.timestamp;
}
}
on_byPlayer_refreshbuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.BLACKOUT_COMBO_BUFF.id) {
debug && console.log('Blackout combo refreshed');
this.blackoutComboBuffs += 1;
this.lastBlackoutComboCast = event.timestamp;
}
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (!SPELLS_WHICH_REMOVE_BOC.includes(spellId)) {
return;
}
// BOC should be up
if (this.lastBlackoutComboCast > 0 && this.lastBlackoutComboCast + BOC_DURATION > event.timestamp) {
this.blackoutComboConsumed += 1;
if (this.spellsBOCWasUsedOn[spellId] === undefined) {
this.spellsBOCWasUsedOn[spellId] = 0;
}
this.spellsBOCWasUsedOn[spellId] += 1;
}
this.lastBlackoutComboCast = 0;
}
suggestions(when) {
const wastedPerc = (this.blackoutComboBuffs - this.blackoutComboConsumed) / this.blackoutComboBuffs;
when(wastedPerc).isGreaterThan(0.1)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>You wasted {formatPercentage(actual)}% of your <SpellLink id={SPELLS.BLACKOUT_COMBO_BUFF.id} /> procs. Try to use the procs as soon as you get them so they are not overwritten.</span>)
.icon(SPELLS.BLACKOUT_COMBO_BUFF.icon)
.actual(`${formatPercentage(actual)}% unused`)
.recommended(`${Math.round(formatPercentage(recommended))}% or less is recommended`)
.regular(recommended + 0.1).major(recommended + 0.2);
});
}
statistic() {
const wastedPerc = (this.blackoutComboBuffs - this.blackoutComboConsumed) / this.blackoutComboBuffs;
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.BLACKOUT_COMBO_BUFF.id} />}
value={`${formatPercentage(wastedPerc)}%`}
label="Wasted blackout combo"
tooltip={`You got total <b>${this.blackoutComboBuffs}</b> blackout combo procs procs and used <b>${this.blackoutComboConsumed}</b> of them.
Blackout combo buff usage:
<ul>
${Object.keys(this.spellsBOCWasUsedOn)
.sort((a, b) => this.spellsBOCWasUsedOn[b] - this.spellsBOCWasUsedOn[a])
.map(type => `<li><i>${SPELLS[type].name || 'Unknown'}</i> was used ${this.spellsBOCWasUsedOn[type]} time${this.spellsBOCWasUsedOn[type] === 1 ? '' : 's'} (${formatPercentage(this.spellsBOCWasUsedOn[type] / this.blackoutComboConsumed)}%)</li>`)
.join('')}
</ul>`}
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL();
}
export default BlackoutCombo;
|
src/components/NotFound.js | joeYeager/personal-site | import React from 'react';
import Breakpoints from './Breakpoints';
const NotFound = () => {
return (
<div id="content">
<Breakpoints count={11}/>
<div id="div404">
<img id="hal" alt="Not Found" src={require("../assets/hal9000.png")} hspace="0" vspace="0"/>
<i className="fa fa-2x fa-quote-left"/>
<p id="msg404">I'm sorry Dave, I'm afraid I can't do that.</p>
<i className="fa fa-2x fa-quote-right rightQuote"/>
</div>
</div>
);
};
export default NotFound;
|
src/svg-icons/av/movie.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvMovie = (props) => (
<SvgIcon {...props}>
<path d="M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4z"/>
</SvgIcon>
);
AvMovie = pure(AvMovie);
AvMovie.displayName = 'AvMovie';
AvMovie.muiName = 'SvgIcon';
export default AvMovie;
|
src/components/StickyNote/StickyNote.js | arvigeus/studentlife | // @flow
import React from 'react';
import Relay from 'react-relay';
import s from './StickyNote.css';
type JokeType = {
joke: {
text: ?string
}
}
function StickyNote({ joke: { text } }: JokeType) {
return (
<div className={s.root} dangerouslySetInnerHTML={{ __html: text || 'Няма налични шеги' }} />
);
}
export default Relay.createContainer(StickyNote, {
fragments: {
joke: () => Relay.QL`
fragment on Joke {
text
}`
}
});
|
src/screens/Settings.js | CiriousJoker/LegacyManager | import React, { Component } from 'react';
import Button from 'material-ui/Button';
import TextField from 'material-ui/TextField';
import Input from 'material-ui/Input/Input';
import Paper from 'material-ui/Paper';
import Grid from 'material-ui/Grid';
import Typography from 'material-ui/Typography';
import Divider from 'material-ui/Divider';
const { dialog } = require('electron').remote;
const settings = require('electron-settings');
// Import functionality
//import { update } from '../functionality/update';
// Constants
const { Constants } = require('./js/Constants');
class LegacyXP extends Component {
constructor(props) {
super(props);
this.state = {
IsoLocation: settings.get(Constants.Settings.BrawlIsoLocation, ""),
Password: settings.get(Constants.Settings.PasswordLegacyXP, "")
};
}
selectBrawlIso = function () {
var result = dialog.showOpenDialog({ properties: ['openFile'] })[0];
console.log("Current path:", this.state.IsoLocation);
console.log("Path:", result);
this.setState({
IsoLocation: result,
});
settings.set(Constants.Settings.BrawlIsoLocation, result);
}
_handlePasswordChanged = (e) => {
var password = e.target.value;
this.setState({
Password: password
});
console.log("New password:", password);
settings.set(Constants.Settings.PasswordLegacyXP, password);
}
render() {
return (
<div className="page_root">
<Typography type="display1" gutterBottom>
Settings
</Typography>
<Typography type="subheading">
Choose your brawl .iso
</Typography>
<Grid container gutter={24}>
<Grid item xs>
<TextField value={this.state.IsoLocation.toString()} placeholder="Path/to/an/empty/folder" fullWidth />
</Grid>
<Grid item>
<Button onClick={this.selectBrawlIso.bind(this)}>
Select .iso
</Button>
</Grid>
</Grid>
{/* TODO: Don't hardcode this height */}
<div style={{ height: "32px" }} />
<Typography type="subheading">
Enter the password
</Typography>
<Grid container gutter={24}>
<Grid item xs>
<TextField value={this.state.Password.toString()} onChange={this._handlePasswordChanged} placeholder="Ask the Legacy XP dev team for the password." fullWidth />
</Grid>
</Grid>
</div>
);
}
}
export default LegacyXP; |
src/app.js | ymkz/syncedTabs | import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/app'
ReactDOM.render(
<App />, document.getElementById('root')
)
|
blueocean-material-icons/src/js/components/svg-icons/image/filter-3.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageFilter3 = (props) => (
<SvgIcon {...props}>
<path d="M21 1H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm14 8v-1.5c0-.83-.67-1.5-1.5-1.5.83 0 1.5-.67 1.5-1.5V7c0-1.11-.9-2-2-2h-4v2h4v2h-2v2h2v2h-4v2h4c1.1 0 2-.89 2-2z"/>
</SvgIcon>
);
ImageFilter3.displayName = 'ImageFilter3';
ImageFilter3.muiName = 'SvgIcon';
export default ImageFilter3;
|
src/svg-icons/navigation/chevron-left.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationChevronLeft = (props) => (
<SvgIcon {...props}>
<path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
</SvgIcon>
);
NavigationChevronLeft = pure(NavigationChevronLeft);
NavigationChevronLeft.displayName = 'NavigationChevronLeft';
NavigationChevronLeft.muiName = 'SvgIcon';
export default NavigationChevronLeft;
|
src/px-branding-bar/index.js | jonniespratley/px-components-react | import React from 'react';
import PredixLogo from './px-predix-svg-logo';
import Logo from './px-ge-svg-logo';
import styles from './px-branding-bar.scss';
//https://www.predix-ui.com/#/elements/px-branding-bar
export default ({ title = 'Predix Design System', powered = 'Powered by', children }) => (
<div className='px-branding-bar flex flex--justify'>
<div className='u-ml flex flex--middle'>
<span className='u-ml-- flex flex--middle'><Logo/></span>
<label className='u-ml-- flex flex--middle'>{title}</label>
{children && <div>{children}</div>}
</div>
<div className='flex flex--middle'>
<span className='u-mr-- px-branding-bar__powered-by-text'>{powered}</span>
<span className='u-mr'><PredixLogo size={10}/></span>
</div>
<style jsx>{styles}</style>
</div>
);
|
Js/Ui/Components/Filters/Price.js | Webiny/Webiny | import React from 'react';
import Webiny from 'webiny';
class Number extends Webiny.Ui.Component {
}
Number.defaultProps = {
format: null,
default: '-',
value: null,
renderer() {
try {
return <span>{Webiny.I18n.price(this.props.value, this.props.format)}</span>;
} catch (e) {
return this.props.default;
}
}
};
export default Webiny.createComponent(Number); |
src/routes.js | anvk/redux-portal-boilerplate | import React, { Component } from 'react';
import { connect } from 'react-redux';
import params from 'query-params';
import { Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { fixUrl } from './utils/utils.js';
import { Dashboard, NotFoundPage } from './components';
import {
App,
LoginPageContainer,
MiscContainer,
ReposContainer,
UsersContainer,
UserContainer,
FollowersContainer
} from './containers';
import { headerAuth } from './constants/auth.js';
import { checkAuth, checkIsLoggedIn } from './reducers/auth.js';
import {
HOME_URL,
LOGIN_URL,
TAB_REPOS,
TAB_FOLLOWERS,
TAB_MISC,
TAB_USERS,
TAB_USER
} from './constants/constants.js';
import { publicPath } from '../config/config.json';
import * as sharedDataActions from './actions/sharedDataActions.js';
import * as loginPageActions from './actions/loginPageActions.js';
class Routes extends Component {
_onEnterCheckAuth = (tabIndex) => {
const { changeTab, store } = this.props;
return (nextState, replace) => {
const { auth } = store.getState();
const { authRole } = auth;
changeTab(tabIndex);
const hasAuth = checkAuth({
...headerAuth[tabIndex],
authRole,
replace
});
if (hasAuth) {
return;
}
replace(HOME_URL);
};
};
_onChange = (prevState, nextState, replace) => {
const { store, logout } = this.props;
if (checkIsLoggedIn(store.getState().auth)) {
return;
}
const { location } = nextState;
const url = location.pathname.replace(publicPath, '') + location.search;
const postFix = url ? `?${params.encode({ url })}` : '';
logout();
replace(fixUrl(`${LOGIN_URL}${postFix}`));
};
render() {
const { store } = this.props;
const routes = [
{
path: fixUrl(LOGIN_URL),
component: LoginPageContainer,
onEnter: (nextState, replace) => {
const { auth } = store.getState();
if (checkIsLoggedIn(auth)) {
replace(HOME_URL);
}
}
},
{
path: publicPath,
component: App,
indexRoute: { component: Dashboard },
onChange: this._onChange,
onEnter: (nextState, replace) =>
this._onChange(null, nextState, replace),
childRoutes: [
{
path: 'user',
indexRoute: { component: UserContainer },
onEnter: this._onEnterCheckAuth(TAB_USER)
},
{
path: 'users',
indexRoute: { component: UsersContainer },
onEnter: this._onEnterCheckAuth(TAB_USERS)
},
{
path: 'repos',
indexRoute: { component: ReposContainer },
onEnter: this._onEnterCheckAuth(TAB_REPOS)
},
{
path: 'followers',
indexRoute: { component: FollowersContainer },
onEnter: this._onEnterCheckAuth(TAB_FOLLOWERS)
},
{
path: 'misc',
indexRoute: { component: MiscContainer },
onEnter: this._onEnterCheckAuth(TAB_MISC)
},
{ path: '*', status: 404, component: NotFoundPage }
]
}
];
const history = syncHistoryWithStore(browserHistory, store);
return <Router history={history} routes={routes} />;
}
}
export default connect(
undefined,
{
changeTab: sharedDataActions.changeTab,
logout: loginPageActions.logout
}
)(Routes);
|
src/components/Post/Post.js | bapti/blog | // @flow strict
import React from 'react';
import { Link } from 'gatsby';
import Author from './Author';
import Comments from './Comments';
import Content from './Content';
import Meta from './Meta';
import Tags from './Tags';
import styles from './Post.module.scss';
import type { Node } from '../../types';
type Props = {
post: Node
};
const Post = ({ post }: Props) => {
const { html } = post;
const { tagSlugs, slug } = post.fields;
const { tags, title, date } = post.frontmatter;
return (
<div className={styles['post']}>
<Link className={styles['post__home-button']} to="/">All Articles</Link>
<div className={styles['post__content']}>
<Content body={html} title={title} />
</div>
<div className={styles['post__footer']}>
<Meta date={date} />
{tags && tagSlugs && <Tags tags={tags} tagSlugs={tagSlugs} />}
<Author />
</div>
<div className={styles['post__comments']}>
<Comments postSlug={slug} postTitle={post.frontmatter.title} />
</div>
</div>
);
};
export default Post;
|
examples/official-storybook/components/FlowTypeButton.js | rhalff/storybook | // @flow
import React from 'react';
/* eslint-disable react/no-unused-prop-types,react/require-default-props */
const Message = {};
type PropsType = {
/** A multi-type prop to be rendered in the button */
label: string,
/** Function to be called when the button is clicked */
onClick?: Function,
/** Boolean representing whether the button is disabled */
disabled?: boolean,
/** A plain object */
obj?: Object,
/** A complex Object with nested types */
shape: {
id: number,
func?: Function,
arr?: Array<{
index: number,
}>,
shape?: {
shape?: {
foo?: string,
},
},
},
/** An array of numbers */
arrayOf?: Array<number>,
/** A custom type */
msg?: typeof Message,
/** `oneOf` as Enum */
enm?: 'News' | 'Photos',
/** `oneOf` A multi-type prop of string or custom Message */
union?: string | typeof Message,
};
/** FlowTypeButton component description imported from comments inside the component file */
const FlowTypeButton = ({ label, onClick, disabled }: PropsType) => (
<button onClick={onClick} disabled={disabled}>
{label}
</button>
);
FlowTypeButton.defaultProps = {
disabled: false,
onClick: () => {},
};
export default FlowTypeButton;
|
src/js/components/GalleryImages/Index.js | appdev-academy/appdev.academy-react | import React from 'react'
import { inject, observer } from 'mobx-react'
import ConfirmationDialog from '../ConfirmationDialog'
import GreenButton from '../Buttons/Green'
import Row from './Row'
@observer
export default class Index extends React.Component {
constructor(props) {
super(props)
this.state = {
image: '',
file: '',
deleteConfirmationDialogShow: false,
deleteConfirmationDialogEntityID: null
}
}
componentDidMount() {
this.props.galleryImagesStore.fetchIndex(this.props.projectID)
}
selectFile() {
this.refs.fileUpload.click()
}
didSelectFile() {
let file = this.refs.fileUpload.files[0]
let reader = new FileReader()
reader.onload = (event) => {
this.setState({
image: event.target.result,
file: file
})
}
reader.readAsDataURL(file)
}
uploadSelectedFile() {
if (this.state.file == '') {
return
}
let data = new FormData()
data.append('gallery_image[image]', this.state.file)
let projectID = this.props.projectID
this.props.galleryImagesStore.create(projectID, data).then((response) => {
this.setState({
image: '',
file: ''
})
this.props.galleryImagesStore.fetchIndex(projectID)
})
}
showDeleteConfirmationDialog(entityID) {
this.setState({
deleteConfirmationDialogShow: true,
deleteConfirmationDialogEntityID: entityID
})
}
hideDeleteConfirmationDialog() {
this.setState({
deleteConfirmationDialogShow: false,
deleteConfirmationDialogEntityID: null
})
}
deleteButtonClick() {
let projectID = this.props.projectID
let galleryImageID = this.state.deleteConfirmationDialogEntityID
this.props.galleryImagesStore.delete(projectID, galleryImageID);
this.setState({
deleteConfirmationDialogShow: false,
deleteConfirmationDialogEntityID: null
})
}
renderImages(images) {
return images.map((image, index) => {
return (
<Row
key={ index }
image={ image }
deleteButtonClick={ (entityID) => { this.showDeleteConfirmationDialog(entityID) }}
/>
)
})
}
render() {
return (
<div>
<h2 className='center'>Article Images</h2>
<table className='admin'>
<thead>
<tr>
<td>Preview</td>
<td>Image URL</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
<tr className='new-article-image'>
<td>
<img src={ this.state.image } onClick={ this.selectFile.bind(this) } />
<input
className='hidden'
name='image'
type='file'
accept='image/png, image/jpeg, image/jpg'
onChange={ this.didSelectFile.bind(this) }
ref='fileUpload'
/>
</td>
<td></td>
<td>
<GreenButton
title='Upload'
onClick={ this.uploadSelectedFile.bind(this) }
/>
</td>
</tr>
{ this.renderImages(this.props.galleryImagesStore.images) }
</tbody>
</table>
<ConfirmationDialog
actionName='delete'
entityName='image'
show={ this.state.deleteConfirmationDialogShow }
destructive={ true }
actionButtonClick={ () => { this.deleteButtonClick() }}
cancelButtonClick= { () => { this.hideDeleteConfirmationDialog() }}
/>
</div>
)
}
}
|
packages/bonde-styleguide/src/content/IconColorful/svg/Power.js | ourcities/rebu-client | import React from 'react'
const Icon = () => (
<svg xmlns='http://www.w3.org/2000/svg' width='60' height='43' viewBox='0 0 60 43'>
<g fill='none' fillRule='evenodd'>
<g fill='#E09' transform='translate(9.6)'>
<ellipse cx='20' cy='19.907' opacity='.297' rx='20' ry='19.907' />
<ellipse cx='20' cy='18.926' opacity='.3' rx='16' ry='15.926' />
<ellipse cx='20' cy='18.944' rx='12' ry='11.944' />
</g>
<path fill='#000' d='M14.791 36.148l2.42-4.046c.603-1.01.193-2.265-.916-2.805l-.024-.012a2.444 2.444 0 0 0-1.322-.231l.172-3.01c.061-1.071-.837-1.985-2.007-2.041-.874-.042-1.653.407-2.016 1.085-.34-.573-.988-.975-1.752-1.012-.995-.048-1.865.54-2.14 1.376a2.216 2.216 0 0 0-1.307-.495c-1.17-.056-2.168.767-2.23 1.839l-.014.253a2.22 2.22 0 0 0-1.284-.476c-1.17-.056-2.167.767-2.229 1.837l-.11 1.934v.008l-.014.015S0 31.356 0 31.503c0 .147.04.809.12 1.324.024.151.161.735.266 1.16.223.903 1.162 2.488 2.17 3.845l.086.125c.04.058.075.128.107.206l.299 3.071c.04.404.43.73.873.73h8.272c.442 0 .833-.327.872-.73l.23-2.36c.084-.342.218-.693.47-1.009M37.604 26.458l2.88-4.816c.718-1.2.23-2.695-1.09-3.338a2.936 2.936 0 0 0-1.602-.29l.205-3.58c.073-1.276-.997-2.364-2.389-2.43-1.04-.05-1.967.484-2.4 1.29-.405-.681-1.176-1.16-2.085-1.203-1.183-.057-2.22.642-2.548 1.637a2.638 2.638 0 0 0-1.555-.589c-1.392-.066-2.58.913-2.652 2.188l-.018.302a2.641 2.641 0 0 0-1.528-.567c-1.392-.067-2.58.913-2.653 2.187l-.131 2.301c-.017.028-.038 1.205-.038 1.38 0 .175.048.963.143 1.575.029.18.192.875.317 1.382.265 1.074 1.383 2.96 2.582 4.575l.102.15c.047.068.09.151.128.245l.455 12.532c.047.48.511.87 1.039.87h9.844c.528 0 .993-.39 1.04-.87 0 0 .032-10.24.173-11.686.1-.408.26-.826.56-1.2M56.791 36.148l2.42-4.046c.603-1.01.193-2.265-.916-2.805l-.024-.012a2.444 2.444 0 0 0-1.322-.231l.172-3.01c.061-1.071-.837-1.985-2.007-2.041-.874-.042-1.653.407-2.016 1.085-.34-.573-.988-.975-1.752-1.012-.995-.048-1.865.54-2.14 1.376a2.216 2.216 0 0 0-1.307-.495c-1.17-.056-2.168.767-2.23 1.839l-.014.253a2.22 2.22 0 0 0-1.284-.476c-1.17-.056-2.167.767-2.229 1.837l-.11 1.934v.008l-.014.015S42 31.356 42 31.503c0 .147.04.809.12 1.324.024.151.161.735.266 1.16.223.903 1.162 2.488 2.17 3.845l.086.125c.04.058.075.128.107.206l.299 3.071c.04.404.43.73.873.73h8.272c.442 0 .833-.327.872-.73l.23-2.36c.084-.342.218-.693.47-1.009' />
</g>
</svg>
)
Icon.displayName = 'IconColorful.Power'
export default Icon
|
actor-apps/app-web/src/app/components/sidebar/ContactsSection.react.js | hejunbinlan/actor-platform | import _ from 'lodash';
import React from 'react';
import { Styles, RaisedButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import ContactStore from 'stores/ContactStore';
import ContactActionCreators from 'actions/ContactActionCreators';
import AddContactStore from 'stores/AddContactStore';
import AddContactActionCreators from 'actions/AddContactActionCreators';
import ContactsSectionItem from './ContactsSectionItem.react';
import AddContactModal from 'components/modals/AddContact.react.js';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
isAddContactModalOpen: AddContactStore.isModalOpen(),
contacts: ContactStore.getContacts()
};
};
class ContactsSection extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
componentWillUnmount() {
ContactActionCreators.hideContactList();
ContactStore.removeChangeListener(this.onChange);
AddContactStore.removeChangeListener(this.onChange);
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ContactActionCreators.showContactList();
ContactStore.addChangeListener(this.onChange);
AddContactStore.addChangeListener(this.onChange);
ThemeManager.setTheme(ActorTheme);
}
onChange = () => {
this.setState(getStateFromStores());
};
openAddContactModal = () => {
AddContactActionCreators.openModal();
};
render() {
let contacts = this.state.contacts;
let contactList = _.map(contacts, (contact, i) => {
return (
<ContactsSectionItem contact={contact} key={i}/>
);
});
let addContactModal;
if (this.state.isAddContactModalOpen) {
addContactModal = <AddContactModal/>;
}
return (
<section className="sidebar__contacts">
<ul className="sidebar__list sidebar__list--contacts">
{contactList}
</ul>
<footer>
<RaisedButton label="Add contact" onClick={this.openAddContactModal} style={{width: '100%'}}/>
{addContactModal}
</footer>
</section>
);
}
}
export default ContactsSection;
|
src/svg-icons/communication/stay-primary-portrait.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationStayPrimaryPortrait = (props) => (
<SvgIcon {...props}>
<path d="M17 1.01L7 1c-1.1 0-1.99.9-1.99 2v18c0 1.1.89 2 1.99 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/>
</SvgIcon>
);
CommunicationStayPrimaryPortrait = pure(CommunicationStayPrimaryPortrait);
CommunicationStayPrimaryPortrait.displayName = 'CommunicationStayPrimaryPortrait';
CommunicationStayPrimaryPortrait.muiName = 'SvgIcon';
export default CommunicationStayPrimaryPortrait;
|
src/pages/todo/components/header.js | mvtnghia/web-boilerplate | // @flow
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addTodo } from '../actions';
import TodoTextInput from './todo-text-input';
export type Props = {
addTodo: Function,
};
function Header(props: Props) {
return (
<div className="header">
<h1>Todos</h1>
<TodoTextInput
newTodo
onSave={props.addTodo}
placeholder="What needs to be done?"
/>
</div>
);
}
export default connect(
null,
dispatch => bindActionCreators({ addTodo }, dispatch),
)(Header);
|
components/Navbar.js | InnoD-WebTier/calwtcrew | import React, { Component } from 'react';
import { Link } from 'react-router';
import { prefixLink } from 'gatsby-helpers'; // eslint-disable-line
import FontAwesome from 'react-fontawesome';
import Headroom from 'react-headroom';
import classNames from 'classnames';
import logo from '../assets/images/logo.png';
export default class Navbar extends Component {
constructor(props) {
super(props);
this.state = {
open: false,
maxHeight: 50,
};
this._handleNavOpen = this._handleNavOpen.bind(this);
}
_handleNavOpen(e) {
e.preventDefault();
this.setState({
open: !this.state.open,
});
}
render() {
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (
<div>
<Headroom
wrapperStyle={{
maxHeight: this.state.maxHeight,
}}
style={{
background: 'rgba(255, 255, 255, 0.99)',
}}
>
<div
className={classNames('navbar', {
'navbar--open': this.state.open,
})}
>
<div className="logo">
<Link to={prefixLink('/')} className="link">
<img src={logo} alt="logo" className="logo__image" />
</Link>
</div>
<div
className={classNames('links', 'navbar__hamburger', {
'navbar__hamburger--active': this.state.open,
})}
onClick={this._handleNavOpen}
>
<div className="hamburger__bar bar" />
<div className="hamburger__bar bar" />
<div className="hamburger__bar bar" />
</div>
<div className="links" onClick={this._handleNavOpen}>
<div className="navbar__media">
<a href="https://www.facebook.com/californialightweightcrew/?ref=br_rs" target="_blank" rel="noopener noreferrer">
<FontAwesome
className="fb__icon"
name="facebook"
/>
</a>
<a href="https://www.instagram.com/cal_lightweights/" target="_blank" rel="noopener noreferrer">
<FontAwesome
className="ig__icon"
name="instagram"
/>
</a>
</div>
<Link to={prefixLink('/about/')} className="link">
ABOUT
</Link>
<div className="roster">
ROSTER
<Link to={prefixLink('/roster/men/')} className="link__navbar--open">
MEN'S
</Link>
<Link to={prefixLink('/roster/women')} className="link__navbar--open">
WOMEN'S
</Link>
</div>
<div className="dropdown">
<button className="dropbtn">ROSTERS</button>
<div className="dropdown__content">
<Link to={prefixLink('/roster/men/')} className="link">
<div className="dropdown__link">MEN'S ROSTER</div>
</Link>
<br />
<Link to={prefixLink('/roster/women/')} className="link">
<div className="dropdown__link">WOMEN'S ROSTER</div>
</Link>
</div>
</div>
<Link to={prefixLink('/schedule/')} className="link">
SCHEDULE
</Link>
<Link to={prefixLink('/alumni/')} className="link">
ALUMNI
</Link>
<Link to={prefixLink('/join/')} className="link">
JOIN US
</Link>
</div>
</div>
</Headroom>
</div>
);
}
}
|
src/sites/launchpads.js | cosmowiki/cosmowiki | import React from 'react';
import LaunchpadsComponent from '../components/launchpads';
export default class Launchpads {
static componentWithData(_, appUrl) {
return <LaunchpadsComponent appUrl={appUrl} />;
}
static fromRawData() {}
}
|
app/javascript/mastodon/components/avatar_overlay.js | MastodonCloud/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { autoPlayGif } from '../initial_state';
export default class AvatarOverlay extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
friend: ImmutablePropTypes.map.isRequired,
animate: PropTypes.bool,
};
static defaultProps = {
animate: autoPlayGif,
};
render() {
const { account, friend, animate } = this.props;
const baseStyle = {
backgroundImage: `url(${account.get(animate ? 'avatar' : 'avatar_static')})`,
};
const overlayStyle = {
backgroundImage: `url(${friend.get(animate ? 'avatar' : 'avatar_static')})`,
};
return (
<div className='account__avatar-overlay'>
<div className='account__avatar-overlay-base' style={baseStyle} />
<div className='account__avatar-overlay-overlay' style={overlayStyle} />
</div>
);
}
}
|
caseStudy/ui/src/App.js | tadas412/EngineeringEssentials | /**
* Copyright 2017 Goldman Sachs.
* 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';
import './style/App.css';
/**
* TODO:
* Import your components
*/
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
/**
* TODO
* Add state objects for the user inputs and anything else you may need to render the highchart.
*/
};
}
render () {
return (
<div className="page-display">
<div className="input">
{/**
* TODO
* Render the StockTicker and Date components. You can use the date component twice
* for both the start and end dates.
* Add onChange props to the StockTicker and both Date components.
* These props methods should set state and help determine if the
* highchart should be displayed by changing the state of that boolean.
* Don't forget to bind these methods!
*/}
<div className="date-range">
</div>
</div>
{/**
* TODO
* Create a div element that shows a highchart when the ticker, start date, end date
* states ALL have values and nothing (null) otherwise. You will need to use a conditional here
* to help control rendering and pass these states as props to the component. This conditional can
* be maintained as a state object.
* http://reactpatterns.com/#conditional-rendering
*/}
</div>
);
}
}
export default App;
|
src/components/Sidebar.js | Shashank1706/olep-serverless | import React from 'react';
import { Link } from 'react-router-dom';
import {
Navbar
} from 'react-bootstrap';
export default (props) => (
<div className={props.visibility ? "overlay visible" : "overlay notvisible"} onClick={props.onClick} >
<div className="sidebar">
<Navbar className="topbar" fluid collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">OLEPCO</Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
</Navbar>
</div>
</div>
);
|
src/routes/Synthesizer/components/Controls.js | prestonbernstein/react-redux-synthesizer | import React from 'react'
const Controls = (props) => (
<div id='Controls'>
<div className='control'>
<label htmlFor='waveform'>
Waveform
</label>
<select
id='waveform'
onChange={props.changeWaveform}
value={props.waveform}
>
{
props.waveforms.map(waveform =>
<option
key={waveform.id}
value={waveform.type}
>
{waveform.type}
</option>
)
}
</select>
</div>
<div className='control'>
<label htmlFor='pitchBend'>Pitch Bend</label>
<input
id='frequency'
type='number'
pattern='[0-9]*'
value={props.frequency}
onChange={props.changeFrequency}
/>
</div>
<div className='control'>
<label htmlFor='duration'>Duration (milliseconds)</label>
<input
id='duration'
type='number'
pattern='[0-9]*'
value={props.duration}
onChange={props.changeDuration}
/>
</div>
</div>
)
Controls.propTypes = {
waveforms: React.PropTypes.arrayOf(
React.PropTypes.object
),
waveform: React.PropTypes.string,
frequency: React.PropTypes.number,
duration: React.PropTypes.number,
changeWaveform: React.PropTypes.func,
changeFrequency: React.PropTypes.func,
changeDuration: React.PropTypes.func
}
export default Controls
|
src/containers/Contact.js | sogalutira/PollerBears | import React, { Component } from 'react';
class Contact extends Component {
render(){
return(
<div className="contact-page">
<article>
<h2>Contact Us</h2>
<section>
<h3>Chief Election Officer</h3>
Scott T. Nago
</section>
<section>
<h3>Office of Elections Address</h3>
<p>
Office of Elections <br />
802 Lehua Avenue <br />
Pearl City, Hawaii 96782
</p>
<p className="col">
<h4>Hours</h4>
7:45am - 4:30pm<br />
<em>Except Saturday, Sunday, and holidays</em>
</p>
</section>
<section>
<h3>Phone</h3>
<section className="phone-container">
<div className="phone-flex">
<h4>Oahu</h4>
808-453-VOTE(8683)
</div>
<div className="phone-flex">
<h4>Neighbor Island Toll Free</h4>
1-800-442-VOTE(8683)
</div>
<div className="phone-flex">
<h4>TTY</h4>
(808)453-6150
</div>
</section>
</section>
<section>
<h3>Fax</h3>
(808)453-6006
</section>
<section>
<h3>Email</h3>
<a href="mailto:elections@hawaii.gov" target="_top">elections@hawaii.gov</a>
</section>
</article>
</div>
);
}
}
export default Contact; |
fields/types/geopoint/GeoPointColumn.js | dryna/keystone-twoje-urodziny | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var GeoPointColumn = React.createClass({
displayName: 'GeoPointColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value || !value.length) return null;
const formattedValue = `${value[1]}, ${value[0]}`;
const formattedTitle = `Lat: ${value[1]} Lng: ${value[0]}`;
return (
<ItemsTableValue title={formattedTitle} field={this.props.col.type}>
{formattedValue}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
},
});
module.exports = GeoPointColumn;
|
react-ui/src/components/NavDropdownComponent/NavDropdownComponent.js | hokustalkshow/find-popular | import React, { Component } from 'react';
import { NavDropdown, MenuItem } from 'react-bootstrap';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
function StandardLi({item}) {
return <li className="navbar-text" >{item.menuItemLabel}</li>
}
class NavDropdownComponent extends Component {
render () {
return (
<NavDropdown eventKey={this.props.eventKey} title={this.props.titlePrefix} id={this.props.id} >
{this.props.menuItemInfo.map((item, index) => {
if (!item.label) {
return (
<MenuItem key={index} eventKey={item.eventKey} onClick={()=>this.props.sort(item.menuItem, item.menuItemLabel)}>
{item.menuItemLabel}
</MenuItem>
);
}
return <StandardLi key={index} item={item} />
})}
</NavDropdown>
);
}
}
NavDropdownComponent.propTypes = {
eventKey: PropTypes.string.isRequired,
titlePrefix: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
menuItemInfo: PropTypes.array.isRequired,
sort: PropTypes.func.isRequired
}
const mapStateToProps = (state) => {
return {
sortedPen: state.sortCodePensReducer.sortedPen
}
}
export default connect(mapStateToProps)(NavDropdownComponent); |
src/index.js | otsoaUnLoco/wolf-chess | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import BoardWrapper from './BoardWrapper';
ReactDOM.render(
<BoardWrapper />,
document.getElementById('root'),
);
|
src/client/scenes/User/index.js | kettui/webcord-web-app | import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { autobind } from 'core-decorators';
import classNames from 'classnames/bind';
import { Segment, Message } from 'semantic-ui-react';
import { MessageLoading, TwitchSearch, Stream } from 'components/';
import UserInfo from './UserInfo';
import * as date from 'utils/date';
import styles from './user.scss';
const cx = classNames.bind(styles);
@inject('userStore', 'navStore') @observer @autobind
class User extends Component {
constructor(props) {
super();
}
componentWillMount() {
this.props.navStore.userRouteHandler();
}
render() {
const {
userStore: { loading, self },
} = this.props;
if(loading)
return <MessageLoading />
return (
<Segment className={styles['wrapper']} basic>
<Segment className={styles['top-bar']} basic>
<UserInfo {...self} />
<TwitchSearch
className={styles['search']}
searchFor="channels"
placeholder="Channel search"
follower={self}
fluid
/>
</Segment>
<Segment className={styles['container']} basic>
{ self.streams.size > 0 ? self.streams.values().map(stream => (
<Stream
key={stream.channel.id}
follower={self}
stream={stream}
/>
)) : (
<Message
icon="info circle"
header="No followed streams"
list={[
"You're currently not following any streams. You can use the search field above to find and follow Twitch channels.",
"Once followed, you will receive announcements whenever the stream goes live."
]}
/>
) }
</Segment>
</Segment>
)
}
}
export default User
|
src/index.js | scenario-generator/frontend | import React from 'react';
import ReactDOM from 'react-dom';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { configureStore } from './store/configureStore';
import Root from './containers/Root'
import * as serviceWorker from './serviceWorker';
const store = configureStore(window.__data);
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Root store={store} history={history} />,
document.getElementById('app')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
examples/counter/index.js | jasonals/redux-devtools | import React from 'react';
import App from './containers/App';
React.render(
<App />,
document.getElementById('root')
);
|
blueprints/view/files/__root__/views/__name__View/__name__View.js | kolpav/react-redux-starter-kit | import React from 'react'
type Props = {
};
export class <%= pascalEntityName %> extends React.Component {
props: Props;
render () {
return (
<div></div>
)
}
}
export default <%= pascalEntityName %>
|
app/javascript/mastodon/features/ui/components/columns_area.js | hugogameiro/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ReactSwipeableViews from 'react-swipeable-views';
import { links, getIndex, getLink } from './tabs_bar';
import { Link } from 'react-router-dom';
import BundleContainer from '../containers/bundle_container';
import ColumnLoading from './column_loading';
import DrawerLoading from './drawer_loading';
import BundleColumnError from './bundle_column_error';
import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, DirectTimeline, FavouritedStatuses, ListTimeline } from '../../ui/util/async-components';
import detectPassiveEvents from 'detect-passive-events';
import { scrollRight } from '../../../scroll';
const componentMap = {
'COMPOSE': Compose,
'HOME': HomeTimeline,
'NOTIFICATIONS': Notifications,
'PUBLIC': PublicTimeline,
'COMMUNITY': CommunityTimeline,
'HASHTAG': HashtagTimeline,
'DIRECT': DirectTimeline,
'FAVOURITES': FavouritedStatuses,
'LIST': ListTimeline,
};
const messages = defineMessages({
publish: { id: 'compose_form.publish', defaultMessage: 'Toot' },
});
const shouldHideFAB = path => path.match(/^\/statuses\//);
export default @(component => injectIntl(component, { withRef: true }))
class ColumnsArea extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
intl: PropTypes.object.isRequired,
columns: ImmutablePropTypes.list.isRequired,
isModalOpen: PropTypes.bool.isRequired,
singleColumn: PropTypes.bool,
children: PropTypes.node,
};
state = {
shouldAnimate: false,
}
componentWillReceiveProps() {
this.setState({ shouldAnimate: false });
}
componentDidMount() {
if (!this.props.singleColumn) {
this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false);
}
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.isRtlLayout = document.getElementsByTagName('body')[0].classList.contains('rtl');
this.setState({ shouldAnimate: true });
}
componentWillUpdate(nextProps) {
if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
componentDidUpdate(prevProps) {
if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) {
this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false);
}
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.setState({ shouldAnimate: true });
}
componentWillUnmount () {
if (!this.props.singleColumn) {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
handleChildrenContentChange() {
if (!this.props.singleColumn) {
const modifier = this.isRtlLayout ? -1 : 1;
this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier);
}
}
handleSwipe = (index) => {
this.pendingIndex = index;
const nextLinkTranslationId = links[index].props['data-preview-title-id'];
const currentLinkSelector = '.tabs-bar__link.active';
const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`;
// HACK: Remove the active class from the current link and set it to the next one
// React-router does this for us, but too late, feeling laggy.
document.querySelector(currentLinkSelector).classList.remove('active');
document.querySelector(nextLinkSelector).classList.add('active');
}
handleAnimationEnd = () => {
if (typeof this.pendingIndex === 'number') {
this.context.router.history.push(getLink(this.pendingIndex));
this.pendingIndex = null;
}
}
handleWheel = () => {
if (typeof this._interruptScrollAnimation !== 'function') {
return;
}
this._interruptScrollAnimation();
}
setRef = (node) => {
this.node = node;
}
renderView = (link, index) => {
const columnIndex = getIndex(this.context.router.history.location.pathname);
const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] });
const icon = link.props['data-preview-icon'];
const view = (index === columnIndex) ?
React.cloneElement(this.props.children) :
<ColumnLoading title={title} icon={icon} />;
return (
<div className='columns-area' key={index}>
{view}
</div>
);
}
renderLoading = columnId => () => {
return columnId === 'COMPOSE' ? <DrawerLoading /> : <ColumnLoading />;
}
renderError = (props) => {
return <BundleColumnError {...props} />;
}
render () {
const { columns, children, singleColumn, isModalOpen, intl } = this.props;
const { shouldAnimate } = this.state;
const columnIndex = getIndex(this.context.router.history.location.pathname);
this.pendingIndex = null;
if (singleColumn) {
const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/statuses/new' className='floating-action-button' aria-label={intl.formatMessage(messages.publish)}><i className='fa fa-pencil' /></Link>;
return columnIndex !== -1 ? [
<ReactSwipeableViews key='content' index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}>
{links.map(this.renderView)}
</ReactSwipeableViews>,
floatingActionButton,
] : [
<div className='columns-area'>{children}</div>,
floatingActionButton,
];
}
return (
<div className={`columns-area ${ isModalOpen ? 'unscrollable' : '' }`} ref={this.setRef}>
{columns.map(column => {
const params = column.get('params', null) === null ? null : column.get('params').toJS();
const other = params && params.other ? params.other : {};
return (
<BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading(column.get('id'))} error={this.renderError}>
{SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn {...other} />}
</BundleContainer>
);
})}
{React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))}
</div>
);
}
}
|
app/components/Login/Social.js | Jberivera/kanban-app | import React from 'react';
import style from './Login.scss';
import classNames from 'classnames/bind';
const css = classNames.bind(style);
const Social = ({ onFacebookLogin }) => {
return (
<div>
<div className={ css('fb-btn') } onClick={onFacebookLogin}>Facebook</div>
</div>
);
};
export default Social;
|
src/components/NotFoundPage.js | michaelgodshall/fullstack-challenge-frontend | import React from 'react';
import { Link } from 'react-router';
const NotFoundPage = () => {
return (
<div>
<h4>
404 Page Not Found
</h4>
<Link to="/"> Go back to homepage </Link>
</div>
);
};
export default NotFoundPage;
|
src/js/components/Servers.js | jaedb/Iris | import React from 'react';
import { Route, Switch, useParams, useHistory } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import Link from './Link';
import Icon from './Icon';
import TextField from './Fields/TextField';
import { indexToArray } from '../util/arrays';
import { Button } from './Button';
import * as mopidyActions from '../services/mopidy/actions';
import { iconFromKeyword } from '../util/helpers';
import { I18n } from '../locale';
const Server = () => {
const { id } = useParams();
if (!id) return null;
const dispatch = useDispatch();
const current_server = useSelector((state) => state.mopidy.current_server);
const server = useSelector((state) => state.mopidy.servers[id]);
if (!server) return null;
const remove = () => dispatch(mopidyActions.removeServer(id));
const setAsCurrent = () => dispatch(mopidyActions.setCurrentServer(server));
const isCurrent = id === current_server;
return (
<div className="sub-tabs__content">
<label className="field">
<div className="name">
<I18n path="settings.servers.name" />
</div>
<div className="input">
<TextField
type="text"
value={server.name}
onChange={(value) => dispatch(mopidyActions.updateServer({ id, name: value }))}
autosave
/>
</div>
</label>
<label className="field">
<div className="name">
<I18n path="settings.servers.host" />
</div>
<div className="input">
<TextField
value={server.host}
onChange={(value) => dispatch(mopidyActions.updateServer({ id, host: value }))}
autosave
/>
</div>
</label>
<label className="field">
<div className="name">
<I18n path="settings.servers.port" />
</div>
<div className="input">
<TextField
type="text"
value={server.port}
onChange={(value) => dispatch(mopidyActions.updateServer({ id, port: value }))}
autosave
/>
</div>
</label>
<div className="field checkbox">
<div className="name">
<I18n path="settings.servers.encryption.label" />
</div>
<div className="input">
<label>
<input
type="checkbox"
name="ssl"
value={server.ssl}
checked={server.ssl}
onChange={() => dispatch(mopidyActions.updateServer({ id, ssl: !server.ssl }))}
/>
<span className="label tooltip">
<I18n path="settings.servers.encryption.sublabel" />
<span className="tooltip__content">
<I18n path="settings.servers.encryption.description" />
</span>
</span>
{!server.ssl && window.location.protocol === 'https:' && (
<span className="red-text">
<I18n path="settings.servers.encryption.incompatible" />
</span>
)}
</label>
</div>
</div>
<Button
type={isCurrent ? 'default' : 'primary'}
onClick={setAsCurrent}
tracking={{
category: 'Servers',
action: 'SetAsCurrent',
label: (isCurrent ? 'Reconnect' : 'Switch'),
}}
>
<I18n path={`settings.servers.${isCurrent ? 'reconnect' : 'switch'}`} />
</Button>
<Button
type="destructive"
disabled={isCurrent}
onClick={remove}
tracking={{ category: 'Servers', action: 'Delete' }}
>
<I18n path="actions.remove" />
</Button>
</div>
);
};
const Menu = () => {
const history = useHistory();
const dispatch = useDispatch();
const servers = indexToArray(useSelector((state) => state.mopidy.servers));
const {
current_server,
connected: mopidyConnected,
connecting: mopidyConnecting,
} = useSelector((state) => state.mopidy);
const {
connected: pusherConnected,
connecting: pusherConnecting,
} = useSelector((state) => state.pusher);
const addServer = () => {
const action = mopidyActions.addServer();
dispatch(action);
history.push(`/settings/servers/${action.server.id}`);
};
return (
<div className="sub-tabs__menu" id="servers-menu">
<div className="menu__inner">
{servers.map((server) => {
let status = (
<span className="status mid_grey-text">
<I18n path="settings.servers.inactive" />
</span>
);
if (server.id === current_server) {
if (mopidyConnecting || pusherConnecting) {
status = (
<span className="status mid_grey-text">
<I18n path="settings.servers.connecting" />
</span>
);
} else if (!mopidyConnected || !pusherConnected) {
status = (
<span className="status red-text">
<I18n path="settings.servers.disconnected" />
</span>
);
} else if (mopidyConnected && pusherConnected) {
status = (
<span className="status green-text">
<I18n path="settings.servers.connected" />
</span>
);
}
}
return (
<Link
history={history}
className="menu-item"
activeClassName="menu-item--active"
to={`/settings/servers/${server.id}`}
scrollTo="#servers-menu"
key={server.id}
>
<div className="menu-item__inner">
<Icon className="menu-item__icon" name={iconFromKeyword(server.name) || 'dns'} />
<div className="menu-item__title">
{server.name}
</div>
{status}
</div>
</Link>
);
})}
<span
className="menu-item menu-item--add"
onClick={addServer}
>
<div className="menu-item__inner">
<Icon className="menu-item__icon" name="add" />
<div className="menu-item__title">
<I18n path="actions.add" />
</div>
<span className="status mid_grey-text">
<I18n path="settings.servers.new_server" />
</span>
</div>
</span>
</div>
</div>
);
};
const Servers = () => (
<div className="sub-tabs sub-tabs--servers">
<Menu />
<Switch>
<Route
exact
path="/settings/servers/:id"
component={Server}
/>
</Switch>
</div>
);
export default Servers;
|
app/components/IssueIcon/index.js | gihrig/react-boilerplate-logic | import React from 'react';
function IssueIcon(props) {
return (
<svg
height="1em"
width="0.875em"
className={props.className}
>
<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: React.PropTypes.string,
};
export default IssueIcon;
|
js/components/location_bar.js | batter/react-weather-widget | import React from 'react';
const {
Component,
} = React;
class LocationBar extends Component {
render () {
return (
<div id='location-bar'>
<h3>Weather for {this.props.location}</h3>
</div>
);
}
};
export default LocationBar;
|
src/Homepage/Login/Loginform/Loginform.js | MLsandbox/MLsandbox | import React from 'react';
import { Link } from 'react-router-dom';
import Styles from '../Login.css';
import Loader from '../Loader';
import Body from './Loginbody';
import { FormGroup, ControlLabel, FormControl, Modal, Button } from 'react-bootstrap';
var renderLoad = (authState, props) => {
if (authState) {
return (<Loader/>);
} else {
return (<Body
signIn={props.signIn} />);
}
};
var Loginform = (props) => {
return (
<div className="login_container">
<a href="#" id="close-body" data-dismiss="modal" onClick={props.onClose}
aria-label="Close" className="close-button"></a>
<div id="login">
{renderLoad(props.authProcess, props)}
<p className="login_p">Not a member?
<a id='form-body-link'href="#" onClick={props.switchForm}> Sign up now</a>
<span className="fa fa-arrow-right"></span></p>
</div>
</div>
);
};
export default Loginform;
|
client/src/Components/FacetContainer/FacetContainer.js | CrashsLanding/petfinder-searcher | import React from 'react';
import './FacetContainer.css';
import Facet from '../Facet/Facet';
import _ from 'lodash';
class FacetContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
facets: {}
};
}
toggleAndFacet(facetName, e) {
let the_state = _.clone(this.props);
if (_.includes(the_state.andFacets, facetName)) {
the_state.andFacets = _.remove(the_state.andFacets, facetName);
} else {
the_state.andFacets.push(facetName);
}
this.props.onAndFacetChange(the_state.andFacets);
}
toggleFacetEntry(facetName, facetEntryValue, e) {
let the_state = _.clone(this.props);
let selected = the_state.facets[facetName][facetEntryValue];
the_state.facets[facetName][facetEntryValue] = !selected;
let selectedFacets = _.reduce(_.map(the_state.facets, (facetEntry, facetName) => {
let selectedFacet = {};
selectedFacet[facetName] = _.compact(_.map(facetEntry, (facetEntryValue, facetEntryKey) => {
if (facetEntryValue) return facetEntryKey;
}));
return selectedFacet;
}), (result, value) => _.merge(result, value), {});
the_state.selectedFacets = selectedFacets;
this.props.onFacetChange(the_state.selectedFacets);
}
render() {
return <div className="FacetContainer col-xs-12 col-sm-3">
{_.map(_.keys(this.props.facets), (facetKey, index) => {
let toggleFunction = _.partial(this.toggleFacetEntry, facetKey);
let andFunction = _.partial(this.toggleAndFacet, facetKey);
return <Facet key={index}
name={facetKey}
values={this.props.facets[facetKey]}
andFunction={andFunction.bind(this)}
andFacets={this.props.andFacets}
andAbleFacets={this.props.andAbleFacets}
toggleFunction={toggleFunction.bind(this)}>
</Facet>;
})}
</div>
}
}
FacetContainer.propTypes = {
facets: React.PropTypes.object,
onFacetChange: React.PropTypes.func
}
export default FacetContainer;
|
src-client/scripts/truckinfo.js | Dolpator/iLuggit | import Backbone from 'backbone'
import React from 'react'
import ReactDOM from 'react-dom'
import ACTIONS from './ACTiONS.js'
import STORE from './STORE.js'
import AppController from './lugg-view-controller.js'
const showTruckInfo = React.createClass({
render: function (){
return (
<div className="container-fluid">
<nav className="navbar navbar-default">
<a className="navbar-brand " href="#"><img className ="navbar-logo" src="../images/logo1.png" alt = "" /></a>
<ul className="nav navbar-nav navbar-right">
<li><a href="#">Home</a></li>
<li><a onClick = {this._logOut}>Logout</a></li>
</ul>
</nav>
<div className ="container-fluid about-container">
<h1 className ="truck-info-lead">iLuggit, Our Story</h1>
</div>
<div className= "container-fluid builderPro">
<div className="col-xs-12 col-md-4 luggProfile">
<div className="thumbnail text-center">
<h3>Jon Gammon</h3>
<img className="profileImg1" src="http://st.motortrend.com/uploads/sites/5/2014/06/2014-Dodge-Demon-Challenger-SRT8-Dee-Snider.jpg"/>
<p>Front End Engineer, Jon, loving performance cars, has never had the ablility to move large items when he needed. He wished he had a truck to move his cars.</p>
</div>
</div>
<div className="col-xs-12 col-md-4 luggProfile ">
<div className="thumbnail text-center">
<h3>Paul Swift</h3>
<img className="profileImg2" src="http://www.imcdb.org/i151027.jpg"/>
<p>Front End Engineer Paul, has a truck, and grew tired of always having his friends ask him to help them move their items.</p>
</div>
</div>
<div className="col-xs-12 col-md-4 luggProfile">
<div className=" thumbnail text-center">
<h3>Barry Daniels</h3>
<img className="profileImg3" src="./images/WoW!.jpeg"/>
<p>Back End Engineer Barry has moved several times, but his moves have never warranted a moving service. It would have been easier with a truck.</p>
</div>
</div>
</div>
</div>
)
}
})
module.exports = showTruckInfo
|
lib/components/blockcontrol.js | pairyo/kattappa | import React from 'react';
import Action from '../utils/action';
class BlockControl extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.getToolbar = this.getToolbar.bind(this);
}
handleClick(e) {
//console.log(e);
var nodes = Array.prototype.slice.call(e.currentTarget.children);
var index = nodes.indexOf(e.target);
if(index < 0) {
return;
}
var action = nodes[index].getAttribute("data-action");
this.props.blockAction(action, this.props.position);
}
getToolbar(index) {
if(this.props.onlyRemove) {
return (
<div
className="katap-control-toolbar katap-clearfix"
onClick={this.handleClick}>
<button title="Remove" data-action={Action.REMOVE} key={Action.REMOVE}>×</button>
</div>
);
}
var buttons = [];
if(index === 0 && this.props.length < 2) {
buttons.push(<button title="Remove" data-action={Action.REMOVE} key={Action.REMOVE}>×</button>);
} else if(index === 0) {
buttons.push(<button title="Remove" data-action={Action.REMOVE} key={Action.REMOVE}>×</button>);
buttons.push(<button title="Move Down" data-action={Action.DOWN} key={Action.DOWN}>↓</button>);
} else if(index === this.props.length-1) {
buttons.push(<button title="Remove" data-action={Action.REMOVE} key={Action.REMOVE}>×</button>);
buttons.push(<button title="Move Up" data-action={Action.UP} key={Action.UP}>↑</button>);
} else {
buttons.push(<button title="Remove" data-action={Action.REMOVE} key={Action.REMOVE}>×</button>);
buttons.push(<button title="Move Up" data-action={Action.UP} key={Action.UP}>↑</button>);
buttons.push(<button title="Move Down" data-action={Action.DOWN} key={Action.DOWN}>↓</button>);
}
return (
<div
className="katap-control-toolbar"
onClick={this.handleClick}>
{buttons}
</div>
);
}
render() {
return this.getToolbar(this.props.position);
}
}
BlockControl.defaultProps = {
onlyRemove: false
};
export default BlockControl;
|
pages/react.js | lukevance/personal_site | import React from 'react'
export default class ReactComponent extends React.Component {
constructor () {
super()
this.state = { count: 0 }
}
handlePlusClick () {
this.setState({ count: this.state.count + 1 })
}
handleMinusClick () {
this.setState({ count: this.state.count - 1 })
}
render () {
return (
<div>
<h1>React.js components</h1>
<h3>Counter example</h3>
<p>{this.state.count}</p>
<button onClick={() => this.handlePlusClick()}>+</button>
<button onClick={() => this.handleMinusClick()}>-</button>
</div>
)
}
}
|
src/components/trends/smbg/FocusedSMBGPointLabel.js | tidepool-org/viz | /*
* == BSD2 LICENSE ==
* Copyright (c) 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 PropTypes from 'prop-types';
import React from 'react';
import _ from 'lodash';
import Tooltip from '../../common/tooltips/Tooltip';
import SMBGToolTip from '../../daily/smbgtooltip/SMBGTooltip';
import { MGDL_UNITS, MMOLL_UNITS } from '../../../utils/constants';
import { formatBgValue } from '../../../utils/format';
import { getOutOfRangeThreshold } from '../../../utils/bloodglucose';
import {
formatClocktimeFromMsPer24,
formatLocalizedFromUTC,
} from '../../../utils/datetime';
import styles from './FocusedSMBGPointLabel.css';
// tooltip offsets
const SIMPLE_VALUE_TOP_OFFSET = 10;
const SIMPLE_DAY_TOP_OFFSET = 10;
const SIMPLE_DAY_HORIZ_OFFSET = 30;
const DETAILED_DAY_HORIZ_OFFSET = 10;
const FocusedSMBGPointLabel = (props) => {
const { focusedPoint } = props;
if (!focusedPoint) {
return null;
}
const {
bgPrefs,
focusedPoint: { datum, position, allSmbgsOnDate, allPositions },
timePrefs,
lines,
} = props;
const lineDate = formatLocalizedFromUTC(datum.normalTime, timePrefs);
const shortDate = formatLocalizedFromUTC(datum.normalTime, timePrefs, 'MMM D');
const side = position.tooltipLeft ? 'left' : 'right';
const smbgsOnDate = allSmbgsOnDate.slice();
const positions = allPositions.slice();
if (!lines) {
const focusedPointIndex = _.findIndex(allSmbgsOnDate, (d) => (d.value === datum.value));
_.pullAt(smbgsOnDate, focusedPointIndex);
_.pullAt(positions, focusedPointIndex);
}
const pointTooltips = _.map(smbgsOnDate, (smbg, i) => (
<Tooltip
key={i}
content={
<span className={styles.number}>
{formatBgValue(smbg.value, bgPrefs, getOutOfRangeThreshold(smbg))}
</span>
}
position={positions[i]}
side={'bottom'}
tail={false}
offset={{ top: SIMPLE_VALUE_TOP_OFFSET, left: 0 }}
/>
));
let focusedTooltip;
if (lines) {
focusedTooltip = (
<Tooltip
title={<span className={styles.explainerText}>{lineDate}</span>}
position={position}
side={side}
offset={{
top: SIMPLE_DAY_TOP_OFFSET,
horizontal: SIMPLE_DAY_HORIZ_OFFSET,
}}
/>
);
} else {
focusedTooltip = (
<SMBGToolTip
title={
<span className={styles.tipWrapper}>
<span className={styles.dateTime}>
{`${shortDate}, ${formatClocktimeFromMsPer24(datum.msPer24)}`}
</span>
</span>
}
position={position}
side={side}
offset={{
top: 0,
horizontal: DETAILED_DAY_HORIZ_OFFSET,
}}
smbg={datum}
bgPrefs={bgPrefs}
timePrefs={timePrefs}
/>
);
}
return (
<div className={styles.container}>
{pointTooltips}
{focusedTooltip}
</div>
);
};
FocusedSMBGPointLabel.propTypes = {
bgPrefs: PropTypes.shape({
bgUnits: PropTypes.oneOf([MGDL_UNITS, MMOLL_UNITS]).isRequired,
// only the bgUnits required in this component
// so leaving off specification of bgBounds shape
}).isRequired,
focusedPoint: PropTypes.shape({
allPositions: PropTypes.arrayOf(PropTypes.shape({
tooltipLeft: PropTypes.bool.isRequired,
top: PropTypes.number.isRequired,
left: PropTypes.number.isRequired,
})),
allSmbgsOnDate: PropTypes.arrayOf(PropTypes.shape({
value: PropTypes.number.isRequired,
})),
date: PropTypes.string.isRequired,
datum: PropTypes.shape({
deviceTime: PropTypes.number,
msPer24: PropTypes.number.isRequired,
subType: PropTypes.string,
time: PropTypes.number,
value: PropTypes.number.isRequired,
}),
position: PropTypes.shape({
top: PropTypes.number.isRequired,
left: PropTypes.number.isRequired,
}),
}),
grouped: PropTypes.bool.isRequired,
lines: PropTypes.bool.isRequired,
timePrefs: PropTypes.shape({
timezoneAware: PropTypes.bool.isRequired,
timezoneName: PropTypes.string,
}).isRequired,
};
export default FocusedSMBGPointLabel;
|
src/pages/profile/profile.js | dejour/react-elm | import React, { Component } from 'react';
import Head from '../../components/header/head'
import FootGuide from '../../components/footer/footer'
import './profile.css'
import {imgBaseUrl} from '../../config/mUtils'
import { connect } from "react-redux";
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
class Profile extends Component {
constructor(props) {
super(props)
this.state = {
profiletitle: '我的',
getUserinfo: {}, //得到数据
username: '登录/注册', //用户名
resetname: '',
mobile: '登录后享受更多特权', //电话号码
balance: 0, //我的余额
count : 0, //优惠券个数
pointNumber : 0, //积分数
avatar: '', //头像地址
imgBaseUrl,
userInfo: null
}
}
render() {
const userInfo = this.state.userInfo
const avatar = this.state.avatar
const username = this.state.username
const mobile = this.state.mobile
const balance = this.state.balance
const count = this.state.count
const pointNumber = this.state.pointNumber
return (
<div className="profile_page">
<Head goBack='true' headTitle="我的"></Head>
<section>
<section className='profile-number'>
<Link to={userInfo? '/profile/info' : '/login'} className="profile-link">
{avatar ? <img src="imgpath" className="privateImage" /> : (
<span className="privateImage" >
<svg className="privateImage-svg">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#avatar-default"></use>
</svg>
</span>
)}
<div className="user-info">
<p>{username}</p>
<p>
<span className="user-icon">
<svg className="icon-mobile" fill="#fff">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#mobile"></use>
</svg>
</span>
<span className="icon-mobile-number">{mobile}</span>
</p>
</div>
<span className="arrow">
<svg className="arrow-svg" fill="#fff">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
</svg>
</span>
</Link>
</section>
<section className="info-data">
<ul className="clear">
<Link to="/balance" className="info-data-link">
<span className="info-data-top"><b>{parseInt(balance).toFixed(2)}</b>元</span>
<span className="info-data-bottom">我的余额</span>
</Link>
<Link to="/benefit" className="info-data-link">
<span className="info-data-top"><b>{count}</b>个</span>
<span className="info-data-bottom">我的优惠</span>
</Link>
<Link to="/points" className="info-data-link">
<span className="info-data-top"><b>{pointNumber}</b>分</span>
<span className="info-data-bottom">我的积分</span>
</Link>
</ul>
</section>
<section className="profile-1reTe">
<Link to='/order' className="myorder">
<aside>
<svg fill="#4aa5f0">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#order"></use>
</svg>
</aside>
<div className="myorder-div">
<span>我的订单</span>
<span className="myorder-divsvg">
<svg fill="#bbb">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
</svg>
</span>
</div>
</Link>
<a href='https://home.m.duiba.com.cn/#/chome/index' className="myorder">
<aside>
<svg fill="#fc7b53">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#point"></use>
</svg>
</aside>
<div className="myorder-div">
<span>积分商城</span>
<span className="myorder-divsvg">
<svg fill="#bbb">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
</svg>
</span>
</div>
</a>
<Link to='/vipcard' className="myorder">
<aside>
<svg fill="#ffc636">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#vip"></use>
</svg>
</aside>
<div className="myorder-div">
<span>饿了么会员卡</span>
<span className="myorder-divsvg">
<svg fill="#bbb">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
</svg>
</span>
</div>
</Link>
</section>
<section className="profile-1reTe">
<Link to='/service' className="myorder">
<aside>
<svg fill="#4aa5f0">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#service"></use>
</svg>
</aside>
<div className="myorder-div">
<span>服务中心</span>
<span className="myorder-divsvg">
<svg fill="#bbb">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
</svg>
</span>
</div>
</Link>
<Link to='/download' className="myorder">
<aside>
<svg fill="#3cabff">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#download"></use>
</svg>
</aside>
<div className="myorder-div" style={{borderBottom: 0}}>
<span>下载饿了么APP</span>
<span className="myorder-divsvg">
<svg fill="#bbb">
<use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#arrow-right"></use>
</svg>
</span>
</div>
</Link>
</section>
</section>
<FootGuide {...this.props}></FootGuide>
</div>
)
}
}
const mapStateToProps = state => {
const { shared } = state;
return {
geoHash: shared.geoHash,
latitude: shared.latitude,
longitude: shared.longitude
};
};
export default connect(mapStateToProps)(Profile) |
src/parser/shaman/elemental/modules/talents/ElementalBlast.js | FaideWW/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage } from 'common/format';
import Analyzer from 'parser/core/Analyzer';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import { ELEMENTAL_BLAST_IDS } from '../../constants';
class ElementalBlast extends Analyzer {
currentBuffAmount=0;
lastFreshApply=0;
resultDuration=0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.ELEMENTAL_BLAST_TALENT.id);
}
on_toPlayer_removebuff(event) {
if (ELEMENTAL_BLAST_IDS.includes(event.ability.guid)){
this.currentBuffAmount--;
if (this.currentBuffAmount===0) {
this.resultDuration += event.timestamp - this.lastFreshApply;
}
}
}
on_toPlayer_applybuff(event) {
if (ELEMENTAL_BLAST_IDS.includes(event.ability.guid)){
if (this.currentBuffAmount===0) {
this.lastFreshApply = event.timestamp;
}
this.currentBuffAmount++;
}
}
get hasteUptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.ELEMENTAL_BLAST_HASTE.id) / this.owner.fightDuration;
}
get critUptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.ELEMENTAL_BLAST_CRIT.id) / this.owner.fightDuration;
}
get masteryUptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.ELEMENTAL_BLAST_MASTERY.id) / this.owner.fightDuration;
}
get elementalBlastUptime() {
return this.resultDuration/this.owner.fightDuration;
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.ELEMENTAL_BLAST_TALENT.id} />}
value={`${formatPercentage(this.elementalBlastUptime)} %`}
label="Uptime"
tooltip={`
<b class="stat-mastery">${formatPercentage(this.masteryUptime)}% Mastery</b><br/>
<b class="stat-criticalstrike">${formatPercentage(this.critUptime)}% Crit</b><br/>
<b class="stat-haste">${formatPercentage(this.hasteUptime)}% Haste</b>`}
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL();
}
export default ElementalBlast;
|
src/collections/Message/MessageContent.js | Semantic-Org/Semantic-UI-React | import cx from 'clsx'
import PropTypes from 'prop-types'
import React from 'react'
import { childrenUtils, customPropTypes, getElementType, getUnhandledProps } from '../../lib'
/**
* A message can contain a content.
*/
function MessageContent(props) {
const { children, className, content } = props
const classes = cx('content', className)
const rest = getUnhandledProps(MessageContent, props)
const ElementType = getElementType(MessageContent, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
MessageContent.propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
export default MessageContent
|
fixtures/packaging/systemjs-builder/dev/input.js | ArunTesco/react | import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
|
src/parser/warlock/destruction/modules/azerite/RollingHavoc.js | sMteX/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import StatTracker from 'parser/shared/modules/StatTracker';
import SPELLS from 'common/SPELLS';
import { calculateAzeriteEffects } from 'common/stats';
import AzeritePowerStatistic from 'interface/statistics/AzeritePowerStatistic';
import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText';
import IntellectIcon from 'interface/icons/Intellect';
const rollingHavocStats = traits => traits.reduce((total, rank) => {
const [ intellect ] = calculateAzeriteEffects(SPELLS.ROLLING_HAVOC.id, rank);
return total + intellect;
}, 0);
const debug = false;
/*
Rolling Havoc:
Each time your spells duplicate to a Havoc target, gain X Intellect for 15 sec. This effect stacks.
*/
class RollingHavoc extends Analyzer {
static dependencies = {
statTracker: StatTracker,
};
intellect = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrait(SPELLS.ROLLING_HAVOC.id);
if (!this.active) {
return;
}
this.intellect = rollingHavocStats(this.selectedCombatant.traitsBySpellId[SPELLS.ROLLING_HAVOC.id]);
debug && this.log(`Total bonus from RH: ${this.intellect}`);
this.statTracker.add(SPELLS.ROLLING_HAVOC_BUFF.id, {
intellect: this.intellect,
});
}
get averageIntellect() {
const averageStacks = this.selectedCombatant.getStackWeightedBuffUptime(SPELLS.ROLLING_HAVOC_BUFF.id) / this.owner.fightDuration;
return (averageStacks * this.intellect).toFixed(0);
}
statistic() {
const history = this.selectedCombatant.getBuffHistory(SPELLS.ROLLING_HAVOC_BUFF.id);
const averageStacksPerCast = (history.map(buff => buff.stacks).reduce((total, current) => total + current, 0) / history.length) || 0;
return (
<AzeritePowerStatistic
size="flexible"
tooltip={`Rolling Havoc grants ${this.intellect} Intellect per stack while active. On average you had ${averageStacksPerCast.toFixed(1)} stacks per Havoc cast (${(averageStacksPerCast * this.intellect).toFixed(0)} Intellect).`}
>
<BoringSpellValueText spell={SPELLS.ROLLING_HAVOC}>
<IntellectIcon /> {this.averageIntellect} <small>average Intellect</small>
</BoringSpellValueText>
</AzeritePowerStatistic>
);
}
}
export default RollingHavoc;
|
example/src/screens/types/Drawer.js | okarakose/react-native-navigation | import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
class MyClass extends React.Component {
render() {
return (
<View style={styles.container}>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: 300,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
},
});
export default MyClass;
|
web/components/Header/index.js | earaujoassis/watchman | import React from 'react';
import './style.css';
const header = () => {
return (
<div role="header"
className="header-root"
style={{ backgroundImage: "url('/assets/971.jpg')" }}>
<h1 className="header-title">Watchman</h1>
</div>
);
};
export default header;
|
src/svg-icons/image/filter-1.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilter1 = (props) => (
<SvgIcon {...props}>
<path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm11 10h2V5h-4v2h2v8zm7-14H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"/>
</SvgIcon>
);
ImageFilter1 = pure(ImageFilter1);
ImageFilter1.displayName = 'ImageFilter1';
ImageFilter1.muiName = 'SvgIcon';
export default ImageFilter1;
|
client/src/assignment/InstructionList.js | ziel5122/autograde | import PropTypes from 'prop-types';
import React from 'react';
const InstructionList = ({
bullet,
instructions,
style,
}) => (
<div style={style}>
{
instructions.map((instruction, index) => (
<div key={index}>
{bullet}
{instruction}
</div>
))
}
</div>
);
InstructionList.defaultProps = {
bullet: ' - ',
style: {
border: '2px solid orangered',
margin: '8px',
padding: '8px',
whiteSpace: 'nowrap',
},
};
InstructionList.propTypes = {
bullet: PropTypes.string,
instructions: PropTypes.arrayOf(PropTypes.string).isRequired,
style: PropTypes.objectOf(PropTypes.string),
};
export default InstructionList;
|
main.js | sloiselle/reptile | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-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 'babel-polyfill';
import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import FastClick from 'fastclick';
import { Provider } from 'react-redux';
import store from './core/store';
import router from './core/router';
import history from './core/history';
let routes = require('./routes.json'); // Loaded with utils/routes-loader.js
const container = document.getElementById('container');
function renderComponent(component) {
ReactDOM.render(<Provider store={store}>{component}</Provider>, container);
}
// Find and render a web page matching the current URL path,
// if such page is not found then render an error page (see routes.json, core/router.js)
function render(location) {
router.resolve(routes, location)
.then(renderComponent)
.catch(error => router.resolve(routes, { ...location, error }).then(renderComponent));
}
// Handle client-side navigation by using HTML5 History API
// For more information visit https://github.com/ReactJSTraining/history/tree/master/docs#readme
history.listen(render);
render(history.getCurrentLocation());
// Eliminates the 300ms delay between a physical tap
// and the firing of a click event on mobile browsers
// https://github.com/ftlabs/fastclick
FastClick.attach(document.body);
// Enable Hot Module Replacement (HMR)
if (module.hot) {
module.hot.accept('./routes.json', () => {
routes = require('./routes.json'); // eslint-disable-line global-require
render(history.getCurrentLocation());
});
}
|
src/components/operations/operation-details.js | FranckCo/Operation-Explorer | import React from 'react';
import { Link } from 'react-router-dom';
import { sparqlConnect } from 'sparql-connect';
import NotFound from '../not-found'
import Spinner from 'components/shared/spinner'
import D, { getLang } from 'i18n'
import { seriesLink } from './routes';
import { tidyString } from 'utils/string-utils'
/**
* Builds the query that retrieves the details on a given operation.
*/
const queryBuilder = operation => `
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX dcterms: <http://purl.org/dc/terms/>
SELECT ?label ?motherSeries ?motherSeriesLabel ?altLabel ?valid ?abstract
FROM <http://rdf.insee.fr/graphes/operations>
WHERE {
<${operation}> skos:prefLabel ?label .
FILTER (lang(?label) = '${getLang()}')
?motherSeries dcterms:hasPart <${operation}> .
?motherSeries skos:prefLabel ?motherSeriesLabel .
FILTER (lang(?motherSeriesLabel) = '${getLang()}') .
OPTIONAL {<${operation}> skos:altLabel ?altLabel} .
OPTIONAL {<${operation}> dcterms:valid ?valid} .
OPTIONAL {<${operation}> dcterms:abstract ?abstract .
FILTER (lang(?abstract) = '${getLang()}')}
}
`;
const connector = sparqlConnect(queryBuilder, {
queryName: 'operationDetails',
params: ['operation'],
singleResult: true
});
function OperationDetails({ label, motherSeries, motherSeriesLabel,
altLabel, valid, abstract }) {
return (
<div>
<h1>{label}</h1>
<h2>{altLabel}</h2>
<h4>{D.motherSeries}{' : '}
<Link to={seriesLink(motherSeries)}>
{motherSeriesLabel}
</Link>
</h4>
{valid && <p className="validFor">{D.validFor} {valid}</p>}
<div className="abstract">{tidyString(abstract)}</div>
</div>
);
}
export default connector(OperationDetails, {
error: ({ operation }) => <NotFound
message={D.operationNotFound(operation)} />,
loading: () => <Spinner text={D.loadingOperation}/>
});
|
src/svg-icons/device/location-searching.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceLocationSearching = (props) => (
<SvgIcon {...props}>
<path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/>
</SvgIcon>
);
DeviceLocationSearching = pure(DeviceLocationSearching);
DeviceLocationSearching.displayName = 'DeviceLocationSearching';
export default DeviceLocationSearching;
|
src/svg-icons/notification/bluetooth-audio.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationBluetoothAudio = (props) => (
<SvgIcon {...props}>
<path d="M14.24 12.01l2.32 2.32c.28-.72.44-1.51.44-2.33 0-.82-.16-1.59-.43-2.31l-2.33 2.32zm5.29-5.3l-1.26 1.26c.63 1.21.98 2.57.98 4.02s-.36 2.82-.98 4.02l1.2 1.2c.97-1.54 1.54-3.36 1.54-5.31-.01-1.89-.55-3.67-1.48-5.19zm-3.82 1L10 2H9v7.59L4.41 5 3 6.41 8.59 12 3 17.59 4.41 19 9 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM11 5.83l1.88 1.88L11 9.59V5.83zm1.88 10.46L11 18.17v-3.76l1.88 1.88z"/>
</SvgIcon>
);
NotificationBluetoothAudio = pure(NotificationBluetoothAudio);
NotificationBluetoothAudio.displayName = 'NotificationBluetoothAudio';
NotificationBluetoothAudio.muiName = 'SvgIcon';
export default NotificationBluetoothAudio;
|
app/javascript/mastodon/components/setting_text.js | RobertRence/Mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
export default class SettingText extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
settingKey: PropTypes.array.isRequired,
label: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
};
handleChange = (e) => {
this.props.onChange(this.props.settingKey, e.target.value);
}
render () {
const { settings, settingKey, label } = this.props;
return (
<label>
<span style={{ display: 'none' }}>{label}</span>
<input
className='setting-text'
value={settings.getIn(settingKey)}
onChange={this.handleChange}
placeholder={label}
/>
</label>
);
}
}
|
src/components/mask/mask.js | n7best/react-weui | import React from 'react';
import PropTypes from 'prop-types';
import classNames from '../../utils/classnames';
/**
* screen mask, use in `Dialog`, `ActionSheet`, `Popup`.
*
*/
class Mask extends React.Component {
static propTypes = {
/**
* Whather mask should be transparent (no color)
*
*/
transparent: PropTypes.bool
};
static defaultProps = {
transparent: false
};
render() {
const {transparent, className, ...others} = this.props;
const clz = classNames({
'weui-mask': !transparent,
'weui-mask_transparent': transparent
}, className);
return (
<div className={clz} {...others}></div>
);
}
}
export default Mask;
|
client/src/templates/Challenges/components/CompletionModal.js | BhaveshSGupta/FreeCodeCamp | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import noop from 'lodash/noop';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { Button, Modal } from '@freecodecamp/react-bootstrap';
import { useStaticQuery, graphql } from 'gatsby';
import ga from '../../../analytics';
import Login from '../../../components/Header/components/Login';
import CompletionModalBody from './CompletionModalBody';
import { dasherize } from '../../../../../utils/slugs';
import './completion-modal.css';
import {
closeModal,
submitChallenge,
completedChallengesIds,
isCompletionModalOpenSelector,
successMessageSelector,
challengeFilesSelector,
challengeMetaSelector,
lastBlockChalSubmitted
} from '../redux';
import { isSignedInSelector } from '../../../redux';
const mapStateToProps = createSelector(
challengeFilesSelector,
challengeMetaSelector,
completedChallengesIds,
isCompletionModalOpenSelector,
isSignedInSelector,
successMessageSelector,
(
files,
{ title, id },
completedChallengesIds,
isOpen,
isSignedIn,
message
) => ({
files,
title,
id,
completedChallengesIds,
isOpen,
isSignedIn,
message
})
);
const mapDispatchToProps = function(dispatch) {
const dispatchers = {
close: () => dispatch(closeModal('completion')),
submitChallenge: () => {
dispatch(submitChallenge());
},
lastBlockChalSubmitted: () => {
dispatch(lastBlockChalSubmitted());
}
};
return () => dispatchers;
};
const propTypes = {
blockName: PropTypes.string,
close: PropTypes.func.isRequired,
completedChallengesIds: PropTypes.array,
currentBlockIds: PropTypes.array,
files: PropTypes.object.isRequired,
id: PropTypes.string,
isOpen: PropTypes.bool,
isSignedIn: PropTypes.bool.isRequired,
lastBlockChalSubmitted: PropTypes.func,
message: PropTypes.string,
submitChallenge: PropTypes.func.isRequired,
title: PropTypes.string
};
export function getCompletedPercent(
completedChallengesIds = [],
currentBlockIds = [],
currentChallengeId
) {
completedChallengesIds = completedChallengesIds.includes(currentChallengeId)
? completedChallengesIds
: [...completedChallengesIds, currentChallengeId];
const completedChallengesInBlock = completedChallengesIds.filter(id => {
return currentBlockIds.includes(id);
});
const completedPercent = Math.round(
(completedChallengesInBlock.length / currentBlockIds.length) * 100
);
return completedPercent > 100 ? 100 : completedPercent;
}
export class CompletionModalInner extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleKeypress = this.handleKeypress.bind(this);
}
state = {
downloadURL: null,
completedPercent: 0
};
static getDerivedStateFromProps(props, state) {
const { files, isOpen } = props;
if (!isOpen) {
return null;
}
const { downloadURL } = state;
if (downloadURL) {
URL.revokeObjectURL(downloadURL);
}
let newURL = null;
if (Object.keys(files).length) {
const filesForDownload = Object.keys(files)
.map(key => files[key])
.reduce((allFiles, { path, contents }) => {
const beforeText = `** start of ${path} **\n\n`;
const afterText = `\n\n** end of ${path} **\n\n`;
allFiles +=
files.length > 1 ? beforeText + contents + afterText : contents;
return allFiles;
}, '');
const blob = new Blob([filesForDownload], {
type: 'text/json'
});
newURL = URL.createObjectURL(blob);
}
const { completedChallengesIds, currentBlockIds, id, isSignedIn } = props;
let completedPercent = isSignedIn
? getCompletedPercent(completedChallengesIds, currentBlockIds, id)
: 0;
return { downloadURL: newURL, completedPercent: completedPercent };
}
handleKeypress(e) {
if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
// Since Hotkeys also listens to Ctrl + Enter we have to stop this event
// getting to it.
e.stopPropagation();
this.handleSubmit();
}
}
handleSubmit() {
this.props.submitChallenge();
this.checkBlockCompletion();
}
// check block completion for donation
checkBlockCompletion() {
if (
this.state.completedPercent === 100 &&
!this.props.completedChallengesIds.includes(this.props.id)
) {
this.props.lastBlockChalSubmitted();
}
}
componentWillUnmount() {
if (this.state.downloadURL) {
URL.revokeObjectURL(this.state.downloadURL);
}
this.props.close();
}
render() {
const {
blockName = '',
close,
isOpen,
message,
title,
isSignedIn
} = this.props;
const { completedPercent } = this.state;
if (isOpen) {
ga.modalview('/completion-modal');
}
const dashedName = dasherize(title);
return (
<Modal
animation={false}
bsSize='lg'
dialogClassName='challenge-success-modal'
keyboard={true}
onHide={close}
onKeyDown={isOpen ? this.handleKeypress : noop}
show={isOpen}
>
<Modal.Header
className='challenge-list-header fcc-modal'
closeButton={true}
>
<Modal.Title className='completion-message'>{message}</Modal.Title>
</Modal.Header>
<Modal.Body className='completion-modal-body'>
<CompletionModalBody
blockName={blockName}
completedPercent={completedPercent}
/>
</Modal.Body>
<Modal.Footer>
{isSignedIn ? null : (
<Login
block={true}
bsSize='lg'
bsStyle='primary'
className='btn-cta'
>
Sign in to save your progress
</Login>
)}
<Button
block={true}
bsSize='large'
bsStyle='primary'
onClick={this.handleSubmit}
>
{isSignedIn ? 'Submit and g' : 'G'}o to next challenge{' '}
<span className='hidden-xs'>(Ctrl + Enter)</span>
</Button>
{this.state.downloadURL ? (
<Button
block={true}
bsSize='lg'
bsStyle='primary'
className='btn-invert'
download={`${dashedName}.txt`}
href={this.state.downloadURL}
>
Download my solution
</Button>
) : null}
</Modal.Footer>
</Modal>
);
}
}
CompletionModalInner.propTypes = propTypes;
const useCurrentBlockIds = blockName => {
const {
allChallengeNode: { edges }
} = useStaticQuery(graphql`
query getCurrentBlockNodes {
allChallengeNode(sort: { fields: [superOrder, order, challengeOrder] }) {
edges {
node {
fields {
blockName
}
id
}
}
}
}
`);
const currentBlockIds = edges
.filter(edge => edge.node.fields.blockName === blockName)
.map(edge => edge.node.id);
return currentBlockIds;
};
const CompletionModal = props => {
const currentBlockIds = useCurrentBlockIds(props.blockName || '');
return <CompletionModalInner currentBlockIds={currentBlockIds} {...props} />;
};
CompletionModal.displayName = 'CompletionModal';
CompletionModal.propTypes = propTypes;
export default connect(
mapStateToProps,
mapDispatchToProps
)(CompletionModal);
|
src/svg-icons/content/reply-all.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentReplyAll = (props) => (
<SvgIcon {...props}>
<path d="M7 8V5l-7 7 7 7v-3l-4-4 4-4zm6 1V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z"/>
</SvgIcon>
);
ContentReplyAll = pure(ContentReplyAll);
ContentReplyAll.displayName = 'ContentReplyAll';
ContentReplyAll.muiName = 'SvgIcon';
export default ContentReplyAll;
|
src/svg-icons/image/iso.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageIso = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5.5 7.5h2v-2H9v2h2V9H9v2H7.5V9h-2V7.5zM19 19H5L19 5v14zm-2-2v-1.5h-5V17h5z"/>
</SvgIcon>
);
ImageIso = pure(ImageIso);
ImageIso.displayName = 'ImageIso';
ImageIso.muiName = 'SvgIcon';
export default ImageIso;
|
client/src/pages/portfolio/investmentForm/DatePicker_2.js | Antholimere/FyctoView | import React from 'react';
import TextField from 'material-ui/TextField';
function DatePickers(props) {
const {
input,
meta: {touched, error}
} = props
return (
<div>
<TextField
id="date"
label="Date"
type="date"
style={{ width: 200, marginTop: 16 }}
InputLabelProps={{
shrink: true,
}}
{...input}
/>
<div style={{color: 'red'}}>{touched && error && <span>{error}</span>}</div>
</div>
);
}
export default DatePickers;
|
node_modules/react-router/modules/RouteContext.js | WatkinsSoftwareDevelopment/HowardsBarberShop | import warning from './warning'
import React from 'react'
const { object } = React.PropTypes
/**
* The RouteContext mixin provides a convenient way for route
* components to set the route in context. This is needed for
* routes that render elements that want to use the Lifecycle
* mixin to prevent transitions.
*/
const RouteContext = {
propTypes: {
route: object.isRequired
},
childContextTypes: {
route: object.isRequired
},
getChildContext() {
return {
route: this.props.route
}
},
componentWillMount() {
warning(false, 'The `RouteContext` mixin is deprecated. You can provide `this.props.route` on context with your own `contextTypes`. http://tiny.cc/router-routecontextmixin')
}
}
export default RouteContext
|
app/javascript/mastodon/features/list_editor/components/edit_list_form.js | h3zjp/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { changeListEditorTitle, submitListEditor } from '../../../actions/lists';
import IconButton from '../../../components/icon_button';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
title: { id: 'lists.edit.submit', defaultMessage: 'Change title' },
});
const mapStateToProps = state => ({
value: state.getIn(['listEditor', 'title']),
disabled: !state.getIn(['listEditor', 'isChanged']) || !state.getIn(['listEditor', 'title']),
});
const mapDispatchToProps = dispatch => ({
onChange: value => dispatch(changeListEditorTitle(value)),
onSubmit: () => dispatch(submitListEditor(false)),
});
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class ListForm extends React.PureComponent {
static propTypes = {
value: PropTypes.string.isRequired,
disabled: PropTypes.bool,
intl: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
};
handleChange = e => {
this.props.onChange(e.target.value);
}
handleSubmit = e => {
e.preventDefault();
this.props.onSubmit();
}
handleClick = () => {
this.props.onSubmit();
}
render () {
const { value, disabled, intl } = this.props;
const title = intl.formatMessage(messages.title);
return (
<form className='column-inline-form' onSubmit={this.handleSubmit}>
<input
className='setting-text'
value={value}
onChange={this.handleChange}
/>
<IconButton
disabled={disabled}
icon='check'
title={title}
onClick={this.handleClick}
/>
</form>
);
}
}
|
node_modules/react-bootstrap/es/Thumbnail.js | ivanhristov92/bookingCalendar | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import SafeAnchor from './SafeAnchor';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
src: React.PropTypes.string,
alt: React.PropTypes.string,
href: React.PropTypes.string
};
var Thumbnail = function (_React$Component) {
_inherits(Thumbnail, _React$Component);
function Thumbnail() {
_classCallCheck(this, Thumbnail);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Thumbnail.prototype.render = function render() {
var _props = this.props,
src = _props.src,
alt = _props.alt,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['src', 'alt', 'className', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var Component = elementProps.href ? SafeAnchor : 'div';
var classes = getClassSet(bsProps);
return React.createElement(
Component,
_extends({}, elementProps, {
className: classNames(className, classes)
}),
React.createElement('img', { src: src, alt: alt }),
children && React.createElement(
'div',
{ className: 'caption' },
children
)
);
};
return Thumbnail;
}(React.Component);
Thumbnail.propTypes = propTypes;
export default bsClass('thumbnail', Thumbnail); |
src/components/Header.js | tehfailsafe/portfolio | import React from 'react';
import Reel from './Reel';
import particles from 'particles.js';
const Header = React.createClass({
getInitialState(){
return({
playing: false
})
},
componentDidMount(){
particlesJS.load('particles-js', 'assets/particles.json');
},
togglePlay(){
this.setState({
playing: !this.state.playing
})
},
render () {
if(this.state.playing){
var content = (
<Reel/>
)
} else {
var content = (
<div className="col-md-10" style={{paddingLeft: 64}}>
<p style={{fontWeight: 700, marginBottom: -8}}>Hello.</p>
<p style={{fontWeight: 700, marginBottom: 48}}>My Name is Mike Johnson.</p>
<p style={{fontSize: 24}}>I am an interaction designer specializing in motion, prototypes, and user testing.</p>
</div>
)
}
return (
<div className="hero">
<div id="particles-js" className="particles"></div>
<img src="assets/images/stack.png" style={{position: 'absolute', bottom: 16, right: 16, opacity: 0.5}}/>
<div className="header-content">
{content}
</div>
</div>
)
}
})
export default Header;
|
src/components/SearchBox/SearchBox.js | nbschool/ecommerce_web | import React from 'react';
import PropTypes from 'prop-types';
import SearchBar from '../SearchBar';
import DropDownList from '../DropDownList';
class SearchBox extends React.Component {
constructor(props) {
super(props);
this.state = {
isActive: false,
query: '',
};
this.updateInputState = this.updateInputState.bind(this);
this.updateQueryValue = this.updateQueryValue.bind(this);
}
/**
* Get the focus/blur status of the searchbar input
* as a boolean value.
* Used to hide the results if the search input is not
* currently focues (allowing interaction with underneath
* elements)
*/
updateInputState(inputState) {
this.setState({ isActive: inputState.active });
}
/**
* Get the search bar input value. Used to determine wether
* to show the dropdown list of results of not (useless if
* no input is present in the dropdown)
*/
updateQueryValue(value) { this.setState({ query: value }); }
get dropdown() {
if (!this.state.query) {
return null;
}
return (
<DropDownList
dropDownList={this.props.searchResults}
loaded={true} />
);
}
render() {
const { search, emptySearchResults } = this.props;
return (
<div>
<SearchBar
search={search}
emptySearchResults={emptySearchResults}
handleFocusChange={this.updateInputState}
handleInputChange={this.updateQueryValue} />
{this.state.isActive ? this.dropdown : null }
</div>
);
}
}
SearchBox.propTypes = {
search: PropTypes.func.isRequired,
searchResults: PropTypes.array.isRequired,
emptySearchResults: PropTypes.func.isRequired,
};
export default SearchBox;
|
src/svg-icons/image/adjust.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageAdjust = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.49 2 2 6.49 2 12s4.49 10 10 10 10-4.49 10-10S17.51 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm3-8c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3z"/>
</SvgIcon>
);
ImageAdjust = pure(ImageAdjust);
ImageAdjust.displayName = 'ImageAdjust';
ImageAdjust.muiName = 'SvgIcon';
export default ImageAdjust;
|
example/examples/StaticMap.js | Nabobil/react-native-maps | import React from 'react';
import {
StyleSheet,
View,
Text,
Dimensions,
ScrollView,
} from 'react-native';
import MapView from 'react-native-maps';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
class StaticMap extends React.Component {
constructor(props) {
super(props);
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
};
}
render() {
return (
<View style={styles.container}>
<ScrollView
style={StyleSheet.absoluteFill}
contentContainerStyle={styles.scrollview}
>
<Text>Clicking</Text>
<Text>and</Text>
<Text>dragging</Text>
<Text>the</Text>
<Text>map</Text>
<Text>will</Text>
<Text>cause</Text>
<Text>the</Text>
<MapView
provider={this.props.provider}
style={styles.map}
scrollEnabled={false}
zoomEnabled={false}
pitchEnabled={false}
rotateEnabled={false}
initialRegion={this.state.region}
>
<MapView.Marker
title="This is a title"
description="This is a description"
coordinate={this.state.region}
/>
</MapView>
<Text>parent</Text>
<Text>ScrollView</Text>
<Text>to</Text>
<Text>scroll.</Text>
<Text>When</Text>
<Text>using</Text>
<Text>a Google</Text>
<Text>Map</Text>
<Text>this only</Text>
<Text>works</Text>
<Text>if you</Text>
<Text>disable:</Text>
<Text>scroll,</Text>
<Text>zoom,</Text>
<Text>pitch,</Text>
<Text>rotate.</Text>
<Text>...</Text>
<Text>It</Text>
<Text>would</Text>
<Text>be</Text>
<Text>nice</Text>
<Text>to</Text>
<Text>have</Text>
<Text>an</Text>
<Text>option</Text>
<Text>that</Text>
<Text>still</Text>
<Text>allows</Text>
<Text>zooming.</Text>
</ScrollView>
</View>
);
}
}
StaticMap.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
scrollview: {
alignItems: 'center',
paddingVertical: 40,
},
map: {
width: 250,
height: 250,
},
});
module.exports = StaticMap;
|
src/containers/Home/Home.js | svsool/react-redux-universal-hot-example | import React, { Component } from 'react';
import { Link } from 'react-router';
import { CounterButton, GithubButton } from 'components';
import config from '../../config';
import Helmet from 'react-helmet';
export default class Home extends Component {
render() {
const styles = require('./Home.scss');
// require the logo image both from client and server
const logoImage = require('./logo.png');
return (
<div className={styles.home}>
<Helmet title="Home"/>
<div className={styles.masthead}>
<div className="container">
<div className={styles.logo}>
<p>
<img src={logoImage}/>
</p>
</div>
<h1>{config.app.title}</h1>
<h2>{config.app.description}</h2>
<p>
<a className={styles.github} href="https://github.com/erikras/react-redux-universal-hot-example"
target="_blank">
<i className="fa fa-github"/> View on Github
</a>
</p>
<GithubButton user="erikras"
repo="react-redux-universal-hot-example"
type="star"
width={160}
height={30}
count large/>
<GithubButton user="erikras"
repo="react-redux-universal-hot-example"
type="fork"
width={160}
height={30}
count large/>
<p className={styles.humility}>
Created and maintained by <a href="https://twitter.com/erikras" target="_blank">@erikras</a>.
</p>
</div>
</div>
<div className="container">
<div className={styles.counterContainer}>
<CounterButton multireducerKey="counter1"/>
<CounterButton multireducerKey="counter2"/>
<CounterButton multireducerKey="counter3"/>
</div>
<p>This starter boilerplate app uses the following technologies:</p>
<ul>
<li>
<del>Isomorphic</del>
{' '}
<a href="https://medium.com/@mjackson/universal-javascript-4761051b7ae9">Universal</a> rendering
</li>
<li>Both client and server make calls to load data from separate API server</li>
<li><a href="https://github.com/facebook/react" target="_blank">React</a></li>
<li><a href="https://github.com/rackt/react-router" target="_blank">React Router</a></li>
<li><a href="http://expressjs.com" target="_blank">Express</a></li>
<li><a href="http://babeljs.io" target="_blank">Babel</a> for ES6 and ES7 magic</li>
<li><a href="http://webpack.github.io" target="_blank">Webpack</a> for bundling</li>
<li><a href="http://webpack.github.io/docs/webpack-dev-middleware.html" target="_blank">Webpack Dev Middleware</a>
</li>
<li><a href="https://github.com/glenjamin/webpack-hot-middleware" target="_blank">Webpack Hot Middleware</a></li>
<li><a href="https://github.com/rackt/redux" target="_blank">Redux</a>'s futuristic <a
href="https://facebook.github.io/react/blog/2014/05/06/flux.html" target="_blank">Flux</a> implementation
</li>
<li><a href="https://github.com/gaearon/redux-devtools" target="_blank">Redux Dev Tools</a> for next
generation DX (developer experience).
Watch <a href="https://www.youtube.com/watch?v=xsSnOQynTHs" target="_blank">Dan Abramov's talk</a>.
</li>
<li><a href="https://github.com/rackt/redux-router" target="_blank">Redux Router</a> Keep
your router state in your Redux store
</li>
<li><a href="http://eslint.org" target="_blank">ESLint</a> to maintain a consistent code style</li>
<li><a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state
in Redux
</li>
<li><a href="https://github.com/erikras/multireducer" target="_blank">multireducer</a> combine several
identical reducer states into one key-based reducer</li>
<li><a href="https://github.com/webpack/style-loader" target="_blank">style-loader</a> and <a
href="https://github.com/jtangelder/sass-loader" target="_blank">sass-loader</a> to allow import of
stylesheets
</li>
<li><a href="https://github.com/shakacode/bootstrap-sass-loader" target="_blank">bootstrap-sass-loader</a> and <a
href="https://github.com/gowravshekar/font-awesome-webpack" target="_blank">font-awesome-webpack</a> to customize Bootstrap and FontAwesome
</li>
<li><a href="http://socket.io/">socket.io</a> for real-time communication</li>
</ul>
<h3>Features demonstrated in this project</h3>
<dl>
<dt>Multiple components subscribing to same redux store slice</dt>
<dd>
The <code>App.js</code> that wraps all the pages contains an <code>InfoBar</code> component
that fetches data from the server initially, but allows for the user to refresh the data from
the client. <code>About.js</code> contains a <code>MiniInfoBar</code> that displays the same
data.
</dd>
<dt>Server-side data loading</dt>
<dd>
The <Link to="/widgets">Widgets page</Link> demonstrates how to fetch data asynchronously from
some source that is needed to complete the server-side rendering. <code>Widgets.js</code>'s
<code>fetchData()</code> function is called before the widgets page is loaded, on either the server
or the client, allowing all the widget data to be loaded and ready for the page to render.
</dd>
<dt>Data loading errors</dt>
<dd>
The <Link to="/widgets">Widgets page</Link> also demonstrates how to deal with data loading
errors in Redux. The API endpoint that delivers the widget data intentionally fails 33% of
the time to highlight this. The <code>clientMiddleware</code> sends an error action which
the <code>widgets</code> reducer picks up and saves to the Redux state for presenting to the user.
</dd>
<dt>Session based login</dt>
<dd>
On the <Link to="/login">Login page</Link> you can submit a username which will be sent to the server
and stored in the session. Subsequent refreshes will show that you are still logged in.
</dd>
<dt>Redirect after state change</dt>
<dd>
After you log in, you will be redirected to a Login Success page. This <strike>magic</strike> logic
is performed in <code>componentWillReceiveProps()</code> in <code>App.js</code>, but it could
be done in any component that listens to the appropriate store slice, via Redux's <code>@connect</code>,
and pulls the router from the context.
</dd>
<dt>Auth-required views</dt>
<dd>
The aforementioned Login Success page is only visible to you if you are logged in. If you try
to <Link to="/loginSuccess">go there</Link> when you are not logged in, you will be forwarded back
to this home page. This <strike>magic</strike> logic is performed by the
<code>onEnter</code> hook within <code>routes.js</code>.
</dd>
<dt>Forms</dt>
<dd>
The <Link to="/survey">Survey page</Link> uses the
still-experimental <a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to
manage form state inside the Redux store. This includes immediate client-side validation.
</dd>
<dt>WebSockets / socket.io</dt>
<dd>
The <Link to="/chat">Chat</Link> uses the socket.io technology for real-time
communication between clients. You need to <Link to="/login">login</Link> first.
</dd>
</dl>
<h3>From the author</h3>
<p>
I cobbled this together from a wide variety of similar "starter" repositories. As I post this in June 2015,
all of these libraries are right at the bleeding edge of web development. They may fall out of fashion as
quickly as they have come into it, but I personally believe that this stack is the future of web development
and will survive for several years. I'm building my new projects like this, and I recommend that you do,
too.
</p>
<p>Thanks for taking the time to check this out.</p>
<p>– Erik Rasmussen</p>
</div>
</div>
);
}
}
|
packages/ringcentral-widgets/components/ConversationPanel/index.js | ringcentral/ringcentral-js-widget | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import dynamicsFont from '../../assets/DynamicsFont/DynamicsFont.scss';
import SpinnerOverlay from '../SpinnerOverlay';
import ConversationMessageList from '../ConversationMessageList';
import LogButton from '../LogButton';
import ContactDisplay from '../ContactDisplay';
import MessageInput from '../MessageInput';
import styles from './styles.scss';
class ConversationPanel extends Component {
constructor(props) {
super(props);
this.state = {
selected: this.getInitialContactIndex(),
isLogging: false,
inputHeight: 63,
loaded: false,
};
this._userSelection = false;
}
componentDidMount() {
if (!this.props.showSpinner) {
this.loadConversation();
}
this._mounted = true;
}
componentWillReceiveProps(nextProps) {
if (
!this._userSelection &&
this.props.conversation &&
nextProps.conversation &&
(nextProps.conversation.conversationMatches !==
this.props.conversation.conversationMatches ||
nextProps.conversation.correspondentMatches !==
this.props.conversation.correspondentMatches)
) {
this.setState({
selected: this.getInitialContactIndex(nextProps),
});
}
if (!nextProps.showSpinner && this.props.showSpinner) {
this.loadConversation();
}
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.messages !== this.props.messages) {
this.props.readMessages(this.props.conversationId);
}
if (prevState.loaded === false && this.state.loaded === true) {
if (this.props.messages.length < this.props.perPage) {
this.props.loadPreviousMessages();
}
}
}
componentWillUnmount() {
this._mounted = false;
this.props.unloadConversation();
}
onSend = () => {
this.props.replyToReceivers(this.props.messageText);
};
onInputHeightChange = (value) => {
this.setState({
inputHeight: value,
});
};
onSelectContact = (value, idx) => {
const selected = this.props.showContactDisplayPlaceholder
? parseInt(idx, 10) - 1
: parseInt(idx, 10);
this._userSelection = true;
this.setState({
selected,
});
if (this.props.autoLog) {
this.logConversation({ redirect: false, selected, prefill: false });
}
};
getMessageListHeight() {
const headerHeight = 41;
return `calc(100% - ${this.state.inputHeight + headerHeight}px)`;
}
getSelectedContact = (selected = this.state.selected) => {
if (!this.props.conversation) {
return null;
}
const contactMatches = this.props.conversation.correspondentMatches;
return (
(selected > -1 && contactMatches[selected]) ||
(contactMatches.length === 1 && contactMatches[0]) ||
null
);
};
getInitialContactIndex(nextProps = this.props) {
const {
correspondentMatches,
lastMatchedCorrespondentEntity,
conversationMatches,
} = nextProps.conversation;
let index = null;
const correspondentMatchId =
(lastMatchedCorrespondentEntity && lastMatchedCorrespondentEntity.id) ||
(conversationMatches[0] && conversationMatches[0].id);
if (correspondentMatchId) {
index = correspondentMatches.findIndex(
(contact) => contact.id === correspondentMatchId,
);
if (index > -1) return index;
}
return -1;
}
getPhoneNumber() {
const { conversation: { correspondents = [] } = {} } = this.props;
return (
(correspondents.length === 1 &&
(correspondents[0].phoneNumber || correspondents[0].extensionNumber)) ||
undefined
);
}
getGroupPhoneNumbers() {
const { conversation: { correspondents = [] } = {} } = this.props;
const groupNumbers =
correspondents.length > 1
? correspondents.map(
(correspondent) =>
correspondent.extensionNumber ||
correspondent.phoneNumber ||
undefined,
)
: null;
return groupNumbers;
}
getFallbackContactName() {
const { conversation: { correspondents = [] } = {} } = this.props;
return (correspondents.length === 1 && correspondents[0].name) || undefined;
}
loadConversation() {
this.props.loadConversation(this.props.conversationId);
this.setState({ loaded: true });
}
async logConversation({ redirect = true, selected, prefill = true } = {}) {
if (
typeof this.props.onLogConversation === 'function' &&
this._mounted &&
!this.state.isLogging
) {
this.setState({
isLogging: true,
});
await this.props.onLogConversation({
correspondentEntity: this.getSelectedContact(selected),
conversationId: this.props.conversation.conversationId,
redirect,
prefill,
});
if (this._mounted) {
this.setState({
isLogging: false,
});
}
}
}
logConversation = this.logConversation.bind(this);
render() {
if (!this.state.loaded) {
return (
<div className={styles.root}>
<SpinnerOverlay />
</div>
);
}
let conversationBody = null;
const loading = this.props.showSpinner;
const { recipients, messageSubjectRenderer } = this.props;
if (!loading) {
conversationBody = (
<ConversationMessageList
currentLocale={this.props.currentLocale}
height={this.getMessageListHeight()}
messages={this.props.messages}
className={styles.conversationBody}
dateTimeFormatter={this.props.dateTimeFormatter}
showSender={recipients && recipients.length > 1}
messageSubjectRenderer={messageSubjectRenderer}
formatPhone={this.props.formatPhone}
loadingNextPage={this.props.loadingNextPage}
loadPreviousMessages={this.props.loadPreviousMessages}
/>
);
}
const {
isLogging,
conversationMatches,
correspondentMatches,
} = this.props.conversation;
const groupNumbers = this.getGroupPhoneNumbers();
const phoneNumber = this.getPhoneNumber();
const fallbackName = this.getFallbackContactName();
const extraButton = this.props.renderExtraButton
? this.props.renderExtraButton(this.props.conversation, {
logConversation: this.logConversation,
isLogging: isLogging || this.state.isLogging,
})
: null;
const logButton =
this.props.onLogConversation && !this.props.renderExtraButton ? (
<LogButton
className={styles.logButton}
onLog={this.logConversation}
disableLinks={this.props.disableLinks}
isLogged={conversationMatches.length > 0}
isLogging={isLogging || this.state.isLogging}
currentLocale={this.props.currentLocale}
/>
) : null;
return (
<div className={styles.root}>
<div data-sign="conversationPanel" className={styles.header}>
<ContactDisplay
brand={this.props.brand}
className={styles.contactDisplay}
selectClassName={styles.contactDisplaySelect}
contactMatches={correspondentMatches || []}
selected={this.state.selected}
onSelectContact={this.onSelectContact}
disabled={this.props.disableLinks}
isLogging={isLogging || this.state.isLogging}
fallBackName={fallbackName}
areaCode={this.props.areaCode}
countryCode={this.props.countryCode}
phoneNumber={phoneNumber}
groupNumbers={groupNumbers}
showType={false}
currentLocale={this.props.currentLocale}
enableContactFallback={this.props.enableContactFallback}
showPlaceholder={this.props.showContactDisplayPlaceholder}
sourceIcons={this.props.sourceIcons}
phoneTypeRenderer={this.props.phoneTypeRenderer}
phoneSourceNameRenderer={this.props.phoneSourceNameRenderer}
showGroupNumberName={this.props.showGroupNumberName}
/>
<a
onClick={() => this.props.goBack()}
data-sign="backButton"
className={styles.backButton}
>
<span className={dynamicsFont.arrow} />
</a>
{extraButton && <div className={styles.logButton}>{extraButton}</div>}
{logButton}
</div>
{conversationBody}
<MessageInput
value={this.props.messageText}
onChange={this.props.updateMessageText}
disabled={this.props.sendButtonDisabled}
currentLocale={this.props.currentLocale}
onSend={this.onSend}
onHeightChange={this.onInputHeightChange}
inputExpandable={this.props.inputExpandable}
/>
</div>
);
}
}
ConversationPanel.propTypes = {
brand: PropTypes.string.isRequired,
replyToReceivers: PropTypes.func.isRequired,
messages: ConversationMessageList.propTypes.messages,
updateMessageText: PropTypes.func,
messageText: PropTypes.string,
recipients: PropTypes.arrayOf(
PropTypes.shape({
phoneNumber: PropTypes.string,
extensionNumber: PropTypes.string,
name: PropTypes.string,
}),
).isRequired,
sendButtonDisabled: PropTypes.bool.isRequired,
currentLocale: PropTypes.string.isRequired,
showSpinner: PropTypes.bool.isRequired,
disableLinks: PropTypes.bool,
conversation: PropTypes.object.isRequired,
onLogConversation: PropTypes.func,
areaCode: PropTypes.string.isRequired,
countryCode: PropTypes.string.isRequired,
autoLog: PropTypes.bool,
enableContactFallback: PropTypes.bool,
dateTimeFormatter: PropTypes.func.isRequired,
goBack: PropTypes.func.isRequired,
showContactDisplayPlaceholder: PropTypes.bool,
sourceIcons: PropTypes.object,
phoneTypeRenderer: PropTypes.func,
phoneSourceNameRenderer: PropTypes.func,
showGroupNumberName: PropTypes.bool,
messageSubjectRenderer: PropTypes.func,
formatPhone: PropTypes.func.isRequired,
readMessages: PropTypes.func.isRequired,
loadPreviousMessages: PropTypes.func.isRequired,
unloadConversation: PropTypes.func.isRequired,
perPage: PropTypes.number,
conversationId: PropTypes.string.isRequired,
loadConversation: PropTypes.func,
renderExtraButton: PropTypes.func,
loadingNextPage: PropTypes.bool,
inputExpandable: PropTypes.bool,
};
ConversationPanel.defaultProps = {
disableLinks: false,
onLogConversation: undefined,
autoLog: false,
enableContactFallback: undefined,
showContactDisplayPlaceholder: true,
sourceIcons: undefined,
phoneTypeRenderer: undefined,
phoneSourceNameRenderer: undefined,
showGroupNumberName: false,
messageText: '',
updateMessageText: () => null,
messageSubjectRenderer: undefined,
perPage: undefined,
loadConversation: () => null,
renderExtraButton: undefined,
loadingNextPage: false,
inputExpandable: undefined,
};
export default ConversationPanel;
|
server/sonar-web/src/main/js/apps/component-measures/components/IconHistory.js | lbndev/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
export default function IconHistory() {
/* eslint max-len: 0 */
return (
<svg
className="measure-tab-icon"
viewBox="0 0 512 448"
fillRule="evenodd"
clipRule="evenodd"
strokeLinejoin="round"
strokeMiterlimit="1.414">
<path
d="M512 384v32H0V32h32v352h480zM480 72v108.75q0 5.25-4.875 7.375t-8.875-1.875L436 156 277.75 314.25q-2.5 2.5-5.75 2.5t-5.75-2.5L208 256 104 360l-48-48 146.25-146.25q2.5-2.5 5.75-2.5t5.75 2.5L272 224l116-116-30.25-30.25q-4-4-1.875-8.875T363.25 64H472q3.5 0 5.75 2.25T480 72z"
/>
</svg>
);
}
|
webapp/docs/components/Topbar/style.js | oorococo/smcoco_com | import React from 'react'
const rule = `
.topbar {
position: absolute;
width: 100%;
left: 0;
top: 0;
z-index: 9999;
background-color: rgba(0,0,0,.15);
border-bottom: 1px solid rgba(0,0,0,.2);
}
.topbar-link {
color: #fff;
display: inline-block;
padding: 3px 10px;
text-decoration: none;
}
.topbar-link.active {
color: #ff1493;
border-bottom: 2px solid #ff1493;
}
@media screen and (max-width: 550px) {
.topbar {
background-color: rgba(0,0,0,.7);
border-bottom: 1px solid rgba(0,0,0,.8);
}
}
`
export default () => <style dangerouslySetInnerHTML={{__html: rule}}/>
|
src/svg-icons/action/invert-colors.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionInvertColors = (props) => (
<SvgIcon {...props}>
<path d="M17.66 7.93L12 2.27 6.34 7.93c-3.12 3.12-3.12 8.19 0 11.31C7.9 20.8 9.95 21.58 12 21.58c2.05 0 4.1-.78 5.66-2.34 3.12-3.12 3.12-8.19 0-11.31zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59s.62-3.11 1.76-4.24L12 5.1v14.49z"/>
</SvgIcon>
);
ActionInvertColors = pure(ActionInvertColors);
ActionInvertColors.displayName = 'ActionInvertColors';
ActionInvertColors.muiName = 'SvgIcon';
export default ActionInvertColors;
|
app/javascript/mastodon/features/home_timeline/components/column_settings.js | Nyoho/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { injectIntl, FormattedMessage } from 'react-intl';
import SettingToggle from '../../notifications/components/setting_toggle';
export default @injectIntl
class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
render () {
const { settings, onChange } = this.props;
return (
<div>
<span className='column-settings__section'><FormattedMessage id='home.column_settings.basic' defaultMessage='Basic' /></span>
<div className='column-settings__row'>
<SettingToggle prefix='home_timeline' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={<FormattedMessage id='home.column_settings.show_reblogs' defaultMessage='Show boosts' />} />
</div>
<div className='column-settings__row'>
<SettingToggle prefix='home_timeline' settings={settings} settingPath={['shows', 'reply']} onChange={onChange} label={<FormattedMessage id='home.column_settings.show_replies' defaultMessage='Show replies' />} />
</div>
</div>
);
}
}
|
app/components/ForecastDay.js | paul-uu/weather | import React from 'react';
const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
months = ['January','February','March','April','May','June','July','August','Spetember','October','November', 'December'];
const dateStyle = {
float: 'left'
};
export default class ForecastDay extends React.Component {
currentDayClick(day) {
this.props.toggleDetailDay(day);
}
render() {
let self = this,
weather = self.props.weather,
d = new Date(weather.date),
day = days[d.getUTCDay()],
date = months[d.getUTCMonth()] + ' ' + d.getUTCDate(),
isSelected = self.props.selected ? 'weather_main selected' : 'weather_main';
return (
<div className='weather_item' onClick={self.currentDayClick.bind( self, weather.date )}>
<div className={isSelected}>
<div className='weather_date' >
<span className='date'>{date}</span><br />
<span className='day'>{day}</span>
</div>
<div className='weather_basic'>
<div className='weather_condition'>{weather.day.condition.text}</div>
<div className='weather_temp_max'>{Math.round(weather.day.maxtemp_f)}</div>
<div className='weather_temp_min'>{Math.round(weather.day.mintemp_f)}</div>
</div>
</div>
</div>
)
}
}
|
docs/src/pages/premium-themes/onepirate/modules/components/Typography.js | lgollut/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import { capitalize } from '@material-ui/core/utils';
import MuiTypography from '@material-ui/core/Typography';
const styles = (theme) => ({
markedH2Center: {
height: 4,
width: 73,
display: 'block',
margin: `${theme.spacing(1)}px auto 0`,
backgroundColor: theme.palette.secondary.main,
},
markedH3Center: {
height: 4,
width: 55,
display: 'block',
margin: `${theme.spacing(1)}px auto 0`,
backgroundColor: theme.palette.secondary.main,
},
markedH4Center: {
height: 4,
width: 55,
display: 'block',
margin: `${theme.spacing(1)}px auto 0`,
backgroundColor: theme.palette.secondary.main,
},
markedH6Left: {
height: 2,
width: 28,
display: 'block',
marginTop: theme.spacing(0.5),
background: 'currentColor',
},
});
const variantMapping = {
h1: 'h1',
h2: 'h1',
h3: 'h1',
h4: 'h1',
h5: 'h3',
h6: 'h2',
subtitle1: 'h3',
};
function Typography(props) {
const { children, classes, marked = false, variant, ...other } = props;
return (
<MuiTypography variantMapping={variantMapping} variant={variant} {...other}>
{children}
{marked ? (
<span className={classes[`marked${capitalize(variant) + capitalize(marked)}`]} />
) : null}
</MuiTypography>
);
}
Typography.propTypes = {
children: PropTypes.node,
classes: PropTypes.object.isRequired,
marked: PropTypes.oneOf([false, 'center', 'left']),
variant: PropTypes.string,
};
export default withStyles(styles)(Typography);
|
app/components/Header.js | alexeyraspopov/evo | import React from 'react';
import ActionButton from 'components/ActionButton';
export default function Header() {
return (
<header className="header">
<ActionButton type="menu" />
<h2 className="header-title">Users</h2>
<ActionButton type="search" />
<ActionButton type="more_vert" />
</header>
);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.