path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/library/Form/FormFieldDivider.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import { FormFieldDividerRoot as Root } from './styled';
import { formFieldDividerPropTypes } from './propTypes';
import type { FormFieldDividerProps } from './types';
const FormFieldDivider = (props: FormFieldDividerProps) => (
<Root {...props} role="separator" />
);
FormFieldDivider.displayName = 'FormFieldDivider';
FormFieldDivider.propTypes = formFieldDividerPropTypes;
export default FormFieldDivider;
|
src/svg-icons/editor/title.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorTitle = (props) => (
<SvgIcon {...props}>
<path d="M5 4v3h5.5v12h3V7H19V4z"/>
</SvgIcon>
);
EditorTitle = pure(EditorTitle);
EditorTitle.displayName = 'EditorTitle';
EditorTitle.muiName = 'SvgIcon';
export default EditorTitle;
|
webapp/app/components/SaveCreation/index.js | EIP-SAM/SAM-Solution-Server | //
// Page create save
//
import React from 'react';
import { PageHeader } from 'react-bootstrap';
import SaveCreationForm from 'containers/SaveCreation/Form';
/* eslint-disable react/prefer-stateless-function */
export default class SaveCreation extends React.Component {
componentWillUnmount() {
this.props.resetStateForm();
}
render() {
return (
<div>
<PageHeader>Scheduled Save</PageHeader>
<SaveCreationForm />
</div>
);
}
}
SaveCreation.propTypes = {
resetStateForm: React.PropTypes.func,
};
|
ui/src/components/common/LeftMenu.js | d3sw/conductor | import React from 'react';
import {Link} from 'react-router'
import {connect} from 'react-redux';
const menuPaths = {
Workflow: [{
header: true,
label: 'Executions',
href: '/events',
icon: 'fa-star'
}, {
label: 'All',
href: '/workflow',
icon: 'fa-circle-thin'
}, {
label: 'Running',
href: '/workflow?status=RUNNING',
icon: 'fa-play-circle'
}, {
label: 'Reset',
href: '/workflow?status=RESET&h=48',
icon: 'fa-refresh'
}, {
label: 'Failed',
href: '/workflow?status=FAILED&h=48',
icon: 'fa-warning'
}, {
label: 'Timed Out',
href: '/workflow?status=TIMED_OUT&h=48',
icon: 'fa-clock-o'
}, {
label: 'Cancelled',
href: '/workflow?status=CANCELLED&h=48',
icon: 'fa-times-circle'
}, {
label: 'Terminated',
href: '/workflow?status=TERMINATED&h=48',
icon: 'fa-ban'
}, {
label: 'Completed',
href: '/workflow?status=COMPLETED&h=48',
icon: 'fa-bullseye'
}, {
header: true,
label: 'Metadata',
href: '/events',
icon: 'fa-star'
}, {
label: 'Workflow Defs',
href: '/workflow/metadata',
icon: 'fa-code-fork'
}, {
label: 'Tasks',
href: '/workflow/metadata/tasks',
icon: 'fa-tasks'
}, {
header: true,
label: 'Workflow Events',
href: '/events',
icon: 'fa-star'
}, {
label: 'Event Handlers',
href: '/events',
icon: 'fa-star'
}, {
header: true,
label: 'Task Queues',
href: '/events',
icon: 'fa-star'
}, {
label: 'Poll Data',
href: '/workflow/queue/data',
icon: 'fa-exchange'
},
{
header: true,
label: 'Error Dashboard',
href: '/events',
icon: 'fa-star'
}, {
label: 'Dashboard',
href: '/workflow/errorDashboard',
icon: 'fa-exchange'
}
]
};
const LeftMenu = React.createClass({
getInitialState() {
return {
sys: {},
minimize: false
};
},
handleResize(e) {
this.setState({windowWidth: window.innerWidth, minimize: window.innerWidth < 600});
},
componentDidMount() {
window.addEventListener('resize', this.handleResize);
},
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
},
componentWillReceiveProps(nextProps) {
this.state.loading = nextProps.fetching;
this.state.version = nextProps.version;
this.state.minimize = nextProps.minimize;
},
render() {
let minimize = this.state.minimize;
let appName = 'Workflow';
const width = minimize ? '50px' : '176px';
if (this.props.appName) {
appName = this.props.appName;
}
let display = minimize ? 'none' : '';
let menuItems = [];
let keyVal = 0;
menuPaths[appName].map((cv, i, arr) => {
let iconClass = 'fa ' + cv['icon'];
if (cv['header'] == true) {
menuItems.push((
<div className="" key={`key-${(keyVal += 1)}`}>
<div className='menuHeader'><i className='fa fa-angle-right'></i> {cv['label']}</div>
</div>
));
} else {
menuItems.push((
<Link to={cv['href']} key={`key-${(keyVal += 1)}`}>
<div className='menuItem'>
<i className={iconClass} style={{width: '20px'}}></i>
<span style={{marginLeft: '10px', display: display}}>
{cv['label']}
</span>
</div>
</Link>
));
}
});
return (
<div className="left-menu" style={{width: width}}>
<div className="logo textual pull-left">
<Link to="/logout" style={{cursor: 'pointer', paddingBottom: '0px'}}>
<i className="fa fa-sign-out"/> Logout
</Link>
<Link to="/" style={{paddingTop: '0px'}}>
<i className={this.state.loading ? "fa fa-bars fa-spin fa-1x" : "fa fa-bars"}/> Conductor
</Link>
</div>
<div className="menuList">
{menuItems}
</div>
</div>
);
}
});
export default connect(state => state.workflow)(LeftMenu);
|
src/app/Content.js | zangrafx/esnext-quickstart | import React from 'react';
import styles from './Content.css';
export default class Content extends React.Component {
render() {
return (
<section className={styles.content}>
<h1>Hello, SydJS!</h1>
</section>
);
}
}
|
src/components/chrome/ChromePointerCircle.js | socialtables/react-color | 'use strict' /* @flow */
import React from 'react'
import ReactCSS from 'reactcss'
import shallowCompare from 'react-addons-shallow-compare'
export class ChromePointerCircle extends ReactCSS.Component {
shouldComponentUpdate = shallowCompare.bind(this, this, arguments[0], arguments[1])
classes(): any {
return {
'default': {
picker: {
width: '12px',
height: '12px',
borderRadius: '6px',
boxShadow: 'inset 0px 0px 0px 1px #fff',
transform: 'translate(-6px, -6px)',
},
},
}
}
render(): any {
return (
<div is="picker"></div>
)
}
}
export default ChromePointerCircle
|
src/components/ImgFigure.js | mojm/photobyreact | import React from 'react';
import ReactDOM from 'react-dom';
require('../css/ImgFigure.scss');
var ImgFigure = React.createClass({
handleClick: function(e) {
if (this.props.arrange.isCenter) {
this.props.inverse();
} else {
this.props.center();
}
e.stopPropagation();
e.preventDefault();
},
render: function() {
var styleObj = {};
if (this.props.arrange.pos) {
styleObj = this.props.arrange.pos;
}
if (this.props.arrange.rotate) {
(['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function(value) {
styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)';
}.bind(this))
}
if (this.props.arrange.isCenter) {
styleObj.zIndex = 11;
}
var imgFigureClassName = 'img-figure';
imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : '';
return (
<figure className ={imgFigureClassName} style = {styleObj} onClick={this.handleClick}>
<img src={this.props.data.imageURL} alt={this.props.data.title}/>
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
<div className="img-back" onClick={this.handleClick}>
<p>{this.props.data.des}</p>
</div>
</figcaption>
</figure>
)
}
});
export default ImgFigure; |
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentSimplifyTypeArgs/__tests__/fixtures/All.js | mroch/flow | // @flow
import React from 'react';
class MyComponent extends React.Component<DefaultProps, Props, State> {
static defaultProps: DefaultProps = {};
state: State = {};
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
const expression = () =>
class extends React.Component<DefaultProps, Props, State> {
static defaultProps: DefaultProps = {};
state: State = {};
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
|
packages/@lyra/components/src/lists/grid/GridList.js | VegaPublish/vega-studio | // @flow
import React from 'react'
import styles from './styles/GridList.css'
import cx from 'classnames'
export default function GridList(props: {className: string}) {
const {
className,
onSortEnd,
onSortStart,
lockToContainerEdges,
useDragHandle,
...rest
} = props
return <ul {...rest} className={cx(styles.root, className)} />
}
|
src/webview/js/app.js | julianburr/sketch-plugin-boilerplate | import React, { Component } from 'react';
import { sendAction } from 'actions/bridge';
import { autobind } from 'core-decorators';
import { connect } from 'react-redux';
import sketchLogo from 'assets/sketch-logo.svg';
import 'styles/index.scss';
const mapStateToProps = state => {
return {
actions: state.bridge.actions
};
};
const mapDispatchToProps = dispatch => {
return {
sendAction: (name, payload) => dispatch(sendAction(name, payload))
};
};
@connect(mapStateToProps, mapDispatchToProps)
@autobind
export default class App extends Component {
sendMessage () {
this.props.sendAction('foo', {foo: 'bar'});
}
render () {
return (
<div className="app">
<img className='logo' src={sketchLogo} width={100} />
<h1>Sketch Plugin Boilerplate</h1>
<div className="app-content">
<p>To get started, edit <code>src/webview/js/app.js</code> and save to reload.</p>
<p><button onClick={this.sendMessage}>Send Action</button></p>
{this.props.actions.map(action => {
return <pre>{JSON.stringify(action, null, 2)}</pre>;
})}
</div>
</div>
);
}
}
|
client/src/components/forms/Systems.js | DjLeChuck/recalbox-manager | import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import { Form } from 'react-form';
import BootstrapForm from 'react-bootstrap/lib/Form';
import Panel from 'react-bootstrap/lib/Panel';
import Well from 'react-bootstrap/lib/Well';
import reactStringReplace from 'react-string-replace';
import { getDefaultValues } from './utils';
import FormActions from './FormActions';
import SwitchInput from './inputs/Switch';
import SelectInput from './inputs/Select';
import SimpleInput from './inputs/Simple';
const SystemsForm = ({ t, saving, onSubmit, defaultValues, dataset }) => {
const retroachievementDesc = reactStringReplace(t("RetroAchievements.org (%s) est un site communautaire qui permet de gagner des haut-faits sur mesure dans les jeux d'arcade grâce à l'émulation."), '%s', (match, i) => (
<a key={i} href="http://retroachievements.org/">http://retroachievements.org/</a>
));
return (
<Form
onSubmit={values => onSubmit(values)}
defaultValues={getDefaultValues(defaultValues)}
>
{({ submitForm, resetForm }) => (
<BootstrapForm horizontal onSubmit={submitForm}>
<Panel header={<h3>{t("Ratio de l'écran")}</h3>}>
<SelectInput id="global-ratio" field="global.ratio"
data={dataset.ratioList}
/>
</Panel>
<Panel header={<h3>{t("Set de shaders")}</h3>}>
<SelectInput id="global-shaderset" field="global.shaderset"
data={dataset.shadersets} preComponent={
<div className="bs-callout bs-callout-warning">
<h4>{t('Shaders disponibles :')}</h4>
<ul>
<li><strong>scanlines</strong> {t('active les scanlines sur tous les emulateurs,')}</li>
<li>
<strong>retro</strong>{' '}
{t('sélectionne le "meilleur" shader pour chaque système, choisi par la communauté.')}{' '}
{t("Il vous apportera l'expérience de jeu la plus proche de l'expérience originale,")}</li>
<li><strong>none</strong> {t('ne met aucun shaders.')}</li>
</ul>
</div>
}
/>
</Panel>
<Panel header={<h3>{t('Lissage des jeux')}</h3>}>
<SwitchInput field="global.smooth" />
</Panel>
<Panel header={<h3>{t('Rembobinage des jeux')}</h3>}>
<SwitchInput field="global.rewind"
help={<p>{t("L'option rembobinage vous autorise à effectuer des retours dans le temps lors de votre partie.")}</p>}
warning={t("Cela peut ralentir certains émulateurs (snes, psx) si vous l'activez par défaut.")}
/>
</Panel>
<Panel header={<h3>{t('Sauvegarde / Chargement automatique')}</h3>}>
<SwitchInput field="global.autosave"
help={
<div>
<p>{t('Cette option vous permet de créer une sauvegarde automatique de votre jeu quand vous le quittez, puis de la charger à nouveau quand vous le relancerez.')}</p>
<p>{t("Une fois le jeu lancé et la sauvegarde chargée, si vous souhaitez revenir à l'écran titre du jeu, utilisez la commande spéciale de reset.")}</p>
</div>
}
/>
</Panel>
<Panel header={<h3>{t('Pixel perfect')}</h3>}>
<SwitchInput field="global.integerscale"
help={<p>{t('Une fois activée, votre écran sera rognée, et vous aure un rendu "pixel perfect" dans vos jeux.')}</p>}
/>
</Panel>
<Panel header={<h3>{t('Retroachievements')}</h3>}>
<SwitchInput field="global.retroachievements"
id="global-retroachievements"
label={t('Activer RetroAchievements')} help={
<div>
<p>{retroachievementDesc}</p>
<p>{t('Les haut-faits sont conçus par et pour la communauté.')}</p>
</div>
}
/>
<Well>
<SimpleInput id="retroachievements-username" label={t('Login')}
field="global.retroachievements.username"
/>
<SimpleInput type="password" id="retroachievements-password"
label={t('Mot de passe')}
field="global.retroachievements.password"
/>
<SwitchInput field="global.retroachievements.hardcore"
id="global-retroachievements-hardcore"
label={t('Activer le mode Hardcore')}
warning={
<span>
{t("Le mode Hardcore désactive *toutes* les possibilités de sauvegarder dans l'émulateur : vous ne pourrez ni sauvegarder ni recharger votre partie en cours de jeu.")}
<br />
{t("Vous devrez compléter le jeu et obtenir les hauts-faits du premier coup, comme c'était le cas sur la console originale !")}
</span>
}
/>
</Well>
</Panel>
<FormActions resetForm={resetForm} saving={saving} />
</BootstrapForm>
)}
</Form>
);
};
SystemsForm.propTypes = {
t: PropTypes.func.isRequired,
saving: PropTypes.bool.isRequired,
onSubmit: PropTypes.func.isRequired,
defaultValues: PropTypes.object,
dataset: PropTypes.object,
};
export default translate()(SystemsForm);
|
index.js | nchaulet/bitbucket-team-pullrequests | import Root from './src/containers/Root';
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(<Root />, document.getElementById('root'));
|
pootle/static/js/auth/components/RequestPasswordResetSent.js | JohnnyKing94/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';
import { PureRenderMixin } from 'react-addons-pure-render-mixin';
import { requestPasswordReset } from '../actions';
import AuthContent from './AuthContent';
import RequestPasswordResetProgress from './RequestPasswordResetProgress';
const RequestPasswordResetSent = React.createClass({
propTypes: {
dispatch: React.PropTypes.func.isRequired,
isLoading: React.PropTypes.bool.isRequired,
resetEmail: React.PropTypes.string.isRequired,
},
mixins: [PureRenderMixin],
/* Handlers */
handleResendEmail() {
this.props.dispatch(requestPasswordReset({
email: this.props.resetEmail,
}));
},
/* Layout */
render() {
if (this.props.isLoading) {
return <RequestPasswordResetProgress email={this.props.resetEmail} />;
}
const emailLinkMsg = interpolate(
gettext('We have sent an email containing the special link to <span>%s</span>'),
[this.props.resetEmail]
);
const instructionsMsg = gettext(
'Please follow that link to continue the password reset procedure.'
);
const resendMsg = gettext(
"Didn't receive an email? Check if it was accidentally filtered out as spam, " +
'or try requesting another copy of the email.'
);
return (
<AuthContent>
<div className="actions password-reset">
<p dangerouslySetInnerHTML={{ __html: emailLinkMsg }} />
<p>{instructionsMsg}</p>
<hr />
<p>{resendMsg}</p>
<div>
<button
className="btn btn-primary"
onClick={this.handleResendEmail}
>
{gettext('Resend Email')}
</button>
</div>
</div>
</AuthContent>
);
},
});
export default RequestPasswordResetSent;
|
node_modules/react-router/es6/RoutingContext.js | tempestaddepvc/proyecto-electron | import React from 'react';
import RouterContext from './RouterContext';
import warning from './routerWarning';
var RoutingContext = React.createClass({
displayName: 'RoutingContext',
componentWillMount: function componentWillMount() {
process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0;
},
render: function render() {
return React.createElement(RouterContext, this.props);
}
});
export default RoutingContext; |
src/components/Database/DatabaseChartBar/index.js | wu-sheng/sky-walking-ui | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { Component } from 'react';
import { Col } from 'antd';
import { ChartCard, MiniBar } from 'components/Charts';
export default class DatabaseChartBar extends Component {
render() {
const {title, total, data} = this.props;
return (
<Col xs={24} sm={24} md={24} lg={8} xl={8} style={{ padding: '0 4px',marginTop: 8 }}>
<ChartCard
title={title}
total={total}
contentHeight={46}
>
<MiniBar
// animate={false}
data={data}
/>
</ChartCard>
</Col>
);
}
}
|
envkey-react/src/components/assoc_manager/assoc_row/key_generated.js | envkey/envkey-app | import React from 'react'
import h from "lib/ui/hyperscript_with_helpers"
import copy from 'lib/ui/copy'
import {openLinkExternal} from 'lib/ui'
export default class KeyGenerated extends React.Component {
constructor(props){
super(props)
this.state = { copied: false }
}
_kvPair(){
return `ENVKEY=${[this.props.envkey, this.props.passphrase].join("-")}`
}
_kvTruncated(){
return this._kvPair().slice(0, 20) + "…"
}
_onCopy(){
const res = copy(this._kvPair(), {message: "Copy the text below with #{key}"})
if (res){
this.setState({copied: true})
}
}
render(){
return h.div(".key-generated", [
h.span(".close", {onClick: this.props.onClose}, "⨉"),
h.div(".top-row", [
h.span(".primary", this._kvTruncated()),
h.button(".copy", {onClick: ::this._onCopy}, "Copy"),
(this.state.copied ? h.span(".copied", "Key copied.") : "")
]),
h.div(".bottom-row", [
h.p([
"Key generated. "
].concat(
{
server: [
"Copy and set it as an",
h.strong(" environment variable"),
" on your server. Don't share it or store it anywhere else."
],
localKey: [
"Copy it into a",
h.strong(" .env file"),
" at the root of your project directory.",
" This file should be",
h.strong(" ignored "),
" in git, svn, mercurial, etc."
]
}[this.props.joinType])
),
h.a({
href: "https://docs.envkey.com/integration-quickstart.html",
target: "__blank",
onClick: openLinkExternal
}, "Integration quickstart ‣")
])
])
}
} |
src/deposit/DepositModal.js | nuruddeensalihu/binary-next-gen | import React from 'react';
import Modal from '../containers/Modal';
import DepositContainer from './DepositContainer';
export default (props) => (
<Modal shown>
<DepositContainer {...props} />
</Modal>
);
|
src/js/components/ui/NetworkLine/NetworkLine.js | nekuno/client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import styles from './NetworkLine.scss';
import RoundedIcon from "../RoundedIcon/RoundedIcon";
export default class NetworkLine extends Component {
static propTypes = {
network: PropTypes.string.isRequired
};
renderIcon() {
let network = this.props.network;
network = network === 'google' ? 'youtube' : network;
return <RoundedIcon icon={network} size={'small'}/>;
};
renderName() {
return this.props.network.toLowerCase();
}
render() {
return (
<div className={styles.networkLine}>
<div className={styles.networkIcon}>
{this.renderIcon()}
</div>
<div className={styles.networkName}>
{this.renderName()}
</div>
</div>
);
}
} |
src/components/Layout/Bread.js | IssaTan1990/antd-admin | import React from 'react'
import PropTypes from 'prop-types'
import { Breadcrumb, Icon } from 'antd'
import { Link } from 'dva/router'
import styles from './Bread.less'
import pathToRegexp from 'path-to-regexp'
import { queryArray } from '../../utils'
const Bread = ({ menu }) => {
// 匹配当前路由
let pathArray = []
let current
for (let index in menu) {
if (menu[index].router && pathToRegexp(menu[index].router).exec(location.pathname)) {
current = menu[index]
break
}
}
const getPathArray = (item) => {
pathArray.unshift(item)
if (item.bpid) {
getPathArray(queryArray(menu, item.bpid, 'id'))
}
}
if (!current) {
pathArray.push(menu[0])
pathArray.push({
id: 404,
name: 'Not Found',
})
} else {
getPathArray(current)
}
// 递归查找父级
const breads = pathArray.map((item, key) => {
const content = (
<span>{item.icon
? <Icon type={item.icon} style={{ marginRight: 4 }} />
: ''}{item.name}</span>
)
return (
<Breadcrumb.Item key={key}>
{((pathArray.length - 1) !== key)
? <Link to={item.router}>
{content}
</Link>
: content}
</Breadcrumb.Item>
)
})
return (
<div className={styles.bread}>
<Breadcrumb>
{breads}
</Breadcrumb>
</div>
)
}
Bread.propTypes = {
menu: PropTypes.array,
}
export default Bread
|
src/atoms/social/speaker/social-link.js | dsmjs/components | import React from 'react';
import {bool, func, string} from 'prop-types';
import Icon from 'react-simple-icons';
import ExternalLink from '../../links/external';
const iconSize = 20;
const listItemStyles = {
padding: '0 0 0 .5em',
height: iconSize,
span: {
paddingLeft: '.25em'
}
};
export const nonHoveredIconColor = '#888';
export default function SocialLink({hovered, service, account, brandColor, onMouseEnter, onMouseLeave}) {
return (
<li css={listItemStyles} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
<ExternalLink to={`https://${service}.com/${account}`} variant="inlineIconWithText">
<Icon fill={hovered ? brandColor : nonHoveredIconColor} size={iconSize} name={service} />
<span>{account}</span>
</ExternalLink>
</li>
);
}
SocialLink.propTypes = {
hovered: bool.isRequired,
service: string.isRequired,
account: string,
brandColor: string.isRequired,
onMouseEnter: func,
onMouseLeave: func
};
|
src/components/posts_index.js | JRiepe/reactblog | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions/index';
import { Link } from 'react-router';
class PostsIndex extends Component {
componentWillMount() {
this.props.fetchPosts();
}
renderPosts() {
return this.props.posts.map((post) => {
return (
<li className="list-group-item" key={post.id}>
<Link to={"posts/" + post.id}>
<span className="pull-xs-right">{post.categories}</span>
<strong>{post.title}</strong>
</Link>
</li>
)
});
}
render() {
return (
<div>
<div className="text-xs-right">
<Link to="/posts/new" className="btn btn-primary">
Add a Post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.post.all };
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex); |
packages/react-vis/src/radar-chart/index.js | uber/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import PropTypes from 'prop-types';
import {scaleLinear} from 'd3-scale';
import {format} from 'd3-format';
import {AnimationPropType} from 'animation';
import XYPlot from 'plot/xy-plot';
import {DISCRETE_COLOR_RANGE} from 'theme';
import {MarginPropType} from 'utils/chart-utils';
import {getCombinedClassName} from 'utils/styling-utils';
import MarkSeries from 'plot/series/mark-series';
import PolygonSeries from 'plot/series/polygon-series';
import LabelSeries from 'plot/series/label-series';
import DecorativeAxis from 'plot/axis/decorative-axis';
const predefinedClassName = 'rv-radar-chart';
const DEFAULT_FORMAT = format('.2r');
/**
* Generate axes for each of the domains
* @param {Object} props
- props.animation {Boolean}
- props.domains {Array} array of object specifying the way each axis is to be plotted
- props.style {object} style object for the whole chart
- props.tickFormat {Function} formatting function for axes
- props.startingAngle {number} the initial angle offset
* @return {Array} the plotted axis components
*/
function getAxes(props) {
const {
animation,
domains,
startingAngle,
style,
tickFormat,
hideInnerMostValues
} = props;
return domains.map((domain, index) => {
const angle = (index / domains.length) * Math.PI * 2 + startingAngle;
const sortedDomain = domain.domain;
const domainTickFormat = t => {
if (hideInnerMostValues && t === sortedDomain[0]) {
return '';
}
return domain.tickFormat ? domain.tickFormat(t) : tickFormat(t);
};
return (
<DecorativeAxis
animation={animation}
key={`${index}-axis`}
axisStart={{x: 0, y: 0}}
axisEnd={{
x: getCoordinate(Math.cos(angle)),
y: getCoordinate(Math.sin(angle))
}}
axisDomain={sortedDomain}
numberOfTicks={5}
tickValue={domainTickFormat}
style={style.axes}
/>
);
});
}
/**
* Generate x or y coordinate for axisEnd
* @param {Number} axisEndPoint
- epsilon is an arbitrarily chosen small number to approximate axisEndPoints
- to true values resulting from trigonometry functions (sin, cos) on angles
* @return {Number} the x or y coordinate accounting for exact trig values
*/
function getCoordinate(axisEndPoint) {
const epsilon = 10e-13;
if (Math.abs(axisEndPoint) <= epsilon) {
axisEndPoint = 0;
} else if (axisEndPoint > 0) {
if (Math.abs(axisEndPoint - 0.5) <= epsilon) {
axisEndPoint = 0.5;
}
} else if (axisEndPoint < 0) {
if (Math.abs(axisEndPoint + 0.5) <= epsilon) {
axisEndPoint = -0.5;
}
}
return axisEndPoint;
}
/**
* Generate labels for the ends of the axes
* @param {Object} props
- props.domains {Array} array of object specifying the way each axis is to be plotted
- props.startingAngle {number} the initial angle offset
- props.style {object} style object for just the labels
* @return {Array} the prepped data for the labelSeries
*/
function getLabels(props) {
const {domains, startingAngle, style} = props;
return domains.map(({name}, index) => {
const angle = (index / domains.length) * Math.PI * 2 + startingAngle;
const radius = 1.2;
return {
x: radius * Math.cos(angle),
y: radius * Math.sin(angle),
label: name,
style
};
});
}
/**
* Generate the actual polygons to be plotted
* @param {Object} props
- props.animation {Boolean}
- props.data {Array} array of object specifying what values are to be plotted
- props.domains {Array} array of object specifying the way each axis is to be plotted
- props.startingAngle {number} the initial angle offset
- props.style {object} style object for the whole chart
* @return {Array} the plotted axis components
*/
function getPolygons(props) {
const {
animation,
colorRange,
domains,
data,
style,
startingAngle,
onSeriesMouseOver,
onSeriesMouseOut
} = props;
const scales = domains.reduce((acc, {domain, name}) => {
acc[name] = scaleLinear()
.domain(domain)
.range([0, 1]);
return acc;
}, {});
return data.map((row, rowIndex) => {
const mappedData = domains.map(({name, getValue}, index) => {
const dataPoint = getValue ? getValue(row) : row[name];
// error handling if point doesn't exist
const angle = (index / domains.length) * Math.PI * 2 + startingAngle;
// dont let the radius become negative
const radius = Math.max(scales[name](dataPoint), 0);
return {
x: radius * Math.cos(angle),
y: radius * Math.sin(angle),
name: row.name
};
});
return (
<PolygonSeries
animation={animation}
className={`${predefinedClassName}-polygon`}
key={`${rowIndex}-polygon`}
data={mappedData}
style={{
stroke:
row.color || row.stroke || colorRange[rowIndex % colorRange.length],
fill:
row.color || row.fill || colorRange[rowIndex % colorRange.length],
...style.polygons
}}
onSeriesMouseOver={onSeriesMouseOver}
onSeriesMouseOut={onSeriesMouseOut}
/>
);
});
}
/**
* Generate circles at the polygon points for Hover functionality
* @param {Object} props
- props.animation {Boolean}
- props.data {Array} array of object specifying what values are to be plotted
- props.domains {Array} array of object specifying the way each axis is to be plotted
- props.startingAngle {number} the initial angle offset
- props.style {object} style object for the whole chart
- props.onValueMouseOver {function} function to call on mouse over a polygon point
- props.onValueMouseOver {function} function to call when mouse leaves a polygon point
* @return {Array} the plotted axis components
*/
function getPolygonPoints(props) {
const {
animation,
domains,
data,
startingAngle,
style,
onValueMouseOver,
onValueMouseOut
} = props;
if (!onValueMouseOver) {
return;
}
const scales = domains.reduce((acc, {domain, name}) => {
acc[name] = scaleLinear()
.domain(domain)
.range([0, 1]);
return acc;
}, {});
return data.map((row, rowIndex) => {
const mappedData = domains.map(({name, getValue}, index) => {
const dataPoint = getValue ? getValue(row) : row[name];
// error handling if point doesn't exist
const angle = (index / domains.length) * Math.PI * 2 + startingAngle;
// dont let the radius become negative
const radius = Math.max(scales[name](dataPoint), 0);
return {
x: radius * Math.cos(angle),
y: radius * Math.sin(angle),
domain: name,
value: dataPoint,
dataName: row.name
};
});
return (
<MarkSeries
animation={animation}
className={`${predefinedClassName}-polygonPoint`}
key={`${rowIndex}-polygonPoint`}
data={mappedData}
size={10}
style={{
...style.polygons,
fill: 'transparent',
stroke: 'transparent'
}}
onValueMouseOver={onValueMouseOver}
onValueMouseOut={onValueMouseOut}
/>
);
});
}
function RadarChart(props) {
const {
animation,
className,
children,
colorRange,
data,
domains,
height,
hideInnerMostValues,
margin,
onMouseLeave,
onMouseEnter,
startingAngle,
style,
tickFormat,
width,
renderAxesOverPolygons,
onValueMouseOver,
onValueMouseOut,
onSeriesMouseOver,
onSeriesMouseOut
} = props;
const axes = getAxes({
domains,
animation,
hideInnerMostValues,
startingAngle,
style,
tickFormat
});
const polygons = getPolygons({
animation,
colorRange,
domains,
data,
startingAngle,
style,
onSeriesMouseOver,
onSeriesMouseOut
});
const polygonPoints = getPolygonPoints({
animation,
colorRange,
domains,
data,
startingAngle,
style,
onValueMouseOver,
onValueMouseOut
});
const labelSeries = (
<LabelSeries
animation={animation}
key={className}
className={`${predefinedClassName}-label`}
data={getLabels({domains, style: style.labels, startingAngle})}
/>
);
return (
<XYPlot
height={height}
width={width}
margin={margin}
dontCheckIfEmpty
className={getCombinedClassName(className, predefinedClassName)}
onMouseLeave={onMouseLeave}
onMouseEnter={onMouseEnter}
xDomain={[-1, 1]}
yDomain={[-1, 1]}
>
{children}
{!renderAxesOverPolygons &&
axes
.concat(polygons)
.concat(labelSeries)
.concat(polygonPoints)}
{renderAxesOverPolygons &&
polygons
.concat(labelSeries)
.concat(axes)
.concat(polygonPoints)}
</XYPlot>
);
}
RadarChart.displayName = 'RadarChart';
RadarChart.propTypes = {
animation: AnimationPropType,
className: PropTypes.string,
colorType: PropTypes.string,
colorRange: PropTypes.arrayOf(PropTypes.string),
data: PropTypes.arrayOf(PropTypes.object).isRequired,
domains: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string.isRequired,
domain: PropTypes.arrayOf(PropTypes.number).isRequired,
tickFormat: PropTypes.func
})
).isRequired,
height: PropTypes.number.isRequired,
hideInnerMostValues: PropTypes.bool,
margin: MarginPropType,
startingAngle: PropTypes.number,
style: PropTypes.shape({
axes: PropTypes.object,
labels: PropTypes.object,
polygons: PropTypes.object
}),
tickFormat: PropTypes.func,
width: PropTypes.number.isRequired,
renderAxesOverPolygons: PropTypes.bool,
onValueMouseOver: PropTypes.func,
onValueMouseOut: PropTypes.func,
onSeriesMouseOver: PropTypes.func,
onSeriesMouseOut: PropTypes.func
};
RadarChart.defaultProps = {
className: '',
colorType: 'category',
colorRange: DISCRETE_COLOR_RANGE,
hideInnerMostValues: true,
startingAngle: Math.PI / 2,
style: {
axes: {
line: {},
ticks: {},
text: {}
},
labels: {
fontSize: 10,
textAnchor: 'middle'
},
polygons: {
strokeWidth: 0.5,
strokeOpacity: 1,
fillOpacity: 0.1
}
},
tickFormat: DEFAULT_FORMAT,
renderAxesOverPolygons: false
};
export default RadarChart;
|
src/renderer/renderPass.js | gabrielbull/react-router-server | import React from 'react';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import AsyncRenderer from '../components/AsyncRenderer';
import removeDuplicateModules from '../utils/removeDuplicateModules';
const renderPass = (context, element, staticMarkup = false) => {
context.callback = () => {
if (context.finishedLoadingModules && !context.statesRenderPass) {
context.statesRenderPass = true;
context.renderResult = renderPass(context, element, staticMarkup);
if (context.fetchingStates <= 0 && context.modulesLoading <= 0) {
context.resolve({
html: context.renderResult,
state: context.fetchStateResults === undefined ? null : context.fetchStateResults,
modules: context.modules === undefined ? null : removeDuplicateModules(context.modules)
});
}
} else if (context.finishedLoadingModules && context.statesRenderPass || !context.hasModules) {
context.renderResult = renderPass(context, element, staticMarkup);
if (context.fetchingStates <= 0 && context.modulesLoading <= 0) {
context.resolve({
html: context.renderResult,
state: context.fetchStateResults === undefined ? null : context.fetchStateResults,
modules: context.modules === undefined ? null : removeDuplicateModules(context.modules)
});
}
}
};
let component = (
<AsyncRenderer context={context}>
{element}
</AsyncRenderer>
);
let result;
try {
if (staticMarkup) {
result = renderToStaticMarkup(component);
} else {
result = renderToString(component);
}
} catch (e) {
return context.reject(e);
}
if (!context.hasModules && !context.hasStates) {
context.resolve({
html: result,
state: context.fetchStateResults === undefined ? null : context.fetchStateResults,
modules: context.modules === undefined ? null : removeDuplicateModules(context.modules)
});
}
return result;
};
export default renderPass;
|
client/src/components/NotFound.js | marceloogeda/react-graphql-example | import React from 'react';
const NotFound = ({ match }) => {
return (
<div className="NotFound">404 Not Found</div>
);
};
export default NotFound;
|
src-clean/routes.js | SIB-Colombia/dataportal_v2_frontend | import React from 'react'
import { Route, IndexRoute } from 'react-router'
import App from 'components/App'
import { HomePage } from 'components'
const routes = (
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
</Route>
)
export default routes
|
src/svg-icons/device/nfc.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceNfc = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 18H4V4h16v16zM18 6h-5c-1.1 0-2 .9-2 2v2.28c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V8h3v8H8V8h2V6H6v12h12V6z"/>
</SvgIcon>
);
DeviceNfc = pure(DeviceNfc);
DeviceNfc.displayName = 'DeviceNfc';
DeviceNfc.muiName = 'SvgIcon';
export default DeviceNfc;
|
src/components/MainPage/MainContainer.js | coolshare/ReactReduxStarterKit | import React from 'react';
import {connect} from 'react-redux'
import cs from '../../services/CommunicationService'
import Footer from './Footer';
import FormTableContainer from './FormTable/FormTableContainer';
import GoogleMapContainer from './Maps/GoogleMap/GoogleMapContainer';
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import MapContainer from './Maps/MapContainer'
/**
*
*/
class _MainContainer extends React.Component{
handleSelect(tabId) {
cs.dispatch({"type":"switchTab", "tabId":tabId})
}
/**
* render
* @return {ReactElement} markup
*/
render(){
return (
<div id="MainContainer">
<Tabs onSelect={this.handleSelect} selectedIndex={this.props.currentTab}>
<TabList>
<Tab>Form/Table</Tab>
<Tab>Maps</Tab>
<Tab>Others</Tab>
</TabList>
<TabPanel>
<FormTableContainer/>
</TabPanel>
<TabPanel>
<MapContainer/>
</TabPanel>
<TabPanel>
<h4>Under construction</h4>
</TabPanel>
</Tabs>
<Footer/>
</div>
)
}
}
const MainContainer = connect(
store => {
return {
currentTab: store.MainContainerReducer.currentTab
};
}
)(_MainContainer);
export default MainContainer |
frontend/src/components/agency/partnerApplicationListFilter.js | unicef/un-partner-portal | import R from 'ramda';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { browserHistory as history, withRouter } from 'react-router';
import { withStyles } from 'material-ui/styles';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';
import SelectForm from '../forms/selectForm';
import CheckboxForm from '../forms/checkboxForm';
import TextFieldForm from '../forms/textFieldForm';
import Agencies from '../forms/fields/projectFields/agencies';
import { selectMappedSpecializations, selectNormalizedCountries, selectNormalizedCfeiTypes } from '../../store';
import resetChanges from '../eois/filters/eoiHelper';
import CountryField from '../forms/fields/projectFields/locationField/countryField';
const messages = {
choose: 'Choose',
labels: {
search: 'Search',
country: 'Country',
sector: 'Sector & Area of Specialization',
type: 'Type of Application',
agency: 'Agency',
show: 'Show Only Selected Applications',
},
clear: 'clear',
submit: 'submit',
};
const styleSheet = theme => ({
filterContainer: {
padding: `${theme.spacing.unit * 2}px ${theme.spacing.unit * 3}px`,
background: theme.palette.primary[300],
},
button: {
display: 'flex',
justifyContent: 'flex-end',
},
});
export const STATUS_VAL = [
{
value: true,
label: 'Active',
},
{
value: false,
label: 'Finalized',
},
];
class PartnerApplicationListFilter extends Component {
constructor(props) {
super(props);
this.state = {
actionOnSubmit: {},
};
this.onSearch = this.onSearch.bind(this);
}
componentWillMount() {
const { pathName, query, agencyId } = this.props;
const agency = this.props.query.agency_app ? this.props.query.agency_app : agencyId;
history.push({
pathname: pathName,
query: R.merge(query,
{ agency_app: agency },
),
});
}
componentWillReceiveProps(nextProps) {
if (R.isEmpty(nextProps.query)) {
const { pathname } = nextProps.location;
const agencyQ = R.is(Number, this.props.query.agency_app) ? this.props.query.agency_app : this.props.agencyId;
history.push({
pathname,
query: R.merge(this.props.query,
{ agency_app: agencyQ },
),
});
}
}
onSearch(values) {
const { pathName, query } = this.props;
const { project_title, agency_app, did_win, country_code, specializations, eoi } = values;
const agencyQ = R.is(Number, agency_app) ? agency_app : this.props.agencyId;
history.push({
pathname: pathName,
query: R.merge(query, {
page: 1,
project_title,
agency_app: agencyQ,
did_win,
country_code,
specializations: Array.isArray(specializations) ? specializations.join(',') : specializations,
eoi,
}),
});
}
resetForm() {
const query = resetChanges(this.props.pathName, this.props.query);
const { pathName, agencyId } = this.props;
history.push({
pathname: pathName,
query: R.merge(query,
{ agency_app: agencyId },
),
});
}
render() {
const { classes, countryCode, eoiTypes, specs, handleSubmit, reset } = this.props;
return (
<form onSubmit={handleSubmit(this.onSearch)}>
<Grid item xs={12} className={classes.filterContainer} >
<Grid container direction="row" >
<Grid item sm={4} xs={12} >
<TextFieldForm
label={messages.labels.search}
placeholder={messages.labels.search}
fieldName="project_title"
optional
/>
</Grid>
<Grid item sm={4} xs={12}>
<CountryField
initialValue={countryCode}
fieldName="country_code"
label={messages.labels.country}
optional
/>
</Grid>
<Grid item sm={4} xs={12}>
<SelectForm
label={messages.labels.sector}
placeholder={messages.labels.choose}
fieldName="specializations"
multiple
values={specs}
sections
optional
/>
</Grid>
</Grid>
<Grid container direction="row" >
<Grid item sm={3} xs={12} >
<SelectForm
label={messages.labels.type}
placeholder={messages.labels.choose}
fieldName="eoi"
values={eoiTypes}
optional
/>
</Grid>
<Grid item sm={3} xs={12}>
<Agencies
fieldName="agency_app"
label={messages.labels.agency}
placeholder={messages.choose}
optional
/>
</Grid>
<Grid item sm={6} xs={12}>
<CheckboxForm
label={messages.labels.show}
fieldName="did_win"
optional
/>
</Grid>
</Grid>
<Grid item className={classes.button}>
<Button
color="accent"
onTouchTap={() => { reset(); this.resetForm(); }}
>
{messages.clear}
</Button>
<Button
color="accent"
onTouchTap={handleSubmit(this.onSearch)}
>
{messages.labels.search}
</Button>
</Grid>
</Grid>
</form >
);
}
}
PartnerApplicationListFilter.propTypes = {
/**
* reset function
*/
reset: PropTypes.func.isRequired,
classes: PropTypes.object.isRequired,
specs: PropTypes.array.isRequired,
eoiTypes: PropTypes.array.isRequired,
pathName: PropTypes.string,
query: PropTypes.object,
agencyId: PropTypes.number,
};
const formEoiFilter = reduxForm({
form: 'partnerApplicationsForm',
destroyOnUnmount: true,
forceUnregisterOnUnmount: true,
enableReinitialize: true,
})(PartnerApplicationListFilter);
const mapStateToProps = (state, ownProps) => {
const { query: { project_title } = {} } = ownProps.location;
const { query: { country_code } = {} } = ownProps.location;
const { query: { agency_app } = {} } = ownProps.location;
const { query: { did_win } = {} } = ownProps.location;
const { query: { specializations } = {} } = ownProps.location;
const { query: { eoi } = {} } = ownProps.location;
const agencyQ = Number(agency_app);
const specializationsQ = specializations &&
R.map(Number, specializations.split(','));
return {
countries: selectNormalizedCountries(state),
specs: selectMappedSpecializations(state),
eoiTypes: selectNormalizedCfeiTypes(state),
pathName: ownProps.location.pathname,
query: ownProps.location.query,
agencyId: state.session.agencyId,
countryCode: country_code,
initialValues: {
project_title,
country_code,
agency_app: agencyQ,
did_win,
specializations: specializationsQ,
eoi,
},
};
};
const connected = connect(mapStateToProps, null)(formEoiFilter);
const withRouterEoiFilter = withRouter(connected);
export default (withStyles(styleSheet, { name: 'partnerApplicationsFilter' })(withRouterEoiFilter));
|
node_modules/react-router-dom/es/HashRouter.js | charmainetham/charmainetham.github.io | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import warning from 'warning';
import React from 'react';
import PropTypes from 'prop-types';
import createHistory from 'history/createHashHistory';
import Router from './Router';
/**
* The public API for a <Router> that uses window.location.hash.
*/
var HashRouter = function (_React$Component) {
_inherits(HashRouter, _React$Component);
function HashRouter() {
var _temp, _this, _ret;
_classCallCheck(this, HashRouter);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret);
}
HashRouter.prototype.componentWillMount = function componentWillMount() {
warning(!this.props.history, '<HashRouter> ignores the history prop. To use a custom history, ' + 'use `import { Router }` instead of `import { HashRouter as Router }`.');
};
HashRouter.prototype.render = function render() {
return React.createElement(Router, { history: this.history, children: this.props.children });
};
return HashRouter;
}(React.Component);
HashRouter.propTypes = {
basename: PropTypes.string,
getUserConfirmation: PropTypes.func,
hashType: PropTypes.oneOf(['hashbang', 'noslash', 'slash']),
children: PropTypes.node
};
export default HashRouter; |
containers/App.js | jonathanpeterwu/calculator | // import React, { Component } from 'react';
// import SomeApp from './SomeApp';
// import { createStore, combineReducers } from 'redux';
// import { Provider } from 'react-redux';
// import * as reducers from '../reducers';
// const reducer = combineReducers(reducers);
// const store = createStore(reducer);
// export default class App extends Component {
// render() {
// return (
// <Provider store={store}>
// {() => <SomeApp /> }
// </Provider>
// );
// }
// }
|
docs/src/modules/components/AppDrawer.js | lgollut/material-ui | import React from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import { withStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import Drawer from '@material-ui/core/Drawer';
import SwipeableDrawer from '@material-ui/core/SwipeableDrawer';
import Divider from '@material-ui/core/Divider';
import Hidden from '@material-ui/core/Hidden';
import Box from '@material-ui/core/Box';
import DiamondSponsors from 'docs/src/modules/components/DiamondSponsors';
import AppDrawerNavItem from 'docs/src/modules/components/AppDrawerNavItem';
import Link from 'docs/src/modules/components/Link';
import { pageToTitleI18n } from 'docs/src/modules/utils/helpers';
import PageContext from 'docs/src/modules/components/PageContext';
let savedScrollTop = null;
function PersistScroll(props) {
const { children } = props;
const rootRef = React.useRef();
React.useEffect(() => {
const parent = rootRef.current ? rootRef.current.parentElement : null;
const activeElement = document.querySelector('.drawer-active');
if (!parent || !activeElement || !activeElement.scrollIntoView) {
return undefined;
}
const activeBox = activeElement.getBoundingClientRect();
if (savedScrollTop === null || activeBox.top - savedScrollTop < 0) {
// Center the selected item in the list container.
activeElement.scrollIntoView();
// Fix a Chrome issue, reset the tabbable ring back to the top of the document.
document.body.scrollIntoView();
} else {
parent.scrollTop = savedScrollTop;
}
return () => {
savedScrollTop = parent.scrollTop;
};
}, []);
return <div ref={rootRef}>{children}</div>;
}
PersistScroll.propTypes = {
children: PropTypes.node,
};
const styles = (theme) => ({
paper: {
width: 240,
backgroundColor: theme.palette.background.level1,
},
title: {
color: theme.palette.text.secondary,
marginBottom: theme.spacing(0.5),
'&:hover': {
color: theme.palette.primary.main,
},
},
// https://github.com/philipwalton/flexbugs#3-min-height-on-a-flex-container-wont-apply-to-its-flex-items
toolbarIe11: {
display: 'flex',
},
toolbar: {
...theme.mixins.toolbar,
paddingLeft: theme.spacing(3),
display: 'flex',
flexGrow: 1,
flexDirection: 'column',
alignItems: 'flex-start',
justifyContent: 'center',
},
});
function renderNavItems(options) {
const { pages, ...params } = options;
return (
<List>
{pages.reduce(
// eslint-disable-next-line no-use-before-define
(items, page) => reduceChildRoutes({ items, page, ...params }),
[],
)}
</List>
);
}
function reduceChildRoutes({ props, activePage, items, page, depth, t }) {
if (page.displayNav === false) {
return items;
}
if (page.children && page.children.length > 1) {
const title = pageToTitleI18n(page, t);
const topLevel = activePage ? activePage.pathname.indexOf(`${page.pathname}/`) === 0 : false;
items.push(
<AppDrawerNavItem
linkProps={page.linkProps}
depth={depth}
key={title}
topLevel={topLevel && !page.subheader}
openImmediately={topLevel || Boolean(page.subheader)}
title={title}
>
{renderNavItems({ props, pages: page.children, activePage, depth: depth + 1, t })}
</AppDrawerNavItem>,
);
} else {
const title = pageToTitleI18n(page, t);
page = page.children && page.children.length === 1 ? page.children[0] : page;
items.push(
<AppDrawerNavItem
linkProps={page.linkProps}
depth={depth}
key={title}
title={title}
href={page.pathname}
onClick={props.onClose}
/>,
);
}
return items;
}
// iOS is hosted on high-end devices. We can enable the backdrop transition without
// dropping frames. The performance will be good enough.
// So: <SwipeableDrawer disableBackdropTransition={false} />
const iOS = process.browser && /iPad|iPhone|iPod/.test(navigator.userAgent);
function AppDrawer(props) {
const { classes, className, disablePermanent, mobileOpen, onClose, onOpen } = props;
const { activePage, pages } = React.useContext(PageContext);
const userLanguage = useSelector((state) => state.options.userLanguage);
const languagePrefix = userLanguage === 'en' ? '' : `/${userLanguage}`;
const t = useSelector((state) => state.options.t);
const drawer = (
<PersistScroll>
<div className={classes.toolbarIe11}>
<div className={classes.toolbar}>
<Link className={classes.title} href="/" onClick={onClose} variant="h6" color="inherit">
Material-UI
</Link>
{process.env.LIB_VERSION ? (
<Link
color="textSecondary"
variant="caption"
href={`https://material-ui.com${languagePrefix}/versions/`}
onClick={onClose}
>
{`v${process.env.LIB_VERSION}`}
</Link>
) : null}
</div>
</div>
<Divider />
<Box mx={3} my={2}>
<DiamondSponsors spot="drawer" />
</Box>
{renderNavItems({ props, pages, activePage, depth: 0, t })}
</PersistScroll>
);
return (
<nav className={className} aria-label={t('mainNavigation')}>
<Hidden lgUp={!disablePermanent} implementation="js">
<SwipeableDrawer
classes={{
paper: clsx(classes.paper, 'algolia-drawer'),
}}
disableBackdropTransition={!iOS}
variant="temporary"
open={mobileOpen}
onOpen={onOpen}
onClose={onClose}
ModalProps={{
keepMounted: true,
}}
>
{drawer}
</SwipeableDrawer>
</Hidden>
{disablePermanent ? null : (
<Hidden mdDown implementation="css">
<Drawer
classes={{
paper: classes.paper,
}}
variant="permanent"
open
>
{drawer}
</Drawer>
</Hidden>
)}
</nav>
);
}
AppDrawer.propTypes = {
classes: PropTypes.object.isRequired,
className: PropTypes.string,
disablePermanent: PropTypes.bool.isRequired,
mobileOpen: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
onOpen: PropTypes.func.isRequired,
};
export default withStyles(styles)(AppDrawer);
|
src/svg-icons/image/rotate-right.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageRotateRight = (props) => (
<SvgIcon {...props}>
<path d="M15.55 5.55L11 1v3.07C7.06 4.56 4 7.92 4 12s3.05 7.44 7 7.93v-2.02c-2.84-.48-5-2.94-5-5.91s2.16-5.43 5-5.91V10l4.55-4.45zM19.93 11c-.17-1.39-.72-2.73-1.62-3.89l-1.42 1.42c.54.75.88 1.6 1.02 2.47h2.02zM13 17.9v2.02c1.39-.17 2.74-.71 3.9-1.61l-1.44-1.44c-.75.54-1.59.89-2.46 1.03zm3.89-2.42l1.42 1.41c.9-1.16 1.45-2.5 1.62-3.89h-2.02c-.14.87-.48 1.72-1.02 2.48z"/>
</SvgIcon>
);
ImageRotateRight = pure(ImageRotateRight);
ImageRotateRight.displayName = 'ImageRotateRight';
ImageRotateRight.muiName = 'SvgIcon';
export default ImageRotateRight;
|
app/src/containers/Home.js | mertkahyaoglu/mertkahyaoglu.github.io | import React from 'react';
import Profile from '../components/Profile';
import NavMenu from '../components/NavMenu';
import ProjectCard from '../components/ProjectCard';
import SkillCard from '../components/SkillCard';
import SocialMenu from '../components/SocialMenu';
import profile from '../data/profile';
import projects from '../data/projects';
import skills from '../data/skills';
const Home = () => (
<div className="content">
<section id="about" className="about">
<div className="container">
<Profile profile={profile} />
<SocialMenu links={profile.links} />
</div>
</section>
<main>
<section className="skills" id="skills">
<div className="container">
<h3 id="skills" className="title">
{'< Skills />'}
</h3>
<div className="skills">
<div className="skills-wrapper">
<h4>Languages</h4>
<div>
{skills.languages.map((skill, i) => (
<SkillCard key={i} name={skill.name} image={skill.image} />
))}
</div>
</div>
<div className="skills-wrapper">
<h4>Technologies & Frameworks</h4>
<div>
{skills.technologies.map((skill, i) => (
<SkillCard key={i} name={skill.name} image={skill.image} />
))}
</div>
</div>
<div className="skills-wrapper">
<h4>Storage</h4>
<div>
{skills.storage.map((skill, i) => (
<SkillCard key={i} name={skill.name} image={skill.image} />
))}
</div>
</div>
</div>
</div>
</section>
<section className="portfolio" id="portfolio">
<div className="container">
<h3 id="portfolio" className="title">
{'< Portfolio />'}
</h3>
<div className="portfolio-wrapper">
{projects.map((project, i) => (
<ProjectCard key={i} project={project} />
))}
</div>
</div>
</section>
</main>
<div className="sticky-menu">
<NavMenu />
</div>
<a
className="forkme"
href="https://github.com/mertkahyaoglu/mertkahyaoglu.github.io"
>
<img
className="github-ribbon"
src="images/fork.png"
alt="Fork me on GitHub"
/>
</a>
</div>
);
export default Home;
|
admin/client/components/List/ListDownloadForm.js | wmertens/keystone | import React from 'react';
import CurrentListStore from '../../stores/CurrentListStore';
import Popout from '../Popout';
import PopoutList from '../Popout/PopoutList';
import { Button, Checkbox, Form, FormField, InputGroup, SegmentedControl } from 'elemental';
const FORMAT_OPTIONS = [
{ label: 'CSV', value: 'csv' },
{ label: 'JSON', value: 'json' },
];
var ListDownloadForm = React.createClass({
propTypes: {
className: React.PropTypes.string.isRequired,
},
getInitialState () {
return {
format: FORMAT_OPTIONS[0].value,
isOpen: false,
useCurrentColumns: true,
selectedColumns: this.getDefaultSelectedColumns(),
};
},
getDefaultSelectedColumns () {
var selectedColumns = {};
CurrentListStore.getActiveColumns().forEach(col => {
selectedColumns[col.path] = true;
});
return selectedColumns;
},
getListUIElements () {
return Keystone.list.uiElements.map((el) => {
return el.type === 'field' ? {
type: 'field',
field: Keystone.list.fields[el.field],
} : el;
});
},
togglePopout (visible) {
this.setState({
isOpen: visible,
});
},
toggleColumn (column, value) {
const newColumns = Object.assign({}, this.state.selectedColumns);
if (value) {
newColumns[column] = value;
} else {
delete newColumns[column];
}
this.setState({
selectedColumns: newColumns,
});
},
changeFormat (value) {
this.setState({
format: value,
});
},
toggleCurrentlySelectedColumns (e) {
const newState = {
useCurrentColumns: e.target.checked,
selectedColumns: this.getDefaultSelectedColumns(),
};
this.setState(newState);
},
handleDownloadRequest () {
CurrentListStore.downloadItems(this.state.format, Object.keys(this.state.selectedColumns));
this.togglePopout(false);
},
renderColumnSelect () {
if (this.state.useCurrentColumns) return null;
const possibleColumns = this.getListUIElements().map((el, i) => {
if (el.type === 'heading') {
return <PopoutList.Heading key={'heading_' + i}>{el.content}</PopoutList.Heading>;
}
const columnKey = el.field.path;
const columnValue = this.state.selectedColumns[columnKey];
return (
<PopoutList.Item
key={'item_' + el.field.path}
icon={columnValue ? 'check' : 'dash'}
iconHover={columnValue ? 'dash' : 'check'}
isSelected={columnValue}
label={el.field.label}
onClick={() => this.toggleColumn(columnKey, !columnValue)} />
);
});
return (
<div style={{ borderTop: '1px dashed rgba(0,0,0,0.1)', marginTop: '1em', paddingTop: '1em' }}>
{possibleColumns}
</div>
);
},
render () {
const { useCurrentColumns } = this.state;
return (
<InputGroup.Section className={this.props.className}>
<Button id="listHeaderDownloadButton" isActive={this.state.isOpen} onClick={() => this.togglePopout(!this.state.isOpen)}>
<span className={this.props.className + '__icon octicon octicon-cloud-download'} />
<span className={this.props.className + '__label'}>Download</span>
<span className="disclosure-arrow" />
</Button>
<Popout isOpen={this.state.isOpen} onCancel={() => this.togglePopout(false)} relativeToID="listHeaderDownloadButton">
<Popout.Header title="Download" />
<Popout.Body scrollable>
<Form type="horizontal" component="div">
<FormField label="File format:">
<SegmentedControl equalWidthSegments options={FORMAT_OPTIONS} value={this.state.format} onChange={this.changeFormat} />
</FormField>
<FormField label="Columns:">
<Checkbox autofocus label="Use currently selected" onChange={this.toggleCurrentlySelectedColumns} value checked={useCurrentColumns} />
</FormField>
{this.renderColumnSelect()}
</Form>
</Popout.Body>
<Popout.Footer
primaryButtonAction={this.handleDownloadRequest}
primaryButtonLabel="Download"
secondaryButtonAction={() => this.togglePopout(false)}
secondaryButtonLabel="Cancel" />
</Popout>
</InputGroup.Section>
);
},
});
module.exports = ListDownloadForm;
|
app/components/PostTitle/index.js | brainsandspace/ship | /**
*
* PostTitle
*
*/
import React from 'react';
import styled from 'styled-components';
const Wrapper = styled.h1`
color: firebrick;
text-align: center;
`;
function PostTitle(props) {
return (
<Wrapper>
{props.children}
</Wrapper>
);
}
PostTitle.propTypes = {
};
export default PostTitle;
|
src/index.js | caviles/wflows | /* eslint-disable import/default */
import React from 'react';
import { render } from 'react-dom';
import { browserHistory } from 'react-router';
import { AppContainer } from 'react-hot-loader';
import Root from './components/Root';
import configureStore from './store/configureStore';
require('./favicon.ico'); // Tell webpack to load favicon.ico
import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page.
import { syncHistoryWithStore } from 'react-router-redux';
const store = configureStore();
// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);
render(
<AppContainer>
<Root store={store} history={history} />
</AppContainer>,
document.getElementById('app')
);
if (module.hot) {
module.hot.accept('./components/Root', () => {
const NewRoot = require('./components/Root').default;
render(
<AppContainer>
<NewRoot store={store} history={history} />
</AppContainer>,
document.getElementById('app')
);
});
}
|
client/node_modules/uu5g03/doc/main/server/public/data/source/uu5-bricks-modal.js | UnicornCollege/ucl.itkpd.configurator | import React from 'react';
import $ from 'jquery';
import {BaseMixin, ElementaryMixin, SectionMixin, Tools} from '../common/common.js';
import {FloatMixin} from '../layout/layout.js';
import Header from './modal-header.js';
import Body from './modal-body.js';
import Footer from './modal-footer.js';
import './modal.less';
export const Modal = React.createClass({
//@@viewOn:mixins
mixins: [
BaseMixin,
ElementaryMixin,
SectionMixin,
FloatMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Bricks.Modal',
classNames: {
main: 'uu5-bricks-modal modal',
dialog: 'uu5-bricks-modal-dialog modal-dialog modal-',
content: 'uu5-bricks-modal-dialog modal-content'
},
defaults: {
header: 'noHeader',
body: 'noBody',
animationDuration: 150, // ms
closeTypes: {
closedButton: 'closedButton',
blur: 'blur',
ifc: 'interface'
}
}
},
//@@viewOff:statics
//@@viewOn:propTypes
propTypes: {
size: React.PropTypes.oneOf(['sm', 'md', 'lg']),
shown: React.PropTypes.bool,
sticky: React.PropTypes.bool,
scrollableBackground: React.PropTypes.bool,
onClose: React.PropTypes.func
},
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
getDefaultProps: function () {
return {
size: 'md',
shown: false,
sticky: false,
scrollableBackground: false,
onClose: null
};
},
getInitialState() {
return {
header: this.getHeader(),
content: this.getContent() || this.props.children,
footer: this.getFooter()
};
},
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
componentWillMount: function () {
this.props.shown ? this.open() : this.hide();
// !this.props.shown && this.hide();
},
componentDidMount: function () {
if (!this.props.sticky) {
$(document).on('keyup', (function (e) {
e.which === 27 && !this.isHidden() && this._blur(e);
}).bind(this));
}
},
componentWillReceiveProps: function (nextProps) {
this.setState(function (state) {
var newState = {};
if (nextProps.shown && state.hidden) {
newState.hidden = false;
} else if (!nextProps.shown && !state.hidden) {
newState.hidden = true;
}
newState.content = nextProps.content || nextProps.children || this.state.content;
return newState;
});
},
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
open: function (openedProps, setStateCallback) {
this._stopScroll();
var newState = {
hidden: false
};
if (openedProps) {
openedProps.header !== undefined && (newState.header = openedProps.header);
openedProps.footer !== undefined && (newState.footer = openedProps.footer);
openedProps.content !== undefined && (newState.content = openedProps.content);
}
this.setState(newState, setStateCallback);
return this;
},
close: function (shouldOnClose, setStateCallback) {
if (typeof this.props.onClose === 'function' && shouldOnClose !== false) {
this.props.onClose({ component: this, closeType: this.getDefault().closeTypes.ifc, callback: setStateCallback });
} else {
this._close(setStateCallback);
}
return this;
},
toggle: function (setStateCallback) {
var modal = this;
this.setState(function (state) {
state.hidden ? modal._stopScroll() : modal._startScroll();
return { hidden: !state.hidden };
}, setStateCallback);
return this;
},
isSticky: function () {
return this.props.sticky;
},
//@@viewOff:interface
//@@viewOn:overridingMethods
buildHeaderChild_: function (headerTypes) {
var headerType = this.getHeaderType(headerTypes);
var headerChild;
if (headerType === 'contentOfStandardHeader') {
headerChild = <Header content={headerTypes.header} />;
headerChild = this.cloneChild(headerChild, this.expandHeaderProps(headerChild));
}
return headerChild;
},
expandHeaderProps_: function (headerChild) {
var extendedHeaderProps = this._extendPartProps(headerChild.props, 'header');
if (extendedHeaderProps) {
extendedHeaderProps._sticky = this.props.sticky;
extendedHeaderProps._onClose = this._onCloseHandler;
}
return extendedHeaderProps;
},
buildFooterChild_: function (footerTypes) {
var footerType = this.getFooterType(footerTypes);
var footerChild;
if (footerType === 'contentOfStandardFooter') {
footerChild = <Footer content={footerTypes.footer} />;
footerChild = this.cloneChild(footerChild, this.expandFooterProps(footerChild));
}
return footerChild;
},
expandFooterProps_: function (footerChild) {
return this._extendPartProps(footerChild.props, 'footer');
},
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
_onBlurHandler: function (event) {
event.target.id === this.getId() && this._blur(event);
return this;
},
_onCloseHandler: function (e) {
if (typeof this.props.onClose === 'function') {
this.props.onClose({ component: this, event: e, closeType: this.getDefault().closeTypes.closedButton });
} else {
this._close();
}
return this;
},
_blur: function (e) {
if (typeof this.props.onClose === 'function') {
this.props.onClose({ component: this, event: e, closeType: this.getDefault().closeTypes.blur });
} else {
this._close();
}
return this;
},
_close: function (callback) {
this._startScroll();
this.hide(callback);
return this;
},
_getScrollbarWidth: function () {
var width = 0;
// if scroll bar is visible
if ($(document).height() > $(window).height()) {
var div = document.createElement("div");
div.style.overflow = "scroll";
div.style.visibility = "hidden";
div.style.position = 'absolute';
div.style.width = '100px';
div.style.height = '100px';
// temporarily creates a div into DOM
document.body.appendChild(div);
try {
width = div.offsetWidth - div.clientWidth;
} finally {
document.body.removeChild(div);
}
}
return width;
},
_startScroll: function () {
var modal = this;
// TODO: wrong, but not found better solution
setTimeout(function () {
!modal.props.scrollableBackground && $('body').removeClass('modal-open');
$('body').css('padding-right', '');
}, this.getDefault().animationDuration);
},
_stopScroll: function () {
// TODO: wrong, but not found better solution
!this.props.scrollableBackground && $('body').addClass('modal-open');
var paddingRight = this._getScrollbarWidth();
paddingRight && $('body').css('padding-right', paddingRight);
},
_getMainAttrs: function () {
var mainAttrs = this.buildMainAttrs();
// id because of checking backdrop on click in _onBlurHandler function
mainAttrs.id = this.getId();
!this.props.sticky && (mainAttrs.onClick = this._onBlurHandler);
var sec = (this.getDefault().animationDuration / 1000) + 's';
mainAttrs.style = mainAttrs.style || {};
mainAttrs.style.WebkitTransitionDuration = sec;
mainAttrs.style.MozTransitionDuration = sec;
mainAttrs.style.OTransitionDuration = sec;
mainAttrs.style.transitionDuration = sec;
return mainAttrs;
},
_extendPartProps: function (partProps, part) {
var newProps = {};
// default values is used if child is set as react element so null or undefined will not set!!!
for (var key in partProps) {
partProps[key] !== null && partProps[key] !== undefined && (newProps[key] = partProps[key]);
}
newProps.key = newProps.id;
return newProps;
},
_extendBodyProps: function (bodyProps) {
var id = this.getId() + '-body';
var newProps = {
id: id
};
// default values is used if child is set as react element so null or undefined will not set!!!
for (var key in bodyProps) {
bodyProps[key] !== null && bodyProps[key] !== undefined && (newProps[key] = bodyProps[key]);
}
return Tools.merge(newProps, { key: newProps.id });
},
//@@viewOff:componentSpecificHelpers
// Render
_buildChildren: function () {
var header = this.state.header;
var footer = this.state.footer;
var bodyContent = this.state.content;
var headerChild;
var footerChild;
if (!bodyContent && ((!header && !footer) || header || footer)) {
header = header || this.getDefault().header;
bodyContent = bodyContent || this.getDefault().body;
}
header && (headerChild = this.buildHeaderChild({ header: header }));
footer && (footerChild = this.buildFooterChild({ footer: footer }));
var bodyProps = this._extendBodyProps({ content: bodyContent });
var bodyChild = this.buildChildren({
children: React.createElement(Body, bodyProps)
});
return [headerChild, bodyChild, footerChild];
},
//@@viewOn:render
render: function () {
return (
<div {...this._getMainAttrs()}>
<div className={this.getClassName().dialog + this.props.size}>
<div className={this.getClassName().content}>
{this._buildChildren()}
</div>
</div>
{this.getDisabledCover()}
</div>
);
}
//@@viewOff:render
});
export default Modal; |
src/routes/Login/components/LoginForm/LoginForm.js | ronihcohen/magic-vote | import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
import { Field, reduxForm } from 'redux-form'
import { TextField } from 'redux-form-material-ui'
import RaisedButton from 'material-ui/RaisedButton'
import Checkbox from 'material-ui/Checkbox'
import { RECOVER_PATH, LOGIN_FORM_NAME } from 'constants'
import { required, validateEmail } from 'utils/form'
import classes from './LoginForm.scss'
export const LoginForm = ({ pristine, submitting, handleSubmit }) => (
<form className={classes.container} onSubmit={handleSubmit}>
<Field
name="email"
component={TextField}
floatingLabelText="Email"
validate={[required, validateEmail]}
/>
<Field
name="password"
component={TextField}
floatingLabelText="Password"
type="password"
validate={required}
/>
<div className={classes.submit}>
<RaisedButton
label={submitting ? 'Loading' : 'Login'}
primary
type="submit"
disabled={pristine || submitting}
/>
</div>
<div className={classes.options}>
<div className={classes.remember}>
<Checkbox
name="remember"
value="remember"
label="Remember"
labelStyle={{ fontSize: '.8rem' }}
/>
</div>
<Link className={classes.recover} to={RECOVER_PATH}>
Forgot Password?
</Link>
</div>
</form>
)
LoginForm.propTypes = {
pristine: PropTypes.bool.isRequired, // added by redux-form
submitting: PropTypes.bool.isRequired, // added by redux-form
handleSubmit: PropTypes.func.isRequired // added by redux-form
}
export default reduxForm({
form: LOGIN_FORM_NAME
})(LoginForm)
|
js/screens/NotificationsScreenComponents/Filter.android.js | ujwalramesh/REHU-discourse | /* @flow */
'use strict'
import React from 'react'
import {
Animated,
Easing,
Text,
TouchableHighlight,
View
} from 'react-native'
import Dimensions from 'Dimensions'
import _ from 'lodash'
import Orientation from 'react-native-orientation'
import colors from '../../colors'
class Filter extends React.Component {
static propTypes = {
onChange: React.PropTypes.func.isRequired,
selectedIndex: React.PropTypes.number.isRequired,
tabs: React.PropTypes.array
}
constructor(props) {
super(props)
this.initialOrientation = Orientation.getInitialOrientation()
this.state = {
indicatorWidth: Dimensions.get('window').width / this.props.tabs.length,
selectedIndex: new Animated.Value(props.selectedIndex)
}
}
componentDidMount() {
Orientation.addOrientationListener(this._orientationDidChange.bind(this))
}
componentWillUnmount() {
Orientation.removeOrientationListener(this._orientationDidChange)
}
onDidSelect(index) {
Animated.timing(this.state.selectedIndex, {
easing: Easing.inOut(Easing.ease),
duration: 250,
toValue: index
}).start()
this.props.onChange(index)
}
render() {
return (
<View style={styles.container}>
{this._renderTabs(this.props.tabs)}
<Animated.View
style={[
styles.indicator,
{
width: this.state.indicatorWidth,
left: this._indicatorLeftPosition()
}
]}
/>
</View>
)
}
_renderTabs(tabs) {
return _.map(tabs, (tab, tabIndex) => {
return (
<TouchableHighlight
key={tab}
underlayColor={colors.yellowUIFeedback}
style={[styles.button]}
onPress={() => this.onDidSelect(tabIndex)}>
<Text style={styles.buttonText}>
{tab.toUpperCase()}
</Text>
</TouchableHighlight>
)
})
}
_indicatorLeftPosition() {
return this.state.selectedIndex.interpolate({
inputRange: [0, 1],
outputRange: [0, this.state.indicatorWidth]
})
}
_orientationDidChange(newOrientation) {
let width
if (newOrientation === this.initialOrientation) {
width = Dimensions.get('window').width / this.props.tabs.length
}
else {
width = Dimensions.get('window').height / this.props.tabs.length
}
this.setState({indicatorWidth: width})
}
}
const styles = {
container: {
alignItems: 'flex-end',
justifyContent: 'center',
backgroundColor: colors.grayUILight,
flexDirection: 'row'
},
button: {
flex: 1,
flexDirection: 'column',
backgroundColor: colors.grayUILight
},
buttonText: {
padding: 12,
fontSize: 14,
fontWeight: '500',
color: colors.grayUI,
textAlign: 'center'
},
indicator: {
backgroundColor: colors.grayUI,
height: 3,
position: 'absolute',
bottom: 0
}
}
export default Filter
|
App.js | zhiyuanMA/ReactNativeShowcase | import React, { Component } from 'react';
import { StatusBar, StyleSheet } from 'react-native';
import { StackNavigator } from 'react-navigation';
import MainView from './components/main/MainView';
import Watch from './components/watch/Watch';
import Tinder from './components/tinder/Tinder';
const Showcase = StackNavigator({
Home: { screen: MainView },
Watch: { screen: Watch },
Tinder: { screen: Tinder },
});
export default class App extends React.Component {
componentDidMount() {
StatusBar.setBarStyle(0);
}
render() {
return <Showcase />;
}
}
|
src/components/NextItem.js | aaroncraigongithub/jsla-talk | import React from 'react';
import PropTypes from 'prop-types';
import {
Card,
CardHeader,
CardText,
} from 'material-ui';
import { itemType } from '../propTypes';
import ListItem from './ListItem';
const NextItem = ({ item, onListItemUpdate }) => (
<Card>
<CardHeader title="Next item up" />
<CardText>
<ListItem item={item} onListItemUpdate={onListItemUpdate} />
</CardText>
</Card>
);
NextItem.propTypes = {
item: itemType.isRequired,
onListItemUpdate: PropTypes.func.isRequired,
};
export default NextItem;
|
examples/with-custom-webpack-config/src/client.js | jaredpalmer/react-production-starter | import React from 'react';
import { hydrate } from 'react-dom';
import App from './App';
hydrate(<App />, document.getElementById('root'));
if (module.hot) {
module.hot.accept();
}
|
admin/client/App/shared/Popout/PopoutList.js | danielmahon/keystone | /**
* Render a popout list. Can also use PopoutListItem and PopoutListHeading
*/
import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';
const PopoutList = React.createClass({
displayName: 'PopoutList',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
},
render () {
const className = classnames('PopoutList', this.props.className);
const props = blacklist(this.props, 'className');
return (
<div className={className} {...props} />
);
},
});
module.exports = PopoutList;
// expose the child to the top level export
module.exports.Item = require('./PopoutListItem');
module.exports.Heading = require('./PopoutListHeading');
|
src/components/navbar.js | lucasflores/lucasflores.github.io | import React from 'react'
import styled, { css } from 'styled-components'
import { Flex, Box } from 'grid-styled'
import scrollToElement from 'scroll-to-element'
import Name from './name'
import { media } from '../utils/style'
const Base = styled.div`
padding: 0;
margin: 0;
max-height: 62px;
line-height: 62px;
width: 100vw;
& ul {
width: 100%;
height: 62px;
padding: 0;
margin: 0;
list-style: none;
font-size: 13px;
}
& ul > li a,
& ul > li {
height: 62px;
font-size: 11px;
float: right;
position: relative;
color: #fff;
text-decoration: none;
cursor: pointer;
transition: opacity .3s ease;
}
& ul > li a {
font-family: 'Raleway';
text-transform: uppercase;
font-weight: 600;
letter-spacing: 1px;
margin-right: 32px;
}
${props =>
props.dark &&
css`
background: #fff;
& ul > li a,
& ul > li {
color: #242424;
opacity: 0.6;
}
& ul > li a:hover {
opacity: 1;
}
a {
color: #000;
}
`}
${props =>
props.main &&
css`
background: transparent;
position: absolute;
top: 0;
left: 0;
z-index: 100;
`}
${media.xs`
& ul {
display: none;
}
`}
`
class NavBar extends React.Component {
render() {
const linkMap = this.props.children
.map(el => {
if (el.props.id)
return { name: el.props.children, href: `#${el.props.id}` }
})
.filter(n => n !== undefined)
.reverse()
const links = linkMap.map(function(link) {
return (
<li key={link.name}>
<a
onClick={() => {
scrollToElement(link.href)
}}
>
{link.name}
</a>
</li>
)
})
return (
<Base {...this.props}>
<Flex>
<Box px={2} width={[1, 1 / 3, 2 / 6]}>
<Name />
</Box>
<Box px={2} width={[0, 2 / 3, 4 / 6]}>
<ul>{links}</ul>
</Box>
</Flex>
</Base>
)
}
}
export default NavBar
|
docs/src/sections/TabsSection.js | jesenko/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function TabsSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="tabs">Togglable tabs</Anchor> <small>Tabs, Tab</small>
</h2>
<p>Add quick, dynamic tab functionality to transition through panes of local content.</p>
<h3><Anchor id="tabs-uncontrolled">Uncontrolled</Anchor></h3>
<p>Allow the component to control its own state.</p>
<ReactPlayground codeText={Samples.TabsUncontrolled} exampleClassName="bs-example-tabs" />
<h3><Anchor id="tabs-controlled">Controlled</Anchor></h3>
<p>Pass down the active state on render via props.</p>
<ReactPlayground codeText={Samples.TabsControlled} exampleClassName="bs-example-tabs" />
<h3><Anchor id="tabs-no-animation">No animation</Anchor></h3>
<p>Set the <code>animation</code> prop to <code>false</code></p>
<ReactPlayground codeText={Samples.TabsNoAnimation} exampleClassName="bs-example-tabs" />
<h3><Anchor id="left-tabs">Left tabs</Anchor></h3>
<p>Set <code>position</code> to <code>"left"</code>. Optionally, <code>tabWidth</code> can be passed the number of columns for the tabs.</p>
<ReactPlayground codeText={Samples.LeftTabs} exampleClassName="bs-example-tabs" />
<h3><Anchor id="tabs-props">Props</Anchor></h3>
<h4><Anchor id="tabs-props-area">Tabs</Anchor></h4>
<PropTable component="Tabs"/>
<h4><Anchor id="tabs-props-pane">Tab</Anchor></h4>
<PropTable component="Tab"/>
</div>
);
}
|
examples/universal/client/index.js | omnidan/redux | import 'babel-core/polyfill';
import React from 'react';
import { Provider } from 'react-redux';
import configureStore from '../common/store/configureStore';
import App from '../common/containers/App';
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState);
const rootElement = document.getElementById('app');
React.render(
<Provider store={store}>
{() => <App/>}
</Provider>,
rootElement
);
|
server/sonar-web/src/main/js/app/components/extensions/ProjectAdminPageExtension.js | Builders-SonarSource/sonarqube-bis | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// @flow
import React from 'react';
import { connect } from 'react-redux';
import Extension from './Extension';
import ExtensionNotFound from './ExtensionNotFound';
import { getComponent } from '../../../store/rootReducer';
import { addGlobalErrorMessage } from '../../../store/globalMessages/duck';
type Props = {
component: {
configuration?: {
extensions: Array<{ key: string }>
}
},
location: { query: { id: string } },
params: {
extensionKey: string,
pluginKey: string
}
};
class ProjectAdminPageExtension extends React.Component {
props: Props;
render () {
const { extensionKey, pluginKey } = this.props.params;
const { component } = this.props;
const extension = component.configuration &&
component.configuration.extensions.find(p => p.key === `${pluginKey}/${extensionKey}`);
return extension ? (
<Extension extension={extension} options={{ component }}/>
) : (
<ExtensionNotFound/>
);
}
}
const mapStateToProps = (state, ownProps: Props) => ({
component: getComponent(state, ownProps.location.query.id)
});
const mapDispatchToProps = { onFail: addGlobalErrorMessage };
export default connect(mapStateToProps, mapDispatchToProps)(ProjectAdminPageExtension);
|
manoseimas/compatibility_test/client/app/ResultsView/SimilarityMps/OneMp.js | ManoSeimas/manoseimas.lt | import React from 'react'
import { SimilarityBar, SimilarityWidget } from '../../../components'
import styles from '../../../styles/views/results.css'
const OneMp = ({mp, fraction, topics, user_answers, expandTopics, expanded_mp}) =>
<div className={styles.item} key={mp.id}>
<a href={mp.url} className={styles.logo} target='_blank'>
<div className={styles.img}>
<img src={mp.logo} alt={mp.title + ' logo'} />
</div>
<img src={fraction.logo} className={styles['fraction-logo']} />
</a>
<main>
<div className={styles.title}>{mp.name}, {mp.fraction}, {mp.similarity}%</div>
<SimilarityBar similarity={mp.similarity} />
<a onClick={() => expandTopics(mp.id)}>
Atsakymai pagal klausimus
<div className={styles.arrow}></div>
</a>
</main>
{(expanded_mp === mp.id)
? <div className={styles.topics}><ol>
{topics.map(topic => {
return <li key={topic.id}>
{topic.name} <br />
<SimilarityWidget topic={topic}
items={[mp]}
user_answers={user_answers} />
</li>
})}
</ol></div>
: ''
}
</div>
export default OneMp |
src/client/components/JumbotronTripWidget/JumbotronTripWidget.js | vidaaudrey/trippian | import log from '../../log'
import React from 'react'
import {
Link
}
from 'react-router'
import {
photos as appConfig
}
from '../../config/appConfig'
import {
JumbotronTitleWidget, ContactButtonWidget, StarRatingWidget, JumbotronMetaAreaWidget
}
from '../index'
/*
isTitled will show/hide the title area
isNoContact will show/hide contact button
isMetad: will show/hide the meta area (full-length-container)
*/
const JumbotronTripWidget = ({
isTitled = true, user, title = '', subTitle = '', metaTitle = '', backgroundFeature = appConfig.defaultTripFeature
}) => {
const styles = {
backgroundImage: {
backgroundImage: 'url(' + backgroundFeature + ')'
}
}
log.info('--inside JumbotronTripWidget', user, metaTitle)
return (
<div className = "jumbotron jumbotron-trip-widget" style={styles.backgroundImage} >
{isTitled && <JumbotronTitleWidget title={title} subTitle={subTitle} />}
{<JumbotronMetaAreaWidget isTripPage="true" title={metaTitle} user={user} />}
</div>
)
}
JumbotronTripWidget.displayName = 'JumbotronTripWidget'
export default JumbotronTripWidget
|
client/containers/TimerMulti.js | rickyeh/nimblecode | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import CountdownTimerMulti from './CountdownTimerMulti';
import StartButtonMulti from './StartButtonMulti';
import { endGame, leavePage, updateElapsedTime } from '../actions/index';
class TimerMulti extends Component {
constructor(props) {
super(props);
this.state = {
tenthSeconds: 0,
seconds: 0,
minutes: 0,
message: 'Click the start button to begin!',
timerOn: false,
winner: ''
}
};
startTimer() {
this.setState({
timerOn: true,
message: '0.0'
});
this.intervalID = setInterval(function() {
var tenthSeconds = this.state.tenthSeconds + 1;
var seconds = this.state.seconds;
var minutes = this.state.minutes;
if (tenthSeconds > 9) {
seconds++;
tenthSeconds = 0;
}
if (seconds > 59) {
minutes++;
seconds = 0;
}
var totalTimeInSeconds = ((minutes * 60) + seconds + (tenthSeconds / 10)).toFixed(1);
var time = {
tenthSeconds: tenthSeconds,
seconds: seconds,
minutes: minutes
};
// calling updateElapsedTime action to the MultiTimerReducer
this.props.updateElapsedTime(time);
this.setState({
tenthSeconds : tenthSeconds,
seconds : seconds,
minutes: minutes,
message: totalTimeInSeconds + ' seconds'
});
}.bind(this), 100);
};
componentDidUpdate() {
// On game end, stop timer
if (this.props.multiTimer === 'STOP_TIMER') {
clearInterval(this.intervalID);
}
// On game start, start if not already running
if (this.props.multiGameState === 'STARTED_GAME' && !this.state.timerOn) {
this.startTimer();
}
// if someone leaves page, stop the timer
if (this.props.multiGameState === null) {
clearInterval(this.intervalID);
}
};
componentWillUnmount() {
clearInterval(this.intervalID);
this.props.leavePage();
};
render() {
return (
<div className="container">
<div className="row">
<h2 className="text-center">{this.state.message}</h2>
</div>
<StartButtonMulti socket={this.props.socket} />
<CountdownTimerMulti />
</div>
);
};
};
function mapStateToProps(state) {
return {
multiGameState: state.multiGameState,
multiTimer: state.multiTimer
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ leavePage: leavePage, endGame: endGame, updateElapsedTime: updateElapsedTime }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(TimerMulti); |
src/components/pages/organize/DetailView.js | yiweimatou/yibinghoutai | import React from 'react'
const styles = {
div:{
display:'flex',
flexFlow:'row wrap'
},
img:{
width: 256,
heigt:256
},
dl:{
marginLeft:50
},
dt:{
float: 'left',
width: 160,
overflow: 'hidden',
clear: 'left',
textAlign: 'right',
whiteSpace: 'nowrap',
fontWeight: 'bold',
lineHeight: 1.42857143
},
dd:{
marginLeft: 180,
lineHeight: 1.42857143
}
}
class DetailView extends React.Component {
render() {
const {
organize
} = this.props
if(organize=== null){
return (null)
}
return (
<div style = { styles.div } >
<img src={organize.logo} alt='logo' style = { styles.img }/>
<dl>
<dt style = {styles.dt}>机构名</dt>
<dd style = {styles.dd}>
{organize.oname}
</dd>
<dt style = {styles.dt}>机构状态</dt>
<dd style = {styles.dd}>
{organize.state===1?'正常':organize.state===2?'冻结':'永久冻结'}
</dd>
<dt style = {styles.dt}>管理员</dt>
<dd style = {styles.dd}>
{organize.admin || organize.uid}
</dd>
<dt style = {styles.dt}>机构描述</dt>
<dd style = {styles.dd}>
{organize.descript}
</dd>
</dl>
</div>
)
}
}
DetailView.propTypes = {
organize: React.PropTypes.object
}
export default DetailView |
src/component/listing-item/index.js | Roomlet/roomlet | import React from 'react'
import { connect } from 'react-redux'
import * as listingActions from '../../action/listing-actions.js'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import { List, ListItem } from 'material-ui/List'
import FloatingActionButton from 'material-ui/FloatingActionButton'
import DeleteIcon from 'material-ui/svg-icons/action/delete-forever'
import Paper from 'material-ui/Paper'
import * as util from '../../lib/util.js'
import CheckCircle from 'material-ui/svg-icons/action/check-circle'
class ListingItem extends React.Component {
constructor(props) {
super(props)
this.state = {
verified: this.props.verified,
}
}
componentWillMount() {}
render() {
return (
<div>
{this.props.listings
.filter(listing => listing.verified === this.props.verified)
.map((listing, i) => {
return (
<MuiThemeProvider key={i}>
<Paper zDepth={2} style={{ marginTop: 10 }}>
<List style={{ textAlign: 'left' }}>
<ListItem
key={listing._id}
primaryText={listing.title}
secondaryText={listing.listingURL}
leftIcon={
<div>
{util.renderIf(
this.state.verified,
<CheckCircle style={{ fill: 'green' }} />
)}
</div>
}
rightIconButton={
<FloatingActionButton
onClick={() => this.props.listingDelete(listing)}
mini={true}
backgroundColor="red"
style={{ marginRight: 20 }}
>
<DeleteIcon />
</FloatingActionButton>
}
/>
</List>
</Paper>
</MuiThemeProvider>
)
})}
</div>
)
}
}
const mapStateToProps = state => ({
listings: state.listings,
})
const mapDispatchToProps = (dispatch, getState) => ({
listingDelete: listing => {
dispatch(listingActions.listingDeleteRequest(listing))
},
})
export default connect(mapStateToProps, mapDispatchToProps)(ListingItem)
|
app/screens/containers/seller/goods.js | yiyinsong/react-native-example-jdh | import React, { Component } from 'react';
import {
View,
Text,
ScrollView,
TouchableOpacity,
TouchableHighlight,
TextInput,
Image,
FlatList,
InteractionManager,
DeviceEventEmitter,
Modal
} from 'react-native';
import Utils from '../../../js/utils';
import Config from '../../../config/config';
import styles from '../../../css/styles';
import ScreenInit from '../../../config/screenInit';
import GoodsItem from '../../components/seller/goods-item';
import Loading from '../../common/ui-loading';
import UIToast from '../../common/ui-toast';
import ModalConfirm from '../../common/modal-confirm';
export default class SellerGoodsScreen extends Component {
constructor(props) {
super(props);
this.state = {
type: this.props.navigation.state.params && this.props.navigation.state.params.type || 0,
switchIndex: 0,
switchIndex2: 0,
list1: [],
list2: [],
list3: [],
keyword: '',
page: [0, 0, 0],
loadingVisible: false,
checkAll: [false, false, false],
havenCheck: [[], [], []],
checkTotal: [0, 0, 0],
over: [false, false, false],
tips: ['', '', ''],
visible: false,
cateId: '',
cateLv1: [],
cateLv2: [],
cateLv3: [],
cateIndex: [-1, -1, -1],
brandId: '',
brand: [],
brandIndex: [-1, -1],
filterTabIndex: 0,
};
}
componentDidMount() {
InteractionManager.runAfterInteractions(() => {
if(this.state.type == 1) {
this.refs.containerScrollView.scrollTo({x: Utils.width, y: 0, animated: false});
}
this.setState({loadingVisible: true});
ScreenInit.checkLogin(this);
this._getData();
this._getCate();
this._getBrand();
});
this.listener_update = DeviceEventEmitter.addListener('sellerGoodsUpdate', () => {
//如果是复制商品
if(this.state.type == 2) {
this._filterInit();
this.setState({keyword: '', type: 0});
this.refs.containerScrollView.scrollTo({x: 0, y: 0});
this._reset(0);
this._delayLoading();
} else {
this._reset(this.state.type);
this._delayLoading();
}
});
}
componentWillUnmount() {
this.timer && clearTimeout(this.timer);
this.listener_update && this.listener_update.remove();
}
render() {
let state = this.state;
return (
<View style={styles.common.flexv}>
<View style={styles.sgoods.tab}>
<View style={[styles.sgoods.tabContainer, styles.common.flexDirectionRow]}>
<TouchableHighlight underlayColor="#f5f5f5" onPress={() => this._tab(0)} style={styles.sgoods.tabItem}>
<Text style={[styles.sgoods.tabText, styles.sgoods.tabFirst, state.type == 0 ? styles.sgoods.tabActive : '']}>自建商品</Text>
</TouchableHighlight>
<TouchableHighlight underlayColor="#f5f5f5" onPress={() => this._tab(1)} style={styles.sgoods.tabItem}>
<Text style={[styles.sgoods.tabText, state.type == 1 ? styles.sgoods.tabActive : '']}>分销商品</Text>
</TouchableHighlight>
<TouchableHighlight underlayColor="#f5f5f5" onPress={() => this._tab(2)} style={styles.sgoods.tabItem}>
<Text style={[styles.sgoods.tabText, styles.sgoods.tabLast, state.type == 2 ? styles.sgoods.tabActive : '']}>商品库</Text>
</TouchableHighlight>
</View>
</View>
<View style={[styles.common.flexDirectionRow, styles.sgoods.search]}>
<View style={[styles.common.flex, styles.sgoods.searchForm, styles.common.flexCenterv]}>
<TextInput onChangeText={(text) => this.setState({keyword: text})} value={this.state.keyword} style={[styles.sgoods.searchInput, styles.common.flex]} underlineColorAndroid="transparent" onSubmitEditing={this._search}/>
<Image source={require('../../../images/icon-search@30x30.png')} style={styles.sgoods.searchIcon}/>
</View>
<TouchableOpacity activeOpacity={.8} style={[styles.common.flexDirectionRow, styles.common.flexCenterv]} onPress={this._openFilter}>
<Image source={require('../../../images/icon-filter.png')} style={styles.sgoods.filter}/>
<Text style={styles.sgoods.filterText}>筛选</Text>
</TouchableOpacity>
</View>
<ScrollView style={styles.common.initWhite} horizontal={true} ref="containerScrollView" showsHorizontalScrollIndicator={false} scrollEnabled={false}>
<View style={{width: Utils.width}}>
<View style={[styles.common.flexDirectionRow, styles.sgoods.switchTitle]}>
<TouchableOpacity activeOpacity={.8} style={[styles.common.flex, styles.sgoods.switchItem]} onPress={() => this._switch(0, 0)}>
<Text style={[styles.sgoods.switchText, state.switchIndex == 0 ? styles.sgoods.switchActive : '']}>在售商品</Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity={.8} style={[styles.common.flex, styles.sgoods.switchItem]} onPress={() => this._switch(1, 0)}>
<Text style={[styles.sgoods.switchText, state.switchIndex == 1 ? styles.sgoods.switchActive : '']}>下架商品</Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity={.8} style={[styles.common.flex, styles.sgoods.switchItem]} onPress={() => this._switch(2, 0)}>
<Text style={[styles.sgoods.switchText, state.switchIndex == 2 ? styles.sgoods.switchActive : '']}>回收站</Text>
</TouchableOpacity>
</View>
<FlatList
data={this.state.list1}
renderItem={({item, index}) => <GoodsItem data={item} index={0} sub={this.state.switchIndex} checkFunc={(ischeck) => {this._itemCheck(ischeck, index)}} props={this.props}></GoodsItem>}
getItemLayout={(data, index) => (
{length: 91, offset: 91 * index, index}
)}
ListFooterComponent={this._renderFlatListFooter1()}
onEndReached={() => {this.state.page[0] > 0 ? this._getData() : null}}
onEndReachedThreshold={.1}
/>
<View style={[styles.sgoods.footer, styles.common.flexDirectionRow]}>
<TouchableOpacity onPress={this._checkedItem} onPress={this._checkAllFunc}>
<View style={styles.sgoods.all}>
{this.state.checkAll[0] ?
<Image source={require('../../../images/icon-checked-blue.png')} style={styles.control.checked} />
: <View style={styles.control.checkbox}></View>}
<Text style={styles.sgoods.allText}>全选</Text>
</View>
</TouchableOpacity>
{this._renderList1Btn()}
</View>
</View>
<View style={{width: Utils.width}}>
<View style={[styles.common.flexDirectionRow, styles.sgoods.switchTitle]}>
<TouchableOpacity activeOpacity={.8} style={[styles.common.flex, styles.sgoods.switchItem]} onPress={() => this._switch(0, 1)}>
<Text style={[styles.sgoods.switchText, state.switchIndex2 == 0 ? styles.sgoods.switchActive : '']}>已分销商品</Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity={.8} style={[styles.common.flex, styles.sgoods.switchItem]} onPress={() => this._switch(1, 1)}>
<Text style={[styles.sgoods.switchText, state.switchIndex2 == 1 ? styles.sgoods.switchActive : '']}>未分销商品</Text>
</TouchableOpacity>
</View>
<FlatList
data={this.state.list2}
renderItem={({item, index}) => <GoodsItem data={item} index={1} sub={this.state.switchIndex2} checkFunc={(ischeck) => {this._itemCheck(ischeck, index)}} props={this.props}></GoodsItem>}
getItemLayout={(data, index) => (
{length: 91, offset: 91 * index, index}
)}
ListFooterComponent={this._renderFlatListFooter2()}
onEndReached={() => {this.state.page[1] > 0 ? this._getData() : null}}
onEndReachedThreshold={.1}
/>
<View style={[styles.sgoods.footer, styles.common.flexDirectionRow]}>
<TouchableOpacity onPress={this._checkedItem} onPress={this._checkAllFunc}>
<View style={styles.sgoods.all}>
{this.state.checkAll[1] ?
<Image source={require('../../../images/icon-checked-blue.png')} style={styles.control.checked} />
: <View style={styles.control.checkbox}></View>}
<Text style={styles.sgoods.allText}>全选</Text>
</View>
</TouchableOpacity>
{this._renderList2Btn()}
</View>
</View>
<View style={{width: Utils.width}}>
<View style={[styles.common.flexDirectionRow, styles.sgoods.switchTitle]}></View>
<FlatList
data={this.state.list3}
renderItem={({item, index}) => <GoodsItem data={item} index={2} checkFunc={(ischeck) => {this._itemCheck(ischeck, index)}} props={this.props} copyGoods={(id) => this._copyGoods(id)}></GoodsItem>}
getItemLayout={(data, index) => (
{length: 91, offset: 91 * index, index}
)}
ListFooterComponent={this._renderFlatListFooter3()}
onEndReached={() => {this.state.page[2] > 0 ? this._getData() : null}}
onEndReachedThreshold={.1}
/>
</View>
</ScrollView>
<Loading visible={this.state.loadingVisible}></Loading>
<ModalConfirm keys={4}></ModalConfirm>
<Modal
animationType='fade'
onRequestClose={() => this._close()}
visible={this.state.visible}
transparent={true}
>
<TouchableOpacity style={styles.modal.container} activeOpacity={1} onPress={this._close}></TouchableOpacity>
<View style={[styles.modal.container2, styles.sgoods.filterBox, {width: Utils.width, height: Utils.height * .8}]}>
<Text style={styles.sgoods.filterTitle}>请选择类目</Text>
<View style={[styles.common.flexDirectionRow, styles.sgoods.filterTab]}>
<TouchableOpacity activeOpacity={.8} style={[styles.common.flex, styles.common.flexCenterv, styles.common.flexCenterh, styles.sgoods.filterTabItem]} onPress={() => this._filterTabFunc(0)}>
<Text style={[styles.sgoods.filterTabText, this.state.filterTabIndex == 0 ? styles.sgoods.filterTabTextActive : '']} numberOfLines={1}>{state.cateLv1[state.cateIndex[0]] && state.cateLv1[state.cateIndex[0]].name || '一级分类'}</Text><View style={[styles.select.down, this.state.filterTabIndex == 0 ? styles.select.downActive : '']}></View>
</TouchableOpacity>
<TouchableOpacity activeOpacity={.8} style={[styles.common.flex, styles.common.flexCenterv, styles.common.flexCenterh, styles.sgoods.filterTabItem]} onPress={() => this._filterTabFunc(1)}>
<Text style={[styles.sgoods.filterTabText, this.state.filterTabIndex == 1 ? styles.sgoods.filterTabTextActive : '']} numberOfLines={1}>{state.cateLv2[state.cateIndex[1]] && state.cateLv2[state.cateIndex[1]].name || '二级分类'}</Text><View style={[styles.select.down, this.state.filterTabIndex == 1 ? styles.select.downActive : '']}></View>
</TouchableOpacity>
<TouchableOpacity activeOpacity={.8} style={[styles.common.flex, styles.common.flexCenterv, styles.common.flexCenterh, styles.sgoods.filterTabItem]} onPress={() => this._filterTabFunc(2)}>
<Text style={[styles.sgoods.filterTabText, this.state.filterTabIndex == 2 ? styles.sgoods.filterTabTextActive : '']} numberOfLines={1}>{state.cateLv3[state.cateIndex[2]] && state.cateLv3[state.cateIndex[2]].name || '三级分类'}</Text><View style={[styles.select.down, this.state.filterTabIndex == 2 ? styles.select.downActive : '']}></View>
</TouchableOpacity>
<TouchableOpacity activeOpacity={.8} style={[styles.common.flex, styles.common.flexCenterv, styles.common.flexCenterh, styles.sgoods.filterTabItem]} onPress={() => this._filterTabFunc(3)}>
<Text style={[styles.sgoods.filterTabText, this.state.filterTabIndex == 3 ? styles.sgoods.filterTabTextActive : '']} numberOfLines={1}>品牌</Text><View style={[styles.select.down, this.state.filterTabIndex == 3 ? styles.select.downActive : '']}></View>
</TouchableOpacity>
</View>
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false} scrollEnabled={false} ref="cateScrollView">
<ScrollView style={{width: Utils.width}}>
{this.state.cateLv1.map((v, k) => {
return (
<TouchableHighlight underlayColor='#fafafa' onPress={() => this._selectCate(0, k, v)}>
<Text style={[styles.sgoods.filterItem, this.state.cateIndex[0] == k? styles.sgoods.filterItemActive : '']}>{v.name}</Text>
</TouchableHighlight>
);
})}
</ScrollView>
<ScrollView style={{width: Utils.width}}>
{this.state.cateLv2.map((v, k) => {
return (
<TouchableHighlight underlayColor='#fafafa' onPress={() => this._selectCate(1, k, v)}>
<Text style={[styles.sgoods.filterItem, this.state.cateIndex[1] == k? styles.sgoods.filterItemActive : '']}>{v.name}</Text>
</TouchableHighlight>
);
})}
</ScrollView>
<ScrollView style={{width: Utils.width}}>
{this.state.cateLv3.map((v, k) => {
return (
<TouchableHighlight underlayColor='#fafafa' onPress={() => this._selectCate(2, k, v)}>
<Text style={[styles.sgoods.filterItem, this.state.cateIndex[2] == k? styles.sgoods.filterItemActive : '']}>{v.name}</Text>
</TouchableHighlight>
);
})}
</ScrollView>
<ScrollView style={{width: Utils.width}}>
{this.state.brand.map((v, k) => {
return (
<View>
<Text style={[styles.sgoods.filterItem, styles.sgoods.filterItemActive]}>{v.letter}</Text>
{v.list.map((v1, k1) => {
return (
<TouchableHighlight underlayColor='#fafafa' onPress={() => this._selectBrand(k, k1, v1.brand_id)}>
<Text style={[styles.sgoods.filterItem, (this.state.brandIndex[0] == k && this.state.brandIndex[1] == k1) ? styles.sgoods.filterBrandActive : '']}>{v1.brand_name}</Text>
</TouchableHighlight>
);
})}
</View>
);
})}
</ScrollView>
</ScrollView>
<View style={styles.common.flexDirectionRow}>
<TouchableOpacity activeOpacity={.8} style={styles.common.flex} onPress={this._filterReset}><Text style={styles.sgoods.filterBtnCancel}>重置</Text></TouchableOpacity>
<TouchableOpacity activeOpacity={.8} style={styles.common.flex} onPress={this._filterConfirm}><Text style={styles.sgoods.filterBtnConfirm}>确定</Text></TouchableOpacity>
</View>
</View>
</Modal>
</View>
);
}
_tab = (type) => {
let state = this.state;
if(state.type === type) return;
this._filterInit();
this.setState({keyword: ''});
this.refs.containerScrollView.scrollTo({x: type * Utils.width, y: 0});
requestAnimationFrame(() => {
this.setState({type});
if(type == 0) {
if(state.list1.length === 0 && !state.over[type]) {
this._reset(0);
this._delayLoading();
}
} else if(type == 1) {
if(state.list2.length === 0 && !state.over[type]) {
this._reset(1);
this._delayLoading();
}
} else {
if(state.list3.length === 0 && !state.over[type]) {
this._reset(2);
this._delayLoading();
}
}
});
}
_switch = (i, t) => {
requestAnimationFrame(() => {
if(t == 0 && this.state.switchIndex == i) return;
if(t == 1 && this.state.switchIndex2 == i) return;
this._reset(t);
if(t == 0) {
this.setState({switchIndex: i});
} else {
this.setState({switchIndex2: i});
}
this._delayLoading();
});
}
_delayLoading = () => {
this.setState({loadingVisible: true});
InteractionManager.runAfterInteractions(() => {
this._getData();
});
}
_onScrollOver = (e) => {
let page = Math.floor(e.nativeEvent.contentOffset.x / e.nativeEvent.layoutMeasurement.width);
let state = this.state;
if(page == state.type) return;
this._filterInit();
this.setState({type: page, keyword: ''});
if(page == 0) {
if(state.list1.length === 0 && !state.over[page]) {
this._reset(0);
this._delayLoading();
}
} else if(page == 1) {
if(state.list2.length === 0 && !state.over[page]) {
this._reset(1);
this._delayLoading();
}
} else {
if(state.list3.length === 0 && !state.over[page]) {
this._reset(2);
this._delayLoading();
}
}
}
_getData = () => {
let state = this.state;
if(state.over[state.type]) return;
this.state.page[state.type]++;
let _url = '';
if(state.type == 0) {
_url = Config.PHPAPI + `api/mapp/goods-seller/list?keyword=${state.keyword}&page=${state.page[state.type]}&pageSize=10&cateId=${state.cateId}&brandId=${state.brandId}&show=${state.switchIndex}&imgSize=200&token=${token}`
} else if (state.type == 1) {
_url = Config.PHPAPI + `api/mapp/goods-seller/jicai?keyword=${state.keyword}&page=${state.page[state.type]}&pageSize=10&cateId=${state.cateId}&brandId=${state.brandId}&imgSize=200&token=${token}&dType=${state.switchIndex2 + 1}`
} else {
_url = Config.PHPAPI + `api/mapp/goods-seller/library?keyword=${state.keyword}&page=${state.page[state.type]}&pageSize=10&cateId=${state.cateId}&brandId=${state.brandId}&imgSize=200&token=${token}`
}
fetch(_url, {
method: 'GET'
})
.then(response => response.json())
.then((data) => {
if(data.error_code == 0) {
let _over = state.over;
let _tips = state.tips;
if(state.type == 0) {
//防止快速切换导致数据错误
if(state.switchIndex !== this.state.switchIndex) return;
this.setState({loadingVisible: false});
if(data.data.currentPage >= data.data.pageCount) {
_over[state.type] = true;
_tips[state.type] = '没有更多数据';
} else {
_tips[state.type] = '加载数据中...';
}
let _tempCheckAll = this.state.checkAll;
_tempCheckAll[state.type] = false;
let _temp = [...state.list1, ...data.data.list];
this.setState({list1: _temp, over: _over, tips: _tips, checkAll: _tempCheckAll});
} else if(state.type == 1) {
if(state.switchIndex2 !== this.state.switchIndex2) return;
this.setState({loadingVisible: false});
if(data.data.currentPage >= data.data.pageCount) {
_over[state.type] = true;
_tips[state.type] = '没有更多数据';
} else {
_tips[state.type] = '加载数据中...';
}
let _tempCheckAll = this.state.checkAll;
_tempCheckAll[state.type] = false;
let _temp = [...state.list2, ...data.data.list];
this.setState({list2: _temp, over: _over, tips: _tips, checkAll: _tempCheckAll});
} else {
this.setState({loadingVisible: false});
if(data.data.currentPage >= data.data.pageCount) {
_over[state.type] = true;
_tips[state.type] = '没有更多数据';
} else {
_tips[state.type] = '加载数据中...';
}
let _tempCheckAll = this.state.checkAll;
_tempCheckAll[state.type] = false;
let _temp = [...state.list3, ...data.data.list];
this.setState({list3: _temp, over: _over, tips: _tips, checkAll: _tempCheckAll});
}
}
});
}
_getCate = () => {
fetch(Config.PHPAPI + 'api/mapp/shop/cate', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `token=${token}`
})
.then(response => response.json())
.then((r) => {
if(r.error_code == 0) {
this.state.cateLv1 = r.data;
}
});
}
_getBrand = (arr) => {
let _cid = '';
if(arr) {
_cid = arr[0] > 0 ? this.state.cateLv1[arr[0]].id : '';
_cid += (arr[1] > 0 ? (',' + this.state.cateLv2[arr[1]].id) : '');
_cid += (arr[2] > 0 ? (',' + this.state.cateLv3[arr[2]].id) : '');
}
fetch(Config.PHPAPI + 'api/mapp/shop/brand', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `cateId=${_cid}&token=${token}`
})
.then(response => response.json())
.then((r) => {
if(r.error_code == 0) {
this.state.brand = r.data.length ? r.data : [];
}
});
}
_checkAllFunc = () => {
let _type = this.state.type;
let _ori = !this.state.checkAll[_type];
let _temp = this.state.checkAll;
_temp[_type] = _ori;
this.setState({
checkAll: _temp
});
this.state.havenCheck[_type] = [];
if (_type == 0) {
if(_ori) {
this.state.checkTotal[0] = this.state.list1.length;
for(var i=0, l=this.state.list1.length; i<l; i++) {
this.state.havenCheck[0].push(true);
}
} else {
this.state.checkTotal[0] = 0;
}
} else if (_type == 1) {
if(_ori) {
this.state.checkTotal[1] = this.state.list2.length;
for(var i=0, l=this.state.list2.length; i<l; i++) {
this.state.havenCheck[1].push(true);
}
} else {
this.state.checkTotal[1] = 0;
}
} else {
if(_ori) {
this.state.checkTotal[2] = this.state.list3.length;
for(var i=0, l=this.state.list3.length; i<l; i++) {
this.state.havenCheck[2].push(true);
}
} else {
this.state.checkTotal[2] = 0;
}
}
DeviceEventEmitter.emit('sellerGoodsCheck', {checked: _ori, index: _type});
}
_itemCheck = (ischeck, index) => {
let _type = this.state.type;
this.state.havenCheck[_type][index] = ischeck;
ischeck ? this.state.checkTotal[_type]++ : this.state.checkTotal[_type]--;
let _temp = this.state.checkAll;
if (_type == 0) {
if(this.state.checkTotal[0] == this.state.list1.length) {
_temp[0] = true;
} else {
_temp[0] = false;
}
} else if (_type == 1) {
if(this.state.checkTotal[1] == this.state.list2.length) {
_temp[1] = true;
} else {
_temp[1] = false;
}
} else {
if(this.state.checkTotal[2] == this.state.list3.length) {
_temp[2] = true;
} else {
_temp[2] = false;
}
}
this.setState({checkAll: _temp});
}
_renderFlatListFooter1 = () => {
return (
<Text style={styles.common.loadingTips}>{this.state.tips[0]}</Text>
);
}
_renderFlatListFooter2 = () => {
return (
<Text style={styles.common.loadingTips}>{this.state.tips[1]}</Text>
);
}
_renderFlatListFooter3 = () => {
return (
<Text style={styles.common.loadingTips}>{this.state.tips[2]}</Text>
);
}
_renderList1Btn = () => {
if(this.state.switchIndex === 0) {
return (
<View style={[styles.common.flex, styles.common.flexEndh]}>
<TouchableHighlight underlayColor='#fafafa' onPress={() => {this._saleFunc(0)}}>
<Text style={styles.btn.defaults}>下架</Text>
</TouchableHighlight>
<TouchableHighlight underlayColor='#fafafa' style={styles.btn.container} onPress={() => {this._delete(1)}}>
<Text style={styles.btn.danger}>删除</Text>
</TouchableHighlight>
</View>
);
} else if(this.state.switchIndex === 1) {
return (
<View style={[styles.common.flex, styles.common.flexEndh]}>
<TouchableHighlight underlayColor='#fafafa' onPress={() => {this._saleFunc(1)}}>
<Text style={styles.btn.defaults}>上架</Text>
</TouchableHighlight>
<TouchableHighlight underlayColor='#fafafa' style={styles.btn.container} onPress={() => {this._delete(1)}}>
<Text style={styles.btn.danger}>删除</Text>
</TouchableHighlight>
</View>
);
} else {
return (
<View style={[styles.common.flex, styles.common.flexEndh]}>
<TouchableHighlight underlayColor='#fafafa' onPress={() => {this._delete(0)}}>
<Text style={styles.btn.defaults}>还原</Text>
</TouchableHighlight>
<TouchableHighlight underlayColor='#fafafa' style={styles.btn.container} onPress={() => {this._delete(2)}}>
<Text style={styles.btn.danger}>彻底删除</Text>
</TouchableHighlight>
</View>
);
}
}
_renderList2Btn = () => {
if(this.state.switchIndex2 === 0) {
return (
<View style={[styles.common.flex, styles.common.flexEndh]}>
<TouchableHighlight underlayColor='#fafafa' onPress={() => {this._unBunging()}}>
<Text style={styles.btn.defaults}>解除绑定</Text>
</TouchableHighlight>
</View>
);
} else if(this.state.switchIndex2 === 1) {
return (
<View style={[styles.common.flex, styles.common.flexEndh]}>
<TouchableHighlight underlayColor='#fafafa' onPress={() => {this._binging()}}>
<Text style={styles.btn.defaults}>一键分销</Text>
</TouchableHighlight>
</View>
);
}
}
_reset = (t) => {
let state = this.state;
let _page = state.page;
_page[t] = 0;
let _checkAll = state.checkAll;
_checkAll[t] = false;
let _havenCheck = state.havenCheck;
_havenCheck[t] = [];
let _checkTotal = state.checkTotal;
_checkTotal[t] = 0;
let _over = state.over;
_over[t] = false;
let _tips = state.tips;
_tips[t] = '';
let _obj = {
page: _page,
checkAll: _checkAll,
havenCheck: _havenCheck,
checkAll: _checkAll,
over: _over,
tips: _tips
}
if(t == 0) {
_obj.list1 = [];
} else if(t == 1) {
_obj.list2 = [];
} else {
_obj.list3 = [];
}
this.setState(_obj);
}
_search = () => {
this._reset(this.state.type);
this._delayLoading();
}
_saleFunc = (t) => {
let state = this.state;
if(state.checkTotal[0] == 0) {
UIToast(t == 0 ? '请选择需要下架的商品' : '请选择需要上架的商品');
return;
}
DeviceEventEmitter.emit('confirmShow', {keys: 4, data: {
text: t == 0 ? '是否确认下架?' : '是否确认上架?',
confirm: () => {
let ids = [];
state.havenCheck[0].map((v, k) => {
if(v) ids.push(state.list1[k].goods_id);
})
let idsString = ids.join(',');
fetch(Config.PHPAPI + 'api/mapp/goods-seller/onsale', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body:`id=${idsString}&status=${t}&token=${token}`
})
.then(response => response.json())
.then((data) => {
if(data.error_code == 0) {
UIToast('操作成功');
this._reset(0);
this._delayLoading();
} else {
UIToast('操作失败');
}
});
}
}});
}
_delete = (t) => {
let state = this.state;
if(state.checkTotal[0] == 0) {
UIToast(t == 0 ? '请选择要还原的商品' : (t == 1 ? '请选择要删除的商品' : '请选择要彻底删除的商品'));
return;
}
DeviceEventEmitter.emit('confirmShow', {keys: 4, data: {
text: t == 0 ? '是否还原所选商品' : (t == 1 ? '是否删除所选商品' : '是否彻底删除所选商品'),
confirm: () => {
let ids = [];
state.havenCheck[0].map((v, k) => {
if(v) ids.push(state.list1[k].goods_id);
})
let idsString = ids.join(',');
fetch(Config.PHPAPI + 'api/mapp/goods-seller/delete', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body:`id=${idsString}&status=${t}&token=${token}`
})
.then(response => response.json())
.then((data) => {
if(data.error_code == 0) {
UIToast('操作成功');
this._reset(0);
this._delayLoading();
} else {
UIToast('操作失败');
}
});
}
}});
}
_unBunging = (t) => {
let state = this.state;
if(state.checkTotal[1] == 0) {
UIToast('请选择解绑商品');
return;
}
DeviceEventEmitter.emit('confirmShow', {keys: 4, data: {
text: '是否解绑所选商品',
confirm: () => {
let ids = [];
state.havenCheck[1].map((v, k) => {
if(v) ids.push(state.list2[k].goods_id);
})
let idsString = ids.join(',');
fetch(Config.PHPAPI + 'api/mapp/goods-seller/unjc', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body:`id=${idsString}&dType=1&token=${token}`
})
.then(response => response.json())
.then((data) => {
if(data.error_code == 0) {
UIToast('操作成功');
this._reset(1);
this._delayLoading();
} else {
UIToast('操作失败');
}
});
}
}});
}
_binging = () => {
let state = this.state;
if(state.checkTotal[1] == 0) {
UIToast('请选择分销商品');
return;
}
let ids = [];
state.havenCheck[1].map((v, k) => {
if(v) ids.push(state.list2[k].goods_id);
})
let idsString = ids.join(',');
DeviceEventEmitter.emit('confirmShow', {keys: 4, data: {
text: '是否分销所选商品',
confirm: () => {
/****先判断是否有重名的商品****/
fetch(Config.PHPAPI + 'api/goods/product/validate-name', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body:`id=${idsString}&token=${token}`
})
.then(response => response.json())
.then((data) => {
if(data.error_code == 500) {
this.timer = setTimeout(() => {
DeviceEventEmitter.emit('confirmShow', {keys: 4, data: {
text: '已存在相同商品名称,您是否继续分销?',
confirm: () => {
fetch(Config.PHPAPI + 'api/mapp/goods-seller/unjc', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body:`id=${idsString}&dType=2&token=${token}`
})
.then(response => response.json())
.then((r) => {
if(r.flag == 1) {
UIToast('操作成功');
this._reset(1);
this._delayLoading();
} else {
UIToast('操作失败');
}
});
}
}
});
}, 300);
} else if(data.error_code == 0) {
this.timer = setTimeout(() => {
DeviceEventEmitter.emit('confirmShow', {keys: 4, data: {
text: '是否确认一键分销所选'+ids.length+'件商品?',
confirm: () => {
fetch(Config.PHPAPI + 'api/mapp/goods-seller/unjc', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body:`id=${idsString}&dType=2&token=${token}`
})
.then(response => response.json())
.then((r) => {
if(r.flag == 1) {
UIToast('操作成功');
this._reset(1);
this._delayLoading();
} else {
UIToast('操作失败');
}
});
}
}
});
}, 300);
} else {
UIToast('操作失败');
}
});
}
}});
}
_close = () => {
this.setState({ visible: false });
}
_openFilter = () => {
this.setState({ visible: true });
requestAnimationFrame(() => {
this.refs.cateScrollView.scrollTo({x: this.state.filterTabIndex * Utils.width, y: 0, animated: false});
});
}
_selectCate = (level, k, item) => {
//如果已选分类,再次点击取消已选
if(this.state.cateIndex[level] == k) {
if(level == 0) {
this.setState({
cateIndex: [-1, -1, -1],
cateLv2: [],
cateLv3: [],
cateId: '',
brandId: '',
brandIndex: [-1, -1]
});
this._getBrand();
} else if(level == 1) {
let _tempCateIndex = this.state.cateIndex;
_tempCateIndex[1] = -1;
_tempCateIndex[2] = -1;
this.setState({
cateIndex: _tempCateIndex,
cateLv3: [],
cateId: this.state.cateLv1[this.state.cateIndex[0]].id,
brandId: '',
brandIndex: [-1, -1]
});
this._getBrand(_tempCateIndex);
} else {
let _tempCateIndex = this.state.cateIndex;
_tempCateIndex[2] = -1;
this.setState({
cateIndex: _tempCateIndex,
cateId: (this.state.cateLv1[this.state.cateIndex[0]].id + ',' + this.state.cateLv2[this.state.cateIndex[1]].id),
brandId: '',
brandIndex: [-1, -1]
});
this._getBrand(_tempCateIndex);
}
} else {
this.setState({filterTabIndex: level+1});
this.refs.cateScrollView.scrollTo({x: (level+1) * Utils.width, y: 0});
requestAnimationFrame(() => {
if (level == 0) {
this.setState({
cateIndex: [k, -1, -1],
cateId: this.state.cateLv1[k].id,
cateLv2: item.list || [],
cateLv3: [],
brandIndex: [-1, -1]
});
this._getBrand([k, -1, -1]);
} else if (level == 1) {
let _temp = this.state.cateIndex;
_temp[1] = k;
this.setState({
cateIndex: _temp,
cateId: (this.state.cateLv1[this.state.cateIndex[0]].id + ',' + this.state.cateLv2[k].id),
cateLv3: item.list || [],
brandIndex: [-1, -1]
});
this._getBrand(_temp);
} else if (level == 2) {
let _temp = this.state.cateIndex;
_temp[2] = k;
this.setState({
cateIndex: _temp,
cateId: (this.state.cateLv1[this.state.cateIndex[0]].id + ',' + this.state.cateLv2[this.state.cateIndex[1]].id + ',' + this.state.cateLv3[k].id),
brandIndex: [-1, -1]
});
this._getBrand(_temp);
}
});
}
}
_filterTabFunc = (level) => {
this.setState({filterTabIndex: level});
this.refs.cateScrollView.scrollTo({x: level * Utils.width, y: 0});
}
_selectBrand = (k, k1, bid) => {
if(this.state.brandIndex[0] == k && this.state.brandIndex[1] == k1) {
this.setState({brandIndex: [-1, -1], brandId: ''});
} else {
this.setState({brandIndex: [k, k1], brandId: bid});
}
}
_filterInit = () => {
this.setState({
cateId: '',
cateLv2: [],
cateLv3: [],
cateIndex: [-1, -1, -1],
brandId: '',
brand: [],
brandIndex: [-1, -1],
filterTabIndex: 0
});
this._getBrand();
}
_filterReset = () => {
this.refs.cateScrollView.scrollTo({x: 0, y: 0});
this._filterInit();
this._close();
this._reset(this.state.type);
this._delayLoading();
}
_filterConfirm = () => {
this._close();
this._reset(this.state.type);
this._delayLoading();
}
_copyGoods = (id) => {
/****先判断是否有重名的商品****/
fetch(Config.PHPAPI + 'api/goods/product/validate-name', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body:`id=${id}&token=${token}`
})
.then(response => response.json())
.then((r) => {
if(r.error_code === 0 || r.error_code === 500) {
DeviceEventEmitter.emit('confirmShow', {keys: 4, data: {
text: r.error_code === 500 ? r.msg : '是否确认复制该商品?',
confirm: () => {
this.props.navigation.navigate('SellerGoodsEdit', {
id,
type: this.state.type + 1
});
}
}
});
}
})
}
}
|
src/components/InfiniteCarouselDots.js | leaffm/react-infinite-carousel | import React from 'react';
import PropTypes from 'prop-types';
import './InfiniteCarousel.css';
const InfiniteCarouselDots = function ({ carouselName, numberOfDots, activePage, onClick }) {
const dots = [];
let classNameIcon;
let dotName;
for (let i = 0; i < numberOfDots; i += 1) {
classNameIcon = `InfiniteCarouselDotIcon ${
i === activePage ? 'InfiniteCarouselDotActiveIcon' : ''
}`;
dotName = `${carouselName}-dots-${i}`;
dots.push(
<button
name={dotName}
data-testid={dotName}
className="InfiniteCarouselDot"
data-index={i}
key={i + 1}
onClick={onClick}
type="button"
>
<i className={classNameIcon} />
</button>
); // eslint-disable-line react/jsx-closing-tag-location
}
return (
<ul data-testid={`${carouselName}-dots`} className="InfiniteCarouselDots">
{dots}
</ul>
);
};
InfiniteCarouselDots.propTypes = {
carouselName: PropTypes.string.isRequired,
numberOfDots: PropTypes.number.isRequired,
activePage: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired,
};
export default InfiniteCarouselDots;
|
src/svg-icons/action/card-travel.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionCardTravel = (props) => (
<SvgIcon {...props}>
<path d="M20 6h-3V4c0-1.11-.89-2-2-2H9c-1.11 0-2 .89-2 2v2H4c-1.11 0-2 .89-2 2v11c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zM9 4h6v2H9V4zm11 15H4v-2h16v2zm0-5H4V8h3v2h2V8h6v2h2V8h3v6z"/>
</SvgIcon>
);
ActionCardTravel = pure(ActionCardTravel);
ActionCardTravel.displayName = 'ActionCardTravel';
ActionCardTravel.muiName = 'SvgIcon';
export default ActionCardTravel;
|
src/shared/element-react/dist/npm/es6/src/layout/Col.js | thundernet8/Elune-WWW | import _typeof from 'babel-runtime/helpers/typeof';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import { Component, PropTypes } from '../../libs';
var Col = function (_Component) {
_inherits(Col, _Component);
function Col() {
_classCallCheck(this, Col);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
Col.prototype.getStyle = function getStyle() {
var style = {};
if (this.context.gutter) {
style.paddingLeft = this.context.gutter / 2 + 'px';
style.paddingRight = style.paddingLeft;
}
return style;
};
Col.prototype.render = function render() {
var _this2 = this;
var classList = [];
['span', 'offset', 'pull', 'push'].forEach(function (prop) {
if (_this2.props[prop]) {
classList.push(prop !== 'span' ? 'el-col-' + prop + '-' + _this2.props[prop] : 'el-col-' + _this2.props[prop]);
}
});
['xs', 'sm', 'md', 'lg'].forEach(function (size) {
if (_typeof(_this2.props[size]) === 'object') {
var props = _this2.props[size];
Object.keys(props).forEach(function (prop) {
classList.push(prop !== 'span' ? 'el-col-' + size + '-' + prop + '-' + props[prop] : 'el-col-' + size + '-' + props[prop]);
});
} else {
if (_this2.props[size]) {
classList.push('el-col-' + size + '-' + Number(_this2.props[size]));
}
}
});
return React.createElement(this.props.tag, {
className: this.className('el-col', classList),
style: this.style(this.getStyle())
}, this.props.children);
};
return Col;
}(Component);
export default Col;
Col.contextTypes = {
gutter: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
};
Col.propTypes = {
span: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
offset: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
pull: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
push: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
xs: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.object]),
sm: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.object]),
md: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.object]),
lg: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.object]),
tag: PropTypes.string
};
Col.defaultProps = {
span: 24,
tag: 'div'
}; |
fields/types/relationship/RelationshipColumn.js | codevlabs/keystone | import React from 'react';
import ItemsTableCell from '../../../admin/client/components/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTableValue';
const moreIndicatorStyle = {
color: '#bbb',
fontSize: '.8rem',
fontWeight: 500,
marginLeft: 8,
};
var RelationshipColumn = React.createClass({
displayName: 'RelationshipColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderMany (value) {
if (!value || !value.length) return;
let refList = this.props.col.field.refList;
let items = [];
for (let i = 0; i < 3; i++) {
if (!value[i]) break;
if (i) {
items.push(<span key={'comma' + i}>, </span>);
}
items.push(
<ItemsTableValue interior truncate={false} key={'anchor' + i} href={Keystone.adminPath + '/' + refList.path + '/' + value[i].id}>
{value[i].name}
</ItemsTableValue>
);
}
if (value.length > 3) {
items.push(<span key="more" style={moreIndicatorStyle}>[...{value.length - 3} more]</span>);
}
return (
<ItemsTableValue field={this.props.col.type}>
{items}
</ItemsTableValue>
);
},
renderValue (value) {
if (!value) return;
let refList = this.props.col.field.refList;
return (
<ItemsTableValue href={Keystone.adminPath + '/' + refList.path + '/' + value.id} padded interior field={this.props.col.type}>
{value.name}
</ItemsTableValue>
);
},
render () {
let value = this.props.data.fields[this.props.col.path];
let many = this.props.col.field.many;
return (
<ItemsTableCell>
{many ? this.renderMany(value) : this.renderValue(value)}
</ItemsTableCell>
);
}
});
module.exports = RelationshipColumn;
|
lib/Modal/stories/BasicUsage.js | folio-org/stripes-components | /**
* Modal: Basic Usage
*/
import React from 'react';
// import { text, boolean, select } from '@storybook/addon-knobs';
import { action } from '@storybook/addon-actions';
import Modal from '../Modal';
import Button from '../../Button';
export default () => {
// const showHeader = boolean('Show header', true);
// const dismissible = boolean('Dismissible', true);
// const label = text('Label', 'Modal Label');
// const size = select('Size', {
// small: 'Small',
// medium: 'Medium',
// large: 'Large',
// }, 'medium');
const footer = (
<>
<Button buttonStyle="primary" marginBottom0>Save</Button>
</>
);
return (
<Modal
open
id="basic-modal-example"
dismissible
closeOnBackgroundClick
label={'Modal label'}
size={'Medium'}
showHeader
onClose={action('onClose callback')}
footer={footer}
aria-label="Example Modal"
>
Modal Content
</Modal>
);
};
|
src/pages/dashboard/components/weather.js | zuiidea/antd-admin | import React from 'react'
import PropTypes from 'prop-types'
import { Spin } from 'antd'
import styles from './weather.less'
function Weather({ city, icon, dateTime, temperature, name, loading }) {
return (
<Spin spinning={loading}>
<div className={styles.weather}>
<div className={styles.left}>
<div
className={styles.icon}
style={{
backgroundImage: `url(${icon})`,
}}
/>
<p>{name}</p>
</div>
<div className={styles.right}>
<h1 className={styles.temperature}>{`${temperature}°`}</h1>
<p className={styles.description}>
{city},{dateTime}
</p>
</div>
</div>
</Spin>
)
}
Weather.propTypes = {
city: PropTypes.string,
icon: PropTypes.string,
dateTime: PropTypes.string,
temperature: PropTypes.string,
name: PropTypes.string,
loading: PropTypes.bool,
}
export default Weather
|
app/javascript/mastodon/features/compose/components/search.js | h3zjp/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import Overlay from 'react-overlays/lib/Overlay';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import { searchEnabled } from '../../../initial_state';
import Icon from 'mastodon/components/icon';
const messages = defineMessages({
placeholder: { id: 'search.placeholder', defaultMessage: 'Search' },
});
class SearchPopout extends React.PureComponent {
static propTypes = {
style: PropTypes.object,
};
render () {
const { style } = this.props;
const extraInformation = searchEnabled ? <FormattedMessage id='search_popout.tips.full_text' defaultMessage='Simple text returns statuses you have written, favourited, boosted, or have been mentioned in, as well as matching usernames, display names, and hashtags.' /> : <FormattedMessage id='search_popout.tips.text' defaultMessage='Simple text returns matching display names, usernames and hashtags' />;
return (
<div style={{ ...style, position: 'absolute', width: 285, zIndex: 2 }}>
<Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}>
{({ opacity, scaleX, scaleY }) => (
<div className='search-popout' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})` }}>
<h4><FormattedMessage id='search_popout.search_format' defaultMessage='Advanced search format' /></h4>
<ul>
<li><em>#example</em> <FormattedMessage id='search_popout.tips.hashtag' defaultMessage='hashtag' /></li>
<li><em>@username@domain</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li>
<li><em>URL</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li>
<li><em>URL</em> <FormattedMessage id='search_popout.tips.status' defaultMessage='status' /></li>
</ul>
{extraInformation}
</div>
)}
</Motion>
</div>
);
}
}
export default @injectIntl
class Search extends React.PureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
value: PropTypes.string.isRequired,
submitted: PropTypes.bool,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
onShow: PropTypes.func.isRequired,
openInRoute: PropTypes.bool,
intl: PropTypes.object.isRequired,
singleColumn: PropTypes.bool,
};
state = {
expanded: false,
};
setRef = c => {
this.searchForm = c;
}
handleChange = (e) => {
this.props.onChange(e.target.value);
}
handleClear = (e) => {
e.preventDefault();
if (this.props.value.length > 0 || this.props.submitted) {
this.props.onClear();
}
}
handleKeyUp = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
this.props.onSubmit();
if (this.props.openInRoute) {
this.context.router.history.push('/search');
}
} else if (e.key === 'Escape') {
document.querySelector('.ui').parentElement.focus();
}
}
handleFocus = () => {
this.setState({ expanded: true });
this.props.onShow();
if (this.searchForm && !this.props.singleColumn) {
const { left, right } = this.searchForm.getBoundingClientRect();
if (left < 0 || right > (window.innerWidth || document.documentElement.clientWidth)) {
this.searchForm.scrollIntoView();
}
}
}
handleBlur = () => {
this.setState({ expanded: false });
}
render () {
const { intl, value, submitted } = this.props;
const { expanded } = this.state;
const hasValue = value.length > 0 || submitted;
return (
<div className='search'>
<label>
<span style={{ display: 'none' }}>{intl.formatMessage(messages.placeholder)}</span>
<input
ref={this.setRef}
className='search__input'
type='text'
placeholder={intl.formatMessage(messages.placeholder)}
value={value}
onChange={this.handleChange}
onKeyUp={this.handleKeyUp}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
/>
</label>
<div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}>
<Icon id='search' className={hasValue ? '' : 'active'} />
<Icon id='times-circle' className={hasValue ? 'active' : ''} aria-label={intl.formatMessage(messages.placeholder)} />
</div>
<Overlay show={expanded && !hasValue} placement='bottom' target={this}>
<SearchPopout />
</Overlay>
</div>
);
}
}
|
app/javascript/mastodon/features/keyboard_shortcuts/index.js | mhffdq/mastodon | import React from 'react';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'keyboard_shortcuts.heading', defaultMessage: 'Keyboard Shortcuts' },
});
@injectIntl
export default class KeyboardShortcuts extends ImmutablePureComponent {
static propTypes = {
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
render () {
const { intl } = this.props;
return (
<Column icon='question' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<div className='keyboard-shortcuts scrollable optionally-scrollable'>
<table>
<thead>
<tr>
<th><FormattedMessage id='keyboard_shortcuts.hotkey' defaultMessage='Hotkey' /></th>
<th><FormattedMessage id='keyboard_shortcuts.description' defaultMessage='Description' /></th>
</tr>
</thead>
<tbody>
<tr>
<td><kbd>r</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.reply' defaultMessage='to reply' /></td>
</tr>
<tr>
<td><kbd>m</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.mention' defaultMessage='to mention author' /></td>
</tr>
<tr>
<td><kbd>f</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.favourite' defaultMessage='to favourite' /></td>
</tr>
<tr>
<td><kbd>b</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.boost' defaultMessage='to boost' /></td>
</tr>
<tr>
<td><kbd>enter</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.enter' defaultMessage='to open status' /></td>
</tr>
<tr>
<td><kbd>up</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.up' defaultMessage='to move up in the list' /></td>
</tr>
<tr>
<td><kbd>down</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.down' defaultMessage='to move down in the list' /></td>
</tr>
<tr>
<td><kbd>1</kbd>-<kbd>9</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.column' defaultMessage='to focus a status in one of the columns' /></td>
</tr>
<tr>
<td><kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.compose' defaultMessage='to focus the compose textarea' /></td>
</tr>
<tr>
<td><kbd>alt</kbd>+<kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.toot' defaultMessage='to start a brand new toot' /></td>
</tr>
<tr>
<td><kbd>backspace</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.back' defaultMessage='to navigate back' /></td>
</tr>
<tr>
<td><kbd>s</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.search' defaultMessage='to focus search' /></td>
</tr>
<tr>
<td><kbd>esc</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.unfocus' defaultMessage='to un-focus compose textarea/search' /></td>
</tr>
<tr>
<td><kbd>?</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.legend' defaultMessage='to display this legend' /></td>
</tr>
</tbody>
</table>
</div>
</Column>
);
}
}
|
src/index.js | mangal49/HORECA | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './Routes';
import { Provider } from 'react-redux';
import { store } from './store';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
// import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
// import getMuiTheme from 'material-ui/styles/getMuiTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
ReactDOM.render(
<Provider store={store}>
{/*<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>*/}
<MuiThemeProvider >
<Router routes={routes} history={browserHistory} />
</MuiThemeProvider>
</Provider>
, document.querySelector('.container'));
|
app/clients/next/components/pagination.js | koapi/koapp | import React from 'react'
import Paginate from 'react-paginate'
import { translate } from 'react-i18next'
export default translate(['common'])(class Pagination extends React.Component {
render () {
const { t } = this.props
return (
<Paginate containerClassName='pagination'
pageClassName='page-item'
pageLinkClassName='page-link'
activeClassName='active'
previousLabel={t('prev_page')}
previousClassName='page-item'
previousLinkClassName='page-link'
breakClassName='page-item'
breakLabel={<a className='page-link'>...</a>}
nextLabel={t('next_page')}
nextClassName='page-item'
disableInitialCallback
nextLinkClassName='page-link' {...this.props} />
)
}
})
|
src/components/basic/Blockquote.js | casesandberg/react-mark | 'use strict';
import React from 'react';
export class BLOCKQUOTE extends React.Component {
render() {
return <blockquote>{ this.props.children }</blockquote>;
}
}
export default BLOCKQUOTE;
|
Libraries/CustomComponents/Navigator/Navigator.js | wenpkpk/react-native | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* Facebook, Inc. ("Facebook") owns all right, title and interest, including
* all intellectual property and other proprietary rights, in and to the React
* Native CustomComponents software (the "Software"). Subject to your
* compliance with these terms, you are hereby granted a non-exclusive,
* worldwide, royalty-free copyright license to (1) use and copy the Software;
* and (2) reproduce and distribute the Software as part of your own software
* ("Your Software"). Facebook reserves all rights not expressly granted to
* you in this license agreement.
*
* THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
* IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR
* EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @providesModule Navigator
*/
/* eslint-disable no-extra-boolean-cast*/
'use strict';
var AnimationsDebugModule = require('NativeModules').AnimationsDebugModule;
var Dimensions = require('Dimensions');
var InteractionMixin = require('InteractionMixin');
var NavigationContext = require('NavigationContext');
var NavigatorBreadcrumbNavigationBar = require('NavigatorBreadcrumbNavigationBar');
var NavigatorNavigationBar = require('NavigatorNavigationBar');
var NavigatorSceneConfigs = require('NavigatorSceneConfigs');
var PanResponder = require('PanResponder');
var React = require('React');
var StyleSheet = require('StyleSheet');
var Subscribable = require('Subscribable');
var TimerMixin = require('react-timer-mixin');
var View = require('View');
var clamp = require('clamp');
var flattenStyle = require('flattenStyle');
var invariant = require('fbjs/lib/invariant');
var rebound = require('rebound');
var PropTypes = React.PropTypes;
// TODO: this is not ideal because there is no guarantee that the navigator
// is full screen, however we don't have a good way to measure the actual
// size of the navigator right now, so this is the next best thing.
var SCREEN_WIDTH = Dimensions.get('window').width;
var SCREEN_HEIGHT = Dimensions.get('window').height;
var SCENE_DISABLED_NATIVE_PROPS = {
pointerEvents: 'none',
style: {
top: SCREEN_HEIGHT,
bottom: -SCREEN_HEIGHT,
opacity: 0,
},
};
var __uid = 0;
function getuid() {
return __uid++;
}
function getRouteID(route) {
if (route === null || typeof route !== 'object') {
return String(route);
}
var key = '__navigatorRouteID';
if (!route.hasOwnProperty(key)) {
Object.defineProperty(route, key, {
enumerable: false,
configurable: false,
writable: false,
value: getuid(),
});
}
return route[key];
}
// styles moved to the top of the file so getDefaultProps can refer to it
var styles = StyleSheet.create({
container: {
flex: 1,
overflow: 'hidden',
},
defaultSceneStyle: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
top: 0,
},
baseScene: {
position: 'absolute',
overflow: 'hidden',
left: 0,
right: 0,
bottom: 0,
top: 0,
},
disabledScene: {
top: SCREEN_HEIGHT,
bottom: -SCREEN_HEIGHT,
},
transitioner: {
flex: 1,
backgroundColor: 'transparent',
overflow: 'hidden',
}
});
var GESTURE_ACTIONS = [
'pop',
'jumpBack',
'jumpForward',
];
/**
* `Navigator` handles the transition between different scenes in your app.
* It is implemented in JavaScript and is available on both iOS and Android. If
* you are targeting iOS only, you may also want to consider using
* [`NavigatorIOS`](docs/navigatorios.html) as it leverages native UIKit
* navigation.
*
* To set up the `Navigator` you provide one or more objects called routes,
* to identify each scene. You also provide a `renderScene` function that
* renders the scene for each route object.
*
* ```
* import React, { Component } from 'react';
* import { Text, Navigator } from 'react-native';
*
* export default class NavAllDay extends Component {
* render() {
* return (
* <Navigator
* initialRoute={{ title: 'Awesome Scene', index: 0 }}
* renderScene={(route, navigator) =>
* <Text>Hello {route.title}!</Text>
* }
* style={{padding: 100}}
* />
* );
* }
* }
* ```
*
* In the above example, `initialRoute` is used to specify the first route. It
* contains a `title` property that identifies the route. The `renderScene`
* prop returns a function that displays text based on the route's title.
*
* ### Additional Scenes
*
* The first example demonstrated one scene. To set up multiple scenes, you pass
* the `initialRouteStack` prop to `Navigator`:
*
* ```
* render() {
* const routes = [
* {title: 'First Scene', index: 0},
* {title: 'Second Scene', index: 1},
* ];
* return (
* <Navigator
* initialRoute={routes[0]}
* initialRouteStack={routes}
* renderScene={(route, navigator) =>
* <TouchableHighlight onPress={() => {
* if (route.index === 0) {
* navigator.push(routes[1]);
* } else {
* navigator.pop();
* }
* }}>
* <Text>Hello {route.title}!</Text>
* </TouchableHighlight>
* }
* style={{padding: 100}}
* />
* );
* }
* ```
*
* In the above example, a `routes` variable is defined with two route objects
* representing two scenes. Each route has an `index` property that is used to
* manage the scene being rendered. The `renderScene` method is changed to
* either push or pop the navigator depending on the current route's index.
* Finally, the `Text` component in the scene is now wrapped in a
* `TouchableHighlight` component to help trigger the navigator transitions.
*
* ### Navigation Bar
*
* You can optionally pass in your own navigation bar by returning a
* `Navigator.NavigationBar` component to the `navigationBar` prop in
* `Navigator`. You can configure the navigation bar properties, through
* the `routeMapper` prop. There you set up the left, right, and title
* properties of the navigation bar:
*
* ```
* <Navigator
* renderScene={(route, navigator) =>
* // ...
* }
* navigationBar={
* <Navigator.NavigationBar
* routeMapper={{
* LeftButton: (route, navigator, index, navState) =>
* { return (<Text>Cancel</Text>); },
* RightButton: (route, navigator, index, navState) =>
* { return (<Text>Done</Text>); },
* Title: (route, navigator, index, navState) =>
* { return (<Text>Awesome Nav Bar</Text>); },
* }}
* style={{backgroundColor: 'gray'}}
* />
* }
* />
* ```
*
* When configuring the left, right, and title items for the navigation bar,
* you have access to info such as the current route object and navigation
* state. This allows you to customize the title for each scene as well as
* the buttons. For example, you can choose to hide the left button for one of
* the scenes.
*
* Typically you want buttons to represent the left and right buttons. Building
* on the previous example, you can set this up as follows:
*
* ```
* LeftButton: (route, navigator, index, navState) =>
* {
* if (route.index === 0) {
* return null;
* } else {
* return (
* <TouchableHighlight onPress={() => navigator.pop()}>
* <Text>Back</Text>
* </TouchableHighlight>
* );
* }
* },
* ```
*
* This sets up a left navigator bar button that's visible on scenes after the
* the first one. When the button is tapped the navigator is popped.
*
* Another type of navigation bar, with breadcrumbs, is provided by
* `Navigator.BreadcrumbNavigationBar`. You can also provide your own navigation
* bar by passing it through the `navigationBar` prop. See the
* [UIExplorer](https://github.com/facebook/react-native/tree/master/Examples/UIExplorer)
* demo to try out both built-in navigation bars out and see how to use them.
*
* ### Scene Transitions
*
* To change the animation or gesture properties of the scene, provide a
* `configureScene` prop to get the config object for a given route:
*
* ```
* <Navigator
* renderScene={(route, navigator) =>
* // ...
* }
* configureScene={(route, routeStack) =>
* Navigator.SceneConfigs.FloatFromBottom}
* />
* ```
* In the above example, the newly pushed scene will float up from the bottom.
* See `Navigator.SceneConfigs` for default animations and more info on
* available [scene config options](/react-native/docs/navigator.html#configurescene).
*/
var Navigator = React.createClass({
propTypes: {
/**
* Optional function where you can configure scene animations and
* gestures. Will be invoked with `route` and `routeStack` parameters,
* where `route` corresponds to the current scene being rendered by the
* `Navigator` and `routeStack` is the set of currently mounted routes
* that the navigator could transition to.
*
* The function should return a scene configuration object.
*
* ```
* (route, routeStack) => Navigator.SceneConfigs.FloatFromRight
* ```
*
* Available scene configutation options are:
*
* - Navigator.SceneConfigs.PushFromRight (default)
* - Navigator.SceneConfigs.FloatFromRight
* - Navigator.SceneConfigs.FloatFromLeft
* - Navigator.SceneConfigs.FloatFromBottom
* - Navigator.SceneConfigs.FloatFromBottomAndroid
* - Navigator.SceneConfigs.FadeAndroid
* - Navigator.SceneConfigs.HorizontalSwipeJump
* - Navigator.SceneConfigs.HorizontalSwipeJumpFromRight
* - Navigator.SceneConfigs.VerticalUpSwipeJump
* - Navigator.SceneConfigs.VerticalDownSwipeJump
*
*/
configureScene: PropTypes.func,
/**
* Required function which renders the scene for a given route. Will be
* invoked with the `route` and the `navigator` object.
*
* ```
* (route, navigator) =>
* <MySceneComponent title={route.title} navigator={navigator} />
* ```
*/
renderScene: PropTypes.func.isRequired,
/**
* The initial route for navigation. A route is an object that the navigator
* will use to identify each scene it renders.
*
* If both `initialRoute` and `initialRouteStack` props are passed to
* `Navigator`, then `initialRoute` must be in a route in
* `initialRouteStack`. If `initialRouteStack` is passed as a prop but
* `initialRoute` is not, then `initialRoute` will default internally to
* the last item in `initialRouteStack`.
*/
initialRoute: PropTypes.object,
/**
* Pass this in to provide a set of routes to initially mount. This prop
* is required if `initialRoute` is not provided to the navigator. If this
* prop is not passed in, it will default internally to an array
* containing only `initialRoute`.
*/
initialRouteStack: PropTypes.arrayOf(PropTypes.object),
/**
* Pass in a function to get notified with the target route when
* the navigator component is mounted and before each navigator transition.
*/
onWillFocus: PropTypes.func,
/**
* Will be called with the new route of each scene after the transition is
* complete or after the initial mounting.
*/
onDidFocus: PropTypes.func,
/**
* Use this to provide an optional component representing a navigation bar
* that is persisted across scene transitions. This component will receive
* two props: `navigator` and `navState` representing the navigator
* component and its state. The component is re-rendered when the route
* changes.
*/
navigationBar: PropTypes.node,
/**
* Optionally pass in the navigator object from a parent `Navigator`.
*/
navigator: PropTypes.object,
/**
* Styles to apply to the container of each scene.
*/
sceneStyle: View.propTypes.style,
},
statics: {
BreadcrumbNavigationBar: NavigatorBreadcrumbNavigationBar,
NavigationBar: NavigatorNavigationBar,
SceneConfigs: NavigatorSceneConfigs,
},
mixins: [TimerMixin, InteractionMixin, Subscribable.Mixin],
getDefaultProps: function() {
return {
configureScene: () => NavigatorSceneConfigs.PushFromRight,
sceneStyle: styles.defaultSceneStyle,
};
},
getInitialState: function() {
this._navigationBarNavigator = this.props.navigationBarNavigator || this;
this._renderedSceneMap = new Map();
var routeStack = this.props.initialRouteStack || [this.props.initialRoute];
invariant(
routeStack.length >= 1,
'Navigator requires props.initialRoute or props.initialRouteStack.'
);
var initialRouteIndex = routeStack.length - 1;
if (this.props.initialRoute) {
initialRouteIndex = routeStack.indexOf(this.props.initialRoute);
invariant(
initialRouteIndex !== -1,
'initialRoute is not in initialRouteStack.'
);
}
return {
sceneConfigStack: routeStack.map(
(route) => this.props.configureScene(route, routeStack)
),
routeStack,
presentedIndex: initialRouteIndex,
transitionFromIndex: null,
activeGesture: null,
pendingGestureProgress: null,
transitionQueue: [],
};
},
componentWillMount: function() {
// TODO(t7489503): Don't need this once ES6 Class landed.
this.__defineGetter__('navigationContext', this._getNavigationContext);
this._subRouteFocus = [];
this.parentNavigator = this.props.navigator;
this._handlers = {};
this.springSystem = new rebound.SpringSystem();
this.spring = this.springSystem.createSpring();
this.spring.setRestSpeedThreshold(0.05);
this.spring.setCurrentValue(0).setAtRest();
this.spring.addListener({
onSpringEndStateChange: () => {
if (!this._interactionHandle) {
this._interactionHandle = this.createInteractionHandle();
}
},
onSpringUpdate: () => {
this._handleSpringUpdate();
},
onSpringAtRest: () => {
this._completeTransition();
},
});
this.panGesture = PanResponder.create({
onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
onPanResponderRelease: this._handlePanResponderRelease,
onPanResponderMove: this._handlePanResponderMove,
onPanResponderTerminate: this._handlePanResponderTerminate,
});
this._interactionHandle = null;
this._emitWillFocus(this.state.routeStack[this.state.presentedIndex]);
},
componentDidMount: function() {
this._handleSpringUpdate();
this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]);
},
componentWillUnmount: function() {
if (this._navigationContext) {
this._navigationContext.dispose();
this._navigationContext = null;
}
this.spring.destroy();
if (this._interactionHandle) {
this.clearInteractionHandle(this._interactionHandle);
}
},
/**
* Reset every scene with an array of routes.
*
* @param {RouteStack} nextRouteStack Next route stack to reinitialize.
* All existing route stacks are destroyed an potentially recreated. There
* is no accompanying animation and this method immediately replaces and
* re-renders the navigation bar and the stack items.
*/
immediatelyResetRouteStack: function(nextRouteStack) {
var destIndex = nextRouteStack.length - 1;
this.setState({
routeStack: nextRouteStack,
sceneConfigStack: nextRouteStack.map(
route => this.props.configureScene(route, nextRouteStack)
),
presentedIndex: destIndex,
activeGesture: null,
transitionFromIndex: null,
transitionQueue: [],
}, () => {
this._handleSpringUpdate();
this._navBar && this._navBar.immediatelyRefresh();
this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]);
});
},
_transitionTo: function(destIndex, velocity, jumpSpringTo, cb) {
if (this.state.presentedIndex === destIndex) {
cb && cb();
return;
}
if (this.state.transitionFromIndex !== null) {
// Navigation is still transitioning, put the `destIndex` into queue.
this.state.transitionQueue.push({
destIndex,
velocity,
cb,
});
return;
}
this.state.transitionFromIndex = this.state.presentedIndex;
this.state.presentedIndex = destIndex;
this.state.transitionCb = cb;
this._onAnimationStart();
if (AnimationsDebugModule) {
AnimationsDebugModule.startRecordingFps();
}
var sceneConfig = this.state.sceneConfigStack[this.state.transitionFromIndex] ||
this.state.sceneConfigStack[this.state.presentedIndex];
invariant(
sceneConfig,
'Cannot configure scene at index ' + this.state.transitionFromIndex
);
if (jumpSpringTo != null) {
this.spring.setCurrentValue(jumpSpringTo);
}
this.spring.setOvershootClampingEnabled(true);
this.spring.getSpringConfig().friction = sceneConfig.springFriction;
this.spring.getSpringConfig().tension = sceneConfig.springTension;
this.spring.setVelocity(velocity || sceneConfig.defaultTransitionVelocity);
this.spring.setEndValue(1);
},
/**
* This happens for each frame of either a gesture or a transition. If both are
* happening, we only set values for the transition and the gesture will catch up later
*/
_handleSpringUpdate: function() {
if (!this.isMounted()) {
return;
}
// Prioritize handling transition in progress over a gesture:
if (this.state.transitionFromIndex != null) {
this._transitionBetween(
this.state.transitionFromIndex,
this.state.presentedIndex,
this.spring.getCurrentValue()
);
} else if (this.state.activeGesture != null) {
var presentedToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._transitionBetween(
this.state.presentedIndex,
presentedToIndex,
this.spring.getCurrentValue()
);
}
},
/**
* This happens at the end of a transition started by transitionTo, and when the spring catches up to a pending gesture
*/
_completeTransition: function() {
if (!this.isMounted()) {
return;
}
if (this.spring.getCurrentValue() !== 1 && this.spring.getCurrentValue() !== 0) {
// The spring has finished catching up to a gesture in progress. Remove the pending progress
// and we will be in a normal activeGesture state
if (this.state.pendingGestureProgress) {
this.state.pendingGestureProgress = null;
}
return;
}
this._onAnimationEnd();
var presentedIndex = this.state.presentedIndex;
var didFocusRoute = this._subRouteFocus[presentedIndex] || this.state.routeStack[presentedIndex];
if (AnimationsDebugModule) {
AnimationsDebugModule.stopRecordingFps(Date.now());
}
this.state.transitionFromIndex = null;
this.spring.setCurrentValue(0).setAtRest();
this._hideScenes();
if (this.state.transitionCb) {
this.state.transitionCb();
this.state.transitionCb = null;
}
this._emitDidFocus(didFocusRoute);
if (this._interactionHandle) {
this.clearInteractionHandle(this._interactionHandle);
this._interactionHandle = null;
}
if (this.state.pendingGestureProgress) {
// A transition completed, but there is already another gesture happening.
// Enable the scene and set the spring to catch up with the new gesture
var gestureToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._enableScene(gestureToIndex);
this.spring.setEndValue(this.state.pendingGestureProgress);
return;
}
if (this.state.transitionQueue.length) {
var queuedTransition = this.state.transitionQueue.shift();
this._enableScene(queuedTransition.destIndex);
this._emitWillFocus(this.state.routeStack[queuedTransition.destIndex]);
this._transitionTo(
queuedTransition.destIndex,
queuedTransition.velocity,
null,
queuedTransition.cb
);
}
},
_emitDidFocus: function(route) {
this.navigationContext.emit('didfocus', {route: route});
if (this.props.onDidFocus) {
this.props.onDidFocus(route);
}
},
_emitWillFocus: function(route) {
this.navigationContext.emit('willfocus', {route: route});
var navBar = this._navBar;
if (navBar && navBar.handleWillFocus) {
navBar.handleWillFocus(route);
}
if (this.props.onWillFocus) {
this.props.onWillFocus(route);
}
},
/**
* Hides all scenes that we are not currently on, gesturing to, or transitioning from
*/
_hideScenes: function() {
var gesturingToIndex = null;
if (this.state.activeGesture) {
gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
}
for (var i = 0; i < this.state.routeStack.length; i++) {
if (i === this.state.presentedIndex ||
i === this.state.transitionFromIndex ||
i === gesturingToIndex) {
continue;
}
this._disableScene(i);
}
},
/**
* Push a scene off the screen, so that opacity:0 scenes will not block touches sent to the presented scenes
*/
_disableScene: function(sceneIndex) {
this.refs['scene_' + sceneIndex] &&
this.refs['scene_' + sceneIndex].setNativeProps(SCENE_DISABLED_NATIVE_PROPS);
},
/**
* Put the scene back into the state as defined by props.sceneStyle, so transitions can happen normally
*/
_enableScene: function(sceneIndex) {
// First, determine what the defined styles are for scenes in this navigator
var sceneStyle = flattenStyle([styles.baseScene, this.props.sceneStyle]);
// Then restore the pointer events and top value for this scene
var enabledSceneNativeProps = {
pointerEvents: 'auto',
style: {
top: sceneStyle.top,
bottom: sceneStyle.bottom,
},
};
if (sceneIndex !== this.state.transitionFromIndex &&
sceneIndex !== this.state.presentedIndex) {
// If we are not in a transition from this index, make sure opacity is 0
// to prevent the enabled scene from flashing over the presented scene
enabledSceneNativeProps.style.opacity = 0;
}
this.refs['scene_' + sceneIndex] &&
this.refs['scene_' + sceneIndex].setNativeProps(enabledSceneNativeProps);
},
_onAnimationStart: function() {
var fromIndex = this.state.presentedIndex;
var toIndex = this.state.presentedIndex;
if (this.state.transitionFromIndex != null) {
fromIndex = this.state.transitionFromIndex;
} else if (this.state.activeGesture) {
toIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
}
this._setRenderSceneToHardwareTextureAndroid(fromIndex, true);
this._setRenderSceneToHardwareTextureAndroid(toIndex, true);
var navBar = this._navBar;
if (navBar && navBar.onAnimationStart) {
navBar.onAnimationStart(fromIndex, toIndex);
}
},
_onAnimationEnd: function() {
var max = this.state.routeStack.length - 1;
for (var index = 0; index <= max; index++) {
this._setRenderSceneToHardwareTextureAndroid(index, false);
}
var navBar = this._navBar;
if (navBar && navBar.onAnimationEnd) {
navBar.onAnimationEnd();
}
},
_setRenderSceneToHardwareTextureAndroid: function(sceneIndex, shouldRenderToHardwareTexture) {
var viewAtIndex = this.refs['scene_' + sceneIndex];
if (viewAtIndex === null || viewAtIndex === undefined) {
return;
}
viewAtIndex.setNativeProps({renderToHardwareTextureAndroid: shouldRenderToHardwareTexture});
},
_handleTouchStart: function() {
this._eligibleGestures = GESTURE_ACTIONS;
},
_handleMoveShouldSetPanResponder: function(e, gestureState) {
var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex];
if (!sceneConfig) {
return false;
}
this._expectingGestureGrant =
this._matchGestureAction(this._eligibleGestures, sceneConfig.gestures, gestureState);
return !!this._expectingGestureGrant;
},
_doesGestureOverswipe: function(gestureName) {
var wouldOverswipeBack = this.state.presentedIndex <= 0 &&
(gestureName === 'pop' || gestureName === 'jumpBack');
var wouldOverswipeForward = this.state.presentedIndex >= this.state.routeStack.length - 1 &&
gestureName === 'jumpForward';
return wouldOverswipeForward || wouldOverswipeBack;
},
_deltaForGestureAction: function(gestureAction) {
switch (gestureAction) {
case 'pop':
case 'jumpBack':
return -1;
case 'jumpForward':
return 1;
default:
invariant(false, 'Unsupported gesture action ' + gestureAction);
return;
}
},
_handlePanResponderRelease: function(e, gestureState) {
var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex];
var releaseGestureAction = this.state.activeGesture;
if (!releaseGestureAction) {
// The gesture may have been detached while responder, so there is no action here
return;
}
var releaseGesture = sceneConfig.gestures[releaseGestureAction];
var destIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
if (this.spring.getCurrentValue() === 0) {
// The spring is at zero, so the gesture is already complete
this.spring.setCurrentValue(0).setAtRest();
this._completeTransition();
return;
}
var isTravelVertical = releaseGesture.direction === 'top-to-bottom' || releaseGesture.direction === 'bottom-to-top';
var isTravelInverted = releaseGesture.direction === 'right-to-left' || releaseGesture.direction === 'bottom-to-top';
var velocity, gestureDistance;
if (isTravelVertical) {
velocity = isTravelInverted ? -gestureState.vy : gestureState.vy;
gestureDistance = isTravelInverted ? -gestureState.dy : gestureState.dy;
} else {
velocity = isTravelInverted ? -gestureState.vx : gestureState.vx;
gestureDistance = isTravelInverted ? -gestureState.dx : gestureState.dx;
}
var transitionVelocity = clamp(-10, velocity, 10);
if (Math.abs(velocity) < releaseGesture.notMoving) {
// The gesture velocity is so slow, is "not moving"
var hasGesturedEnoughToComplete = gestureDistance > releaseGesture.fullDistance * releaseGesture.stillCompletionRatio;
transitionVelocity = hasGesturedEnoughToComplete ? releaseGesture.snapVelocity : -releaseGesture.snapVelocity;
}
if (transitionVelocity < 0 || this._doesGestureOverswipe(releaseGestureAction)) {
// This gesture is to an overswiped region or does not have enough velocity to complete
// If we are currently mid-transition, then this gesture was a pending gesture. Because this gesture takes no action, we can stop here
if (this.state.transitionFromIndex == null) {
// There is no current transition, so we need to transition back to the presented index
var transitionBackToPresentedIndex = this.state.presentedIndex;
// slight hack: change the presented index for a moment in order to transitionTo correctly
this.state.presentedIndex = destIndex;
this._transitionTo(
transitionBackToPresentedIndex,
-transitionVelocity,
1 - this.spring.getCurrentValue()
);
}
} else {
// The gesture has enough velocity to complete, so we transition to the gesture's destination
this._emitWillFocus(this.state.routeStack[destIndex]);
this._transitionTo(
destIndex,
transitionVelocity,
null,
() => {
if (releaseGestureAction === 'pop') {
this._cleanScenesPastIndex(destIndex);
}
}
);
}
this._detachGesture();
},
_handlePanResponderTerminate: function(e, gestureState) {
if (this.state.activeGesture == null) {
return;
}
var destIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._detachGesture();
var transitionBackToPresentedIndex = this.state.presentedIndex;
// slight hack: change the presented index for a moment in order to transitionTo correctly
this.state.presentedIndex = destIndex;
this._transitionTo(
transitionBackToPresentedIndex,
null,
1 - this.spring.getCurrentValue()
);
},
_attachGesture: function(gestureId) {
this.state.activeGesture = gestureId;
var gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._enableScene(gesturingToIndex);
},
_detachGesture: function() {
this.state.activeGesture = null;
this.state.pendingGestureProgress = null;
this._hideScenes();
},
_handlePanResponderMove: function(e, gestureState) {
if (this._isMoveGestureAttached !== undefined) {
invariant(
this._expectingGestureGrant,
'Responder granted unexpectedly.'
);
this._attachGesture(this._expectingGestureGrant);
this._onAnimationStart();
this._expectingGestureGrant = undefined;
}
var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex];
if (this.state.activeGesture) {
var gesture = sceneConfig.gestures[this.state.activeGesture];
return this._moveAttachedGesture(gesture, gestureState);
}
var matchedGesture = this._matchGestureAction(GESTURE_ACTIONS, sceneConfig.gestures, gestureState);
if (matchedGesture) {
this._attachGesture(matchedGesture);
}
},
_moveAttachedGesture: function(gesture, gestureState) {
var isTravelVertical = gesture.direction === 'top-to-bottom' || gesture.direction === 'bottom-to-top';
var isTravelInverted = gesture.direction === 'right-to-left' || gesture.direction === 'bottom-to-top';
var distance = isTravelVertical ? gestureState.dy : gestureState.dx;
distance = isTravelInverted ? -distance : distance;
var gestureDetectMovement = gesture.gestureDetectMovement;
var nextProgress = (distance - gestureDetectMovement) /
(gesture.fullDistance - gestureDetectMovement);
if (nextProgress < 0 && gesture.isDetachable) {
var gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._transitionBetween(this.state.presentedIndex, gesturingToIndex, 0);
this._detachGesture();
if (this.state.pendingGestureProgress != null) {
this.spring.setCurrentValue(0);
}
return;
}
if (this._doesGestureOverswipe(this.state.activeGesture)) {
var frictionConstant = gesture.overswipe.frictionConstant;
var frictionByDistance = gesture.overswipe.frictionByDistance;
var frictionRatio = 1 / ((frictionConstant) + (Math.abs(nextProgress) * frictionByDistance));
nextProgress *= frictionRatio;
}
nextProgress = clamp(0, nextProgress, 1);
if (this.state.transitionFromIndex != null) {
this.state.pendingGestureProgress = nextProgress;
} else if (this.state.pendingGestureProgress) {
this.spring.setEndValue(nextProgress);
} else {
this.spring.setCurrentValue(nextProgress);
}
},
_matchGestureAction: function(eligibleGestures, gestures, gestureState) {
if (!gestures || !eligibleGestures || !eligibleGestures.some) {
return null;
}
var matchedGesture = null;
eligibleGestures.some((gestureName, gestureIndex) => {
var gesture = gestures[gestureName];
if (!gesture) {
return;
}
if (gesture.overswipe == null && this._doesGestureOverswipe(gestureName)) {
// cannot swipe past first or last scene without overswiping
return false;
}
var isTravelVertical = gesture.direction === 'top-to-bottom' || gesture.direction === 'bottom-to-top';
var isTravelInverted = gesture.direction === 'right-to-left' || gesture.direction === 'bottom-to-top';
var startedLoc = isTravelVertical ? gestureState.y0 : gestureState.x0;
var currentLoc = isTravelVertical ? gestureState.moveY : gestureState.moveX;
var travelDist = isTravelVertical ? gestureState.dy : gestureState.dx;
var oppositeAxisTravelDist =
isTravelVertical ? gestureState.dx : gestureState.dy;
var edgeHitWidth = gesture.edgeHitWidth;
if (isTravelInverted) {
startedLoc = -startedLoc;
currentLoc = -currentLoc;
travelDist = -travelDist;
oppositeAxisTravelDist = -oppositeAxisTravelDist;
edgeHitWidth = isTravelVertical ?
-(SCREEN_HEIGHT - edgeHitWidth) :
-(SCREEN_WIDTH - edgeHitWidth);
}
if (startedLoc === 0) {
startedLoc = currentLoc;
}
var moveStartedInRegion = gesture.edgeHitWidth == null ||
startedLoc < edgeHitWidth;
if (!moveStartedInRegion) {
return false;
}
var moveTravelledFarEnough = travelDist >= gesture.gestureDetectMovement;
if (!moveTravelledFarEnough) {
return false;
}
var directionIsCorrect = Math.abs(travelDist) > Math.abs(oppositeAxisTravelDist) * gesture.directionRatio;
if (directionIsCorrect) {
matchedGesture = gestureName;
return true;
} else {
this._eligibleGestures = this._eligibleGestures.slice().splice(gestureIndex, 1);
}
});
return matchedGesture || null;
},
_transitionSceneStyle: function(fromIndex, toIndex, progress, index) {
var viewAtIndex = this.refs['scene_' + index];
if (viewAtIndex === null || viewAtIndex === undefined) {
return;
}
// Use toIndex animation when we move forwards. Use fromIndex when we move back
var sceneConfigIndex = fromIndex < toIndex ? toIndex : fromIndex;
var sceneConfig = this.state.sceneConfigStack[sceneConfigIndex];
// this happens for overswiping when there is no scene at toIndex
if (!sceneConfig) {
sceneConfig = this.state.sceneConfigStack[sceneConfigIndex - 1];
}
var styleToUse = {};
var useFn = index < fromIndex || index < toIndex ?
sceneConfig.animationInterpolators.out :
sceneConfig.animationInterpolators.into;
var directionAdjustedProgress = fromIndex < toIndex ? progress : 1 - progress;
var didChange = useFn(styleToUse, directionAdjustedProgress);
if (didChange) {
viewAtIndex.setNativeProps({style: styleToUse});
}
},
_transitionBetween: function(fromIndex, toIndex, progress) {
this._transitionSceneStyle(fromIndex, toIndex, progress, fromIndex);
this._transitionSceneStyle(fromIndex, toIndex, progress, toIndex);
var navBar = this._navBar;
if (navBar && navBar.updateProgress && toIndex >= 0 && fromIndex >= 0) {
navBar.updateProgress(progress, fromIndex, toIndex);
}
},
_handleResponderTerminationRequest: function() {
return false;
},
_getDestIndexWithinBounds: function(n) {
var currentIndex = this.state.presentedIndex;
var destIndex = currentIndex + n;
invariant(
destIndex >= 0,
'Cannot jump before the first route.'
);
var maxIndex = this.state.routeStack.length - 1;
invariant(
maxIndex >= destIndex,
'Cannot jump past the last route.'
);
return destIndex;
},
_jumpN: function(n) {
var destIndex = this._getDestIndexWithinBounds(n);
this._enableScene(destIndex);
this._emitWillFocus(this.state.routeStack[destIndex]);
this._transitionTo(destIndex);
},
/**
* Transition to an existing scene without unmounting.
* @param {object} route Route to transition to. The specified route must
* be in the currently mounted set of routes defined in `routeStack`.
*/
jumpTo: function(route) {
var destIndex = this.state.routeStack.indexOf(route);
invariant(
destIndex !== -1,
'Cannot jump to route that is not in the route stack'
);
this._jumpN(destIndex - this.state.presentedIndex);
},
/**
* Jump forward to the next scene in the route stack.
*/
jumpForward: function() {
this._jumpN(1);
},
/**
* Jump backward without unmounting the current scene.
*/
jumpBack: function() {
this._jumpN(-1);
},
/**
* Navigate forward to a new scene, squashing any scenes that you could
* jump forward to.
* @param {object} route Route to push into the navigator stack.
*/
push: function(route) {
invariant(!!route, 'Must supply route to push');
var activeLength = this.state.presentedIndex + 1;
var activeStack = this.state.routeStack.slice(0, activeLength);
var activeAnimationConfigStack = this.state.sceneConfigStack.slice(0, activeLength);
var nextStack = activeStack.concat([route]);
var destIndex = nextStack.length - 1;
var nextSceneConfig = this.props.configureScene(route, nextStack);
var nextAnimationConfigStack = activeAnimationConfigStack.concat([nextSceneConfig]);
this._emitWillFocus(nextStack[destIndex]);
this.setState({
routeStack: nextStack,
sceneConfigStack: nextAnimationConfigStack,
}, () => {
this._enableScene(destIndex);
this._transitionTo(destIndex, nextSceneConfig.defaultTransitionVelocity);
});
},
_popN: function(n) {
if (n === 0) {
return;
}
invariant(
this.state.presentedIndex - n >= 0,
'Cannot pop below zero'
);
var popIndex = this.state.presentedIndex - n;
var presentedRoute = this.state.routeStack[this.state.presentedIndex];
var popSceneConfig = this.props.configureScene(presentedRoute); // using the scene config of the currently presented view
this._enableScene(popIndex);
this._emitWillFocus(this.state.routeStack[popIndex]);
this._transitionTo(
popIndex,
popSceneConfig.defaultTransitionVelocity,
null, // no spring jumping
() => {
this._cleanScenesPastIndex(popIndex);
}
);
},
/**
* Transition back and unmount the current scene.
*/
pop: function() {
if (this.state.transitionQueue.length) {
// This is the workaround to prevent user from firing multiple `pop()`
// calls that may pop the routes beyond the limit.
// Because `this.state.presentedIndex` does not update until the
// transition starts, we can't reliably use `this.state.presentedIndex`
// to know whether we can safely keep popping the routes or not at this
// moment.
return;
}
if (this.state.presentedIndex > 0) {
this._popN(1);
}
},
/**
* Replace a scene as specified by an index.
* @param {object} route Route representing the new scene to render.
* @param {number} index The route in the stack that should be replaced.
* If negative, it counts from the back of the stack.
* @param {Function} cb Callback function when the scene has been replaced.
*/
replaceAtIndex: function(route, index, cb) {
invariant(!!route, 'Must supply route to replace');
if (index < 0) {
index += this.state.routeStack.length;
}
if (this.state.routeStack.length <= index) {
return;
}
var nextRouteStack = this.state.routeStack.slice();
var nextAnimationModeStack = this.state.sceneConfigStack.slice();
nextRouteStack[index] = route;
nextAnimationModeStack[index] = this.props.configureScene(route, nextRouteStack);
if (index === this.state.presentedIndex) {
this._emitWillFocus(route);
}
this.setState({
routeStack: nextRouteStack,
sceneConfigStack: nextAnimationModeStack,
}, () => {
if (index === this.state.presentedIndex) {
this._emitDidFocus(route);
}
cb && cb();
});
},
/**
* Replace the current scene with a new route.
* @param {object} route Route that replaces the current scene.
*/
replace: function(route) {
this.replaceAtIndex(route, this.state.presentedIndex);
},
/**
* Replace the previous scene.
* @param {object} route Route that replaces the previous scene.
*/
replacePrevious: function(route) {
this.replaceAtIndex(route, this.state.presentedIndex - 1);
},
/**
* Pop to the first scene in the stack, unmounting every other scene.
*/
popToTop: function() {
this.popToRoute(this.state.routeStack[0]);
},
/**
* Pop to a particular scene, as specified by its route.
* All scenes after it will be unmounted.
* @param {object} route Route to pop to.
*/
popToRoute: function(route) {
var indexOfRoute = this.state.routeStack.indexOf(route);
invariant(
indexOfRoute !== -1,
'Calling popToRoute for a route that doesn\'t exist!'
);
var numToPop = this.state.presentedIndex - indexOfRoute;
this._popN(numToPop);
},
/**
* Replace the previous scene and pop to it.
* @param {object} route Route that replaces the previous scene.
*/
replacePreviousAndPop: function(route) {
if (this.state.routeStack.length < 2) {
return;
}
this.replacePrevious(route);
this.pop();
},
/**
* Navigate to a new scene and reset route stack.
* @param {object} route Route to navigate to.
*/
resetTo: function(route) {
invariant(!!route, 'Must supply route to push');
this.replaceAtIndex(route, 0, () => {
// Do not use popToRoute here, because race conditions could prevent the
// route from existing at this time. Instead, just go to index 0
if (this.state.presentedIndex > 0) {
this._popN(this.state.presentedIndex);
}
});
},
/**
* Returns the current list of routes.
*/
getCurrentRoutes: function() {
// Clone before returning to avoid caller mutating the stack
return this.state.routeStack.slice();
},
_cleanScenesPastIndex: function(index) {
var newStackLength = index + 1;
// Remove any unneeded rendered routes.
if (newStackLength < this.state.routeStack.length) {
this.setState({
sceneConfigStack: this.state.sceneConfigStack.slice(0, newStackLength),
routeStack: this.state.routeStack.slice(0, newStackLength),
});
}
},
_renderScene: function(route, i) {
var disabledSceneStyle = null;
var disabledScenePointerEvents = 'auto';
if (i !== this.state.presentedIndex) {
disabledSceneStyle = styles.disabledScene;
disabledScenePointerEvents = 'none';
}
return (
<View
key={'scene_' + getRouteID(route)}
ref={'scene_' + i}
onStartShouldSetResponderCapture={() => {
return (this.state.transitionFromIndex != null) || (this.state.transitionFromIndex != null);
}}
pointerEvents={disabledScenePointerEvents}
style={[styles.baseScene, this.props.sceneStyle, disabledSceneStyle]}>
{this.props.renderScene(
route,
this
)}
</View>
);
},
_renderNavigationBar: function() {
let { navigationBar } = this.props;
if (!navigationBar) {
return null;
}
return React.cloneElement(navigationBar, {
ref: (navBar) => {
this._navBar = navBar;
if (navigationBar && typeof navigationBar.ref === 'function') {
navigationBar.ref(navBar);
}
},
navigator: this._navigationBarNavigator,
navState: this.state,
});
},
render: function() {
var newRenderedSceneMap = new Map();
var scenes = this.state.routeStack.map((route, index) => {
var renderedScene;
if (this._renderedSceneMap.has(route) &&
index !== this.state.presentedIndex) {
renderedScene = this._renderedSceneMap.get(route);
} else {
renderedScene = this._renderScene(route, index);
}
newRenderedSceneMap.set(route, renderedScene);
return renderedScene;
});
this._renderedSceneMap = newRenderedSceneMap;
return (
<View style={[styles.container, this.props.style]}>
<View
style={styles.transitioner}
{...this.panGesture.panHandlers}
onTouchStart={this._handleTouchStart}
onResponderTerminationRequest={
this._handleResponderTerminationRequest
}>
{scenes}
</View>
{this._renderNavigationBar()}
</View>
);
},
_getNavigationContext: function() {
if (!this._navigationContext) {
this._navigationContext = new NavigationContext();
}
return this._navigationContext;
}
});
module.exports = Navigator;
|
website/core/WebPlayer.js | Swaagie/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule WebPlayer
*/
'use strict';
var Prism = require('Prism');
var React = require('React');
var WEB_PLAYER_VERSION = '1.2.6';
/**
* Use the WebPlayer by including a ```ReactNativeWebPlayer``` block in markdown.
*
* Optionally, include url parameters directly after the block's language. For
* the complete list of url parameters, see: https://github.com/dabbott/react-native-web-player
*
* E.g.
* ```ReactNativeWebPlayer?platform=android
* import React from 'react';
* import { AppRegistry, Text } from 'react-native';
*
* const App = () => <Text>Hello World!</Text>;
*
* AppRegistry.registerComponent('MyApp', () => App);
* ```
*/
var WebPlayer = React.createClass({
parseParams: function(paramString) {
var params = {};
if (paramString) {
var pairs = paramString.split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
params[pair[0]] = pair[1];
}
}
return params;
},
render: function() {
var hash = `#code=${encodeURIComponent(this.props.children)}`;
if (this.props.params) {
hash += `&${this.props.params}`;
}
return (
<div className={'web-player'}>
<Prism>{this.props.children}</Prism>
<iframe
style={{marginTop: 4}}
width="880"
height={this.parseParams(this.props.params).platform === 'android' ? '425' : '420'}
data-src={`//cdn.rawgit.com/dabbott/react-native-web-player/gh-v${WEB_PLAYER_VERSION}/index.html${hash}`}
frameBorder="0"
/>
</div>
);
},
});
module.exports = WebPlayer;
|
src/components/Feedback/Feedback.js | djfm/ps-translations-interface-mockup | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 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, { Component } from 'react';
import s from './Feedback.scss';
import withStyles from '../../decorators/withStyles';
@withStyles(s)
class Feedback extends Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<a className={s.link} href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a>
<span className={s.spacer}>|</span>
<a className={s.link} href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a>
</div>
</div>
);
}
}
export default Feedback;
|
src/pages/index.js | apburnes/allpointsburnes | import React from 'react'
import { StaticQuery, graphql } from 'gatsby'
import Layout from '../components/Layout'
import ContentContainer from '../components/ContentContainer'
import Section from '../components/Section'
import CardsSection from '../components/CardsSection'
import Download from '../components/elements/Download'
import Resume from '../components/Resume'
import PostCard from '../components/PostCard'
import ProjectCard from '../components/ProjectCard'
const Posts = ({ data }) => {
const PostsComponent = CardsSection(PostCard)
return <PostsComponent data={data.allMarkdownRemark} length={4} />
}
const Projects = ({ data }) => {
const ProjectsComponent = CardsSection(ProjectCard)
return <ProjectsComponent data={data.allProjectsJson} />
}
export default (props) => (
<StaticQuery
query={graphql`
query IndexQuery {
site {
siteMetadata {
title
}
}
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
edges {
node {
frontmatter {
path
date
description
}
frontmatter {
title
}
}
}
}
allProjectsJson {
edges {
node {
name
link
description
type
}
}
}
allResumeJson {
edges {
node {
start
school
type
end
degree
employer
position
}
}
}
}
`}
render={(data) => (
<Layout location={props.location}>
<ContentContainer>
<Section name="latest posts" to="/posts/">
<Posts data={data} />
</Section>
<Section name="projects">
<Projects data={data} />
</Section>
<Section name="resume">
<Resume edges={data.allResumeJson.edges} />
<Download
url="http://yadayadayadadocs.s3-us-west-2.amazonaws.com/resume/burnes_resume.pdf"
text="Download resume pdf"
/>
</Section>
</ContentContainer>
</Layout>
)}
/>
)
|
plugins/Wallet/js/components/lockscreen.js | NebulousLabs/New-Sia-UI | import PropTypes from 'prop-types'
import React from 'react'
import PasswordPrompt from '../containers/passwordprompt.js'
import UninitializedWalletDialog from '../containers/uninitializedwalletdialog.js'
import RescanDialog from './rescandialog.js'
const LockScreen = ({ unlocked, unlocking, encrypted, rescanning }) => {
if (unlocked && encrypted && !unlocking && !rescanning) {
// Wallet is unlocked and encrypted, return an empty lock screen.
return <div />
}
let lockscreenContents
if (!unlocked && encrypted && !rescanning) {
lockscreenContents = <PasswordPrompt />
} else if (rescanning) {
lockscreenContents = <RescanDialog />
} else if (!encrypted) {
// Wallet is not encrypted, return a lockScreen that initializes a new wallet.
lockscreenContents = <UninitializedWalletDialog />
}
return (
<div className='modal'>
<div className='lockscreen'>{lockscreenContents}</div>
</div>
)
}
LockScreen.propTypes = {
unlocked: PropTypes.bool.isRequired,
unlocking: PropTypes.bool.isRequired,
encrypted: PropTypes.bool.isRequired,
rescanning: PropTypes.bool.isRequired
}
export default LockScreen
|
client/modules/App/components/Header/Header.js | sethkaufee/TherapyApp | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router';
import { FormattedMessage } from 'react-intl';
import { withStyles } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';
import MenuIcon from 'material-ui-icons/Home';
// Import Style
// import styles from './Header.css';
const styles = theme => ({
root: {
marginTop: theme.spacing.unit * 0,
width: '100%',
},
flex: {
flex: 1,
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
});
export function Header(props, context) {
const { classes } = props;
const languageNodes = props.intl.enabledLanguages.map(
lang => <li key={lang} onClick={() => props.switchLanguage(lang)} className={lang === props.intl.locale ? styles.selected : ''}>{lang}</li>
);
let editLink = <Link to="/"/>;
return (
<div className={classes.root}>
<AppBar position="static" elevation={5}>
<Toolbar>
<IconButton component={Link} to="/" className={classes.menuButton} color="contrast" aria-label="Menu">
<MenuIcon />
</IconButton>
<Typography type="title" color="inherit" className={classes.flex}>
Therapy Department
</Typography>
<Button component={Link} to="/search" color="contrast">Search</Button>
<Button component={Link} to="/calendar" color="contrast">Calendar</Button>
<Button disabled color="contrast">Login</Button>
</Toolbar>
</AppBar>
</div>
);
}
Header.contextTypes = {
router: React.PropTypes.object,
};
Header.propTypes = {
toggleAddPost: PropTypes.func.isRequired,
switchLanguage: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(Header);
|
src/svg-icons/action/pageview.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPageview = (props) => (
<SvgIcon {...props}>
<path d="M11.5 9C10.12 9 9 10.12 9 11.5s1.12 2.5 2.5 2.5 2.5-1.12 2.5-2.5S12.88 9 11.5 9zM20 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-2zm-3.21 14.21l-2.91-2.91c-.69.44-1.51.7-2.39.7C9.01 16 7 13.99 7 11.5S9.01 7 11.5 7 16 9.01 16 11.5c0 .88-.26 1.69-.7 2.39l2.91 2.9-1.42 1.42z"/>
</SvgIcon>
);
ActionPageview = pure(ActionPageview);
ActionPageview.displayName = 'ActionPageview';
ActionPageview.muiName = 'SvgIcon';
export default ActionPageview;
|
app/containers/Notifications/index.js | VonIobro/ab-web | import React from 'react';
// import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { notifyRemove } from './actions';
import { selectNotifications } from './selectors';
import { makeSelectLoggedIn } from '../AccountProvider/selectors';
import Notifications from '../../components/Notifications';
const NotificationsContainer = (props) => (
<Notifications {...props} />
);
const mapDispatchToProps = (dispatch) => ({
notifyRemove: (txId) => dispatch(notifyRemove(txId)),
});
const mapStateToProps = createStructuredSelector({
notifications: selectNotifications(),
loggedIn: makeSelectLoggedIn(),
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(NotificationsContainer);
|
test/test.js | VovanR/react-multiselect-two-sides | import test from 'ava';
import React from 'react';
import {shallow, mount} from 'enzyme';
import C from '../src';
test('render component block', t => {
const wrapper = shallow(<C/>);
t.true(wrapper.hasClass('msts'));
t.is(wrapper.type('div'), 'div');
});
test('allow to add custom class name', t => {
const props = {
className: 'foo bar'
};
const wrapper = shallow(<C {...props}/>);
t.true(wrapper.hasClass('msts foo bar'));
});
test('render children blocks', t => {
const props = {
};
const wrapper = shallow(<C {...props}/>);
t.true(wrapper.find('.msts__side').length === 2);
const sideAvailable = wrapper.find('.msts__side_available');
t.is(sideAvailable.type(), 'div');
t.true(sideAvailable.hasClass('msts__side msts__side_available'));
const sideSelected = wrapper.find('.msts__side_selected');
t.is(sideSelected.type(), 'div');
t.true(sideSelected.hasClass('msts__side msts__side_selected'));
});
test('render list items', t => {
const props = {
options: [
{label: 'Foo', value: 0},
{label: 'Bar', value: 1}
],
value: [1]
};
const wrapper = mount(<C {...props}/>);
const items = wrapper.find('.msts__list-item');
t.is(items.get(0).props.children, 'Foo');
t.is(items.get(1).props.children, 'Bar');
});
test('render controls', t => {
const props = {
showControls: true
};
const wrapper = shallow(<C {...props}/>);
const items = wrapper.find('.msts__side_controls');
t.is(items.type(), 'div');
t.true(items.hasClass('msts__side msts__side_controls'));
});
test('dont render controls by default', t => {
const props = {};
const wrapper = shallow(<C {...props}/>);
const items = wrapper.find('.msts__side_controls');
t.is(items.length, 0);
});
test('render filter', t => {
const props = {
searchable: true
};
const wrapper = shallow(<C {...props}/>);
const items = wrapper.find('.msts__subheading');
t.is(items.type(), 'div');
t.true(items.hasClass('msts__subheading'));
});
test('dont render filter by default', t => {
const props = {};
const wrapper = shallow(<C {...props}/>);
const items = wrapper.find('.msts__subheading');
t.is(items.length, 0);
});
test('render filter clear', t => {
const props = {
searchable: true
};
const wrapper = mount(<C {...props}/>);
const filters = wrapper.find('.msts__filter-input');
t.is(wrapper.find('.msts__filter-clear').length, 0, 'dont render if filter is empty');
filters.at(0).simulate('change', {target: {value: 'foo'}});
t.is(wrapper.find('.msts__filter-clear').length, 1);
filters.at(1).simulate('change', {target: {value: 'foo'}});
t.is(wrapper.find('.msts__filter-clear').length, 2);
const filterClear = wrapper.find('.msts__filter-clear');
t.is(filterClear.length, 2);
t.is(filterClear.at(0).type(), 'span');
t.true(filterClear.at(0).hasClass('msts__filter-clear'));
});
test('custom `filterBy` property', t => {
const props = {
searchable: true,
// Custom case-sensitive filter for test
filterBy: (item, filter, labelKey) => item[labelKey].indexOf(filter) > -1,
options: [
{label: 'Foo', value: 0},
{label: 'foo', value: 1},
{label: 'Bar', value: 2},
{label: 'bar', value: 3}
],
value: [2, 3]
};
const wrapper = mount(<C {...props}/>);
const filters = wrapper.find('.msts__filter-input');
filters.at(0).simulate('change', {target: {value: 'Fo'}});
const available = wrapper.find('.msts__side_available');
t.is(available.find('.msts__list-item').length, 1);
t.is(available.find('.msts__list-item').text(), 'Foo');
filters.at(1).simulate('change', {target: {value: 'Ba'}});
const selected = wrapper.find('.msts__side_selected');
t.is(selected.find('.msts__list-item').length, 1);
t.is(selected.find('.msts__list-item').text(), 'Bar');
});
test('dont render filter clear if `clearable` is false', t => {
const props = {
searchable: true,
clearable: false
};
const wrapper = mount(<C {...props}/>);
const filters = wrapper.find('.msts__filter-input');
filters.at(0).simulate('change', {target: {value: 'foo'}});
t.is(wrapper.find('.msts__filter-clear').length, 0);
});
test('`disabled`: disable controls', t => {
const props = {
showControls: true,
disabled: true,
options: [
{label: 'Foo', value: 0},
{label: 'Bar', value: 1}
],
value: [1]
};
const wrapper = mount(<C {...props}/>);
const controls = wrapper.find('.msts__control');
t.is(controls.get(0).props.disabled, true);
t.is(controls.get(1).props.disabled, true);
});
test('`disabled`: disable filter', t => {
const props = {
searchable: true,
disabled: true
};
const wrapper = mount(<C {...props}/>);
const filters = wrapper.find('.msts__filter-input');
t.is(filters.get(0).props.disabled, true);
t.is(filters.get(1).props.disabled, true);
filters.at(0).simulate('change', {target: {value: 'foo'}});
filters.at(1).simulate('change', {target: {value: 'foo'}});
t.is(wrapper.find('.msts__filter-clear').length, 0, 'dont render clear buttons');
});
test('`disabled`: disable component', t => {
const props = {
disabled: true
};
const wrapper = shallow(<C {...props}/>);
t.true(wrapper.hasClass('msts msts_disabled'));
});
test('`disabled`: disable handle', t => {
let isChanged = false;
const props = {
disabled: true,
options: [
{label: 'Foo', value: 0}
],
onChange() {
isChanged = true;
}
};
const wrapper = mount(<C {...props}/>);
const items = wrapper.find('.msts__list-item');
items.simulate('click');
t.false(isChanged);
});
test('`disabled`: disable option', t => {
let isChanged = false;
const props = {
options: [
{label: 'Foo', value: 0, disabled: true}
],
onChange() {
isChanged = true;
}
};
const wrapper = mount(<C {...props}/>);
const items = wrapper.find('.msts__list-item');
items.simulate('click');
t.false(isChanged);
t.true(items.hasClass('msts__list-item'));
t.true(items.hasClass('msts__list-item_disabled'));
});
test('dont select disabled option by select all', t => {
let value = [];
const props = {
showControls: true,
options: [
{label: 'Foo', value: 0, disabled: true},
{label: 'Bar', value: 1}
],
onChange(newValue) {
value = newValue;
}
};
const wrapper = mount(<C {...props}/>);
const selectAll = wrapper.find('.msts__control_select-all');
selectAll.simulate('click');
t.deepEqual(value, [1]);
});
test('`highlight`: highlight option', t => {
const props = {
options: [
{label: 'Foo', value: 0},
{label: 'Bar', value: 1}
],
highlight: [1]
};
const wrapper = mount(<C {...props}/>);
const items = wrapper.find('.msts__list-item');
t.is(items.at(0).props().className, 'msts__list-item');
t.is(items.at(1).props().className, 'msts__list-item msts__list-item_highlighted');
});
test('prop clearFilterText', t => {
const props = {
searchable: true,
clearFilterText: 'Foo'
};
const wrapper = mount(<C {...props}/>);
const filters = wrapper.find('.msts__filter-input');
filters.at(0).simulate('change', {target: {value: 'foo'}});
filters.at(1).simulate('change', {target: {value: 'foo'}});
const filterClear = wrapper.find('.msts__filter-clear');
t.is(filterClear.get(0).props.title, 'Foo');
t.is(filterClear.get(1).props.title, 'Foo');
});
test('prop selectAllText and deselectAllText', t => {
const props = {
showControls: true,
selectAllText: 'Foo',
deselectAllText: 'Bar'
};
const wrapper = mount(<C {...props}/>);
const selectAll = wrapper.find('.msts__control_select-all');
t.is(selectAll.get(0).props.title, 'Foo');
const deselectAll = wrapper.find('.msts__control_deselect-all');
t.is(deselectAll.get(0).props.title, 'Bar');
});
test('prop labelKey and valueKey', t => {
let value = [];
const props = {
labelKey: 'foo',
valueKey: 'bar',
options: [
{foo: 'Foo', bar: 3},
{foo: 'Bar', bar: 4}
],
value: [4],
onChange(newValue) {
value = newValue;
}
};
const wrapper = mount(<C {...props}/>);
const items = wrapper.find('.msts__list-item');
t.is(items.length, 2);
t.is(items.get(0).props.children, 'Foo');
items.at(0).simulate('click');
t.deepEqual(value, [4, 3]);
});
test('prop labelKey and valueKey controls', t => {
let value = [];
const props = {
labelKey: 'foo',
valueKey: 'bar',
showControls: true,
options: [
{foo: 'Foo', bar: 3},
{foo: 'Bar', bar: 4}
],
value: [4],
onChange(newValue) {
value = newValue;
}
};
const wrapper = mount(<C {...props}/>);
const selectAll = wrapper.find('.msts__control_select-all');
selectAll.at(0).simulate('click');
t.deepEqual(value, [3, 4]);
const deselectAll = wrapper.find('.msts__control_deselect-all');
deselectAll.at(0).simulate('click');
t.deepEqual(value, []);
});
test('prop labelKey and valueKey filterAvailable', t => {
const props = {
labelKey: 'foo',
valueKey: 'bar',
searchable: true,
options: [
{foo: 'Foo', bar: 3}
]
};
const wrapper = mount(<C {...props}/>);
const filters = wrapper.find('.msts__filter-input');
t.is(wrapper.find('.msts__list-item').length, 1);
filters.at(0).simulate('change', {target: {value: 'f'}});
t.is(wrapper.find('.msts__list-item').length, 1);
filters.at(0).simulate('change', {target: {value: 'fb'}});
t.is(wrapper.find('.msts__list-item').length, 0);
});
test('prop labelKey and valueKey filterSelected', t => {
const props = {
labelKey: 'foo',
valueKey: 'bar',
searchable: true,
options: [
{foo: 'Foo', bar: 3}
],
value: [3]
};
const wrapper = mount(<C {...props}/>);
t.is(wrapper.find('.msts__list-item').length, 1);
const filters = wrapper.find('.msts__filter-input');
filters.at(1).simulate('change', {target: {value: 'f'}});
t.is(wrapper.find('.msts__list-item').length, 1, '`f`');
filters.at(1).simulate('change', {target: {value: 'fb'}});
t.is(wrapper.find('.msts__list-item').length, 0, '`fb`');
});
test('limit list', t => {
let isChanged = false;
const props = {
options: [
{label: 'Foo', value: 0},
{label: 'Bar', value: 1},
{label: 'Baz', value: 2},
{label: 'Qux', value: 3},
{label: 'Quux', value: 4}
],
limit: 3,
value: [0, 1, 2],
onChange() {
isChanged = true;
}
};
const wrapper = mount(<C {...props}/>);
const items = wrapper.find('.msts__list-item');
items.at(0).simulate('click');
t.is(items.at(0).props().className, 'msts__list-item msts__list-item_disabled');
t.is(items.at(0).text(), 'Qux');
t.is(items.at(1).props().className, 'msts__list-item msts__list-item_disabled');
t.is(items.at(1).text(), 'Quux');
t.false(isChanged);
});
test('limit list selectall', t => {
let value = [];
const props = {
showControls: true,
options: [
{label: 'Foo', value: 0},
{label: 'Bar', value: 1, disabled: true},
{label: 'Baz', value: 2},
{label: 'Qux', value: 3},
{label: 'Quux', value: 4}
],
value: [4],
limit: 3,
onChange(newValue) {
value = newValue;
}
};
const wrapper = mount(<C {...props}/>);
const selectAll = wrapper.find('.msts__control_select-all');
selectAll.simulate('click');
t.deepEqual(value, [0, 2, 4]);
});
test('selectall filtered items only', t => {
let value = [];
const props = {
searchable: true,
showControls: true,
options: [
{label: 'Foo', value: 0},
{label: 'Bar', value: 1},
{label: 'Baz', value: 2},
{label: 'Qux', value: 3},
{label: 'Quux', value: 4}
],
value: [0],
onChange(newValue) {
value = newValue;
}
};
const wrapper = mount(<C {...props}/>);
const filters = wrapper.find('.msts__filter-input');
const selectAll = wrapper.find('.msts__control_select-all');
filters.at(0).simulate('change', {target: {value: 'ux'}});
selectAll.simulate('click');
t.deepEqual(value, [0, 3, 4]);
});
test('deselectall filtered items only', t => {
let value = [];
const props = {
searchable: true,
showControls: true,
options: [
{label: 'Foo', value: 0},
{label: 'Bar', value: 1},
{label: 'Baz', value: 2},
{label: 'Qux', value: 3},
{label: 'Quux', value: 4}
],
value: [0, 1, 2, 3, 4],
onChange(newValue) {
value = newValue;
}
};
const wrapper = mount(<C {...props}/>);
const filters = wrapper.find('.msts__filter-input');
const deselectAll = wrapper.find('.msts__control_deselect-all');
filters.at(1).simulate('change', {target: {value: 'ux'}});
deselectAll.simulate('click');
t.deepEqual(value, [0, 1, 2]);
});
|
examples/with-qs/pages/index.js | BDav24/next-url-prettifier | import React from 'react';
import {Link} from 'next-url-prettifier';
import {Router} from '../routes';
export default function IndexPage() {
const linkParams = {
a: 1,
b: [2, 3],
c: {d: [4, 5]}
};
return (
<div>
<h1>Homepage</h1>
<Link route={Router.getPrettyUrl('index', linkParams)}>
<a>Link with complex params</a>
</Link>
</div>
);
}
|
src/Svg/ArrowSVG.js | numieco/patriot-trading | import React from 'react'
const ArrowSVG = () => (
<div>
<svg width="9px" height="17px" viewBox="0 0 9 17" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">
<title>Shape Copy 8</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Welcome" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
<g id="Tablet" transform="translate(-772.000000, -2143.000000)" stroke="#1C1E22" fillRule="nonzero" strokeWidth="1.428" fill="#1C1E22">
<path d="M774.095746,2144.22559 C773.849472,2143.9248 773.43959,2143.9248 773.184705,2144.22559 C772.938432,2144.51621 772.938432,2144.99991 773.184705,2145.28986 L777.804203,2150.74126 C777.804203,2150.74126 778.279093,2151.2515 778.279093,2151.5 C778.279093,2151.7485 777.804203,2152.25806 777.804203,2152.25806 L773.184705,2157.6993 C772.938432,2158.00009 772.938432,2158.48446 773.184705,2158.77441 C773.43959,2159.0752 773.850046,2159.0752 774.095746,2158.77441 L779.808836,2152.03247 C780.063721,2151.74185 780.063721,2151.25815 779.808836,2150.96821 L774.095746,2144.22559 Z" id="Shape-Copy-8" transform="translate(776.500000, 2151.500000) scale(1, -1) rotate(-360.000000) translate(-776.500000, -2151.500000) "></path>
</g>
</g>
</svg>
</div>
)
export default ArrowSVG |
docs/src/sections/PanelSection.js | jesenko/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function PanelSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="panels">Panels</Anchor> <small>Panel, PanelGroup, Accordion</small>
</h2>
<h3><Anchor id="panels-basic">Basic example</Anchor></h3>
<p>By default, all the <code><Panel /></code> does is apply some basic border and padding to contain some content.</p>
<p>You can pass on any additional properties you need, e.g. a custom <code>onClick</code> handler, as it is shown in the example code. They all will apply to the wrapper <code>div</code> element.</p>
<ReactPlayground codeText={Samples.PanelBasic} />
<h3><Anchor id="panels-collapsible">Collapsible Panel</Anchor></h3>
<ReactPlayground codeText={Samples.PanelCollapsible} />
<h3><Anchor id="panels-heading">Panel with heading</Anchor></h3>
<p>Easily add a heading container to your panel with the <code>header</code> prop.</p>
<ReactPlayground codeText={Samples.PanelWithHeading} />
<h3><Anchor id="panels-footer">Panel with footer</Anchor></h3>
<p>Pass buttons or secondary text in the <code>footer</code> prop. Note that panel footers do not inherit colors and borders when using contextual variations as they are not meant to be in the foreground.</p>
<ReactPlayground codeText={Samples.PanelWithFooter} />
<h3><Anchor id="panels-contextual">Contextual alternatives</Anchor></h3>
<p>Like other components, easily make a panel more meaningful to a particular context by adding a <code>bsStyle</code> prop.</p>
<ReactPlayground codeText={Samples.PanelContextual} />
<h3><Anchor id="panels-tables">With tables and list groups</Anchor></h3>
<p>Add the <code>fill</code> prop to <code><Table /></code> or <code><ListGroup /></code> elements to make them fill the panel.</p>
<ReactPlayground codeText={Samples.PanelListGroupFill} />
<h3><Anchor id="panels-controlled">Controlled PanelGroups</Anchor></h3>
<p><code>PanelGroup</code>s can be controlled by a parent component. The <code>activeKey</code> prop dictates which panel is open.</p>
<ReactPlayground codeText={Samples.PanelGroupControlled} />
<h3><Anchor id="panels-uncontrolled">Uncontrolled PanelGroups</Anchor></h3>
<p><code>PanelGroup</code>s can also be uncontrolled where they manage their own state. The <code>defaultActiveKey</code> prop dictates which panel is open when initially.</p>
<ReactPlayground codeText={Samples.PanelGroupUncontrolled} />
<h3><Anchor id="panels-accordion">Accordions</Anchor></h3>
<p><code><Accordion /></code> aliases <code><PanelGroup accordion /></code>.</p>
<ReactPlayground codeText={Samples.PanelGroupAccordion} />
<h3><Anchor id="panels-props">Props</Anchor></h3>
<h4><Anchor id="panels-props-accordion">Panels, Accordion</Anchor></h4>
<PropTable component="Panel"/>
<h4><Anchor id="panels-props-group">PanelGroup</Anchor></h4>
<PropTable component="PanelGroup"/>
</div>
);
}
|
src/DropdownToggle.js | pandoraui/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import Button from './Button';
import CustomPropTypes from './utils/CustomPropTypes';
import SafeAnchor from './SafeAnchor';
const CARET = <span> <span className="caret" /></span>;
export default class DropdownToggle extends React.Component {
render() {
const caret = this.props.noCaret ? null : CARET;
const classes = {
'dropdown-toggle': true
};
const Component = this.props.useAnchor ? SafeAnchor : Button;
return (
<Component
{...this.props}
className={classNames(classes, this.props.className)}
type="button"
aria-haspopup
aria-expanded={this.props.open}>
{this.props.title || this.props.children}{caret}
</Component>
);
}
}
const titleAndChildrenValidation = CustomPropTypes.singlePropFrom([
'title',
'children'
]);
DropdownToggle.defaultProps = {
open: false,
useAnchor: false,
bsRole: 'toggle'
};
DropdownToggle.propTypes = {
bsRole: React.PropTypes.string,
children: titleAndChildrenValidation,
noCaret: React.PropTypes.bool,
open: React.PropTypes.bool,
title: titleAndChildrenValidation,
useAnchor: React.PropTypes.bool
};
DropdownToggle.isToggle = true;
DropdownToggle.titleProp = 'title';
DropdownToggle.onClickProp = 'onClick';
|
src/svg-icons/navigation/arrow-drop-up.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationArrowDropUp = (props) => (
<SvgIcon {...props}>
<path d="M7 14l5-5 5 5z"/>
</SvgIcon>
);
NavigationArrowDropUp = pure(NavigationArrowDropUp);
NavigationArrowDropUp.displayName = 'NavigationArrowDropUp';
NavigationArrowDropUp.muiName = 'SvgIcon';
export default NavigationArrowDropUp;
|
app/containers/Home/HomeContainer.js | saelili/F3C_Website | import React from 'react'
import { HeroContainer, AdminsContainer, CtaContainer, ResourcesContainer } from '../'
import styles from './styles.scss'
const HomeContainer = () => (
<div>
<HeroContainer />
<hr className={styles.break} />
<AdminsContainer />
<hr className={styles.break} />
<CtaContainer />
<hr className={styles.break} />
<ResourcesContainer />
</div>
)
export default HomeContainer
|
ReactNativeApp/react-native-starter-app/src/index.js | jjhyu/hackthe6ix2017 | /**
* Index - this is where everything
* starts - but offloads to app.js
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
/* global __DEV__ */
import React from 'react';
import { applyMiddleware, compose, createStore } from 'redux';
import { connect, Provider } from 'react-redux';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import { Router } from 'react-native-router-flux';
// Consts and Libs
import { AppStyles } from '@theme/';
import AppRoutes from '@navigation/';
import Analytics from '@lib/analytics';
// All redux reducers (rolled into one mega-reducer)
import rootReducer from '@redux/index';
// Connect RNRF with Redux
const RouterWithRedux = connect()(Router);
// Load middleware
let middleware = [
Analytics,
thunk, // Allows action creators to return functions (not just plain objects)
];
if (__DEV__) {
// Dev-only middleware
middleware = [
...middleware,
createLogger(), // Logs state changes to the dev console
];
}
// Init redux store (using the given reducer & middleware)
const store = compose(
applyMiddleware(...middleware),
)(createStore)(rootReducer);
/* Component ==================================================================== */
// Wrap App in Redux provider (makes Redux available to all sub-components)
export default function AppContainer() {
return (
<Provider store={store}>
<RouterWithRedux scenes={AppRoutes} style={AppStyles.appContainer} />
</Provider>
);
}
|
modules/gui/src/app/home/body/process/recipe/ccdc/panels/opticalPreprocess/opticalPreprocess.js | openforis/sepal | import {Form} from 'widget/form/form'
import {Layout} from 'widget/layout'
import {Panel} from 'widget/panel/panel'
import {RecipeFormPanel, recipeFormPanel} from 'app/home/body/process/recipeFormPanel'
import {compose} from 'compose'
import {msg} from 'translate'
import {selectFrom} from 'stateUtils'
import React from 'react'
import _ from 'lodash'
import styles from './opticalPreprocess.module.css'
const fields = {
corrections: new Form.Field(),
histogramMatching: new Form.Field(),
cloudDetection: new Form.Field(),
cloudMasking: new Form.Field(),
shadowMasking: new Form.Field(),
snowMasking: new Form.Field()
}
const mapRecipeToProps = recipe => ({
sources: selectFrom(recipe, 'model.sources.dataSets'),
dataSetType: selectFrom(recipe, 'model.sources.dataSetType'),
})
class OpticalPreprocess extends React.Component {
render() {
return (
<RecipeFormPanel
className={styles.panel}
placement='bottom-right'>
<Panel.Header
icon='cog'
title={msg('process.ccdc.panel.preprocess.title')}/>
<Panel.Content>
<Layout>
{this.renderCorrectionsOptions()}
{this.renderHistogramMatching()}
{this.renderCloudDetectionOptions()}
{this.renderCloudMaskingOptions()}
{this.renderShadowMaskingOptions()}
{this.renderSnowMaskingOptions()}
</Layout>
</Panel.Content>
<Form.PanelButtons/>
</RecipeFormPanel>
)
}
renderCorrectionsOptions() {
const {dataSetType, inputs: {corrections}} = this.props
if (dataSetType === 'PLANET') {
return null
}
return (
<Form.Buttons
label={msg('process.ccdc.panel.preprocess.form.corrections.label')}
input={corrections}
multiple={true}
options={[{
value: 'SR',
label: msg('process.ccdc.panel.preprocess.form.corrections.surfaceReflectance.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.corrections.surfaceReflectance.tooltip')
}, {
value: 'BRDF',
label: msg('process.ccdc.panel.preprocess.form.corrections.brdf.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.corrections.brdf.tooltip')
}]}
/>
)
}
renderHistogramMatching() {
const {dataSetType, inputs: {histogramMatching}} = this.props
if (dataSetType !== 'PLANET') {
return null
}
const options = [
{value: 'ENABLED', label: msg('process.planetMosaic.panel.options.form.histogramMatching.options.ENABLED')},
{value: 'DISABLED', label: msg('process.planetMosaic.panel.options.form.histogramMatching.options.DISABLED')},
]
return (
<Form.Buttons
label={msg('process.planetMosaic.panel.options.form.histogramMatching.label')}
tooltip={msg('process.planetMosaic.panel.options.form.histogramMatching.tooltip')}
input={histogramMatching}
options={options}
/>
)
}
renderCloudDetectionOptions() {
const {sources, inputs: {corrections, cloudDetection}} = this.props
const pino26Disabled = corrections.value.includes('SR') || !_.isEqual(Object.keys(sources), ['SENTINEL_2'])
return (
<Form.Buttons
label={msg('process.ccdc.panel.preprocess.form.cloudDetection.label')}
input={cloudDetection}
multiple
options={[
{
value: 'QA',
label: msg('process.ccdc.panel.preprocess.form.cloudDetection.qa.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.cloudDetection.qa.tooltip')
},
{
value: 'CLOUD_SCORE',
label: msg('process.ccdc.panel.preprocess.form.cloudDetection.cloudScore.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.cloudDetection.cloudScore.tooltip')
},
{
value: 'PINO_26',
label: msg('process.ccdc.panel.preprocess.form.cloudDetection.pino26.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.cloudDetection.pino26.tooltip'),
neverSelected: pino26Disabled
}
]}
type='horizontal'
disabled={this.noProcessing()}
/>
)
}
renderCloudMaskingOptions() {
const {inputs: {cloudMasking}} = this.props
return (
<Form.Buttons
label={msg('process.ccdc.panel.preprocess.form.cloudMasking.label')}
input={cloudMasking}
options={[{
value: 'MODERATE',
label: msg('process.ccdc.panel.preprocess.form.cloudMasking.moderate.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.cloudMasking.moderate.tooltip')
}, {
value: 'AGGRESSIVE',
label: msg('process.ccdc.panel.preprocess.form.cloudMasking.aggressive.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.cloudMasking.aggressive.tooltip')
}]}
type='horizontal'
disabled={this.noProcessing()}
/>
)
}
renderShadowMaskingOptions() {
const {inputs: {shadowMasking}} = this.props
return (
<Form.Buttons
label={msg('process.ccdc.panel.preprocess.form.shadowMasking.label')}
input={shadowMasking}
options={[{
value: 'OFF',
label: msg('process.ccdc.panel.preprocess.form.shadowMasking.off.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.shadowMasking.off.tooltip')
}, {
value: 'ON',
label: msg('process.ccdc.panel.preprocess.form.shadowMasking.on.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.shadowMasking.on.tooltip')
}]}
type='horizontal-nowrap'
disabled={this.noProcessing()}
/>
)
}
renderSnowMaskingOptions() {
const {inputs: {snowMasking}} = this.props
return (
<Form.Buttons
label={msg('process.ccdc.panel.preprocess.form.snowMasking.label')}
input={snowMasking}
options={[{
value: 'OFF',
label: msg('process.ccdc.panel.preprocess.form.snowMasking.off.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.snowMasking.off.tooltip')
}, {
value: 'ON',
label: msg('process.ccdc.panel.preprocess.form.snowMasking.on.label'),
tooltip: msg('process.ccdc.panel.preprocess.form.snowMasking.on.tooltip')
}]}
type='horizontal-nowrap'
disabled={this.noProcessing()}
/>
)
}
componentDidMount() {
const {inputs: {histogramMatching}} = this.props
if (!histogramMatching.value) {
histogramMatching.set('DISABLED')
}
}
noProcessing() {
const {sources, inputs: {histogramMatching}} = this.props
return Object.values(sources).flat().includes('DAILY') && histogramMatching.value !== 'ENABLED'
}
}
OpticalPreprocess.propTypes = {}
const valuesToModel = values => ({
corrections: values.corrections,
histogramMatching: values.histogramMatching,
cloudDetection: values.cloudDetection,
cloudMasking: values.cloudMasking,
shadowMasking: values.shadowMasking,
snowMasking: values.snowMasking,
})
const modelToValues = model => {
return ({
corrections: model.corrections,
histogramMatching: model.histogramMatching,
cloudDetection: model.cloudDetection,
cloudMasking: model.cloudMasking,
shadowMasking: model.shadowMasking,
snowMasking: model.snowMasking
})
}
export default compose(
OpticalPreprocess,
recipeFormPanel({id: 'options', fields, modelToValues, valuesToModel, mapRecipeToProps})
)
|
react/ScreenReaderSkipTarget/ScreenReaderSkipTarget.js | seekinternational/seek-asia-style-guide | import styles from './ScreenReaderSkipTarget.less';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class ScreenReaderSkipTarget extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
])
};
render() {
return (
<div tabIndex="-1" className={styles.root} id={this.props.name}>
{this.props.children}
</div>
);
}
}
|
docs-site/src/components/schema-form/grid-layout.js | bolt-design-system/bolt | import { h } from '@bolt/core';
// import React from 'react';
import React, { Component } from 'react';
import { WidthProvider, Responsive } from 'react-grid-layout';
const ResponsiveReactGridLayout = WidthProvider(Responsive);
const originalLayouts = getFromLS('layouts') || {};
/**
* This layout demonstrates how to sync multiple responsive layouts to localstorage.
*/
export class ResponsiveLocalStorageLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
layouts: JSON.parse(JSON.stringify(originalLayouts)),
};
}
static get defaultProps() {
return {
className: 'c-bolt-demo-grid',
cols: {
lg: 12,
md: 10,
sm: 6,
xs: 4,
xxs: 2,
},
rowHeight: 10,
};
}
resetLayout() {
this.setState({ layouts: {} });
}
onLayoutChange(layout, layouts) {
saveToLS('layouts', layouts);
this.setState({ layouts });
}
render() {
return (
<div style={this.props.style} className={this.props.className}>
<button
style={{
position: 'absolute',
bottom: 0,
left: 0,
transform: 'translate3d(0, 100%, 0)',
}}
onClick={() => this.resetLayout()}>
Reset Layout
</button>
<ResponsiveReactGridLayout
className="layout"
margin={[0, 0]}
// cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}
cols={{
lg: 12,
md: 8,
sm: 6,
xs: 4,
xxs: 2,
}}
style={{
alignSelf: 'center',
width: '100%',
display: 'flex',
justifyContent: 'center',
}}
isDraggable={false}
// rowHeight={30}
layouts={this.state.layouts}
onLayoutChange={(layout, layouts) =>
this.onLayoutChange(layout, layouts)
}>
{this.props.children}
</ResponsiveReactGridLayout>
</div>
);
}
}
function getFromLS(key) {
let ls = {};
if (global.localStorage) {
try {
ls = JSON.parse(global.localStorage.getItem('rgl-8')) || {};
} catch (e) {
/*Ignore*/
}
}
return ls[key];
}
function saveToLS(key, value) {
if (global.localStorage) {
global.localStorage.setItem(
'rgl-8',
JSON.stringify({
[key]: value,
}),
);
}
}
|
web/src/components/Description.js | doeg/plantly-graphql | import cx from 'classnames'
import React from 'react'
import style from './description.css'
import EditableText from './EditableText'
import type { PlantPatch } from '../mutations/UpdatePlantMutation'
type Props = {
children?: ?any,
className?: ?string,
onPlantUpdate: (plantPatch: PlantPatch) => void,
plant: ?Object,
}
const Description = ({ children, className, onPlantUpdate, plant }: Props) => {
const onSave = (description: ?string) => {
onPlantUpdate({ description })
}
return (
<EditableText
element="p"
multiline
onSave={onSave}
placeholder="Add a description"
>
{plant.description}
</EditableText>
)
}
export default Description
|
Client/src/js/history.js | simondi88/schoolbus | import React from 'react';
import * as Api from './api';
import * as Constant from './constants';
// History Entity Types
export const BUS = 'School Bus';
export const OWNER = 'Owner';
export const USER = 'User';
export const ROLE = 'Role';
export const INSPECTION = 'Inspection';
// History Events
export const BUS_ADDED = 'School Bus %e was added by Owner %e.';
export const BUS_MODIFIED = 'School Bus %e was modified.';
export const BUS_MODIFIED_OWNER = 'The owner of School Bus %e was changed to %e.';
export const BUS_MODIFIED_STATUS = 'The status of School Bus %e was changed';
export const BUS_PASSED_INSPECTION = 'School Bus %e passed an Inspection %e.';
export const BUS_FAILED_INSPECTION = 'School Bus %e failed an Inspection %e.';
export const BUS_OUT_OF_SERVICE = 'School Bus %e is out of service %e.';
export const BUS_PERMIT_GENERATED = 'School Bus %e - Permit';
export const BUS_INSPECTION_ADDED = 'School Bus %e - Inspection %e was added.';
export const BUS_INSPECTION_MODIFIED = 'School Bus %e - Inspection %e was modified.';
export const BUS_INSPECTION_DELETED = 'School Bus %e - Inspection %e was deleted.';
export const OWNER_ADDED = 'Owner %e was added.';
export const OWNER_MODIFIED = 'Owner %e was modified.';
export const OWNER_MODIFIED_STATUS = 'The status of %e was changed';
export const OWNER_MODIFIED_NAME = 'Owner name was changed to %e';
export const OWNER_ADDED_BUS = 'A school bus was added or moved to Owner %e - School Bus %e.';
export const OWNER_REMOVED_BUS = 'A school bus was removed from Owner %e - School Bus %e.';
export const USER_ADDED = 'User %e was added.';
export const USER_MODIFIED = 'User %e was modified.';
export const USER_DELETED = 'User %e was deleted.';
// Helper to create an entity object
export function makeHistoryEntity(type, entity) {
return {
type: type,
id: entity.id,
description: entity.name,
url: entity.url,
path: entity.path,
};
}
// Log a history event
export function log(historyEntity, event, ...entities) {
// prepend the 'parent' entity
entities.unshift(historyEntity);
// Build the history text
var historyText = JSON.stringify({
// The event text, with entity placeholders
text: event,
// The array of entities
entities: entities,
});
// Choose the correct API call.
var addHistoryPromise = null;
switch (historyEntity.type) {
case BUS:
addHistoryPromise = Api.addSchoolBusHistory;
break;
case OWNER:
addHistoryPromise = Api.addOwnerHistory;
break;
case USER:
addHistoryPromise = Api.addUserHistory;
break;
}
if (addHistoryPromise) {
addHistoryPromise(historyEntity.id, {
historyText: historyText,
});
}
return historyText;
}
function buildLink(entity, closeFunc) {
// Return a link if the entity has a path; just the description otherwise.
return entity.path ? <a onClick={ closeFunc } href={ entity.url }>{ entity.description }</a> : <span>{ entity.description }</span>;
}
export function renderEvent(historyText, closeFunc) {
try {
// Unwrap the JSONed event
var event = JSON.parse(historyText);
// Parse the text and return it inside a <div>, replacing field placeholders with linked content.
var tokens = event.text.split('%e');
return <div>
{
tokens.map((token, index) => {
return <span key={ index }>
{ token }
{ index < tokens.length - 1 ? buildLink(event.entities[index], closeFunc) : null }
</span>;
})
}
</div>;
} catch (err) {
// Not JSON so just push out what's in there.
return <span>{ historyText }</span>;
}
}
export function get(historyEntity, offset, limit) {
// If not showing all, then just fetch the first 10 entries
var params = {
offset: offset || 0,
limit: limit || null,
};
switch (historyEntity.type) {
case BUS:
return Api.getSchoolBusHistory(historyEntity.id, params);
case OWNER:
return Api.getOwnerHistory(historyEntity.id, params);
case USER:
return Api.getUserHistory(historyEntity.id, params);
}
return null;
}
// Logging
export function logNewBus(bus, owner) {
log(bus.historyEntity, BUS_ADDED, owner.historyEntity);
log(owner.historyEntity, OWNER_ADDED_BUS, bus.historyEntity);
}
export function logModifiedBus(bus) {
log(bus.historyEntity, BUS_MODIFIED);
}
// Bus Details
export function logModifiedBusStatus(bus) {
var event = BUS_MODIFIED_STATUS;
// Check if status exists.
if(typeof(bus.status) === 'string') {
event += ' to ';
event += bus.status;
}
event += '.';
log(bus.historyEntity, event);
}
export function logModifiedBusOwner(bus, previousOwner) {
// Temporary fix for owner.historyEntity async load issue
var nextOwnerHistoryMock = {
type: 'Owner',
id: bus.schoolBusOwner.id,
description: bus.ownerName,
url: bus.ownerURL,
};
nextOwnerHistoryMock.path = 'owners/' + bus.schoolBusOwner.id;
log(bus.historyEntity, BUS_MODIFIED_OWNER, nextOwnerHistoryMock);
log(nextOwnerHistoryMock, OWNER_ADDED_BUS, bus.historyEntity);
log(previousOwner.historyEntity, OWNER_REMOVED_BUS, bus.historyEntity);
}
export function logGeneratedBusPermit(bus) {
var event = BUS_PERMIT_GENERATED;
if(bus.permitNumber) {
event += ' #';
event += (bus.permitNumber).toString();
}
event += ' was generated.';
log(bus.historyEntity, event);
}
// Bus Inspection
export function logNewInspection(bus, inspection) {
var event = null;
if (inspection.inspectionResultCode === Constant.INSPECTION_RESULT_FAILED) {
event = BUS_FAILED_INSPECTION;
} else if (inspection.inspectionResultCode === Constant.INSPECTION_RESULT_PASSED) {
event = BUS_PASSED_INSPECTION;
} else if (inspection.inspectionResultCode === Constant.INSPECTION_RESULT_OUT_OF_SERVICE) {
event = BUS_OUT_OF_SERVICE;
}
if (event) {
log(bus.historyEntity, event, inspection.historyEntity);
}
}
export function logModifiedInspection(bus, inspection) {
log(bus.historyEntity, BUS_INSPECTION_MODIFIED, inspection.historyEntity);
}
export function logDeletedInspection(bus, inspection) {
log(bus.historyEntity, BUS_INSPECTION_DELETED, inspection.historyEntity);
}
//// LOG OWNER
export function logNewOwner(owner) {
log(owner.historyEntity, OWNER_ADDED);
}
export function logModifiedOwnerStatus(owner) {
var event = OWNER_MODIFIED_STATUS;
if(typeof(owner.status) === 'string') {
event += ' to ';
event += owner.status;
}
event += '.';
log(owner.historyEntity, event);
}
export function logModifiedOwnerName(owner) {
log(owner.historyEntity, OWNER_MODIFIED_NAME);
}
|
blueocean-material-icons/src/js/components/svg-icons/action/search.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionSearch = (props) => (
<SvgIcon {...props}>
<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
</SvgIcon>
);
ActionSearch.displayName = 'ActionSearch';
ActionSearch.muiName = 'SvgIcon';
export default ActionSearch;
|
example/pages/preview/index.js | n7best/react-weui | import React from 'react';
import Page from '../../component/page';
import { Preview, PreviewHeader, PreviewFooter, PreviewBody, PreviewItem, PreviewButton } from '../../../build/packages';
const PreviewDemo = (props) => (
<Page className="preview" title="Preview" subTitle="表单预览">
<Preview>
<PreviewHeader>
<PreviewItem label="Total" value="$49.99" />
</PreviewHeader>
<PreviewBody>
<PreviewItem label="Product" value="Name" />
<PreviewItem label="Description" value="Product Description" />
<PreviewItem label="Details" value="Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. " />
</PreviewBody>
<PreviewFooter>
<PreviewButton primary>Action</PreviewButton>
</PreviewFooter>
</Preview>
<br/>
<Preview>
<PreviewHeader>
<PreviewItem label="Total" value="$49.99" />
</PreviewHeader>
<PreviewBody>
<PreviewItem label="Product" value="Name" />
<PreviewItem label="Description" value="Product Description" />
<PreviewItem label="Details" value="Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. " />
</PreviewBody>
<PreviewFooter>
<PreviewButton >Action</PreviewButton>
<PreviewButton primary>Action</PreviewButton>
</PreviewFooter>
</Preview>
</Page>
);
export default PreviewDemo; |
assets/jqwidgets/demos/react/app/fileupload/buttonsrendering/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxFileUpload from '../../../jqwidgets-react/react_jqxfileupload.js';
class App extends React.Component {
render() {
return (
<JqxFileUpload
width={300} uploadUrl={'imageUpload.php'}
fileInputName={'fileToUpload'} cancelTemplate={'danger'}
browseTemplate={'success'} uploadTemplate={'primary'}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
app/components/AppExperimentals/index.js | ethan605/react-native-zero | /**
* @providesModule ZeroProj.Components.AppExperimentals
*/
import React from 'react';
import { StyleSheet, View } from 'react-native';
import Button from 'react-native-button';
import moment from 'moment';
import _ from 'lodash';
// Constants
import { FEATURES } from 'app/constants/Flags';
// Utils
import FontUtils from 'app/utils/FontUtils';
import Logger from 'app/utils/Logger';
// Locals
import withConnect from './withConnect';
if (FEATURES.GLOBAL_MODULES) {
Object.assign(global, {
moment,
_,
});
}
function Welcome({ onPress }) {
return (
<View style={styles.container}>
<Button onPress={onPress} style={styles.welcomeText}>
Make some experiments!
</Button>
</View>
);
}
class AppExperimentals extends React.PureComponent {
componentDidMount() {
}
onPress = () => {
Logger.debug('invoke onPress');
};
render() {
return <Welcome onPress={this.onPress} />;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#3b5998',
},
welcomeText: FontUtils.build({
align: 'center',
color: 'white',
size: 20,
weight: FontUtils.weights.bold,
}),
});
export default withConnect(AppExperimentals);
|
admin/client/App/shared/Popout/PopoutListItem.js | michaelerobertsjr/keystone | /**
* Render a popout list item
*/
import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';
var PopoutListItem = React.createClass({
displayName: 'PopoutListItem',
propTypes: {
icon: React.PropTypes.string,
iconHover: React.PropTypes.string,
isSelected: React.PropTypes.bool,
label: React.PropTypes.string.isRequired,
onClick: React.PropTypes.func,
},
getInitialState () {
return {
hover: false,
};
},
hover () {
this.setState({ hover: true });
},
unhover () {
this.setState({ hover: false });
},
// Render an icon
renderIcon () {
if (!this.props.icon) return null;
const icon = this.state.hover && this.props.iconHover ? this.props.iconHover : this.props.icon;
const iconClassname = classnames('PopoutList__item__icon octicon', ('octicon-' + icon));
return <span className={iconClassname} />;
},
render () {
const itemClassname = classnames('PopoutList__item', {
'is-selected': this.props.isSelected,
});
const props = blacklist(this.props, 'className', 'icon', 'isSelected', 'label');
return (
<button
type="button"
title={this.props.label}
className={itemClassname}
onFocus={this.hover}
onBlur={this.unhover}
onMouseOver={this.hover}
onMouseOut={this.unhover}
{...props}
>
{this.renderIcon()}
<span className="PopoutList__item__label">
{this.props.label}
</span>
</button>
);
},
});
module.exports = PopoutListItem;
|
javascript/User/SingleBallotTicket.js | AppStateESS/election | 'use strict'
import React from 'react'
import PropTypes from 'prop-types'
import Panel from '../Mixin/Panel'
import SingleCandidate from './SingleCandidate'
import {BreakIt} from '../Mixin/Mixin.jsx'
const SingleBallotTicket = (props) => {
const candidateCount = props.candidates.length
let candidates
if (candidateCount > 0) {
candidates = props.candidates.map(function (value) {
return <SingleCandidate key={value.id} {...value} candidateLength={candidateCount}/>
}.bind(this))
}
var heading = <h2>{props.title}</h2>
var platform = BreakIt(props.platform)
var website = null
if (props.siteAddress.length) {
website = <div className="website">
<a href={props.siteAddress} target="_blank">{props.siteAddress}
<i className="fa fa-external-link"></i>
</a>
</div>
}
var body = (
<div className="ticket">
<div className="row">
<div className="col-sm-6">
{platform}
<hr/> {website}
</div>
{candidates}
</div>
<button className="btn btn-primary btn-block btn-lg" onClick={props.updateVote}>
<i className="fa fa-check-square-o"></i>
Vote for {props.title}
</button>
</div>
)
return (<Panel heading={heading} body={body}/>)
}
SingleBallotTicket.propTypes = {
title: PropTypes.string,
platform: PropTypes.string,
siteAddress: PropTypes.string,
candidates: PropTypes.array,
updateVote: PropTypes.func,
vote: PropTypes.array,
}
export default SingleBallotTicket
|
src/views/AdminView.js | mjasinski5/ContestReduxApp | import React from 'react';
import { Link } from 'react-router';
const AdminView = () => (
<div className='container text-center'>
<h1>Admin</h1>
<hr />
<Link to='/'>Back To Home View</Link>
</div>
);
export default AdminView;
|
examples/with-loadable-components/src/Body.js | jaredpalmer/react-production-starter | import React from 'react';
import loadable from 'loadable-components';
const BodyPart = loadable(() =>
import(/* webpackChunkName: "body-part" */ './BodyPart')
);
const Body = () => (
<div>
This is my Body <BodyPart />
</div>
);
export default Body;
|
src/svg-icons/action/view-week.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionViewWeek = (props) => (
<SvgIcon {...props}>
<path d="M6 5H3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zm14 0h-3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zm-7 0h-3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1z"/>
</SvgIcon>
);
ActionViewWeek = pure(ActionViewWeek);
ActionViewWeek.displayName = 'ActionViewWeek';
ActionViewWeek.muiName = 'SvgIcon';
export default ActionViewWeek;
|
src/svg-icons/hardware/keyboard-voice.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboardVoice = (props) => (
<SvgIcon {...props}>
<path d="M12 15c1.66 0 2.99-1.34 2.99-3L15 6c0-1.66-1.34-3-3-3S9 4.34 9 6v6c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 15 6.7 12H5c0 3.42 2.72 6.23 6 6.72V22h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"/>
</SvgIcon>
);
HardwareKeyboardVoice = pure(HardwareKeyboardVoice);
HardwareKeyboardVoice.displayName = 'HardwareKeyboardVoice';
HardwareKeyboardVoice.muiName = 'SvgIcon';
export default HardwareKeyboardVoice;
|
client/extensions/woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal/packages-step/add-item.js | Automattic/woocommerce-connect-client | /** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { localize } from 'i18n-calypso';
import { includes, size, some } from 'lodash';
/**
* Internal dependencies
*/
import Dialog from 'components/dialog';
import FormCheckbox from 'components/forms/form-checkbox';
import FormLabel from 'components/forms/form-label';
import getPackageDescriptions from './get-package-descriptions';
import FormSectionHeading from 'components/forms/form-section-heading';
import {
closeAddItem,
setAddedItem,
addItems,
} from 'woocommerce/woocommerce-services/state/shipping-label/actions';
import { getShippingLabel } from 'woocommerce/woocommerce-services/state/shipping-label/selectors';
import { getAllPackageDefinitions } from 'woocommerce/woocommerce-services/state/packages/selectors';
const AddItemDialog = props => {
const {
siteId,
orderId,
showAddItemDialog,
addedItems,
openedPackageId,
selected,
all,
translate,
} = props;
if ( ! showAddItemDialog ) {
return null;
}
const packageLabels = getPackageDescriptions( selected, all, true );
const getPackageNameElement = pckgId => {
return <span className="packages-step__dialog-package-name">{ packageLabels[ pckgId ] }</span>;
};
const renderCheckbox = ( pckgId, itemIdx, item ) => {
const itemLabel = packageLabels[ pckgId ]
? translate( '%(item)s from {{pckg/}}', {
args: { item: item.name },
components: { pckg: getPackageNameElement( pckgId ) },
} )
: item;
const onChange = event =>
props.setAddedItem( orderId, siteId, pckgId, itemIdx, event.target.checked );
return (
<FormLabel
key={ `${ pckgId }-${ itemIdx }` }
className="packages-step__dialog-package-option"
>
<FormCheckbox checked={ includes( addedItems[ pckgId ], itemIdx ) } onChange={ onChange } />
<span>{ itemLabel }</span>
</FormLabel>
);
};
const itemOptions = [];
Object.keys( selected ).forEach( pckgId => {
if ( pckgId === openedPackageId ) {
return;
}
let itemIdx = 0;
selected[ pckgId ].items.forEach( item => {
itemOptions.push( renderCheckbox( pckgId, itemIdx, item ) );
itemIdx++;
} );
} );
const onClose = () => props.closeAddItem( orderId, siteId );
const buttons = [
{ action: 'close', label: translate( 'Close' ), onClick: onClose },
{
action: 'add',
label: translate( 'Add' ),
isPrimary: true,
disabled: ! some( addedItems, size ),
onClick: () => props.addItems( orderId, siteId, openedPackageId ),
},
];
return (
<Dialog
isVisible={ showAddItemDialog }
isFullScreen={ false }
onClickOutside={ onClose }
onClose={ onClose }
buttons={ buttons }
additionalClassNames="wcc-root woocommerce packages-step__dialog"
>
<FormSectionHeading>{ translate( 'Add item' ) }</FormSectionHeading>
<div className="packages-step__dialog-body">
<p>
{ translate( 'Which items would you like to add to {{pckg/}}?', {
components: {
pckg: getPackageNameElement( openedPackageId ),
},
} ) }
</p>
{ itemOptions }
</div>
</Dialog>
);
};
AddItemDialog.propTypes = {
siteId: PropTypes.number.isRequired,
orderId: PropTypes.number.isRequired,
showAddItemDialog: PropTypes.bool.isRequired,
addedItems: PropTypes.object,
openedPackageId: PropTypes.string.isRequired,
selected: PropTypes.object.isRequired,
all: PropTypes.object.isRequired,
closeAddItem: PropTypes.func.isRequired,
setAddedItem: PropTypes.func.isRequired,
addItems: PropTypes.func.isRequired,
};
const mapStateToProps = ( state, { orderId, siteId } ) => {
const shippingLabel = getShippingLabel( state, orderId, siteId );
return {
showAddItemDialog: Boolean( shippingLabel.showAddItemDialog ),
addedItems: shippingLabel.addedItems,
openedPackageId: shippingLabel.openedPackageId,
selected: shippingLabel.form.packages.selected,
all: getAllPackageDefinitions( state, siteId ),
};
};
const mapDispatchToProps = dispatch => {
return bindActionCreators( { closeAddItem, setAddedItem, addItems }, dispatch );
};
export default connect(
mapStateToProps,
mapDispatchToProps
)( localize( AddItemDialog ) );
|
tests/components/icons/status/CriticalStatus-test.js | abzfarah/Pearson.NAPLAN.GnomeH | import {test} from 'tape';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import CriticalStatus from
'../../../src/components/icons/status/CriticalStatus';
import CSSClassnames from '../../../src/utils/CSSClassnames';
const STATUS_ICON = CSSClassnames.STATUS_ICON;
test('loads a critical status icon', (t) => {
t.plan(1);
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(CriticalStatus));
const criticalIcon = shallowRenderer.getRenderOutput();
if (criticalIcon.props.className.indexOf(`${STATUS_ICON}-critical`) > -1) {
t.pass('Icon has critical status class');
} else {
t.fail('Icon does not have critical status class');
}
});
test('loads a critical status icon with custom class applied', (t) => {
t.plan(1);
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(CriticalStatus, {
className:'custom-class'
}));
const criticalIcon = shallowRenderer.getRenderOutput();
if (criticalIcon.props.className.indexOf('custom-class') > -1) {
t.pass('Critical Icon has custom class applied');
} else {
t.fail('Critical Icon does not have custom class applied');
}
});
|
_src/src/pages/404.js | YannickDot/yannickdot.github.io | import React from 'react'
import { Link } from 'react-router'
import { Container } from 'react-responsive-grid'
import { prefixLink } from 'gatsby-helpers'
import { rhythm, scale } from 'utils/typography'
import { config } from 'config'
import MarkdownIt from 'markdown-it'
const md = new MarkdownIt()
const mdText = md.render(`
# 404
Sorry folks! Bad news, this route doesn't exist ...
But you should have a look at the [homepage](/), maybe you will find what you are looking for.
`)
const NotFound = () => <div dangerouslySetInnerHTML={{ __html: mdText }} />
NotFound.propTypes = {
children: React.PropTypes.any,
location: React.PropTypes.object,
route: React.PropTypes.object
}
export default NotFound
|
src/icons/AndroidFolder.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class AndroidFolder extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g id="Icon_10_">
<g>
<g>
<path d="M213.338,96H74.666C51.197,96,32,115.198,32,138.667v234.666C32,396.802,51.197,416,74.666,416h362.668
C460.803,416,480,396.802,480,373.333V186.667C480,163.198,460.803,144,437.334,144H256.006L213.338,96z"></path>
</g>
</g>
</g>
</g>;
} return <IconBase>
<g id="Icon_10_">
<g>
<g>
<path d="M213.338,96H74.666C51.197,96,32,115.198,32,138.667v234.666C32,396.802,51.197,416,74.666,416h362.668
C460.803,416,480,396.802,480,373.333V186.667C480,163.198,460.803,144,437.334,144H256.006L213.338,96z"></path>
</g>
</g>
</g>
</IconBase>;
}
};AndroidFolder.defaultProps = {bare: false} |
app/packs/src/components/managing_actions/ManagingModalSharing.js | ComPlat/chemotion_ELN | import React from 'react';
import PropTypes from 'prop-types';
import {Button, FormGroup, FormControl, ControlLabel} from 'react-bootstrap';
import Select from 'react-select';
import {debounce} from 'lodash';
import SharingShortcuts from '../sharing/SharingShortcuts';
import CollectionActions from '../actions/CollectionActions';
import UserActions from '../actions/UserActions';
import UIStore from '../stores/UIStore';
import UserStore from '../stores/UserStore';
import UsersFetcher from '../fetchers/UsersFetcher';
import MatrixCheck from '../common/MatrixCheck';
import klasses from '../../../../../config/klasses.json';
export default class ManagingModalSharing extends React.Component {
constructor(props) {
super(props);
// TODO update for new check/uncheck info
let {currentUser} = UserStore.getState();
this.state = {
currentUser: currentUser,
role:'Pick a sharing role',
permissionLevel: props.permissionLevel,
sampleDetailLevel: props.sampleDetailLevel,
reactionDetailLevel: props.reactionDetailLevel,
wellplateDetailLevel: props.wellplateDetailLevel,
screenDetailLevel: props.screenDetailLevel,
elementDetailLevel: props.elementDetailLevel,
selectedUsers: null,
}
this.onUserChange = this.onUserChange.bind(this);
this.handleSelectUser = this.handleSelectUser.bind(this);
this.handleSharing = this.handleSharing.bind(this);
this.promptTextCreator = this.promptTextCreator.bind(this);
// this.loadUserByName = debounce(this.loadUserByName.bind(this), 300);
this.loadUserByName = this.loadUserByName.bind(this);
}
componentDidMount() {
UserStore.listen(this.onUserChange);
UserActions.fetchCurrentUser();
}
componentWillUnmount() {
UserStore.unlisten(this.onUserChange);
}
onUserChange(state) {
this.setState({
currentUser: state.currentUser
})
}
isElementSelectionEmpty(element) {
return !element.checkedAll &&
element.checkedIds.size == 0 &&
element.uncheckedIds.size == 0;
}
isSelectionEmpty(uiState) {
let isSampleSelectionEmpty = this.isElementSelectionEmpty(uiState.sample);
let isReactionSelectionEmpty = this.isElementSelectionEmpty(uiState.reaction);
let isWellplateSelectionEmpty = this.isElementSelectionEmpty(uiState.wellplate);
let isScreenSelectionEmpty = this.isElementSelectionEmpty(uiState.screen);
let isElementSelectionEmpty = false;
const currentUser = (UserStore.getState() && UserStore.getState().currentUser) || {};
if (MatrixCheck(currentUser.matrix, 'genericElement')) {
// eslint-disable-next-line no-unused-expressions
klasses && klasses.forEach((klass) => {
isElementSelectionEmpty = isElementSelectionEmpty && this.isElementSelectionEmpty(uiState[`${klass}`]);
});
}
return isSampleSelectionEmpty && isReactionSelectionEmpty &&
isWellplateSelectionEmpty && isScreenSelectionEmpty &&
isElementSelectionEmpty;
}
filterParamsWholeCollection(uiState) {
let collectionId = uiState.currentCollection.id;
let filterParams = {
sample: {
all: true,
included_ids: [],
excluded_ids: [],
collection_id: collectionId
},
reaction: {
all: true,
included_ids: [],
excluded_ids: [],
collection_id: collectionId
},
wellplate: {
all: true,
included_ids: [],
excluded_ids: [],
collection_id: collectionId
},
screen: {
all: true,
included_ids: [],
excluded_ids: [],
collection_id: collectionId
},
research_plan: {
all: true,
included_ids: [],
excluded_ids: [],
collection_id: collectionId
},
currentSearchSelection: uiState.currentSearchSelection
};
klasses && klasses.forEach((klass) => {
filterParams[`${klass}`] = {
all: true,
included_ids: [],
excluded_ids: [],
collection_id: collectionId
};
});
console.log(filterParams);
return filterParams;
}
filterParamsFromUIState(uiState) {
let collectionId = uiState.currentCollection.id;
let filterParams = {
sample: {
all: uiState.sample.checkedAll,
included_ids: uiState.sample.checkedIds,
excluded_ids: uiState.sample.uncheckedIds,
collection_id: collectionId
},
reaction: {
all: uiState.reaction.checkedAll,
included_ids: uiState.reaction.checkedIds,
excluded_ids: uiState.reaction.uncheckedIds,
collection_id: collectionId
},
wellplate: {
all: uiState.wellplate.checkedAll,
included_ids: uiState.wellplate.checkedIds,
excluded_ids: uiState.wellplate.uncheckedIds,
collection_id: collectionId
},
screen: {
all: uiState.screen.checkedAll,
included_ids: uiState.screen.checkedIds,
excluded_ids: uiState.screen.uncheckedIds,
collection_id: collectionId
},
research_plan: {
all: uiState.research_plan.checkedAll,
included_ids: uiState.research_plan.checkedIds,
excluded_ids: uiState.research_plan.uncheckedIds,
collection_id: collectionId
},
currentSearchSelection: uiState.currentSearchSelection
};
klasses && klasses.forEach((klass) => {
filterParams[`${klass}`] = {
all: uiState[`${klass}`].checkedAll,
included_ids: uiState[`${klass}`].checkedIds,
excluded_ids: uiState[`${klass}`].uncheckedIds,
collection_id: collectionId
};
});
console.log(filterParams);
return filterParams;
}
handleSharing() {
const {
permissionLevel, sampleDetailLevel, reactionDetailLevel,
wellplateDetailLevel, screenDetailLevel, elementDetailLevel
} = this.state;
const params = {
id: this.props.collectionId,
collection_attributes: {
permission_level: permissionLevel,
sample_detail_level: sampleDetailLevel,
reaction_detail_level: reactionDetailLevel,
wellplate_detail_level: wellplateDetailLevel,
screen_detail_level: screenDetailLevel,
element_detail_level: elementDetailLevel
},
};
if (this.props.collAction === "Create") {
const userIds = this.state.selectedUsers;
const uiState = UIStore.getState();
const currentCollection = uiState.currentCollection;
const filterParams =
this.isSelectionEmpty(uiState)
? this.filterParamsWholeCollection(uiState)
: this.filterParamsFromUIState(uiState);
const fullParams = {
...params,
elements_filter: filterParams,
user_ids: userIds,
currentCollection
};
CollectionActions.createSharedCollections(fullParams);
}
if (this.props.collAction === 'Update') { CollectionActions.updateSharedCollection(params); }
if (this.props.collAction === 'EditSync') { CollectionActions.editSync(params); }
if (this.props.collAction === 'CreateSync') {
const userIds = this.state.selectedUsers;
const fullParams = {
...params,
user_ids: userIds,
};
CollectionActions.createSync(fullParams);
}
this.props.onHide();
}
handleShortcutChange(e) {
let val = e.target.value
let permAndDetLevs = {}
switch(val) {
case 'user':
permAndDetLevs = SharingShortcuts.user();
break;
case 'partner':
permAndDetLevs = SharingShortcuts.partner();
break;
case 'collaborator':
permAndDetLevs = SharingShortcuts.collaborator();
break;
case 'reviewer':
permAndDetLevs = SharingShortcuts.reviewer();
break;
case 'supervisor':
permAndDetLevs = SharingShortcuts.supervisor();
break;
}
this.setState({...permAndDetLevs,role:val});
}
handlePLChange(e) {
let val = e.target.value
this.setState({
role:'Pick a sharing role',
permissionLevel: val
});
}
handleDLChange(e,elementType){
let val = e.target.value
let state = {}
state[elementType+'DetailLevel'] = val
state.role = 'Pick a sharing role'
this.setState(state)
}
handleSelectUser(val) {
if (val) {
this.setState({selectedUsers: val})
}
}
loadUserByName(input) {
let {selectedUsers} = this.state;
if (!input) {
return Promise.resolve({ options: [] });
}
return UsersFetcher.fetchUsersByName(input)
.then((res) => {
let usersEntries = res.users.filter(u => u.id != this.state.currentUser.id)
.map(u => {
return {
value: u.id,
name: u.name,
label: u.name + " (" + u.abb + ")"
}
});
return {options: usersEntries};
}).catch((errorMessage) => {
console.log(errorMessage);
});
}
promptTextCreator(label) {
return ("Share with \"" + label + "\"");
}
selectUsers() {
let style = this.props.selectUsers ? {} : {display: 'none'};
let {selectedUsers} = this.state;
return(
<div style={style}>
<ControlLabel>Select Users to share with</ControlLabel>
<Select.AsyncCreatable id="share-users-select" multi={true} isLoading={true}
backspaceRemoves={true} value={selectedUsers}
valueKey="value" labelKey="label" matchProp="name"
promptTextCreator={this.promptTextCreator}
loadOptions={this.loadUserByName}
onChange={this.handleSelectUser}
/>
</div>
)
}
render() {
const displayWarning = (this.state.permissionLevel || '') === '5' ? 'inline-block' : 'none';
return (
<div>
<FormGroup controlId="shortcutSelect">
<ControlLabel>Role</ControlLabel>
<FormControl componentClass="select"
placeholder="Pick a sharing role (optional)"
value={this.state.role || ''}
onChange={(e) => this.handleShortcutChange(e)}>
<option value='Pick a sharing role'>Pick a sharing role (optional)</option>
<option value='user'>User</option>
<option value='partner'>Partner</option>
<option value='collaborator'>Collaborator</option>
<option value='reviewer'>Reviewer</option>
<option value='supervisor'>Supervisor</option>
</FormControl>
</FormGroup>
<FormGroup controlId="permissionLevelSelect" id="permissionLevelSelect">
<ControlLabel>Permission level</ControlLabel>
<FormControl componentClass="select"
onChange={(e) => this.handlePLChange(e)}
value={this.state.permissionLevel || ''}>
<option value='0'>Read</option>
<option value='1'>Write</option>
<option value='2'>Share</option>
<option value='3'>Delete</option>
<option value='4'>Import Elements</option>
<option value='5'>Pass ownership</option>
</FormControl>
<div style={{
color: '#d9534f', fontSize: '12px', paddingLeft: '8px', paddingTop: '4px', display: displayWarning
}}
>
<i className="fa fa-exclamation-circle" aria-hidden="true" /> Transfering ownership applies for all sub collections.
</div>
</FormGroup>
<FormGroup controlId="sampleDetailLevelSelect">
<ControlLabel>Sample detail level</ControlLabel>
<FormControl componentClass="select"
onChange={(e) => this.handleDLChange(e,'sample')}
value={this.state.sampleDetailLevel || ''}>
<option value='0'>Molecular mass of the compound, external label</option>
<option value='1'>Molecule, structure</option>
<option value='2'>Analysis Result + Description</option>
<option value='3'>Analysis Datasets</option>
<option value='10'>Everything</option>
</FormControl>
</FormGroup>
<FormGroup controlId="reactionDetailLevelSelect">
<ControlLabel>Reaction detail level</ControlLabel>
<FormControl componentClass="select"
onChange={(e) => this.handleDLChange(e,'reaction')}
value={this.state.reactionDetailLevel || ''}>
<option value='0'>Observation, description, calculation</option>
<option value='10'>Everything</option>
</FormControl>
</FormGroup>
<FormGroup controlId="wellplateDetailLevelSelect">
<ControlLabel>Wellplate detail level</ControlLabel>
<FormControl componentClass="select"
onChange={(e) => this.handleDLChange(e,'wellplate')}
value={this.state.wellplateDetailLevel || ''}>
<option value='0'>Wells (Positions)</option>
<option value='1'>Readout</option>
<option value='10'>Everything</option>
</FormControl>
</FormGroup>
<FormGroup controlId="screenDetailLevelSelect">
<ControlLabel>Screen detail level</ControlLabel>
<FormControl componentClass="select"
onChange={(e) => this.handleDLChange(e,'screen')}
value={this.state.screenDetailLevel || ''}>
<option value='0'>Name, description, condition, requirements</option>
<option value='10'>Everything</option>
</FormControl>
</FormGroup>
<FormGroup controlId="screenDetailLevelSelect">
<ControlLabel>Element detail level</ControlLabel>
<FormControl componentClass="select"
onChange={(e) => this.handleDLChange(e,'element')}
value={this.state.elementDetailLevel || ''}>
<option value='10'>Everything</option>
</FormControl>
</FormGroup>
{this.selectUsers()}
<br/>
<Button id="create-sync-shared-col-btn" bsStyle="warning" onClick={this.handleSharing}>{this.props.collAction} Shared Collection</Button>
</div>
)
}
}
ManagingModalSharing.propTypes = {
collectionId: PropTypes.number,
collAction: PropTypes.string,
selectUsers: PropTypes.bool,
permissionLevel: PropTypes.number,
sampleDetailLevel: PropTypes.number,
reactionDetailLevel: PropTypes.number,
wellplateDetailLevel: PropTypes.number,
screenDetailLevel: PropTypes.number,
elementDetailLevel: PropTypes.number,
onHide: PropTypes.func.isRequired,
listSharedCollections: PropTypes.bool
};
ManagingModalSharing.defaultProps = {
collectionId: null,
collAction: "Create",
selectUsers: true,
permissionLevel: 0,
sampleDetailLevel: 0,
reactionDetailLevel: 0,
wellplateDetailLevel: 0,
screenDetailLevel: 0,
elementDetailLevel: 10
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.