path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/interface/icons/DiscordTiny.js | fyruna/WoWAnalyzer | import React from 'react';
// From the Discord branding website. Should only use this rarely.
const Icon = ({ ...other }) => (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="35 20 175 200" className="icon" {...other}>
<path d="M104.4 103.9c-5.7 0-10.2 5-10.2 11.1s4.6 11.1 10.2 11.1c5.7 0 10.2-5 10.2-11.1.1-6.1-4.5-11.1-10.2-11.1zM140.9 103.9c-5.7 0-10.2 5-10.2 11.1s4.6 11.1 10.2 11.1c5.7 0 10.2-5 10.2-11.1s-4.5-11.1-10.2-11.1z" />
<path d="M189.5 20h-134C44.2 20 35 29.2 35 40.6v135.2c0 11.4 9.2 20.6 20.5 20.6h113.4l-5.3-18.5 12.8 11.9 12.1 11.2 21.5 19V40.6c0-11.4-9.2-20.6-20.5-20.6zm-38.6 130.6s-3.6-4.3-6.6-8.1c13.1-3.7 18.1-11.9 18.1-11.9-4.1 2.7-8 4.6-11.5 5.9-5 2.1-9.8 3.5-14.5 4.3-9.6 1.8-18.4 1.3-25.9-.1-5.7-1.1-10.6-2.7-14.7-4.3-2.3-.9-4.8-2-7.3-3.4-.3-.2-.6-.3-.9-.5-.2-.1-.3-.2-.4-.3-1.8-1-2.8-1.7-2.8-1.7s4.8 8 17.5 11.8c-3 3.8-6.7 8.3-6.7 8.3-22.1-.7-30.5-15.2-30.5-15.2 0-32.2 14.4-58.3 14.4-58.3 14.4-10.8 28.1-10.5 28.1-10.5l1 1.2c-18 5.2-26.3 13.1-26.3 13.1s2.2-1.2 5.9-2.9c10.7-4.7 19.2-6 22.7-6.3.6-.1 1.1-.2 1.7-.2 6.1-.8 13-1 20.2-.2 9.5 1.1 19.7 3.9 30.1 9.6 0 0-7.9-7.5-24.9-12.7l1.4-1.6s13.7-.3 28.1 10.5c0 0 14.4 26.1 14.4 58.3 0 0-8.5 14.5-30.6 15.2z" />
</svg>
);
export default Icon;
|
ui/src/js/main/ProjectTeaser.js | Dica-Developer/weplantaforest | import React, { Component } from 'react';
import { browserHistory } from 'react-router';
import PolygonMap from '../common/components/PolygonMap';
import { getFirstParagraph, getTextForSelectedLanguage } from '../common/language/LanguageHelper';
export default class ProjectTeaser extends Component {
constructor(props) {
super(props);
}
linkTo(url) {
browserHistory.push(url);
}
render() {
return (
<div>
<a
role="button"
onClick={() => {
this.linkTo('/projects/' + this.props.content.name);
}}
>
<PolygonMap positions={this.props.content.positions} />
<h1>{this.props.content.name}</h1>
<div className="description">
<p
dangerouslySetInnerHTML={{
__html: getFirstParagraph(getTextForSelectedLanguage(this.props.content.description))
}}
/>
</div>
</a>
</div>
);
}
}
ProjectTeaser.defaultProps = {
content: {
latitude: 0,
longitude: 0,
projectName: '',
description: ''
}
};
/* vim: set softtabstop=2:shiftwidth=2:expandtab */
|
html-test/n-dialog/test.js | bradwoo8621/parrot2 | import $ from 'jquery'
import React from 'react'
import ReactDOM from 'react-dom'
import {Model} from '../../src/js/model/model'
import {Layout} from '../../src/js/layout/layout'
import {Envs} from '../../src/js/envs'
import {NDialog, NDialogUtil} from '../../src/js/components/n-dialog'
import {NText} from '../../src/js/components/n-text'
import {NButton} from '../../src/js/components/n-button'
$(function() {
let model = new Model({
name: 'test'
});
model.addPostChangeListener('name', function(evt) {
// console.log(this);
// console.log(evt);
console.log(evt)
});
let layout = new Layout('name', {
comp: {
content: {
label: 'A Dialog',
comp: {
children: {
name: {
pos: {width: 3, row: 10}
},
button: {
label: 'Close',
comp: {
type: Envs.COMPONENT_TYPES.BUTTON
},
evt: {
click: function() {
dialog.hide();
}
},
pos: {width: 3, row: 20}
}
}
}
}
}
});
let dialog = NDialogUtil.createDialog({
model: model,
layout: layout
});
let panel = (<div className='n-top-container'>
<div className='n-row n-in-form'>
<div className='n-col-sm-3 n-col-md-3'>
<NButton model={model}
n-id='test'
n-label='Standard'
n-evt-click={()=>{dialog.show()}} />
</div>
</div>
</div>);
ReactDOM.render(panel, document.getElementById('main'));
});
|
test/integration/css-fixtures/custom-configuration-legacy/pages/_app.js | flybayer/next.js | import React from 'react'
import App from 'next/app'
import '../styles/global.css'
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
|
static/src/Results.js | sheki/parsesearch | import React, { Component } from 'react';
export default class Results extends Component {
constructor(props) {
super(props);
}
render() {
const {results} = this.props;
return (
<div>
{results.length} results
<ul>
{results.map(result =>
<li key={result.id}>- {JSON.stringify(result.toJSON())}</li>
)}
</ul>
</div>
);
}
}
|
src/views/QuotesList.js | abachuk/quotes | import React from 'react'
import 'styles/core.scss'
import { actions as quoteActions } from '../redux/modules/getquotes'
import { connect } from 'react-redux'
import _ from 'lodash'
import styles from '../styles/QuotesListStyles.scss'
import QuoteTile from '../components/quote-tile'
const mapStateToProps = (state) => ({
quotes: state.quotes
})
export class QuotesList extends React.Component {
static propTypes = {
quotes: React.PropTypes.object,
fetch: React.PropTypes.func,
getQuotes: React.PropTypes.func
}
componentDidMount () {
this.props.getQuotes()
}
filterList (e) {
console.log(this)
console.log(e.target.value)
}
render () {
let categories = _.countBy(this.props.quotes, 'category')
console.log(categories)
return (
<div className={styles['quotes-container']}>
<select className='categories' onChange={this.filterList.bind(this)}>
<option>All</option>
{_.map(categories, function (val, key) {
return <option value={key} key={key}>{key} ({val})</option>
})}
</select>
<ul className={styles['quotes-list']}>
{_.map(this.props.quotes, function (val, key) {
return <QuoteTile quote={val} key={key} id={key} />
})}
</ul>
</div>
)
}
}
export default connect(mapStateToProps, quoteActions)(QuotesList)
|
app/javascript/mastodon/features/home_timeline/components/column_settings.js | salvadorpla/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>
);
}
}
|
examples/huge-apps/routes/Grades/components/Grades.js | fiture/react-router | import React from 'react';
class Grades extends React.Component {
render () {
return (
<div>
<h2>Grades</h2>
</div>
);
}
}
export default Grades;
|
docs/app/Examples/elements/Input/index.js | mohammed88/Semantic-UI-React | import React from 'react'
import Types from './Types'
import States from './States'
import Variations from './Variations'
const InputExamples = () => (
<div>
<Types />
<States />
<Variations />
</div>
)
export default InputExamples
|
docs/app/Examples/elements/Icon/Groups/IconExampleLoadingGroup.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Icon } from 'semantic-ui-react'
const IconExampleLoadingGroup = () => (
<div>
<Icon.Group size='huge'>
<Icon size='big' color='red' name='dont' />
<Icon color='black' name='user' />
</Icon.Group>
<Icon.Group size='huge'>
<Icon loading size='big' name='sun' />
<Icon name='user' />
</Icon.Group>
</div>
)
export default IconExampleLoadingGroup
|
client/src/admin/Home.js | ziel5122/autograde | import Paper from 'material-ui/Paper';
import React from 'react';
import HomeBody from './HomeBody';
import HomeTabs from './HomeTabs';
const paperStyle = {
display: 'flex',
flexDirection: 'column',
height: '100%',
width: '100%',
};
const style = {
flex: 1,
maxWidth: '1000px',
width: '100%',
};
const Home = () => (
<div style={style}>
<Paper style={paperStyle} zDepth={5}>
<HomeTabs />
<HomeBody />
</Paper>
</div>
);
export default Home;
|
examples/todos-with-undo/containers/UndoRedo.js | splendido/redux | import React from 'react'
import { ActionCreators as UndoActionCreators } from 'redux-undo'
import { connect } from 'react-redux'
let UndoRedo = ({ canUndo, canRedo, onUndo, onRedo }) => (
<p>
<button onClick={onUndo} disabled={!canUndo}>
Undo
</button>
<button onClick={onRedo} disabled={!canRedo}>
Redo
</button>
</p>
)
const mapStateToProps = (state) => {
return {
canUndo: state.todos.past.length > 0,
canRedo: state.todos.future.length > 0
}
}
const mapDispatchToProps = (dispatch) => {
return {
onUndo: () => dispatch(UndoActionCreators.undo()),
onRedo: () => dispatch(UndoActionCreators.redo())
}
}
UndoRedo = connect(
mapStateToProps,
mapDispatchToProps
)(UndoRedo)
export default UndoRedo
|
src/layouts/index.js | yen223/yens-blog | import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import Helmet from 'react-helmet'
const Header = () =>
<div style={{textAlign: "center", padding: 50}}>
<h1>Wei Yen</h1>
<span> <Link to="/">home</Link> </span> ·
<span> <a href="https://github.com/yen223">github</a></span> ·
<span> <a href="https://www.linkedin.com/in/weiyen/">linkedin</a></span>
</div>
const TemplateWrapper = ({ children }) =>
<div style={{
maxWidth: 840,
padding: '0px 1.0875rem 1.45rem',
paddingTop: 0,
marginRight: "auto",
marginLeft: "auto",
}}>
<Helmet
title="Wei Yen's Personal Site"
meta={[
{ name: 'description', content: 'Wei Yen personal site' },
{ name: 'keywords', content: 'Wei Yen, blog, personal, articles, software' },
]}
/>
<Header />
<div>
{children()}
</div>
</div>
TemplateWrapper.propTypes = {
children: PropTypes.func,
}
export default TemplateWrapper
|
src/svg-icons/av/replay.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvReplay = (props) => (
<SvgIcon {...props}>
<path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/>
</SvgIcon>
);
AvReplay = pure(AvReplay);
AvReplay.displayName = 'AvReplay';
AvReplay.muiName = 'SvgIcon';
export default AvReplay;
|
app/js/containers/splashAnimation.js | ue/electra | import React from 'react';
const styles = {
height: 650
}
class SplashAnimation extends React.Component {
constructor (props) {
super(props);
}
componentWillMount() {
if(!localStorage.getItem('darkTheme')){
localStorage.setItem('darkTheme', false);
}
}
render() {
return (
<div style={styles} className="animation">
<div className="rotate"></div>
<div className="rotate rotating"></div>
<div className="rotate rotating-left"></div>
<div className="splash-banner">
electra
</div>
</div>
);
}
}
export default SplashAnimation; |
src/example/WithHoverPropsExample.js | klarna/higher-order-components | import React from 'react'
import { withHoverProps } from '../'
export default withHoverProps({ hovered: true })(function Focusable({ hovered, ...props }) {
return (
<article {...props}>
<h1>withHoverProps</h1>
<code>
<pre
style={{
color: 'lightgreen',
backgroundColor: 'black',
padding: 10,
overflowX: 'scroll',
}}
>{`import React from 'react'
import { withHoverProps } from '@klarna/higher-order-components'
export default withHoverProps({ hovered: true })(function Focusable({ hovered, ...props }) {
return (
<article {...props}>
<h1>withHoverProps</h1>
{hovered ? 'hovered!' : 'hover the example to see it change'}
</article>
)
})`}</pre>
</code>
{hovered ? 'hovered!' : 'hover the example to see it change'}
</article>
)
})
|
fields/types/boolean/BooleanColumn.js | tony2cssc/keystone | import React from 'react';
import Checkbox from '../../components/Checkbox';
import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue';
var BooleanColumn = React.createClass({
displayName: 'BooleanColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
return (
<ItemsTableValue truncate={false} field={this.props.col.type}>
<Checkbox readonly checked={this.props.data.fields[this.props.col.path]} />
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
},
});
module.exports = BooleanColumn;
|
examples/src/components/CustomKeysField.js | SenecaSystems/react-select | import React from 'react';
import Select from 'react-select';
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
var CustomKeysField = React.createClass({
displayName: 'CustomKeysField',
propTypes: {
label: React.PropTypes.string
},
getInitialState () {
return {
options: [
{ id: '1', name: 'One' },
{ id: '2', name: 'Two' },
{ id: '3', name: 'Three' },
{ id: '4', name: 'Four' }
],
value: null,
multi: false
};
},
onChange(value, values) {
this.setState({
value: value
});
logChange(value, values);
},
onChangeMulti(event) {
this.setState({
multi: event.target.checked
});
},
render () {
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select
searchable
labelKey="name"
valueKey="id"
options={this.state.options}
onChange={this.onChange}
value={this.state.value}
multi={this.state.multi}
/>
<div className="checkbox-list">
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.multi} onChange={this.onChangeMulti} />
<span className="checkbox-label">Multi-Select</span>
</label>
</div>
</div>
);
}
});
module.exports = CustomKeysField;
|
src/svg-icons/action/assignment-late.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAssignmentLate = (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-6 15h-2v-2h2v2zm0-4h-2V8h2v6zm-1-9c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/>
</SvgIcon>
);
ActionAssignmentLate = pure(ActionAssignmentLate);
ActionAssignmentLate.displayName = 'ActionAssignmentLate';
ActionAssignmentLate.muiName = 'SvgIcon';
export default ActionAssignmentLate;
|
app/components/groups/groups.js | dfmcphee/pinnr | import React from 'react';
import { Link } from 'react-router';
import { Card } from 'semantic-ui-react';
import GroupStore from '../../stores/group-store';
export default class Groups extends React.Component {
constructor(props) {
super(props);
this.state = {
groups: GroupStore.getGroups(),
loading: true
};
}
componentWillMount() {
GroupStore.init()
}
componentDidMount() {
GroupStore.addChangeListener(() => this.updateGroups())
}
componentWillUnmount() {
GroupStore.removeChangeListener(() => this.updateGroups())
}
updateGroups() {
this.setState({
groups: GroupStore.getGroups(),
loading: false
})
}
render() {
return (
<div className="groups">
<Card.Group>
{this.state.groups.map(group => (
<Card key={group.id}>
<Card.Content>
<Card.Header><Link to={`/group/${group.id}`}>{group.title}</Link></Card.Header>
<Card.Meta>#{group.hashtag}</Card.Meta>
</Card.Content>
</Card>
))}
</Card.Group>
</div>
);
}
}
|
packages/kickoff-scripts/fixtures/kitchensink/src/features/syntax/ArrayDestructuring.js | TryKickoff/create-kickoff-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load() {
return [[1, '1'], [2, '2'], [3, '3'], [4, '4']];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-array-destructuring">
{this.state.users.map(user => {
const [id, name] = user;
return <div key={id}>{name}</div>;
})}
</div>
);
}
}
|
admin/client/App/screens/Item/components/FormHeading.js | naustudio/keystone | import React from 'react';
import evalDependsOn from '../../../../../../fields/utils/evalDependsOn';
module.exports = React.createClass({
displayName: 'FormHeading',
propTypes: {
options: React.PropTypes.object,
},
render () {
if (!evalDependsOn(this.props.options.dependsOn, this.props.options.values)) {
return null;
}
return <h3 className="form-heading">{this.props.content}</h3>;
},
});
|
client/reactapp/components/App.js | TribeMedia/loopback-example-react | import React from 'react';
import { RouteHandler } from 'react-router';
export default class App extends React.Component {
static contextTypes = {
router: React.PropTypes.func
}
constructor ( props, context ) {
super( props, context );
this.props = props;
this.state = { };
this.context = context;
}
componentWillReceiveProps ( nextProps ) { }
componentReceiveProps ( ) { }
render ( ) {
return (
<div>
<RouteHandler {...this.props} />
</div>
);
}
} |
packages/material-ui-icons/src/Subtitles.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Subtitles = props =>
<SvgIcon {...props}>
<path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM4 12h4v2H4v-2zm10 6H4v-2h10v2zm6 0h-4v-2h4v2zm0-4H10v-2h10v2z" />
</SvgIcon>;
Subtitles = pure(Subtitles);
Subtitles.muiName = 'SvgIcon';
export default Subtitles;
|
lib/CurrentWeather.js | danalvarez5280/Weatherly | import React from 'react';
import WeatherColors from './WeatherColors';
export default function CurrentWeather (props){
const propsIcon = props.icon;
const image = `./assets/${propsIcon}.svg`;
const backgroundColor = WeatherColors[props.condition].style;
return (
<div className="current-weather" style={ backgroundColor }>
<p className="current-info">{ props.location }</p>
<p className="current-info">{ props.date }</p>
<p className="current-info"> <img className="main-icon" src= { image } /></p>
<p className="current-info">{ props.temp } °F</p>
<p className="current-info">{ props.condition }</p>
<hr />
<section className="high-low">
<section className="high">
<p className="current-info">High: { props.high } °F</p>
</section>
<section className="high">
<p className="current-info">Low: { props.low } °F</p>
</section>
</section>
</div>
);
}
|
src/packages/@ncigdc/utils/download/index.js | NCI-GDC/portal-ui | // @flow
import React from 'react';
import _ from 'lodash';
import Cookies from 'js-cookie';
import { setModal } from '@ncigdc/dux/modal';
import { Row, Column } from '@ncigdc/uikit/Flex';
import Button from '@ncigdc/uikit/Button';
import { notify, closeNotification } from '@ncigdc/dux/notification';
const getBody = iframe => {
const document = iframe.contentWindow || iframe.contentDocument;
return (document.document || document).body;
};
// const cookiePath = document.querySelector('base').getAttribute('href')
const cookiePath = '/';
const getIframeResponse = iFrame =>
JSON.parse(getBody(iFrame).querySelector('pre').innerText);
const showErrorModal = error => {
const warning = error.warning || error.message;
window.store.dispatch(
setModal(
<Column
style={{
padding: '15px',
}}
>
{warning}
<Row style={{ paddingTop: '0.5rem', justifyContent: 'flex-end' }}>
<Button onClick={() => window.store.dispatch(setModal(null))}>
OK
</Button>
</Row>
</Column>,
),
);
};
// notification config
const progressChecker = (
iFrame,
cookieKey: string,
downloadToken: string,
altMessage: boolean,
inProgress: Function,
done: Function,
) => {
inProgress();
const waitTime = 1000;
let attempts = 0;
let timeoutPromise = null;
const cookieStillThere = () => downloadToken === Cookies.get(cookieKey); // TODO: not $
const handleError = () => {
const error = _.flow(
_.attempt,
e =>
_.isError(e)
? {
message: 'GDC download service is currently experiencing issues.',
}
: e,
)(_.partial(getIframeResponse, iFrame));
return error;
};
const finished = () => {
//console.info('Download check count & wait interval (in milliseconds):', attempts, waitTime);
timeoutPromise = null;
window.store.dispatch(closeNotification());
iFrame.parentNode.removeChild(iFrame);
done();
};
const cancelDownload = () => {
if (timeoutPromise) {
clearTimeout(timeoutPromise);
timeoutPromise = null;
}
finished();
};
const simpleMessage = (
<div>
<div>Download preparation in progress. Please wait…</div>
<a onClick={cancelDownload}>
<i className="fa fa-times-circle-o" /> Cancel Download
</a>
</div>
);
const detailedMessage = (
<div>
<div>
The download preparation can take time due to different factors (total
file size, number of files, or number of concurrent users).
</div>
<div>
We recommend that you use the{' '}
<a
href="https://gdc.cancer.gov/access-data/gdc-data-transfer-tool"
target="_blank"
rel="noopener noreferrer"
>
{' '}
GDC Data Transfer Tool
</a>{' '}
or cancel the download and try again later.
</div>
<a
onClick={cancelDownload}
style={{
textDecoration: 'underline',
}}
>
<strong>
<i className="fa fa-times-circle-o" /> Cancel Download
</strong>
</a>
</div>
);
const checker = () => {
attempts++;
if (iFrame.__frame__loaded) {
// The downloadToken cookie is removed before the server sends the response
if (cookieStillThere()) {
const error = handleError();
Cookies.remove(cookieKey);
finished();
showErrorModal(error);
} else {
// A download should be now initiated.
finished();
}
} else if (cookieStillThere()) {
if (altMessage) {
if (attempts === 5 || attempts === 2) {
window.store.dispatch(
notify({
action: 'add',
id: `download/${attempts}`,
component: simpleMessage,
delay: 1000,
}),
);
} else if (attempts === 6) {
window.store.dispatch(
notify({
action: 'add',
id: `download/${attempts}`,
component: detailedMessage,
delay: 0,
}),
);
}
} else {
window.store.dispatch(
notify({
action: 'add',
id: `download/${attempts}`,
component: simpleMessage,
delay: 0,
}),
);
}
timeoutPromise = setTimeout(checker, waitTime);
} else {
// In case the download is initiated without triggering the iFrame to reload
finished();
}
};
timeoutPromise = setTimeout(checker, waitTime);
};
const cookielessChecker = (iFrame, inProgress, done) => {
// let attempts = 30;
// const finished = () => {
// iFrame.parentNode.removeChild(iFrame);
// done();
// };
// const checker = () => {
// // Here we simply try to read the error message if the iFrame DOM is
// // reloaded; for a successful download, the error message is not in the DOM
// // therefore #getIframeResponse will return a JS error.
// const error = _.attempt(_.partial(getIframeResponse, iFrame));
// if (_.isError(error)) {
// // Keep waiting until we exhaust `attempts` then we do the cleanup.
// if (--attempts < 0) {
// finished();
// } else {
// // setTimeout(checker, waitTime)
// }
// } else {
// finished();
// showErrorModal(error);
// }
// };
// setTimeout(checker, waitTime);
};
const hashString = s =>
s.split('').reduce((acc, c) => (acc << 5) - acc + c.charCodeAt(0), 0);
const toHtml = (key, value) =>
`<input
type="hidden"
name="${key}"
value="${_.isPlainObject(value)
? JSON.stringify(value).replace(/"/g, '"')
: value}"
/>`;
const arrayToStringFields = ['expand', 'fields', 'facets'];
const arrayToStringOnFields = (key, value, fields) =>
_.includes(fields, key) ? [].concat(value).join() : value;
type TDownloadCallbacks = (inProgress: Function, done: Function) => {};
const download = ({
url,
params,
method = 'GET',
altMessage = false,
}: {
url: string,
params: any,
method: string,
altMessage?: boolean,
}): TDownloadCallbacks => {
const downloadToken = _.uniqueId(`${+new Date()}-`);
// a cookie value that the server will remove as a download-ready indicator
const cookieKey = navigator.cookieEnabled
? Math.abs(hashString(JSON.stringify(params) + downloadToken)).toString(16)
: null;
if (cookieKey) {
Cookies.set(cookieKey, downloadToken);
_.assign(params, {
downloadCookieKey: cookieKey,
downloadCookiePath: cookiePath,
});
}
const fields = _.reduce(
params,
(result, value, key) => {
const paramValue = arrayToStringOnFields(key, value, arrayToStringFields);
return (
result +
[].concat(paramValue).reduce((acc, v) => acc + toHtml(key, v), '')
);
},
'',
);
const iFrame = document.createElement('iframe');
iFrame.style.display = 'none';
iFrame.src = 'about:blank';
iFrame.onload = function() {
this.__frame__loaded = true;
};
// Appending to document body to allow navigation away from the current
// page and downloads in the background
document.body.appendChild(iFrame);
iFrame.__frame__loaded = false;
const form = document.createElement('form');
form.method = method.toUpperCase();
form.action = url;
form.innerHTML = fields;
getBody(iFrame).appendChild(form);
form.submit();
return cookieKey
? _.partial(progressChecker, iFrame, cookieKey, downloadToken, altMessage)
: _.partial(cookielessChecker, iFrame);
};
/*----------------------------------------------------------------------------*/
export default download;
|
information/blendle-frontend-react-source/app/modules/alerts/components/AlertManageForm.js | BramscoChill/BlendleParser | import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import Input from 'components/Input';
import Button from 'components/Button';
import { translate, translateElement } from 'instances/i18n';
export default class AlertManageForm extends React.Component {
static propTypes = {
onClickEdit: PropTypes.func.isRequired,
onChangeQuery: PropTypes.func.isRequired,
onClickShowResults: PropTypes.func.isRequired,
onClickDelete: PropTypes.func.isRequired,
query: PropTypes.string,
};
state = {
showEdit: false,
query: this.props.query,
};
_onClickShowEdit(e) {
e.preventDefault();
this.setState({ showEdit: !this.state.showEdit });
}
_onClickEdit() {
const inp = ReactDOM.findDOMNode(this.refs.query);
this.props.onClickEdit({ query: inp.value });
}
_renderEdit() {
if (!this.state.showEdit) {
return null;
}
return (
<form className="edit" name="alert" onSubmit={this.props.onClickShowResults}>
<Input
ref="query"
name="query"
className="inp inp-text inp-keyword"
defaultValue={this.props.query}
onChange={this.props.onChangeQuery}
autoFocus
/>
<Button className="btn-text btn-try" onClick={this.props.onClickShowResults}>
{translate('alerts.buttons.show')}
</Button>
<Button className="btn-text btn-update" onClick={() => this._onClickEdit()}>
{translate('alerts.buttons.edit')}
</Button>
<div className="lnk lnk-delete" onClick={this.props.onClickDelete}>
{translate('alerts.buttons.delete')}
</div>
</form>
);
}
render() {
return (
<div className="v-tile v-alert-settings l-transparent tile-explain s-success">
<div className="explanation">
{translateElement(<h2 />, 'alerts.tiles.settings.explanation', [this.props.query], true)}
</div>
<div className="display">
<a href="#" className="lnk lnk-edit" onClick={this._onClickShowEdit.bind(this)}>
{translate('alerts.links.edit')}
</a>
</div>
{this._renderEdit()}
</div>
);
}
}
// WEBPACK FOOTER //
// ./src/js/app/modules/alerts/components/AlertManageForm.js |
app/javascript/mastodon/features/ui/components/bundle.js | WitchesTown/mastodon | import React from 'react';
import PropTypes from 'prop-types';
const emptyComponent = () => null;
const noop = () => { };
class Bundle extends React.PureComponent {
static propTypes = {
fetchComponent: PropTypes.func.isRequired,
loading: PropTypes.func,
error: PropTypes.func,
children: PropTypes.func.isRequired,
renderDelay: PropTypes.number,
onFetch: PropTypes.func,
onFetchSuccess: PropTypes.func,
onFetchFail: PropTypes.func,
}
static defaultProps = {
loading: emptyComponent,
error: emptyComponent,
renderDelay: 0,
onFetch: noop,
onFetchSuccess: noop,
onFetchFail: noop,
}
static cache = new Map
state = {
mod: undefined,
forceRender: false,
}
componentWillMount() {
this.load(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.fetchComponent !== this.props.fetchComponent) {
this.load(nextProps);
}
}
componentWillUnmount () {
if (this.timeout) {
clearTimeout(this.timeout);
}
}
load = (props) => {
const { fetchComponent, onFetch, onFetchSuccess, onFetchFail, renderDelay } = props || this.props;
const cachedMod = Bundle.cache.get(fetchComponent);
onFetch();
if (cachedMod) {
this.setState({ mod: cachedMod.default });
onFetchSuccess();
return Promise.resolve();
}
this.setState({ mod: undefined });
if (renderDelay !== 0) {
this.timestamp = new Date();
this.timeout = setTimeout(() => this.setState({ forceRender: true }), renderDelay);
}
return fetchComponent()
.then((mod) => {
Bundle.cache.set(fetchComponent, mod);
this.setState({ mod: mod.default });
onFetchSuccess();
})
.catch((error) => {
this.setState({ mod: null });
onFetchFail(error);
});
}
render() {
const { loading: Loading, error: Error, children, renderDelay } = this.props;
const { mod, forceRender } = this.state;
const elapsed = this.timestamp ? (new Date() - this.timestamp) : renderDelay;
if (mod === undefined) {
return (elapsed >= renderDelay || forceRender) ? <Loading /> : null;
}
if (mod === null) {
return <Error onRetry={this.load} />;
}
return children(mod);
}
}
export default Bundle;
|
src/scripts/vendors.js | kodokojo/kodokojo-ui-commons | /**
* Kodo Kojo - Software factory done right
* Copyright © 2017 Kodo Kojo (infos@kodokojo.io)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// core
import React from 'react'
import { compose } from 'redux'
import { Provider, connect } from 'react-redux'
// router
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
// intl
import { intlShape, injectIntl, addLocaleData } from 'react-intl'
// ui
import { themr } from 'react-css-themr'
// DOM, browser
import ReactDOM from 'react-dom'
import injectTapEventPlugin from 'react-tap-event-plugin'
// form
import { reduxForm } from 'redux-form'
// other
import Promise from 'bluebird'
|
extension/examples/todomvc/components/TodoItem.js | gaearon/redux-devtools | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import TodoTextInput from './TodoTextInput';
class TodoItem extends Component {
constructor(props, context) {
super(props, context);
this.state = {
editing: false,
};
}
handleDoubleClick() {
this.setState({ editing: true });
}
handleSave(id, text) {
if (text.length === 0) {
this.props.deleteTodo(id);
} else {
this.props.editTodo(id, text);
}
this.setState({ editing: false });
}
render() {
const { todo, completeTodo, deleteTodo } = this.props;
let element;
if (this.state.editing) {
element = (
<TodoTextInput
text={todo.text}
editing={this.state.editing}
onSave={(text) => this.handleSave(todo.id, text)}
/>
);
} else {
element = (
<div className="view">
<input
className="toggle"
type="checkbox"
checked={todo.completed}
onChange={() => completeTodo(todo.id)}
/>
<label onDoubleClick={this.handleDoubleClick.bind(this)}>
{todo.text}
</label>
<button className="destroy" onClick={() => deleteTodo(todo.id)} />
</div>
);
}
return (
<li
className={classnames({
completed: todo.completed,
editing: this.state.editing,
})}
>
{element}
</li>
);
}
}
TodoItem.propTypes = {
todo: PropTypes.object.isRequired,
editTodo: PropTypes.func.isRequired,
deleteTodo: PropTypes.func.isRequired,
completeTodo: PropTypes.func.isRequired,
};
export default TodoItem;
|
src/svg-icons/image/timer.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageTimer = (props) => (
<SvgIcon {...props}>
<path d="M15 1H9v2h6V1zm-4 13h2V8h-2v6zm8.03-6.61l1.42-1.42c-.43-.51-.9-.99-1.41-1.41l-1.42 1.42C16.07 4.74 14.12 4 12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9 9-4.03 9-9c0-2.12-.74-4.07-1.97-5.61zM12 20c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/>
</SvgIcon>
);
ImageTimer = pure(ImageTimer);
ImageTimer.displayName = 'ImageTimer';
ImageTimer.muiName = 'SvgIcon';
export default ImageTimer;
|
docs/src/routes/not-found/NotFound.js | bmatthews/haze-lea | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './NotFound.css';
class NotFound extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>
{this.props.title}
</h1>
<p>Sorry, the page you were trying to view does not exist.</p>
</div>
</div>
);
}
}
export default withStyles(s)(NotFound);
|
src/components/hello/hello.js | nordsoftware/react-starter | import React from 'react';
import { connect } from 'react-redux';
import { Row, Column } from 'react-foundation';
import { Navbar } from '../navbar/navbar';
export const Hello = ({ isAuthenticated }) => (
<div className="hello">
<Navbar isAuthenticated={isAuthenticated}/>
<Row>
<Column>
<p className="hello__text">Hello from React!</p>
</Column>
</Row>
</div>
);
function mapStateToProps(state) {
return {
isAuthenticated: state.auth.get('isAuthenticated')
};
}
export const HelloContainer = connect(mapStateToProps)(Hello);
|
app/javascript/mastodon/features/compose/components/warning.js | robotstart/mastodon | import React from 'react';
import PropTypes from 'prop-types';
class Warning extends React.PureComponent {
constructor (props) {
super(props);
}
render () {
const { message } = this.props;
return (
<div className='compose-form__warning'>
{message}
</div>
);
}
}
Warning.propTypes = {
message: PropTypes.node.isRequired
};
export default Warning;
|
packages/simple-cache-provider/src/SimpleCacheProvider.js | syranide/react | /**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import React from 'react';
import warning from 'fbjs/lib/warning';
function noop() {}
const Empty = 0;
const Pending = 1;
const Resolved = 2;
const Rejected = 3;
type EmptyRecord = {|
status: 0,
suspender: null,
value: null,
error: null,
|};
type PendingRecord<V> = {|
status: 1,
suspender: Promise<V>,
value: null,
error: null,
|};
type ResolvedRecord<V> = {|
status: 2,
suspender: null,
value: V,
error: null,
|};
type RejectedRecord = {|
status: 3,
suspender: null,
value: null,
error: Error,
|};
type Record<V> =
| EmptyRecord
| PendingRecord<V>
| ResolvedRecord<V>
| RejectedRecord;
type RecordCache<K, V> = Map<K, Record<V>>;
// TODO: How do you express this type with Flow?
type ResourceCache = Map<any, RecordCache<any, any>>;
type Cache = {
invalidate(): void,
read<K, V, A>(
resourceType: mixed,
key: K,
miss: (A) => Promise<V>,
missArg: A,
): V,
preload<K, V, A>(
resourceType: mixed,
key: K,
miss: (A) => Promise<V>,
missArg: A,
): void,
// DEV-only
$$typeof?: Symbol | number,
};
let CACHE_TYPE;
if (__DEV__) {
CACHE_TYPE = 0xcac4e;
}
let isCache;
if (__DEV__) {
isCache = value =>
value !== null &&
typeof value === 'object' &&
value.$$typeof === CACHE_TYPE;
}
export function createCache(invalidator: () => mixed): Cache {
const resourceCache: ResourceCache = new Map();
function getRecord<K, V>(resourceType: any, key: K): Record<V> {
if (__DEV__) {
warning(
typeof resourceType !== 'string' && typeof resourceType !== 'number',
'Invalid resourceType: Expected a symbol, object, or function, but ' +
'instead received: %s. Strings and numbers are not permitted as ' +
'resource types.',
resourceType,
);
}
let recordCache = resourceCache.get(resourceType);
if (recordCache !== undefined) {
const record = recordCache.get(key);
if (record !== undefined) {
return record;
}
} else {
recordCache = new Map();
resourceCache.set(resourceType, recordCache);
}
const record = {
status: Empty,
suspender: null,
value: null,
error: null,
};
recordCache.set(key, record);
return record;
}
function load<V>(emptyRecord: EmptyRecord, suspender: Promise<V>) {
const pendingRecord: PendingRecord<V> = (emptyRecord: any);
pendingRecord.status = Pending;
pendingRecord.suspender = suspender;
suspender.then(
value => {
// Resource loaded successfully.
const resolvedRecord: ResolvedRecord<V> = (pendingRecord: any);
resolvedRecord.status = Resolved;
resolvedRecord.suspender = null;
resolvedRecord.value = value;
},
error => {
// Resource failed to load. Stash the error for later so we can throw it
// the next time it's requested.
const rejectedRecord: RejectedRecord = (pendingRecord: any);
rejectedRecord.status = Rejected;
rejectedRecord.suspender = null;
rejectedRecord.error = error;
},
);
}
const cache: Cache = {
invalidate() {
invalidator();
},
preload<K, V, A>(
resourceType: any,
key: K,
miss: A => Promise<V>,
missArg: A,
): void {
const record: Record<V> = getRecord(resourceType, key);
switch (record.status) {
case Empty:
// Warm the cache.
const suspender = miss(missArg);
load(record, suspender);
return;
case Pending:
// There's already a pending request.
return;
case Resolved:
// The resource is already in the cache.
return;
case Rejected:
// The request failed.
return;
}
},
read<K, V, A>(
resourceType: any,
key: K,
miss: A => Promise<V>,
missArg: A,
): V {
const record: Record<V> = getRecord(resourceType, key);
switch (record.status) {
case Empty:
// Load the requested resource.
const suspender = miss(missArg);
load(record, suspender);
throw suspender;
case Pending:
// There's already a pending request.
throw record.suspender;
case Resolved:
return record.value;
case Rejected:
default:
// The requested resource previously failed loading.
const error = record.error;
const emptyRecord: EmptyRecord = (record: any);
emptyRecord.status = 0;
emptyRecord.error = null;
throw error;
}
},
};
if (__DEV__) {
cache.$$typeof = CACHE_TYPE;
}
return cache;
}
let warnIfNonPrimitiveKey;
if (__DEV__) {
warnIfNonPrimitiveKey = (key, methodName) => {
warning(
typeof key === 'string' ||
typeof key === 'number' ||
typeof key === 'boolean' ||
key === undefined ||
key === null,
'%s: Invalid key type. Expected a string, number, symbol, or boolean, ' +
'but instead received: %s' +
'\n\nTo use non-primitive values as keys, you must pass a hash ' +
'function as the second argument to createResource().',
methodName,
key,
);
};
}
type primitive = string | number | boolean | void | null;
type ResourceReader<K, V> = (Cache, K) => V;
type Resource<K, V> = ResourceReader<K, V> & {
preload(cache: Cache, key: K): void,
};
// These declarations are used to express function overloading. I wish there
// were a more elegant way to do this in the function definition itself.
// Primitive keys do not request a hash function.
declare function createResource<V, K: primitive, H: primitive>(
loadResource: (K) => Promise<V>,
hash?: (K) => H,
): Resource<K, V>;
// Non-primitive keys *do* require a hash function.
// eslint-disable-next-line no-redeclare
declare function createResource<V, K: mixed, H: primitive>(
loadResource: (K) => Promise<V>,
hash: (K) => H,
): Resource<K, V>;
// eslint-disable-next-line no-redeclare
export function createResource<V, K, H: primitive>(
loadResource: K => Promise<V>,
hash: K => H,
): Resource<K, V> {
// The read function itself serves as the resource type.
function read(cache, key) {
if (__DEV__) {
warning(
isCache(cache),
'read(): The first argument must be a cache. Instead received: %s',
cache,
);
}
if (hash === undefined) {
if (__DEV__) {
warnIfNonPrimitiveKey(key, 'read');
}
return cache.read(read, key, loadResource, key);
}
const hashedKey = hash(key);
return cache.read(read, hashedKey, loadResource, key);
}
read.preload = function(cache, key) {
if (__DEV__) {
warning(
isCache(cache),
'preload(): The first argument must be a cache. Instead received: %s',
cache,
);
}
if (hash === undefined) {
if (__DEV__) {
warnIfNonPrimitiveKey(key, 'preload');
}
cache.preload(read, key, loadResource, key);
return;
}
const hashedKey = hash(key);
cache.preload(read, hashedKey, loadResource, key);
};
return read;
}
// Global cache has no eviction policy (except for, ya know, a browser refresh).
const globalCache = createCache(noop);
export const SimpleCache = React.createContext(globalCache);
|
docs/app/Examples/modules/Search/Variations/SearchExampleInput.js | shengnian/shengnian-ui-react | import React from 'react'
import SearchExampleStandard from '../Types/SearchExampleStandard'
const SearchExampleInput = () => <SearchExampleStandard input={{ icon: 'search', iconPosition: 'left' }} />
export default SearchExampleInput
|
docs/client/components/pages/InlineToolbar/CustomInlineToolbarEditor/index.js | koaninc/draft-js-plugins | /* eslint-disable react/no-multi-comp */
import React, { Component } from 'react';
// eslint-disable-next-line import/no-unresolved
import Editor, { createEditorStateWithText } from 'draft-js-plugins-editor';
// eslint-disable-next-line import/no-unresolved
import createInlineToolbarPlugin, { Separator } from 'draft-js-inline-toolbar-plugin';
import {
ItalicButton,
BoldButton,
UnderlineButton,
CodeButton,
HeadlineOneButton,
HeadlineTwoButton,
HeadlineThreeButton,
UnorderedListButton,
OrderedListButton,
BlockquoteButton,
CodeBlockButton,
} from 'draft-js-buttons'; // eslint-disable-line import/no-unresolved
import editorStyles from './editorStyles.css';
class HeadlinesPicker extends Component {
componentDidMount() {
setTimeout(() => { window.addEventListener('click', this.onWindowClick); });
}
componentWillUnmount() {
window.removeEventListener('click', this.onWindowClick);
}
onWindowClick = () =>
// Call `onOverrideContent` again with `undefined`
// so the toolbar can show its regular content again.
this.props.onOverrideContent(undefined);
render() {
const buttons = [HeadlineOneButton, HeadlineTwoButton, HeadlineThreeButton];
return (
<div>
{buttons.map((Button, i) => // eslint-disable-next-line
<Button key={i} {...this.props} />
)}
</div>
);
}
}
class HeadlinesButton extends Component {
onClick = () =>
// A button can call `onOverrideContent` to replace the content
// of the toolbar. This can be useful for displaying sub
// menus or requesting additional information from the user.
this.props.onOverrideContent(HeadlinesPicker);
render() {
return (
<div className={editorStyles.headlineButtonWrapper}>
<button onClick={this.onClick} className={editorStyles.headlineButton}>
H
</button>
</div>
);
}
}
const inlineToolbarPlugin = createInlineToolbarPlugin({
structure: [
BoldButton,
ItalicButton,
UnderlineButton,
CodeButton,
Separator,
HeadlinesButton,
UnorderedListButton,
OrderedListButton,
BlockquoteButton,
CodeBlockButton
]
});
const { InlineToolbar } = inlineToolbarPlugin;
const plugins = [inlineToolbarPlugin];
const text = 'In this editor a toolbar shows up once you select part of the text …';
export default class CustomInlineToolbarEditor extends Component {
state = {
editorState: createEditorStateWithText(text),
};
onChange = (editorState) => {
this.setState({
editorState,
});
};
focus = () => {
this.editor.focus();
};
render() {
return (
<div className={editorStyles.editor} onClick={this.focus}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
ref={(element) => { this.editor = element; }}
/>
<InlineToolbar />
</div>
);
}
}
|
js/components/Header/index.android.js | ChiragHindocha/stay_fit |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Header, Title, Content, Button, Icon, Left, Right, Body, Text, ListItem, List } from 'native-base';
import { Actions } from 'react-native-router-flux';
import { actions } from 'react-native-navigation-redux-helpers';
import { openDrawer, closeDrawer } from '../../actions/drawer';
import styles from './styles';
const {
pushRoute,
} = actions;
const datas = [
{
route: 'header1',
text: 'Only Title',
},
{
route: 'header2',
text: 'Icon Buttons',
},
{
route: 'header3',
text: 'Text Buttons',
},
{
route: 'header4',
text: 'Icon Button and Text Button',
},
{
route: 'header6',
text: 'Multiple Icon Buttons',
},
{
route: 'header7',
text: 'Title and Subtitle',
},
{
route: 'header8',
text: 'Custom backgroundColor',
},
];
class HeaderNB extends Component { // eslint-disable-line
static propTypes = {
openDrawer: React.PropTypes.func,
pushRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
pushRoute(route) {
this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={this.props.openDrawer}>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>Headers</Title>
</Body>
<Right />
</Header>
<Content>
<List
dataArray={datas} renderRow={data =>
<ListItem button onPress={() => { Actions[data.route](); this.props.closeDrawer() }} >
<Text>{data.text}</Text>
<Right>
<Icon name="arrow-forward" style={{ color: '#999' }} />
</Right>
</ListItem>
}
/>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
closeDrawer: () => dispatch(closeDrawer()),
pushRoute: (route, key) => dispatch(pushRoute(route, key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(HeaderNB);
|
docs/src/pages/404.js | isaacs/node-tap | import React from 'react';
import Navbar from '../components/navbar';
import styled from 'styled-components';
import {Flex} from 'rebass';
import exclamationMark from '../images/exclamation.gif';
import EncircledImage from '../components/EncircledImage';
import SEO from '../components/seo';
const Container = styled(Flex)`
flex-direction: column;
align-items: center;
min-height: 100vh;
padding-top: 80px;
`;
const Headline = styled.h1`
margin: 10px 0 0;
`;
const ErrorPage = () => {
return (
<>
<SEO title="404 Not Found" />
<Navbar/>
<Container>
<div>
<EncircledImage image={exclamationMark} alt="!" />
</div>
<Headline>404</Headline>
<p>Page not found</p>
</Container>
</>
);
};
export default ErrorPage;
|
tests/react/useImperativeHandle_hook.js | facebook/flow | // @flow
import React from 'react';
{
React.useImperativeHandle(); // Error: function requires another argument.
}
type Interface = {|
focus: () => void
|};
{
const api: Interface = {
focus: () => {}
};
const ref: {current: null | Interface } = React.createRef();
React.useImperativeHandle(ref, () => api); // Ok
const refSetter = (instance: null | Interface) => {};
React.useImperativeHandle(refSetter, () => api); // Ok
}
{
const api: Interface = {
focus: () => {}
};
const ref: {current: null | Interface } = React.createRef();
React.useImperativeHandle(ref, () => ({})); // Error: inexact object literal is incompatible with exact Interface
const refSetter = (instance: null | Interface) => {};
React.useImperativeHandle(refSetter, () => ({})); // Error: inexact object literal is incompatible with exact Interface
}
|
src/parser/priest/holy/modules/spells/SpiritOfRedemption.js | fyruna/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import Analyzer from 'parser/core/Analyzer';
import EventEmitter from 'parser/core/modules/EventEmitter';
import DeathDowntime from 'parser/shared/modules/downtime/DeathDowntime';
import SpellLink from 'common/SpellLink';
import { isItAprilFoolDay } from 'common/aprilFools';
class SpiritOfRedemption extends Analyzer {
static dependencies = {
eventEmitter: EventEmitter,
deathDowntime: DeathDowntime,
};
sorStartTime = 0;
timeSpentRedeeming = 0;
timeSpendDead = 0;
get spiritUptime() {
return this.timeSpentRedeeming;
}
get deadTime() {
return this.deathDowntime.totalDowntime;
}
get aliveTime() {
return this.owner.fightDuration - this.deadTime - this.spiritUptime;
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.SPIRIT_OF_REDEMPTION_BUFF.id) {
this.sorStartTime = event.timestamp;
this.eventEmitter.fabricateEvent({
...event,
type: 'cast',
}, event);
}
}
on_byPlayer_removebuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.SPIRIT_OF_REDEMPTION_BUFF.id) {
this.timeSpentRedeeming += event.timestamp - this.sorStartTime;
}
}
get deadTimeThresholds() {
return {
actual: this.timeSpentRedeeming,
isLessThan: {
minor: 10,
average: 5,
major: 1,
},
style: 'number',
};
}
suggestions(when) {
if (isItAprilFoolDay()) {
when(this.deadTimeThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<>We noticed that you didn't die during this encounter. It is recommended that you die within the last 15 seconds of each encounter to make the most of <SpellLink id={SPELLS.SPIRIT_OF_REDEMPTION_BUFF.id} />. If you are having trouble dying, try standing in fire.</>)
.icon('inv_enchant_essenceeternallarge')
.actual(`${actual} seconds spent redeeming`)
.recommended(`${recommended} seconds is recommended`);
});
}
}
}
export default SpiritOfRedemption;
|
src/elements/Reveal/RevealContent.js | Semantic-Org/Semantic-UI-React | import cx from 'clsx'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
customPropTypes,
getElementType,
getUnhandledProps,
useKeyOnly,
} from '../../lib'
/**
* A content sub-component for the Reveal.
*/
function RevealContent(props) {
const { children, className, content, hidden, visible } = props
const classes = cx(
'ui',
useKeyOnly(hidden, 'hidden'),
useKeyOnly(visible, 'visible'),
'content',
className,
)
const rest = getUnhandledProps(RevealContent, props)
const ElementType = getElementType(RevealContent, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
RevealContent.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,
/** A reveal may contain content that is visible before interaction. */
hidden: PropTypes.bool,
/** A reveal may contain content that is hidden before user interaction. */
visible: PropTypes.bool,
}
export default RevealContent
|
app/routes.js | billyvg/pokemon-journal | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/App';
import HomePage from './containers/HomePage';
import CounterPage from './containers/CounterPage';
export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
<Route path="/counter" component={CounterPage} />
</Route>
);
|
examples/relay/src/App.js | svrcekmichal/react-scripts | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header ">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to Reactt</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
|
src/CarouselContext.js | peterasplund/slim-react-carousel | import React from 'react';
const CarouselContext = React.createContext({});
export const CarouselProvider = CarouselContext.Provider;
export const CarouselConsumer = CarouselContext.Consumer;
export default CarouselContext;
|
src/components/Reset/index.js | adam-beck/react-powerball | import React from 'react';
const Reset = ({reset}) => (
<button onClick={reset}>Reset</button>
);
export { Reset };
|
src/components/textfield/demos/SingleLine.js | isogon/styled-mdl | import React from 'react'
import { Textfield } from '../../../'
export default () => <Textfield floatingLabel label="Text..." />
|
examples/sidebar/app.js | chrisirhc/react-router | import React from 'react';
import { Router, Route, Link } from 'react-router';
import data from './data';
var Category = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<h1>{category.name}</h1>
{this.props.children || (
<p>{category.description}</p>
)}
</div>
);
}
});
var CategorySidebar = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<Link to="/">◀︎ Back</Link>
<h2>{category.name} Items</h2>
<ul>
{category.items.map((item, index) => (
<li key={index}>
<Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link>
</li>
))}
</ul>
</div>
);
}
});
var Item = React.createClass({
render() {
var { category, item } = this.props.params;
var menuItem = data.lookupItem(category, item);
return (
<div>
<h1>{menuItem.name}</h1>
<p>${menuItem.price}</p>
</div>
);
}
});
var Index = React.createClass({
render() {
return (
<div>
<h1>Sidebar</h1>
<p>
Routes can have multiple components, so that all portions of your UI
can participate in the routing.
</p>
</div>
);
}
});
var IndexSidebar = React.createClass({
render() {
return (
<div>
<h2>Categories</h2>
<ul>
{data.getAll().map((category, index) => (
<li key={index}>
<Link to={`/category/${category.name}`}>{category.name}</Link>
</li>
))}
</ul>
</div>
);
}
});
var App = React.createClass({
render() {
var { children } = this.props;
return (
<div>
<div className="Sidebar">
{children ? children.sidebar : <IndexSidebar />}
</div>
<div className="Content">
{children ? children.content : <Index />}
</div>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="category/:category" components={{content: Category, sidebar: CategorySidebar}}>
<Route path=":item" component={Item} />
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
js/components/projectlist.js | orionwei/mygit | /**
* Created by orionwei on 2016/11/20.
*/
import React from 'react';
import Relay from 'react-relay';
import Header from './header';
class ProjectList extends React.Component {
render() {
return (
<div>
<Header/>
</div>
);
}
}
export default Relay.createContainer(ProjectList, {
fragments: {
Film: () => Relay.QL`
fragment on Film {
id
}
`,
},
});
|
src/checkout/index.js | bhongy/react-components | import React from 'react';
import { Route } from 'react-router-dom';
import { Provider } from 'react-redux';
import configureStore from './store';
import EnterCode from './enter-code';
import Offer from './offer';
import Debugger from './debugger';
const CheckoutDemo = ({ match }) => (
<Provider store={configureStore()}>
<section>
<Route path={`${match.url}/:offerCode`} component={Offer} />
<Route exact path={match.url} component={EnterCode} />
<Debugger />
</section>
</Provider>
);
export default CheckoutDemo;
|
app/imports/ui/client/components/Login/index.js | valcol/ScrumNinja | import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import LinkItem from '../misc/LinkItem';
import { createContainer } from 'meteor/react-meteor-data';
import { Session } from 'meteor/session';
import FeedbackMessage from '../misc/FeedbackMessage';
class Login extends Component {
constructor(props) {
super(props);
this.state = {email: '', password: ''};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangePassword = this.handleChangePassword.bind(this);
}
handleChangeEmail(event) {
this.setState({email: event.target.value});
}
handleChangePassword(event) {
this.setState({password: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
let email = this.state.email;
let password = this.state.password;
Meteor.loginWithPassword(email, password, function(err, res) {
if (err) {
Session.set('error', err.message);
} else {
window.location.href = '/u/';
}
});
}
render() {
return (
<div className="login-box">
<div className="login-logo">
<img src="/img/logo-wide.png" width='75%' height='75%' alt="logo"></img>
</div>
{/* /.login-logo */}
<div className="login-box-body">
<p className="login-box-msg">Sign in to start your session</p>
<FeedbackMessage
error={this.props.error}
success={this.props.success}
/>
<div className="form-group has-feedback">
<input type="email" className="form-control" placeholder="Email" name="email" value={this.state.email}
onChange={this.handleChangeEmail}/>
<span className="glyphicon glyphicon-envelope form-control-feedback" />
</div>
<div className="form-group has-feedback">
<input type="password" className="form-control" placeholder="Password" name="password" value={this.state.password}
onChange={this.handleChangePassword}/>
<span className="glyphicon glyphicon-lock form-control-feedback" />
</div>
<div className="row">
<div className="col-xs-4">
<button onClick={this.handleSubmit} className="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
</div>
<LinkItem to={'/r/register'} className={'signup'}>Register a new membership</LinkItem>
<LinkItem to={'/r/forgot'} className={'signup'}>Forgot your password ?</LinkItem>
</div>
</div>
);
}
}
export default createContainer(() => {
return {
error: Session.get('error')
};
}, Login);
|
src/basic/ListItem.js | sampsasaarela/NativeBase | import React, { Component } from 'react';
import { TouchableHighlight, Platform, TouchableNativeFeedback, View } from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';
import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames';
import variable from '../theme/variables/platform';
class ListItem extends Component {
static contextTypes = {
theme: React.PropTypes.object,
}
render() {
const variables = (this.context.theme) ? this.context.theme['@@shoutem.theme/themeStyle'].variables : variable;
if (Platform.OS === 'ios' || variable.androidRipple === false || !this.props.onPress || !this.props.onLongPress || Platform.Version <= 21) {
return (
<TouchableHighlight
onPress={this.props.onPress}
onLongPress={this.props.onLongPress}
ref={c => this._root = c}
underlayColor={variables.listBtnUnderlayColor}
>
<View {...this.props}>{this.props.children}</View>
</TouchableHighlight>
);
}
else {
return(
<TouchableNativeFeedback ref={c => this._root = c}
onPress={this.props.onPress}
onLongPress={this.props.onLongPress}
background={(this.props.androidRippleColor) ? TouchableNativeFeedback.Ripple(this.props.androidRippleColor) : TouchableNativeFeedback.Ripple(variable.androidRippleColorDark)}>
<View style={{ marginLeft: -17, paddingLeft: 17 }}>
<View {...this.props}>{this.props.children}</View>
</View>
</TouchableNativeFeedback>
);
}
}
}
ListItem.propTypes = {
...TouchableHighlight.propTypes,
style: React.PropTypes.object,
itemDivider: React.PropTypes.bool,
button: React.PropTypes.bool,
};
const StyledListItem = connectStyle('NativeBase.ListItem', {}, mapPropsToStyleNames)(ListItem);
export {
StyledListItem as ListItem,
};
|
resources/assets/js/components/profile/TimelineItem.js | jrm2k6/i-heart-reading | import React from 'react';
import moment from 'moment';
import { Link } from 'react-router';
class TimelineItem extends React.Component {
getUpdateContent() {
const { update } = this.props;
const when = moment(update.created_at).fromNow();
if (update.assignment) {
const book = update.assignment.book;
const wasMarkedAsRead = update.mark_book_read === 1;
const numPagesRead = update.num_pages_read;
if (wasMarkedAsRead) {
return (
<div className='timeline-update-row' key={update.id}>
<div className='circle book-read' />
<span className='update-row-content'>
{book.title} by {book.author} was marked as read
</span>
<span className='update-row-readable-time'>({when})</span>
</div>
);
}
return (
<div className='timeline-update-row' key={update.id}>
<div className='circle pages-read' />
<span className='update-row-content'>
Read {numPagesRead} pages of {book.title} by {book.author}
</span>
<span className='update-row-readable-time'>({when})</span>
</div>
);
}
const circleColor = this.getCircleColor(update);
const _className = `circle ${circleColor}`;
const linkContent = `/app/responses/student-response/${update.id}`;
return (
<div className='timeline-update-row'>
<div className={_className} />
<span className='update-row-content'>
Submitted a response for {update.book.title} by {update.book.author}
</span>
<span className='update-row-readable-time'>({when})</span>
<div className='option-response-item'>
<span className='update-row-readable-time'>
<Link className='link-response' to={linkContent}>View response</Link>
</span>
</div>
</div>
);
}
render() {
return (
<div className='profile-container-timeline-item'>
{this.getUpdateContent()}
</div>
);
}
getCircleColor(update) {
return (update.currentReview) ? update.currentReview.decision_type_name
: 'no-decision';
}
}
export default TimelineItem;
|
src/routes/CollectionStatsView/CollectionStatsView.js | robertkirsz/magic-cards-manager | import React from 'react'
import PropTypes from 'proptypes'
import { connect } from 'react-redux'
import { CollectionStats } from 'components'
const mapStateToProps = ({ user }) => ({ user })
const CollectionStatsView = ({ user }) => (
<div className="collection-stats-view">
<CollectionStats />
</div>
)
CollectionStatsView.propTypes = {
user: PropTypes.object
}
export default connect(mapStateToProps)(CollectionStatsView)
|
src/components/NewRestaurantSignUp/NewRestaurantSignUp.js | tfrankie88/splitzi_react | import React, { Component } from 'react';
import update from 'react-addons-update';
import { browserHistory } from 'react-router';
import NavigationSplitIt from '../Navigation/NavigationSplitIt';
class NewRestaurant extends Component {
constructor(props) {
super(props);
this.state = {
restaurant: {
first_name: '',
last_name: '',
email: '',
password_digest: '',
restaurant_name: '',
country: '',
postal: ''
}
};
}
componentWillMount() {
if (localStorage.getItem('token')) {
browserHistory.push('/login');
}
}
handleChange(event) {
let newState = update(this.state, {
restaurant: {
$merge: {
[event.target.name]: event.target.value
}
}
});
this.setState(newState);
}
handleSubmit(event) {
event.preventDefault();
if (this.state.restaurant.email !== '' && this.state.restaurant.password_digest !== '') {
fetch('https://splitzi-api.herokuapp.com/restaurant/sign_up', {
method: 'POST',
body: JSON.stringify(this.state),
headers: {
'Content-Type': 'application/json'
}
})
.then(() => {
browserHistory.push('/login');
})
.catch(() => {
alert('Not authenticated!');
});
} else {
alert('please fill out entire application');
}
}
render(){
return(
<div>
<NavigationSplitIt />
<div className="content-container">
<div className="new-restaurant-title">sign up</div>
<form onSubmit={this.handleSubmit.bind(this)} className="new-restaurant-container">
<input type="text" name="first_name" placeholder="first name" onChange={this.handleChange.bind(this)}></input>
<input type="text" name="last_name" placeholder="last name" onChange={this.handleChange.bind(this)}></input>
<input type="text" name="email" placeholder="email" onChange={this.handleChange.bind(this)}></input>
<input type="password" onChange={this.handleChange.bind(this)} name="password_digest" placeholder="password"></input>
<input type="text" name="restaurant_name" placeholder="restaurant name" onChange={this.handleChange.bind(this)}></input>
<input type="text" name="country" placeholder="country" onChange={this.handleChange.bind(this)}></input>
<input type="text" name="postal" placeholder="postal" onChange={this.handleChange.bind(this)}></input><br/>
<button href="/login" type="submit">Submit</button>
</form>
</div>
</div>
);
}
}
export default NewRestaurant;
|
src/chapters/04-porazdelitve-verjetnosti/03-diskretne-porazdelitve/06-poissonova-porazdelitev/index.js | medja/ovs-prirocnik | import React from 'react';
import { createChapter } from 'components/chapter';
import Equation from 'components/equation';
import Formula from 'components/formula';
import Chart from 'components/chart';
const title = 'Poissonova porazdelitev';
function Title(props) {
return (
<span>
{ props.title }{' '}
<Equation math="P(\lambda)" />
</span>
);
}
function Chapter() {
const variables = '0 & 1 & 2 & ... & n';
const probabilities = 'e^{-\\lambda} & \\lambda e^{-\\lambda} & f(2) & ... & f(n)';
const distribution = `
P(\\lambda) \\sim \\left(\\begin{array}{c}
${variables}\\\\ ${probabilities}
\\end{array}\\right)
`;
return (
<div>
<p>
Poissonova porazdelitev razporeja glede na število ponovitev
nekega dogodka v danem časovnem intervalu. Odvisna je torej le
od pričakovanih ponovitev v enakem časovnem intervalu. Primer
take porazdelitve je opazovanje števila vozil, ki pripelje skozi
križišče v desetih minutah.
</p>
<Formula
name="Poissonova porazdelitev"
math={distribution}
params={{
'\\lambda': 'Pričakovana frekvenca dogodka'
}}
/>
<p>
Pri računanju s Poissonovo porazdelitvijo si lahko pomagamo z
naslednjimi formulami:
</p>
<Formula.Group>
<Formula
name="Funkcija gostote"
math="f(x) = \frac{\lambda^x e^{-\lambda}}{x!}"
/>
<Formula
name="Porazdelitvena funkcija"
math="F(x) = e^{-\lambda} \sum_{i=0}^{x} \frac{\lambda^i}{i!}"
params={{
'x': 'Število poskusov'
}}
/>
</Formula.Group>
<Formula.Group>
<Formula
name="Matematično upanje"
math="E(X) = \lambda"
/>
<Formula
name="Disperzija"
math="D(X) = \lambda"
params={{
'X': 'Slučajna spremenljivka'
}}
/>
</Formula.Group>
<Chart
name="Primer grafa"
width="500" height="400"
func="Poisson(x, \lambda)" params={{ '\\lambda': 3 }}
range={[-1, 10]} discrete
/>
</div>
);
}
export default createChapter(title, Chapter, [], { Title }); |
src/Parser/Druid/Restoration/Modules/Items/T21_4Set.js | enragednuke/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import ItemHealingDone from 'Main/ItemHealingDone';
const T21_4SET_YSERAS_BOOST = 5;
class T21_4Set extends Analyzer {
static dependencies = {
combatants: Combatants,
};
yserasDuringAwakenedHealing = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.RESTO_DRUID_T21_4SET_BONUS_BUFF.id);
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
const amount = event.amount + (event.absorbed || 0);
if (this.combatants.selected.hasBuff(SPELLS.AWAKENED.id) &&
(spellId === SPELLS.YSERAS_GIFT_OTHERS.id || spellId === SPELLS.YSERAS_GIFT_SELF.id)) {
this.yserasDuringAwakenedHealing += amount;
}
}
item() {
const healing = this.yserasDuringAwakenedHealing * (1 - (1 / T21_4SET_YSERAS_BOOST));
return {
id: `spell-${SPELLS.RESTO_DRUID_T21_4SET_BONUS_BUFF.id}`,
icon: <SpellIcon id={SPELLS.RESTO_DRUID_T21_4SET_BONUS_BUFF.id} />,
title: <SpellLink id={SPELLS.RESTO_DRUID_T21_4SET_BONUS_BUFF.id} />,
result: (
<dfn data-tip="This is the amount of healing done by the extra Ysera's Gift ticks only. Healing from the additional applications of Dreamer are counted under the T21 2Set number">
<ItemHealingDone amount={healing} />
</dfn>
),
};
}
}
export default T21_4Set;
|
app/components/FavoriteList/index.js | juanda99/arasaac-frontend | import React from 'react'
import PropTypes from 'prop-types'
import { DragDropContext } from 'react-dnd'
import HTML5Backend from 'react-dnd-html5-backend'
import withWidth, { SMALL, LARGE } from 'material-ui/utils/withWidth'
import { DEFAULT_LIST } from 'utils'
import DragPictogramSnippet from 'components/PictogramSnippet/DragPictogramSnippet'
import CustomDragLayer from 'components/PictogramSnippet/CustomDragLayer'
import ListSnippet from './ListSnippet'
const Masonry = require('react-masonry-component')
const masonryOptions = {
transitionDuration: '1s'
}
const styles = {
masonry: {
listStyleType: 'none',
display: 'flex',
flexWrap: 'wrap',
flexGrow: 2,
justifyContent: 'space-around'
}
}
export class FavoriteList extends React.Component {
handleDeleteFavorite = (fileName) => {
const { onDeleteFavorite, selectedList } = this.props
onDeleteFavorite(fileName, selectedList)
};
render() {
const {
items,
width,
selectedList,
onDownload,
onDelete,
onSelect,
onRename,
onDrop,
listPictograms,
onDownloadList
} = this.props
let renderLists
/* if not authenticated item.keys is undefined and should not render anything */
const [...lists] = items.keys()
if (selectedList === DEFAULT_LIST) {
renderLists = lists
.filter((listItem) => listItem !== DEFAULT_LIST)
.map((listItem) => {
const totalItems = items.get(listItem).size
return (
<ListSnippet
key={listItem}
listName={listItem}
totalItems={totalItems}
onDelete={onDelete}
onDownload={onDownloadList}
onSelect={onSelect}
onRename={onRename}
/>
)
})
} else {
/* in these case we just render back button */
renderLists = (
<ListSnippet
key={DEFAULT_LIST}
listName={DEFAULT_LIST}
onDelete={onDelete}
onDownload={onDownloadList}
onSelect={onSelect}
onRename={onRename}
/>
)
}
const renderPictograms = listPictograms.map((pictogram) =>
<DragPictogramSnippet
pictogram={pictogram}
locale={'es'}
key={pictogram._id}
showExtra={width === LARGE}
onDrop={onDrop}
onDelete={this.handleDeleteFavorite}
onDownload={onDownload}
/>
)
return (
<div>
{width !== SMALL ? (
<Masonry
className={'my-gallery-class'} // default ''
elementType={'ul'} // default 'div'
options={masonryOptions} // default {}
disableImagesLoaded={false} // default false
style={styles.masonry}
>
{renderLists}
{renderPictograms}
</Masonry>
) : (
<ul>
{renderLists}
{renderPictograms}
</ul>
)}
<CustomDragLayer />
</div>
)
}
}
FavoriteList.propTypes = {
items: PropTypes.object,
width: PropTypes.number.isRequired,
listPictograms: PropTypes.arrayOf(PropTypes.object),
onSelect: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onDownload: PropTypes.func.isRequired,
onDownloadList: PropTypes.func.isRequired,
onRename: PropTypes.func.isRequired,
selectedList: PropTypes.string.isRequired,
onDrop: PropTypes.func.isRequired,
onDeleteFavorite: PropTypes.func.isRequired
}
export default withWidth()(DragDropContext(HTML5Backend)(FavoriteList))
|
stories/Tooltip/ExamplePlacement.js | nirhart/wix-style-react | import React from 'react';
import {Tooltip} from 'wix-style-react';
import styles from './Example.scss';
export default () =>
<Tooltip active placement="right" alignment="center" content="Right Center" showTrigger="custom" hideTrigger="custom">
<div className={styles.box}>Right Center</div>
</Tooltip>;
|
components/Contact/Contact.js | inthegully/reactPortfolio | import React from 'react';
import './contact.css';
import GitHub from '../../images/githublogo.png';
import LinkedIn from '../../images/linkedinlogo.png';
import Insta from '../../images/instagramlogo.png';
import Twitter from '../../images/Twitterlogo.png';
export default class Contact extends React.Component {
render () {
return (
<div className="contact-container">
<h2 className="email">inthegullydesign@gmail.com</h2>
<div className="contact-logos-flex">
<div>
<a href="https://github.com/inthegully" target="_blank">
<img className="contact-logo" src={GitHub} alt="Github logo"/>
</a>
</div>
<div>
<a href="https://www.linkedin.com/in/inthegully/" target="_blank">
<img className="contact-logo" src={LinkedIn} alt="Linkedin logo"/>
</a>
</div>
<div>
<a href="https://www.instagram.com/inthegully/" target="_blank">
<img className="contact-logo" src={Insta} alt="Instagram logo"/>
</a>
</div>
<div>
<a href="https://twitter.com/inthegully" target="_blank">
<img className="contact-logo" src={Twitter} alt="Twitter logo"/>
</a>
</div>
</div>
</div>
);
}
}
|
website-prototyping-tools/RelayPlayground.js | magnus-lycka/relay | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import './RelayPlayground.css';
import 'codemirror/mode/javascript/javascript';
import Codemirror from 'react-codemirror';
import React from 'react';
import ReactDOM from 'react/lib/ReactDOM';
import Relay from 'react-relay'; window.Relay = Relay;
import RelayLocalSchema from 'relay-local-schema';
import babel from 'babel-core/browser';
import babelRelayPlaygroundPlugin from './babelRelayPlaygroundPlugin';
import debounce from 'lodash.debounce';
import defer from 'lodash.defer';
import delay from 'lodash.delay';
import errorCatcher from 'babel-plugin-react-error-catcher/error-catcher';
import errorCatcherPlugin from 'babel-plugin-react-error-catcher';
import evalSchema from './evalSchema';
import getBabelRelayPlugin from 'babel-relay-plugin';
import {introspectionQuery} from 'graphql/utilities';
import {graphql} from 'graphql';
var {PropTypes} = React;
const CODE_EDITOR_OPTIONS = {
extraKeys: {
Tab(cm) {
// Insert spaces when the tab key is pressed
var spaces = Array(cm.getOption('indentUnit') + 1).join(' ');
cm.replaceSelection(spaces);
},
},
indentWithTabs: false,
lineNumbers: true,
mode: 'javascript',
tabSize: 2,
theme: 'solarized light',
};
const ERROR_TYPES = {
graphql: 'GraphQL Validation',
query: 'Query',
runtime: 'Runtime',
schema: 'Schema',
syntax: 'Syntax',
};
const RENDER_STEP_EXAMPLE_CODE =
`ReactDOM.render(
<Relay.RootContainer
Component={MyRelayContainer}
route={new MyHomeRoute()}
/>,
mountNode
);`;
function errorFromGraphQLResultAndQuery(errors, request) {
var queryString = request.getQueryString();
var variables = request.getVariables();
var errorText = `
${errors.map(e => e.message).join('\n')}
Query: ${queryString}
`;
if (variables) {
errorText += `Variables: ${JSON.stringify(variables)}`;
}
return {stack: errorText.trim()};
}
class PlaygroundRenderer extends React.Component {
componentDidMount() {
this._container = document.createElement('div');
this.refs.mountPoint.appendChild(this._container);
this._updateTimeoutId = defer(this._update);
}
componentDidUpdate(prevProps) {
if (this._updateTimeoutId != null) {
clearTimeout(this._updateTimeoutId);
}
this._updateTimeoutId = defer(this._update);
}
componentWillUnmount() {
if (this._updateTimeoutId != null) {
clearTimeout(this._updateTimeoutId);
}
try {
ReactDOM.unmountComponentAtNode(this._container);
} catch(e) {}
}
_update = () => {
ReactDOM.render(React.Children.only(this.props.children), this._container);
}
render() {
return <div ref="mountPoint" />;
}
}
export default class RelayPlayground extends React.Component {
static defaultProps = {
autoExecute: false,
};
static propTypes = {
autoExecute: PropTypes.bool.isRequired,
initialAppSource: PropTypes.string,
initialSchemaSource: PropTypes.string,
onAppSourceChange: PropTypes.func,
onSchemaSourceChange: PropTypes.func,
};
state = {
appElement: null,
appSource: this.props.initialAppSource,
busy: false,
editTarget: 'app',
error: null,
schemaSource: this.props.initialSchemaSource,
shouldExecuteCode: this.props.autoExecute,
};
componentDidMount() {
// Hijack console.warn to collect GraphQL validation warnings (we hope)
this._originalConsoleWarn = console.warn;
var collectedWarnings = [];
console.warn = (...args) => {
collectedWarnings.push([Date.now(), args]);
this._originalConsoleWarn.apply(console, args);
}
// Hijack window.onerror to catch any stray fatals
this._originalWindowOnerror = window.onerror;
window.onerror = (message, url, lineNumber, something, error) => {
// GraphQL validation warnings are followed closely by a thrown exception.
// Console warnings that appear too far before this exception are probably
// not related to GraphQL. Throw those out.
if (/GraphQL validation error/.test(message)) {
var recentWarnings = collectedWarnings
.filter(([createdAt, args]) => Date.now() - createdAt <= 500)
.reduce((memo, [createdAt, args]) => memo.concat(args), []);
this.setState({
error: {stack: recentWarnings.join('\n')},
errorType: ERROR_TYPES.graphql,
});
} else {
this.setState({error, errorType: ERROR_TYPES.runtime});
}
collectedWarnings = [];
return false;
};
if (this.state.shouldExecuteCode) {
this._updateSchema(this.state.schemaSource, this.state.appSource);
}
}
componentDidUpdate(prevProps, prevState) {
var recentlyEnabledCodeExecution =
!prevState.shouldExecuteCode && this.state.shouldExecuteCode;
var appChanged = this.state.appSource !== prevState.appSource;
var schemaChanged = this.state.schemaSource !== prevState.schemaSource;
if (
this.state.shouldExecuteCode &&
(recentlyEnabledCodeExecution || appChanged || schemaChanged)
) {
this.setState({busy: true});
this._handleSourceCodeChange(
this.state.appSource,
recentlyEnabledCodeExecution || schemaChanged
? this.state.schemaSource
: null,
);
}
}
componentWillUnmount() {
clearTimeout(this._errorReporterTimeout);
clearTimeout(this._warningScrubberTimeout);
this._handleSourceCodeChange.cancel();
console.warn = this._originalConsoleWarn;
window.onerror = this._originalWindowOnerror;
}
_handleExecuteClick = () => {
this.setState({shouldExecuteCode: true});
}
_handleSourceCodeChange = debounce((appSource, schemaSource) => {
if (schemaSource != null) {
this._updateSchema(schemaSource, appSource);
} else {
this._updateApp(appSource);
}
}, 300, {trailing: true})
_updateApp = (appSource) => {
clearTimeout(this._errorReporterTimeout);
// We're running in a browser. Create a require() shim to catch any imports.
var require = (path) => {
switch (path) {
// The errorCatcherPlugin injects a series of import statements into the
// program body. Return locally bound variables in these three cases:
case '//error-catcher.js':
return (React, filename, displayName, reporter) => {
// When it fatals, render an empty <span /> in place of the app.
return errorCatcher(React, filename, <span />, reporter);
};
case 'react':
return React;
case 'reporterProxy':
return (error, instance, filename, displayName) => {
this._errorReporterTimeout = defer(
this.setState.bind(this),
{error, errorType: ERROR_TYPES.runtime}
);
};
default: throw new Error(`Cannot find module "${path}"`);
}
};
try {
var {code} = babel.transform(appSource, {
filename: 'RelayPlayground',
plugins : [
babelRelayPlaygroundPlugin,
this._babelRelayPlugin,
errorCatcherPlugin('reporterProxy'),
],
retainLines: true,
sourceMaps: 'inline',
stage: 0,
});
var result = eval(code);
if (
React.isValidElement(result) &&
result.type.name === 'RelayRootContainer'
) {
this.setState({
appElement: React.cloneElement(result, {forceFetch: true}),
});
} else {
this.setState({
appElement: (
<div>
<h2>
Render a Relay.RootContainer into <code>mountNode</code> to get
started.
</h2>
<p>
Example:
</p>
<pre>{RENDER_STEP_EXAMPLE_CODE}</pre>
</div>
),
});
}
this.setState({error: null});
} catch(error) {
this.setState({error, errorType: ERROR_TYPES.syntax});
}
this.setState({busy: false});
}
_updateCode = (newSource) => {
var sourceStorageKey = `${this.state.editTarget}Source`;
this.setState({[sourceStorageKey]: newSource});
if (this.state.editTarget === 'app' && this.props.onAppSourceChange) {
this.props.onAppSourceChange(newSource);
}
if (this.state.editTarget === 'schema' && this.props.onSchemaSourceChange) {
this.props.onSchemaSourceChange(newSource);
}
}
_updateEditTarget = (editTarget) => {
this.setState({editTarget});
}
_updateSchema = (schemaSource, appSource) => {
try {
var Schema = evalSchema(schemaSource);
} catch(error) {
this.setState({error, errorType: ERROR_TYPES.schema});
return;
}
graphql(Schema, introspectionQuery).then((result) => {
if (
this.state.schemaSource !== schemaSource ||
this.state.appSource !== appSource
) {
// This version of the code is stale. Bail out.
return;
}
this._babelRelayPlugin = getBabelRelayPlugin(result.data);
Relay.injectNetworkLayer(
new RelayLocalSchema.NetworkLayer({
schema: Schema,
onError: (errors, request) => {
this.setState({
error: errorFromGraphQLResultAndQuery(errors, request),
errorType: ERROR_TYPES.query,
});
},
})
);
this._updateApp(appSource);
});
}
renderApp() {
if (!this.state.shouldExecuteCode) {
return (
<div className="rpExecutionGuard">
<div className="rpExecutionGuardMessage">
<h2>For your security, this playground did not auto-execute</h2>
<p>
Clicking <strong>execute</strong> will run the code in the two
tabs to the left.
</p>
<button onClick={this._handleExecuteClick}>Execute</button>
</div>
</div>
);
} else if (this.state.error) {
return (
<div className="rpError">
<h1>{this.state.errorType} Error</h1>
<pre className="rpErrorStack">{this.state.error.stack}</pre>
</div>
);
} else if (this.state.appElement) {
return <PlaygroundRenderer>{this.state.appElement}</PlaygroundRenderer>;
}
return null;
}
render() {
var sourceCode = this.state.editTarget === 'schema'
? this.state.schemaSource
: this.state.appSource;
return (
<div className="rpShell">
<section className="rpCodeEditor">
<nav className="rpCodeEditorNav">
<button
className={this.state.editTarget === 'app' && 'rpButtonActive'}
onClick={this._updateEditTarget.bind(this, 'app')}>
Code
</button>
<button
className={this.state.editTarget === 'schema' && 'rpButtonActive'}
onClick={this._updateEditTarget.bind(this, 'schema')}>
Schema
</button>
</nav>
{/* What is going on with the choice of key in Codemirror?
* https://github.com/JedWatson/react-codemirror/issues/12
*/}
<Codemirror
key={`${this.state.editTarget}-${this.state.shouldExecuteCode}`}
onChange={this._updateCode}
options={{
...CODE_EDITOR_OPTIONS,
readOnly: !this.state.shouldExecuteCode,
}}
value={sourceCode}
/>
</section>
<section className="rpResult">
<h1 className="rpResultHeader">
Relay Playground
<span className={
'rpActivity' + (this.state.busy ? ' rpActivityBusy' : '')
} />
</h1>
<div className="rpResultOutput">
{this.renderApp()}
</div>
</section>
</div>
);
}
}
|
src/componentOrElement.js | react-bootstrap/react-prop-types | import React from 'react';
import createChainableTypeChecker from './utils/createChainableTypeChecker';
function validate(props, propName, componentName, location, propFullName) {
const propValue = props[propName];
const propType = typeof propValue;
if (React.isValidElement(propValue)) {
return new Error(
`Invalid ${location} \`${propFullName}\` of type ReactElement ` +
`supplied to \`${componentName}\`, expected a ReactComponent or a ` +
'DOMElement. You can usually obtain a ReactComponent or DOMElement ' +
'from a ReactElement by attaching a ref to it.'
);
}
if (
(propType !== 'object' || typeof propValue.render !== 'function') &&
propValue.nodeType !== 1
) {
return new Error(
`Invalid ${location} \`${propFullName}\` of value \`${propValue}\` ` +
`supplied to \`${componentName}\`, expected a ReactComponent or a ` +
'DOMElement.'
);
}
return null;
}
export default createChainableTypeChecker(validate);
|
node_modules/react-router/es6/IndexRedirect.js | amybingzhao/savings-planner-web | import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import Redirect from './Redirect';
import { falsy } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes;
var string = _React$PropTypes.string;
var object = _React$PropTypes.object;
/**
* An <IndexRedirect> is used to redirect from an indexRoute.
*/
var IndexRedirect = React.createClass({
displayName: 'IndexRedirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = Redirect.createRouteFromReactElement(element);
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0;
}
}
},
propTypes: {
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default IndexRedirect; |
packages/ringcentral-widgets-docs/src/app/pages/Components/DropdownSelect/Demo.js | ringcentral/ringcentral-js-widget | import React, { Component } from 'react';
// eslint-disable-next-line
import DropdownSelect from 'ringcentral-widgets/components/DropdownSelect';
/**
* A example of `DropdownSelect`
*/
const options = [
{
display: 'Option1',
value: '1',
},
{
display: 'Option2',
value: '2',
},
];
class DropdownSelectDemo extends Component {
constructor(props) {
super(props);
this.state = {
value: '1',
};
}
onChange = (option) => {
this.setState({
value: option.value,
});
};
renderValue = (value) => {
const selected = options.find((option) => option.value === value);
return selected.display;
};
render() {
return (
<div>
<DropdownSelect
value={this.state.value}
options={options}
onChange={this.onChange}
renderFunction={(option) => option.display}
valueFunction={(option) => option.value}
renderValue={this.renderValue}
/>
<p>{`The value you selected is ${this.state.value}`}</p>
</div>
);
}
}
export default DropdownSelectDemo;
|
src/pages/settings.js | yamalight/bpjs-electron | // npm packages
import React from 'react';
import {Link} from 'react-router-dom';
// our packages
import PluginManager from '../api/index';
export default class Settings extends React.Component {
constructor() {
super();
this.state = {};
}
componentDidMount() {}
componentWillUnmount() {}
render() {
// const {series} = this.state;
return (
<div>
<nav className="nav">
<div className="nav-left nav-menu">
<div className="nav-item">
<Link to="/" className=" button">
<span className="icon">
<i className="fa fa-arrow-left" />
</span>
<span>Back</span>
</Link>
</div>
</div>
</nav>
<div className="content columns">
<div className="column">
{PluginManager.drawSettings()}
</div>
</div>
</div>
);
}
}
|
client/extensions/woocommerce/app/order/order-customer/index.js | Automattic/woocommerce-connect-client | /** @format */
/**
* External dependencies
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { localize } from 'i18n-calypso';
/**
* Internal dependencies
*/
import AddressView from 'woocommerce/components/address-view';
import Button from 'components/button';
import Card from 'components/card';
import CustomerAddressDialog from './dialog';
import {
areLocationsLoaded,
getAllCountries,
} from 'woocommerce/state/sites/data/locations/selectors';
import { editOrder } from 'woocommerce/state/ui/orders/actions';
import { fetchLocations } from 'woocommerce/state/sites/data/locations/actions';
import { isCurrentlyEditingOrder, getOrderWithEdits } from 'woocommerce/state/ui/orders/selectors';
import { isOrderFinished } from 'woocommerce/lib/order-status';
import getAddressViewFormat from 'woocommerce/lib/get-address-view-format';
import { getOrder } from 'woocommerce/state/sites/orders/selectors';
import { getSelectedSiteId } from 'state/ui/selectors';
import SectionHeader from 'components/section-header';
class OrderCustomerInfo extends Component {
static propTypes = {
countries: PropTypes.arrayOf(
PropTypes.shape( {
code: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
states: PropTypes.arrayOf(
PropTypes.shape( {
code: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
} )
),
} )
),
editOrder: PropTypes.func.isRequired,
isEditing: PropTypes.bool,
loadedLocations: PropTypes.bool,
orderId: PropTypes.oneOfType( [
PropTypes.number, // A number indicates an existing order
PropTypes.shape( { id: PropTypes.string } ), // Placeholders have format { id: 'order_1' }
] ).isRequired,
order: PropTypes.shape( {
billing: PropTypes.object.isRequired,
shipping: PropTypes.object.isRequired,
} ),
siteId: PropTypes.number.isRequired,
};
state = {
showDialog: false,
};
maybeFetchLocations = () => {
const { loadedLocations, siteId } = this.props;
if ( siteId && ! loadedLocations ) {
this.props.fetchLocations( siteId );
}
};
componentDidMount = () => {
this.maybeFetchLocations( this.props );
};
componentDidUpdate = () => {
this.maybeFetchLocations( this.props );
};
updateAddress = ( type = 'billing' ) => {
const { siteId, order } = this.props;
return address => {
const { copyToShipping = false, ...newAddress } = address;
if ( siteId ) {
this.props.editOrder( siteId, { id: order.id, [ type ]: newAddress } );
if ( copyToShipping && 'billing' === type ) {
this.props.editOrder( siteId, { id: order.id, shipping: newAddress } );
}
}
};
};
toggleDialog = type => {
return () => {
this.setState( { showDialog: type } );
};
};
renderDialogs = () => {
const { siteId } = this.props;
const { billing, shipping } = this.props.order;
return [
<CustomerAddressDialog
key="dialog-billing"
address={ billing }
closeDialog={ this.toggleDialog( false ) }
isBilling
isVisible={ 'billing' === this.state.showDialog }
siteId={ siteId }
updateAddress={ this.updateAddress( 'billing' ) }
/>,
<CustomerAddressDialog
key="dialog-shipping"
address={ shipping }
closeDialog={ this.toggleDialog( false ) }
isVisible={ 'shipping' === this.state.showDialog }
siteId={ siteId }
updateAddress={ this.updateAddress( 'shipping' ) }
/>,
];
};
render() {
const { countries, isEditing, loadedLocations, order, translate } = this.props;
if ( ! order || ! loadedLocations ) {
return null;
}
const { billing, shipping } = order;
const isEditable = isEditing && ! isOrderFinished( order.status );
return (
<div className="order-customer">
<SectionHeader label={ translate( 'Customer Information' ) } />
<Card>
<div className="order-customer__container">
<div className="order-customer__billing">
<h3 className="order-customer__billing-details">
{ translate( 'Billing Details' ) }
{ isEditable ? (
<Button
compact
className="order-customer__edit-link"
onClick={ this.toggleDialog( 'billing' ) }
borderless
>
{ translate( 'Edit' ) }
</Button>
) : null }
</h3>
<h4>{ translate( 'Address' ) }</h4>
<div className="order-customer__billing-address">
<p>{ `${ billing.first_name } ${ billing.last_name }` }</p>
<AddressView address={ getAddressViewFormat( billing ) } countries={ countries } />
</div>
<h4>{ translate( 'Email' ) }</h4>
<p>{ billing.email }</p>
<h4>{ translate( 'Phone' ) }</h4>
<span>{ billing.phone }</span>
</div>
<div className="order-customer__shipping">
<h3 className="order-customer__shipping-details">
{ translate( 'Shipping Details' ) }
{ isEditable ? (
<Button
compact
className="order-customer__edit-link"
onClick={ this.toggleDialog( 'shipping' ) }
borderless
>
{ translate( 'Edit' ) }
</Button>
) : null }
</h3>
<h4>{ translate( 'Address' ) }</h4>
<div className="order-customer__shipping-address">
<p>{ `${ shipping.first_name } ${ shipping.last_name }` }</p>
<AddressView address={ getAddressViewFormat( shipping ) } countries={ countries } />
</div>
</div>
</div>
</Card>
{ isEditing && this.renderDialogs() }
</div>
);
}
}
export default connect(
( state, props ) => {
const siteId = getSelectedSiteId( state );
const isEditing = isCurrentlyEditingOrder( state );
const order = isEditing ? getOrderWithEdits( state ) : getOrder( state, props.orderId );
const loadedLocations = areLocationsLoaded( state, siteId );
const countries = getAllCountries( state, siteId );
return {
countries,
isEditing,
loadedLocations,
order,
siteId,
};
},
dispatch => bindActionCreators( { editOrder, fetchLocations }, dispatch )
)( localize( OrderCustomerInfo ) );
|
src/shared/views/navigation/NavigationList/NavigationList.js | in-depth/indepth-demo | import React from 'react'
import { NavigationItem } from '../index'
import styles from './NavigationList.css'
import { navigationLinks } from '../../routes'
const NavigationList = () => {
return (
<ul className={styles.menu}>
{navigationLinks.map((navigationLink) => (
<NavigationItem
key={navigationLink.title} link={navigationLink.link}
title={navigationLink.title} icon={navigationLink.icon}
/>
))}
</ul>
)
}
export default NavigationList
|
src/index.js | jonashao/palm | import React from 'react';
import ReactDOM from 'react-dom';
import AV from 'leancloud-storage';
import Root from './containers/Root';
import configureStore from './store/configureStore'
import { appId, appKey } from './avconfig'
import { syncHistoryWithStore } from 'react-router-redux';
import { browserHistory } from 'react-router';
import 'semantic-ui-css/semantic.min.css';
import './css/index.css';
const store = configureStore()
const history = syncHistoryWithStore(browserHistory, store)
AV.init({
appId,
appKey
});
ReactDOM.render(< Root store={ store } history={ history } />, document.getElementById('root')); |
examples/with-atlaskit/components/ButtonComponent.js | flybayer/next.js | import React from 'react'
import Button, { ButtonGroup } from '@atlaskit/button'
export default function ButtonComponent() {
return (
<React.Fragment>
<Button style={{ margin: 10 }}>Button</Button>
<Button style={{ margin: 10 }} appearance="primary">
Primary Button
</Button>
<Button style={{ margin: 10 }} appearance="danger">
Danger Button
</Button>
<Button style={{ margin: 10 }} appearance="warning">
Warning Button
</Button>
<Button style={{ margin: 10 }} appearance="link">
Link Button
</Button>
<Button style={{ margin: 10 }} isDisabled>
Disabled Button
</Button>
<ButtonGroup appearance="primary">
<Button>First Button</Button>
<Button>Second Button</Button>
<Button>Third Button</Button>
</ButtonGroup>
</React.Fragment>
)
}
|
boxroom/archive/backup-js-bling-2018-04-28/boxroom/archive/js-surface-2018-01-27/boxroom/archive/2018-01-11/src/main/js-surface-react.js | mcjazzyfunky/js-surface | import adaptReactLikeComponentSystem from './adaption/adaptReactLikeComponentSystem';
import React from 'react';
import ReactDOM from 'react-dom';
function reactMount(content, targetNode) {
ReactDOM.render(content, targetNode);
return () => ReactDOM.unmountComponentAtNode(targetNode);
}
const {
createElement,
defineComponent,
isElement,
mount,
unmount,
Adapter,
Config
} = adaptReactLikeComponentSystem({
name: 'react',
api: { React, ReactDOM },
createElement: React.createElement,
createFactory: React.createFactory,
isValidElement: React.isValidElement,
mount: reactMount,
Component: React.Component,
browserBased: true
});
export {
createElement,
defineComponent,
isElement,
mount,
unmount,
Adapter,
Config
};
|
src/OptionGroup.js | jacycode/react-select-plus-2 | import React from 'react';
import classNames from 'classnames';
const OptionGroup = React.createClass({
propTypes: {
children: React.PropTypes.any,
className: React.PropTypes.string, // className (based on mouse position)
label: React.PropTypes.node, // the heading to show above the child options
option: React.PropTypes.object.isRequired, // object that is base for that option group
},
blockEvent (event) {
event.preventDefault();
event.stopPropagation();
if ((event.target.tagName !== 'A') || !('href' in event.target)) {
return;
}
if (event.target.target) {
window.open(event.target.href, event.target.target);
} else {
window.location.href = event.target.href;
}
},
handleMouseDown (event) {
event.preventDefault();
event.stopPropagation();
},
handleTouchEnd(event){
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if(this.dragging) return;
this.handleMouseDown(event);
},
handleTouchMove (event) {
// Set a flag that the view is being dragged
this.dragging = true;
},
handleTouchStart (event) {
// Set a flag that the view is not being dragged
this.dragging = false;
},
render () {
var { option } = this.props;
var className = classNames(this.props.className, option.className);
if(this.props.label == null){
var optiongroupLabel = null;
var optiongroupvalues = [];
this.props.option.options.forEach((val, ind)=>{
if(val.type == "label"){
optiongroupLabel = this.props.children[ind];
}else{
optiongroupvalues.push(this.props.children[ind]);
}
});
return <div className={className}
onMouseDown={this.blockEvent}
onClick={this.blockEvent}>
<div className="Select-option-group-label" style={{marginLeft:'-10px'}}>
{optiongroupLabel}
</div>
{optiongroupvalues}
</div>;
}else{
return option.disabled ? (
<div className={className}
onMouseDown={this.blockEvent}
onClick={this.blockEvent}>
{this.props.children}
</div>
) : (
<div className={className}
style={option.style}
onMouseDown={this.handleMouseDown}
onMouseEnter={this.handleMouseEnter}
onMouseMove={this.handleMouseMove}
onTouchStart={this.handleTouchStart}
onTouchMove={this.handleTouchMove}
onTouchEnd={this.handleTouchEnd}
title={option.title}>
<div className="Select-option-group-label">
{this.props.label}
</div>
{this.props.children}
</div>
);
}
}
});
module.exports = OptionGroup;
|
postgraphiql/src/components/PostGraphiQL.js | calebmer/postgraphql | import React from 'react';
import GraphiQL from 'graphiql';
import { getOperationAST, parse } from 'graphql';
import GraphiQLExplorer from 'graphiql-explorer';
import StorageAPI from 'graphiql/dist/utility/StorageAPI';
import './postgraphiql.css';
import { buildClientSchema, getIntrospectionQuery, isType, GraphQLObjectType } from 'graphql';
import { SubscriptionClient } from 'subscriptions-transport-ws';
import { createClient } from 'graphql-ws';
import formatSQL from '../formatSQL';
const defaultQuery = `\
# Welcome to PostGraphile's built-in GraphiQL IDE
#
# GraphiQL is an in-browser tool for writing, validating, and
# testing GraphQL queries.
#
# Type queries into this side of the screen, and you will see intelligent
# typeaheads aware of the current GraphQL type schema and live syntax and
# validation errors highlighted within the text.
#
# GraphQL queries typically start with a "{" character. Lines that starts
# with a # are ignored.
#
# An example GraphQL query might look like:
#
# {
# field(arg: "value") {
# subField
# }
# }
#
# Keyboard shortcuts:
#
# Prettify Query: Shift-Ctrl-P (or press the prettify button above)
#
# Merge Query: Shift-Ctrl-M (or press the merge button above)
#
# Run Query: Ctrl-Enter (or press the play button above)
#
# Auto Complete: Ctrl-Space (or just start typing)
#
`;
const isSubscription = ({ query, operationName }) => {
const node = parse(query);
const operation = getOperationAST(node, operationName);
return operation && operation.operation === 'subscription';
};
const {
POSTGRAPHILE_CONFIG = {
graphqlUrl: 'http://localhost:5000/graphql',
streamUrl: 'http://localhost:5000/graphql/stream',
enhanceGraphiql: true,
websockets: 'none', // 'none' | 'v0' | 'v1'
allowExplain: true,
credentials: 'same-origin',
},
} = window;
const isValidJSON = json => {
try {
JSON.parse(json);
return true;
} catch (e) {
return false;
}
};
const l = window.location;
const websocketUrl = POSTGRAPHILE_CONFIG.graphqlUrl.match(/^https?:/)
? POSTGRAPHILE_CONFIG.graphqlUrl.replace(/^http/, 'ws')
: `ws${l.protocol === 'https:' ? 's' : ''}://${l.hostname}${
l.port !== 80 && l.port !== 443 ? ':' + l.port : ''
}${POSTGRAPHILE_CONFIG.graphqlUrl}`;
const STORAGE_KEYS = {
SAVE_HEADERS_TEXT: 'PostGraphiQL:saveHeadersText',
HEADERS_TEXT: 'PostGraphiQL:headersText',
EXPLAIN: 'PostGraphiQL:explain',
};
/**
* The standard GraphiQL interface wrapped with some PostGraphile extensions.
* Including a JWT setter and live schema udpate capabilities.
*/
class PostGraphiQL extends React.PureComponent {
// Use same storage as GraphiQL to save explorer visibility state
_storage = new StorageAPI();
state = {
// Our GraphQL schema which GraphiQL will use to do its intelligence
// stuffs.
schema: null,
query: '',
showHeaderEditor: false,
saveHeadersText: this._storage.get(STORAGE_KEYS.SAVE_HEADERS_TEXT) === 'true',
headersText: this._storage.get(STORAGE_KEYS.HEADERS_TEXT) || '{\n"Authorization": null\n}\n',
explain: this._storage.get(STORAGE_KEYS.EXPLAIN) === 'true',
explainResult: null,
headersTextValid: true,
explorerIsOpen: this._storage.get('explorerIsOpen') === 'false' ? false : true,
haveActiveSubscription: false,
socketStatus: POSTGRAPHILE_CONFIG.websockets === 'none' ? null : 'pending',
};
restartRequested = false;
restartSubscriptionsClient = () => {
// implementation will be replaced...
this.restartRequested = true;
};
maybeSubscriptionsClient = () => {
switch (POSTGRAPHILE_CONFIG.websockets) {
case 'none':
return;
case 'v0':
const client = new SubscriptionClient(websocketUrl, {
reconnect: true,
connectionParams: () => this.getHeaders() || {},
});
const unlisten1 = client.on('connected', () => {
this.setState({ socketStatus: 'connected', error: null });
});
const unlisten2 = client.on('disconnected', () => {
this.setState({ socketStatus: 'closed', error: new Error('Socket disconnected') });
});
const unlisten3 = client.on('connecting', () => {
this.setState({ socketStatus: 'connecting' });
});
const unlisten4 = client.on('reconnected', () => {
this.setState({ socketStatus: 'connected', error: null });
});
const unlisten5 = client.on('reconnecting', () => {
this.setState({ socketStatus: 'connecting' });
});
const unlisten6 = client.on('error', error => {
// tslint:disable-next-line no-console
console.error('Client connection error', error);
this.setState({ error: new Error('Subscriptions client connection error') });
});
this.unlistenV0SubscriptionsClient = () => {
unlisten1();
unlisten2();
unlisten3();
unlisten4();
unlisten5();
unlisten6();
};
// restart by closing the socket which should trigger a silent reconnect
this.restartSubscriptionsClient = () => {
this.subscriptionsClient.close(false, true);
};
// if any restarts were missed during the connection
// phase, restart and reset the request
if (this.restartRequested) {
this.restartRequested = false;
this.restartSubscriptionsClient();
}
return client;
case 'v1':
return createClient({
url: websocketUrl,
lazy: false,
retryAttempts: Infinity, // keep retrying while the browser is open
connectionParams: () => this.getHeaders() || {},
on: {
connecting: () => {
this.setState({ socketStatus: 'connecting' });
},
connected: socket => {
this.setState({ socketStatus: 'connected', error: null });
// restart by closing the socket which will trigger a silent reconnect
this.restartSubscriptionsClient = () => {
if (socket.readyState === WebSocket.OPEN) {
socket.close(4205, 'Client Restart');
}
};
// if any restarts were missed during the connection
// phase, restart and reset the request
if (this.restartRequested) {
this.restartRequested = false;
this.restartSubscriptionsClient();
}
},
closed: closeEvent => {
this.setState({
socketStatus: 'closed',
error: new Error(`Socket closed with ${closeEvent.code} ${closeEvent.reason}`),
});
},
},
});
default:
throw new Error(`Invalid websockets argument ${POSTGRAPHILE_CONFIG.websockets}`);
}
};
activeSubscription = null;
componentDidMount() {
// Update the schema for the first time. Log an error if we fail.
this.updateSchema();
// Connect socket if should connect
this.subscriptionsClient = this.maybeSubscriptionsClient();
// If we were given a `streamUrl`, we want to construct an `EventSource`
// and add listeners.
if (POSTGRAPHILE_CONFIG.streamUrl) {
// Starts listening to the event stream at the `sourceUrl`.
const eventSource = new EventSource(POSTGRAPHILE_CONFIG.streamUrl);
// When we get a change notification, we want to update our schema.
eventSource.addEventListener(
'change',
() => {
this.updateSchema();
},
false,
);
// Add event listeners that just log things in the console.
eventSource.addEventListener(
'open',
() => {
// tslint:disable-next-line no-console
console.log('PostGraphile: Listening for server sent events');
this.setState({ error: null });
this.updateSchema();
},
false,
);
eventSource.addEventListener(
'error',
error => {
// tslint:disable-next-line no-console
console.error('PostGraphile: Failed to connect to event stream', error);
this.setState({ error: new Error('Failed to connect to event stream') });
},
false,
);
// Store our event source so we can unsubscribe later.
this._eventSource = eventSource;
}
const graphiql = this.graphiql;
this.setState({ query: graphiql._storage.get('query') || defaultQuery });
const editor = graphiql.getQueryEditor();
editor.setOption('extraKeys', {
...(editor.options.extraKeys || {}),
'Shift-Alt-LeftClick': this._handleInspectOperation,
});
}
componentWillUnmount() {
// Dispose of connection if available
if (this.subscriptionsClient) {
if (this.unlistenV0SubscriptionsClient) {
// v0
this.unlistenV0SubscriptionsClient();
} else {
// v1
this.subscriptionsClient.dispose();
}
this.subscriptionsClient = null;
}
// Close out our event source so we get no more events.
this._eventSource.close();
this._eventSource = null;
}
_handleInspectOperation = (cm, mousePos) => {
const parsedQuery = parse(this.state.query || '');
if (!parsedQuery) {
console.error("Couldn't parse query document");
return null;
}
var token = cm.getTokenAt(mousePos);
var start = { line: mousePos.line, ch: token.start };
var end = { line: mousePos.line, ch: token.end };
var relevantMousePos = {
start: cm.indexFromPos(start),
end: cm.indexFromPos(end),
};
var position = relevantMousePos;
var def = parsedQuery.definitions.find(definition => {
if (!definition.loc) {
console.log('Missing location information for definition');
return false;
}
const { start, end } = definition.loc;
return start <= position.start && end >= position.end;
});
if (!def) {
console.error('Unable to find definition corresponding to mouse position');
return null;
}
var operationKind =
def.kind === 'OperationDefinition'
? def.operation
: def.kind === 'FragmentDefinition'
? 'fragment'
: 'unknown';
var operationName =
def.kind === 'OperationDefinition' && !!def.name
? def.name.value
: def.kind === 'FragmentDefinition' && !!def.name
? def.name.value
: 'unknown';
var selector = `.graphiql-explorer-root #${operationKind}-${operationName}`;
var el = document.querySelector(selector);
el && el.scrollIntoView();
};
cancelSubscription = () => {
if (this.activeSubscription !== null) {
this.activeSubscription.unsubscribe();
this.setState({
haveActiveSubscription: false,
});
}
};
/**
* Get the user editable headers as an object
*/
getHeaders = () => {
const { headersText } = this.state;
let extraHeaders;
try {
extraHeaders = JSON.parse(headersText);
for (const k in extraHeaders) {
if (extraHeaders[k] == null) {
delete extraHeaders[k];
}
}
} catch (e) {
// Do nothing
}
return extraHeaders;
};
/**
* Executes a GraphQL query with some extra information then the standard
* parameters. Namely a JWT which may be added as an `Authorization` header.
*/
executeQuery = async graphQLParams => {
const extraHeaders = this.getHeaders();
const response = await fetch(POSTGRAPHILE_CONFIG.graphqlUrl, {
method: 'POST',
headers: Object.assign(
{
Accept: 'application/json',
'Content-Type': 'application/json',
...(this.state.explain && POSTGRAPHILE_CONFIG.allowExplain
? { 'X-PostGraphile-Explain': 'on' }
: null),
},
extraHeaders,
),
credentials: POSTGRAPHILE_CONFIG.credentials,
body: JSON.stringify(graphQLParams),
});
const result = await response.json();
this.setState({ explainResult: result && result.explain ? result.explain : null });
return result;
};
/**
* Routes the request either to the subscriptionClient or to executeQuery.
*/
fetcher = graphQLParams => {
this.cancelSubscription();
if (isSubscription(graphQLParams) && this.subscriptionsClient) {
const client = this.subscriptionsClient;
return {
subscribe: observer => {
setTimeout(() => {
// Without this timeout, this message doesn't display on the first
// subscription after the first render of the page.
observer.next('Waiting for subscription to yield data…');
}, 0);
const subscription =
POSTGRAPHILE_CONFIG.websockets === 'v0'
? client.request(graphQLParams).subscribe(observer)
: // v1
{
unsubscribe: client.subscribe(graphQLParams, {
next: observer.next,
complete: observer.complete,
error: err => {
if (err instanceof Error) {
observer.error(err);
} else if (err instanceof CloseEvent) {
observer.error(
new Error(
`Socket closed with event ${err.code}` + err.reason
? `: ${err.reason}` // reason will be available on clean closes
: '',
),
);
} else {
// GraphQLError[]
observer.error(new Error(err.map(({ message }) => message).join(', ')));
}
},
}),
};
this.setState({ haveActiveSubscription: true });
this.activeSubscription = subscription;
return subscription;
},
};
} else {
return this.executeQuery(graphQLParams);
}
};
/**
* When we recieve an event signaling a change for the schema, we must rerun
* our introspection query and notify the user of the results.
*/
// TODO: Send the introspection query results in the server sent event?
async updateSchema() {
try {
// Fetch the schema using our introspection query and report once that has
// finished.
const { data } = await this.executeQuery({ query: getIntrospectionQuery() });
// Use the data we got back from GraphQL to build a client schema (a
// schema without resolvers).
const schema = buildClientSchema(data);
// Update our component with the new schema.
this.setState({ schema });
// Do some hacky stuff to GraphiQL.
this._updateGraphiQLDocExplorerNavStack(schema);
// tslint:disable-next-line no-console
console.log('PostGraphile: Schema updated');
this.setState({ error: null });
} catch (error) {
// tslint:disable-next-line no-console
console.error('Error occurred when updating the schema:');
// tslint:disable-next-line no-console
console.error(error);
this.setState({ error });
}
}
/**
* Updates the GraphiQL documentation explorer’s navigation stack. This
* depends on private API. By default the GraphiQL navigation stack uses
* objects from a GraphQL schema. Therefore if the schema is updated, the
* old objects will still be in the navigation stack. This is bad for us
* because we want to reflect the new schema information! So, we manually
* update the navigation stack with this function.
*
* I’m sorry Lee Byron.
*/
// TODO: Submit a PR which adds this as a non-hack.
_updateGraphiQLDocExplorerNavStack(nextSchema) {
// Get the documentation explorer component from GraphiQL. Unfortunately
// for them this looks like public API. Muwahahahaha.
const { docExplorerComponent } = this.graphiql;
if (!docExplorerComponent) {
console.log('No docExplorerComponent, could not update navStack');
return;
}
const { navStack } = docExplorerComponent.state;
// If one type/field isn’t find this will be set to false and the
// `navStack` will just reset itself.
let allOk = true;
let exitEarly = false;
// Ok, so if you look at GraphiQL source code, the `navStack` is made up of
// objects that are either types or fields. Let’s use that to search in
// our new schema for matching (updated) types and fields.
const nextNavStack = navStack
.map((navStackItem, i) => {
// If we are not ok, abort!
if (exitEarly || !allOk) return null;
// Get the definition from the nav stack item.
const typeOrField = navStackItem.def;
// If there is no type or field then this is likely the root schema view,
// or a search. If this is the case then just return that nav stack item!
if (!typeOrField) {
return navStackItem;
} else if (isType(typeOrField)) {
// If this is a type, let’s do some shenanigans...
// Let’s see if we can get a type with the same name.
const nextType = nextSchema.getType(typeOrField.name);
// If there is no type with this name (it was removed), we are not ok
// so set `allOk` to false and return undefined.
if (!nextType) {
exitEarly = true;
return null;
}
// If there is a type with the same name, let’s return it! This is the
// new type with all our new information.
return { ...navStackItem, def: nextType };
} else {
// If you thought this function was already pretty bad, it’s about to get
// worse. We want to update the information for an object field.
// Ok, so since this is an object field, we will assume that the last
// element in our stack was an object type.
const nextLastType = nextSchema.getType(navStack[i - 1] ? navStack[i - 1].name : null);
// If there is no type for the last type in the nav stack’s name.
// Panic!
if (!nextLastType) {
allOk = false;
return null;
}
// If the last type is not an object type. Panic!
if (!(nextLastType instanceof GraphQLObjectType)) {
allOk = false;
return null;
}
// Next we will see if the new field exists in the last object type.
const nextField = nextLastType.getFields()[typeOrField.name];
// If not, Panic!
if (!nextField) {
allOk = false;
return null;
}
// Otherwise we hope very much that it is correct.
return { ...navStackItem, def: nextField };
}
})
.filter(_ => _);
// This is very hacky but works. React is cool.
if (allOk) {
this.graphiql.docExplorerComponent.setState({
// If we are not ok, just reset the `navStack` with an empty array.
// Otherwise use our new stack.
navStack: nextNavStack,
});
}
}
getQueryEditor = () => {
return this.graphiql.getQueryEditor();
};
handleEditQuery = query => {
this.setState({ query });
};
handleEditHeaders = headersText => {
this.setState(
{
headersText,
headersTextValid: isValidJSON(headersText),
},
() => {
if (this.state.headersTextValid && this.state.saveHeadersText) {
this._storage.set(STORAGE_KEYS.HEADERS_TEXT, this.state.headersText);
}
if (this.state.headersTextValid && this.subscriptionsClient) {
// Reconnect to websocket with new headers
this.restartSubscriptionsClient();
}
},
);
};
handlePrettifyQuery = () => {
const editor = this.getQueryEditor();
if (typeof window.prettier !== 'undefined' && typeof window.prettierPlugins !== 'undefined') {
// TODO: window.prettier.formatWithCursor
editor.setValue(
window.prettier.format(editor.getValue(), {
parser: 'graphql',
plugins: window.prettierPlugins,
}),
);
} else {
return this.graphiql.handlePrettifyQuery();
}
};
handleToggleHistory = e => {
this.graphiql.handleToggleHistory(e);
};
handleToggleHeaders = () => {
this.setState({ showHeaderEditor: !this.state.showHeaderEditor });
};
handleToggleExplorer = () => {
this.setState({ explorerIsOpen: !this.state.explorerIsOpen }, () =>
this._storage.set(
'explorerIsOpen',
// stringify so that storage API will store the state (it deletes key if value is false)
JSON.stringify(this.state.explorerIsOpen),
),
);
};
handleToggleSaveHeaders = () => {
this.setState(
oldState => ({ saveHeadersText: !oldState.saveHeadersText }),
() => {
this._storage.set(
STORAGE_KEYS.SAVE_HEADERS_TEXT,
JSON.stringify(this.state.saveHeadersText),
);
this._storage.set(
STORAGE_KEYS.HEADERS_TEXT,
this.state.saveHeadersText ? this.state.headersText : '',
);
},
);
};
handleToggleExplain = () => {
this.setState(
oldState => ({ explain: !oldState.explain }),
() => {
this._storage.set(STORAGE_KEYS.EXPLAIN, JSON.stringify(this.state.explain));
try {
this.graphiql.handleRunQuery();
} catch (e) {
/* ignore */
}
},
);
};
renderSocketStatus() {
const { socketStatus, error } = this.state;
if (socketStatus === null) {
return null;
}
const icon =
{
connecting: '🤔',
connected: '😀',
closed: '☹️',
}[socketStatus] || '😐';
const tick = (
<path fill="transparent" stroke="white" d="M30,50 L45,65 L70,30" strokeWidth="8" />
);
const cross = (
<path fill="transparent" stroke="white" d="M30,30 L70,70 M30,70 L70,30" strokeWidth="8" />
);
const decoration =
{
connecting: null,
connected: tick,
closed: cross,
}[socketStatus] || null;
const color =
{
connected: 'green',
connecting: 'orange',
closed: 'red',
}[socketStatus] || 'gray';
const svg = (
<svg width="25" height="25" viewBox="0 0 100 100" style={{ marginTop: 4 }}>
<circle fill={color} cx="50" cy="50" r="45" />
{decoration}
</svg>
);
return (
<>
{error ? (
<div
style={{ fontSize: '1.5em', marginRight: '0.25em' }}
title={error.message || `Error occurred: ${error}`}
onClick={() => this.setState({ error: null })}
>
<span aria-label="ERROR" role="img">
{'⚠️'}
</span>
</div>
) : null}
<div
style={{ fontSize: '1.5em', marginRight: '0.25em' }}
title={'Websocket status: ' + socketStatus}
onClick={this.cancelSubscription}
>
<span aria-label={socketStatus} role="img">
{svg || icon}
</span>
</div>
</>
);
}
setGraphiqlRef = ref => {
if (!ref) {
return;
}
this.graphiql = ref;
this.setState({ mounted: true });
};
render() {
const { schema } = this.state;
const sharedProps = {
ref: this.setGraphiqlRef,
schema: schema,
fetcher: this.fetcher,
};
if (!POSTGRAPHILE_CONFIG.enhanceGraphiql) {
return <GraphiQL {...sharedProps} />;
} else {
return (
<div
className={`postgraphiql-container graphiql-container ${
this.state.explain && this.state.explainResult && this.state.explainResult.length
? 'explain-mode'
: ''
}`}
>
<GraphiQLExplorer
schema={schema}
query={this.state.query}
onEdit={this.handleEditQuery}
onRunOperation={operationName => this.graphiql.handleRunQuery(operationName)}
explorerIsOpen={this.state.explorerIsOpen}
onToggleExplorer={this.handleToggleExplorer}
//getDefaultScalarArgValue={getDefaultScalarArgValue}
//makeDefaultArg={makeDefaultArg}
/>
<GraphiQL
onEditQuery={this.handleEditQuery}
query={this.state.query}
headerEditorEnabled
headers={this.state.headersText}
onEditHeaders={this.handleEditHeaders}
{...sharedProps}
>
<GraphiQL.Logo>
<div style={{ display: 'flex', alignItems: 'center' }}>
<div>
<img
alt="PostGraphile logo"
src="https://www.graphile.org/images/postgraphile-tiny.optimized.svg"
width="32"
height="32"
style={{ marginTop: '4px', marginRight: '0.5rem' }}
/>
</div>
<div>
PostGraph
<em>i</em>
QL
</div>
</div>
</GraphiQL.Logo>
<GraphiQL.Toolbar>
{this.renderSocketStatus()}
<GraphiQL.Button
onClick={this.handlePrettifyQuery}
title="Prettify Query (Shift-Ctrl-P)"
label="Prettify"
/>
<GraphiQL.Button
onClick={this.handleToggleHistory}
title="Show History"
label="History"
/>
<GraphiQL.Button
label="Explorer"
title="Construct a query with the GraphiQL explorer"
onClick={this.handleToggleExplorer}
/>
<GraphiQL.Button
onClick={this.graphiql && this.graphiql.handleMergeQuery}
title="Merge Query (Shift-Ctrl-M)"
label="Merge"
/>
<GraphiQL.Button
onClick={this.graphiql && this.graphiql.handleCopyQuery}
title="Copy Query (Shift-Ctrl-C)"
label="Copy"
/>
{POSTGRAPHILE_CONFIG.allowExplain ? (
<GraphiQL.Button
label={this.state.explain ? 'Explain ON' : 'Explain disabled'}
title="View the SQL statements that this query invokes"
onClick={this.handleToggleExplain}
/>
) : null}
<GraphiQL.Button
label={'Headers ' + (this.state.saveHeadersText ? 'SAVED' : 'unsaved')}
title="Should we persist the headers to localStorage? Header editor is next to variable editor at the bottom."
onClick={this.handleToggleSaveHeaders}
/>
</GraphiQL.Toolbar>
<GraphiQL.Footer>
<div className="postgraphile-footer">
{this.state.explainResult && this.state.explainResult.length ? (
<div className="postgraphile-plan-footer">
{this.state.explainResult.map(res => (
<div>
<h4>
Result from SQL{' '}
<a href="https://www.postgresql.org/docs/current/sql-explain.html">
EXPLAIN
</a>{' '}
on executed query:
</h4>
<pre className="explain-plan">
<code>{res.plan}</code>
</pre>
<h4>Executed SQL query:</h4>
<pre className="explain-sql">
<code>{formatSQL(res.query)}</code>
</pre>
</div>
))}
<p>
Having performance issues?{' '}
<a href="https://www.graphile.org/support/">We can help with that!</a>
</p>
<hr />
</div>
) : null}
<div className="postgraphile-regular-footer">
PostGraphile:{' '}
<a
title="Open PostGraphile documentation"
href="https://graphile.org/postgraphile/introduction/"
target="new"
>
Documentation
</a>{' '}
|{' '}
<a
title="Open PostGraphile documentation"
href="https://graphile.org/postgraphile/examples/"
target="new"
>
Examples
</a>{' '}
|{' '}
<a
title="PostGraphile is supported by the community, please sponsor ongoing development"
href="https://graphile.org/sponsor/"
target="new"
>
Sponsor
</a>{' '}
|{' '}
<a
title="Get support from the team behind PostGraphile"
href="https://graphile.org/support/"
target="new"
>
Support
</a>
</div>
</div>
</GraphiQL.Footer>
</GraphiQL>
</div>
);
}
}
}
export default PostGraphiQL;
|
react/features/display-name/components/web/DisplayNamePrompt.js | gpolitis/jitsi-meet | /* @flow */
import { FieldTextStateless as TextField } from '@atlaskit/field-text';
import React from 'react';
import { Dialog } from '../../../base/dialog';
import { translate } from '../../../base/i18n';
import { connect } from '../../../base/redux';
import AbstractDisplayNamePrompt, {
type Props
} from '../AbstractDisplayNamePrompt';
/**
* The type of the React {@code Component} props of {@link DisplayNamePrompt}.
*/
type State = {
/**
* The name to show in the display name text field.
*/
displayName: string
};
/**
* Implements a React {@code Component} for displaying a dialog with an field
* for setting the local participant's display name.
*
* @augments Component
*/
class DisplayNamePrompt extends AbstractDisplayNamePrompt<State> {
/**
* Initializes a new {@code DisplayNamePrompt} instance.
*
* @param {Object} props - The read-only properties with which the new
* instance is to be initialized.
*/
constructor(props: Props) {
super(props);
this.state = {
displayName: ''
};
// Bind event handlers so they are only bound once for every instance.
this._onDisplayNameChange = this._onDisplayNameChange.bind(this);
this._onSubmit = this._onSubmit.bind(this);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
return (
<Dialog
isModal = { false }
onSubmit = { this._onSubmit }
titleKey = 'dialog.displayNameRequired'
width = 'small'>
<TextField
autoFocus = { true }
compact = { true }
label = { this.props.t('dialog.enterDisplayName') }
name = 'displayName'
onChange = { this._onDisplayNameChange }
shouldFitContainer = { true }
type = 'text'
value = { this.state.displayName } />
</Dialog>);
}
_onDisplayNameChange: (Object) => void;
/**
* Updates the entered display name.
*
* @param {Object} event - The DOM event triggered from the entered display
* name value having changed.
* @private
* @returns {void}
*/
_onDisplayNameChange(event) {
this.setState({
displayName: event.target.value
});
}
_onSetDisplayName: string => boolean;
_onSubmit: () => boolean;
/**
* Dispatches an action to update the local participant's display name. A
* name must be entered for the action to dispatch.
*
* @private
* @returns {boolean}
*/
_onSubmit() {
return this._onSetDisplayName(this.state.displayName);
}
}
export default translate(connect()(DisplayNamePrompt));
|
src/containers/Info.js | gorand/redux_test | import React, { Component } from 'react';
class Info extends Component {
render() {
return (
<p>Реализация редактора заметок с помощью стека React + Redux + React-Router
<br />
Данные сохраняются в LocalStorage
</p>
);
}
}
export default Info;
|
app/packs/src/components/ReactionDetailsContainers.js | ComPlat/chemotion_ELN | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
PanelGroup,
Panel,
Button,
OverlayTrigger, SplitButton, ButtonGroup, MenuItem, Tooltip
} from 'react-bootstrap';
import Container from './models/Container';
import ContainerComponent from './ContainerComponent';
import PrintCodeButton from './common/PrintCodeButton';
import QuillViewer from './QuillViewer';
import ImageModal from './common/ImageModal';
import { hNmrCount, cNmrCount, instrumentText } from './utils/ElementUtils';
import { contentToText } from './utils/quillFormat';
import { chmoConversions } from './OlsComponent';
import { previewContainerImage } from './utils/imageHelper';
import { JcampIds, BuildSpcInfos } from './utils/SpectraHelper';
import UIStore from './stores/UIStore';
import SpectraActions from './actions/SpectraActions';
import LoadingActions from './actions/LoadingActions';
import ViewSpectra from './ViewSpectra';
import TextTemplateActions from './actions/TextTemplateActions';
const nmrMsg = (reaction, container) => {
if (container.extended_metadata &&
(typeof container.extended_metadata.kind === 'undefined' ||
(container.extended_metadata.kind.split('|')[0].trim() !== chmoConversions.nmr_1h.termId && container.extended_metadata.kind.split('|')[0].trim() !== chmoConversions.nmr_13c.termId)
)) {
return '';
}
const nmrStr = container.extended_metadata && contentToText(container.extended_metadata.content);
if ((container.extended_metadata.kind || '').split('|')[0].trim() === chmoConversions.nmr_1h.termId) {
const msg = hNmrCount(nmrStr);
return (<div style={{ display: 'inline', color: 'black' }}> (<sup>1</sup>H: {msg})</div>);
} else if ((container.extended_metadata.kind || '').split('|')[0].trim() === chmoConversions.nmr_13c.termId) {
const msg = cNmrCount(nmrStr);
return (<div style={{ display: 'inline', color: 'black' }}> (<sup>13</sup>C: {msg})</div>);
}
};
const SpectraEditorBtn = ({
element, spcInfo, hasJcamp, hasChemSpectra,
toggleSpectraModal, confirmRegenerate,
}) => (
<OverlayTrigger
placement="bottom"
delayShow={500}
overlay={<Tooltip id="spectra">Spectra Editor {!spcInfo ? ': Reprocess' : ''}</Tooltip>}
>{spcInfo ? (
<ButtonGroup className="button-right">
<SplitButton
id="spectra-editor-split-button"
pullRight
bsStyle="info"
bsSize="xsmall"
title={<i className="fa fa-area-chart" />}
onToggle={(open, event) => { if (event) { event.stopPropagation(); } }}
onClick={toggleSpectraModal}
disabled={!spcInfo || !hasChemSpectra}
>
<MenuItem
id="regenerate-spectra"
key="regenerate-spectra"
onSelect={(eventKey, event) => {
event.stopPropagation();
confirmRegenerate(event);
}}
disabled={!hasJcamp || !element.can_update}
>
<i className="fa fa-refresh" /> Reprocess
</MenuItem>
</SplitButton>
</ButtonGroup>
) : (
<Button
bsStyle="warning"
bsSize="xsmall"
className="button-right"
onClick={confirmRegenerate}
disabled={false}
>
<i className="fa fa-area-chart" /><i className="fa fa-refresh " />
</Button>
)}
</OverlayTrigger>
);
SpectraEditorBtn.propTypes = {
element: PropTypes.object,
hasJcamp: PropTypes.bool,
spcInfo: PropTypes.oneOfType([
PropTypes.object,
PropTypes.bool,
]),
hasChemSpectra: PropTypes.bool,
toggleSpectraModal: PropTypes.func.isRequired,
confirmRegenerate: PropTypes.func.isRequired,
};
SpectraEditorBtn.defaultProps = {
hasJcamp: false,
spcInfo: false,
element: {},
hasChemSpectra: false,
};
export default class ReactionDetailsContainers extends Component {
constructor(props) {
super();
const { reaction } = props;
this.state = {
reaction,
activeContainer: 0
};
this.handleChange = this.handleChange.bind(this);
this.handleAdd = this.handleAdd.bind(this);
this.handleRemove = this.handleRemove.bind(this);
this.handleUndo = this.handleUndo.bind(this);
this.handleOnClickRemove = this.handleOnClickRemove.bind(this);
this.handleAccordionOpen = this.handleAccordionOpen.bind(this);
this.handleSpChange = this.handleSpChange.bind(this);
}
componentDidMount() {
TextTemplateActions.fetchTextTemplates('reaction');
}
// eslint-disable-next-line camelcase
UNSAFE_componentWillReceiveProps(nextProps) {
this.setState({
reaction: nextProps.reaction,
});
}
handleChange(container) {
const { reaction } = this.state;
this.props.parent.handleReactionChange(reaction);
}
handleSpChange(reaction, cb) {
this.props.parent.handleReactionChange(reaction);
cb();
}
handleUndo(container) {
const { reaction } = this.state;
container.is_deleted = false;
this.props.parent.handleReactionChange(reaction, { schemaChanged: false });
}
handleAdd() {
const { reaction } = this.state;
const container = Container.buildEmpty();
container.container_type = 'analysis';
container.extended_metadata.content = { ops: [{ insert: '' }] };
if (reaction.container.children.length === 0) {
const analyses = Container.buildEmpty();
analyses.container_type = 'analyses';
reaction.container.children.push(analyses);
}
reaction.container.children.filter(element => (
~element.container_type.indexOf('analyses')
))[0].children.push(container);
const newKey = reaction.container.children.filter(element => (
~element.container_type.indexOf('analyses')
))[0].children.length - 1;
this.handleAccordionOpen(newKey);
this.props.parent.handleReactionChange(reaction, { schemaChanged: false });
}
handleOnClickRemove(container) {
if (confirm('Delete the container?')) {
this.handleRemove(container);
}
}
headerBtnGroup(container, reaction, readOnly) {
const jcampIds = JcampIds(container);
const hasJcamp = jcampIds.orig.length > 0;
const confirmRegenerate = (e) => {
e.stopPropagation();
if (confirm('Regenerate spectra?')) {
LoadingActions.start();
SpectraActions.Regenerate(jcampIds, this.handleChange);
}
};
const spcInfo = BuildSpcInfos(reaction, container);
const { hasChemSpectra } = UIStore.getState();
const toggleSpectraModal = (e) => {
e.stopPropagation();
SpectraActions.ToggleModal();
SpectraActions.LoadSpectra.defer(spcInfo);
};
return (
<div className="upper-btn">
<Button
bsSize="xsmall"
bsStyle="danger"
className="button-right"
disabled={readOnly}
onClick={() => this.handleOnClickRemove(container)}
>
<i className="fa fa-trash" />
</Button>
<PrintCodeButton element={reaction} analyses={[container]} ident={container.id} />
<SpectraEditorBtn
element={reaction}
hasJcamp={hasJcamp}
spcInfo={spcInfo}
hasChemSpectra={hasChemSpectra}
toggleSpectraModal={toggleSpectraModal}
confirmRegenerate={confirmRegenerate}
/>
</div>
);
};
handleRemove(container) {
const { reaction } = this.state;
container.is_deleted = true;
this.props.parent.handleReactionChange(reaction, { schemaChanged: false });
}
handleAccordionOpen(key) {
this.setState({ activeContainer: key });
}
addButton() {
const { readOnly } = this.props;
if (!readOnly) {
return (
<Button
className="button-right"
bsSize="xsmall"
bsStyle="success"
onClick={this.handleAdd}
>
Add analysis
</Button>
);
}
return (<span />);
}
render() {
const { reaction, activeContainer } = this.state;
const { readOnly } = this.props;
const containerHeader = (container) => {
let kind = container.extended_metadata.kind || '';
kind = (kind.split('|')[1] || kind).trim();
const insText = instrumentText(container);
const previewImg = previewContainerImage(container);
const status = container.extended_metadata.status || '';
const content = container.extended_metadata.content || { ops: [{ insert: '' }] };
const contentOneLine = {
ops: content.ops.map((x) => {
const c = Object.assign({}, x);
if (c.insert) c.insert = c.insert.replace(/\n/g, ' ');
return c;
}),
};
let hasPop = true;
let fetchNeeded = false;
let fetchId = 0;
if (previewImg.startsWith('data:image')) {
fetchNeeded = true;
fetchId = container.preview_img.id;
} else {
hasPop = false;
}
return (
<div className="analysis-header order" style={{ width: '100%' }}>
<div className="preview">
<ImageModal
hasPop={hasPop}
previewObject={{
src: previewImg
}}
popObject={{
title: container.name,
src: previewImg,
fetchNeeded,
fetchId
}}
/>
</div>
<div className="abstract">
{
this.headerBtnGroup(container, reaction, readOnly)
}
<div className="lower-text">
<div className="main-title">{container.name}</div>
<div className="sub-title">Type: {kind}</div>
<div className="sub-title">Status: {status} {nmrMsg(reaction, container)} {insText}</div>
<div className="desc sub-title">
<span style={{ float: 'left', marginRight: '5px' }}>
Content:
</span>
<QuillViewer value={contentOneLine} />
</div>
</div>
</div>
</div>
)
};
const containerHeaderDeleted = (container) => {
const kind = container.extended_metadata.kind && container.extended_metadata.kind !== '';
const titleKind = kind ? (` - Type: ${(container.extended_metadata.kind.split('|')[1] || container.extended_metadata.kind).trim()}`) : '';
const status = container.extended_metadata.status && container.extended_metadata.status != '';
const titleStatus = status ? (' - Status: ' + container.extended_metadata.status) : '';
return (
<div style={{ width: '100%' }}>
<strike>
{container.name}
{titleKind}
{titleStatus}
</strike>
<Button className="pull-right" bsSize="xsmall" bsStyle="danger"
onClick={() => this.handleUndo(container)}>
<i className="fa fa-undo"></i>
</Button>
</div>
)
};
if (reaction.container != null && reaction.container.children) {
const analyses_container = reaction.container.children.filter(element => (
~element.container_type.indexOf('analyses')
));
if (analyses_container.length === 1 && analyses_container[0].children.length > 0) {
return (
<div>
<div style={{ marginBottom: '10px' }}>
{this.addButton()}
</div>
<PanelGroup id="reaction-analyses-panel" defaultActiveKey={0} activeKey={activeContainer} onSelect={this.handleAccordionOpen} accordion>
{analyses_container[0].children.map((container, key) => {
if (container.is_deleted) {
return (
<Panel
eventKey={key}
key={`reaction_container_deleted_${container.id}`}
>
<Panel.Heading>{containerHeaderDeleted(container)}</Panel.Heading>
</Panel>
);
}
return (
<Panel
eventKey={key}
key={`reaction_container_${container.id}`}
>
<Panel.Heading>
<Panel.Title toggle>
{containerHeader(container)}
</Panel.Title>
</Panel.Heading>
<Panel.Body collapsible="true">
<ContainerComponent
disabled={readOnly}
readOnly={readOnly}
templateType="reaction"
container={container}
onChange={this.handleChange.bind(this, container)}
/>
<ViewSpectra
sample={reaction}
handleSampleChanged={this.handleSpChange}
handleSubmit={this.props.handleSubmit}
/>
</Panel.Body>
</Panel>
);
})}
</PanelGroup>
</div>
);
}
return (
<div
style={{ marginBottom: '10px' }}
className="noAnalyses-warning"
>
There are currently no Analyses.
{this.addButton()}
</div>
);
}
return (
<div className="noAnalyses-warning">
There are currently no Analyses.
</div>
);
}
}
ReactionDetailsContainers.propTypes = {
readOnly: PropTypes.bool,
parent: PropTypes.object,
handleSubmit: PropTypes.func
};
|
spec/javascripts/jsx/external_apps/components/DeleteExternalToolButtonSpec.js | djbender/canvas-lms | /*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import ReactDOM from 'react-dom'
import TestUtils from 'react-dom/test-utils'
import Modal from 'react-modal'
import DeleteExternalToolButton from 'jsx/external_apps/components/DeleteExternalToolButton'
import store from 'jsx/external_apps/lib/ExternalAppsStore'
import {mount} from 'enzyme'
const {Simulate} = TestUtils
const wrapper = document.getElementById('fixtures')
Modal.setAppElement(wrapper)
const createElement = data => (
<DeleteExternalToolButton
tool={data.tool}
canAddEdit={data.canAddEdit}
returnFocus={data.returnFocus}
/>
)
const renderComponent = data => ReactDOM.render(createElement(data), wrapper)
const getDOMNodes = function(data) {
const component = renderComponent(data)
const btnTriggerDelete = component.refs.btnTriggerDelete
return [component, btnTriggerDelete]
}
QUnit.module('ExternalApps.DeleteExternalToolButton', {
setup() {
this.tools = [
{
app_id: 1,
app_type: 'ContextExternalTool',
description:
'Talent provides an online, interactive video platform for professional development',
enabled: true,
installed_locally: true,
name: 'Talent'
},
{
app_id: 2,
app_type: 'Lti::ToolProxy',
description: null,
enabled: true,
installed_locally: true,
name: 'Twitter'
}
]
store.reset()
return store.setState({externalTools: this.tools})
},
teardown() {
store.reset()
ReactDOM.unmountComponentAtNode(wrapper)
}
})
test('does not render when the canAddEdit permission is false', () => {
const tool = {name: 'test tool'}
const component = renderComponent({tool, canAddEdit: false, returnFocus: () => {}})
const node = ReactDOM.findDOMNode(component)
notOk(node)
})
test('open and close modal', function() {
const data = {tool: this.tools[1], canAddEdit: true, returnFocus: () => {}}
const [component, btnTriggerDelete] = Array.from(getDOMNodes(data))
Simulate.click(btnTriggerDelete)
ok(component.state.modalIsOpen, 'modal is open')
component.closeModal()
ok(!component.state.modalIsOpen, 'modal is not open')
})
test('deletes a tool', function() {
sinon.spy(store, 'delete')
const wrapper = mount(
<DeleteExternalToolButton tool={this.tools[0]} canAddEdit returnFocus={() => {}} />
)
wrapper.instance().deleteTool({preventDefault: () => {}})
ok(store.delete.called)
store.delete.restore()
wrapper.unmount()
})
|
components/AddMealDialog.js | filbertteo/frontend-challenge | import React from 'react';
import Dialog from 'material-ui/lib/dialog';
import FlatButton from 'material-ui/lib/flat-button';
import DatePicker from 'material-ui/lib/date-picker/date-picker';
import TimePicker from 'material-ui/lib/time-picker/time-picker';
import TextField from 'material-ui/lib/text-field';
import DropDownMenu from 'material-ui/lib/DropDownMenu';
import MenuItem from 'material-ui/lib/menus/menu-item';
class AddMealDialog extends React.Component {
constructor(props) {
super(props);
this.getDefaultInitialState = this.getDefaultInitialState.bind(this);
this.handleSelectDate = this.handleSelectDate.bind(this);
this.handleSelectTime = this.handleSelectTime.bind(this);
this.handleDropDownMenuSelection = this.handleDropDownMenuSelection.bind(this);
this.updateCustomMealName = this.updateCustomMealName.bind(this);
this.addMeal = this.addMeal.bind(this);
this.state = this.getDefaultInitialState();
}
getDefaultInitialState() {
return {
mealValue: 1,
mealName: 'Breakfast',
customMealName: '',
selectedDate: null,
selectedTime: null,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps) {
if (!this.props.open && nextProps.open &&
typeof nextProps.defaultDatetime == 'object') {
// Update the selected date and time if dialog is opening
this.setState({
selectedDate: nextProps.defaultDatetime,
selectedTime: nextProps.defaultDatetime,
});
} else if (this.props.open && !nextProps.open) {
// Reset the state to default if dialog is closing
this.setState(this.getDefaultInitialState());
}
}
}
handleSelectDate(event, date) {
this.setState({
selectedDate: date,
});
}
handleSelectTime(event, time) {
this.setState({
selectedTime: time,
});
}
handleDropDownMenuSelection(event, index, value) {
let mealName;
switch (value) {
case 1:
mealName = "Breakfast";
break;
case 2:
mealName = "Lunch";
break;
case 3:
mealName = "Dinner";
break;
case 4:
mealName = this.state.customMealName;
break;
}
this.setState({
mealValue: value,
mealName: mealName
});
if (value == 4) {
// It's not possible to set focus to the TextField for
// custom meal name without using a callback, but
// setImmediate() doesn't work (DropDownMenu doesn't close),
// so we're using setTimeout with 0 delay
setTimeout(() => {
this._mealNameInput.focus();
}, 0);
}
}
updateCustomMealName(event) {
// Only update mealName if "Custom:" is selected, which should
// be the case since the TextField is disabled otherwise. But
// including this to allow flexibility in case of future changes.
if (this.state.mealValue == 4) {
this.setState({
customMealName: event.target.value,
mealName: event.target.value
});
} else {
this.setState({
customMealName: event.target.value,
});
}
}
addMeal() {
// TODO Refactor this into a utility function
const datetime = new Date(
this.state.selectedDate.getFullYear(),
this.state.selectedDate.getMonth(),
this.state.selectedDate.getDate(),
this.state.selectedTime.getHours(),
this.state.selectedTime.getMinutes()
); // We are ignoring the seconds
this.props.onRequestAddMeal(datetime, this.state.mealName);
}
render() {
const {
open,
onRequestClose,
defaultDatetime
} = this.props;
const {
mealValue,
mealName,
customMealName,
selectedDate,
selectedTime,
} = this.state;
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={onRequestClose}
/>,
<FlatButton
label="Add"
primary={true}
disabled={!(mealName && selectedDate && selectedTime)}
onTouchTap={this.addMeal}
/>,
];
return (
<Dialog
title="Add a Meal"
actions={actions}
modal={false}
open={open}
onRequestClose={onRequestClose}
>
<DatePicker
hintText="Meal date"
defaultDate={defaultDatetime}
onChange={this.handleSelectDate}
autoOk={true}
/>
<TimePicker
hintText="Meal time"
defaultTime={defaultDatetime}
onChange={this.handleSelectTime}
/>
<DropDownMenu
value={mealValue}
onChange={this.handleDropDownMenuSelection}
floatingLabelText="Meal name"
>
<MenuItem value={1} primaryText="Breakfast" />
<MenuItem value={2} primaryText="Lunch" />
<MenuItem value={3} primaryText="Dinner" />
<MenuItem value={4} primaryText="Custom:" />
</DropDownMenu>
<TextField
ref={component => this._mealNameInput = component}
value={customMealName}
maxLength="15"
onChange={this.updateCustomMealName}
onEnterKeyDown={(mealName && selectedDate && selectedTime) ? this.addMeal : null}
disabled={mealValue != 4}
hintText={mealValue == 4 ? "Enter meal name" : ""}
/>
</Dialog>
)
}
}
export default AddMealDialog;
|
client/src/app/components/localSignupForm.js | jhuntoo/starhackit | import React from 'react';
//import _ from 'lodash';
import Checkit from 'checkit';
import LocalAuthenticationForm from 'components/localAuthenticationForm';
import authActions from 'actions/auth';
import {createError} from 'utils/error';
import Debug from 'debug';
let debug = new Debug("components:signup");
export default React.createClass( {
getInitialState() {
return {
errors: {},
errorServer:null
};
},
getDefaultProps() {
return {
onSignedUp: () => {}
};
},
renderError() {
let error = this.state.errorServer;
if(!error) return;
return (
<div className="alert alert-danger text-center animate bounceIn" role="alert">
<div>An error occured: {error.name}</div>
<div>{error.message}</div>
<div>Status Code: {error.status}</div>
</div>
);
},
render() {
return (
<div className="local-signup-form">
{ this.renderError()}
<LocalAuthenticationForm
buttonCaption={this.props.buttonCaption || 'Create an account' }
errors={ this.state.errors }
onButtonClick={this.signup}
/>
</div>
);
},
signup( payload ) {
this.setState( {
errors: {},
errorServer: null
} );
return validateSignup.call( this, payload )
.with( this )
.then( signupLocal )
.then( this.props.onSignedUp )
.catch( setErrors );
}
} );
//////////////////////
function validateSignup( payload ) {
let rules = new Checkit( {
username: [ 'required', 'alphaDash', 'minLength:3', 'maxLength:64'],
password: [ 'required', 'alphaDash', 'minLength:6', 'maxLength:64' ],
email: [ 'required', 'email', 'minLength:6', 'maxLength:64' ]
} );
return rules.run( payload );
}
function signupLocal( payload ) {
return authActions.signupLocal( payload.username, payload.password, payload.email );
}
function setErrors( e ) {
debug("setErrors", e);
this.setState(createError(e));
}
|
app/assets/scripts/components/panel-title.js | energy-data/market-opportunities | import React from 'react'
import c from 'classnames'
const PanelTitle = React.createClass({
propTypes: {
title: React.PropTypes.string,
visible: React.PropTypes.string,
updateVisibleLayers: React.PropTypes.func,
openSelection: React.PropTypes.func
},
render: function () {
const { title, visible, openSelection } = this.props
return (
<header className='panel__header'>
<div className='panel__headline'>
<h1 className='panel__title'>{title}</h1>
</div>
<div className='panel__meta-actions'>
<button onClick={openSelection} className='panel__button-edit' title='Change country and scenario'><span>Edit</span></button>
</div>
<div className='panel__tab-nav'>
<ul className='layers-menu' role='menu'>
<li><a onClick={this._handleIndicatorToggle} href='#' title='View indicators' className={c('layers-menu-item', {'layers-menu-item--active': visible === 'indicators'})} >Indicators</a></li>
<li><a onClick={this._handleBaseToggle} href='#' title='View base layers' className={c('layers-menu-item', {'layers-menu-item--active': visible === 'base'})}>Background</a></li>
</ul>
</div>
</header>
)
},
_handleIndicatorToggle: function (e) {
this.props.updateVisibleLayers(e, 'indicators')
},
_handleBaseToggle: function (e) {
this.props.updateVisibleLayers(e, 'base')
}
})
export default PanelTitle
|
src/core/components/types/NullType.js | remy/jsconsole | import React, { Component } from 'react';
class NullType extends Component {
shouldComponentUpdate() {
return false;
}
render() {
return <div className="type null">null</div>;
}
}
export default NullType;
|
examples/redux/SortableItem.js | danielstocks/react-sortable | import React from 'react'
import { sortable } from '../../src'
class Item extends React.Component {
render() {
return (
<li {...this.props}>
{this.props.children}
</li>
)
}
}
export default sortable(Item)
|
fields/components/ItemsTableCell.js | giovanniRodighiero/cms | import React from 'react';
import classnames from 'classnames';
function ItemsTableCell ({ className, ...props }) {
props.className = classnames('ItemList__col', className);
return <td {...props} />;
};
module.exports = ItemsTableCell;
|
src/components/App.js | sanalonyedi/egitimbudur-web-app | import React from 'react'
import { browserHistory, Router } from 'react-router'
import { Provider } from 'react-redux'
import PropTypes from 'prop-types'
class App extends React.Component {
static propTypes = {
store: PropTypes.object.isRequired,
routes: PropTypes.object.isRequired,
}
shouldComponentUpdate () {
return false
}
render () {
return (
<Provider store={this.props.store}>
<div style={{ height: '100%' }}>
<Router history={browserHistory} children={this.props.routes} />
</div>
</Provider>
)
}
}
export default App
|
packages/mineral-ui-icons/src/IconAccessible.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconAccessible(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<circle cx="12" cy="4" r="2"/><path d="M19 13v-2c-1.54.02-3.09-.75-4.07-1.83l-1.29-1.43c-.17-.19-.38-.34-.61-.45-.01 0-.01-.01-.02-.01H13c-.35-.2-.75-.3-1.19-.26C10.76 7.11 10 8.04 10 9.09V15c0 1.1.9 2 2 2h5v5h2v-5.5c0-1.1-.9-2-2-2h-3v-3.45c1.29 1.07 3.25 1.94 5 1.95zm-6.17 5c-.41 1.16-1.52 2-2.83 2-1.66 0-3-1.34-3-3 0-1.31.84-2.41 2-2.83V12.1a5 5 0 1 0 5.9 5.9h-2.07z"/>
</g>
</Icon>
);
}
IconAccessible.displayName = 'IconAccessible';
IconAccessible.category = 'action';
|
packages/ringcentral-widgets/containers/ConferenceCallDialerPage/index.js | u9520107/ringcentral-js-widget | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import withPhone from '../../lib/withPhone';
import BackButton from '../../components/BackButton';
import BackHeader from '../../components/BackHeader';
import DialerPanel from '../../components/DialerPanel';
import {
mapToProps as mapToBaseProps,
mapToFunctions as mapToBaseFunctions,
} from '../DialerPage';
import i18n from './i18n';
function ConferenceCallDialerPanel({
onBack,
...baseProps
}) {
return [
<BackHeader
key="header"
onBackClick={onBack}
backButton={<BackButton label={i18n.getString('activeCall')} />}
/>,
<DialerPanel
key="dialer"
{...baseProps}
/>
];
}
ConferenceCallDialerPanel.propTypes = {
...DialerPanel.propTypes,
onBack: PropTypes.func.isRequired,
};
ConferenceCallDialerPanel.defaultProps = {
...DialerPanel.defaultProps,
};
function mapToProps(_, {
...props
}) {
const baseProps = mapToBaseProps(_, {
...props,
});
return {
...baseProps,
showFromField: false,
};
}
function mapToFunctions(_, {
params,
phone,
onBack,
...props
}) {
const baseProps = mapToBaseFunctions(_, {
params,
phone,
...props,
});
return {
...baseProps,
onBack,
onCallButtonClick() {
phone.dialerUI.onCallButtonClick({
fromNumber: params.fromNumber,
});
},
};
}
const ConferenceCallDialerPage = withPhone(connect(
mapToProps,
mapToFunctions,
)(ConferenceCallDialerPanel));
export {
mapToProps,
mapToFunctions,
ConferenceCallDialerPage as default,
};
|
app/components/ShopListItemRenderer/ShopListItemRenderer.js | tenhaus/bbwelding | import React from 'react';
import Radium from 'radium';
import AltActions from '../../actions/AltActions';
import Style from './_ShopListItemRenderer.style';
class ShopListItemRenderer extends React.Component {
constructor() {
super();
this.onClick = this.onClick.bind(this);
}
onClick() {
AltActions.setSelectedShopItem(this.props.item);
}
render() {
let item = this.props.item;
let profileImage = '';
if(item.fields.primaryImage.hasOwnProperty('fields')) {
profileImage = item.fields.primaryImage.fields.file.url;
}
profileImage += '?w=100&fm=jpg&q=75';
return (
<li className='team-list-item' style={Style.base}
onClick={this.onClick}>
<p>{item.fields.name}</p>
</li>
);
}
}
export default Radium(ShopListItemRenderer);
|
src/parser/DEFAULT_BUILD.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import ArmoryIcon from 'interface/icons/Armory';
export default {
name: "Standard Build",
url: "standard",
icon: <ArmoryIcon />,
};
|
src/svg-icons/image/looks-two.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLooksTwo = (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-2zm-4 8c0 1.11-.9 2-2 2h-2v2h4v2H9v-4c0-1.11.9-2 2-2h2V9H9V7h4c1.1 0 2 .89 2 2v2z"/>
</SvgIcon>
);
ImageLooksTwo = pure(ImageLooksTwo);
ImageLooksTwo.displayName = 'ImageLooksTwo';
ImageLooksTwo.muiName = 'SvgIcon';
export default ImageLooksTwo;
|
node_modules/react-bootstrap/es/FormControl.js | Chen-Hailin/iTCM.github.io | 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 elementType from 'react-prop-types/lib/elementType';
import warning from 'warning';
import FormControlFeedback from './FormControlFeedback';
import FormControlStatic from './FormControlStatic';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType,
/**
* Only relevant if `componentClass` is `'input'`.
*/
type: React.PropTypes.string,
/**
* Uses `controlId` from `<FormGroup>` if not explicitly specified.
*/
id: React.PropTypes.string
};
var defaultProps = {
componentClass: 'input'
};
var contextTypes = {
$bs_formGroup: React.PropTypes.object
};
var FormControl = function (_React$Component) {
_inherits(FormControl, _React$Component);
function FormControl() {
_classCallCheck(this, FormControl);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
FormControl.prototype.render = function render() {
var formGroup = this.context.$bs_formGroup;
var controlId = formGroup && formGroup.controlId;
var _props = this.props;
var Component = _props.componentClass;
var type = _props.type;
var _props$id = _props.id;
var id = _props$id === undefined ? controlId : _props$id;
var className = _props.className;
var props = _objectWithoutProperties(_props, ['componentClass', 'type', 'id', 'className']);
var _splitBsProps = splitBsProps(props);
var bsProps = _splitBsProps[0];
var elementProps = _splitBsProps[1];
process.env.NODE_ENV !== 'production' ? warning(controlId == null || id === controlId, '`controlId` is ignored on `<FormControl>` when `id` is specified.') : void 0;
// input[type="file"] should not have .form-control.
var classes = void 0;
if (type !== 'file') {
classes = getClassSet(bsProps);
}
return React.createElement(Component, _extends({}, elementProps, {
type: type,
id: id,
className: classNames(className, classes)
}));
};
return FormControl;
}(React.Component);
FormControl.propTypes = propTypes;
FormControl.defaultProps = defaultProps;
FormControl.contextTypes = contextTypes;
FormControl.Feedback = FormControlFeedback;
FormControl.Static = FormControlStatic;
export default bsClass('form-control', FormControl); |
server/sonar-web/src/main/js/app/components/extensions/Extension.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.
*/
// @flow
import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { addGlobalErrorMessage } from '../../../store/globalMessages/duck';
import { getCurrentUser } from '../../../store/rootReducer';
import { translate } from '../../../helpers/l10n';
import { getExtensionStart } from './utils';
import getStore from '../../utils/getStore';
type Props = {
currentUser: Object,
extension: {
key: string,
title: string
},
onFail: (string) => void,
options?: {},
router: Object
};
class Extension extends React.Component {
container: Object;
props: Props;
stop: ?Function;
componentDidMount() {
this.startExtension();
}
componentDidUpdate(prevProps: Props) {
if (prevProps.extension !== this.props.extension) {
this.stopExtension();
this.startExtension();
}
}
componentWillUnmount() {
this.stopExtension();
}
handleStart = (start: Function) => {
const store = getStore();
this.stop = start({
store,
el: this.container,
currentUser: this.props.currentUser,
router: this.props.router,
...this.props.options
});
};
handleFailure = () => {
this.props.onFail(translate('page_extension_failed'));
};
startExtension() {
const { extension } = this.props;
getExtensionStart(extension.key).then(this.handleStart, this.handleFailure);
}
stopExtension() {
this.stop && this.stop();
this.stop = null;
}
render() {
return (
<div>
<div ref={container => this.container = container} />
</div>
);
}
}
const mapStateToProps = state => ({
currentUser: getCurrentUser(state)
});
const mapDispatchToProps = { onFail: addGlobalErrorMessage };
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Extension));
|
services/ui/src/components/NavTabs/index.js | amazeeio/lagoon | import React from 'react';
import css from 'styled-jsx/css';
import EnvironmentLink from 'components/link/Environment';
import BackupsLink from 'components/link/Backups';
import DeploymentsLink from 'components/link/Deployments';
import TasksLink from 'components/link/Tasks';
import ProblemsLink from 'components/link/Problems';
import FactsLink from 'components/link/Facts';
import { bp, color } from 'lib/variables';
import problems from '../../pages/problems';
const { className: aClassName, styles: aStyles } = css.resolve`
a {
color: ${color.darkGrey};
display: block;
padding: 20px 20px 19px 60px;
@media ${bp.wideUp} {
padding-left: calc((100vw / 16) * 1);
}
}
.active a {
color: ${color.black};
}
`;
const NavTabs = ({ activeTab, environment }) => (
<ul className="navigation">
<li
className={`overview ${
activeTab == 'overview' ? 'active' : ''
} ${aClassName}`}
>
<EnvironmentLink
environmentSlug={environment.openshiftProjectName}
projectSlug={environment.project.name}
className={aClassName}
>
Overview
</EnvironmentLink>
</li>
<li
className={`deployments ${
activeTab == 'deployments' ? 'active' : ''
} ${aClassName}`}
>
<DeploymentsLink
environmentSlug={environment.openshiftProjectName}
projectSlug={environment.project.name}
className={aClassName}
>
Deployments
</DeploymentsLink>
</li>
<li
className={`backups ${
activeTab == 'backups' ? 'active' : ''
} ${aClassName}`}
>
<BackupsLink
environmentSlug={environment.openshiftProjectName}
projectSlug={environment.project.name}
className={aClassName}
>
Backups
</BackupsLink>
</li>
<li
className={`tasks ${activeTab == 'tasks' ? 'active' : ''} ${aClassName}`}
>
<TasksLink
environmentSlug={environment.openshiftProjectName}
projectSlug={environment.project.name}
className={aClassName}
>
Tasks
</TasksLink>
</li>
{(environment.project.problemsUi == 1) && <li
className={`problems ${activeTab == 'problems' ? 'active' : ''} ${aClassName}`}
>
<ProblemsLink
environmentSlug={environment.openshiftProjectName}
projectSlug={environment.project.name}
className={aClassName}
>
Problems
</ProblemsLink>
</li>
}
{(environment.project.factsUi == 1) && <li
className={`facts ${activeTab == 'facts' ? 'active' : ''} ${aClassName}`}
>
<FactsLink
environmentSlug={environment.openshiftProjectName}
projectSlug={environment.project.name}
className={aClassName}
>
Facts
</FactsLink>
</li>
}
<style jsx>{`
.navigation {
background: ${color.lightestGrey};
border-right: 1px solid ${color.midGrey};
margin: 0;
z-index: 10;
@media ${bp.tabletUp} {
min-width: 30%;
padding-bottom: 60px;
}
@media ${bp.wideUp} {
min-width: 25%;
}
li {
border-bottom: 1px solid ${color.midGrey};
margin: 0;
padding: 0;
position: relative;
&:hover {
background-color: ${color.white};
}
&::before {
background-color: ${color.linkBlue};
background-position: center center;
background-repeat: no-repeat;
content: '';
display: block;
height: 59px;
left: 0;
position: absolute;
top: 0;
transition: all 0.3s ease-in-out;
width: 45px;
}
a {
color: ${color.darkGrey};
display: block;
padding: 20px 20px 19px 60px;
@media ${bp.wideUp} {
padding-left: calc((100vw / 16) * 1);
}
}
&.active {
&::before {
background-color: ${color.almostWhite};
}
background-color: ${color.almostWhite};
border-right: 1px solid ${color.almostWhite};
width: calc(100% + 1px);
a {
color: ${color.black};
}
}
&.overview {
&::before {
background-image: url('/static/images/overview.svg');
background-size: 18px;
}
&.active::before {
background-image: url('/static/images/overview-active.svg');
}
}
&.deployments {
&::before {
background-image: url('/static/images/deployments.svg');
background-size: 21px 16px;
}
&.active::before {
background-image: url('/static/images/deployments-active.svg');
}
}
&.backups {
&::before {
background-image: url('/static/images/backups.svg');
background-size: 19px;
}
&.active::before {
background-image: url('/static/images/backups-active.svg');
}
}
&.tasks {
&::before {
background-image: url('/static/images/tasks.svg');
background-size: 16px;
}
&.active::before {
background-image: url('/static/images/tasks-active.svg');
}
}
&.problems {
&::before {
background-image: url('/static/images/problems.svg');
background-size: 16px;
}
&.active::before {
background-image: url('/static/images/problems-active.svg');
}
}
&.facts {
&::before {
background-image: url('/static/images/facts.svg');
background-size: 16px;
}
&.active::before {
background-image: url('/static/images/facts-active.svg');
}
}
}
}
`}</style>
{aStyles}
</ul>
);
export default NavTabs;
|
pootle/static/js/admin/general/components/ContentPreview.js | translate/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
const ContentPreview = React.createClass({
propTypes: {
value: React.PropTypes.string.isRequired,
style: React.PropTypes.object,
},
render() {
return (
<div
className="content-preview"
style={this.props.style}
>
{this.props.value ?
<div
className="staticpage"
dangerouslySetInnerHTML={{ __html: this.props.value }}
/> :
<div className="placeholder">
{gettext('Preview will be displayed here.')}
</div>
}
</div>
);
},
});
export default ContentPreview;
|
admin/client/App/shared/InvalidFieldType.js | helloworld3q3q/keystone | /**
* Renders an "Invalid Field Type" error
*/
import React from 'react';
const InvalidFieldType = function (props) {
return (
<div className="alert alert-danger">
Invalid field type <strong>{props.type}</strong> at path <strong>{props.path}</strong>
</div>
);
};
InvalidFieldType.propTypes = {
path: React.PropTypes.string,
type: React.PropTypes.string,
};
module.exports = InvalidFieldType;
|
frontend/src/components/organizationProfile/edit/mandate/partnerProfileMandate.js | unicef/un-partner-portal | import R from 'ramda';
import React, { Component } from 'react';
import { withRouter, browserHistory as history } from 'react-router';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getFormInitialValues, SubmissionError } from 'redux-form';
import PartnerProfileMandateBackground from './partnerProfileMandateBackground';
import PartnerProfileMandateGovernance from './partnerProfileMandateGovernance';
import PartnerProfileMandateEthics from './partnerProfileMandateEthics';
import PartnerProfileMandateExperience from './partnerProfileMandateExperience';
import PartnerProfileMandatePopulation from './partnerProfileMandatePopulation';
import PartnerProfileMandateCountryPresence from './partnerProfileMandateCountryPresence';
import PartnerProfileMandateSecurity from './partnerProfileMandateSecurity';
import PartnerProfileStepperContainer from '../partnerProfileStepperContainer';
import { patchPartnerProfile } from '../../../../reducers/partnerProfileDetailsUpdate';
import { flatten } from '../../../../helpers/jsonMapper';
import { changedValues } from '../../../../helpers/apiHelper';
import { loadPartnerDetails } from '../../../../reducers/partnerProfileDetails';
import { emptyMsg } from '../partnerProfileEdit';
const STEPS = readOnly => [
{
component: <PartnerProfileMandateBackground readOnly={readOnly} />,
label: 'Background',
name: 'background',
},
{
component: <PartnerProfileMandateGovernance readOnly={readOnly} />,
label: 'Governance',
name: 'governance',
},
{
component: <PartnerProfileMandateEthics readOnly={readOnly} />,
label: 'Ethics',
name: 'ethics',
},
{
component: <PartnerProfileMandateExperience readOnly={readOnly} />,
label: 'Experience',
name: 'experience',
},
{
component: <PartnerProfileMandatePopulation readOnly={readOnly} />,
label: 'Population of Concern',
name: 'populations_of_concern',
infoText: 'Populations of Concern: is composed of various groups of people including ' +
'refugees, asylum-seekers, internally displaced persons (IDPs) protected/assisted by ' +
'UNHCR, stateless persons and returnees (returned refugees and IDPs).',
},
{
component: <PartnerProfileMandateCountryPresence readOnly={readOnly} />,
label: 'Country Presence',
name: 'country_presence',
},
{
component: <PartnerProfileMandateSecurity readOnly={readOnly} />,
label: 'Security',
name: 'security',
},
];
class PartnerProfileMandate extends Component {
constructor(props) {
super(props);
this.state = {
actionOnSubmit: {},
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleNext = this.handleNext.bind(this);
this.handleExit = this.handleExit.bind(this);
}
onSubmit() {
const { partnerId, tabs, params: { type } } = this.props;
if (this.state.actionOnSubmit === 'next') {
const index = tabs.findIndex(itab => itab.path === type);
history.push({
pathname: `/profile/${partnerId}/edit/${tabs[index + 1].path}`,
});
} else if (this.state.actionOnSubmit === 'exit') {
history.push(`/profile/${partnerId}/overview`);
}
}
handleNext() {
this.setState({ actionOnSubmit: 'next' });
}
handleExit() {
this.setState({ actionOnSubmit: 'exit' });
}
handleSubmit(formValues) {
const { initialValues, updateTab, partnerId, loadPartnerProfileDetails } = this.props;
const mandateMission = flatten(formValues.mandate_mission);
const initMandateMission = flatten(initialValues.mandate_mission);
const convertExperiences = mandateMission.specializations
? R.flatten(R.map(item => (item.areas ?
R.map(area => R.assoc('years', item.years,
R.objOf('specialization_id', area)),
item.areas) : []), mandateMission.specializations))
: [];
const changed = changedValues(initMandateMission, mandateMission);
let patchValues = R.assoc('experiences', R.filter(item => !R.isNil(item.specialization_id), convertExperiences), changed);
if (R.isEmpty(patchValues.experiences)) {
patchValues = R.dissoc('experiences', patchValues);
}
if (!R.isEmpty(patchValues)) {
return updateTab(partnerId, 'mandate-mission', patchValues)
.then(() => loadPartnerProfileDetails(partnerId).then(() => this.onSubmit()))
.catch((error) => {
const errorMsg = error.response.data.non_field_errors || 'Error while saving sections. Please try again.';
throw new SubmissionError({
...error.response.data,
_error: errorMsg,
});
});
}
throw new SubmissionError({
_error: emptyMsg,
});
}
render() {
const { readOnly } = this.props;
return (<PartnerProfileStepperContainer
handleNext={this.handleNext}
handleExit={this.handleExit}
onSubmit={this.handleSubmit}
name="mandate_mission"
readOnly={readOnly}
steps={STEPS(readOnly)}
/>
);
}
}
PartnerProfileMandate.propTypes = {
readOnly: PropTypes.bool,
partnerId: PropTypes.string,
updateTab: PropTypes.func,
initialValues: PropTypes.object,
loadPartnerProfileDetails: PropTypes.func,
params: PropTypes.object,
tabs: PropTypes.array,
};
const mapState = (state, ownProps) => ({
partnerId: ownProps.params.id,
tabs: state.partnerProfileDetailsNav.tabs,
initialValues: getFormInitialValues('partnerProfile')(state),
});
const mapDispatch = dispatch => ({
loadPartnerProfileDetails: partnerId => dispatch(loadPartnerDetails(partnerId)),
updateTab: (partnerId, tabName, body) => dispatch(patchPartnerProfile(partnerId, tabName, body)),
dispatch,
});
const connectedPartnerProfileMandate = connect(mapState, mapDispatch)(PartnerProfileMandate);
export default withRouter(connectedPartnerProfileMandate);
|
lib/components/MapUrlTile.js | pjamrozowicz/react-native-maps | import PropTypes from 'prop-types';
import React from 'react';
import {
ViewPropTypes,
View,
} from 'react-native';
import decorateMapComponent, {
USES_DEFAULT_IMPLEMENTATION,
SUPPORTED,
} from './decorateMapComponent';
// if ViewPropTypes is not defined fall back to View.propType (to support RN < 0.44)
const viewPropTypes = ViewPropTypes || View.propTypes;
const propTypes = {
...viewPropTypes,
/**
* The url template of the tile server. The patterns {x} {y} {z} will be replaced at runtime
* For example, http://c.tile.openstreetmap.org/{z}/{x}/{y}.png
*/
urlTemplate: PropTypes.string.isRequired,
/**
* The order in which this tile overlay is drawn with respect to other overlays. An overlay
* with a larger z-index is drawn over overlays with smaller z-indices. The order of overlays
* with the same z-index is arbitrary. The default zIndex is -1.
*
* @platform android
*/
zIndex: PropTypes.number,
};
class MapUrlTile extends React.Component {
render() {
const AIRMapUrlTile = this.getAirComponent();
return (
<AIRMapUrlTile
{...this.props}
/>
);
}
}
MapUrlTile.propTypes = propTypes;
module.exports = decorateMapComponent(MapUrlTile, {
componentType: 'UrlTile',
providers: {
google: {
ios: SUPPORTED,
android: USES_DEFAULT_IMPLEMENTATION,
},
},
});
|
frontend/app_v2/src/components/Widget/WidgetPlaceholder.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
function WidgetPlaceholder() {
return <div className="bg-gray-100 text-gray-100 mt-5 w-auto h-48" />
}
export default WidgetPlaceholder
|
src/components/index.js | adjohnson916/github-issue-rank | import _ from 'lodash';
import React from 'react';
import { Link } from 'react-router';
import Griddle from 'griddle-react';
import Loader from 'react-loader';
import { octokat, octokatHelper } from '../factory';
import * as helper from '../helper';
import Auth from '../auth';
import { history, linker } from './router';
import { dispatcher } from '../dispatcher';
import {
Alert,
Button,
CollapsibleNav,
Input,
MenuItem,
Modal,
Nav,
Navbar,
NavBrand,
NavDropdown,
NavItem
} from 'react-bootstrap';
export class AppRoute extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: [],
user: null,
authed: false,
gitHubAccessToken: null,
rateLimit: {},
reset: new Date(),
repos: [
'oauth-io/oauth-js',
'isaacs/github',
'AndersDJohnson/github-issue-rank'
]
};
dispatcher.register(payload => {
if(dispatcher.type(payload, 'AUTH')) {
var errors = this.state.errors;
errors = _.filter(errors, error => {
if (this.isAuthError(error)) {
return false;
}
return true;
});
this.setState({errors});
}
});
dispatcher.register(payload => {
if(payload.actionType === dispatcher.actionTypes.ERROR) {
var error = payload.data;
this.setState({
errors: this.state.errors.concat([error])
});
}
});
}
isAuthError(err) {
return err.status && (err.status === 401 || err.status === 403);
}
componentDidMount() {
this.checkAuth();
dispatcher.register(payload => {
if (dispatcher.type(payload, 'SIGNED_IN')) {
var { gitHubAccessToken } = payload.data;
this.setState({ gitHubAccessToken });
console.log('auth set token', gitHubAccessToken);
this.onSignedIn();
}
});
var checkRateLimit = () => {
if (!octokat()) {
setTimeout(checkRateLimit, 2000);
return;
}
octokat().rateLimit.fetch().then(
(data) => {
var rateLimit = data.resources.core;
var reset = data.resources.core.reset;
var date = new Date(reset*1000);
var state = {rateLimit, reset: date};
this.setState(state);
setTimeout(checkRateLimit, 2000);
},
(err) => {
console.error(err);
}
);
};
checkRateLimit();
}
onClickSignIn() {
this.showAuthModal();
}
onClickAuth() {
this.showAuthModal();
}
showAuthModal() {
history.pushState(null, '/auth');
}
setGitHubAccessToken(gitHubAccessToken) {
this.setState({
gitHubAccessToken: gitHubAccessToken,
inputGitHubAccessToken: gitHubAccessToken
});
}
signIn() {
Auth.signIn().then(d => {
console.log('sign in data', d);
this.setGitHubAccessToken(d.gitHubAccessToken);
this.onSignedIn();
});
}
onClickSignOut() {
console.log('onClickSignOut');
Auth.signOut().
then(d => {
this.setState({
authed: false,
user: null
});
this.setGitHubAccessToken(null);
});
}
checkAuth(options) {
Auth.check(options).
then(d => {
console.log('authed', d);
this.setGitHubAccessToken(d.gitHubAccessToken);
this.onSignedIn();
});
}
checkSignIn(gitHubAccessToken) {
octokat().user.fetch().then(
user => {
this.setState({user});
Auth.setToken(gitHubAccessToken).
then(data => {
var {gitHubAccessToken} = data;
console.log('auth set token', gitHubAccessToken);
this.setGitHubAccessToken(gitHubAccessToken);
this.onSignedIn();
});
},
err => {
console.error('sign in error', err);
// TODO: Show in UI.
}
)
}
onSignedIn() {
this.setState({authed: true});
return octokat().user.fetch().then(user => {
this.setState({user});
}, err => {
console.error(err);
});
}
signInFromAlert() {
this.dismissAlert();
this.signIn();
}
dismissAlert() {
this.setState({errors: []});
}
render() {
var children = this.props.children;
if (! children) {
children = (
<ul>
{this.state.repos.map(r => {
return (
<li key={r}>
<Link to={linker.github('/' + r)}>{r}</Link>
</li>
);
})}
</ul>
);
}
var errorCmps = [];
var error = this.state.errors;
if (this.state.errors) {
this.state.errors.forEach(error => {
var message = error.message || error;
var errorCmp =
<Alert bsStyle="danger" onDismiss={this.dismissAlert.bind(this)}>
<h4>Oh snap! You got an error!</h4>
<p>{message}</p>
<p>
<Link to={linker.auth()}>Sign In</Link>
<span> or </span>
<Button onClick={this.dismissAlert.bind(this)}>Hide Alert</Button>
</p>
</Alert>;
errorCmps.push(errorCmp);
})
}
var authBarCmp;
if (! this.state.user) {
/*
* https://github.com/react-bootstrap/react-bootstrap/issues/1404
*/
authBarCmp = (
<button type="button"
className="btn btn-success navbar-btn navbar-right"
onClick={this.onClickSignIn.bind(this)}
>
Sign In
</button>
);
}
else {
var avatar = (
<img src={this.state.user.avatarUrl}
className="ghir-navbar-user-avatar"
></img>
);
authBarCmp = (
<Nav navbar right>
<NavDropdown eventKey={2}
title={avatar}
id="ghir-navbar-user-dropdown"
>
<MenuItem eventKey={5}
onSelect={this.onClickAuth.bind(this)}
>
<i className="fa fa-user"></i> Authentication
</MenuItem>
<MenuItem eventKey={5}
onSelect={this.onClickSignOut.bind(this)}
>
<i className="fa fa-sign-out"></i> Sign Out
</MenuItem>
</NavDropdown>
</Nav>
);
}
return (
<div>
<Navbar fixedTop fluid toggleNavKey={0}>
<NavBrand>
<Link to="/">GitHub Issue Rank</Link>
</NavBrand>
<CollapsibleNav eventKey={0}>
<Nav navbar right>
<NavDropdown eventKey={3}
title={<i className="fa fa-bars"></i>}
id="ghir-navbar-more-dropdown"
>
<MenuItem eventKey={1}>
<i className="fa fa-gear"></i> Settings
</MenuItem>
<MenuItem divider />
<MenuItem eventKey={4}
href="https://github.com/AndersDJohnson/github-issue-rank"
target="_blank"
>
<i className="fa fa-code"></i> Source Code
</MenuItem>
</NavDropdown>
</Nav>
{authBarCmp}
</CollapsibleNav>
</Navbar>
{errorCmps}
<div>
<progress id="gh-api-limit"
title="API Limit"
value={this.state.rateLimit.remaining}
max={this.state.rateLimit.limit} />
<label htmlFor="gh-api-limit">
API Limit {this.state.rateLimit.remaining} / {this.state.rateLimit.limit}
(resets {this.state.reset.toString()})
</label>
</div>
{children}
</div>
)
}
};
export class NoRoute extends React.Component {
componentDidMount() {
console.log(this.props.params);
}
render() {
return (
<h1>404</h1>
)
}
};
export class LinkComponent extends React.Component {
render() {
var data = this.data();
var {owner, repo, number} = this.props.rowData;
var href = linker.github('/' + owner + '/' + repo + '/' + number);
return (
<Link to={href}>
{data}
</Link>
);
}
data() {
return this.props.data;
}
};
class IssueNumberComponent extends LinkComponent {
data() {
var data = this.props.data;
return data ? '#' + data : '';
}
};
export class RepoRoute extends React.Component {
constructor(props) {
super(props);
var columnMetadata = [
{
columnName: 'number',
displayName: '#',
customComponent: IssueNumberComponent,
cssClassName: 'griddle-column-number'
},
{
columnName: 'title',
displayName: 'Title',
customComponent: LinkComponent,
cssClassName: 'griddle-column-title'
},
{
columnName: 'voteCount',
displayName: '# Votes',
customComponent: LinkComponent,
cssClassName: 'griddle-column-voteCount'
},
{
columnName: 'owner',
visible: false
},
{
columnName: 'repo',
visible: false
},
{
columnName: 'htmlUrl',
visible: false
}
];
columnMetadata = _.each(columnMetadata, (md, i) => { md.order = i; })
var columns =_.chain(columnMetadata)
.sortBy('order')
.filter((md) => {
return md.visible == null ? true : false;
})
.pluck('columnName')
.value();
this.state = {
owner: null,
repo: null,
rows: [],
loaded: false,
anyLoaded: false,
columnMetadata,
columns,
showingIssueModal: false,
commentsWithVotes: [],
issue: {},
progress: {
value:0,
max: 0
}
};
}
componentDidUpdate() {
// this.setState({unmounting: false});
this.showRepo();
}
componentDidMount() {
this.setState({unmounting: false});
this.showRepo();
}
componentWillUnmount () {
// allows us to ignore an inflight request in scenario 4
this.owner = null;
this.repo = null;
this.setState({unmounting: true});
if (_.isFunction(this.cancel)) this.cancel();
}
sameState(owner, repo) {
return (! this.state.unmounting) && (owner && (owner === this.state.owner)) && (repo && (repo === this.state.repo));
}
refresh() {
this.showRepo({
refresh: true
})
}
showRepo(opts) {
opts = opts || {};
var {owner, repo} = this.props.params;
var {refresh} = opts;
if (!refresh && this.sameState(owner, repo)) return;
if (refresh) {
if (_.isFunction(this.cancel)) this.cancel();
}
this.setState({
loaded: false,
owner: owner,
repo: repo,
rows: []
});
Auth.wait().then(() => {
helper.showRepo(owner, repo,
(err, result) => {
if (err) return dispatcher.error(err);
var {data: rows, cancel, progress} = result;
this.cancel = cancel;
if ( ! this.sameState(owner, repo)) return cancel();
this.showRows(err, rows);
this.setState({
anyLoaded: true,
progress
});
},
(err, result) => {
if (err) throw err;
var {data: rows, cancel, progress} = result;
this.cancel = cancel;
if (err) {
this.setState({loaded: true, anyLoaded: true})
return dispatcher.error(err);
}
if ( ! this.sameState(owner, repo)) return cancel();
this.showRows(err, rows);
this.setState({
loaded: true,
progress
});
}
);
});
}
showRows(err, rows) {
if (! this.state.unmounting) {
this.setState({
rows
});
}
}
render() {
var children = this.props.children;
var {owner, repo} = this.props.params;
return (
<div className="ghir-route-repo">
<h2>
<Link to={linker.github('/' + owner + '/' + repo)}>
{owner}/{repo}
</Link>
<a href={'https://github.com/' + owner + '/' + repo}
target="_blank"
className="ghir-link-github"
>
<i className="fa fa-github"></i>
</a>
</h2>
<button onClick={this.refresh.bind(this)}>refresh</button>
<progress
value={this.state.progress.value}
max={this.state.progress.max}
></progress>
<Loader loaded={this.state.loaded}></Loader>
<Loader loaded={this.state.anyLoaded}>
<div># issues: {this.state.rows.length}</div>
<Griddle
results={this.state.rows}
columnMetadata={this.state.columnMetadata}
columns={this.state.columns}
resultsPerPage={10}
showSettings={true}
showFilter={true}
/>
</Loader>
{children}
</div>
)
}
};
export class AuthRoute extends React.Component {
constructor(props) {
super(props);
this.state = {
inputGitHubAccessToken: Auth.gitHubAccessToken(),
user: null
};
}
componentDidMount() {
dispatcher.register(payload => {
if (dispatcher.type(payload, 'SIGNED_IN')) {
return octokat().user.fetch().then(user => {
this.setState({user});
}, err => {
console.error(err);
});
}
});
}
closeAuthModal() {
history.pushState(null, '/');
}
onClickSignOut() {
console.log('onClickSignOut');
Auth.signOut().
then(d => {
this.setState({
authed: false,
user: null
});
this.setGitHubAccessToken(null);
});
}
onChangeInputGitHubAccessToken(e) {
var inputGitHubAccessToken = e.target.value;
this.setState({inputGitHubAccessToken});
dispatcher.dispatch({
actionType: 'CHECK_SIGN_IN',
data: {
gitHubAccessToken: inputGitHubAccessToken
}
});
}
signIn() {
Auth.signIn().then(data => {
console.log('sign in data', data);
var {gitHubAccessToken} = data;
this.setState({
gitHubAccessToken,
inputGitHubAccessToken: gitHubAccessToken
});
dispatcher.dispatch({
actionType: 'SIGNED_IN',
data: {
gitHubAccessToken: gitHubAccessToken
}
});
},
(err) => {
// TODO: Handle errors.
console.error(err);
});
}
render() {
var authModalSignInCmp;
if (! this.state.user) {
authModalSignInCmp = (
<Button
bsStyle="success"
onClick={this.signIn.bind(this)}
>
Sign In to GitHub via OAuth.io
</Button>
);
}
else {
authModalSignInCmp = (
<div>
<div>
<a
href={this.state.user.htmlUrl}
target="_blank"
>
<img src={this.state.user.avatarUrl}
className="ghir-auth-user-avatar"
></img>
</a>
</div>
<div>
<a
href={this.state.user.htmlUrl}
target="_blank"
>
@{this.state.user.login}
</a>
</div>
<div>
<Button
bsStyle="success"
onClick={this.onClickSignOut.bind(this)}
>
<i className="fa fa-sign-out"></i> Sign Out
</Button>
</div>
</div>
);
}
return (
<div className="ghir-route-auth">
<Modal show={true} onHide={this.closeAuthModal.bind(this)}>
<Modal.Header closeButton>
<Modal.Title>Authentication</Modal.Title>
</Modal.Header>
<Modal.Body>
{authModalSignInCmp}
<hr />
<p>Or provide an access token:</p>
<Input
type="text"
value={this.state.inputGitHubAccessToken}
onChange={this.onChangeInputGitHubAccessToken.bind(this)}
/>
</Modal.Body>
<Modal.Footer>
<Button
onClick={this.closeAuthModal.bind(this)}
>
Close
</Button>
</Modal.Footer>
</Modal>
</div>
);
}
};
export class IssueRoute extends React.Component {
constructor(props) {
super(props);
this.state = {
owner: null,
repo: null,
number: null,
issue: {},
comments: [],
commentsWithVotes: [],
loaded: false
};
}
componentDidMount() {
this.setState({
unmounting: false
})
this.showComments();
}
componentWillUnmount() {
this.setState({
unmounting: true
})
}
showComments() {
var {owner, repo, number} = this.props.params;
Auth.wait().then(() => {
octokat()
.repos(owner, repo)
.issues(number)
.fetch()
.then(issue => {
// console.log('issue', issue);
this.setState({issue});
}, (err) => {
if (err) throw err;
});
octokatHelper().getComments(
owner, repo, number,
(err, results, cancel) => {
if (err) {
return dispatcher.error(err);
}
var {data: comments} = results;
// console.log('each', err, comments, cancel);
comments = helper.mapCommentsHaveVotes(comments);
this.setState({comments});
var commentsWithVotes = comments.filter(c => {
return c.hasVote;
});
this.setState({commentsWithVotes});
},
(err, comments) => {
if (err) {
return dispatcher.error(err);
}
// console.log('done', comments);
}
);
});
}
closeIssueModal() {
var {owner, repo} = this.props.params;
var href = linker.github('/' + owner + '/' + repo);
history.pushState(null, href);
}
render() {
var {owner, repo, number} = this.props.params;
return (
<div className="ghir-route-issue">
<Modal show={true} onHide={this.closeIssueModal.bind(this)}>
<Modal.Header closeButton>
<Modal.Title>
<Link to={linker.github('/' + owner + '/' + repo)}>
{owner}/{repo}
</Link>
<a href={'https://github.com/' + owner + '/' + repo}
target="_blank"
className="ghir-link-github"
>
<i className="fa fa-github"></i>
</a>
<Link to={linker.github('/' + owner + '/' + repo + '/' + number)}>
#{number}
</Link>
<a href={'https://github.com/' + owner + '/' + repo
+ '/issues/' + number}
target="_blank"
className="ghir-link-github"
>
<i className="fa fa-github"></i>
</a>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<h3>
{this.state.issue.title}
</h3>
<div>
{this.state.commentsWithVotes.length} votes
</div>
<ul className="ghir-issue-votes list-unstyled list-inline">
{this.state.commentsWithVotes.map(c => {
return (
<li key={c.id} className="ghir-issue-vote">
<a href={c.htmlUrl} target="_blank">
<img className="ghir-issue-vote-avatar"
src={c.user.avatarUrl + '&s=32'} />
</a>
</li>
);
})}
</ul>
</Modal.Body>
<Modal.Footer>
<Button
onClick={this.closeIssueModal.bind(this)}
>
Close
</Button>
</Modal.Footer>
</Modal>
</div>
);
}
};
|
src/browser/components/Baseline.js | reedlaw/read-it | // @flow
import type { State } from '../../common/types';
import type { Theme } from '../../common/themes/types';
import * as themes from '../themes';
import React from 'react';
import { compose } from 'ramda';
import { connect } from 'react-redux';
// Test vertical rhythm visually. Inspired by basehold.it
type BaselineProps = {|
baselineShown: boolean,
children: any,
theme: Theme,
|};
const styles = {
container: {
position: 'relative',
},
baseline: lineHeight => ({
backgroundImage: 'linear-gradient(to bottom, rgba(0, 0, 0, 0.1) 1px, transparent 1px)',
backgroundSize: `auto ${lineHeight}px`,
bottom: 0,
left: 0,
marginTop: '-1px',
pointerEvents: 'none',
position: 'absolute',
right: 0,
top: 0,
zIndex: 9999,
}),
};
const Baseline = ({ baselineShown, children, theme }: BaselineProps) => (
<div style={styles.container}>
{children}
{baselineShown &&
<div style={styles.baseline(theme.typography.lineHeight)} />}
</div>
);
export default compose(
connect((state: State) => ({
baselineShown: state.app.baselineShown,
theme: themes[state.app.currentTheme] || themes.defaultTheme,
})),
)(Baseline);
|
src/Components/Tabs/Tabs.js | sashasushko/moira-front | // @flow
import React from 'react';
import Tabs from 'retail-ui/components/Tabs';
import cn from './Tabs.less';
type Props = {|
value: string;
children: any;
|};
type TabProps = {|
id: string;
label: string;
children: any;
|};
type State = {|
active: string;
|};
const TabsTab = Tabs.Tab;
export default class TabsCustom extends React.Component {
props: Props;
state: State;
constructor(props: Props) {
super(props);
this.state = {
active: props.value,
};
}
static Tab = function Tab({ children }: TabProps): React.Element<*> {
return <div>{children}</div>;
};
render(): React.Element<*> {
const { active } = this.state;
const { children } = this.props;
return React.Children.count(children) === 1 ? (
<div>{children}</div>
) : (
<div>
<div className={cn('header')}>
<Tabs value={active} onChange={(target, value) => this.setState({ active: value })}>
{React.Children.map(children, ({ props }) => <TabsTab id={props.id}>{props.label}</TabsTab>)}
</Tabs>
</div>
{React.Children.toArray(children).filter(({ props }) => props.id === active)}
</div>
);
}
}
export const Tab = TabsCustom.Tab;
|
app/config/routes.js | joshuar500/repository-notes | import React from 'react';
import Main from '../components/Main';
import Home from '../components/Home';
import Profile from '../components/Profile';
import Router from 'react-router';
import { Route, IndexRoute } from 'react-router';
export default (
// when at index of homepage, render Route component
<Route path="/" component={Main}>
<Route path="profile/:username" component={Profile} />
<IndexRoute component={Home} />
</Route>
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.