path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
app/demos/customView.js
|
asantebuil/room-reservation
|
import React from 'react';
import BigCalendar from '../../src/index';
import events from '../events';
import { navigate } from 'react-big-calendar/utils/constants';
import Week from 'react-big-calendar/Week';
import dates from 'react-big-calendar/utils/dates';
import localizer from 'react-big-calendar/localizer';
import TimeGrid from 'react-big-calendar/TimeGrid';
class MyWeek extends Week {
render() {
let { date } = this.props;
let { start, end } = MyWeek.range(date, this.props);
return (
<TimeGrid {...this.props} start={start} end={end} eventOffset={15} />
);
}
}
MyWeek.navigate = (date, action)=>{
switch (action){
case navigate.PREVIOUS:
return dates.add(date, -1, 'week');
case navigate.NEXT:
return dates.add(date, 1, 'week')
default:
return date;
}
}
MyWeek.range = (date, { culture }) => {
let firstOfWeek = localizer.startOfWeek(culture);
let start = dates.startOf(date, 'week', firstOfWeek);
let end = dates.endOf(date, 'week', firstOfWeek);
if (firstOfWeek === 1) {
end = dates.subtract(end, 2, 'day');
} else {
start = dates.add(start, 1, 'day');
end = dates.subtract(end, 1, 'day');
}
return { start, end };
}
let CustomView = React.createClass({
render(){
return (
<div>
<BigCalendar
events={events}
defaultDate={new Date(2015, 3, 1)}
views={{ month: true, week: MyWeek }}
test="io"
/>
</div>
)
}
})
export default CustomView;
|
docs/src/sections/FormInputGroupSection.js
|
dozoisch/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 FormInputGroupSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="forms-input-groups">Input groups</Anchor> <small>InputGroup, InputGroup.Addon, InputGroup.Button</small>
</h2>
<h3><Anchor id="forms-input-addons">Input add-ons</Anchor></h3>
<p>Wrap your form control in an <code>{'<InputGroup>'}</code>, then use for normal add-ons and for button add-ons. Exotic configurations may require CSS on your side.</p>
<ReactPlayground codeText={Samples.FormInputAddons} />
<h3><Anchor id="forms-input-sizes">Input sizes</Anchor></h3>
<p>Use <code>bsSize</code> on <code>{'<FormGroup>'}</code> or <code>{'<InputGroup>'}</code> to change the size of inputs. It also works with add-ons and most other options.</p>
<ReactPlayground codeText={Samples.FormInputSizes} />
<h3><Anchor id="forms-input-groups-props">Props</Anchor></h3>
<h4><Anchor id="forms-props-input-group">InputGroup</Anchor></h4>
<PropTable component="InputGroup" />
<h4><Anchor id="forms-props-input-group-addon">InputGroup.Addon</Anchor></h4>
<PropTable component="InputGroupAddon" />
<h4><Anchor id="forms-props-input-group-button">InputGroup.Button</Anchor></h4>
<PropTable component="InputGroupButton" />
</div>
);
}
|
app/index.js
|
pratyk/react-signup-zxcvbn
|
import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
render(
<Router routes={routes} history={browserHistory}/>,
document.getElementById('app')
);
|
src/native/components/Header.js
|
TeodorKolev/Help
|
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import { Text, H1 } from 'native-base';
import Spacer from './Spacer';
const Header = ({ title, content }) => (
<View>
<Spacer size={25} />
<H1>{title}</H1>
{!!content &&
<View>
<Spacer size={10} />
<Text>{content}</Text>
</View>
}
<Spacer size={25} />
</View>
);
Header.propTypes = {
title: PropTypes.string,
content: PropTypes.string,
};
Header.defaultProps = {
title: 'Missing title',
content: '',
};
export default Header;
|
lib/editor/components/question_editors/parts/ValueEditorPart.js
|
jirokun/survey-designer-js
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import cuid from 'cuid';
import S from 'string';
import { List } from 'immutable';
import NumericInput from 'react-numeric-input';
import ExSelect from './ExSelect';
/**
* 直接値を入力するか、再掲値を選択するかを選ぶことのできるエディタ
*/
class ValueEditorPart extends Component {
static makeReferenceValue(od) {
return `{{${od.getId()}.answer}}`;
}
constructor(props) {
super(props);
this.cuid = cuid();
const { value } = props;
this.state = {
mode: S(value).isEmpty() || S(value).isNumeric() ? 'fixedValue' : 'answerValue',
};
}
handleChangeMode(mode) {
this.props.onChange('');
this.setState({ mode });
}
handleChangeQuestionAttribute(value) {
this.props.onChange(value);
}
createValueElement() {
const { node, options, survey, value } = this.props;
if (this.state.mode === 'fixedValue') {
if (options.isShowDetail()) {
return S(value).isEmpty() ? <span className="alert-value">未設定</span> : <span className="fixed-value">{value}</span>;
}
return (
<NumericInput
className="form-control fixed-value-input"
value={value}
placeholder="半角数字で入力"
onChange={(numValue, strValue) => this.handleChangeQuestionAttribute(strValue)}
/>
);
}
const keyBase = this.cuid;
let optionList = List().push(<option key={`${keyBase}-empty`} value="" data-error />);
const precedingOutputDefinitions = survey.findPrecedingOutputDefinition(node.getId(), true);
if (value !== '' && precedingOutputDefinitions.findIndex(od => ValueEditorPart.makeReferenceValue(od) === value) === -1) {
optionList = optionList.push(<option key={`${keyBase}-deleted`} value={value} data-error>エラー 不正な参照です</option>);
}
optionList = optionList.concat(
precedingOutputDefinitions.filter(od => od.getOutputType() === 'number')
.map(od => <option key={`${keyBase}-${od.getId()}`} value={ValueEditorPart.makeReferenceValue(od)}>{od.getLabelWithOutputNo()}</option>)
.toList());
return (
<ExSelect
className="form-control reference-select"
value={value}
onChange={e => this.handleChangeQuestionAttribute(e.target.value)}
detailMode={options.isShowDetail()}
>
{optionList}
</ExSelect>
);
}
render() {
const { options, style } = this.props;
return (
<div className="input-group value-editor-part" style={style}>
<ExSelect
className="form-control value-type"
value={this.state.mode}
onChange={e => this.handleChangeMode(e.target.value)}
detailMode={options.isShowDetail()}
>
<option value="fixedValue">固定値</option>
<option value="answerValue">回答値</option>
</ExSelect>
{this.createValueElement()}
</div>
);
}
}
const stateToProps = state => ({
survey: state.getSurvey(),
runtime: state.getRuntime(),
options: state.getOptions(),
});
export default connect(
stateToProps,
)(ValueEditorPart);
|
app/components/ToggleOption/index.js
|
MaleSharker/Qingyan
|
/**
*
* ToggleOption
*
*/
import React from 'react';
import { injectIntl, intlShape } from 'react-intl';
const ToggleOption = ({ value, message, intl }) => (
<option value={value}>
{message ? intl.formatMessage(message) : value}
</option>
);
ToggleOption.propTypes = {
value: React.PropTypes.string.isRequired,
message: React.PropTypes.object,
intl: intlShape.isRequired,
};
export default injectIntl(ToggleOption);
|
techCurriculum/ui/solutions/4.2/src/components/CardForm.js
|
tadas412/EngineeringEssentials
|
/**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
import TextInput from './TextInput.js'
class CardForm extends React.Component {
render() {
return (
<form className='card-form'>
<h2>Add a Card</h2>
<TextInput name='username' label='Username'/>
<TextInput name='message' label='Message'/>
</form>
);
}
}
export default CardForm;
|
lib/Navigation/Tabs/tabOne/views/TabOneNavigation.js
|
Ezeebube5/Nairasense
|
// React
import React from 'react';
// Redux
import { connect } from 'react-redux';
// Icon
import Icon from 'react-native-vector-icons/FontAwesome';
// Navigation
import { addNavigationHelpers } from 'react-navigation';
import { NavigatorTabOne } from '../navigationConfiguration';
class TabOneNavigation extends React.Component {
static navigationOptions = {
drawerLabel: 'Home',
drawerIcon: ({ tintColor }) => <Icon size={20} name={'home'} color={tintColor} />
}
render() {
const { navigationState, dispatch } = this.props;
return (
<NavigatorTabOne
navigation={
addNavigationHelpers({
dispatch,
state: navigationState
})
}
/>
);
}
}
const mapStateToProps = (state) => ({
navigationState: state.tabOne
});
export default connect(mapStateToProps)(TabOneNavigation);
|
demos/badges/index.js
|
isogon/styled-mdl-website
|
import React from 'react'
import DemoPage from '../../components/DemoPage'
import numberOnIcon from './demos/numberOnIcon'
import iconOnIcon from './demos/iconOnIcon'
import number from './demos/number'
import icon from './demos/icon'
import button from './demos/button'
const title = 'Badges'
const subtitle = 'Small status descriptors for UI elements.'
const demos = [
{ title: 'Badges with icons', demos: [numberOnIcon, iconOnIcon] },
{ title: 'Badges with text', demos: [number, icon] },
{ title: 'Badges with buttons', demos: [button] },
]
const usage = {
'<Badge>': {
sourceLink:
'https://github.com/isogon/styled-mdl/blob/master/src/badges/Badge.js',
props: [
{
name: 'text',
type: 'node',
default: 'undefined',
description:
'This is what will render inside the badge, can be any valid react node, but it will look strange if this is more than a few characters or a single icon',
},
{
name: 'forButton',
type: 'boolean',
default: 'false',
description:
'Set this to true if you are using the badge with a button',
},
{
name: 'overlap',
type: 'boolean',
default: 'false',
description:
'Slighly offsets the badge to the right. Set this to true if you are using the badge on top of an icon',
},
],
},
}
export default () => (
<DemoPage
title={title}
subtitle={subtitle}
demoGroups={demos}
usage={usage}
/>
)
|
jenkins-design-language/src/js/components/material-ui/svg-icons/device/battery-charging-90.js
|
alvarolobato/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const DeviceBatteryCharging90 = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h5.47L13 7v1h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L12.47 8H7v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8h-4v4.5z"/>
</SvgIcon>
);
DeviceBatteryCharging90.displayName = 'DeviceBatteryCharging90';
DeviceBatteryCharging90.muiName = 'SvgIcon';
export default DeviceBatteryCharging90;
|
src/routes/chart/Container.js
|
zhouchao0924/SLCOPY
|
import React from 'react'
import PropTypes from 'prop-types'
import styles from './Container.less'
import { ResponsiveContainer } from 'recharts'
const Container = ({ children, ratio = 5 / 2, minHeight = 250, maxHeight = 350 }) => <div className={styles.container} style={{ minHeight, maxHeight }}>
<div style={{ marginTop: `${100 / ratio}%` || '100%' }}></div>
<div className={styles.content} style={{ minHeight, maxHeight }}>
<ResponsiveContainer>
{children}
</ResponsiveContainer>
</div>
</div>
Container.propTypes = {
children: PropTypes.element.isRequired,
ratio: PropTypes.number,
minHeight: PropTypes.number,
maxHeight: PropTypes.number,
}
export default Container
|
app/components/ProgressBar/index.js
|
wenpengfei/react-boilerplate
|
import React from 'react'
import ProgressBar from './ProgressBar'
function withProgressBar(WrappedComponent) {
class AppWithProgressBar extends React.Component {
constructor(props) {
super(props)
this.state = {
progress: -1,
loadedRoutes: props.location && [props.location.pathname],
}
this.updateProgress = this.updateProgress.bind(this)
}
componentWillMount() {
// Store a reference to the listener.
/* istanbul ignore next */
this.unsubscribeHistory = this.props.router && this.props.router.listenBefore((location) => {
// Do not show progress bar for already loaded routes.
if (this.state.loadedRoutes.indexOf(location.pathname) === -1) {
this.updateProgress(0)
}
})
}
componentWillUpdate(newProps, newState) {
const { loadedRoutes, progress } = this.state
const { pathname } = newProps.location
// Complete progress when route changes. But prevent state update while re-rendering.
if (loadedRoutes.indexOf(pathname) === -1 && progress !== -1 && newState.progress < 100) {
this.updateProgress(100)
this.setState({
loadedRoutes: loadedRoutes.concat([pathname]),
})
}
}
componentWillUnmount() {
// Unset unsubscribeHistory since it won't be garbage-collected.
this.unsubscribeHistory = undefined
}
updateProgress(progress) {
this.setState({ progress })
}
render() {
return (
<div>
<ProgressBar percent={this.state.progress} updateProgress={this.updateProgress} />
<WrappedComponent {...this.props} />
</div>
)
}
}
AppWithProgressBar.propTypes = {
location: React.PropTypes.object,
router: React.PropTypes.object,
}
return AppWithProgressBar
}
export default withProgressBar
|
docs/app/Examples/elements/Image/Usage/index.js
|
clemensw/stardust
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const ImageUsageExamples = () => (
<ExampleSection title='Usage'>
<ComponentExample
title='Children'
description='An image can render children.'
examplePath='elements/Image/Usage/ImageExampleChildren'
/>
</ExampleSection>
)
export default ImageUsageExamples
|
examples/with-mobx/pages/other.js
|
nikvm/next.js
|
import React from 'react'
import { Provider } from 'mobx-react'
import { initStore } from '../store'
import Page from '../components/Page'
export default class Counter extends React.Component {
static getInitialProps ({ req }) {
const isServer = !!req
const store = initStore(isServer)
return { lastUpdate: store.lastUpdate, isServer }
}
constructor (props) {
super(props)
this.store = initStore(props.isServer, props.lastUpdate)
}
render () {
return (
<Provider store={this.store}>
<Page title='Other Page' linkTo='/' />
</Provider>
)
}
}
|
frontend/src/idPortal/users/newUser/newUserForm.js
|
unicef/un-partner-portal
|
import R from 'ramda';
import React from 'react';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import PropTypes from 'prop-types';
import TextFieldForm from '../../../components/forms/textFieldForm';
import GridColumn from '../../../components/common/grid/gridColumn';
import { email } from '../../../helpers/validation';
import RoleField from './roleField';
import { selectNormalizedOffices } from '../../../store';
import { AGENCY_ROLES } from '../../../helpers/permissions';
const messages = {
formName: 'newUserForm',
selectPartners: 'Select Partners',
selectionCriteria: 'Selection Criteria',
firstName: 'Full name',
email: 'E-mail',
};
const NewUserForm = (props) => {
const { handleSubmit, id } = props;
return (
<form onSubmit={handleSubmit}>
<div style={{ width: '40vw' }}>
<GridColumn>
<TextFieldForm
label={messages.firstName}
fieldName="fullname"
readOnly={!R.isNil(id)}
/>
<TextFieldForm
label={messages.email}
fieldName="email"
validation={[email]}
readOnly={!R.isNil(id)}
textFieldProps={{
"type": "email"
}}
/>
<RoleField id={id} formName="newUserForm" />
</GridColumn>
</div>
</form >
);
};
NewUserForm.propTypes = {
/**
* callback for form submit
*/
handleSubmit: PropTypes.func.isRequired,
id: PropTypes.number,
};
const formNewUser = reduxForm({
form: 'newUserForm',
})(NewUserForm);
const mapStateToProps = (state, ownProps) => {
let initialValues;
const offices = selectNormalizedOffices(state);
if (ownProps.id) {
const users = state.idPortalUsersList.users;
const user = R.find(R.propEq('id', ownProps.id))(users);
const fullname = user.fullname;
const email = user.email;
const office_memberships = R.map(item => R.assoc('office_id', item.office.id,
R.assoc('role', item.role, R.assoc('readOnly', state.session.officeId === item.office.id || state.session.officeRole === AGENCY_ROLES.HQ_EDITOR, null)))
, user.office_memberships);
initialValues = { fullname, email, office_memberships };
} else if (offices.length === 1) {
initialValues = { office_memberships: [{ office_id: offices[0].value }] };
}
return {
initialValues,
};
};
export default connect(
mapStateToProps,
)(formNewUser);
|
src/svg-icons/image/gradient.js
|
manchesergit/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageGradient = (props) => (
<SvgIcon {...props}>
<path d="M11 9h2v2h-2zm-2 2h2v2H9zm4 0h2v2h-2zm2-2h2v2h-2zM7 9h2v2H7zm12-6H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 18H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm2-7h-2v2h2v2h-2v-2h-2v2h-2v-2h-2v2H9v-2H7v2H5v-2h2v-2H5V5h14v6z"/>
</SvgIcon>
);
ImageGradient = pure(ImageGradient);
ImageGradient.displayName = 'ImageGradient';
ImageGradient.muiName = 'SvgIcon';
export default ImageGradient;
|
Realization/frontend/czechidm-core/src/components/advanced/IdentityContractInfo/IdentityContractInfo.js
|
bcvsolutions/CzechIdMng
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import * as Utils from '../../../utils';
import * as Basic from '../../basic';
import { IdentityContractManager } from '../../../redux';
import AbstractEntityInfo from '../EntityInfo/AbstractEntityInfo';
import DateValue from '../DateValue/DateValue';
import EntityInfo from '../EntityInfo/EntityInfo';
const manager = new IdentityContractManager();
/**
* Component for rendering nice identifier for identity contracts, similar function as roleInfo.
*
* @author Ondrej Kopr
* @author Radek Tomiška
*/
export class IdentityContractInfo extends AbstractEntityInfo {
getManager() {
return manager;
}
getNiceLabel() {
const _entity = this.getEntity();
const { showIdentity } = this.props;
//
return this.getManager().getNiceLabel(_entity, showIdentity);
}
/**
* Returns entity icon (null by default - icon will not be rendered)
*
* @param {object} entity
*/
getEntityIcon(entity) {
if (entity && entity.main) {
return 'component:main-contract';
}
return 'component:contract';
}
showLink() {
if (!super.showLink()) {
return false;
}
const { _permissions } = this.props;
if (!this.getManager().canRead(this.getEntity(), _permissions)) {
return false;
}
return true;
}
/**
* Returns true, when disabled decorator has to be used
*
* @param {object} entity
* @return {bool}
*/
isDisabled(entity) {
return !Utils.Entity.isValid(entity);
}
/**
* Get link to detail (`url`).
*
* @return {string}
*/
getLink() {
const { entityIdentifier } = this.props;
const _entity = this.getEntity();
//
if (!_entity._embedded || !_entity._embedded.identity) {
return null;
}
const identityIdentifier = encodeURIComponent(_entity._embedded.identity.username);
return `/identity/${ identityIdentifier }/identity-contract/${ entityIdentifier }/detail`;
}
/**
* Returns popovers title
*
* @param {object} entity
*/
getPopoverTitle() {
return this.i18n('entity.IdentityContract._type');
}
getTableChildren() {
// component are used in #getPopoverContent => skip default column resolving
return [
<Basic.Column property="label"/>,
<Basic.Column property="value"/>
];
}
/**
* Returns popover info content
*
* @param {array} table data
*/
getPopoverContent(entity) {
return [
{
label: this.i18n('entity.Identity._type'),
value: (
<EntityInfo
entityType="identity"
entity={ entity._embedded ? entity._embedded.identity : null }
entityIdentifier={ entity.identity }
face="link" />
)
},
{
label: this.i18n('entity.IdentityContract.position'),
value: entity.position
},
{
label: this.i18n('entity.IdentityContract.workPosition'),
value: (
<EntityInfo
entityType="treeNode"
entity={ entity._embedded ? entity._embedded.workPosition : null }
entityIdentifier={ entity.workPosition }
face="link" />
)
},
{
label: this.i18n('entity.TreeType._type'),
value: !entity._embedded || !entity._embedded.workPosition ||
<EntityInfo
entityType="treeType"
entity={ entity._embedded.workPosition._embedded.treeType }
entityIdentifier={ entity._embedded.workPosition.treeType }
face="link" />
},
{
label: this.i18n('entity.validFrom'),
value: (<DateValue value={ entity.validFrom }/>)
},
{
label: this.i18n('entity.validTill'),
value: (<DateValue value={ entity.validTill }/>)
}
];
}
}
IdentityContractInfo.propTypes = {
...AbstractEntityInfo.propTypes,
/**
* Selected entity - has higher priority
*/
entity: PropTypes.object,
/**
* Selected entity's id - entity will be loaded automatically
*/
entityIdentifier: PropTypes.string,
/**
* Show contract's identity
*/
showIdentity: PropTypes.bool,
//
_showLoading: PropTypes.bool,
_permissions: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.arrayOf(PropTypes.string)
])
};
IdentityContractInfo.defaultProps = {
...AbstractEntityInfo.defaultProps,
entity: null,
face: 'link',
_showLoading: true,
showIdentity: true,
};
function select(state, component) {
const entity = manager.getEntity(state, component.entityIdentifier);
return {
_entity: entity,
_showLoading: manager.isShowLoading(state, null, component.entityIdentifier),
_permissions: manager.getPermissions(state, null, component.entityIdentifier)
};
}
export default connect(select)(IdentityContractInfo);
|
app/containers/FooterContainer/index.js
|
josueorozco/parlay
|
import React from 'react';
import { connect } from 'react-redux';
import Footer from '../../components/Footer';
/*
|--------------------------------------------------------------------------
| FooterContainer
|--------------------------------------------------------------------------
|
| Container index.js
|
*/
export class FooterContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<Footer />
);
}
}
/**
* mapDispatchToProps
*
* @param dispatch
* @returns {object}
*/
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapDispatchToProps)(FooterContainer);
|
packages/mineral-ui-icons/src/IconCallMade.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconCallMade(props: IconProps) {
const iconProps = {
rtl: true,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M9 5v2h6.59L4 18.59 5.41 20 17 8.41V15h2V5z"/>
</g>
</Icon>
);
}
IconCallMade.displayName = 'IconCallMade';
IconCallMade.category = 'communication';
|
tests/lib/schema.spec.js
|
LucasBassetti/react-simple-chatbot
|
import React from 'react';
import { describe, it } from 'mocha';
import { expect } from 'chai';
import schema from '../../lib/schemas/schema';
import { stringify } from 'flatted';
describe('schema', () => {
it('should throw a invalid step error', () => {
const step = { test: 'test' };
expect(() => {
schema.parse(step);
}).to.throw(Error, `The step ${stringify(step)} is invalid`);
});
it('should throw a key required error', () => {
const step = { message: 'test' };
expect(() => {
schema.parse(step);
}).to.throw(Error, `Key 'id' is required in step ${stringify(step)}`);
});
it('should throw a key type error', () => {
const step = { id: () => { }, options: [] };
expect(() => {
schema.parse(step);
}).to.throw(Error, 'The type of \'id\' value must be string or number instead of function');
});
it('should delete a invalid key', () => {
const step = schema.parse({
id: '1',
message: 'test',
test: 'test',
});
const resultStep = stringify({ id: '1', message: 'test' });
expect(stringify(step)).to.be.equal(resultStep);
});
it('should not throw error to a user step', () => {
const step = { id: '1', user: true, end: true };
expect(() => {
schema.parse(step);
}).to.not.throw();
});
it('should not throw error to a component step', () => {
const step = { id: '1', component: <div />, end: true };
expect(() => {
schema.parse(step);
}).to.not.throw();
});
it('should not throw error to a update step', () => {
const step = { id: '1', update: '2', trigger: '3' };
expect(() => {
schema.parse(step);
}).to.not.throw();
});
it('should throw error of inexistent step id', () => {
const steps = {
1: {
id: '1',
message: 'Test',
trigger: '2',
},
};
expect(() => {
schema.checkInvalidIds(steps);
}).to.throw();
});
it('should throw error of inexistent step id in option', () => {
const steps = {
1: {
id: '1',
options: [
{ label: 'test', value: 'test', trigger: '2' },
],
},
};
expect(() => {
schema.checkInvalidIds(steps);
}).to.throw();
});
it('should not throw error of inexistent step id', () => {
const steps = {
1: {
id: '1',
message: 'Test',
trigger: '2',
},
2: {
id: '2',
message: 'End',
end: true,
},
};
expect(() => {
schema.checkInvalidIds(steps);
}).to.not.throw();
});
it('should not throw error with metadata', () => {
const step = { id: '1', message: 'Test', metadata: { data: 'test' } };
expect(() => {
schema.parse(step);
}).to.not.throw();
const resultStep = schema.parse(step);
expect(resultStep).to.be.equal(step);
});
it('should not throw error with inputAttributes', () => {
const step = { id: '1', message: 'Test', inputAttributes: { autoComplete: 'firstname' } };
expect(() => {
schema.parse(step);
}).to.not.throw();
const resultStep = schema.parse(step);
expect(resultStep).to.be.equal(step);
});
});
|
node_modules/react-bootstrap/es/BreadcrumbItem.js
|
Crisa221/Lista-Giocatori
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import SafeAnchor from './SafeAnchor';
var propTypes = {
/**
* If set to true, renders `span` instead of `a`
*/
active: React.PropTypes.bool,
/**
* `href` attribute for the inner `a` element
*/
href: React.PropTypes.string,
/**
* `title` attribute for the inner `a` element
*/
title: React.PropTypes.node,
/**
* `target` attribute for the inner `a` element
*/
target: React.PropTypes.string
};
var defaultProps = {
active: false
};
var BreadcrumbItem = function (_React$Component) {
_inherits(BreadcrumbItem, _React$Component);
function BreadcrumbItem() {
_classCallCheck(this, BreadcrumbItem);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
BreadcrumbItem.prototype.render = function render() {
var _props = this.props;
var active = _props.active;
var href = _props.href;
var title = _props.title;
var target = _props.target;
var className = _props.className;
var props = _objectWithoutProperties(_props, ['active', 'href', 'title', 'target', 'className']);
// Don't try to render these props on non-active <span>.
var linkProps = { href: href, title: title, target: target };
return React.createElement(
'li',
{ className: classNames(className, { active: active }) },
active ? React.createElement('span', props) : React.createElement(SafeAnchor, _extends({}, props, linkProps))
);
};
return BreadcrumbItem;
}(React.Component);
BreadcrumbItem.propTypes = propTypes;
BreadcrumbItem.defaultProps = defaultProps;
export default BreadcrumbItem;
|
test/ListGroupItemSpec.js
|
rapilabs/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ListGroupItem from '../src/ListGroupItem';
describe('ListGroupItem', function () {
it('Should output a "span" with the class "list-group-item"', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ListGroupItem>Text</ListGroupItem>
);
assert.equal(React.findDOMNode(instance).nodeName, 'SPAN');
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group-item'));
});
it('Should output an "anchor" if "href" prop is set', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ListGroupItem href='#test'>Anchor</ListGroupItem>
);
assert.equal(React.findDOMNode(instance).nodeName, 'A');
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group-item'));
});
it('Should output an "li" if "listItem" prop is set', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ListGroupItem listItem>Item 1</ListGroupItem>
);
assert.equal(React.findDOMNode(instance).nodeName, 'LI');
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group-item'));
});
it('Should support "bsStyle" prop', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ListGroupItem bsStyle='success'>Item 1</ListGroupItem>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'list-group-item-success'));
});
it('Should support "active" and "disabled" prop', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ListGroupItem active>Item 1</ListGroupItem>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'active'));
});
it('Should support "disabled" prop', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ListGroupItem disabled>Item 2</ListGroupItem>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'disabled'));
});
it('Should support "header" prop as a string', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ListGroupItem header='Heading'>Item text</ListGroupItem>
);
let node = React.findDOMNode(instance);
assert.equal(node.firstChild.nodeName, 'H4');
assert.equal(node.firstChild.innerText, 'Heading');
assert.ok(node.firstChild.className.match(/\blist-group-item-heading\b/));
assert.equal(node.lastChild.nodeName, 'P');
assert.equal(node.lastChild.innerText, 'Item text');
assert.ok(node.lastChild.className.match(/\blist-group-item-text\b/));
});
it('Should support "header" prop as a ReactComponent', function () {
let header = <h2>Heading</h2>;
let instance = ReactTestUtils.renderIntoDocument(
<ListGroupItem header={header}>Item text</ListGroupItem>
);
let node = React.findDOMNode(instance);
assert.equal(node.firstChild.nodeName, 'H2');
assert.equal(node.firstChild.innerText, 'Heading');
assert.ok(node.firstChild.className.match(/\blist-group-item-heading\b/));
assert.equal(node.lastChild.nodeName, 'P');
assert.equal(node.lastChild.innerText, 'Item text');
assert.ok(node.lastChild.className.match(/\blist-group-item-text\b/));
});
});
|
test/test_helper.js
|
renamos/traderjoes-db
|
import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
packages/reactReduxFormBase/DEV/AppFormState.js
|
daniloster/react-experiments
|
import React, { Component } from 'react';
import Input from './Input';
import schemaData from './simpleSchemaData';
import { FormState, FormStateItem } from '../src';
export default class AppFormState extends Component {
state = {
person: {},
shouldValidate: false,
};
onValidate = (e) => {
e.preventDefault();
this.setState({ shouldValidate: true });
};
onSubmit = (e) => {
e.preventDefault();
alert('Submitting...');
};
render() {
const { shouldValidate } = this.state;
return (
<div>
<h2>FormState</h2>
<FormState schemaData={schemaData}>
<label htmlFor="firstname">Firstname</label>
<div key="name-group-data">
<FormStateItem path="firstname">
{({ onChange, value, validations }) => (
<span key="firstname" data-form-state-item>
<Input id="firstname" onChange={onChange} value={value} />
{validations && validations.map(({ message }) => message)}
</span>
)}
</FormStateItem>
<br />
<label htmlFor="lastname">Lastname</label>
<FormStateItem path="lastname">
{({ onChange, value, validations }) => (
<span key="lastname" data-form-state-item>
<Input id="lastname" onChange={onChange} value={value} />
{validations && validations.map(({ message }) => message)}
</span>
)}
</FormStateItem>
<br />
<FormStateItem>
{({ isAllValid }) => (
<button
key="validate"
onClick={this.onValidate}
disabled={!isAllValid(['fistname', 'lastname'])}
>
Validate Certificate
</button>
)}
</FormStateItem>
</div>
<label htmlFor="description">Certificate description</label>
<FormStateItem path="certificate.description">
{({ onChange, value, validations }) => (
<span key="description" data-form-state-item>
<Input id="description" onChange={onChange} value={value} />
{shouldValidate && validations && validations.map(({ message }) => message)}
</span>
)}
</FormStateItem>
<br />
<FormStateItem>
{({ isAllValid }) => (
<button key="submit" onClick={this.onSubmit} disabled={!isAllValid()}>
Submit
</button>
)}
</FormStateItem>
</FormState>
</div>
);
}
}
|
client/extensions/woocommerce/app/settings/payments/payment-method-cheque.js
|
Automattic/woocommerce-connect-client
|
/** @format */
/**
* External dependencies
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { localize } from 'i18n-calypso';
/**
* Internal dependencies
*/
import Dialog from 'components/dialog';
import FormFieldset from 'components/forms/form-fieldset';
import FormLabel from 'components/forms/form-label';
import FormTextarea from 'components/forms/form-textarea';
import FormTextInput from 'components/forms/form-text-input';
class PaymentMethodCheque extends Component {
static propTypes = {
method: PropTypes.shape( {
settings: PropTypes.shape( {
title: PropTypes.shape( {
id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
} ),
} ),
} ),
translate: PropTypes.func.isRequired,
onCancel: PropTypes.func.isRequired,
onEditField: PropTypes.func.isRequired,
onDone: PropTypes.func.isRequired,
};
onEditFieldHandler = e => {
this.props.onEditField( e.target.name, e.target.value );
};
buttons = [
{ action: 'cancel', label: this.props.translate( 'Cancel' ), onClick: this.props.onCancel },
{
action: 'save',
label: this.props.translate( 'Done' ),
onClick: this.props.onDone,
isPrimary: true,
},
];
render() {
const {
method,
method: { settings },
translate,
} = this.props;
return (
<Dialog
additionalClassNames="payments__dialog woocommerce"
buttons={ this.buttons }
isVisible
>
<FormFieldset className="payments__method-edit-field-container">
<FormLabel>{ translate( 'Title' ) }</FormLabel>
<FormTextInput
name="title"
onChange={ this.onEditFieldHandler }
value={ settings.title.value }
/>
</FormFieldset>
<FormFieldset className="payments__method-edit-field-container">
<FormLabel>{ translate( 'Instructions for customer at checkout' ) }</FormLabel>
<FormTextarea
name="description"
onChange={ this.onEditFieldHandler }
value={ method.description }
placeholder={ translate( 'Pay for this order by check.' ) }
/>
</FormFieldset>
<FormFieldset className="payments__method-edit-field-container">
<FormLabel>
{ translate( 'Instructions for customer in order email notification' ) }
</FormLabel>
<FormTextarea
name="instructions"
onChange={ this.onEditFieldHandler }
value={ settings.instructions.value }
placeholder={ translate( 'Make your check payable to…' ) }
/>
</FormFieldset>
</Dialog>
);
}
}
export default localize( PaymentMethodCheque );
|
src/components/buttons/FloatingActionButton.js
|
tuckerconnelly/carbon-ui
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Animated, TouchableOpacity, Platform } from 'react-native'
import { animate } from 'uranium'
import { Animations, TouchableRipple, Elevation, gu, connectTheme } from '../../index'
/**
* A floating action button represents the primary action in an application.
*
* The Android implementation is temporarily un-rippled until the React Native
* team implements `overflow: hidden` on Android.
*
* ### Examples
*
* import React from 'react'
* import { View } from 'react-native'
* import { FloatingActionButton, Icon, gu } from 'carbon-ui'
*
* export default () =>
* <View style={{ justifyContent: 'flex-start', flexDirection: 'row' }}>
* <FloatingActionButton style={{ marginRight: 2 * gu }}>
* <Icon name="add" style={{ color: 'white' }} />
* </FloatingActionButton>
* <FloatingActionButton accent>
* <Icon name="keyboard_voice" style={{ color: 'white' }} />
* </FloatingActionButton>
* </View>
*
*/
class FloatingActionButton extends Component {
_setPressed = e => {
Animations.standard(this._pressAV).start()
this.props.onPressIn && this.props.onPressIn(e)
}
_setNotPressed = e => {
Animations.standard(this._pressAV, { toValue: 0 }).start()
this.props.onPressOut && this.props.onPressOut(e)
}
_pressAV = new Animated.Value(0)
render() {
const { accent, children, style, theme, ...other } = this.props
// Until Android implements `overflow: hidden`. Until then, the "rippled"
// area would be square instead of round. See:
// https://github.com/facebook/react-native/issues/3198
const TouchableComponent = Platform.OS === 'android' ?
TouchableOpacity :
TouchableRipple
const styles = tStyles(theme)
return (
<Animated.View
style={[
styles.base,
animate(styles.base, styles.pressed, this._pressAV),
accent && { backgroundColor: theme.colors.accent },
].concat(style)}>
<TouchableComponent
rippleColor="white"
{...other}
style={styles.touchableRipple}
onPressIn={this._setPressed}
onPressOut={this._setNotPressed}>
{children}
</TouchableComponent>
</Animated.View>
)
}
}
FloatingActionButton.propTypes = {
/**
* Will set the background color to the accent color if set to true
*/
accent: PropTypes.bool,
/**
* Usually an <Icon />
*/
children: PropTypes.node,
style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
onPressIn: PropTypes.func,
onPressOut: PropTypes.func,
// connectTheme
theme: PropTypes.object.isRequired,
}
export default
connectTheme(
FloatingActionButton)
const tStyles = theme => ({
base: {
position: 'relative',
width: 14 * gu,
height: 14 * gu,
borderRadius: 7 * gu,
backgroundColor: theme.colors.primary,
...Elevation.dp6,
},
pressed: {
...Elevation.dp12,
},
touchableRipple: {
borderRadius: 7 * gu,
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
})
|
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js
|
chrisirhc/react-router
|
import React from 'react';
import { Link } from 'react-router';
export default class AnnouncementsSidebar extends React.Component {
render () {
var announcements = COURSES[this.props.params.courseId].announcements;
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{announcements.map(announcement => (
<li key={announcement.id}>
<Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}>
{announcement.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
|
src/components/chatbot/oldslick.js
|
gordongordon/hom
|
import React from 'react';
import { Carousel, WhiteSpace, WingBlank, Button } from 'antd-mobile';
import { Generic } from 'react-simple-chatbot';
import PropTypes from 'prop-types';
export default class Slick extends React.Component {
constructor( props ) {
super( props )
this.state = {
data: ['', '', ''],
initialHeight: 450,
value: null,
trigger: false
};
this.triggetNext = this.triggetNext.bind(this);
}
componentDidMount() {
// simulate img loading
setTimeout(() => {
this.setState({
data: ['AiyWuByWklrrUDlFignR', 'TekJlZRVCjLFexlOCuWn', 'IJOtIlfsYdTyaDTRVrLI'],
});
}, 100);
}
triggetNext() {
this.setState({ trigger: true }, () => {
this.props.triggerNextStep( { value: 'building', label : 'matching' });
});
}
render() {
const hProp = this.state.initialHeight ? { height: this.state.initialHeight } : {};
return (
<Carousel
className="my-carousel"
autoplay={false}
dots={true}
selectedIndex={0}
swipeSpeed={3}
beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}
afterChange={index => console.log('slide to', index)}
>
<Generic onClick={this.triggetNext} />
<Generic onClick={this.triggetNext} />
<Generic onClick={this.triggetNext} />
</Carousel>
);
}
}
Slick.propTypes = {
steps: PropTypes.object,
triggerNextStep: PropTypes.func,
};
Slick.defaultProps = {
steps: undefined,
triggerNextStep: undefined,
};
|
js/components/common/single-row-list-item/singleRowListItem.js
|
justarrived/p2p-client
|
import React, { Component } from 'react';
import { Text } from 'react-native';
import { CardItem, Left, Right, Icon } from 'native-base';
export default class SingleRowListItem extends Component {
static propTypes = {
text: React.PropTypes.string.isRequired,
icon: React.PropTypes.string,
};
static defaultProps = {
icon: undefined,
};
render() {
const { text, icon } = this.props;
let iconIfProvided = [];
if (icon !== undefined) {
iconIfProvided = (
<Right>
<Icon name={icon} />
</Right>
);
}
return (
<CardItem bordered button>
<Left>
<Text>{text}</Text>
</Left>
{iconIfProvided}
</CardItem>
);
}
}
|
src/icons/SignalWifi0BarIcon.js
|
kiloe/ui
|
import React from 'react';
import Icon from '../Icon';
export default class SignalWifi0BarIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path fillOpacity=".3" d="M24.02 42.98L47.28 14c-.9-.68-9.85-8-23.28-8C10.57 6 1.62 13.32.72 14l23.26 28.98.02.02.02-.02z"/></svg>;}
};
|
client/screens/Guia/index.js
|
francixcoag/trace_packages
|
import React from 'react';
import { Link } from 'react-router';
import AppNavBar from '../App/components/AppNavBar';
import AppSideBar from '../App/components/AppSideBar';
import GuiaContainer from './GuiaContainer.js';
import HeaderContainer from './HeaderContainer.js';
export default (props) => (
<div className="wrapper">
<AppNavBar label="Tracking Encomendas" screen="app/main" />
<div className="left side-menu open">
<AppSideBar label="Detalhes Guia" screen="guias/guia" />
</div>
<div className="content-page">
<div className="content">
<div className="container">
<div className="row">
<div className="col-sm-12 col-md-12 col-lg-12">
<div className="page-title-box">
<ol className="breadcrumb pull-right">
<li className="breadcrumb-item"><Link to="/app">Home</Link></li>
<li className="breadcrumb-item"><Link to="/guias">Guias</Link></li>
<li className="breadcrumb-item active">Guia Detalhes</li>
</ol>
<h4 className="page-title">Detalhes de Guia</h4>
</div>
</div>
</div>
<div className="row text-center">
<div className="col-sm-12 col-md-12 col-lg-12">
<div className="card-box">
<HeaderContainer codProcess={props.params.codProcess}/>
</div>
</div>
</div>
<div className="row text-center">
<div className="col-sm-12 col-md-12 col-lg-12">
<div className="card-box">
<GuiaContainer codProcess={props.params.codProcess}/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
|
src/DateHeader.js
|
TeaBough/react-big-calendar
|
import PropTypes from 'prop-types'
import React from 'react'
const DateHeader = ({ label, drilldownView, onDrillDown }) => {
if (!drilldownView) {
return <span>{label}</span>
}
return (
<a href="#" onClick={onDrillDown}>
{label}
</a>
)
}
DateHeader.propTypes = {
label: PropTypes.node,
date: PropTypes.instanceOf(Date),
drilldownView: PropTypes.string,
onDrillDown: PropTypes.func,
isOffRange: PropTypes.bool,
}
export default DateHeader
|
src/containers/ActivityContainer.js
|
zzelune/neam
|
/*
* @Author: zhaozheng1.zh
* @Date: 2017-09-09 22:10:22
* @Last Modified by: fishci
* @Last Modified time: 2017-10-27 16:39:14
*/
import React, { Component } from 'react';
import Activity from '../pages/activity'
import Icon from 'react-native-vector-icons/Ionicons';
export default class ActivityContainer extends Component {
static navigationOptions = {
header: null,
tabBarLabel: '活动',
tabBarIcon: ({tintColor}) => (
<Icon name='ios-home-outline' size={30} color={tintColor}/>
),
};
render() {
return (
<Activity {...this.props}/>
);
}
}
|
examples/huge-apps/routes/Course/components/Nav.js
|
cold-brew-coding/react-router
|
import React from 'react';
import { Link } from 'react-router';
import AnnouncementsRoute from '../routes/Announcements';
import AssignmentsRoute from '../routes/Assignments';
import GradesRoute from '../routes/Grades';
const styles = {};
styles.nav = {
borderBottom: '1px solid #aaa'
};
styles.link = {
display: 'inline-block',
padding: 10,
textDecoration: 'none',
};
styles.activeLink = Object.assign({}, styles.link, {
//color: 'red'
});
class Nav extends React.Component {
render () {
var { course } = this.props;
var pages = [
['announcements', 'Announcements'],
['assignments', 'Assignments'],
['grades', 'Grades'],
];
return (
<nav style={styles.nav}>
{pages.map((page, index) => (
<Link
key={page[0]}
activeStyle={index === 0 ?
Object.assign({}, styles.activeLink, { paddingLeft: 0 }) :
styles.activeLink}
style={index === 0 ?
Object.assign({}, styles.link, { paddingLeft: 0 }) :
styles.link }
to={`/course/${course.id}/${page[0]}`}
>{page[1]}</Link>
))}
</nav>
);
}
}
export default Nav;
|
src/components/__tests__/EmailListView_test.js
|
varenya/email-client
|
import React from 'react';
import {shallow} from 'enzyme';
import {EmailList, getEmails} from '../EmailListView';
import {fromJS, is} from 'immutable';
import {MetaEmail} from '../MetaEmail';
describe("EmailListView", () => {
let emailList = null;
beforeEach(() => {
const sampleProps = {
inbox: [{
selected: false,
unread: false,
name: 'Test',
desc: 'Hello Test',
subject: 'TestSubject',
avatar: './src/img/test.jpg'
}]
};
emailList = shallow(<EmailList emailList={fromJS(sampleProps)} match={{
params: {
groupName: 'inbox',
emailId: '0'
}
}}/>);
});
it("should have MetaEmail component", () => {
expect(emailList.find(MetaEmail).exists()).toBeTruthy();
});
it("should have correct number of MetaEmail components", () => {
expect(emailList.find(MetaEmail).length).toEqual(1);
});
it("should have div with id list element", () => {
expect(emailList.find('#list').exists()).toBeTruthy();
});
it("should not have a MetaEmail component if list is empty", () => {
const email = shallow(<EmailList emailList={fromJS({inbox : []})} match={{params : {}}}/>);
expect(email.find(MetaEmail).exists()).toBeFalsy();
});
it("should have getEmails method and should work as expected", () => {
const testData = fromJS({
test1: [
{
name: 'test',
group: 'test1'
}
],
test2: [
{
name: 'test1',
group: 'test2'
}
]
});
const result = fromJS([
{
name: 'test',
'group': 'test1'
}
]);
const actualResult = getEmails(testData, 'test1');
expect(is(result, actualResult)).toBeTruthy();
})
})
|
frontend/src/components/pages/video.js
|
wilsonwen/kanmeiju
|
import React, { Component } from 'react';
import Config from '../../config'
import { browserHistory } from 'react-router';
import Spin from '../spin'
import { VelocityTransitionGroup } from 'velocity-react';
import './video.css'
class Video extends Component {
constructor(props) {
super(props);
this.state = {
fetchDone: false,
json : ""
}
this.config = Config();
this.fetchData = this.fetchData.bind(this);
this.handleError = this.handleError.bind(this);
}
/* callde first initialize */
componentDidMount() {
this.fetchData(this.props.params.episodeSid);
}
fetchData(episodeSid) {
let url = this.config.server + '/api/m3u8/' + episodeSid;
fetch(url).then((res) => res.json()).then((data) => {
this.setState({
fetchDone: true,
json: data
});
}).catch(function(error){
this.setState({
fetchDone: true
})
}.bind(this));
}
handleError() {
this.setState({json: {'data': undefined}});
}
render() {
let content = null;
/* Check search done */
if (this.state.fetchDone) {
if (this.state.json.data !== undefined &&
this.state.json.data.m3u8 !== undefined &&
this.state.json.data.m3u8.url !== "") {
content = <video className="col-xs-12"
src={this.state.json.data.m3u8.url}
type="video/mp4"
onError={this.handleError}
controls autoPlay>
</video>
} else {
content = <div className="alert alert-danger" role="alert">
<span className="sr-only">Error:</span>
抱歉,视频已经下线。<a href="#" onClick={browserHistory.goBack}>返回剧集</a>
</div>
}
} else {
content = <Spin />
}
return (
<div >
<VelocityTransitionGroup enter={{animation: "transition.slideLeftIn"}} leave={{animation: "transition.slideRightOut"}}
runOnMount={true}>
<p className="video-title">{this.props.params.title}</p>
{ content }
</VelocityTransitionGroup>
</div>
)
}
}
export default Video;
|
packages/babel-plugin-jsx-pragmatic/__tests__/__fixtures__/existing-imports.js
|
emotion-js/emotion
|
// inserted import has to go AFTER polyfills
import 'react-app-polyfill/ie11'
import 'react-app-polyfill/stable'
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(<App />, document.getElementById('root'))
|
definitions/npm/react-transition-group_v2.x.x/test_react-transition-group.js
|
orlandoc01/flow-typed
|
// @flow
import { describe, it } from 'flow-typed-test';
import React from 'react';
import {
CSSTransition,
ReplaceTransition,
Transition,
TransitionGroup,
} from 'react-transition-group';
describe('CSS/Transition', () => {
const handleEnter = (node: HTMLElement, isAppearing: boolean) => {};
const handleExit = (node: HTMLElement) => {};
const handleEndListener = (node: HTMLElement, done: () => void) =>
node.addEventListener('transitionend', done, false);
describe('Transition', () => {
it('should accept all parameters', () => {
<Transition
in
mountOnEnter
unmountOnExit
appear
enter
exit
timeout={ 1 }
addEndListener={ handleEndListener }
onEnter={ handleEnter }
onEntering={ handleEnter }
onEntered={ handleEnter }
onExit={ handleExit }
onExiting={ handleExit }
onExited={ handleExit }
>
<div />
</Transition>;
})
it('should accept one of timeout and addEndListener', () => {
<Transition timeout={ { enter: 1, exit: 1 } }>
<div />
</Transition>;
<Transition addEndListener={ handleEndListener }>
<div />
</Transition>;
})
it('should fail without required params', () => {
// $ExpectError
<Transition><div /></Transition>;
// $ExpectError
<Transition timeout={ 1 } />
})
it('props should be compatible with other types with same structure', () => {
type WithTransitionProps = {
// props copied from Transition element config
mountOnEnter?: boolean,
unmountOnExit?: boolean,
appear?: boolean,
enter?: boolean,
exit?: boolean,
timeout: number,
addListener?: (node: HTMLElement, done: () => void) => void,
onEnter?: (node: HTMLElement, isAppearing: boolean) => void,
onEntering?: (node: HTMLElement, isAppearing: boolean) => void,
onEntered?: (node: HTMLElement, isAppearing: boolean) => void,
onExit?: (node: HTMLElement) => void,
onExiting?: (node: HTMLElement) => void,
onExited?: (node: HTMLElement) => void,
in?: boolean,
// custom props
children: React$Node,
getClassName(state: string): string
};
class WrapperComponent extends React.PureComponent<WithTransitionProps> {
render() {
const {
children,
mountOnEnter,
unmountOnExit,
appear,
enter,
exit,
timeout,
addListener,
onEnter,
onEntering,
onEntered,
onExit,
onExiting,
onExited,
in: transitionIn,
...restProps
} = this.props;
return (
<Transition
in={transitionIn}
mountOnEnter={mountOnEnter}
unmountOnExit={unmountOnExit}
appear={appear}
enter={enter}
exit={exit}
timeout={timeout}
addListener={addListener}
onEnter={onEnter}
onEntering={onEntering}
onEntered={onEntered}
onExit={onExit}
onExited={onExited}
onExiting={onExiting}
>
{state => (
<div className={restProps.getClassName(state)}>
{children}
</div>
)}
</Transition>
)
}
}
<WrapperComponent timeout={100} getClassName={state => `transition-${state}`}>Foobar</WrapperComponent>;
});
})
describe('CSSTransition', () => {
it('should accept all parameters', () => {
<CSSTransition
in
mountOnEnter
unmountOnExit
appear
enter
exit
timeout={ 1 }
addEndListener={ handleEndListener }
onEnter={ handleEnter }
onEntering={ handleEnter }
onEntered={ handleEnter }
onExit={ handleExit }
onExiting={ handleExit }
onExited={ handleExit }
classNames='fade'
>
<div />
</CSSTransition>;
})
it('should accept a function child of the current status to react node', () => {
<CSSTransition
in
timeout={ 1 }
classNames='fade'
>
{status => (<div>{status}</div>)}
</CSSTransition>;
});
it('should accept alternative parameters', () => {
<CSSTransition
timeout={ { enter: 1, exit: 1 } }
classNames={ {
appear: 'fade-appear',
appearActive: 'fade-active-appear',
enter: 'fade-enter',
enterActive: 'fade-active-enter',
enterDone: 'fade-done-enter',
exit: 'fade-exit',
exitActive: 'fade-active-exit',
exitDone: 'fade-done-exit',
} }
>
<div />
</CSSTransition>;
})
it('should fail without required parameters', () => {
// $ExpectError
<CSSTransition timeout={ 1 }><div /></CSSTransition>;
})
})
})
describe('Groups', () => {
const t1 = <Transition timeout={ 1 }><div /></Transition>;
const t2 = <CSSTransition timeout={ 1 } classNames='fade'><div /></CSSTransition>;
describe('TransitionGroup', () => {
function childFactory(child: React$Node) {
return child;
}
it('should accept a null component', () => {
<TransitionGroup component={null} childFactory={ childFactory }>
{ t1 }
{ t2 }
</TransitionGroup>;
})
it('should accept string component', () => {
<TransitionGroup component={'nav'}>
{ t1 }
{ t2 }
</TransitionGroup>;
})
})
describe('ReplaceTransition', () => {
it('should accept minimum parameters', () => {
<ReplaceTransition in timeout={ 1 }>
{ t1 }
{ t2 }
</ReplaceTransition>;
})
it('should fail without required parameters', () => {
// $ExpectError
<ReplaceTransition timeout={ 1 }>
{ t1 }
{ t2 }
</ReplaceTransition>;
})
})
})
|
node_modules/react-router/es6/Router.js
|
ottomajik/react-demo
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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, { Component } from 'react';
import createHashHistory from 'history/lib/createHashHistory';
import { createRoutes } from './RouteUtils';
import RoutingContext from './RoutingContext';
import useRoutes from './useRoutes';
import { routes } from './PropTypes';
var _React$PropTypes = React.PropTypes;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;
/**
* A <Router> is a high-level API for automatically setting up
* a router that renders a <RoutingContext> with all the props
* it needs each time the URL changes.
*/
var Router = (function (_Component) {
_inherits(Router, _Component);
function Router(props, context) {
_classCallCheck(this, Router);
_Component.call(this, props, context);
this.state = {
location: null,
routes: null,
params: null,
components: null
};
}
Router.prototype.handleError = function handleError(error) {
if (this.props.onError) {
this.props.onError.call(this, error);
} else {
// Throw errors by default so we don't silently swallow them!
throw error; // This error probably occurred in getChildRoutes or getComponents.
}
};
Router.prototype.componentWillMount = function componentWillMount() {
var _this = this;
var _props = this.props;
var history = _props.history;
var children = _props.children;
var routes = _props.routes;
var parseQueryString = _props.parseQueryString;
var stringifyQuery = _props.stringifyQuery;
var createHistory = history ? function () {
return history;
} : createHashHistory;
this.history = useRoutes(createHistory)({
routes: createRoutes(routes || children),
parseQueryString: parseQueryString,
stringifyQuery: stringifyQuery
});
this._unlisten = this.history.listen(function (error, state) {
if (error) {
_this.handleError(error);
} else {
_this.setState(state, _this.props.onUpdate);
}
});
};
/* istanbul ignore next: sanity check */
Router.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
process.env.NODE_ENV !== 'production' ? warning(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : undefined;
process.env.NODE_ENV !== 'production' ? warning((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : undefined;
};
Router.prototype.componentWillUnmount = function componentWillUnmount() {
if (this._unlisten) this._unlisten();
};
Router.prototype.render = function render() {
var _state = this.state;
var location = _state.location;
var routes = _state.routes;
var params = _state.params;
var components = _state.components;
var _props2 = this.props;
var RoutingContext = _props2.RoutingContext;
var createElement = _props2.createElement;
var props = _objectWithoutProperties(_props2, ['RoutingContext', 'createElement']);
if (location == null) return null; // Async match
// Only forward non-Router-specific props to routing context, as those are
// the only ones that might be custom routing context props.
Object.keys(Router.propTypes).forEach(function (propType) {
return delete props[propType];
});
return React.createElement(RoutingContext, _extends({}, props, {
history: this.history,
createElement: createElement,
location: location,
routes: routes,
params: params,
components: components
}));
};
return Router;
})(Component);
Router.propTypes = {
history: object,
children: routes,
routes: routes, // alias for children
RoutingContext: func.isRequired,
createElement: func,
onError: func,
onUpdate: func,
parseQueryString: func,
stringifyQuery: func
};
Router.defaultProps = {
RoutingContext: RoutingContext
};
export default Router;
|
docs/src/app/components/pages/components/FlatButton/Page.js
|
rscnt/material-ui
|
import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import flatButtonReadmeText from './README';
import flatButtonExampleSimpleCode from '!raw!./ExampleSimple';
import FlatButtonExampleSimple from './ExampleSimple';
import flatButtonExampleComplexCode from '!raw!./ExampleComplex';
import FlatButtonExampleComplex from './ExampleComplex';
import flatButtonExampleIconCode from '!raw!./ExampleIcon';
import FlatButtonExampleIcon from './ExampleIcon';
import flatButtonCode from '!raw!material-ui/lib/FlatButton/FlatButton';
const descriptions = {
simple: '`FlatButton` with default color, `primary`, `secondary` and and `disabled` props applied.',
complex: 'The first example uses an `input` as a child component, ' +
'the next has next has an [SVG Icon](/#/components/svg-icon), with the label positioned after. ' +
'The final example uses a [Font Icon](/#/components/font-icon), and is wrapped in an anchor tag.',
icon: 'Examples of Flat Buttons using an icon without a label. The first example uses an' +
' [SVG Icon](/#/components/svg-icon), and has the default color. The second example shows' +
' how the icon and background color can be changed. The final example uses a' +
' [Font Icon](/#/components/font-icon), and is wrapped in an anchor tag.',
};
const FlatButtonPage = () => (
<div>
<Title render={(previousTitle) => `Flat Button - ${previousTitle}`} />
<MarkdownElement text={flatButtonReadmeText} />
<CodeExample
title="Simple examples"
description={descriptions.simple}
code={flatButtonExampleSimpleCode}
>
<FlatButtonExampleSimple />
</CodeExample>
<CodeExample
title="Complex examples"
description={descriptions.complex}
code={flatButtonExampleComplexCode}
>
<FlatButtonExampleComplex />
</CodeExample>
<CodeExample
title="Icon examples"
description={descriptions.icon}
code={flatButtonExampleIconCode}
>
<FlatButtonExampleIcon />
</CodeExample>
<PropTypeDescription code={flatButtonCode} />
</div>
);
export default FlatButtonPage;
|
src/containers/NotFound/NotFound.js
|
Trippstan/elephonky
|
import React from 'react';
export default function NotFound() {
return (
<div className="container">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
);
}
|
frontend/src/containers/AppContainer.js
|
SeaItRise/SeaItRise-webportal
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { browserHistory, Router } from 'react-router';
import { Provider } from 'react-redux';
class AppContainer extends Component {
static propTypes = {
routes: PropTypes.object.isRequired,
store: PropTypes.object.isRequired,
}
shouldComponentUpdate() {
return false;
}
render() {
const { routes, store } = this.props;
return (
<Provider store={store}>
<div style={{ height: '100%' }}>
<Router history={browserHistory} children={routes} />
</div>
</Provider>
);
}
}
export default AppContainer;
|
react/features/old-client-notification/components/OldElectronAPPNotificationDescription.js
|
bgrozev/jitsi-meet
|
// @flow
import React, { Component } from 'react';
import { translate } from '../../base/i18n';
/**
* The type of the React {@code Component} props of {@link OldElectronAPPNotificationDescription}.
*/
type Props = {
/**
* Invoked to obtain translated strings.
*/
t: Function
};
/**
* A component that renders the description of the notification for old Jitsi Meet Electron clients.
*
* @extends AbstractApp
*/
export class OldElectronAPPNotificationDescription extends Component<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { t } = this.props;
return (
<div>
{ t('notify.oldElectronClientDescription1') }
<a
href = 'https://github.com/jitsi/jitsi-meet-electron/releases/latest'
rel = 'noopener noreferrer'
target = '_blank'>
{ t('notify.oldElectronClientDescription2') }
</a>
{ t('notify.oldElectronClientDescription3') }
</div>);
}
}
export default translate(OldElectronAPPNotificationDescription);
|
client/src/components/Header/index.js
|
pahosler/freecodecamp
|
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'gatsby';
import FCCSearch from 'react-freecodecamp-search';
import NavLogo from './components/NavLogo';
import UserState from './components/UserState';
import './header.css';
function Header({ disableSettings }) {
return (
<header>
<nav id='top-nav'>
<a className='home-link' href='https://www.freecodecamp.org'>
<NavLogo />
</a>
{disableSettings ? null : <FCCSearch />}
<ul id='top-right-nav'>
<li>
<Link to='/learn'>Curriculum</Link>
</li>
<li>
<a
href='https://forum.freecodecamp.org'
rel='noopener noreferrer'
target='_blank'
>
Forum
</a>
</li>
<li>
<UserState disableSettings={disableSettings} />
</li>
</ul>
</nav>
</header>
);
}
Header.propTypes = {
disableSettings: PropTypes.bool
};
export default Header;
|
examples/IconSimple.js
|
mattBlackDesign/react-materialize
|
import React from 'react';
import Icon from '../src/Icon';
export default
<Icon>insert_chart</Icon>;
|
examples/passing-props-to-children/app.js
|
ryardley/react-router
|
import React from 'react';
import { Router, Route, Link, History } from 'react-router';
var App = React.createClass({
mixins: [ History ],
getInitialState() {
return {
tacos: [
{ name: 'duck confit' },
{ name: 'carne asada' },
{ name: 'shrimp' }
]
};
},
addTaco() {
var name = prompt('taco name?');
this.setState({
tacos: this.state.tacos.concat({name: name})
});
},
handleRemoveTaco(removedTaco) {
var tacos = this.state.tacos.filter(function (taco) {
return taco.name != removedTaco;
});
this.setState({tacos: tacos});
this.history.pushState(null, '/');
},
render() {
var links = this.state.tacos.map(function (taco, i) {
return (
<li key={i}>
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
</li>
);
});
return (
<div className="App">
<button onClick={this.addTaco}>Add Taco</button>
<ul className="Master">
{links}
</ul>
<div className="Detail">
{this.props.children && React.cloneElement(this.props.children, {
onRemoveTaco: this.handleRemoveTaco
})}
</div>
</div>
);
}
});
var Taco = React.createClass({
remove() {
this.props.onRemoveTaco(this.props.params.name);
},
render() {
return (
<div className="Taco">
<h1>{this.props.params.name}</h1>
<button onClick={this.remove}>remove</button>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="taco/:name" component={Taco} />
</Route>
</Router>
), document.getElementById('example'));
|
node_modules/react-bootstrap/es/ButtonGroup.js
|
Technaesthetic/ua-tools
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import all from 'react-prop-types/lib/all';
import Button from './Button';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
vertical: React.PropTypes.bool,
justified: React.PropTypes.bool,
/**
* Display block buttons; only useful when used with the "vertical" prop.
* @type {bool}
*/
block: all(React.PropTypes.bool, function (_ref) {
var block = _ref.block,
vertical = _ref.vertical;
return block && !vertical ? new Error('`block` requires `vertical` to be set to have any effect') : null;
})
};
var defaultProps = {
block: false,
justified: false,
vertical: false
};
var ButtonGroup = function (_React$Component) {
_inherits(ButtonGroup, _React$Component);
function ButtonGroup() {
_classCallCheck(this, ButtonGroup);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ButtonGroup.prototype.render = function render() {
var _extends2;
var _props = this.props,
block = _props.block,
justified = _props.justified,
vertical = _props.vertical,
className = _props.className,
props = _objectWithoutProperties(_props, ['block', 'justified', 'vertical', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps)] = !vertical, _extends2[prefix(bsProps, 'vertical')] = vertical, _extends2[prefix(bsProps, 'justified')] = justified, _extends2[prefix(Button.defaultProps, 'block')] = block, _extends2));
return React.createElement('div', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return ButtonGroup;
}(React.Component);
ButtonGroup.propTypes = propTypes;
ButtonGroup.defaultProps = defaultProps;
export default bsClass('btn-group', ButtonGroup);
|
src/components/TabBarIOS.js
|
RealOrangeOne/react-native-mock
|
import React from 'react';
import createMockComponent from './createMockComponent';
const TabBarIOS = React.createClass({
propTypes: {
children: React.PropTypes.node
},
statics: {
Item: createMockComponent('TabBarIOS.Item')
},
render() {
return null;
}
});
module.exports = TabBarIOS;
|
app/assets/javascripts/components/stories/StoryLink.js
|
Codeminer42/cm42-central
|
import React from 'react';
import hoverTemplate from 'templates/story_hover.ejs';
import noteTemplate from 'templates/note.ejs';
const STORY_STATE_ICONS = {
unstarted: 'access_time',
started: 'check_box_outline_blank',
finished: 'check_box',
delivered: 'hourglass_empty',
rejected: 'close',
accepted: 'done'
};
export default class StoryLink extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const { story } = this.props;
document.getElementById(`story-${story.get('id')}`).scrollIntoView();
story && _.each(story.views, view => view.highlight());
}
renderIcon(storyState) {
return (
<i className={`mi story-link-icon ${storyState}`}>
{STORY_STATE_ICONS[storyState]}
</i>
);
}
render() {
const { story } = this.props;
const storyState = story.get('state');
const id = story.get('id');
const popoverContent = hoverTemplate({
story: story,
noteTemplate: noteTemplate
});
return (
<a className={`story-link popover-activate ${storyState}`}
data-content={popoverContent}
data-original-title={story.get('title')}
id={`story-link-${id}`}
onClick={this.handleClick}>
{ `#${id}` }
{ (storyState !== 'unscheduled') && this.renderIcon(storyState) }
</a>
);
}
}
|
src/icons/IosInfinite.js
|
fbfeix/react-icons
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosInfinite extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M456.821,182.377C436.782,162.788,410.062,152,381.585,152c-28.477,0-55.195,10.788-75.21,30.354l-39.106,37.885
l25.06,24.689l38.843-37.769c13.458-13.095,31.321-20.307,50.299-20.307c18.979,0,36.841,7.212,50.282,20.291
c13.363,13.077,20.712,30.468,20.693,48.97c-0.019,18.443-7.363,35.75-20.677,48.728c-13.458,13.095-31.32,20.307-50.299,20.307
c-18.978,0-36.841-7.212-50.291-20.299L205.646,182.359C185.491,162.782,158.778,152,130.427,152
c-28.477,0-55.195,10.788-75.23,30.373C35.103,201.986,24.023,228.132,24,255.993c-0.024,27.822,11.055,53.973,31.192,73.63
C75.232,349.212,101.951,360,130.427,360c28.475,0,55.194-10.788,75.223-30.363l38.994-37.909l-25.088-24.502l-38.829,37.615
c-13.458,13.095-31.321,20.307-50.3,20.307c-18.977,0-36.839-7.212-50.28-20.291c-13.364-13.077-20.714-30.469-20.694-48.971
c0.019-18.443,7.363-35.749,20.678-48.727c13.458-13.095,31.32-20.307,50.297-20.307c18.979,0,36.842,7.212,50.292,20.299
l125.532,122.489C326.406,349.218,353.119,360,381.47,360c28.476,0,55.194-10.788,75.213-30.355
c20.179-19.573,31.301-45.727,31.317-73.64C488.017,228.167,476.942,202.018,456.821,182.377z"></path>
</g>;
} return <IconBase>
<path d="M456.821,182.377C436.782,162.788,410.062,152,381.585,152c-28.477,0-55.195,10.788-75.21,30.354l-39.106,37.885
l25.06,24.689l38.843-37.769c13.458-13.095,31.321-20.307,50.299-20.307c18.979,0,36.841,7.212,50.282,20.291
c13.363,13.077,20.712,30.468,20.693,48.97c-0.019,18.443-7.363,35.75-20.677,48.728c-13.458,13.095-31.32,20.307-50.299,20.307
c-18.978,0-36.841-7.212-50.291-20.299L205.646,182.359C185.491,162.782,158.778,152,130.427,152
c-28.477,0-55.195,10.788-75.23,30.373C35.103,201.986,24.023,228.132,24,255.993c-0.024,27.822,11.055,53.973,31.192,73.63
C75.232,349.212,101.951,360,130.427,360c28.475,0,55.194-10.788,75.223-30.363l38.994-37.909l-25.088-24.502l-38.829,37.615
c-13.458,13.095-31.321,20.307-50.3,20.307c-18.977,0-36.839-7.212-50.28-20.291c-13.364-13.077-20.714-30.469-20.694-48.971
c0.019-18.443,7.363-35.749,20.678-48.727c13.458-13.095,31.32-20.307,50.297-20.307c18.979,0,36.842,7.212,50.292,20.299
l125.532,122.489C326.406,349.218,353.119,360,381.47,360c28.476,0,55.194-10.788,75.213-30.355
c20.179-19.573,31.301-45.727,31.317-73.64C488.017,228.167,476.942,202.018,456.821,182.377z"></path>
</IconBase>;
}
};IosInfinite.defaultProps = {bare: false}
|
examples/src/components/CustomComponents.js
|
Craga89/react-select
|
import React from 'react';
import Select from 'react-select';
import Gravatar from 'react-gravatar';
const USERS = require('../data/users');
const GRAVATAR_SIZE = 15;
const GravatarOption = React.createClass({
propTypes: {
children: React.PropTypes.node,
className: React.PropTypes.string,
isDisabled: React.PropTypes.bool,
isFocused: React.PropTypes.bool,
isSelected: React.PropTypes.bool,
onFocus: React.PropTypes.func,
onSelect: React.PropTypes.func,
onUnfocus: React.PropTypes.func,
option: React.PropTypes.object.isRequired,
},
handleMouseDown (event) {
event.preventDefault();
event.stopPropagation();
this.props.onSelect(this.props.option, event);
},
handleMouseEnter (event) {
this.props.onFocus(this.props.option, event);
},
handleMouseMove (event) {
if (this.props.isFocused) return;
this.props.onFocus(this.props.option, event);
},
handleMouseLeave (event) {
this.props.onUnfocus(this.props.option, event);
},
render () {
let gravatarStyle = {
borderRadius: 3,
display: 'inline-block',
marginRight: 10,
position: 'relative',
top: -2,
verticalAlign: 'middle',
};
return (
<div className={this.props.className}
onMouseDown={this.handleMouseDown}
onMouseEnter={this.handleMouseEnter}
onMouseMove={this.handleMouseMove}
onMouseLeave={this.handleMouseLeave}
title={this.props.option.title}>
<Gravatar email={this.props.option.email} size={GRAVATAR_SIZE} style={gravatarStyle} />
{this.props.children}
</div>
);
}
});
const GravatarValue = React.createClass({
propTypes: {
children: React.PropTypes.node,
placeholder: React.PropTypes.string,
value: React.PropTypes.object
},
render () {
var gravatarStyle = {
borderRadius: 3,
display: 'inline-block',
marginRight: 10,
position: 'relative',
top: -2,
verticalAlign: 'middle',
};
return (
<div className="Select-value" title={this.props.value.title}>
<span className="Select-value-label">
<Gravatar email={this.props.value.email} size={GRAVATAR_SIZE} style={gravatarStyle} />
{this.props.children}
</span>
</div>
);
}
});
const UsersField = React.createClass({
propTypes: {
hint: React.PropTypes.string,
label: React.PropTypes.string,
},
getInitialState () {
return {};
},
setValue (value) {
this.setState({ value });
},
render () {
var placeholder = <span>☺ Select User</span>;
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select
onChange={this.setValue}
optionComponent={GravatarOption}
options={USERS}
placeholder={placeholder}
value={this.state.value}
valueComponent={GravatarValue}
/>
<div className="hint">
This example implements custom Option and Value components to render a Gravatar image for each user based on their email.
It also demonstrates rendering HTML elements as the placeholder.
</div>
</div>
);
}
});
module.exports = UsersField;
|
docs/lib/examples/PlayerWithCaptions.js
|
video-react/video-react
|
import React from 'react';
import { Player, ControlBar, ClosedCaptionButton } from 'video-react';
export default function PlayerWithCaptions() {
return (
<Player videoId="video-1" autoPlay>
<source
src="//d2zihajmogu5jn.cloudfront.net/elephantsdream/ed_hd.mp4"
type="video/mp4"
/>
<source
src="//d2zihajmogu5jn.cloudfront.net/elephantsdream/ed_hd.ogg"
type="video/ogg"
/>
<track
kind="captions"
src="/assets/elephantsdream/captions.en.vtt"
srcLang="en"
label="English"
default
/>
<track
kind="captions"
src="/assets/elephantsdream/captions.sv.vtt"
srcLang="sv"
label="Swedish"
/>
<track
kind="captions"
src="/assets/elephantsdream/captions.ru.vtt"
srcLang="ru"
label="Russian"
/>
<track
kind="captions"
src="/assets/elephantsdream/captions.ja.vtt"
srcLang="ja"
label="Japanese"
/>
<track
kind="captions"
src="/assets/elephantsdream/captions.ar.vtt"
srcLang="ar"
label="Arabic"
/>
<track
kind="descriptions"
src="/assets/elephantsdream/descriptions.en.vtt"
srcLang="en"
label="English"
/>
<track
kind="chapters"
src="/assets/elephantsdream/chapters.en.vtt"
srcLang="en"
label="English"
/>
<ControlBar autoHide={false}>
<ClosedCaptionButton order={7} />
</ControlBar>
</Player>
);
}
|
src/js/components/CalculatorResult/CalculatorResultContainer.react.js
|
ali404/calculator-on-steroids
|
import React from 'react'
import Base from '../_helpers/BaseComponent'
import CalculatorResult from './CalculatorResult.react'
import CalculatorStore from '../../stores/CalculatorStore'
export default class CalculatorResultContainer extends Base {
constructor() {
super()
this._bind(
'_onChange',
'_getCalculatorResultState'
)
this.state = this._getCalculatorResultState()
}
componentDidMount() {
CalculatorStore.addChangeListener(this._onChange)
}
componentWillUnmount() {
CalculatorStore.removeChangeListener(this._onChange)
}
_onChange() {
this.setState(this._getCalculatorResultState())
}
_getCalculatorResultState() {
return {
queryResult: CalculatorStore.getQueryResult()
}
}
render() {
return (
<CalculatorResult
queryResult={this.state.queryResult}
/>
)
}
}
|
node_modules/react-bootstrap/es/Table.js
|
vitorgomateus/NotifyMe
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
striped: React.PropTypes.bool,
bordered: React.PropTypes.bool,
condensed: React.PropTypes.bool,
hover: React.PropTypes.bool,
responsive: React.PropTypes.bool
};
var defaultProps = {
bordered: false,
condensed: false,
hover: false,
responsive: false,
striped: false
};
var Table = function (_React$Component) {
_inherits(Table, _React$Component);
function Table() {
_classCallCheck(this, Table);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Table.prototype.render = function render() {
var _extends2;
var _props = this.props,
striped = _props.striped,
bordered = _props.bordered,
condensed = _props.condensed,
hover = _props.hover,
responsive = _props.responsive,
className = _props.className,
props = _objectWithoutProperties(_props, ['striped', 'bordered', 'condensed', 'hover', 'responsive', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'striped')] = striped, _extends2[prefix(bsProps, 'bordered')] = bordered, _extends2[prefix(bsProps, 'condensed')] = condensed, _extends2[prefix(bsProps, 'hover')] = hover, _extends2));
var table = React.createElement('table', _extends({}, elementProps, {
className: classNames(className, classes)
}));
if (responsive) {
return React.createElement(
'div',
{ className: prefix(bsProps, 'responsive') },
table
);
}
return table;
};
return Table;
}(React.Component);
Table.propTypes = propTypes;
Table.defaultProps = defaultProps;
export default bsClass('table', Table);
|
src/basic/Fab.js
|
sampsasaarela/NativeBase
|
/* @flow */
import React, { Component } from 'react';
import { Button } from './Button';
import { Platform, Animated, TouchableOpacity } from 'react-native';
// import View from './View';
import { Icon } from './Icon';
// import Badge from './Badge';
import { IconNB } from './IconNB';
// import Text from './Text';
import _ from 'lodash';
import { connectStyle } from 'native-base-shoutem-theme';
import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames';
import computeProps from '../Utils/computeProps';
const AnimatedFab = Animated.createAnimatedComponent(Button);
class Fab extends Component {
constructor(props) {
super(props);
this.state = {
buttons: undefined,
active: false,
};
}
fabTopValue(pos) {
if (pos === 'topLeft') {
return {
top: 20,
bottom: undefined,
left: 20,
right: undefined,
};
} else if (pos === 'bottomRight') {
return {
top: undefined,
bottom: (Platform.OS === 'ios') ? 20 : 40,
left: undefined,
right: 20,
};
} else if (pos === 'bottomLeft') {
return {
top: undefined,
bottom: (Platform.OS === 'ios') ? 20 : 40,
left: 20,
right: undefined,
};
} else if (pos === 'topRight') {
return {
top: 20,
bottom: undefined,
left: undefined,
right: 20,
};
}
}
fabOtherBtns(direction, i) {
if (direction === 'up') {
return {
top: undefined,
bottom: (this.props.active === false) ? ((Platform.OS === 'ios') ? 8 : 8) : ((i * 50) + 65),
left: 8,
right: 0,
};
} else if (direction === 'left') {
return {
top: 8,
bottom: 0,
left: (this.props.active === false) ? ((Platform.OS === 'ios') ? 8 : 8) : -((i * 50) + 50),
right: 0,
};
} else if (direction === 'down') {
return {
top: (this.props.active === false) ? ((Platform.OS === 'ios') ? 8 : 8) : ((i * 50) + 65),
bottom: 0,
left: 8,
right: 0,
};
} else if (direction === 'right') {
return {
top: 10,
bottom: 0,
left: (this.props.active === false) ? ((Platform.OS === 'ios') ? 8 : 8) : ((i * 50) + 65),
right: 0,
};
}
}
getInitialStyle(iconStyle) {
return {
fab: {
height: 56,
width: 56,
borderRadius: 28,
elevation: 4,
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
bottom: 0,
backgroundColor: 'blue',
},
container: {
position: 'absolute',
top: (this.props.position) ? this.fabTopValue(this.props.position).top : undefined,
bottom: (this.props.position) ? this.fabTopValue(this.props.position).bottom : 20,
right: (this.props.position) ? this.fabTopValue(this.props.position).right : 20,
left: (this.props.position) ? this.fabTopValue(this.props.position).left : undefined,
width: 56,
height: this.containerHeight,
flexDirection: (this.props.direction) ? ((this.props.direction == 'left || right') ? 'row' : 'column') : 'column',
alignItems: 'center',
},
iconStyle: {
color: '#fff',
fontSize: 24,
lineHeight: (Platform.OS === 'ios') ? 27 : undefined,
...iconStyle,
},
buttonStyle: {
position: 'absolute',
height: 40,
width: 40,
left: 7,
borderRadius: 20,
marginBottom: 10,
backgroundColor: 'blue',
},
};
}
getContainerStyle() {
return _.merge(this.getInitialStyle().container, this.props.containerStyle);
}
prepareFabProps() {
const defaultProps = {
style: this.getInitialStyle().fab,
};
const incomingProps = _.clone(this.props);
delete incomingProps.onPress;
return computeProps(incomingProps, defaultProps);
}
getOtherButtonStyle(child, i) {
const type = {
top: (this.props.direction) ? (this.fabOtherBtns(this.props.direction, i).top) : undefined,
left: (this.props.direction) ? (this.fabOtherBtns(this.props.direction, i).left) : 8,
right: (this.props.direction) ? (this.fabOtherBtns(this.props.direction, i).right) : 0,
bottom: (this.props.direction) ? (this.fabOtherBtns(this.props.direction, i).bottom) : ((this.props.active === false) ? ((Platform.OS === 'ios') ? 8 : 8) : ((i * 50) + 65)),
};
return _.merge(this.getInitialStyle().buttonStyle, child.props.style, type);
}
prepareButtonProps(child) {
const inp = _.clone(child.props);
delete inp.style;
const defaultProps = {};
return computeProps(inp, defaultProps);
}
componentDidMount() {
const childrenArray = React.Children.toArray(this.props.children);
const icon = _.remove(childrenArray, (item) => {
if (item.type.displayName === 'Styled(Button)') {
return true;
}
});
this.setState({
buttons: icon.length,
});
setTimeout(() => {
this.setState({
active: this.props.active,
});
}, 0);
}
renderFab() {
const childrenArray = React.Children.toArray(this.props.children);
const icon = _.remove(childrenArray, (item) => {
if (item.type === Button) {
return true;
}
});
// this.setState({
// buttons: icon.length
// });
return React.cloneElement(childrenArray[0], { style: this.getInitialStyle(childrenArray[0].props.style).iconStyle });
}
renderButtons() {
const childrenArray = React.Children.toArray(this.props.children);
const icon = _.remove(childrenArray, (item) => {
if (item.type.displayName === "Styled(Icon)" || item.type.displayName === "Styled(IconNB)") {
return true;
}
});
const newChildren = [];
{ childrenArray.map((child, i) => {
newChildren.push(<AnimatedFab
style={this.getOtherButtonStyle(child, i)}
{...this.prepareButtonProps(child, i)}
fabButton
key={i}
>{child.props.children}
</AnimatedFab>);
}
); }
return newChildren;
}
upAnimate() {
if (!this.props.active) {
Animated.spring(this.containerHeight, {
toValue: (this.state.buttons * 51.3) + 56,
}).start();
Animated.spring(this.buttonScale, {
toValue: 1,
}).start();
} else {
Animated.spring(this.containerHeight, {
toValue: 56,
}).start();
Animated.spring(this.buttonScale, {
toValue: 0,
}).start();
}
}
leftAnimate() {
if (!this.state.active) {
Animated.spring(this.containerWidth, {
toValue: (this.state.buttons * 51.3) + 56,
}).start();
Animated.spring(this.buttonScale, {
toValue: 1,
}).start();
} else {
this.setState({
active: false,
});
Animated.spring(this.containerHeight, {
toValue: 56,
}).start();
Animated.spring(this.buttonScale, {
toValue: 0,
}).start();
}
}
rightAnimate() {
if (!this.state.active) {
Animated.spring(this.containerWidth, {
toValue: (this.state.buttons * 51.3) + 56,
}).start();
Animated.spring(this.buttonScale, {
toValue: 1,
}).start();
} else {
this.setState({
active: false,
});
Animated.spring(this.containerHeight, {
toValue: 56,
}).start();
Animated.spring(this.buttonScale, {
toValue: 0,
}).start();
}
}
downAnimate() {
if (!this.state.active) {
Animated.spring(this.containerHeight, {
toValue: (56),
}).start();
Animated.spring(this.buttonScale, {
toValue: 1,
}).start();
} else {
this.setState({
active: false,
});
Animated.spring(this.containerHeight, {
toValue: 56,
}).start();
Animated.spring(this.buttonScale, {
toValue: 0,
}).start();
}
}
_animate() {
const { props: { direction, position } } = this;
if (this.props.direction) {
if (this.props.direction === 'up') {
this.upAnimate();
} else if (this.props.direction === 'left') {
this.leftAnimate();
} else if (this.props.direction === 'right') {
this.rightAnimate();
} else if (this.props.direction === 'down') {
this.downAnimate();
}
} else {
this.upAnimate();
}
}
fabOnPress() {
if (this.props.onPress) {
this.props.onPress();
this._animate();
}
}
render() {
const { props: { active } } = this;
if (!this.props.active) {
this.containerHeight = new Animated.Value(56);
this.containerWidth = new Animated.Value(56);
this.buttonScale = new Animated.Value(1);
} else {
this.containerHeight = this.containerHeight || new Animated.Value(0);
this.containerWidth = this.containerWidth || new Animated.Value(0);
this.buttonScale = this.buttonScale || new Animated.Value(0);
}
return (
<Animated.View style={this.getContainerStyle()}>
{this.renderButtons()}
<TouchableOpacity
onPress={() => this.fabOnPress()}
{...this.prepareFabProps()} activeOpacity={1}
>
{this.renderFab()}
</TouchableOpacity>
</Animated.View>
);
}
}
Fab.propTypes = {
...Animated.propTypes,
style: React.PropTypes.object,
active: React.PropTypes.bool,
direction: React.PropTypes.string,
containerStyle: React.PropTypes.object,
position: React.PropTypes.string,
};
const StyledFab = connectStyle('NativeBase.Fab', {}, mapPropsToStyleNames)(Fab);
export {
StyledFab as Fab,
};
|
admin/client/Signin/index.js
|
joerter/keystone
|
/**
* The signin page, it renders a page with a username and password input form.
*
* This is decoupled from the main app (in the "App/" folder) because we inject
* lots of data into the other screens (like the lists that exist) that we don't
* want to have injected here, so this is a completely separate route and template.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import SigninView from './SigninView';
ReactDOM.render(
<SigninView
brand={Keystone.brand}
from={Keystone.from}
logo={Keystone.logo}
user={Keystone.user}
userCanAccessKeystone={Keystone.userCanAccessKeystone}
/>,
document.getElementById('signin-view')
);
|
app/components/ViewerComponent.js
|
openexp/OpenEXP
|
// @flow
import React, { Component } from 'react';
import { Subscription, Observable } from 'rxjs';
import { isNil } from 'lodash';
import {
MUSE_CHANNELS,
EMOTIV_CHANNELS,
DEVICES,
VIEWER_DEFAULTS
} from '../constants/constants';
const Mousetrap = require('mousetrap');
interface Props {
signalQualityObservable: ?Observable;
deviceType: DEVICES;
plottingInterval: number;
}
interface State {
channels: Array<string>;
domain: number;
autoScale: boolean;
}
class ViewerComponent extends Component<Props, State> {
props: Props;
state: State;
graphView: ?HTMLElement;
signalQualitySubscription: Subscription;
constructor(props: Props) {
super(props);
this.state = {
...VIEWER_DEFAULTS,
channels:
props.deviceType === DEVICES.EMOTIV ? EMOTIV_CHANNELS : MUSE_CHANNELS
};
this.graphView = null;
this.signalQualitySubscription = null;
}
componentDidMount() {
this.graphView = document.querySelector('webview');
this.graphView.addEventListener('dom-ready', () => {
this.graphView.send('initGraph', {
plottingInterval: this.props.plottingInterval,
channels: this.state.channels,
domain: this.state.domain,
channelColours: this.state.channels.map(() => '#66B0A9')
});
this.setKeyListeners();
if (!isNil(this.props.signalQualityObservable)) {
this.subscribeToObservable(this.props.signalQualityObservable);
}
});
}
componentDidUpdate(prevProps: Props, prevState: State) {
if (
this.props.signalQualityObservable !== prevProps.signalQualityObservable
) {
this.subscribeToObservable(this.props.signalQualityObservable);
}
if (this.props.deviceType !== prevProps.deviceType) {
this.setState({
channels:
this.props.deviceType === DEVICES.MUSE
? MUSE_CHANNELS
: EMOTIV_CHANNELS
});
}
if (this.state.channels !== prevState.channels) {
this.graphView.send('updateChannels', this.state.channels);
}
if (this.state.domain !== prevState.domain) {
this.graphView.send('updateDomain', this.state.domain);
}
if (this.state.channels !== prevState.channels) {
this.graphView.send('updateChannels', this.state.channels);
}
if (this.state.autoScale !== prevState.autoScale) {
this.graphView.send('autoScale');
}
}
componentWillUnmount() {
if (!isNil(this.signalQualitySubscription)) {
this.signalQualitySubscription.unsubscribe();
}
Mousetrap.unbind('up');
Mousetrap.unbind('down');
}
setKeyListeners() {
Mousetrap.bind('up', () => this.graphView.send('zoomIn'));
Mousetrap.bind('down', () => this.graphView.send('zoomOut'));
}
subscribeToObservable(observable: any) {
if (!isNil(this.signalQualitySubscription)) {
this.signalQualitySubscription.unsubscribe();
}
this.signalQualitySubscription = observable.subscribe(
chunk => {
this.graphView.send('newData', chunk);
},
error => new Error(`Error in epochSubscription ${error}`)
);
}
render() {
return (
<webview
id="eegView"
src={`file://${__dirname}/viewer.html`}
autosize="true"
nodeintegration="true"
plugins="true"
/>
);
}
}
export default ViewerComponent;
|
src/static/containers/Login/index.js
|
KarimJedda/django-react-setup
|
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import classNames from 'classnames';
import { push } from 'react-router-redux';
import t from 'tcomb-form';
import * as actionCreators from '../../actions/auth';
const Form = t.form.Form;
const Login = t.struct({
email: t.String,
password: t.String
});
const LoginFormOptions = {
auto: 'placeholders',
help: <i>Hint: a@a.com / qw</i>,
fields: {
password: {
type: 'password',
}
}
};
class LoginView extends React.Component {
static propTypes = {
dispatch: React.PropTypes.func.isRequired,
isAuthenticated: React.PropTypes.bool.isRequired,
isAuthenticating: React.PropTypes.bool.isRequired,
statusText: React.PropTypes.string,
actions: React.PropTypes.shape({
authLoginUser: React.PropTypes.func.isRequired,
}).isRequired,
location: React.PropTypes.shape({
query: React.PropTypes.object.isRequired
})
};
constructor(props) {
super(props);
const redirectRoute = this.props.location ? this.props.location.query.next || '/' : '/';
this.state = {
formValues: {
email: '',
password: ''
},
redirectTo: redirectRoute
};
}
componentWillMount() {
if (this.props.isAuthenticated) {
this.props.dispatch(push('/'));
}
}
onFormChange = (value) => {
this.setState({ formValues: value });
};
login = (e) => {
e.preventDefault();
const value = this.loginForm.getValue();
if (value) {
this.props.actions.authLoginUser(value.email, value.password, this.state.redirectTo);
}
};
render() {
let statusText = null;
if (this.props.statusText) {
const statusTextClassNames = classNames({
'alert': true,
'alert-danger': this.props.statusText.indexOf('Authentication Error') === 0,
'alert-success': this.props.statusText.indexOf('Authentication Error') !== 0
});
statusText = (
<div className="row">
<div className="col-sm-12">
<div className={statusTextClassNames}>
{this.props.statusText}
</div>
</div>
</div>
);
}
return (
<div className="container login">
<h1 className="text-center">Login</h1>
<div className="login-container margin-top-medium">
{statusText}
<form onSubmit={this.login}>
<Form ref={(ref) => { this.loginForm = ref; }}
type={Login}
options={LoginFormOptions}
value={this.state.formValues}
onChange={this.onFormChange}
/>
<button disabled={this.props.isAuthenticating}
type="submit"
className="btn btn-default btn-block"
>
Submit
</button>
</form>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
isAuthenticated: state.auth.isAuthenticated,
isAuthenticating: state.auth.isAuthenticating,
statusText: state.auth.statusText
};
};
const mapDispatchToProps = (dispatch) => {
return {
dispatch,
actions: bindActionCreators(actionCreators, dispatch)
};
};
export default connect(mapStateToProps, mapDispatchToProps)(LoginView);
export { LoginView as LoginViewNotConnected };
|
app/components/listItem.js
|
SunsetFrost/ReactMusicPlayer
|
import React from 'react';
import './listitem.less'
let PubSub = require('pubsub-js');
let ListItem = React.createClass({
deleteHandler(item, event) {
event.stopPropagation();
PubSub.publish('DEL_MUSIC', item);
},
playMusic(item, e) {
PubSub.publish('PLAY_MUSIC', item);
},
render() {
let item = this.props.data;
return (
<li className={`row components-listitem${this.props.focus ? 'focus' : ''}`} onClick={this.playMusic.bind(this, item)}>
<p><strong>{item.title}</strong> - {item.artist}</p>
<p className="-col-auto delete" onClick={this.deleteHandler.bind(this, item)}></p>
</li>
);
}
});
export default ListItem;
|
source/containers/VideoPage/QuestionsBuilder/ChoiceListItem.js
|
mikey1384/twin-kle
|
import React from 'react';
import PropTypes from 'prop-types';
import { DragSource, DropTarget } from 'react-dnd';
import ItemTypes from 'constants/itemTypes';
import Icon from 'components/Icon';
import { Color } from 'constants/css';
const ListItemSource = {
beginDrag(props) {
return {
id: props.id,
questionIndex: props.questionIndex
};
},
isDragging(props, monitor) {
return (
props.id === monitor.getItem().id &&
props.questionIndex === monitor.getItem().questionIndex
);
},
endDrag(props) {
props.onDrop();
}
};
const ListItemTarget = {
hover(targetProps, monitor) {
const targetId = targetProps.id;
const sourceProps = monitor.getItem();
const sourceId = sourceProps.id;
const targetQuestionIndex = targetProps.questionIndex;
const sourceQuestionIndex = sourceProps.questionIndex;
if (targetQuestionIndex === sourceQuestionIndex && sourceId !== targetId) {
targetProps.onMove({ sourceId, targetId });
}
}
};
ChoiceListItem.propTypes = {
connectDragSource: PropTypes.func,
connectDropTarget: PropTypes.func,
deleted: PropTypes.bool,
isDragging: PropTypes.bool,
onSelect: PropTypes.func,
checked: PropTypes.bool,
checkDisabled: PropTypes.bool,
label: PropTypes.string,
placeholder: PropTypes.string
};
function ChoiceListItem({
checked,
checkDisabled,
connectDragSource,
connectDropTarget,
deleted,
isDragging,
label,
onSelect,
placeholder
}) {
return deleted
? renderListItem()
: connectDragSource(connectDropTarget(renderListItem()));
function renderListItem() {
return (
<nav
style={{
opacity: isDragging ? 0 : 1,
cursor: !checkDisabled && 'ns-resize'
}}
className="unselectable"
>
<main>
<section>
<div style={{ width: '10%' }}>
<Icon
icon="align-justify"
style={{ color: Color.borderGray() }}
/>
</div>
<div
style={{
width: '90%',
color: !label && '#999'
}}
>
{label || placeholder}
</div>
</section>
</main>
<aside>
<input
type="radio"
onChange={onSelect}
checked={checked}
disabled={checkDisabled}
style={{ cursor: !checkDisabled && 'pointer' }}
/>
</aside>
</nav>
);
}
}
export default DropTarget(ItemTypes.LIST_ITEM, ListItemTarget, connect => ({
connectDropTarget: connect.dropTarget()
}))(
DragSource(ItemTypes.LIST_ITEM, ListItemSource, (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
}))(ChoiceListItem)
);
|
packages/mineral-ui-icons/src/IconQueueMusic.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconQueueMusic(props: IconProps) {
const iconProps = {
rtl: true,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M15 6H3v2h12V6zm0 4H3v2h12v-2zM3 16h8v-2H3v2zM17 6v8.18c-.31-.11-.65-.18-1-.18-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3V8h3V6h-5z"/>
</g>
</Icon>
);
}
IconQueueMusic.displayName = 'IconQueueMusic';
IconQueueMusic.category = 'av';
|
test/fixtures/webpack-message-formatting/src/AppAliasUnknownExport.js
|
ConnectedHomes/create-react-web-app
|
import React, { Component } from 'react';
import { bar as bar2 } from './AppUnknownExport';
class App extends Component {
componentDidMount() {
bar2();
}
render() {
return <div />;
}
}
export default App;
|
app/containers/App/index.js
|
IntAlert/chatplayer
|
/**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import styled from 'styled-components';
import Helmet from 'react-helmet';
import Header from 'components/Header';
import Footer from 'components/Footer';
const AppWrapper = styled.div`
margin: 0 auto;
display: flex;
flex-direction: column;
`;
export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<AppWrapper>
<Helmet
titleTemplate="Tomato Challenge"
defaultTitle="Tomato Challenge"
meta={[
{ name: 'description', content: 'Tomato Challenge' },
]}
/>
{/* <Header /> */}
{React.Children.toArray(this.props.children)}
{/*<Footer />*/}
</AppWrapper>
);
}
}
|
src/js/components/common.js
|
otchy210/feedly-hatebu
|
import React from 'react';
import styled from 'styled-components';
import { hatenaBlue, feedlyGreen, alertRed, lineGrey } from './colors';
export const Section = styled.section`
`;
const H2 = styled.h2`
margin: 12px 0 0 0;
padding: 0 4px;
border-bottom: 2px solid;
border-image: linear-gradient(to right, ${feedlyGreen} 0%, ${hatenaBlue} 100%);
border-image-slice: 1;
line-height: 32px;
font-size: 20px;
font-weibht: normal;
`;
const Note = styled.small`
margin: 0 0 0 8px;
font-size: 12px;
line-height: 12px;
font-weight: normal;
color: ${alertRed};
`;
export const SectionTitle = ({ children, note }) => {
return <H2>
{children}
{note && <Note>{note}</Note>}
</H2>;
};
export const SectionBody = styled.div`
margin: 12px 0 0 0;
padding: 0 4px;
font-size: 16px;
line-height: 24px;
`;
export const Link = styled.a.attrs({target: '_blank'})`
color: #00c;
`;
export const RadioButton = styled.input.attrs({type: 'radio'})`
`;
export const RadioButtonLabel = styled.label`
display: inline-block;
padding: 8px;
border-style: solid;
border-width: 1px;
border-color: ${props => props.checked ? lineGrey : 'transparent'};
border-radius: 4px;
opacity: ${props => props.disabled ? '0.5' : '1'};
cursor: ${props => props.disabled ? 'default' : 'pointer'};
`;
|
kamanni/src/SchoolIntroduction.js
|
jam-world/kanmanni
|
import React, { Component } from 'react';
import image from './image/frontPage.jpg';
import {slideStyle, slideTxtStyle} from './slideStyle';
class SchoolIntroduction extends Component {
render() {
return (
<div style={slideStyle}>
<img src={image} style={{height: "100%", width: "100%"}}/>
<h1 style={{...{color: 'white'} ,...slideTxtStyle}}>学校介绍</h1>
</div>
)
};
};
export default SchoolIntroduction;
|
src/components/ProgressBar/ProgressBar.js
|
eliaslopezgt/ps-react-eli
|
import React from 'react';
import PropTypes from 'prop-types';
class ProgressBar extends React.Component {
getColor = () => {
if (this.props.percent === 100) return 'green';
return this.props.percent > 50 ? 'lightgreen' : 'red';
}
getWidthAsPercentOfTotalWidth = () => {
return parseInt(this.props.width * (this.props.percent / 100), 10);
}
render() {
const {percent, width, height} = this.props;
return (
<div style={{border: 'solid 1px lightgray', width: width}}>
<div style={{
width: this.getWidthAsPercentOfTotalWidth(),
height,
backgroundColor: this.getColor(percent)
}} />
</div>
);
}
}
ProgressBar.propTypes = {
/** Percent of progress completed */
percent: PropTypes.number.isRequired,
/** Bar width */
width: PropTypes.number.isRequired,
/** Bar height */
height: PropTypes.number
};
ProgressBar.defaultProps = {
height: 5
};
export default ProgressBar;
|
lib/components/Contracts/index.js
|
gmtcreators/atom-solidity
|
'use babel'
// Copyright 2018 Etheratom Authors
// This file is part of Etheratom.
// Etheratom is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Etheratom is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Etheratom. If not, see <http://www.gnu.org/licenses/>.
import React from 'react';
import { connect, Provider } from 'react-redux';
import { Collapse } from 'react-collapse';
import ContractCompiled from '../ContractCompiled';
import ContractExecution from '../ContractExecution';
import ErrorView from '../ErrorView';
import PropTypes from 'prop-types';
import { setErrors, addInterface } from '../../actions';
class CollapsedFile extends React.Component {
constructor(props) {
super(props);
this.helpers = props.helpers;
this.state = {
isOpened: false,
toggleBtnStyle: 'btn icon icon-unfold inline-block-tight',
toggleBtnTxt: 'Expand'
};
this._toggleCollapse = this._toggleCollapse.bind(this);
this._clearContract = this._clearContract.bind(this);
}
_toggleCollapse() {
const { isOpened } = this.state;
this.setState({ isOpened: !isOpened });
if (!isOpened) {
this.setState({
toggleBtnStyle: 'btn btn-success icon icon-fold inline-block-tight',
toggleBtnTxt: 'Collapse'
});
} else {
this.setState({
toggleBtnStyle: 'btn icon icon-unfold inline-block-tight',
toggleBtnTxt: 'Expand'
});
}
}
_clearContract() {
// TODO: clear interface from store
}
render() {
const { isOpened, toggleBtnStyle, toggleBtnTxt } = this.state;
const { fileName, compiled, deployed, compiling, interfaces } = this.props;
return (
<div>
<label className="label file-collapse-label">
<h4 className="text-success">{fileName}</h4>
<div>
<button className={toggleBtnStyle} onClick={this._toggleCollapse}>
{toggleBtnTxt}
</button>
</div>
</label>
<Collapse isOpened={isOpened}>
{
Object.keys(compiled.contracts[fileName]).map((contractName, index) => {
const regexVyp = /([a-zA-Z0-9\s_\\.\-():])+(.vy|.v.py|.vyper.py)$/g;
const bytecode = fileName.match(regexVyp)
? compiled.contracts[fileName][contractName].evm.bytecode.object.substring(2)
: compiled.contracts[fileName][contractName].evm.bytecode.object;
return (
<div id={contractName} className="contract-container" key={index}>
{
!deployed[contractName] && interfaces !== null && interfaces[contractName] && compiling === false &&
<ContractCompiled
contractName={contractName}
fileName={fileName}
bytecode={bytecode}
index={index}
helpers={this.helpers}
/>
}
{
deployed[contractName] &&
<ContractExecution
contractName={contractName}
bytecode={bytecode}
index={index}
helpers={this.helpers}
/>
}
</div>
);
})
}
</Collapse>
</div>
);
}
}
class Contracts extends React.Component {
constructor(props) {
super(props);
this.helpers = props.helpers;
}
componentDidUpdate(prevProps) {
const { sources, compiled } = this.props;
if (sources != prevProps.sources) {
// Start compilation of contracts from here
const workspaceElement = atom.views.getView(atom.workspace);
atom.commands.dispatch(workspaceElement, 'eth-interface:compile');
}
if (compiled !== null && compiled !== prevProps.compiled) {
if (compiled.contracts) {
for (const file of Object.entries(compiled.contracts)) {
for (const [contractName, contract] of Object.entries(file[1])) {
// Add interface to redux
const ContractABI = contract.abi;
this.props.addInterface({ contractName, ContractABI });
}
}
}
if (compiled.errors) {
this.props.setErrors(compiled.errors);
}
}
}
render() {
const { compiled, deployed, compiling, interfaces } = this.props;
return (
<Provider store={this.props.store}>
<div id="compiled-code" className="compiled-code">
{
compiled && compiled.contracts &&
Object.keys(compiled.contracts).map((fileName, index) => {
return (
<CollapsedFile
fileName={fileName}
compiled={compiled}
deployed={deployed}
compiling={compiling}
interfaces={interfaces}
helpers={this.helpers}
key={index}
/>
);
})
}
{
!compiled &&
<h2 className="text-warning no-header">No compiled contract!</h2>
}
<div id="compiled-error" className="error-container">
<ErrorView />
</div>
</div>
</Provider>
);
}
}
CollapsedFile.propTypes = {
helpers: PropTypes.any.isRequired,
contractName: PropTypes.string,
bytecode: PropTypes.string,
index: PropTypes.number,
instances: PropTypes.any,
interfaces: PropTypes.object,
fileName: PropTypes.string,
compiled: PropTypes.object,
deployed: PropTypes.any,
compiling: PropTypes.bool,
};
Contracts.propTypes = {
sources: PropTypes.object,
helpers: PropTypes.any.isRequired,
store: PropTypes.any.isRequired,
compiled: PropTypes.object,
deployed: PropTypes.any,
compiling: PropTypes.bool,
interfaces: PropTypes.object,
addInterface: PropTypes.func,
setErrors: PropTypes.func
};
const mapStateToProps = ({ contract }) => {
const { sources, compiled, deployed, compiling, interfaces } = contract;
return { sources, compiled, deployed, compiling, interfaces };
};
export default connect(mapStateToProps, { addInterface, setErrors })(Contracts);
|
src/NavItem.js
|
lo1tuma/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const NavItem = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
linkId: React.PropTypes.string,
onSelect: React.PropTypes.func,
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
href: React.PropTypes.string,
role: React.PropTypes.string,
title: React.PropTypes.node,
eventKey: React.PropTypes.any,
target: React.PropTypes.string,
'aria-controls': React.PropTypes.string
},
getDefaultProps() {
return {
href: '#'
};
},
render() {
let {
role,
linkId,
disabled,
active,
href,
title,
target,
children,
'aria-controls': ariaControls, // eslint-disable-line react/prop-types
...props } = this.props;
let classes = {
active,
disabled
};
let linkProps = {
role,
href,
title,
target,
id: linkId,
onClick: this.handleClick,
ref: 'anchor'
};
if (!role && href === '#') {
linkProps.role = 'button';
}
return (
<li {...props} role='presentation' className={classNames(props.className, classes)}>
<a {...linkProps} aria-selected={active} aria-controls={ariaControls}>
{ children }
</a>
</li>
);
},
handleClick(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
}
}
}
});
export default NavItem;
|
src/client/components/message/customerSuccess.js
|
uuchat/uuchat
|
import React, { Component } from 'react';
import { Row, Col, Modal, notification } from 'antd';
import io from 'socket.io-client';
import Header from '../user/header';
import ChatMenu from '../menu/chatMenu';
import ChatSend from './chatSend';
import ChatMessage from './chatMessage';
import ChatEmpty from './chatEmpty';
import ChatUser from '../user/chatUser';
import ChatHistory from './chatHistory';
import MenuSetting from '../menu/chatMenuSetting';
import '../../static/css/customerSuccess.css';
let notifyKey = '';
class CustomerSuccess extends Component{
constructor(props){
super(props);
this.state = {
socket: {},
csid: localStorage['uuchat.csid'] || '',
name: localStorage['uuchat.name'] || '',
displayName: localStorage['uuchat.displayName'] || '',
email: localStorage['uuchat.email'] || '',
avatar: localStorage['uuchat.avatar'] || '../../static/images/contact.png',
bgThemeImg: localStorage['bgThemeImg'] || '',
bgThemeOpacity: localStorage['bgThemeOpacity'] || 0.7,
status: 1, // 1:online,2:offline, 3:connect error
menuType: 1, // 1:onlineChat, 2:historyChat, 3:settings
menuSetting: 'Account',
historyChat: {},
chatLists: {},
chatActive: {}
};
}
componentDidMount(){
this.createSocket();
}
createSocket = () => {
let sio = io('/cs', {
forceNew: true,
reconnectionAttempts: 5,
reconnectionDelay: 2000 ,
timeout: 10000
});
sio.on('connect', this.customerSuccessConnect);
sio.on('connect_error', this.customerSuccessConnectErr);
sio.on('reconnect', this.socketReconnect);
sio.on('cs.customer.one', this.csCustomerOne);
sio.on('cs.customer.list', this.csCustomerList);
sio.on('cs.dispatch', this.csDispatch);
sio.on('cs.need.login', this.csNeedLogin);
sio.on('c.message', this.cMessage);
sio.on('c.timeout', this.deleteChat);
sio.on('c.disconnect', this.cDisconnect);
sio.on('cs.customer.offline', this.csCustomerOffline);
sio.on('cs.shortcut', this.csShortcuts);
sio.on('error', this.socketError);
this.setState({
socket: sio
});
};
csCustomerList = (data) => {
let {chatLists, chatActive} = this.state;
this.setState({
chatLists: chatLists,
chatActive: chatActive
});
};
csCustomerOne = (data) => {
let {chatLists, chatActive} = this.state;
chatLists[data.cid] = {
cid: data.cid,
marked: data.marked,
info: data.info,
name: data.name,
notifies: 0,
status: 1,
active: chatActive === null,
messageLists: [],
pageNum: 2,
isLoading: false,
hasMoreHistoryChat: true
};
if (!chatActive.cid) {
chatActive.cid = data.cid;
}
this.getChatHistory(data.cid);
this.setState({
chatLists: chatLists,
chatActive: chatActive
});
};
csDispatch = (cid, name, info) => {
this.csCustomerOne({
cid: cid,
name: name,
info: info,
marked: -1
});
};
csNeedLogin = (fn) => {
fn(true);
this.state.socket.disconnect();
window.location.href="/";
};
cMessage = (cid, msg) => {
let {chatLists, chatActive} = this.state;
if (cid !== chatActive.cid) {
chatLists[cid].notifies++;
}
chatLists[cid].messageLists.push({
msgAvatar: '',
msgText: msg,
msgType: 0,
msgTime: new Date()
});
this.setState({
chatLists: chatLists
});
};
cDisconnect = (cid) => {
this.deleteChat(cid);
};
csCustomerOffline = (data) => {
let {chatLists, chatActive} = this.state;
let cid = data.cid;
!chatActive.cid && (chatActive.cid = cid);
data.msg.map((chat) =>
chatLists[cid] = {
cid: cid,
marked: 0,
info: data.info,
name: cid.split('-')[0],
notifies: 0,
status: 2,
active: chatActive === null,
messageLists: [{
msgAvatar: '',
msgText: {
email: data.email,
msg: data.msg,
type: chat.type,
name: cid.substr(0, 6)
},
msgType: chat.type,
msgTime: data.updatedAt
}],
pageNum: 0,
isLoading: false,
hasMoreHistoryChat: true
}
);
this.setState({
chatActive: chatActive,
chatLists: chatLists
});
};
socketReconnect = () => {};
socketError = () => {};
customerSuccessConnect = () => {
let status = this.state.status;
if (status === 3) {
notification.close("errNotifyKey");
notifyKey = "";
this.setState({
status: 1
});
}
};
customerSuccessConnectErr = () => {
if (notifyKey === "") {
notification.open({
message: 'Server error',
top: 50,
duration: null,
key: 'errNotifyKey',
description: 'The server has offline!!!!.'
});
notifyKey = "nKey";
}
this.setState({
status: 3,
chatActive: {
cid: ''
},
chatLists: {}
});
};
toggleChat = (name, cid) => {
let {chatActive, chatLists} = this.state;
if (cid === chatActive.cid) {
return false;
}
chatLists[chatActive.cid].active = false;
chatLists[chatActive.cid].notifies = 0;
chatActive.cid = cid;
this.setState({
chatLists: chatLists,
chatActive: chatActive
});
};
sendMessageToCustomer = (msg) => {
let {chatActive, chatLists, avatar, socket} = this.state;
let cid = chatActive.cid;
if (msg !== '') {
let d = new Date();
let messageEvent = 'cs.message';
chatLists[cid].messageLists.push({
msgAvatar: avatar,
msgText: msg,
msgType: 1,
msgTime: d
});
this.setState({
chatLists: chatLists
});
if (chatLists[chatActive.cid].status === 2) {
messageEvent = 'cs.offlineMessage';
}
socket.emit(messageEvent, cid, msg, function (success) {
if (success) {
document.querySelector('.t-' + d.getTime()).className += ' done';
}
});
}
};
closeChat = (cid) => {
let _self = this;
Modal.confirm({
title: 'Do you Want to close this customer?',
content: 'If yes , the customer will be remove',
okText: 'Yes',
cancelText: 'No',
onOk() {
_self.state.socket.emit('cs.closeDialog', cid, function(flag){
_self.deleteChat(cid);
});
}
});
};
transferChat = (cid) => {
this.deleteChat(cid);
};
statusHandle = (type) => {
this.state.socket.emit('cs.status', this.state.chatActive.cid, type, function(state){});
};
getChatHistory = (cid) => {
let _self = this;
let {csid, avatar, chatLists} = this.state;
fetch('/messages/customer/'+cid+'/cs/'+csid)
.then((data) => data.json())
.then(d =>{
d.msg.map((chat) =>
chatLists[cid].messageLists.push({
msgAvatar: (chat.type === 1 || chat.type === 2) ? avatar : '',
msgText: chat.msg,
msgType: chat.type,
msgTime: chat.createdAt
})
);
_self.setState({
chatLists: chatLists
});
})
.catch(function(e){});
};
csShortcuts = (action, shortcut) => {
shortcut.action = action;
let shortList = JSON.parse(localStorage.getItem('shortcutList'));
let hasExist = false;
if (action === 'INSERT') {
for (let i = 0, l = shortList.length; i < l; i++) {
if (shortList[i].shortcut === shortcut.shortcut) {
hasExist = true;
break;
}
}
}
!hasExist && localStorage.setItem('newShortcut', JSON.stringify(shortcut));
};
rateFeedBack = () => {
let {chatLists, chatActive, avatar} = this.state;
chatLists[chatActive.cid].messageLists.push({
msgAvatar: avatar,
msgText: 'Invitation evaluation has been sent',
msgType: 1,
msgTime: new Date()
});
this.setState({
chatLists: chatLists
});
};
deleteChat = (cid) => {
let {chatLists, chatActive} = this.state;
delete chatLists[cid];
if (Object.keys(chatLists).length === 0) {
chatActive.cid = '';
} else if (cid === chatActive.cid) {
for (let k in chatLists) {
chatActive.cid = k;
break;
}
}
this.setState({
chatLists: chatLists,
chatActive: chatActive
});
};
render(){
let {status, avatar, csid, socket, bgThemeImg, bgThemeOpacity, chatLists, chatActive, menuType, historyChat, menuSetting} = this.state;
let bgStyle = {};
if (bgThemeImg && status === 1) {
bgThemeImg = bgThemeImg.split('::');
if (bgThemeImg[0] === 'photo') {
bgStyle.backgroundImage = 'url('+bgThemeImg[1]+'?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1280&fit=max)';
} else if (bgThemeImg[0] === 'color') {
bgStyle.background = bgThemeImg[1];
}
}
return (
<div className={"uuchat-customerSuccess " + ((status !== 1) ? " off " : "") +(bgThemeImg[1] ? "theme" : "")}
style={bgStyle}>
<Header customerSuccess={this} />
<Row className="customerSuccess-main" style={{background: 'rgba(255, 255, 255, '+bgThemeOpacity+')'}}>
<Col xs={24} sm={7} md={7} lg={6} xl={6}>
<ChatMenu customerSuccess={this} />
</Col>
<Col xs={24} sm={11} md={11} lg={12} xl={12}>
<div className="customerSuccess-content">
{
(menuType === 1)
&& chatActive.cid
&& <div>
<ChatMessage
socket={socket && socket}
csid={csid}
avatar={avatar}
transferChat={this.transferChat}
customerSuccess={this}
chat={chatLists[chatActive.cid]}
/>
<ChatSend
sendMessage={this.sendMessageToCustomer}
statusHandle={this.statusHandle}
cid={chatActive.cid}
csid={csid}
socket={socket}
rateFeedBack={this.rateFeedBack}
/>
</div>
}
{
(menuType === 1) && !chatActive.cid && <ChatEmpty />
}
{
(menuType === 2) && <ChatHistory historyChat={historyChat} csid={csid} />
}
{
(menuType === 3) && <MenuSetting menu={menuSetting} customerSuccess={this} />
}
</div>
</Col>
<Col xs={24} sm={6} md={6} lg={6} xl={6}>
<div className="customerSuccess-right">
{menuType === 1 && chatActive.cid && <ChatUser info={chatLists[chatActive.cid].info} />}
{menuType === 2 && historyChat.cid && <ChatUser info={historyChat.chatsArr.info} />}
</div>
</Col>
</Row>
</div>
);
}
}
export default CustomerSuccess;
|
src/components/ContentWrapper/ContentWrapper.js
|
falmar/react-adm-lte
|
import React from 'react'
import PropTypes from 'prop-types'
const ContentWrapper = ({children}) => {
return (
<div className='content-wrapper'>
{children}
</div>
)
}
ContentWrapper.propTypes = {
children: PropTypes.node
}
export default ContentWrapper
|
ide/static/js/content.js
|
Cloud-CV/IDE
|
import React from 'react';
import Canvas from './canvas';
import Pane from './pane';
import SetParams from './setParams';
import Tooltip from './tooltip'
import TopBar from './topBar';
import Tabs from './tabs';
import data from './data';
import netLayout from './netLayout_vertical';
import Modal from 'react-modal';
import ModelZoo from './modelZoo';
import Login from './login';
import ImportTextbox from './importTextbox';
import UrlImportModal from './urlImportModal';
import UserProfile from './UserProfile';
import UpdateHistoryModal from './updateHistoryModal';
import CommentSidebar from './CommentSidebar';
import FilterBar from './filterBar';
import $ from 'jquery'
const infoStyle = {
content : {
top : '50%',
left : '55%',
right : '60%',
bottom : 'auto',
marginRight : '-50%',
transform : 'translate(-50%, -50%)',
borderRadius : '8px'
},
overlay: {
zIndex : 100
}
};
class Content extends React.Component {
constructor(props) {
super(props);
this.state = {
net: {},
net_name: 'Untitled',
networkId: 0,
draggingLayer: null,
selectedLayer: null,
commentOnLayer: null,
hoveredLayer: null,
nextLayerId: 0,
rebuildNet: false,
selectedPhase: 0,
error: [],
info: [],
load: false,
modalIsOpen: false,
totalParameters: 0,
modelConfig: null,
modelFramework: 'caffe',
isShared: false,
isForked: false,
socket: null,
randomUserId: null,
highlightColor: '#000000'
};
this.addNewLayer = this.addNewLayer.bind(this);
this.changeSelectedLayer = this.changeSelectedLayer.bind(this);
this.changeHoveredLayer = this.changeHoveredLayer.bind(this);
this.componentWillMount = this.componentWillMount.bind(this);
this.modifyLayer = this.modifyLayer.bind(this);
this.setDraggingLayer = this.setDraggingLayer.bind(this);
this.changeNetName = this.changeNetName.bind(this);
this.adjustParameters = this.adjustParameters.bind(this);
this.modifyLayerParams = this.modifyLayerParams.bind(this);
this.deleteLayer = this.deleteLayer.bind(this);
this.exportPrep = this.exportPrep.bind(this);
this.exportNet = this.exportNet.bind(this);
this.importNet = this.importNet.bind(this);
this.changeNetStatus = this.changeNetStatus.bind(this);
this.changeNetPhase = this.changeNetPhase.bind(this);
this.dismissError = this.dismissError.bind(this);
this.addError = this.addError.bind(this);
this.dismissAllErrors = this.dismissAllErrors.bind(this);
this.addInfo = this.addInfo.bind(this);
this.dismissInfo = this.dismissInfo.bind(this);
this.copyTrain = this.copyTrain.bind(this);
this.trainOnly = this.trainOnly.bind(this);
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
this.saveDb = this.saveDb.bind(this);
this.loadDb = this.loadDb.bind(this);
this.infoModal = this.infoModal.bind(this);
this.faqModal = this.faqModal.bind(this);
this.toggleSidebar = this.toggleSidebar.bind(this);
this.zooModal = this.zooModal.bind(this);
this.textboxModal = this.textboxModal.bind(this);
this.urlModal = this.urlModal.bind(this);
this.updateHistoryModal =this.updateHistoryModal.bind(this);
this.setModelConfig = this.setModelConfig.bind(this);
this.setModelFramework = this.setModelFramework.bind(this);
this.setModelUrl = this.setModelUrl.bind(this);
this.setModelFrameworkUrl = this.setModelFrameworkUrl.bind(this);
this.loadLayerShapes = this.loadLayerShapes.bind(this);
this.calculateParameters = this.calculateParameters.bind(this);
this.getLayerParameters = this.getLayerParameters.bind(this);
this.updateLayerShape = this.updateLayerShape.bind(this);
this.createSocket = this.createSocket.bind(this);
this.onSocketConnect = this.onSocketConnect.bind(this);
this.sendSocketMessage = this.sendSocketMessage.bind(this);
this.onSocketMessage = this.onSocketMessage.bind(this);
this.onSocketOpen = this.onSocketOpen.bind(this);
this.onSocketError = this.onSocketError.bind(this);
this.waitForConnection = this.waitForConnection.bind(this);
this.setUserId = this.setUserId.bind(this);
this.getUserId = this.getUserId.bind(this);
this.getUserName = this.getUserName.bind(this);
this.setUserName = this.setUserName.bind(this);
this.modalContent = null;
this.modalHeader = null;
// Might need to improve the logic of clickEvent
this.clickEvent = false;
this.handleClick = this.handleClick.bind(this);
this.performSharedUpdate = this.performSharedUpdate.bind(this);
this.performSharedAdd = this.performSharedAdd.bind(this);
this.performSharedDelete = this.performSharedDelete.bind(this);
this.addHighlightOnLayer = this.addHighlightOnLayer.bind(this);
this.addSharedComment = this.addSharedComment.bind(this);
this.changeCommentOnLayer = this.changeCommentOnLayer.bind(this);
this.getRandomColor = this.getRandomColor.bind(this);
this.downloadModel = this.downloadModel.bind(this);
}
getRandomColor() {
var rint = Math.round(0xffffff * Math.random());
return ('#0' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1');
}
createSocket(url) {
return new WebSocket(url);
}
onSocketConnect() {
// binder for socket
const socket = this.state.socket;
socket.onopen = this.onSocketOpen;
socket.onmessage = this.onSocketMessage;
socket.onerror = this.onSocketError;
}
onSocketOpen() {
// socket opening goes here
// console.log('socket opened for RTC....');
}
onSocketMessage(message) {
// message received on socket
let data = JSON.parse(message['data']);
//let rebuildNet = false;
//let nextLayerId = this.state.nextLayerId;
const net = this.state.net;
if(data['action'] == 'ExportNet') {
if(data['result'] == 'success') {
this.downloadModel(data);
}
else {
this.addError(data['error']);
}
}
else if(data['action'] == 'UpdateHighlight' && data['randomId'] != this.state.randomId) {
let addHighlightToId = data['addHighlightTo'];
let removeHighlightFromId = data['removeHighlightFrom'];
let username = data['username'];
if (addHighlightToId != null) {
if (('highlight' in net[addHighlightToId]) == false) {
net[addHighlightToId]['highlight'] = [];
net[addHighlightToId]['highlightColor'] = [];
}
net[addHighlightToId]['highlight'].push(username);
net[addHighlightToId]['highlightColor'].push(data['highlightColor'])
}
if (removeHighlightFromId != null) {
let index = net[removeHighlightFromId]['highlight'].indexOf(removeHighlightFromId);
net[removeHighlightFromId]['highlight'].splice(index, 1);
net[removeHighlightFromId]['highlightColor'].splice(index, 1);
}
this.setState({
net: net
});
}
else {
if (data['randomId'] != this.state.randomId) {
if(data['action'] == 'UpdateParam') {
if (data['isProp']) {
net[data['layerId']]['props'][data['param']] = data['value'];
}
else {
net[data['layerId']]['params'][data['param']][0] = data['value'];
}
this.setState({ net: net });
}
else if (data['action'] == 'AddLayer') {
this.addNewLayer(data['layer'], data['prevLayerId'], false);
this.changeNetStatus(true);
}
else if(data['action'] == 'DeleteLayer') {
this.deleteLayer(data['layerId'], false);
}
else if(data['action'] == 'AddComment') {
if (('comments' in net[data['layerId']]) == false) {
net[data['layerId']]['comments'] = [];
}
net[data['layerId']]['comments'].push(data['comment']);
this.setState({ net });
}
}
}
}
sendSocketMessage(message) {
// generalized method to send message to socket
const socket = this.state.socket;
socket.send(JSON.stringify(message));
}
onSocketError(error) {
// socket error handling goes here
this.addError(error);
}
waitForConnection(callback, interval=100) {
// delay hook used while creating a new socket
const socket = this.state.socket;
if (socket != null && socket.readyState === 1) {
callback();
}
else {
var that = this;
setTimeout(function () {
that.waitForConnection(callback, interval);
}, interval);
}
}
performSharedUpdate(layerId, param, value, isProp) {
// method to handle pre-processing of message before sending
// through a socket based on type of action, will be extended further
// as per requirement of message types.
let msg = '';
msg = 'Layer parameter updated';
this.sendSocketMessage({
layerId: layerId,
param: param,
value: value,
isProp: isProp,
action: 'UpdateParam',
message: msg,
nextLayerId: this.state.nextLayerId,
randomId: this.state.randomId
});
}
performSharedAdd(layer, prevLayerId, nextLayerId, layerId) {
let msg = 'New layer added';
this.sendSocketMessage({
layer: layer,
prevLayerId: prevLayerId,
layerId: layerId,
action: 'AddLayer',
message: msg,
nextLayerId: nextLayerId,
randomId: this.state.randomId
})
}
performSharedDelete(net, layerId, nextLayerId) {
let msg = 'Delete existing layer';
this.sendSocketMessage({
layerId: layerId,
nextLayerId: nextLayerId,
action: 'DeleteLayer',
message: msg,
randomId: this.state.randomId
})
}
addHighlightOnLayer(layerId, previousLayerId) {
this.sendSocketMessage({
addHighlightTo: layerId,
removeHighlightFrom: previousLayerId,
userId: this.getUserId(),
action: 'UpdateHighlight',
randomId: this.state.randomId,
highlightColor: this.state.highlightColor,
username: this.getUserName()
})
}
addSharedComment(layerId, comment) {
this.sendSocketMessage({
layerId: layerId,
comment: comment,
action: 'AddComment',
randomId: this.state.randomId
})
}
downloadModel(response) {
const downloadAnchor = document.getElementById('download');
downloadAnchor.download = response.name;
downloadAnchor.href = response.url;
downloadAnchor.click();
if ('customLayers' in response && response.customLayers.length !== 0) {
this.addInfo(
<span>
<span>This network uses custom layers, to download click on: </span>
{response.customLayers.map((layer, index) => {
return (
<span key={index}>
<a onClick={function() {
downloadAnchor.download = layer.filename;
downloadAnchor.href = layer.url;
downloadAnchor.click();
}} style={{fontWeight: 'bold'}}>
{layer.name}
</a>
{index != response.customLayers.length-1 && <span>, </span>}
</span>
);
})}
</span>
);
}
}
openModal() {
this.setState({ modalIsOpen: true });
}
closeModal() {
this.setState({ modalIsOpen: false });
}
setUserId(user_id) {
UserProfile.setUserId(user_id);
}
getUserId() {
return UserProfile.getUserId();
}
setUserName(name) {
UserProfile.setUsername(name);
}
getUserName() {
return UserProfile.getUsername();
}
addNewLayer(layer, prevLayerId, publishUpdate=true) {
const net = this.state.net;
const layerId = `l${this.state.nextLayerId}`;
const nextLayerId = this.state.nextLayerId;
var totalParameters = this.state.totalParameters;
// shared addition of layer connections
if (publishUpdate == false) {
if (Array.isArray(prevLayerId)) {
for (var i=0;i<prevLayerId.length;i++) {
net[prevLayerId[i]]['connection']['output'].push(layerId);
}
}
else
net[prevLayerId]['connection']['output'].push(layerId);
}
net[layerId] = layer;
// Parsing for integer parameters when new layers are added as by default all params are string
// In case some parameters are missed please cover them too
var intParams = ["crop_size", "num_output", "new_height", "new_width", "height", "width", "kernel_h", "kernel_w",
"kernel_d", "stride_h", "stride_w", "stride_d", "pad_h", "pad_w", "pad_d", "size_h", "size_w",
"size_d", "n"];
Object.keys(net[layerId].params).forEach(param => {
if (intParams.includes(param)){
net[layerId].params[param][0] = parseInt(net[layerId].params[param][0]);
if (isNaN(net[layerId].params[param][0]))
net[layerId].params[param][0] = 0;
}
});
this.updateLayerShape(net, layerId);
// Check for only layers with valid shape
if (net[layerId]['shape']['input'] != null && net[layerId]['shape']['output'] != null) {
net[layerId]['info']['parameters'] = this.getLayerParameters(net[layerId], net);
totalParameters += net[layerId]['info']['parameters'];
}
this.setState({ net, nextLayerId: this.state.nextLayerId + 1, totalParameters: totalParameters });
// if model is in RTC mode send updates to respective sockets
if (this.state.isShared && !this.state.isForked && publishUpdate) {
this.performSharedAdd(net[layerId], prevLayerId, nextLayerId + 1, layerId);
}
}
changeCommentOnLayer(layerId) {
this.setState({
commentOnLayer: layerId
});
}
changeSelectedLayer(layerId) {
const net = this.state.net;
if (this.state.selectedLayer) {
// remove css from previously selected layer
net[this.state.selectedLayer].info.class = '';
}
if (layerId) {
// css when layer is selected
net[layerId].info.class = 'selected';
}
if (this.state.isShared && !this.state.isForked) {
this.addHighlightOnLayer(layerId, this.state.selectedLayer);
}
this.setState({ net, selectedLayer: layerId });
}
changeHoveredLayer(layerId) {
const net = this.state.net;
if (this.state.hoveredLayer && this.state.hoveredLayer in net) {
// remove css from previously selected layer
net[this.state.hoveredLayer].info.class = '';
}
if (layerId) {
// css when layer is selected
net[layerId].info.class = 'hover';
}
this.setState({ net, hoveredLayer: layerId });
}
modifyLayer(layer, layerId = this.state.selectedLayer) {
const net = this.state.net;
var oldLayerParams = this.state.totalParameters;
if (net[layerId]['shape']['input'] != null && net[layerId]['shape']['output'] != null)
oldLayerParams -= net[layerId]['info']['parameters'];
net[layerId] = layer;
this.updateLayerShape(net, layerId);
if (net[layerId]['shape']['input']!=null && net[layerId]['shape']['output']!=null) {
net[layerId]['info']['parameters'] = this.getLayerParameters(net[layerId], net);
oldLayerParams += net[layerId]['info']['parameters'];
}
this.setState({ net: net, totalParameters: oldLayerParams });
}
modifyLayerParams(layer, layerId = this.state.selectedLayer) {
const net = this.state.net;
let index;
if (this.state.selectedPhase === 1 && net[layerId].info.phase === null) {
// we need to break this common layer for each phase
const testLayer = JSON.parse(JSON.stringify(layer));
const trainLayer = JSON.parse(JSON.stringify(net[layerId]));
testLayer.info.phase = 1;
(testLayer.connection.output).forEach(outputId => {
if (net[outputId].info.phase === 0) {
index = testLayer.connection.output.indexOf(outputId);
testLayer.connection.output.splice(index, 1);
index = net[outputId].connection.input.indexOf(layerId);
net[outputId].connection.input.splice(index, 1);
}
});
(testLayer.connection.input).forEach(inputId => {
if (net[inputId].info.phase === 0) {
index = testLayer.connection.input.indexOf(inputId);
testLayer.connection.input.splice(index, 1);
index = net[inputId].connection.output.indexOf(layerId);
net[inputId].connection.output.splice(index, 1);
}
});
net[layerId] = testLayer;
this.setState({ net });
trainLayer.info.phase = 0;
trainLayer.props.name = `${data[trainLayer.info.type].name}${this.state.nextLayerId}`;
(trainLayer.connection.output).forEach(outputId => {
if (net[outputId].info.phase === 1) {
index = trainLayer.connection.output.indexOf(outputId);
trainLayer.connection.output.splice(index, 1);
}
});
(trainLayer.connection.input).forEach(inputId => {
if (net[inputId].info.phase === 1) {
index = trainLayer.connection.input.indexOf(inputId);
trainLayer.connection.input.splice(index, 1);
}
});
const nextLayerId = `l${this.state.nextLayerId}`;
(trainLayer.connection.output).forEach(outputId => {
net[outputId].connection.input.push(nextLayerId);
});
const inputIds = [];
(trainLayer.connection.input).forEach(inputId => {
net[inputId].connection.output.push(nextLayerId);
inputIds.push(inputId)
});
this.addNewLayer(trainLayer, inputIds);
// if model is in RTC mode addNewLayer will send updates to respective sockets
} else {
net[layerId] = layer;
this.setState({ net });
}
}
deleteLayer(layerId, publishUpdate=true) {
const net = this.state.net;
const input = net[layerId].connection.input;
const output = net[layerId].connection.output;
const layerIdNum = parseInt(layerId.substring(1,layerId.length)); //numeric value of the layerId
const nextLayerId = this.state.nextLayerId - 1 == layerIdNum ? layerIdNum : this.state.nextLayerId;
//if last layer was deleted nextLayerId is replaced by deleted layer's id
var totalParameters = this.state.totalParameters;
let index;
totalParameters -= this.getLayerParameters(net[layerId], net);
delete net[layerId];
input.forEach(inputId => {
index = net[inputId].connection.output.indexOf(layerId);
net[inputId].connection.output.splice(index, 1);
});
output.forEach(outputId => {
index = net[outputId].connection.input.indexOf(layerId);
net[outputId].connection.input.splice(index, 1);
});
this.setState({ net, selectedLayer: null, nextLayerId: nextLayerId, totalParameters: totalParameters });
// if model is in RTC mode send updates to respective sockets
// to avoid infinite loop of deletion over multiple session
if (this.state.isShared && !this.state.isForked && publishUpdate == true) {
this.performSharedDelete(net, layerId, nextLayerId);
}
}
updateLayerShape(net, layerId) {
const netData = JSON.parse(JSON.stringify(net));
Object.keys(netData[layerId].params).forEach(param => {
netData[layerId].params[param] = netData[layerId].params[param][0];
});
net[layerId]['shape'] = {};
net[layerId]['shape']['input'] = null;
net[layerId]['shape']['output'] = null;
net[layerId]['info']['parameters'] = 0;
$.ajax({
url: 'layer_parameter/',
dataType: 'json',
type: 'POST',
async: false,
data: {
net: JSON.stringify(netData),
layerId: layerId
},
success : function (response) {
if (response.result == "success") {
if (response.net[layerId]['shape']['input'] != null)
net[layerId]['shape']['input'] = response.net[layerId]['shape']['input'].slice();
if (response.net[layerId]['shape']['output'] != null)
net[layerId]['shape']['output'] = response.net[layerId]['shape']['output'].slice();
}
else
this.addError(response.error);
}.bind(this)
});
}
getLayerParameters(layer, net) {
// check for layers with no shape to avoid errors
// this can be improved further.
if (layer['shape']['input'] == null || layer['shape']['output'] == null) {
return 0;
}
// obtain the total parameters of the model
var weight_params = 0;
var bias_params = 0;
var filter_layers = ["Convolution", "Deconvolution"];
var fc_layers = ["InnerProduct", "Embed", "Recurrent", "LSTM"];
if(filter_layers.includes(layer.info.type)) {
// if layer is Conv or DeConv calculating total parameter of the layer using:
// N_Input * K_H * K_W * N_Output
var kernel_params = 1;
if('kernel_h' in layer.params && layer.params['kernel_h'][0] != '')
kernel_params *= layer.params['kernel_h'][0];
if('kernel_w' in layer.params && layer.params['kernel_w'][0] != '')
kernel_params *= layer.params['kernel_w'][0];
if('kernel_d' in layer.params && layer.params['kernel_d'][0] != '')
kernel_params *= layer.params['kernel_d'][0];
weight_params = layer.shape['input'][0] * kernel_params * layer.params['num_output'][0];
bias_params += layer.params['num_output'][0];
}
else if(fc_layers.includes(layer.info.type)) {
// if layer is one of Recurrent layer or Fully Connected layers calculate parameters using:
// Num_Input * Num_Ouput
// if previous layer is D-dimensional then obtain the total inputs by (N1xN2x...xNd)
var inputParams = 1;
for(var i=0;i<layer.shape['input'].length;i++) {
if(layer.shape['input'][i] != 0)
inputParams *= layer.shape['input'][i];
}
weight_params = inputParams * layer.params['num_output'][0];
bias_params = layer.params['num_output'][0];
}
if(layer.info.type == "BatchNorm") {
let cnt = 2;
if(layer.connection['output'].length > 0) {
const childLayer = net[layer.connection['output'][0]];
if(childLayer.info.type == "Scale") {
if(childLayer.params['scale'][0] == true)
cnt +=1
if(childLayer.params['bias_term'][0] == true)
cnt +=1;
}
}
weight_params = cnt * layer.shape['output'][0];
}
if('use_bias' in layer.params) {
if (layer.params['use_bias'][0] == false)
bias_params = 0;
}
// Update the total parameters of model after considering this layer.
return (weight_params + bias_params);
}
calculateParameters(net) {
// Iterate over model's each layer & separately add the contribution of each layer
var totalParameters = 0;
Object.keys(net).sort().forEach(layerId => {
const layer = net[layerId];
net[layerId]['info']['parameters'] = this.getLayerParameters(layer, net);
totalParameters += net[layerId]['info']['parameters'];
});
this.setState({ net: net, totalParameters: totalParameters});
}
loadLayerShapes() {
this.dismissAllErrors();
// Making call to endpoint inorder to obtain shape of each layer i.e. input & output shape
const netData = JSON.parse(JSON.stringify(this.state.net));
$.ajax({
url: 'model_parameter/',
dataType: 'json',
type: 'POST',
data: {
net: JSON.stringify(netData)
},
success : function (response) {
const net = response.net;
// call to intermediate method which will iterate over layers & calculate the parameters separately
this.calculateParameters(net);
// update the net object with shape attributes added
this.setState({ net });
}.bind(this),
error() {
//console.log('error'+response.error);
}
});
}
exportPrep(callback) {
this.dismissAllErrors();
const error = [];
const netObj = JSON.parse(JSON.stringify(this.state.net));
if (Object.keys(netObj).length == 0) {
this.addError("No model available for export");
return;
}
Object.keys(netObj).forEach(layerId => {
const layer = netObj[layerId];
Object.keys(layer.params).forEach(param => {
layer.params[param] = layer.params[param][0];
const paramData = data[layer.info.type].params[param];
if (layer.info.type == 'Python' || param == 'endPoint'){
return;
}
if (paramData.required === true && layer.params[param] === '') {
error.push(`Error: "${paramData.name}" required in "${layer.props.name}" Layer`);
}
});
});
if (error.length) {
this.setState({ error });
} else {
callback(netObj);
}
}
exportNet(framework) {
this.exportPrep(function(netData) {
Object.keys(netData).forEach(layerId => {
delete netData[layerId].state;
if (netData[layerId]['comments']) {
// not adding comments as part of export parameters of net
delete netData[layerId].comments;
}
});
this.sendSocketMessage({
framework: framework,
net: JSON.stringify(netData),
action: 'ExportNet',
net_name: this.state.net_name,
randomId: this.state.randomId
});
}.bind(this));
}
importNet(framework, id) {
this.dismissAllErrors();
this.closeModal();
this.clickEvent = false;
const url = {'caffe': '/caffe/import', 'keras': '/keras/import', 'tensorflow': '/tensorflow/import'};
const formData = new FormData();
const caffe_fillers = ['constant', 'gaussian', 'positive_unitball', 'uniform', 'xavier', 'msra', 'bilinear'];
const keras_fillers = ['Zeros', 'Ones', 'Constant', 'RandomNormal', 'RandomUniform', 'TruncatedNormal',
'VarianceScaling', 'Orthogonal', 'Identity', 'lecun_uniform', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform'];
if (framework == 'samplecaffe'){
framework = 'caffe'
formData.append('sample_id', id);
}
else if (framework == 'samplekeras'){
framework = 'keras'
formData.append('sample_id', id);
}
else if (framework == 'input') {
framework = this.state.modelFramework;
formData.append('config', this.state.modelConfig);
}
else if (framework == 'url') {
framework = this.state.modelFramework;
formData.append('url', this.state.modelUrl);
}
else
formData.append('file', $('#inputFile'+framework)[0].files[0]);
this.setState({ load: true });
if (framework == 'keras'){
var fillers = keras_fillers;
}
else{
fillers = caffe_fillers;
}
data['Convolution']['params']['weight_filler']['options'] = fillers;
data['Convolution']['params']['bias_filler']['options'] = fillers;
data['Deconvolution']['params']['weight_filler']['options'] = fillers;
data['Deconvolution']['params']['bias_filler']['options'] = fillers;
data['Recurrent']['params']['weight_filler']['options'] = fillers;
data['Recurrent']['params']['bias_filler']['options'] = fillers;
data['RNN']['params']['weight_filler']['options'] = fillers;
data['RNN']['params']['bias_filler']['options'] = fillers;
data['LSTM']['params']['weight_filler']['options'] = fillers;
data['LSTM']['params']['bias_filler']['options'] = fillers;
data['InnerProduct']['params']['weight_filler']['options'] = fillers;
data['InnerProduct']['params']['bias_filler']['options'] = fillers;
data['Embed']['params']['weight_filler']['options'] = fillers;
data['Bias']['params']['filler']['options'] = fillers;
$.ajax({
url: url[framework],
dataType: 'json',
type: 'POST',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function (response) {
if (response.result === 'success'){
this.initialiseImportedNet(response.net,response.net_name);
if (Object.keys(this.state.net).length)
this.loadLayerShapes();
} else if (response.result === 'error'){
this.addError(response.error);
}
this.setState({ load: false });
}.bind(this),
error : function () {
this.setState({ load: false });
this.addError("Error");
}.bind(this)
});
}
initialiseImportedNet(net,net_name) {
// this line will unmount all the layers
// so that the new imported layers will all be mounted again
const tempError = {};
// Initialize Python layer parameters to be empty
data['Python']['params'] = {}
this.setState({ net: {}, selectedLayer: null, hoveredLayer: null, nextLayerId: 0, selectedPhase: 0, error: [] });
Object.keys(net).forEach(layerId => {
var layer = net[layerId];
const type = layer.info.type;
// extract unique input & output nodes
net[layerId]['connection']['input'] = net[layerId]['connection']['input'].filter((val,id,array) => array.indexOf(val) == id);
net[layerId]['connection']['output'] = net[layerId]['connection']['output'].filter((val,id,array) => array.indexOf(val) == id);
// const index = +layerId.substring(1);
if (this.state.isShared == false) {
// if network object is being loaded from db avoid reinitializing the frontend part
if (type == 'Python') {
Object.keys(layer.params).forEach(param => {
layer.params[param] = [layer.params[param], false];
});
layer.params['caffe'] = [true, false];
}
if (data.hasOwnProperty(type)) {
// add the missing params with default values
Object.keys(data[type].params).forEach(param => {
if (!layer.params.hasOwnProperty(param)) {
// The initial value is a list with the first element being the actual value, and the second being a flag which
// controls whether the parameter is disabled or not on the frontend.
layer.params[param] = [data[type].params[param].value, false];
}
else {
layer.params[param] = [layer.params[param], false];
}
});
if (type == 'Convolution' || type == 'Pooling' || type == 'Upsample' || type == 'LocallyConnected' || type == 'Eltwise'){
layer = this.adjustParameters(layer, 'layer_type', layer.params['layer_type'][0]);
}
// layer.props = JSON.parse(JSON.stringify(data[type].props));
layer.props = {};
// default name
layer.props.name = layerId;
}
else {
tempError[type] = null;
}
}
});
// initialize the position of layers
if (tempError.length == undefined) {
netLayout(net);
}
if (Object.keys(tempError).length) {
const errorLayers = Object.keys(tempError).join(', ');
this.setState({ error: [`Error: Currently we do not support these layers: ${errorLayers}.`] });
} else {
instance.detachEveryConnection();
instance.deleteEveryEndpoint();
this.setState({
net,
net_name,
selectedLayer: null,
hoveredLayer: null,
nextLayerId: Object.keys(net).length,
rebuildNet: true,
selectedPhase: 0,
error: [],
totalParameters: 0
});
}
}
setDraggingLayer(id) {
this.setState({ draggingLayer: id })
}
changeNetName(event) {
this.setState({net_name: event.target.value});
}
adjustParameters(layer, para, value) {
if (para == 'layer_type'){
if (layer.info['type'] == 'Convolution' || layer.info['type'] == 'Pooling'){
if (value == '1D'){
layer.params['caffe'] = [false, false];
layer.params['kernel_h'] = [layer.params['kernel_h'][0], true];
layer.params['kernel_d'] = [layer.params['kernel_d'][0], true];
layer.params['pad_h'] = [layer.params['pad_h'][0], true];
layer.params['pad_d'] = [layer.params['pad_d'][0], true];
layer.params['stride_h'] = [layer.params['stride_h'][0], true];
layer.params['stride_d'] = [layer.params['stride_d'][0], true];
if (layer.info['type'] == 'Convolution'){
layer.params['dilation_h'] = [layer.params['dilation_h'][0], true];
layer.params['dilation_d'] = [layer.params['dilation_d'][0], true];
}
}
else if (value == '2D'){
layer.params['caffe'] = [true, false];
layer.params['kernel_h'] = [layer.params['kernel_h'][0], false];
layer.params['kernel_d'] = [layer.params['kernel_d'][0], true];
layer.params['pad_h'] = [layer.params['pad_h'][0], false];
layer.params['pad_d'] = [layer.params['pad_d'][0], true];
layer.params['stride_h'] = [layer.params['stride_h'][0], false];
layer.params['stride_d'] = [layer.params['stride_d'][0], true];
if (layer.info['type'] == 'Convolution'){
layer.params['dilation_h'] = [layer.params['dilation_h'][0], false];
layer.params['dilation_d'] = [layer.params['dilation_d'][0], true];
}
}
else {
layer.params['caffe'] = [false, false];
layer.params['kernel_h'] = [layer.params['kernel_h'][0], false];
layer.params['kernel_d'] = [layer.params['kernel_d'][0], false];
layer.params['pad_h'] = [layer.params['pad_h'][0], false];
layer.params['pad_d'] = [layer.params['pad_d'][0], false];
layer.params['stride_h'] = [layer.params['stride_h'][0], false];
layer.params['stride_d'] = [layer.params['stride_d'][0], false];
if (layer.info['type'] == 'Convolution'){
layer.params['dilation_h'] = [layer.params['dilation_h'][0], false];
layer.params['dilation_d'] = [layer.params['dilation_d'][0], false];
}
}
}
else if (layer.info['type'] == 'Upsample'){
if (value == '1D'){
layer.params['size_h'] = [layer.params['size_h'][0], true];
layer.params['size_d'] = [layer.params['size_d'][0], true];
}
else if (value == '2D'){
layer.params['size_h'] = [layer.params['size_h'][0], false];
layer.params['size_d'] = [layer.params['size_d'][0], true];
}
else{
layer.params['size_h'] = [layer.params['size_h'][0], false];
layer.params['size_d'] = [layer.params['size_d'][0], false];
}
}
else if (layer.info['type'] == 'LocallyConnected'){
if (value == '1D'){
layer.params['kernel_h'] = [layer.params['kernel_h'][0], true];
layer.params['stride_h'] = [layer.params['stride_h'][0], true];
}
}
else if (layer.info['type'] == 'Eltwise'){
if (value == 'Average' || value == 'Dot'){
layer.params['caffe'] = [false, false];
}
}
}
return layer;
}
changeNetStatus(bool) {
this.setState({ rebuildNet: bool });
}
changeNetPhase(phase) {
const net = this.state.net;
this.setState({ net, selectedPhase: phase, rebuildNet: true });
}
dismissError(errorIndex) {
const error = this.state.error;
error.splice(errorIndex, 1);
this.setState({ error, info: []});
}
addError(errorText) {
const error = this.state.error;
error.push(errorText);
this.setState({ error });
}
dismissAllErrors() {
this.setState({ error: [] });
this.setState({ info: [] });
}
addInfo(infoContent) {
const info = this.state.info;
info.push(infoContent)
this.setState({ info, error: [] })
}
dismissInfo(infoIndex) {
const info = this.state.info;
info.splice(infoIndex, 1);
this.setState({ info });
}
copyTrain() {
const net = this.state.net;
Object.keys(net).forEach(layerId => {
if (net[layerId].info.phase === 0) {
net[layerId].info.phase = null;
} else if (net[layerId].info.phase === 1) {
this.deleteLayer(layerId);
}
});
this.setState({
net,
selectedLayer: null,
rebuildNet: true
});
}
trainOnly() {
const net = this.state.net;
const layer = net[this.state.selectedLayer];
const layerId = this.state.selectedLayer;
let index;
if (layer.info.phase == null) {
(layer.connection.output).forEach(outputId => {
if (net[outputId].info.phase === 1) {
index = layer.connection.output.indexOf(outputId);
layer.connection.output.splice(index, 1);
index = net[outputId].connection.input.indexOf(layerId);
net[outputId].connection.input.splice(index, 1);
}
});
(layer.connection.input).forEach(inputId => {
if (net[inputId].info.phase === 1) {
index = layer.connection.input.indexOf(inputId);
layer.connection.input.splice(index, 1);
index = net[inputId].connection.output.indexOf(layerId);
net[inputId].connection.output.splice(index, 1);
}
});
}
layer.info.phase = 0;
this.setState({ net });
}
saveDb(){
let netData = this.state.net;
this.setState({ load: true });
$.ajax({
url: '/save',
dataType: 'json',
type: 'POST',
data: {
net: JSON.stringify(netData),
net_name: this.state.net_name,
user_id: this.getUserId(),
nextLayerId: this.state.nextLayerId
},
success : function (response) {
if (response.result == 'success') {
var url = 'http://' + window.location.host + '/load?id=' + response.id;
this.modalHeader = 'Your model url is';
this.modalContent = (<a href={url}>{url}</a>);
this.openModal();
}
else if (response.result == 'error') {
this.addError(response.error);
}
this.setState({ load: false });
}.bind(this),
error() {
this.setState({ load: false });
}
});
}
componentWillMount(){
var url = window.location.href.split('#');
var urlParams = {};
let randomId = url[1];
url = url[0];
url.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) {
urlParams[$1] = $3;
}
);
// setting up socket connection
let socket = this.createSocket('ws://' + window.location.host + '/ws/connect/?id=' + urlParams['id']);
this.setState({ socket: socket });
this.waitForConnection (this.onSocketConnect, 1000);
if ('id' in urlParams){
if ('version' in urlParams) {
this.loadDb(urlParams['id'], urlParams['version']);
this.setState({
isShared: true,
isForked: true,
networkId: parseInt(urlParams['id']),
randomId: randomId,
highlightColor: this.getRandomColor()
});
}
else {
this.loadDb(urlParams['id']);
this.setState({
isShared: true,
networkId: parseInt(urlParams['id']),
randomId: randomId,
highlightColor: this.getRandomColor()
});
}
}
}
loadDb(id, version_id = null) {
// in case model is getting loaded from history disable sending updates
// Note: this needs to be improved when handling conflict resolution to avoid
// inconsistent states of model
let nextLayerId = this.state.nextLayerId;
this.setState({ load: true });
this.dismissAllErrors();
$.ajax({
url: '/load',
dataType: 'json',
type: 'POST',
data: {
proto_id: id,
version_id: version_id
},
success: function (response) {
if (response.result === 'success'){
// while loading a model ensure paramete intialisation
// for UI show/hide is not executed, it leads to inconsistent
// data which cannot be used further
nextLayerId = response.next_layer_id;
this.initialiseImportedNet(response.net,response.net_name);
if (Object.keys(response.net).length){
this.calculateParameters(response.net);
}
}
else if (response.result === 'error') {
this.addError(response.error);
}
this.setState({
load: false,
isShared: true,
nextLayerId: parseInt(nextLayerId)
});
}.bind(this),
error() {
this.setState({ load: false });
}
});
}
infoModal() {
this.modalHeader = "About"
this.modalContent = `Fabrik is an online collaborative platform to build and visualize deep\
learning models via a simple drag-and-drop interface. It allows researchers to\
collaboratively develop and debug models using a web GUI that supports importing,\
editing and exporting networks written in widely popular frameworks like Caffe,\
Keras, and TensorFlow.`;
this.openModal();
}
faqModal() {
this.modalHeader = "Help/FAQ"
this.modalContent = (<p><b>Q:</b> What is Fabrik?<br />
<b>A:</b> Fabrik is an online platform, created by CloudCV, allowing AI researchers and enthusiasts to
build and visualize deep learning models.<br />
<b>Q:</b> What is the model zoo?<br />
<b>A:</b> It is a collection of pre-built models that you can use.
To access it, simply click the folder icon in the left corner of the toolbox and pick a model.
You can find the available models
<a target="_blank" href="https://github.com/Cloud-CV/Fabrik/blob/master/docs/source/tested_models.md"> here</a>.
<br />
<b>Q:</b> What do the Train/Test buttons mean?<br />
<b>A:</b> They are two different modes of your model:
Train and Test - respectively for training your model with data and testing how and if it works.<br />
<b>Q:</b> What does the import fuction do?<br />
<b>A:</b> It allows you to import your previously created models in Caffe (.protoxt files),
Keras (.json files) and TensorFlow (.pbtxt files)<br />
<b>Q:</b> What does the export function do?<br />
<b>A:</b> You can use it to download models from Fabrik. You can train and test them directly on your computer,
using <a target="_blank" href="https://github.com/Cloud-CV/Fabrik/blob/master/docs/source/caffe_prototxt_usage_1.md">Caffe</a>,
<a target="_blank" href="https://github.com/Cloud-CV/Fabrik/blob/master/docs/source/keras_json_usage_1.md"> Keras </a>
and TensorFlow.<br />
<b>Q:</b> How can I contribute to Fabrik?<br />
<b>A:</b> Please see the instructions listed
<a target="_blank" href="https://github.com/Cloud-CV/Fabrik/blob/master/README.md"> here</a>
<br /><br />
<b>If you have anymore questions, please visit Fabrik's Github page available
<a target="_blank" href="https://github.com/Cloud-CV/Fabrik"> here</a> for more information.</b>
</p>);
this.openModal();
}
toggleSidebar() {
$('#sidebar').toggleClass('visible');
$('.sidebar-button').toggleClass('close');
}
zooModal() {
this.modalHeader = null;
this.modalContent = <ModelZoo importNet={this.importNet} />;
this.openModal();
}
setModelFramework(e) {
const el = e.target;
const modelFramework = el.dataset.framework;
this.setState({modelFramework});
$('.import-textbox-tab.selected').removeClass('selected');
$(el).addClass('selected');
}
setModelFrameworkUrl(e) {
const el = e.target;
const modelFramework = el.dataset.framework;
this.setState({modelFramework});
$('.url-import-modal-tab.selected').removeClass('selected');
$(el).addClass('selected');
}
setModelConfig(e) {
const modelConfig = e.target.value;
this.setState({modelConfig});
}
setModelUrl(url) {
this.setState({ modelUrl: url});
}
textboxModal() {
this.modalHeader = null;
this.modalContent = <ImportTextbox
modelConfig={this.state.modelConfig}
modelFramework={this.state.modelFramework}
setModelConfig={this.setModelConfig}
setModelFramework={this.setModelFramework}
importNet={this.importNet}
addError={this.addError}
/>;
this.openModal();
}
urlModal() {
this.modalHeader = null;
this.modalContent = <UrlImportModal
modelFramework={this.state.modelFramework}
setModelFramework={this.setModelFrameworkUrl}
setModelUrl={this.setModelUrl}
importNet={this.importNet}
addError={this.addError}
/>;
this.openModal();
}
updateHistoryModal() {
$.ajax({
url: '/model_history',
dataType: 'json',
type: 'POST',
data: {
net_id: this.state.networkId
},
success : function (response) {
if (response.result == 'success') {
this.modalHeader = 'Model update history';
this.modalContent = <UpdateHistoryModal
networkId={this.state.networkId}
modelHistory={response.data}
addError={this.addError}
/>;
this.openModal();
}
else if (response.result == 'error') {
this.addError(response.error);
}
this.setState({ load: false });
}.bind(this),
error() {
this.setState({ load: false });
}
});
}
handleClick(event) {
event.preventDefault();
this.clickEvent = true;
const net = this.state.net;
// extracting layerId from Pane id which is in form LayerName_Button
const id = event.target.id.split('_')[0];
const prevLayerId = 'l' + (this.state.nextLayerId - 1);
const prev = net[prevLayerId];
const next = data[id];
const zoom = instance.getZoom();
const layer = {};
let phase = this.state.selectedPhase;
if (this.state.nextLayerId>0 //makes sure that there are other layers
&& data[prev.info.type].endpoint.src == "Bottom" //makes sure that the source has a bottom
&& next.endpoint.trg == "Top") { //makes sure that the target has a top
layer.connection = { input: [], output: [] };
layer.info = {
type: id.toString(),
phase,
class: ''
}
layer.params = {
'endPoint' : [next['endpoint'], false] //This key is endpoint in data.js, but endPoint in everywhere else.
}
Object.keys(next.params).forEach(j => {
layer.params[j] = [next.params[j].value, false]; //copys all params from data.js
});
layer.props = JSON.parse(JSON.stringify(next.props)) //copys all props rom data.js
layer.state = {
top: `${(parseInt(prev.state.top.split('px')[0])/zoom + 80)}px`, // This makes the new layer is exactly 80px under the previous one.
left: `${(parseInt(prev.state.left.split('px')[0])/zoom)}px`, // This aligns the new layer with the previous one.
class: ''
}
layer.props.name = `${next.name}${this.state.nextLayerId}`;
prev.connection.output.push(`l${this.state.nextLayerId}`);
layer.connection.input.push(`l${this.state.nextLayerId-1}`);
this.addNewLayer(layer, prevLayerId);
}
else if (Object.keys(net).length == 0) { // if there are no layers
layer.connection = { input: [], output: [] };
layer.info = {
type: id.toString(),
phase,
class: ''
}
layer.params = {
'endPoint' : [next['endpoint'], false] //This key is endpoint in data.js, but endPoint in everywhere else.
}
Object.keys(next.params).forEach(j => {
layer.params[j] = [next.params[j].value, false]; //copys all params from data.js
});
layer.props = JSON.parse(JSON.stringify(next.props)) //copys all props from data.js
const height = Math.round(0.05*window.innerHeight, 0); // 5% of screen height, rounded to zero decimals
const width = Math.round(0.35*window.innerWidth, 0); // 35% of screen width, rounded to zero decimals
var top = height + Math.ceil(81-height);
var left = width;
layer.state = {
top: `${top}px`,
left: `${left}px`,
class: ''
}
layer.props.name = `${next.name}${this.state.nextLayerId}`;
this.addNewLayer(layer);
}
}
render() {
let loader = null;
if (this.state.load) {
loader = (<div className="loaderOverlay">
<div className="loader"></div>
</div>);
}
return (
<div id="parent">
<a className="sidebar-button" onClick={this.toggleSidebar}></a>
<div id="sidebar">
<div id="logo_back">
<a href="http://fabrik.cloudcv.org"><img src={'/static/img/fabrik_t.png'} className="img-responsive" alt="logo" id="logo"/></a>
</div>
<div id="sidebar-scroll" className="col-md-12">
<h5 className="sidebar-heading">ACTIONS</h5>
<TopBar
exportNet={this.exportNet}
importNet={this.importNet}
saveDb={this.saveDb}
zooModal={this.zooModal}
textboxModal={this.textboxModal}
urlModal={this.urlModal}
updateHistoryModal={this.updateHistoryModal}
/>
<Login setUserId={this.setUserId} setUserName={this.setUserName}></Login>
<h5 className="sidebar-heading">INSERT LAYER</h5>
<div className="sidebar-heading">
<FilterBar />
</div>
<Pane
handleClick = {this.handleClick}
setDraggingLayer = {this.setDraggingLayer}
/>
<div className="text-center">
<Tabs selectedPhase={this.state.selectedPhase} changeNetPhase={this.changeNetPhase} />
</div>
<h5 className="sidebar-heading">EXTRAS</h5>
<a className="btn btn-block extra-buttons text-left" onClick={this.faqModal}>Help</a>
<a className="btn btn-block extra-buttons text-left" href="https://github.com/Cloud-CV/Fabrik" target="_blank">GitHub</a>
<a className="btn btn-block extra-buttons text-left" href="http://cloudcv.org" target="_blank">CloudCV</a>
<a className="btn btn-block extra-buttons text-left" onClick={this.infoModal}>About Us</a>
</div>
</div>
<div id="main">
<input type="text"
className={$.isEmptyObject(this.state.net) ? "hidden": ""}
id="netName"
placeholder="Net name"
value={this.state.net_name}
onChange={this.changeNetName}
spellCheck="false"
/>
{loader}
<Canvas
net={this.state.net}
rebuildNet={this.state.rebuildNet}
addNewLayer={this.addNewLayer}
nextLayerId={this.state.nextLayerId}
changeSelectedLayer={this.changeSelectedLayer}
changeHoveredLayer={this.changeHoveredLayer}
modifyLayer={this.modifyLayer}
changeNetStatus={this.changeNetStatus}
error={this.state.error}
dismissError={this.dismissError}
addError={this.addError}
info={this.state.info}
dismissInfo={this.dismissInfo}
addInfo={this.addInfo}
clickEvent={this.clickEvent}
totalParameters={this.state.totalParameters}
selectedPhase={this.state.selectedPhase}
draggingLayer={this.state.draggingLayer}
setDraggingLayer={this.setDraggingLayer}
selectedLayer={this.state.selectedLayer}
socket={this.state.socket}
addSharedComment={this.addSharedComment}
isShared={this.state.isShared}
isForked={this.state.isForked}
changeCommentOnLayer={this.changeCommentOnLayer}
/>
<SetParams
net={this.state.net}
selectedLayer={this.state.selectedLayer}
modifyLayer={this.modifyLayerParams}
adjustParameters={this.adjustParameters}
changeSelectedLayer={this.changeSelectedLayer}
deleteLayer={this.deleteLayer}
selectedPhase={this.state.selectedPhase}
copyTrain={this.copyTrain}
trainOnly={this.trainOnly}
updateLayerWithShape={this.modifyLayer}
performSharedUpdate={this.performSharedUpdate}
/>
<CommentSidebar
net={this.state.net}
commentOnLayer={this.state.commentOnLayer}
changeCommentOnLayer={this.changeCommentOnLayer}
addSharedComment={this.addSharedComment}
/>
<CommentSidebar
net={this.state.net}
commentOnLayer={this.state.commentOnLayer}
changeCommentOnLayer={this.changeCommentOnLayer}
performSharedUpdate={this.performSharedUpdate}
/>
<Tooltip
id={'tooltip_text'}
net={this.state.net}
hoveredLayer={this.state.hoveredLayer}
/>
<Modal
isOpen={this.state.modalIsOpen}
onRequestClose={this.closeModal}
style={infoStyle}
contentLabel="Modal">
<button type="button" style={{padding: 5+'px'}} className="close" onClick={this.closeModal}>×</button>
<h4>{ this.modalHeader }</h4>
{ this.modalContent }
</Modal>
</div>
</div>
);
}
}
export default Content;
|
index.js
|
anthonator/react-contentable
|
import React from 'react';
/**
* This component provides contenteditable DIV functionality. This component
* encapsulates logic for managing a contenteditable value while taking changes
* within the property model into account.
*/
class Contentable extends React.Component {
constructor() {
super();
}
shouldComponentUpdate(nextProps) {
let nextValue = nextProps.value;
return this._didNextPropsChange(nextProps) || nextValue !== React.findDOMNode(this).innerHTML;
}
componentDidUpdate() {
let node = React.findDOMNode(this);
if (this.props.value !== node.innerHTML) {
node.innerHTML = this.props.value;
}
}
render() {
return (
<div { ...this.props }
contentEditable={ this._isContentEditable() }
dangerouslySetInnerHTML={ { __html: this.props.value || '' } } />
);
}
// private
/**
* !!! This is a little ridiculous. In order to allow component properties to
* reflect change within a component we need to have the ability to see if a
* components properties have changed independent of whether the value has
* changed. We can easily do this by cloning props and nextProps and stripping
* out `value`. However, properties may contain functions and functions never
* equate. So if you pass in an event or other property with a function your
* objects will never equate. So this method manually checks for property
* equality by ignoring functions. Currently, if a property contains an
* object with a function it will probably 'splode.
*
*/
_didNextPropsChange(nextProps) {
let clonedProps = {};
let clonedNextProps = {};
Object.assign(clonedProps, this.props);
Object.assign(clonedNextProps, nextProps);
delete clonedProps.value;
delete clonedNextProps.value;
for(let key in clonedProps) {
if (clonedNextProps.hasOwnProperty(key)) {
if (typeof clonedProps[key] !== 'function' && typeof clonedNextProps[key] !== 'function') {
if (clonedProps[key] !== clonedNextProps[key]) {
return true;
}
}
} else {
return true;
}
}
return false;
}
_isContentEditable() {
if (this.props.contentEditable !== undefined && this.props.contentEditable !== null) {
return this.props.contentEditable;
} else {
return true;
}
}
}
export default Contentable;
|
client/App.js
|
trantuthien/React-Test
|
/**
* Root Component
*/
import React from 'react';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import IntlWrapper from './modules/Intl/IntlWrapper';
// Import Routes
import routes from './routes';
// Base stylesheet
require('./main.css');
export default function App(props) {
return (
<Provider store={props.store}>
<IntlWrapper>
<Router history={browserHistory}>
{routes}
</Router>
</IntlWrapper>
</Provider>
);
}
App.propTypes = {
store: React.PropTypes.object.isRequired,
};
|
src/client/components/component.react.js
|
youprofit/este
|
import React from 'react';
import shallowEqual from 'react-pure-render/shallowEqual';
/**
* Purified React.Component. Goodness.
* http://facebook.github.io/react/docs/advanced-performance.html
*/
export default class Component extends React.Component {
static contextTypes = {
router: React.PropTypes.func
}
shouldComponentUpdate(nextProps, nextState) {
// This hack will be removed with react-router 1.0.0.
if (this.context.router) {
const changed = this.pureComponentLastPath !== this.context.router.getCurrentPath();
this.pureComponentLastPath = this.context.router.getCurrentPath();
if (changed) return true;
}
const shouldUpdate =
!shallowEqual(this.props, nextProps) ||
!shallowEqual(this.state, nextState);
// TODO: Dev tools.
// if (shouldUpdate)
// const name = this.constructor.displayName || this.constructor.name
// console.log(`${name} shouldUpdate`)
return shouldUpdate;
}
}
|
src/svg-icons/action/language.js
|
mit-cml/iot-website-source
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLanguage = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm6.93 6h-2.95c-.32-1.25-.78-2.45-1.38-3.56 1.84.63 3.37 1.91 4.33 3.56zM12 4.04c.83 1.2 1.48 2.53 1.91 3.96h-3.82c.43-1.43 1.08-2.76 1.91-3.96zM4.26 14C4.1 13.36 4 12.69 4 12s.1-1.36.26-2h3.38c-.08.66-.14 1.32-.14 2 0 .68.06 1.34.14 2H4.26zm.82 2h2.95c.32 1.25.78 2.45 1.38 3.56-1.84-.63-3.37-1.9-4.33-3.56zm2.95-8H5.08c.96-1.66 2.49-2.93 4.33-3.56C8.81 5.55 8.35 6.75 8.03 8zM12 19.96c-.83-1.2-1.48-2.53-1.91-3.96h3.82c-.43 1.43-1.08 2.76-1.91 3.96zM14.34 14H9.66c-.09-.66-.16-1.32-.16-2 0-.68.07-1.35.16-2h4.68c.09.65.16 1.32.16 2 0 .68-.07 1.34-.16 2zm.25 5.56c.6-1.11 1.06-2.31 1.38-3.56h2.95c-.96 1.65-2.49 2.93-4.33 3.56zM16.36 14c.08-.66.14-1.32.14-2 0-.68-.06-1.34-.14-2h3.38c.16.64.26 1.31.26 2s-.1 1.36-.26 2h-3.38z"/>
</SvgIcon>
);
ActionLanguage = pure(ActionLanguage);
ActionLanguage.displayName = 'ActionLanguage';
ActionLanguage.muiName = 'SvgIcon';
export default ActionLanguage;
|
webapp/src/components/subsection.js
|
nathandunn/agr
|
import React, { Component } from 'react';
import style from './style.css';
class Subsection extends Component {
render() {
return (
<div className={style.subsection}>
{this.props.hardcoded && <span className='tag tag-danger'>Hardcoded Example Data</span>}
{this.props.title && <h3>{this.props.title}</h3>}
{typeof this.props.hasData !== 'undefined' && !this.props.hasData ?
<i className="text-muted">No Data Available</i> :
this.props.children}
</div>
);
}
}
Subsection.propTypes = {
children: React.PropTypes.element.isRequired,
hardcoded: React.PropTypes.bool,
hasData: React.PropTypes.bool,
title: React.PropTypes.string,
};
export default Subsection;
|
ReactJS_Seed_Project/app/components/layouts/Main.js
|
huang6349/inspinia
|
import React from 'react';
import Progress from '../common/Progress';
import Navigation from '../common/Navigation';
import Footer from '../common/Footer';
import TopHeader from '../common/TopHeader';
import { correctHeight, detectBody } from './Helpers';
class Main extends React.Component {
render() {
let wrapperClass = "gray-bg " + this.props.location.pathname;
return (
<div id="wrapper">
<Progress />
<Navigation location={this.props.location}/>
<div id="page-wrapper" className={wrapperClass}>
<TopHeader />
{this.props.children}
<Footer />
</div>
</div>
)
}
componentDidMount() {
// Run correctHeight function on load and resize window event
$(window).bind("load resize", function() {
correctHeight();
detectBody();
});
// Correct height of wrapper after metisMenu animation.
$('.metismenu a').click(() => {
setTimeout(() => {
correctHeight();
}, 300)
});
}
}
export default Main
|
src/components/stateless/HiddenField.js
|
thomas-p-wilson/react-form
|
import React from 'react'; // eslint-disable-line no-unused-vars
import BasicField from '../BasicField';
/**
* Produces an HTML input field with the type set to `hidden` and which performs
* just like its pure HTML counterpart in all respects.
*/
export default class HiddenField extends BasicField {
static displayName = 'HiddenField';
/**
* Perform render
* @returns {Object} - A React element
*/
render() {
const props = this.getProps({
'type': 'hidden'
});
return (
<input { ...props } />
);
}
}
|
src/components/Field.js
|
jozaru/my-bank-app
|
import React from 'react';
import { FormGroup, ControlLabel, FormControl, HelpBlock } from 'react-bootstrap';
export class Field extends React.Component {
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
this.input = null;
}
componentDidMount() {
this.props.setFieldValidationMessage(this.props.name, '');
}
handleChange(ev) {
let val = ev.target.value;
const name = this.props.name;
let empty = false;
if (this.props.required && (!val || val.lenght === 0)) {
empty = true;
}
this.props.setFormMessage(this.props.formName);
this.props.setFieldValidationMessage(this.props.name, '');
if (empty) {
this.props.setFieldValidationMessage(this.props.name, 'Campo obligatorio');
}
if (!empty && this.props.validationFunction) {
let message = this.props.validationFunction(val);
if (message) {
this.props.setFieldValidationMessage(this.props.name, message);
val = '';
}
}
const formData = Object.assign({}, this.props[this.props.formName].formData, { [name]: val });
this.props.setFormData(this.props.formName, formData);
}
render() {
return (
<FormGroup validationState={this.props.validationMessage ? 'error': null}>
<ControlLabel>{this.props.label}</ControlLabel>
<FormControl
type={this.props.type}
onChange={this.handleChange}
min={this.props.min}
/>
<HelpBlock>{this.props.validationMessage}</HelpBlock>
</FormGroup>
);
}
}
Field.propTypes = {
label: React.PropTypes.string.isRequired,
type: React.PropTypes.string.isRequired,
name: React.PropTypes.string.isRequired,
min: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]),
validationMessage: React.PropTypes.string,
formName: React.PropTypes.string.isRequired,
required: React.PropTypes.bool,
setFieldValidationMessage: React.PropTypes.func.isRequired,
setFormData: React.PropTypes.func.isRequired,
setFormMessage: React.PropTypes.func.isRequired,
validationFunction: React.PropTypes.func
}
export default Field;
|
caseStudy/ui/src/components/Company.js
|
jennybkim/engineeringessentials
|
import React from 'react';
|
src/icons/Bonfire.js
|
fbfeix/react-icons
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class Bonfire extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M270.93,350.601C270.219,342.42,263.364,336,255,336c-7.635,0-14.01,5.352-15.605,12.506l-0.007-0.002l-15.612,92.502
C223.273,443.258,223,445.597,223,448c0,17.673,14.327,32,32,32s32-14.327,32-32c0-2.899-0.393-5.705-1.115-8.377L270.93,350.601z"></path>
<polygon points="305.904,355.046 305.903,355.044 305.9,355.046 "></polygon>
<path d="M392.875,390.261c-1.718-1.407-3.3-2.881-5.138-3.94l-63.629-47.507c-5.775-3.796-11.997-3.689-16.527,0.85
c-4.131,4.143-4.686,10.369-1.678,15.381l48.959,65.763c0.946,1.494,2.166,2.799,3.366,4.195c7.802,9.071,25.08,9.588,34.646-0.007
C402.445,415.409,402.305,397.986,392.875,390.261z"></path>
<polygon points="372.511,335.018 372.509,335.018 372.509,335.02 "></polygon>
<path d="M435.428,322.475l-59.521-2.284c-3.891-0.558-7.4,2.053-8.065,6.011c-0.604,3.611,1.347,7.138,4.668,8.816l0.013-0.039
c0.041,0.019,0.062,0.006,0.105,0.025l57.717,17.756c8.289,1.93,17.656-2.343,17.656-11.648
C448,329.328,444.917,323.667,435.428,322.475z"></path>
<polygon points="139.222,335.02 139.222,335.018 139.22,335.018 "></polygon>
<path d="M139.209,334.979l0.013,0.039c3.321-1.679,5.272-5.205,4.668-8.816c-0.665-3.958-4.175-6.568-8.065-6.011l-59.521,2.284
C66.813,323.667,64,329.328,64,341.111c0,9.306,9.098,13.578,17.387,11.648l57.717-17.756
C139.146,334.984,139.168,334.997,139.209,334.979z"></path>
<path d="M187.903,338.807l-63.597,47.431c-1.838,1.057-3.569,2.362-5.137,3.931c-9.563,9.567-9.566,25.088-0.004,34.65
c9.561,9.571,25.055,9.578,34.618,0.007c1.3-1.299,2.405-2.694,3.352-4.185L206.097,355c3.007-5,2.452-11.213-1.677-15.346
C199.893,335.126,192.712,334.762,187.903,338.807z"></path>
<path d="M352,128c0-61-72.35-96-96-96c12.017,85.553-101.667,119.667-112,192s48,96,48,96
c16.333-59.896,72.386-79.997,109.667-105.667C342.333,186.333,352,160.061,352,128z"></path>
<path d="M352,256c5.03-15.613,4.91-49,0-64c-8.999,18.5-26.287,34.3-47.186,48.689c-8.584,5.911-19.859,11.443-28.83,16.797
c-18.714,11.165-34.984,21.848-47.329,36.4C240.001,311.25,256.973,320,272,320C307.999,320,336,305.662,352,256z"></path>
<path d="M152.037,160c11.722-15.952,24.856-25.209,38.19-38.362c13.436-13.254,22.077-22.471,27.464-33.173
C207.025,67.134,189.842,61.857,176,64c2.333,30.334-29.97,46.567-32,68.657C142.773,146,146.5,156,152.037,160z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M270.93,350.601C270.219,342.42,263.364,336,255,336c-7.635,0-14.01,5.352-15.605,12.506l-0.007-0.002l-15.612,92.502
C223.273,443.258,223,445.597,223,448c0,17.673,14.327,32,32,32s32-14.327,32-32c0-2.899-0.393-5.705-1.115-8.377L270.93,350.601z"></path>
<polygon points="305.904,355.046 305.903,355.044 305.9,355.046 "></polygon>
<path d="M392.875,390.261c-1.718-1.407-3.3-2.881-5.138-3.94l-63.629-47.507c-5.775-3.796-11.997-3.689-16.527,0.85
c-4.131,4.143-4.686,10.369-1.678,15.381l48.959,65.763c0.946,1.494,2.166,2.799,3.366,4.195c7.802,9.071,25.08,9.588,34.646-0.007
C402.445,415.409,402.305,397.986,392.875,390.261z"></path>
<polygon points="372.511,335.018 372.509,335.018 372.509,335.02 "></polygon>
<path d="M435.428,322.475l-59.521-2.284c-3.891-0.558-7.4,2.053-8.065,6.011c-0.604,3.611,1.347,7.138,4.668,8.816l0.013-0.039
c0.041,0.019,0.062,0.006,0.105,0.025l57.717,17.756c8.289,1.93,17.656-2.343,17.656-11.648
C448,329.328,444.917,323.667,435.428,322.475z"></path>
<polygon points="139.222,335.02 139.222,335.018 139.22,335.018 "></polygon>
<path d="M139.209,334.979l0.013,0.039c3.321-1.679,5.272-5.205,4.668-8.816c-0.665-3.958-4.175-6.568-8.065-6.011l-59.521,2.284
C66.813,323.667,64,329.328,64,341.111c0,9.306,9.098,13.578,17.387,11.648l57.717-17.756
C139.146,334.984,139.168,334.997,139.209,334.979z"></path>
<path d="M187.903,338.807l-63.597,47.431c-1.838,1.057-3.569,2.362-5.137,3.931c-9.563,9.567-9.566,25.088-0.004,34.65
c9.561,9.571,25.055,9.578,34.618,0.007c1.3-1.299,2.405-2.694,3.352-4.185L206.097,355c3.007-5,2.452-11.213-1.677-15.346
C199.893,335.126,192.712,334.762,187.903,338.807z"></path>
<path d="M352,128c0-61-72.35-96-96-96c12.017,85.553-101.667,119.667-112,192s48,96,48,96
c16.333-59.896,72.386-79.997,109.667-105.667C342.333,186.333,352,160.061,352,128z"></path>
<path d="M352,256c5.03-15.613,4.91-49,0-64c-8.999,18.5-26.287,34.3-47.186,48.689c-8.584,5.911-19.859,11.443-28.83,16.797
c-18.714,11.165-34.984,21.848-47.329,36.4C240.001,311.25,256.973,320,272,320C307.999,320,336,305.662,352,256z"></path>
<path d="M152.037,160c11.722-15.952,24.856-25.209,38.19-38.362c13.436-13.254,22.077-22.471,27.464-33.173
C207.025,67.134,189.842,61.857,176,64c2.333,30.334-29.97,46.567-32,68.657C142.773,146,146.5,156,152.037,160z"></path>
</g>
</IconBase>;
}
};Bonfire.defaultProps = {bare: false}
|
blueocean-material-icons/src/js/components/svg-icons/communication/call-missed-outgoing.js
|
kzantow/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const CommunicationCallMissedOutgoing = (props) => (
<SvgIcon {...props}>
<path d="M3 8.41l9 9 7-7V15h2V7h-8v2h4.59L12 14.59 4.41 7 3 8.41z"/>
</SvgIcon>
);
CommunicationCallMissedOutgoing.displayName = 'CommunicationCallMissedOutgoing';
CommunicationCallMissedOutgoing.muiName = 'SvgIcon';
export default CommunicationCallMissedOutgoing;
|
src/components/posts_index.js
|
nicolasmsg/react-blog
|
import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPosts } from '../actions';
class PostsIndex extends Component {
componentDidMount(){
this.props.fetchPosts();
}
renderPosts(){
console.log('called ', this.props)
return _.map(this.props.posts, post => {
return (
<li className="list-group-item" key={post.id}>
<Link to={`/posts/${post.id}`}>
{post.title}
</Link>
</li>
);
});
}
render(){
return (
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">
Add a post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state){
console.log('mapStateToProps', state);
return { posts: state.posts};
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
// Here we directly pass an action creator to connect without using the mapDispatchToProps, but its exaclty the samething
// As we dont do any computation in the mapDispatchToProps function, only asign fetchPost... you can use this syntax
|
client/app/components/Home/Home.js
|
ejingfx/ews-mern-boiler
|
import React from 'react';
const Home = () => (
<div className="l-container">
<h1>Home</h1>
</div>
);
export default Home;
|
src/layouts/Frame.js
|
recharts/recharts.org
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import Helmet from 'react-helmet';
import { getLocaleType, localeGet } from '../utils/LocaleUtils';
import Affix from '../components/Affix';
import '../styles/app.scss';
const modules = ['guide', 'api', 'examples', 'blog'];
const locales = [
{ locale: 'en-US', text: 'En' },
{ locale: 'zh-CN', text: '中文' },
];
@connect((state, ownProps) => ({
page: ownProps.location.pathname.split('/').filter((item) => !!item)[1] || 'index',
}))
class Frame extends Component {
static propTypes = {
page: PropTypes.string,
children: PropTypes.node,
};
renderLocaleSwitch(curLocale) {
const { location } = this.props;
const pathName = location.pathname || '/';
return (
<span className="language-switch">
{locales.map(({ locale, text }, index) => {
const isActive = locale === curLocale;
const linkPath = pathName.indexOf(curLocale) >= 0 ? pathName.replace(curLocale, locale) : `/${locale}`;
return (
<span key={`item-${index}`}>
{index ? <span> | </span> : null}
{isActive ? (
<span className="switch-item active">{text}</span>
) : (
<Link className="switch-item" to={linkPath}>
{text}
</Link>
)}
</span>
);
})}
</span>
);
}
render() {
const { page, children } = this.props;
const locale = getLocaleType(this.props);
return (
<div className="container">
<Helmet titleTemplate="%s | Recharts" />
<Affix>
<header>
<div className="header-wrapper">
<h1 className="logo">
<Link className="nav-logo" to={`/${locale}`}>
<Recharts />
</Link>
</h1>
<nav>
<ul className="nav" id="nav">
{modules.map((entry, index) => (
<li key={`item-${index}`}>
<Link className={`nav-link ${entry === page ? 'active' : ''}`} to={`/${locale}/${entry}`}>
{localeGet(locale, 'frame', entry)}
</Link>
</li>
))}
<li className="github-wrapper">
<a
href="https://github.com/recharts/recharts"
target="_blank"
className="nav-github"
rel="noreferrer"
>
GitHub
</a>
</li>
<li className="language-switch-wrapper">{this.renderLocaleSwitch(locale)}</li>
</ul>
</nav>
</div>
</header>
</Affix>
{children}
<footer>
<p>
<span>Released under the </span>
<a href="http://opensource.org/licenses/MIT" target="_blank" rel="noreferrer">
MIT License
</a>
</p>
<p>Copyright (c) 2016-2021 Recharts Group</p>
</footer>
</div>
);
}
}
export default Frame;
|
client/App.js
|
Pennsy/todolist
|
/**
* Root Component
*/
import React from 'react';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import IntlWrapper from './modules/Intl/IntlWrapper';
// Import Routes
import routes from './routes';
// Base stylesheet
import 'todomvc-app-css/index.css'
//require('./main.css');
export default function App(props) {
return (
<Provider store={props.store}>
<IntlWrapper>
<Router history={browserHistory}>
{routes}
</Router>
</IntlWrapper>
</Provider>
);
}
App.propTypes = {
store: React.PropTypes.object.isRequired,
};
|
app/containers/BreadCrumbs/index.js
|
surzhik/coreola5
|
/**
* Created by home on 19.09.2016.
*/
import React from 'react';
import {connect} from 'react-redux';
import {Link} from 'react-router';
import {push} from 'react-router-redux';
import {createStructuredSelector} from 'reselect';
import {selectCrumbs} from '../App/selectors';
import {Breadcrumb, Icon} from 'antd';
import {m2s} from '../../utils/'
import {selectMessages} from '../LanguageProvider/selectors';
export class BreadCrumbs extends React.Component {
render() {
let messages = this.props.messages;
let crumbs = [{path: "/", name: m2s(messages("coreolaDashboardModuleMenuName"))}];
crumbs = [...crumbs, ...this.props.crumbs];
let crumbsItems = crumbs.map(function (item, index) {
return ( <Breadcrumb.Item key={index}><Link to={item.path}>{item.name}</Link></Breadcrumb.Item>)
});
return (
<Breadcrumb>
{crumbsItems}
</Breadcrumb>
)
}
}
BreadCrumbs.propTypes = {
changeRoute: React.PropTypes.func,
history: React.PropTypes.object,
dispatch: React.PropTypes.func,
crumbs: React.PropTypes.array,
messages: React.PropTypes.func
};
function mapDispatchToProps(dispatch) {
return {
changeRoute: (url) => dispatch(push(url)),
dispatch,
};
}
const mapStateToProps = createStructuredSelector({
crumbs: selectCrumbs(),
messages: selectMessages()
});
// Wrap the component to inject dispatch and state into it
export default connect(mapStateToProps, mapDispatchToProps)(BreadCrumbs);
|
src/pages/About/index.js
|
jcarva/select_title
|
import React from 'react'
import { Layout, Row, Col } from 'antd';
const { Content } = Layout;
// Require About component style
require('./style.sass');
export default () => {
return(
<div id="about">
<Content style={{ padding: '0 50px' }}>
<Row>
<Col span={12} offset={6}>
<Row type="flex" justify="center">
<h1>
A simple project to fetch data from an api and show the informations as a sortable and filterable list.
Using cutting-edge tecnologies you can use the skeleton of the repository to make great applications.
</h1>
<h1 id="source">You can check the source code <a href="https://github.com/jcarva/select_title">here</a>.</h1>
</Row>
</Col>
</Row>
</Content>
</div>
)
};
|
src/svg-icons/action/date-range.js
|
kittyjumbalaya/material-components-web
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionDateRange = (props) => (
<SvgIcon {...props}>
<path d="M9 11H7v2h2v-2zm4 0h-2v2h2v-2zm4 0h-2v2h2v-2zm2-7h-1V2h-2v2H8V2H6v2H5c-1.11 0-1.99.9-1.99 2L3 20c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H5V9h14v11z"/>
</SvgIcon>
);
ActionDateRange = pure(ActionDateRange);
ActionDateRange.displayName = 'ActionDateRange';
ActionDateRange.muiName = 'SvgIcon';
export default ActionDateRange;
|
examples/CarouselBasic.js
|
chris-gooley/react-materialize
|
import React from 'react';
import Carousel from '../src/Carousel';
export default
<Carousel images={[
'https://lorempixel.com/250/250/nature/1',
'https://lorempixel.com/250/250/nature/2',
'https://lorempixel.com/250/250/nature/3',
'https://lorempixel.com/250/250/nature/4',
'https://lorempixel.com/250/250/nature/5'
]} />;
|
src/client/story_box.js
|
uptownhr/hacker-menu
|
import React from 'react'
import _ from 'lodash'
import Client from 'electron-rpc/client'
import StoryList from './story_list.js'
import Spinner from './spinner.js'
import Menu from './menu.js'
import StoryType from '../model/story_type'
export default class StoryBox extends React.Component {
constructor (props) {
super(props)
this.client = new Client()
this.state = {
stories: [],
selected: StoryType.TOP_TYPE,
status: '',
version: '',
upgradeVersion: ''
}
}
componentDidMount () {
var self = this
self.client.request('current-version', function (err, version) {
if (err) {
console.error(err)
return
}
self.setState({ version: version })
})
self.onNavbarClick(self.state.selected)
}
onQuitClick () {
this.client.request('terminate')
}
onUrlClick (url) {
this.client.request('open-url', { url: url })
}
onMarkAsRead (id) {
this.client.request('mark-as-read', { id: id }, function () {
var story = _.findWhere(this.state.stories, { id: id })
story.hasRead = true
this.setState({ stories: this.state.stories })
}.bind(this))
}
onNavbarClick (selected) {
var self = this
self.setState({ stories: [], selected: selected })
self.client.localEventEmitter.removeAllListeners()
self.client.on('update-available', function (err, releaseVersion) {
if (err) {
console.error(err)
return
}
self.setState({ status: 'update-available', upgradeVersion: releaseVersion })
})
var storycb = function (err, storiesMap) {
if (err) {
return
}
// console.log(JSON.stringify(Object.keys(storiesMap), null, 2))
var stories = storiesMap[self.state.selected]
if (!stories) {
return
}
// console.log(JSON.stringify(stories, null, 2))
self.setState({stories: stories})
}
self.client.request(selected, storycb)
self.client.on(selected, storycb)
}
render () {
var navNodes = _.map(StoryType.ALL, function (selection) {
var className = 'control-item'
if (this.state.selected === selection) {
className = className + ' active'
}
return (
<a key={selection} className={className} onClick={this.onNavbarClick.bind(this, selection)}>{selection}</a>
)
}, this)
var content = null
if (_.isEmpty(this.state.stories)) {
content = <Spinner />
} else {
content = <StoryList stories={this.state.stories} onUrlClick={this.onUrlClick.bind(this)} onMarkAsRead={this.onMarkAsRead.bind(this)} />
}
return (
<div className='story-menu'>
<header className='bar bar-nav'>
<div className='segmented-control'>
{navNodes}
</div>
</header>
{content}
<Menu onQuitClick={this.onQuitClick.bind(this)} status={this.state.status} version={this.state.version} upgradeVersion={this.state.upgradeVersion} />
</div>
)
}
}
|
src/pages/404.js
|
thibmaek/thibmaek.github.io
|
/* eslint-disable react/prop-types */
import React from 'react';
import { Preview as PostPreview } from '../components/post/';
import random from '../lib/pickRandom';
const NotFoundPage = ({ data }) => {
const { node: post } = random(data.allContentfulPost.edges);
return (
<div>
<header>
<h1>
<span aria-label='Woman shrugging' role='img'>🤷🏼</span> There doesn't seem to be a page here…
</h1>
<p>But check out this cool article:</p>
</header>
<PostPreview excerpt={post.body.childMarkdownRemark.excerpt} timeToRead={post.body.childMarkdownRemark.timeToRead} {...post} />
</div>
);
};
export const query = graphql`
query RandomPostQuery {
allContentfulPost(limit: 10) {
edges {
node {
title,
date,
slug,
body {
childMarkdownRemark { excerpt, timeToRead }
}
}
}
}
}
`;
export default NotFoundPage;
|
test/ButtonGroupSpec.js
|
cgvarela/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ButtonGroup from '../src/ButtonGroup';
import Button from '../src/Button';
import { shouldWarn } from './helpers';
describe('ButtonGroup', () => {
it('Should output a button group', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.equal(React.findDOMNode(instance).nodeName, 'DIV');
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group\b/));
});
it('Should add size', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup bsSize='large'>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-lg\b/));
});
it('Should add vertical variation', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup vertical>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.equal(React.findDOMNode(instance).className.trim(), 'btn-group-vertical');
});
it('Should add block variation', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup vertical block>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-block\b/));
});
it('Should warn about block without vertical', () => {
ReactTestUtils.renderIntoDocument(
<ButtonGroup block>
<Button>
Title
</Button>
</ButtonGroup>
);
shouldWarn('The block property requires the vertical property to be set to have any effect');
});
it('Should add justified variation', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup justified>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-justified\b/));
});
});
|
bayty/src/components/common/Spinner.js
|
Asmaklf/bayty
|
import React from 'react';
import { View, ActivityIndicator } from 'react-native';
const Spinner = ({ size }) => {
return (
<View style={styles.spinnerStyle}>
<ActivityIndicator size={size || 'large'} />
</View>
);
};
const styles = {
spinnerStyle: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
};
export { Spinner };
|
app/javascript/mastodon/features/ui/components/actions_modal.js
|
abcang/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import StatusContent from '../../../components/status_content';
import Avatar from '../../../components/avatar';
import RelativeTimestamp from '../../../components/relative_timestamp';
import DisplayName from '../../../components/display_name';
import IconButton from '../../../components/icon_button';
import classNames from 'classnames';
export default class ActionsModal extends ImmutablePureComponent {
static propTypes = {
status: ImmutablePropTypes.map,
actions: PropTypes.array,
onClick: PropTypes.func,
};
renderAction = (action, i) => {
if (action === null) {
return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
}
const { icon = null, text, meta = null, active = false, href = '#' } = action;
return (
<li key={`${text}-${i}`}>
<a href={href} target='_blank' rel='noopener noreferrer' onClick={this.props.onClick} data-index={i} className={classNames({ active })}>
{icon && <IconButton title={text} icon={icon} role='presentation' tabIndex='-1' inverted />}
<div>
<div className={classNames({ 'actions-modal__item-label': !!meta })}>{text}</div>
<div>{meta}</div>
</div>
</a>
</li>
);
}
render () {
const status = this.props.status && (
<div className='status light'>
<div className='boost-modal__status-header'>
<div className='boost-modal__status-time'>
<a href={this.props.status.get('url')} className='status__relative-time' target='_blank' rel='noopener noreferrer'>
<RelativeTimestamp timestamp={this.props.status.get('created_at')} />
</a>
</div>
<a href={this.props.status.getIn(['account', 'url'])} className='status__display-name'>
<div className='status__avatar'>
<Avatar account={this.props.status.get('account')} size={48} />
</div>
<DisplayName account={this.props.status.get('account')} />
</a>
</div>
<StatusContent status={this.props.status} />
</div>
);
return (
<div className='modal-root__modal actions-modal'>
{status}
<ul className={classNames({ 'with-status': !!status })}>
{this.props.actions.map(this.renderAction)}
</ul>
</div>
);
}
}
|
src/Row.js
|
Cellule/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
const Row = React.createClass({
propTypes: {
componentClass: React.PropTypes.node.isRequired
},
getDefaultProps() {
return {
componentClass: 'div'
};
},
render() {
let ComponentClass = this.props.componentClass;
return (
<ComponentClass {...this.props} className={classNames(this.props.className, 'row')}>
{this.props.children}
</ComponentClass>
);
}
});
export default Row;
|
react-flux-mui/js/material-ui/src/Dialog/Dialog.spec.js
|
pbogdan/react-flux-mui
|
/* eslint-env mocha */
import React from 'react';
import Dialog from './Dialog';
import {spy} from 'sinon';
import {mount} from 'enzyme';
import {assert} from 'chai';
import TestUtils from 'react-addons-test-utils';
import getMuiTheme from '../styles/getMuiTheme';
describe('<Dialog />', () => {
const muiTheme = getMuiTheme();
const mountWithContext = (node) => mount(node, {context: {muiTheme}});
it('appends a dialog to the document body', () => {
const testClass = 'test-dialog-class';
mountWithContext(
<Dialog
open={true}
contentClassName={testClass}
/>
);
const dialogEl = document.getElementsByClassName(testClass)[0];
assert.ok(dialogEl);
});
it('registers events on dialog actions', () => {
const clickSpy = spy();
const testClass = 'dialog-action';
mountWithContext(
<Dialog
open={true}
actions={[
<button
key="a"
onClick={clickSpy}
className={testClass}
>
test
</button>,
]}
/>
);
const actionEl = document.getElementsByClassName(testClass)[0];
assert.ok(actionEl);
TestUtils.Simulate.click(actionEl);
assert.ok(clickSpy.called);
});
});
|
modules/Query/index.js
|
mjoslyn/react-prismic-hocs
|
//@flow
import React from 'react'
import { query } from '../queries'
import type { APIOptions } from 'prismic.io'
type Props = {
url: string,
apiOptions: APIOptions,
query: any,
queryKey: string,
predicates: Predicates,
predicateOptions: Options,
children: any
};
export default class Query extends React.Component {
props: Props;
state: {
loading: boolean,
prismic: any,
error: boolean | Error
}
static defaultProps = {
apiOptions: {},
query: false,
queryKey: '',
predicates: '',
predicateOptions: {}
}
constructor(props: Props) {
super(props)
this.state = {
loading: true,
prismic: false,
error: false
}
}
componentDidMount = () => {
const _this = this
query({ url: this.props.url, apiOptions: this.props.apiOptions, query: this.props.query, predicates: this.props.predicates, predicateOptions: this.props.predicateOptions })
.then( (response: any) => {
_this.setState({ loading: false, prismic: response })
})
.catch( (err: Error) => {
_this.setState({ loading: false, error: err })
})
}
render() {
const keyed = this.props.queryKey.length > 0
const prismic = {
queryKey: keyed ? this.props.queryKey: false,
[keyed ? `${this.props.queryKey}Loading` : 'loading']: this.state.loading,
[keyed ? `${this.props.queryKey}Error` : 'error']: this.state.error,
[keyed ? `${this.props.queryKey}Prismic` : 'prismic']: this.state.prismic
}
return (
<div>
{this.props.children(prismic)}
</div>
)
}
}
|
app/classifier/tasks/survey/summary.spec.js
|
zooniverse/Panoptes-Front-End
|
import { mount } from 'enzyme';
import assert from 'assert';
import counterpart from 'counterpart';
import React from 'react';
import Summary from './summary';
import { workflow } from '../../../pages/dev-classifier/mock-data';
import enLocale from '../../../locales/en';
counterpart.registerTranslations('en', enLocale);
const noIdentification = {
task: 'survey',
value: []
};
const oneIdentification = {
task: 'survey',
value: [{
choice: 'ar',
answers: {
ho: 'two',
be: [
'mo',
'ea'
]
},
filters: {}
}]
};
const twoIdentifications = {
task: 'survey',
value: [{
choice: 'ar',
answers: {
ho: 'one',
be: [
'mo'
]
},
filters: {}
}, {
choice: 'to',
answers: {
ho: 'two',
be: [
'ea'
],
in: 'n',
bt: 'Y'
},
filters: {}
}]
};
const task = workflow.tasks.survey;
const oneExpectedSummary = 'Armadillo: 2; Moving, Eating';
const twoExpectedSummary = ['Armadillo: 1; Moving', 'Tortoise: 2; Eating; Nope; HECK YES'];
describe('Survey task summary, no identifications, not expanded', function() {
const wrapper = mount(<Summary annotation={noIdentification} task={task} translation={task} />);
const question = wrapper.find('.question span').first();
const answers = wrapper.find('.answers .answer');
it('should summarise the survey task', function() {
const count = task.choicesOrder.length;
assert.equal(`Survey of ${count}`, question.text());
});
it('should show one answer node', function() {
assert.equal(answers.length, 1);
});
it('should summarise the number of identifications', function() {
assert.equal(answers.text(), 'No identifications');
});
});
describe('Survey task summary, no identifications, expanded', function() {
const wrapper = mount(<Summary annotation={noIdentification} task={task} translation={task} />);
const question = wrapper.find('.question span').first();
const answers = wrapper.find('.answers .answer');
it('should summarise the survey task', function() {
const count = task.choicesOrder.length;
assert.equal(`Survey of ${count}`, question.text());
});
it('should show one answer node', function() {
assert.equal(answers.length, 1);
});
it('should summarise the number of identifications', function() {
assert.equal(answers.text(), 'No identifications');
});
});
describe('Survey task summary, one identification, not expanded', function() {
const wrapper = mount(<Summary annotation={oneIdentification} task={task} translation={task} />);
const question = wrapper.find('.question span').first();
const answers = wrapper.find('.answers .answer');
it('should summarise the survey task', function() {
const count = task.choicesOrder.length;
assert.equal(`Survey of ${count}`, question.text());
});
it('should show one answer node', function() {
assert.equal(answers.length, 1);
});
it('should summarise the number of identifications', function() {
assert.equal(answers.text(), '1 identification');
});
});
describe('Survey task summary, one identification, expanded', function() {
const wrapper = mount(<Summary annotation={oneIdentification} task={task} translation={task} expanded={true} />);
const question = wrapper.find('.question span').first();
const answers = wrapper.find('.answers .answer');
it('should summarise the survey task', function() {
const count = task.choicesOrder.length;
assert.equal(`Survey of ${count}`, question.text());
});
it('should show two answer nodes', function() {
assert.equal(answers.length, 2);
});
it('should summarise the identification and questions', function() {
assert.equal(answers.last().text(), oneExpectedSummary);
});
});
describe('Survey task summary, two identifications, not expanded', function() {
const wrapper = mount(<Summary annotation={twoIdentifications} task={task} translation={task} />);
const question = wrapper.find('.question span').first();
const answers = wrapper.find('.answers .answer');
it('should summarise the survey task', function() {
const count = task.choicesOrder.length;
assert.equal(`Survey of ${count}`, question.text());
});
it('should show one answer node', function() {
assert.equal(answers.length, 1);
});
it('should summarise the number of identifications', function() {
assert.equal(answers.text(), '2 identifications');
});
});
describe('Survey task summary, two identifications, expanded', function() {
const wrapper = mount(<Summary annotation={twoIdentifications} task={task} translation={task} expanded={true} />);
const question = wrapper.find('.question span').first();
const answers = wrapper.find('.answers .answer');
it('should summarise the survey task', function() {
const count = task.choicesOrder.length;
assert.equal(`Survey of ${count}`, question.text());
});
it('should show three answer nodes', function() {
assert.equal(answers.length, 3);
});
it('should summarise the identification and questions', function() {
assert.equal(answers.at(0).text(), '2 identifications');
assert.equal(answers.at(1).text(), twoExpectedSummary[0]);
assert.equal(answers.at(2).text(), twoExpectedSummary[1]);
});
});
|
src/Parser/Paladin/Retribution/Modules/HolyPower/HolyPowerDetails.js
|
hasseboulen/WoWAnalyzer
|
import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Tab from 'Main/Tab';
import { formatPercentage, formatNumber } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import ResourceBreakdown from 'Parser/Core/Modules/ResourceTracker/ResourceBreakdown';
import HolyPowerTracker from './HolyPowerTracker';
import WastedHPIcon from '../../images/paladin_hp.jpg';
const holyPowerIcon = 'inv_helmet_96';
class HolyPowerDetails extends Analyzer {
static dependencies = {
holyPowerTracker: HolyPowerTracker,
};
get wastedHolyPowerPercent() {
return this.holyPowerTracker.wasted / (this.holyPowerTracker.wasted + this.holyPowerTracker.generated);
}
get suggestionThresholds() {
return {
actual: 1 - this.wastedHolyPowerPercent,
isLessThan: {
minor: 0.98,
average: 0.95,
major: 0.92,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(`You wasted ${formatNumber(this.holyPowerTracker.wasted)} Holy Power.`)
.icon(holyPowerIcon)
.actual(`${formatPercentage(this.wastedHolyPowerPercent)}% Holy Power wasted`)
.recommended(`Wasting <${formatPercentage(1 - recommended)}% is recommended.`);
});
}
statistic() {
return (
<StatisticBox
icon={(
<img
src={WastedHPIcon}
alt="Wasted Holy Power"
/>
)}
value={formatNumber(this.holyPowerTracker.wasted)}
label="Holy Power Wasted"
tooltip={`${formatPercentage(this.wastedHolyPowerPercent)}% wasted`}
/>
);
}
tab() {
return {
title: 'Holy Power Usage',
url: 'holy-power-usage',
render: () => (
<Tab title="Holy Power usage breakdown">
<ResourceBreakdown
tracker={this.holyPowerTracker}
resourceName="Holy Power"
showSpenders={true}
/>
</Tab>
),
};
}
statisticOrder = STATISTIC_ORDER.CORE(4);
}
export default HolyPowerDetails;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.