path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
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: [email protected] / 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;
|
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;
|
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>
)
}
}
|
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;
|
examples/js/selection/unselectable-table.js | rolandsusans/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
const selectRowProp = {
mode: 'checkbox',
clickToSelect: true,
unselectable: [ 1, 3 ] // give rowkeys for unselectable row
};
export default class UnSelectableTable extends React.Component {
render() {
return (
<BootstrapTable data={ products } selectRow={ selectRowProp }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/svg-icons/device/signal-wifi-1-bar-lock.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi1BarLock = (props) => (
<SvgIcon {...props}>
<path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z"/><path d="M15.5 14.5c0-2.8 2.2-5 5-5 .4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4C5.3 3 .8 6.7.4 7L12 21.5l3.5-4.3v-2.7z" opacity=".3"/><path d="M6.7 14.9l5.3 6.6 3.5-4.3v-2.6c0-.2 0-.5.1-.7-.9-.5-2.2-.9-3.6-.9-3 0-5.1 1.7-5.3 1.9z"/>
</SvgIcon>
);
DeviceSignalWifi1BarLock = pure(DeviceSignalWifi1BarLock);
DeviceSignalWifi1BarLock.displayName = 'DeviceSignalWifi1BarLock';
export default DeviceSignalWifi1BarLock;
|
src/components/Greeting.js | kesean/Dashboard-Frontend | import React from 'react'
import Paper from 'material-ui/Paper'
import {CardTitle} from 'material-ui/Card'
export default function Greeting(props) {
//Set greeting depending on hour of day
return(
<Paper zDepth={5} className="greeting">
<CardTitle>{getGreeting()}</CardTitle>
<CardTitle>{props.userFirst} {props.userLast}!</CardTitle>
</Paper>
)
}
function getGreeting(){
let time = new Date().getHours()
if (time >= 2 && time <= 11) {
return "Good Morning"
}else if (time >= 12 && time <= 17) {
return "Good Afternoon"
}else {
return "Good Evening"
}
}
|
data-browser-ui/public/app/components/tableComponents/td/numberTdComponent.js | CloudBoost/cloudboost | import React from 'react';
import ReactDOM from 'react-dom';
class NumberTdComponent extends React.Component {
constructor(){
super()
this.state = {}
}
componentDidMount(){
this.state = {
inputHidden:true
}
this.setState(this.state)
}
toggleInput(which,e){
if(which){
let string = this.props.elementData.toString()
this.props.updateElement(parseFloat(string.replace(/[^\d.-]/g, '')))
this.props.updateObject()
}
this.state['inputHidden'] = which
this.setState(this.state)
}
saveKeyAction(e){
if(e.which == 13){
this.toggleInput(true)
}
}
componentDidUpdate(){
if(!this.state['inputHidden']){
ReactDOM.findDOMNode(this.refs.Input).focus()
}
}
changeHandler(e){
this.props.updateElement(e.target.value)
}
render() {
let requiredClass = this.props.isRequired ? " requiredred":""
return (
<td className={ this.state.inputHidden ? ('mdl-data-table__cell--non-numeric pointer'+requiredClass) : 'mdl-data-table__cell--non-numeric pointer padleftright0' } onDoubleClick={this.toggleInput.bind(this,false)}>
<span className={!this.state.inputHidden ? 'hide':''}>{this.props.elementData ? this.props.elementData.toString().slice(0,20):''}</span>
<input ref="Input" value={this.props.elementData || "" } onChange={this.changeHandler.bind(this)} className={this.state.inputHidden ? 'hide':'form-control texttypetdinput'} onBlur={this.toggleInput.bind(this,true)} type="text" onKeyDown={ this.saveKeyAction.bind(this) }/>
</td>
);
}
}
export default NumberTdComponent; |
examples/simple/components/App.js | gaearon/library-boilerplate | import React, { Component } from 'react';
import { add } from 'library-boilerplate';
export default class App extends Component {
render() {
return (
<p>
2 + 2 = {add(2, 2)}
</p>
);
}
}
|
webapp-src/src/Admin/Navbar.js | babelouest/glewlwyd | import React, { Component } from 'react';
import i18next from 'i18next';
import messageDispatcher from '../lib/MessageDispatcher';
import apiManager from '../lib/APIManager';
class Navbar extends Component {
constructor(props) {
super(props);
this.state = {
config: props.config,
curNav: "users",
navDropdown: false,
profileList: props.profileList,
loggedIn: props.loggedIn
}
messageDispatcher.subscribe('Navbar', (message) => {
});
this.navigate = this.navigate.bind(this);
this.toggleLogin = this.toggleLogin.bind(this);
this.changeLang = this.changeLang.bind(this);
this.changeProfile = this.changeProfile.bind(this);
this.gotoManageUsers = this.gotoManageUsers.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({loggedIn: nextProps.loggedIn, profileList: nextProps.profileList});
}
navigate(e, page, navDropdown) {
e.preventDefault();
messageDispatcher.sendMessage('App', {type: "nav", message: page});
this.setState({curNav: page, navDropdown: navDropdown});
}
reloadApp(e) {
messageDispatcher.sendMessage('App', {type: "reloadApp"});
}
toggleLogin() {
if (this.state.loggedIn) {
apiManager.glewlwydRequest("/auth/?username=" + encodeURIComponent(this.state.profileList[0].username), "DELETE")
.then(() => {
messageDispatcher.sendMessage('Notification', {type: "info", message: i18next.t("login.success-delete-session")});
messageDispatcher.sendMessage('App', {type: 'loggedIn', loggedIn: false});
})
.fail((err) => {
if (err.status !== 401) {
messageDispatcher.sendMessage('Notification', {type: "danger", message: i18next.t("login.error-delete-session")});
}
messageDispatcher.sendMessage('App', {type: 'loggedIn', loggedIn: false});
});
} else {
var schemeDefault = false;
this.state.config.sessionSchemes.forEach((scheme) => {
if (scheme.scheme_default) {
scheme.scheme_default.forEach((page) => {
if (page === "admin") {
schemeDefault = scheme.scheme_name;
}
});
}
});
document.location.href = this.state.config.LoginUrl + "?callback_url=" + encodeURIComponent([location.protocol, '//', location.host, location.pathname].join('')) + "&scope=" + encodeURIComponent(this.state.config.admin_scope) + (schemeDefault?("&scheme="+encodeURIComponent(schemeDefault)):"");
}
}
changeLang(e, lang) {
i18next.changeLanguage(lang)
.then(() => {
this.setState({lang: lang});
messageDispatcher.sendMessage('App', {type: "lang"});
});
}
changeProfile(e, profile) {
e.preventDefault();
if (profile) {
apiManager.glewlwydRequest("/auth/", "POST", {username: profile.username})
.then(() => {
messageDispatcher.sendMessage('App', {type: "profile"});
})
.fail(() => {
messageDispatcher.sendMessage('Notification', {type: "danger", message: i18next.t("login.error-login")});
});
} else {
var schemeDefault = false;
this.state.config.sessionSchemes.forEach((scheme) => {
if (scheme.scheme_default) {
scheme.scheme_default.forEach((page) => {
if (page === "admin") {
schemeDefault = scheme.scheme_name;
}
});
}
});
document.location.href = this.state.config.LoginUrl + "?callback_url=" + encodeURIComponent([location.protocol, '//', location.host, location.pathname].join('')) + "&scope=" + encodeURIComponent(this.state.config.admin_scope) + (schemeDefault?("&scheme="+encodeURIComponent(schemeDefault)):"") + "&prompt=login";
}
}
gotoManageUsers(e) {
e.preventDefault();
document.location.href = this.state.config.LoginUrl + "?callback_url=" + encodeURIComponent([location.protocol, '//', location.host, location.pathname].join('')) + "&scope=" + encodeURIComponent(this.state.config.admin_scope) + "&prompt=select_account";
}
userHasScope(user, scope_list) {
var hasScope = false;
if (scope_list) {
scope_list.split(" ").forEach(scope => {
if (user.scope.indexOf(scope) > -1) {
hasScope = true;
}
});
}
return hasScope;
}
render() {
var langList = [], profileList = [], profileDropdown, loginButton;
var profilePicture;
this.state.config.lang.forEach((lang, i) => {
if (lang === i18next.language) {
langList.push(<a className="dropdown-item active" href="#" key={i}>{lang}</a>);
} else {
langList.push(<a className="dropdown-item" href="#" onClick={(e) => this.changeLang(e, lang)} key={i}>{lang}</a>);
}
});
if (this.state.profileList.length) {
this.state.profileList.forEach((profile, index) => {
if (this.userHasScope(profile, this.state.config.admin_scope)) {
profileList.push(<a className={"dropdown-item"+(!index?" active":"")} href="#" onClick={(e) => this.changeProfile(e, profile)} key={index}>{profile.name||profile.username}</a>);
} else {
profileList.push(<a className={"dropdown-item glwd-nav-user-unavailable"+(!index?" active":"")} key={index} href="#" disabled={true}>{profile.name||profile.username}</a>);
}
});
profileList.push(<div className="dropdown-divider" key={profileList.length}></div>);
profileList.push(<a className="dropdown-item" href="#" onClick={(e) => this.changeProfile(e, null)} key={profileList.length}>{i18next.t("profile.menu-session-new")}</a>);
profileList.push(<a className="dropdown-item" href="#" onClick={(e) => this.gotoManageUsers(e)} key={profileList.length}>{i18next.t("login.manage-users")}</a>);
if (this.state.profileList && this.state.profileList[0]) {
if (this.state.config.profilePicture && this.state.profileList[0][this.state.config.profilePicture.property]) {
var picData = this.state.profileList[0][this.state.config.profilePicture.property];
if (Array.isArray(picData)) {
picData = picData[0];
}
profilePicture =
<div className="glwd-nav-picture-div">
<img className="img-medium glwd-nav-picture-image" src={"data:image/*;base64,"+picData}/>
{this.state.profileList[0].username}
</div>
} else {
profilePicture =
<div className="glwd-nav-picture-div">
<img className="img-medium glwd-nav-picture-spacer" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" /> {/*1-pixel transparent image as spacer (Possible Bootstrap bug)*/}
<i className="fas fa-user">
</i>
{this.state.profileList[0].username}
</div>
}
}
profileDropdown =
<div className="btn-group" role="group">
<button className="btn btn-secondary dropdown-toggle" type="button" id="dropdownProfile" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<div className="glwd-nav-picture-container">
{profilePicture}
</div>
</button>
<div className="dropdown-menu" aria-labelledby="dropdownProfile">
{profileList}
</div>
</div>
}
if (this.state.loggedIn) {
loginButton = <button type="button" className="btn btn-secondary" onClick={this.toggleLogin} title={i18next.t("title-logout")}>
<i className="fas btn-icon fa-sign-out-alt"></i>
</button>
} else {
loginButton = <button type="button" className="btn btn-secondary" onClick={this.toggleLogin} title={i18next.t("title-login")}>
<i className="fas btn-icon fa-sign-in-alt"></i>
</button>
}
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="#">
<img className="mr-3" src="img/logo-admin.png" alt="logo"/>
{i18next.t("admin.menu-title")}
</a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
<li className={"nav-item" + (this.state.curNav==="users"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "users", false)}>
{i18next.t("admin.menu-users")}
</a>
</li>
<li className={"nav-item" + (this.state.curNav==="clients"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "clients", false)}>
{i18next.t("admin.menu-clients")}
</a>
</li>
<li className={"nav-item" + (this.state.curNav==="scopes"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "scopes", false)}>
{i18next.t("admin.menu-scopes")}
</a>
</li>
<li className={"d-md-none nav-item" + (this.state.curNav==="users-mod"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "users-mod", false)}>
{i18next.t("admin.menu-users-mod")}
</a>
</li>
<li className={"d-md-none nav-item" + (this.state.curNav==="clients-mod"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "clients-mod", false)}>
{i18next.t("admin.menu-clients-mod")}
</a>
</li>
<li className={"d-md-none nav-item" + (this.state.curNav==="auth-schemes"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "auth-schemes", false)}>
{i18next.t("admin.menu-auth-schemes")}
</a>
</li>
<li className={"d-md-none nav-item" + (this.state.curNav==="plugins"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "plugins", false)}>
{i18next.t("admin.menu-plugins")}
</a>
</li>
<li className={"d-md-none nav-item" + (this.state.curNav==="api-key"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "api-key", false)}>
{i18next.t("admin.menu-api-key")}
</a>
</li>
<li className="nav-item dropdown d-none d-md-block">
<a className={"nav-link dropdown-toggle" + (this.state.navDropdown?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{i18next.t("admin.menu-parameters")}
</a>
<div className={"dropdown-menu"} aria-labelledby="navbarDropdown">
<a className={"dropdown-item" + (this.state.curNav==="users-mod"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "users-mod", true)}>{i18next.t("admin.menu-users-mod")}</a>
<a className={"dropdown-item" + (this.state.curNav==="clients-mod"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "clients-mod", true)}>{i18next.t("admin.menu-clients-mod")}</a>
<div className="dropdown-divider"></div>
<a className={"dropdown-item" + (this.state.curNav==="users-middleware-mod"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "users-middleware-mod", true)}>{i18next.t("admin.menu-users-middleware-mod")}</a>
<div className="dropdown-divider"></div>
<a className={"dropdown-item" + (this.state.curNav==="auth-schemes"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "auth-schemes", true)}>{i18next.t("admin.menu-auth-schemes")}</a>
<div className="dropdown-divider"></div>
<a className={"dropdown-item" + (this.state.curNav==="plugins"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "plugins", true)}>{i18next.t("admin.menu-plugins")}</a>
<div className="dropdown-divider"></div>
<a className={"dropdown-item" + (this.state.curNav==="api-key"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "api-key", true)}>{i18next.t("admin.menu-api-key")}</a>
<div className="dropdown-divider"></div>
<a className={"dropdown-item" + (this.state.curNav==="misc-config"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "misc-config", true)}>{i18next.t("admin.menu-misc-config")}</a>
</div>
</li>
</ul>
<form className="form-inline my-2 my-lg-0">
<div className="btn-group" role="group">
<div className="btn-group" role="group">
<button disabled={!this.state.loggedIn} type="button" className="btn btn-secondary" onClick={(e) => this.reloadApp(e)} title={i18next.t("login.btn-reload")}>
<i className="fas fa-refresh"></i>
</button>
<button className="btn btn-secondary dropdown-toggle" type="button" id="dropdownLang" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i className="fas fa-language"></i>
</button>
<div className="dropdown-menu" aria-labelledby="dropdownLang">
{langList}
</div>
</div>
{profileDropdown}
{loginButton}
</div>
</form>
</div>
</nav>
);
}
}
export default Navbar;
|
src/containers/AppContainer/index.js | pnicolli/demo-calculator | import React, { Component } from 'react';
import App from '../../views/App';
class AppContainer extends Component {
initialState = () => ({
negativeSign: false,
intValue: '0',
decimalValue: '',
showComma: false,
firstOperand: 0,
currentOperation: null,
resetNumberOnNextDigit: false,
});
constructor(props) {
super(props);
this.state = this.initialState();
}
// AC button
resetState = () => this.setState(this.initialState);
// C button
resetCurrentValue = () => this.setState((prevState, props) => ({
...this.initialState(),
firstOperand: prevState.firstOperand,
currentOperation: prevState.currentOperation,
}));
invertSign = () => this.setState((prevState, props) => ({
negativeSign: !prevState.negativeSign,
}));
// concat a digit, or replace the whole string if it is just '0'
// TODO: unit test this
addIntDigit = (digit, numString) => (
numString === '0' ? digit : numString.concat(digit)
);
// add the digit to the correct state number,
// using showComma to decide which one is the correct one
// TODO: unit test this
numberClick = digit => this.setState((prevState, props) => {
if (prevState.resetNumberOnNextDigit) {
return {
...this.initialState(),
intValue: digit,
firstOperand: this.numFromState(prevState),
currentOperation: prevState.currentOperation,
};
}
if (prevState.showComma) {
return { decimalValue: prevState.decimalValue.concat(digit) };
}
else {
return { intValue: this.addIntDigit(digit, prevState.intValue) };
}
});
// create an actual number from the given state
// TODO: unit test this
numFromState = state => {
let number = parseInt(state.intValue, 10);
if (state.showComma && state.decimalValue !== '') {
// compute 0.2345 from string '2345'
const numOfDigits = state.decimalValue.length;
const decimalNumber = parseInt(state.decimalValue, 10);
const decimalPart = decimalNumber / Math.pow(10, numOfDigits);
number += decimalPart;
}
if (state.negativeSign) {
number *= (-1);
}
return number;
};
// set the next operation to be performed
// TODO compute current operation, if given, before assigning the new one
// in order to allow chaining operations
setOperation = op => this.setState((prevState, props) => ({
currentOperation: op,
firstOperand: this.numFromState(prevState),
resetNumberOnNextDigit: true,
}));
// start typing decimal part of the number (a.k.a. show comma)
startDecimal = () => this.setState(() => ({
showComma: true,
}));
// called when '=' is pressed TODO
// computes operation based on the current state
computeNow = () => this.setState((prevState, props) => this.computeOperation(prevState));
// compute the operation described by the given state
// TODO: unit test this
computeOperation = state => {
//no-op if no operation is set
if (!state.currentOperation) {
return state;
}
const firstOperand = state.firstOperand;
const secondOperand = this.numFromState(state);
let result;
switch (state.currentOperation) {
case '+':
result = firstOperand + secondOperand;
break;
case '-':
result = firstOperand - secondOperand;
break;
case '/':
// TODO handle division by 0
result = firstOperand / secondOperand;
break;
case 'x':
result = firstOperand * secondOperand;
break;
default:
result = 0;
break;
}
const negativeSign = result < 0;
if (negativeSign) {
result *= (-1);
}
const numStrings = result.toString().split('.');
const hasDecimal = numStrings.length > 1;
return {
...this.initialState(),
intValue: numStrings[0],
decimalValue: hasDecimal ? numStrings[1] : '',
showComma: hasDecimal,
negativeSign: negativeSign,
resetNumberOnNextDigit: true,
};
};
// compute text to display from given state
// TODO: unit test this
textToDisplay = state => {
let text = state.negativeSign ? '-' : '';
text += state.intValue;
if (state.showComma) {
text += ',' + state.decimalValue;
}
return text;
}
controls = [
{ text: 'AC', className: 'dark smaller', onClick: this.resetState },
{ text: '7', onClick: () => this.numberClick('7') },
{ text: '4', onClick: () => this.numberClick('4') },
{ text: '1', onClick: () => this.numberClick('1') },
{ text: '0', onClick: () => this.numberClick('0') },
{ text: 'C', className: 'dark smaller', onClick: this.resetCurrentValue },
{ text: '8', onClick: () => this.numberClick('8') },
{ text: '5', onClick: () => this.numberClick('5') },
{ text: '2', onClick: () => this.numberClick('2') },
{ text: '.', className: 'dark', onClick: this.startDecimal },
{ text: '+/−', className: 'dark smaller', onClick: this.invertSign },
{ text: '9', onClick: () => this.numberClick('9') },
{ text: '6', onClick: () => this.numberClick('6') },
{ text: '3', onClick: () => this.numberClick('3') },
{ text: '=', className: 'dark', onClick: this.computeNow },
{ text: '÷', className: 'dark', onClick: () => this.setOperation('/') },
{ text: '×', className: 'dark', onClick: () => this.setOperation('x') },
{ text: '−', className: 'dark', onClick: () => this.setOperation('-') },
{ text: '+', className: 'dark double', onClick: () => this.setOperation('+') },
];
render() {
return (
<App
currentValue={this.textToDisplay(this.state)}
controls={[...this.controls]}
/>
);
}
}
export default AppContainer;
|
src/components/modals/alert_modal.js | dcporter44/tunefest-frontend | import React, { Component } from 'react';
import { RaisedButton } from 'material-ui';
export default class AlertModal extends Component {
render () {
return (
<div className="modal modal-sm">
<div className="modal-content">
<div className="modal-body">
{this.props.text}
</div>
<div className="modal-footer">
<RaisedButton autoFocus label="OK" primary={true} onClick={this.props.closeModal} />
</div>
</div>
</div>
)
}
}
|
pages/apply-now.js | aimanaiman/supernomadfriendsquad | import React from 'react'
import Helmet from 'react-helmet'
import { config } from 'config'
import { prefixLink } from 'gatsby-helpers'
import { Link } from 'react-router'
import skype from '../icon/skype.png'
import pencil from '../icon/pencil.png'
import gift from '../icon/gift.png'
import businessman from '../icon/businessman.png'
import tie from '../icon/tie.png'
export default class ApplyNow extends React.Component {
render () {
return (
<div>
<Helmet
title={`${config.siteTitle} | Application`}
/>
<div className="hero" id="apply-now-hero">
<div className="overlay">
<h1 style={{color:'#f3f3f3'}}>Here We Go . . .</h1>
</div>
</div>
<section id="proccess" >
<div className="gallery">
<h1>The Proccess</h1>
</div>
<div className="row center-xs">
<div className="col-xs-6 col-lg-3">
<img src={pencil} alt=""/>
<p>Fill in the application form below.</p>
</div>
<div className="col-xs-6 col-lg-3">
<img src={skype} alt=""/>
<p>We set up a skype call interview.</p>
</div>
<div className="col-xs-6 col-lg-3">
<img src={tie} alt=""/>
<p>We assess all applicants and select 50 Super Nomad Friend Squad Members. "12 Angry Men" style.</p>
</div>
<div className="col-xs-6 col-lg-3">
<img src={gift} alt=""/>
<p>Once approved we will send you an awesome care package to all our successful applicants.</p>
</div>
</div>
</section>
<section id="application-form" style={{backgroundColor:'#ecf0f1'}}>
<div className="gallery">
<h1>Application Form</h1>
</div>
<div className="row around-xs" id="form">
<div className="col-xs-10 col-lg-5" style={{padding:'0'}} >
<form name="application" data-netlify={true} data-netlify-honeypot={true}>
<label htmlFor="name">Name:</label>
<input type="text" name="name" placeholder="Sandy H. Warmbuns" required />
<label htmlFor="email">Email:</label>
<input type="email" name="email" placeholder="[email protected]" required />
<label htmlFor="skype">Skype ID:</label>
<input type="text" name="skype" placeholder="the.warmest.bun" required />
<label htmlFor="gender" className="gender">Gender:</label>
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
<label htmlFor="occupation">What do you do for a living?</label>
<input type="text" name="occupation" placeholder="Bun Warmer" />
<label htmlFor="citizenship">Country of Citizenship:</label>
<input type="text" name="citizenship" placeholder="Narnia" />
<label htmlFor="remote-work">
Are you currently working remotely?
</label>
<label htmlFor="yes" className="yes-no">
<input type="radio" name="remote-work" value="yes" id="yes"/>Yes
</label>
<label htmlFor="no" className="yes-no" style={{marginTop:'0'}}>
<input type="radio" name="remote-work" value="no" id="no"/>No
</label>
<label htmlFor="income" className="income">Income Level?</label>
<select name="income" id="income">
<option value="25k">0 - $25,000</option>
<option value="25k-75k">$25,000 - $75,000</option>
<option value="75k-150k">$75,000 - $150,000</option>
<option value="150k">$150,000 and above</option>
</select>
<label htmlFor="about-you">
Tell us a little about yourself. About your daily routines.
</label>
<textarea type="textarea" name="about-you" placeholder="" />
<label htmlFor="why">
Why do you want to join our program?
</label>
<textarea type="why" name="why" placeholder="" />
<div className="row around-xs">
<button className="col-xs-12">
<Link to="/success">Submit</Link>
</button>
</div>
</form>
</div>
</div>
</section>
</div>
)
}
} |
src/index.js | simoneas02/contracts-list | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
|
packages/icons/src/md/action/List.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdList(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M6 26h4v-4H6v4zm0 8h4v-4H6v4zm0-16h4v-4H6v4zm8 8h28v-4H14v4zm0 8h28v-4H14v4zm0-20v4h28v-4H14z" />
</IconBase>
);
}
export default MdList;
|
app/shared/wrapper.component.js | TPW-team/tpw_ui | import React from 'react';
export const Wrapper = ({component: Component, ...rest}) => (
<Component {...rest}></Component>
); |
src/components/decoline_item.js | lizarraldeignacio/personal-website | import React, { Component } from 'react';
/**
DecolineItem atomic element of DecoLine list
Params:
title: The title of the element
description: The description of the element
remove: A function to handle the removal of this item from the list
auth: A flag that indicates if the user is authenticated or not
**/
class DecolineItem extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="o-grid__col-md-4 o-grid__col-sm-6">
<div className="o-media o-media--block">
<div className="o-content">
<hr className="c-deco-line t-primary-color-line" />
<div className="o-content__body">
<h3>{this.props.title}</h3>
<p>{this.props.description}</p>
</div>
</div>
{this.props.auth &&
<div className="o-media__figure inline-elem-rigth">
<div className="materialize-iso inline-elem btn-add">
<a className="btn-floating btn-tiny waves-effect waves-light red"
href="javascript:void(0);"
onClick={() => {this.props.remove(this.props.title)}}>
<i className="material-icons">clear</i>
</a>
</div>
</div>}
</div>
</div>
);
}
}
export default DecolineItem;
|
app/components/map/footer/index.js | Vizzuality/forest-watcher | // @flow
import type { Alert, SelectedAlert } from 'types/alerts.types';
import type { MapItemFeatureProperties } from 'types/common.types';
import type { SelectedReport } from 'types/reports.types';
import type { LocationPoint } from 'types/routes.types';
import React, { Component } from 'react';
import { Animated, View } from 'react-native';
import CircleButton from 'components/common/circle-button';
import InfoBanner from 'components/map/info-banner';
import LocationErrorBanner from 'components/map/locationErrorBanner';
import { withSafeArea } from 'react-native-safe-area';
const FooterSafeAreaView = withSafeArea(View, 'margin', 'bottom');
const FooterBackgroundSafeAreaView = withSafeArea(View, 'padding', 'bottom');
const startTrackingIcon = require('assets/startTracking.png');
const stopTrackingIcon = require('assets/stopTracking.png');
const myLocationIcon = require('assets/my_location.png');
const createReportIcon = require('assets/createReport.png');
const addLocationIcon = require('assets/add_location.png');
const cancelIcon = require('assets/cancel.png');
import styles from './styles';
type Props = {|
animatedPosition: Animated.Value,
customReporting: boolean,
isRouteTracking: boolean,
locationError: ?number,
onCustomReportingPress: () => void,
onReportSelectionPress: () => void,
onSelectAllConnectedAlertsPress: ($ReadOnlyArray<Alert>) => void,
onSelectionCancelPress: () => void,
onStartTrackingPress: () => void,
onStopTrackingPress: () => void,
onZoomToUserLocationPress: () => void,
connectedAlerts: $ReadOnlyArray<SelectedAlert>,
highlightedAlerts: $ReadOnlyArray<Alert>,
selectedAlerts: $ReadOnlyArray<SelectedAlert>,
selectedReports: $ReadOnlyArray<SelectedReport>,
tappedOnFeatures: $ReadOnlyArray<MapItemFeatureProperties>,
userLocation: ?LocationPoint
|};
export default class MapFooter extends Component<Props> {
renderButtonPanel() {
const {
animatedPosition,
connectedAlerts,
customReporting,
isRouteTracking,
userLocation,
locationError,
selectedAlerts,
highlightedAlerts,
selectedReports,
tappedOnFeatures,
onReportSelectionPress,
onCustomReportingPress,
onZoomToUserLocationPress,
onSelectionCancelPress,
onStartTrackingPress,
onStopTrackingPress,
onSelectAllConnectedAlertsPress
} = this.props;
const hasAlertsSelected = selectedAlerts && selectedAlerts.length > 0;
const hasReportSelected = selectedReports?.length;
const canReport = hasAlertsSelected || hasReportSelected || customReporting;
// To fix the missing signal text overflow rendering in reverse row
// last to render will be on top of the others
return (
<React.Fragment>
<LocationErrorBanner
style={styles.locationErrorBanner}
locationError={locationError}
mostRecentLocationTime={userLocation?.timestamp}
/>
<Animated.View style={{ transform: [{ translateY: animatedPosition }] }}>
<InfoBanner
style={styles.infoBanner}
tappedOnFeatures={tappedOnFeatures}
connectedAlerts={connectedAlerts}
highlightedAlerts={highlightedAlerts}
onSelectAllConnectedAlertsPress={onSelectAllConnectedAlertsPress}
/>
</Animated.View>
<View style={styles.buttonPanel}>
{canReport ? (
<CircleButton shouldFillContainer onPress={onReportSelectionPress} light icon={createReportIcon} />
) : (
<CircleButton shouldFillContainer onPress={onCustomReportingPress} icon={addLocationIcon} />
)}
{userLocation ? (
<CircleButton shouldFillContainer onPress={onZoomToUserLocationPress} light icon={myLocationIcon} />
) : null}
{canReport ? (
<CircleButton shouldFillContainer onPress={onSelectionCancelPress} light icon={cancelIcon} />
) : null}
{isRouteTracking || canReport ? (
<CircleButton
shouldFillContainer
onPress={isRouteTracking ? onStopTrackingPress : onStartTrackingPress}
light
icon={isRouteTracking ? stopTrackingIcon : startTrackingIcon}
/>
) : null}
</View>
</React.Fragment>
);
}
render() {
return [
<FooterBackgroundSafeAreaView key="bg" pointerEvents="none" style={styles.footerBGContainer}>
<View style={styles.buttonPanelTray} />
</FooterBackgroundSafeAreaView>,
<FooterSafeAreaView key="footer" pointerEvents="box-none" style={styles.footer}>
{this.renderButtonPanel()}
</FooterSafeAreaView>
];
}
}
|
src/js/contexts/ResponsiveContext/ResponsiveContext.js | HewlettPackard/grommet | import React from 'react';
import { ResponsiveContextPropTypes } from './propTypes';
export const ResponsiveContext = React.createContext(undefined);
ResponsiveContext.propTypes = ResponsiveContextPropTypes;
|
app/javascript/mastodon/features/compose/components/character_counter.js | masto-donte-com-br/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { length } from 'stringz';
export default class CharacterCounter extends React.PureComponent {
static propTypes = {
text: PropTypes.string.isRequired,
max: PropTypes.number.isRequired,
};
checkRemainingText (diff) {
if (diff < 0) {
return <span className='character-counter character-counter--over'>{diff}</span>;
}
return <span className='character-counter'>{diff}</span>;
}
render () {
const diff = this.props.max - length(this.props.text);
return this.checkRemainingText(diff);
}
}
|
src/containers/NotFound/container/NotFound.js | WCCrazyCoder/react-redux-web-application | import React from 'react';
export default class NotFound extends React.Component {
render() {
return (
<div>
<h1>...喔噢... 404 not found.</h1>
</div>
)
}
}
|
src/TextField/TextField.js | dsslimshaddy/material-ui | // @flow
import React from 'react';
import type { Element } from 'react';
import Input, { InputLabel } from '../Input';
import FormControl from '../Form/FormControl';
import FormHelperText from '../Form/FormHelperText';
export type Props = {
/**
* This property helps users to fill forms faster, especially on mobile devices.
* The name can be confusion, it's more like an autofill.
* You can learn about it with that article
* https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill
*/
autoComplete?: string,
/**
* If `true`, the input will be focused during the first mount.
*/
autoFocus?: boolean,
/**
* @ignore
*/
className?: string,
/**
* The default value of the `Input` element.
*/
defaultValue?: string,
/**
* If `true`, the input will be disabled.
*/
disabled?: boolean,
/**
* If `true`, the label will be displayed in an error state.
*/
error?: boolean,
/**
* Properties applied to the `FormHelperText` element.
*/
FormHelperTextProps?: Object,
/**
* If `true`, the input will take up the full width of its container.
*/
fullWidth?: boolean,
/**
* The helper text content.
*/
helperText?: string | Element<*>,
/**
* The CSS class name of the helper text element.
*/
helperTextClassName?: string,
/**
* The id of the `input` element.
*/
id?: string,
/**
* The CSS class name of the `input` element.
*/
inputClassName?: string,
/**
* The CSS class name of the `Input` element.
*/
InputClassName?: string,
/**
* Properties applied to the `InputLabel` element.
*/
InputLabelProps?: Object,
/**
* Properties applied to the `input` element.
*/
inputProps?: Object,
/**
* Properties applied to the `Input` element.
*/
InputProps?: Object,
/**
* Use that property to pass a ref callback to the native input component.
*/
inputRef?: Function,
/**
* The label content.
*/
label?: string | Element<*>,
/**
* The CSS class name of the label element.
*/
labelClassName?: string,
/**
* If `true`, a textarea element will be rendered instead of an input.
*/
multiline?: boolean,
/**
* Name attribute of the `Input` element.
*/
name?: string,
placeholder?: string,
/**
* If `true`, the label is displayed as required.
*/
required?: boolean,
/**
* Use that property to pass a ref callback to the root component.
*/
rootRef?: Function,
/**
* Number of rows to display when multiline option is set to true.
*/
rows?: string | number,
/**
* Maximum number of rows to display when multiline option is set to true.
*/
rowsMax?: string | number,
/**
* Type attribute of the `Input` element. It should be a valid HTML5 input type.
*/
type?: string,
/**
* The value of the `Input` element, required for a controlled component.
*/
value?: string | number,
/**
* If `dense` | `normal`, will adjust vertical spacing of this and contained components.
*/
margin?: 'none' | 'dense' | 'normal',
};
function TextField(props: Props) {
const {
autoComplete,
autoFocus,
className,
defaultValue,
disabled,
error,
id,
inputClassName,
InputClassName,
inputProps: inputPropsProp,
InputProps,
inputRef,
label,
labelClassName,
InputLabelProps,
helperText,
helperTextClassName,
FormHelperTextProps,
fullWidth,
required,
type,
multiline,
name,
placeholder,
rootRef,
rows,
rowsMax,
value,
...other
} = props;
let inputProps = inputPropsProp;
if (inputClassName) {
inputProps = {
className: inputClassName,
...inputProps,
};
}
return (
<FormControl
fullWidth={fullWidth}
ref={rootRef}
className={className}
error={error}
required={required}
{...other}
>
{label &&
<InputLabel htmlFor={id} className={labelClassName} {...InputLabelProps}>
{label}
</InputLabel>}
<Input
autoComplete={autoComplete}
autoFocus={autoFocus}
className={InputClassName}
defaultValue={defaultValue}
disabled={disabled}
multiline={multiline}
name={name}
rows={rows}
rowsMax={rowsMax}
type={type}
value={value}
id={id}
inputProps={inputProps}
inputRef={inputRef}
placeholder={placeholder}
{...InputProps}
/>
{helperText &&
<FormHelperText className={helperTextClassName} {...FormHelperTextProps}>
{helperText}
</FormHelperText>}
</FormControl>
);
}
TextField.defaultProps = {
required: false,
};
export default TextField;
|
app/javascript/mastodon/features/notifications/components/clear_column_button.js | clworld/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Icon from 'mastodon/components/icon';
export default class ClearColumnButton extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func.isRequired,
};
render () {
return (
<button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.props.onClick}><Icon id='eraser' /> <FormattedMessage id='notifications.clear' defaultMessage='Clear notifications' /></button>
);
}
}
|
src/svg-icons/action/hourglass-full.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionHourglassFull = (props) => (
<SvgIcon {...props}>
<path d="M6 2v6h.01L6 8.01 10 12l-4 4 .01.01H6V22h12v-5.99h-.01L18 16l-4-4 4-3.99-.01-.01H18V2H6z"/>
</SvgIcon>
);
ActionHourglassFull = pure(ActionHourglassFull);
ActionHourglassFull.displayName = 'ActionHourglassFull';
ActionHourglassFull.muiName = 'SvgIcon';
export default ActionHourglassFull;
|
docs/app/Examples/elements/Loader/Variations/LoaderExampleInline.js | koenvg/Semantic-UI-React | import React from 'react'
import { Loader } from 'semantic-ui-react'
const LoaderExampleInline = () => (
<Loader active inline />
)
export default LoaderExampleInline
|
test/fixtures/bugfix-175/actual.js | oliviertassinari/babel-plugin-transform-react-remove-prop-types | import React from 'react';
import PropTypes from 'prop-types';
const sharedPropType = PropTypes.number;
export default class Foo extends React.Component {
static propTypes = {
bar: sharedPropType,
}
}
|
src/routes/x-axis-assembly/XAxisAssembly.js | bigearth/www.clone.earth | import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './XAxisAssembly.css';
import { Grid, Row, Col, Image } from 'react-bootstrap';
import DocsTOC from '../../components/DocsTOC';
class XAxisAssembly extends React.Component {
render() {
return (
<Grid fluid>
<Row className={s.root}>
<Col xs={12} sm={12} md={2} lg={2} >
<DocsTOC selected="/x-axis-assembly" />
</Col>
<Col xs={12} sm={12} md={10} lg={10}>
<Row>
<Col xs={12} md={6}>
<h2>X Axis Assembly</h2>
<h3 id='step1'>Step 1 Gather materials</h3>
<h4>Tools</h4>
<ul>
<li>Needle nose pliers x1</li>
<li>2 mm Hex key</li>
<li>1.5 mm Hex key</li>
</ul>
<h4>3D printed parts</h4>
<ul>
<li>Carriage x1</li>
<li>Motor x1</li>
<li>Idler x1</li>
</ul>
<h4>Hardware</h4>
<ul>
<li>
Rods
<ul>
<li>M8 Chrome rod 35 cm x2</li>
</ul>
</li>
<li>
Nuts & Bolts
<ul>
<li>M3x10 screw x2</li>
<li>M3x18 screw x4</li>
<li>M3x16 screw x2</li>
<li>M3 square nut x2</li>
<li>M3 locknut x1</li>
<li>GT2 pulley x1</li>
<li>Idler Bearing x1</li>
<li>Linear bearings x7</li>
</ul>
</li>
<li>
Electronics
<ul>
<li>Nema 17 stepper motor x1</li>
<li>X axis endstop x1</li>
</ul>
</li>
<li>
Miscellaneous
<ul>
<li>Zip tie 10 cm x6</li>
<li>GT2 belt 68 cm x1</li>
</ul>
</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-1.jpg'>
<Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-1.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step2'>Step 2 Assemble the Y-axis rods</h3>
<h4>Hardware</h4>
<ul>
<li>Linear Bearings x3</li>
<li>Chrome rods 35 cm x2</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-2-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-2-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Carefully slide linear bearings on rods.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-2-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-2-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step3'>Step 3 Prepare the printed parts</h3>
<h4>Hardware</h4>
<ul>
<li>Linear Bearing x4</li>
<li>X-end-motor</li>
<li>X-end-idler</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-3-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-3-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Insert linear bearing into the printed parts.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-3-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-3-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step4'>Step 4 Prepare the tension screws</h3>
<h4>Hardware</h4>
<ul>
<li>M3 squre nut x2</li>
<li>M3x10 screw x2</li>
<li>X-end-idler</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-4-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-4-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Insert M3 square nuts and put in place M3x10 screws.</li>
<li>Avoid overtightening of the screws.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-4-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-4-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step5'>Step 5 Assemble the X-axis base</h3>
<h4>Hardware</h4>
<ul>
<li>Assembled y-axis rods</li>
<li>Prepared printed parts</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-5-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-5-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Insert the rods with bearings fully into the printed parts.</li>
<li>Ensure the correct orientation of the parts and rods (rod with 2 bearings must be on the side with the nut trap).</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-5-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-5-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step6'>Step 6 Preparing the X-end idler</h3>
<h4>Hardware</h4>
<ul>
<li>M3x18 screw x1</li>
<li>bearing w/ housing x1</li>
<li>M3 locknut x1</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-6-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-6-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Insert the bearing into the X-end idler.</li>
<li>Secure it in position using M3x18 screw.</li>
<li>Tighten it with M3 nylock nut, but the idler (wheel) must rotate freely.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-6-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-6-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step7'>Step 7 Prepare the X carriage</h3>
<h4>Hardware</h4>
<ul>
<li>X Carriage</li>
<li>Zip tie x6</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-7-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-7-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Insert zipties into the X-carriage.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-7-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-7-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step8'>Step 8 Placing the X carriage</h3>
<h4>Hardware</h4>
<ul>
<li>Assembled X axis base</li>
<li>Prepared X Carriage</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Place the X-carriage on the X-axis base.</li>
<li>Ensure the correct orientation of X-carriage.</li>
<li>Use pliers to tighten the zipties.</li>
<li>Use pliers to cut off any excess ziptie.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-b.jpg' />
</a>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-d.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-d.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step9'>Step 9 Assemble the X Motor</h3>
<h4>Hardware</h4>
<ul>
<li>M3x18 screw x3</li>
<li>Stepper motor</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-9-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-9-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Tighten the motor to the X-end-motor part.</li>
<li>Ensure the correct position of cables (Cables should face down).</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-9-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-9-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step10'>Step 10 Assemble the X motor pulley</h3>
<h4>Hardware</h4>
<ul>
<li>GT2 Pulley</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-10-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-10-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Place GT2 pulley on the X motor shaft.</li>
<li>Tighten up the pulley.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-10-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-10-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step11'>Step 11 Assemble the X endstop</h3>
<h4>Hardware</h4>
<ul>
<li>X Endstop</li>
<li>M3x16 screw x2</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-11-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-11-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Place the endstop on the printed part and insert </li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-11-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-11-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='allDone'>All Done!</h3>
<p>Congratulations! Now on to the next step.</p>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/done.jpg'>
<Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/done.jpg' />
</a>
</Col>
</Row>
</Col>
</Row>
</Grid>
);
}
}
export default withStyles(s)(XAxisAssembly);
|
src/svg-icons/communication/rss-feed.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationRssFeed = (props) => (
<SvgIcon {...props}>
<circle cx="6.18" cy="17.82" r="2.18"/><path d="M4 4.44v2.83c7.03 0 12.73 5.7 12.73 12.73h2.83c0-8.59-6.97-15.56-15.56-15.56zm0 5.66v2.83c3.9 0 7.07 3.17 7.07 7.07h2.83c0-5.47-4.43-9.9-9.9-9.9z"/>
</SvgIcon>
);
CommunicationRssFeed = pure(CommunicationRssFeed);
CommunicationRssFeed.displayName = 'CommunicationRssFeed';
CommunicationRssFeed.muiName = 'SvgIcon';
export default CommunicationRssFeed;
|
client/portfolio2017/src/Components/Routs/ProjectsRoute/ProjectsRoute.js | corrortiz/portafolio2017 | import React from 'react';
//Internal Components
import ListOfProjects from '../../ListOfProjects/ListOfProjects';
import FooterApp from '../../FooterApp/FooterApp';
//locale Assest
import { Projects } from '../../../Assets/diccionary';
/**
* layout of the projects rout
*/
const ProjectsRoute = () => {
return (
<div>
<FooterApp title={Projects} />
<ListOfProjects />
</div>
);
};
export default ProjectsRoute;
|
docs/app/Examples/elements/Header/Types/HeaderExampleContent.js | vageeshb/Semantic-UI-React | import React from 'react'
import { Header } from 'semantic-ui-react'
const HeaderExampleContent = () => (
<div>
<Header size='huge'>Huge Header</Header>
<Header size='large'>Large Header</Header>
<Header size='medium'>Medium Header</Header>
<Header size='small'>Small Header</Header>
<Header size='tiny'>Tiny Header</Header>
</div>
)
export default HeaderExampleContent
|
src/components/storyComment/StoryComment.js | ummahusla/Hacker-Reader | import React, { Component } from 'react';
import { Button } from 'react-bootstrap';
import Navigation from '../navigation/Navigation';
import ScoreLabel from '../shared-components/scoreLabel/ScoreLabel';
import AuthorLabel from '../shared-components/authorLabel/AuthorLabel';
import DateLabel from '../shared-components/dateLabel/DateLabel';
import './StoryComment.css';
import * as api from '../../helpers/api';
class StoryComment extends Component {
constructor(props) {
super(props);
this.state = {
storyItems: []
};
}
loadStoryItems() {
api.getStoryItem(this.props.params.id)
.then((response) => {
if(response.data) {
this.setState({ storyItems: response.data });
}
});
}
componentDidMount() {
this.loadStoryItems();
}
render() {
const storyItem = this.state.storyItems;
return (
<div>
<Navigation />
<div className="container">
<div className="row">
<div className="col-12">
<div>
<Button href={storyItem.url} className="story-header" bsStyle="link"><h3>{storyItem.title}</h3></Button>
</div>
</div>
</div>
<div className="row">
<div className="col-12">
<div>
<ScoreLabel score={storyItem.score}/>
<AuthorLabel author={storyItem.by}/>
<DateLabel date={storyItem.time}/>
</div>
</div>
</div>
</div>
</div>
);
}
}
StoryComment.propTypes = {
id: React.PropTypes.string
};
export default StoryComment;
|
src/components/topic/MediaTableContainer.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import MediaTable from './MediaTable';
import { isUrlSharingFocalSet } from '../../lib/topicVersionUtil';
/**
* Simple wrapper around MediaTable to pull in some stuff from state (so the components that use
* MediaTable don't need to pass it in). This just passses along all the other props so maintenance
* cost is low.
*/
const MediaTableContainer = (props) => (
<MediaTable {...props} />
);
MediaTableContainer.propTypes = {
// from state
showTweetCounts: PropTypes.bool.isRequired,
topicId: PropTypes.number.isRequired,
usingUrlSharingSubtopic: PropTypes.bool.isRequired,
};
const mapStateToProps = state => ({
topicId: state.topics.selected.id,
// show tweet counts if the user has a crimson hexagon id on the topic (to deptecate?)
showTweetCounts: Boolean(state.topics.selected.info.ch_monitor_id),
// only show the author count, and hide inlinks/outlinks, if the user is in a "url sharing" focus
usingUrlSharingSubtopic: (state.topics.selected.filters.focusId !== null) && isUrlSharingFocalSet(state.topics.selected.timespans.selected.focal_set),
});
export default (
connect(mapStateToProps)(
MediaTableContainer
)
);
|
src/svg-icons/action/flip-to-back.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionFlipToBack = (props) => (
<SvgIcon {...props}>
<path d="M9 7H7v2h2V7zm0 4H7v2h2v-2zm0-8c-1.11 0-2 .9-2 2h2V3zm4 12h-2v2h2v-2zm6-12v2h2c0-1.1-.9-2-2-2zm-6 0h-2v2h2V3zM9 17v-2H7c0 1.1.89 2 2 2zm10-4h2v-2h-2v2zm0-4h2V7h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2zM5 7H3v12c0 1.1.89 2 2 2h12v-2H5V7zm10-2h2V3h-2v2zm0 12h2v-2h-2v2z"/>
</SvgIcon>
);
ActionFlipToBack = pure(ActionFlipToBack);
ActionFlipToBack.displayName = 'ActionFlipToBack';
ActionFlipToBack.muiName = 'SvgIcon';
export default ActionFlipToBack;
|
js/controls/AttributionControl.js | mekto/brouter-online | import React from 'react';
import Control from './Control';
class AttributionComponent extends React.Component {
state = { layerAttributions: [] }
componentDidMount() {
this.props.map.on('layerchange', ::this.updateLayerAttributions);
}
updateLayerAttributions(e) {
this.setState({
layerAttributions: e.layers.map(layer => layer.attribution),
});
}
render() {
return (
<div>
<span>© <a href="http://leafletjs.com" title="A JS library for interactive maps" target="_blank">Leaflet</a> | </span>
{this.state.layerAttributions.map((attribution, i) =>
<span key={i}>tiles <span dangerouslySetInnerHTML={{__html: attribution}}></span> | </span>
)}
<span>routing © <a href="http://brouter.de/brouter/" title="BRouter: Let's get serious about bike routing" target="_blank">BRouter</a> | </span>
<span>search © <a href="https://www.google.com/maps" target="_blank">Google</a> | </span>
<span>code on <a href="https://github.com/mekto/brouter-online" target="_blank">GitHub</a></span>
</div>
);
}
}
export default Control.extend({
options: {
position: 'bottomright',
className: 'leaflet-control-attribution',
},
getComponentClass() { return AttributionComponent; }
});
|
src/layouts/index.js | xenotime-india/CV | import React from 'react'
import { siteMetadata } from '../../gatsby-config'
import './../styles/init.scss'
import 'font-awesome/css/font-awesome.css'
class Template extends React.Component {
componentDidMount() {}
componentDidUpdate() {}
render() {
const { location, children } = this.props
return <div>{children()}</div>
}
}
export default Template
|
fields/types/password/PasswordField.js | linhanyang/keystone | import React from 'react';
import Field from '../Field';
import {
Button,
FormInput,
InlineGroup as Group,
InlineGroupSection as Section,
} from '../../../admin/client/App/elemental';
module.exports = Field.create({
displayName: 'PasswordField',
statics: {
type: 'Password',
},
getInitialState () {
return {
passwordIsSet: this.props.value ? true : false,
showChangeUI: this.props.mode === 'create' ? true : false,
password: '',
confirm: '',
};
},
valueChanged (which, event) {
var newState = {};
newState[which] = event.target.value;
this.setState(newState);
},
showChangeUI () {
this.setState({
showChangeUI: true,
}, () => this.focus());
},
onCancel () {
this.setState({
showChangeUI: false,
}, () => this.focus());
},
renderValue () {
return <FormInput noedit>{this.props.value ? 'Password Set' : ''}</FormInput>;
},
renderField () {
return this.state.showChangeUI ? this.renderFields() : this.renderChangeButton();
},
renderFields () {
return (
<Group block>
<Section grow>
<FormInput
autoComplete="off"
name={this.getInputName(this.props.path)}
onChange={this.valueChanged.bind(this, 'password')}
placeholder="New password"
ref="focusTarget"
type="password"
value={this.state.password}
/>
</Section>
<Section grow>
<FormInput
autoComplete="off"
name={this.getInputName(this.props.paths.confirm)}
onChange={this.valueChanged.bind(this, 'confirm')}
placeholder="Confirm new password" value={this.state.confirm}
type="password"
/>
</Section>
{this.state.passwordIsSet ? (
<Section>
<Button onClick={this.onCancel}>Cancel</Button>
</Section>
) : null}
</Group>
);
},
renderChangeButton () {
var label = this.state.passwordIsSet
? 'Change Password'
: 'Set Password';
return (
<Button ref="focusTarget" onClick={this.showChangeUI}>{label}</Button>
);
},
});
|
examples/jenarMine/components/WindowOverlay.js | tatsuhino/reactPractice | import styles from '../css/main.css'
import React from 'react'
import {hashHistory} from 'react-router';
const WindowOverlay = () =>{
return (
<div className={styles.windowOverlay} onClick={linkTo}></div>
)
}
const linkTo = () =>{
hashHistory.push('/');
}
export default WindowOverlay
|
src/redux/utils/createDevToolsWindow.js | wwwiiilll/drinkstat | import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import DevTools from '../../containers/DevToolsWindow'
export default function createDevToolsWindow (store) {
const win = window.open(
null,
'redux-devtools', // give it a name so it reuses the same window
`width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no`
)
// reload in case it's reusing the same window with the old content
win.location.reload()
// wait a little bit for it to reload, then render
setTimeout(() => {
// Wait for the reload to prevent:
// "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element."
win.document.write('<div id="react-devtools-root"></div>')
win.document.body.style.margin = '0'
ReactDOM.render(
<Provider store={store}>
<DevTools />
</Provider>
, win.document.getElementById('react-devtools-root')
)
}, 10)
}
|
docs/app/Examples/collections/Message/Types/MessageMessagePropsExample.js | jcarbo/stardust | import React from 'react'
import { Message } from 'stardust'
const MessageMessagePropsExample = () => (
<Message
header='Changes in Service'
content='We updated our privacy policy here to better service our customers. We recommend reviewing the changes.'
/>
)
export default MessageMessagePropsExample
|
scripts/apps/translations/directives/TranslationReactDropdown.js | thnkloud9/superdesk-client-core | /* eslint-disable react/no-multi-comp */
import React from 'react';
/**
* @ngdoc directive
* @module superdesk.apps.translations
* @name TranslationReactDropdown
*
* @requires React
* @requires item
* @requires className
* @requires TranslationService
* @requires noLanguagesLabel
*
* @param {Object} [langugages] collection of languages
*
* @description Creates dropdown react element with list of available languages
*/
TranslationReactDropdown.$inject = ['item', 'className', 'TranslationService', 'noLanguagesLabel'];
export function TranslationReactDropdown(item, className, TranslationService, noLanguagesLabel) {
var languages = TranslationService.get() || {_items: []};
/*
* Creates specific language button in list
* @return {React} Language button
*/
class TranslateBtn extends React.Component {
constructor(props) {
super(props);
this.markTranslate = this.markTranslate.bind(this);
}
markTranslate(event) {
event.stopPropagation();
TranslationService.set(this.props.item, this.props.language);
}
render() {
var item = this.props.item;
var language = this.props.language;
var isCurrentLang = item.language === language.language;
if (!language.destination) {
return false;
}
return React.createElement(
'button', {
disabled: isCurrentLang,
onClick: this.markTranslate
},
language.label
);
}
}
TranslateBtn.propTypes = {
item: React.PropTypes.object,
language: React.PropTypes.object
};
/*
* Creates list element for specific language
* @return {React} Single list element
*/
var createTranslateItem = function(language) {
return React.createElement(
'li',
{key: 'language-' + language._id},
React.createElement(TranslateBtn, {item: item, language: language})
);
};
/*
* If there are no languages, print none-langugage message
* @return {React} List element
*/
var noLanguage = function() {
return React.createElement(
'li',
{},
React.createElement(
'button',
{disabled: true},
noLanguagesLabel)
);
};
/*
* Creates list with languages
* @return {React} List element
*/
return React.createElement(
'ul',
{className: className},
languages._items.length ? languages._items.map(createTranslateItem) : React.createElement(noLanguage)
);
}
|
packages/app/app/containers/MainContentContainer/index.js | nukeop/nuclear | import React from 'react';
import { Route, Switch, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as SearchActions from '../../actions/search';
import MainLayout from '../../components/MainLayout';
import AlbumViewContainer from '../AlbumViewContainer';
import ArtistViewContainer from '../ArtistViewContainer';
import DashboardContainer from '../DashboardContainer';
import DownloadsContainer from '../DownloadsContainer';
import EqualizerViewContainer from '../EqualizerViewContainer';
import FavoritesContainer from '../FavoritesContainer';
import LibraryViewContainer from '../LibraryViewContainer';
import LyricsContainer from '../LyricsContainer';
import PlaylistViewContainer from '../PlaylistViewContainer';
import PlaylistsContainer from '../PlaylistsContainer';
import PluginsContainer from '../PluginsContainer';
import SearchResultsContainer from '../SearchResultsContainer';
import SettingsContainer from '../SettingsContainer';
import TagViewContainer from '../TagViewContainer';
import VisualizerNode from '../VisualizerContainer/VisualizerNode';
class MainContentContainer extends React.Component {
componentDidMount () {
if (this.props.history &&
this.props.location &&
this.props.location.pathname === '/') {
this.props.history.push('/dashboard');
}
}
render () {
return (
<Route render={({ location }) => {
return (
<MainLayout>
<Switch key={location.key} location={location}>
<Route path='/album/:albumId' component={AlbumViewContainer} />
<Route path='/artist/:artistId' component={ArtistViewContainer} />
<Route path='/dashboard' component={DashboardContainer} />
<Route path='/downloads' component={DownloadsContainer} />
<Route path='/favorites/albums' component={FavoritesContainer} />
<Route path='/favorites/tracks' component={FavoritesContainer} />
<Route path='/favorites/artists' component={FavoritesContainer} />
<Route path='/playlists' component={PlaylistsContainer} />
<Route path='/playlist/:playlistId' component={PlaylistViewContainer} />
<Route path='/plugins' component={PluginsContainer} />
<Route path='/settings' component={SettingsContainer} />
<Route path='/tag/:tagName' component={TagViewContainer} />
<Route path='/search' component={SearchResultsContainer} />
<Route path='/lyrics' component={LyricsContainer} />
<Route path='/equalizer' component={EqualizerViewContainer} />
<Route path='/visualizer' component={VisualizerNode} />
<Route path='/library' component={LibraryViewContainer} />
</Switch>
</MainLayout>
);
}
} />
);
}
}
function mapStateToProps () {
return {};
}
function mapDispatchToProps (dispatch) {
return {
searchActions: bindActionCreators(SearchActions, dispatch)
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(MainContentContainer));
|
src/interface/layout/Footer/index.js | sMteX/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Tooltip, { TooltipElement } from 'common/Tooltip';
import DiscordLogo from 'interface/icons/DiscordTiny';
import GithubLogo from 'interface/icons/GitHubMarkSmall';
import PatreonIcon from 'interface/icons/PatreonTiny';
import { hasPremium } from 'interface/selectors/user';
import Logo from 'interface/images/logo.svg';
import Ad from 'interface/common/Ad';
import './style.scss';
class Footer extends React.PureComponent {
static propTypes = {
premium: PropTypes.bool,
};
render() {
const { premium } = this.props;
return (
<footer>
<div className="container text-center">
<div>
<a href="/">
<img src={Logo} alt="Logo" className="wowanalyzer-logo" />
</a>
<h1>
Be a part of us
</h1>
<div className="social-links">
{/* For some reason the tooltip disappears and reappears when mousing over the svg icons (maybe when the cursor leaves filled areas)*/}
<Tooltip content="Discord">
<a href="https://wowanalyzer.com/discord">
<DiscordLogo />
</a>
</Tooltip>
<Tooltip content="GitHub">
<a href="https://github.com/WoWAnalyzer/WoWAnalyzer">
<GithubLogo />
</a>
</Tooltip>
<Tooltip content="Patreon">
<a href="https://www.patreon.com/join/wowanalyzer">
<PatreonIcon />
</a>
</Tooltip>
</div>
<br />
<div className="attribution">
Log data from <a href="https://www.warcraftlogs.com">Warcaft Logs</a>.{' '}
<TooltipElement
content={(
<>
Icon creators:<br />
<ul>
<li>Fingerprint by IconsGhost</li>
<li>Scroll by jngll</li>
<li>Delete by johartcamp</li>
<li>Skull by Royyan Razka</li>
<li>Heart by Emir Palavan</li>
<li>armor by Jetro Cabau Quirós</li>
<li>Checklist by David</li>
<li>Idea by Anne</li>
<li>About Document by Deepz</li>
<li>Stats by Barracuda</li>
<li>Dropdown by zalhan</li>
<li>timeline by Alexander Blagochevsky</li>
<li>abilities by sachin modgekar</li>
<li>Vision by supalerk laipawat</li>
<li>Lightning by Mooms</li>
<li>Grid Many Rows by Justin White</li>
<li>Info by Gregor Cresnar</li>
<li>Plus by Galaxicon</li>
<li>duration by Bohdan Burmich</li>
<li>link by arjuazka</li>
</ul>
</>
)}
>Icons by the <a href="https://thenounproject.com">Noun Project</a>.</TooltipElement><br />
World of Warcraft and related artwork is copyright of Blizzard Entertainment, Inc.<br />
This is a fan site and we are not affiliated.
</div>
</div>
{premium === false && (
<div>
<Ad
data-ad-slot="3815063023" // Footer
/>
</div>
)}
</div>
</footer>
);
}
}
const mapStateToProps = state => ({
premium: hasPremium(state),
});
export default connect(mapStateToProps)(Footer);
|
examples/js/others/table-in-tabs.js | powerhome/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { Tabs, Tab } from 'react-bootstrap';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
export default class TableInTabs extends React.Component {
constructor(props) {
super(props);
this.state = {
key: 2
};
}
handleTabChange = (key) => {
this.setState({
key
}, () => {
/*
* If you enable animation in react-bootstrap tab
* please remember to call forceUpdate in async call.
* If disable animation, call forceUpdate directly.
*/
if (key === 1) {
setTimeout(() => {
this.refs.table1.forceUpdate();
}, 500);
} else if (key === 2) {
setTimeout(() => {
this.refs.table2.forceUpdate();
}, 500);
}
});
}
render() {
return (
<Tabs activeKey={ this.state.key } onSelect={ this.handleTabChange } animation>
<Tab eventKey={ 1 } title='Tab 1'>
<BootstrapTable ref='table1' data={ products }>
<TableHeaderColumn dataField='id' isKey dataSort>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name' width='300' dataSort>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
</Tab>
<Tab eventKey={ 2 } title='Tab 2'>
<BootstrapTable ref='table2' data={ products }>
<TableHeaderColumn dataField='id' isKey dataSort>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name' width='300' dataSort>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
<TableHeaderColumn dataField='price' width='90'>Product Price</TableHeaderColumn>
</BootstrapTable>
</Tab>
<Tab eventKey={ 3 } title='Tab 3'>Tab 3 content</Tab>
</Tabs>
);
}
}
|
src/Repeat/index.js | pinebit/react-cr | import React from 'react';
import PropTypes from 'prop-types';
import Wrapper from '../Wrapper';
const Repeat = ({ count, children, ...wrapperProps }) => {
if (!children || count <= 0 || Array.isArray(children)) {
return null;
}
if (count === 1) {
return (
<Wrapper {...wrapperProps}>
{children}
</Wrapper>
);
}
const fakeArray = Array.from(new Array(count)).map((x, index) => index + 1);
return (
<Wrapper {...wrapperProps}>
{fakeArray.map(key => React.cloneElement(children, { key }))}
</Wrapper>
);
};
Repeat.propTypes = {
count: PropTypes.number.isRequired,
children: PropTypes.node
};
export default Repeat;
|
src/common/containers/LocationPanel/LocationPanel.js | aarmour/my-denver | import React, { Component } from 'react';
import BasePanel from '../BasePanel';
export default class LocationPanel extends Component {
render() {
return (
<BasePanel>
</BasePanel>
);
}
}
|
src/components/Search/SearchStories.js | DeloitteDigitalUK/react-redux-starter-app | import React from 'react';
import { storiesOf } from '@kadira/storybook';
import Search from './index';
storiesOf('Search', module)
.addDecorator(story => (
<div className="col-xs-8 col-xs-offset-2">
{story()}
</div>
))
.add('Default State', () => (
<Search
heading="Search GitHub"
buttonText="Search"
/>
))
.add('With A Valid Search Term', () => (
<Search
heading="Search GitHub"
inputValue="React"
buttonText="Search"
/>
))
.add('With an invalid Character', () => (
<Search
heading="Search GitHub"
inputValue="~"
buttonText="Search"
errorMessage="You have entered a forbidden character!"
/>
))
.add('Submitted without entering anything', () => (
<Search
heading="Search GitHub"
buttonText="Search"
errorMessage="You need to enter search criteria before submitting"
/>
))
.add('Clicking off Search box', () => (
<Search
heading="Search GitHub"
buttonText="Search"
errorMessage="Please enter search criteria"
/>
));
|
src/pages/navbar.js | michaelnyu/michaelnyu.github.io | import React from 'react';
import House from '~/assets/house.svg';
import NavbarComponent from '~/src/components/navbar';
import Link from '~/src/components/link';
import { Heading, FONT_COLORS } from '~/src/shared/typography';
export const leftNavbar = (
<Link to="/">
<House css={{ width: 60, height: 'auto' }} />
</Link>
);
export const rightNavbar = (
<div css={{ display: 'flex', alignItems: 'center' }}>
<Link to="/about">
<Heading css={{ display: 'inline' }} color={FONT_COLORS.GRAY}>
about
</Heading>
</Link>
</div>
);
const Navbar = () => {
return <NavbarComponent left={leftNavbar} right={rightNavbar} />;
};
export default Navbar;
|
src/ToggleButtonWithLabel/index.js | DuckyTeam/ducky-components | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Typography from '../Typography';
import SwitchToggleButton from '../SwitchToggleButton';
import styles from './styles.css';
function ToggleButtonWithLabel(props) {
return (
<div className={classNames(styles.wrapper)}>
<Typography
className={classNames(styles.text, {
[styles.textDarkTheme]: props.theme === 'dark'
})}
type="bodyTextNormal"
>
{props.label}
</Typography>
<SwitchToggleButton
onChange={props.onChange}
checked={props.checked}
defaultChecked={props.defaultChecked}
theme={props.theme}
/>
</div>
);
}
ToggleButtonWithLabel.propTypes = {
checked: PropTypes.bool,
label: PropTypes.string,
theme: PropTypes.string
};
export default ToggleButtonWithLabel;
|
packages/material-ui-icons/src/Details.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Details = props =>
<SvgIcon {...props}>
<path d="M3 4l9 16 9-16H3zm3.38 2h11.25L12 16 6.38 6z" />
</SvgIcon>;
Details = pure(Details);
Details.muiName = 'SvgIcon';
export default Details;
|
src/organisms/cards/PolicyCard/Compare.js | policygenius/athenaeum | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Text from 'atoms/Text';
import Hide from 'wrappers/Hide';
import Spacer from 'atoms/Spacer';
import CheckBoxField from 'molecules/formfields/CheckBoxField';
import styles from './policy_card.module.scss';
const Compare = ({ compareSelected, onCompare, name }) => (
<Hide hideOn='mobile' className={styles['compare']}>
<div
id={`${name}-checkbox-wrapper`}
className={styles['checkbox-wrapper']}
onClick={onCompare}
>
<Text
color='neutral-2'
size={11}
font='a'
bold
spaced
className={classnames(compareSelected && styles['checked'])}
>
COMPARE
</Text>
<Spacer spacer={1} />
<CheckBoxField
input={{
value: compareSelected,
name
}}
/>
</div>
</Hide>
);
Compare.propTypes = {
compareSelected: PropTypes.bool,
onCompare: PropTypes.func,
name: PropTypes.string,
};
export default Compare;
|
client/node_modules/react-router/es/withRouter.js | bourdakos1/Visual-Recognition-Tool | 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; }
import React from 'react';
import PropTypes from 'prop-types';
import hoistStatics from 'hoist-non-react-statics';
import Route from './Route';
/**
* A public higher-order component to access the imperative API
*/
var withRouter = function withRouter(Component) {
var C = function C(props) {
var wrappedComponentRef = props.wrappedComponentRef,
remainingProps = _objectWithoutProperties(props, ['wrappedComponentRef']);
return React.createElement(Route, { render: function render(routeComponentProps) {
return React.createElement(Component, _extends({}, remainingProps, routeComponentProps, { ref: wrappedComponentRef }));
} });
};
C.displayName = 'withRouter(' + (Component.displayName || Component.name) + ')';
C.WrappedComponent = Component;
C.propTypes = {
wrappedComponentRef: PropTypes.func
};
return hoistStatics(C, Component);
};
export default withRouter; |
js/src/dialogs/NewFolder.js | syslo/file_publisher | import React from 'react'
import {Button, Form, FormControl, FormGroup, InputGroup} from 'react-bootstrap'
import {Modal} from 'react-bootstrap'
const validator = new RegExp('^[_a-zA-Z0-9]+$')
export default class NewFolder extends React.Component {
create() {
const n = this.props.state.nodes[this.props.state.active.path]
this.props.actions.newFolder(
`${n.path}/${this.props.value}`
).then(()=>
this.props.actions.fetchNode(n)
)
this.props.onChange('')
this.props.onClose()
}
onSubmit(e) {
e.preventDefault()
e.stopPropagation()
if (validator.test(this.props.value)){
this.create()
}
return false
}
render() {
let value = this.props.value || ''
let active = this.props.state.active || {}
let valid = validator.test(value)
return (
<Modal
show={this.props.show && active.asFolder}
onHide={this.props.onClose}
>
<Modal.Header closeButton>
<Modal.Title>New Folder</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form onSubmit={this.onSubmit.bind(this)}>
<FormGroup validationState={value && !valid ? 'error' : null}>
<InputGroup>
<InputGroup.Addon>{active.path}/</InputGroup.Addon>
<FormControl
autoFocus
type="text"
value={value}
onChange={(e)=>this.props.onChange(e.target.value)}
/>
</InputGroup>
</FormGroup>
<FormGroup>
<Button bsStyle="primary" disabled={!valid} onClick={this.create.bind(this)}>
Create
</Button>
</FormGroup>
</Form>
</Modal.Body>
</Modal>
)
}
}
|
components/form/FileImage.js | resource-watch/resource-watch | import 'isomorphic-fetch';
import React from 'react';
import PropTypes from 'prop-types';
// Components
import Dropzone from 'react-dropzone';
import Icon from 'components/ui/icon';
import FormElement from './FormElement';
class FileImage extends FormElement {
constructor(props) {
super(props);
const defaultValue = props.properties.default;
const previewURL = `${defaultValue || ''}`;
const { getUrlImage } = props;
this.state = {
value: (defaultValue && !getUrlImage)
? this.getBase64FromURL(previewURL)
: '',
accepted: (defaultValue)
? [{ name: defaultValue, preview: previewURL }]
: [],
rejected: [],
dropzoneActive: false,
loading: false,
};
// BINDINGS
this.triggerBrowseOrCancel = this.triggerBrowseOrCancel.bind(this);
this.onDragEnter = this.onDragEnter.bind(this);
this.onDragLeave = this.onDragLeave.bind(this);
this.onDrop = this.onDrop.bind(this);
}
/**
* DROPZONE EVENTS
* - onDragEnter
* - onDragLeave
* - onDrop
*/
onDragEnter() {
this.setState({
dropzoneActive: true,
});
}
onDragLeave() {
this.setState({
dropzoneActive: false,
});
}
onDrop(accepted, rejected) {
this.setState({
accepted,
rejected,
dropzoneActive: false,
}, () => {
if (accepted.length) {
switch (this.props.mode) {
case 'image':
this.getBase64(accepted[0]);
break;
case 'url':
this.props.getUrlImage(accepted[0])
.then((value) => {
this.setState({
value,
}, () => {
// Publish the new value to the form
if (this.props.onChange) this.props.onChange(this.state.value);
// Trigger validation
this.triggerValidate();
});
});
break;
default:
this.getBase64(accepted[0]);
}
}
});
}
/**
* - getBase64
* - getFileFromUrl
*/
getBase64(file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
this.setState({
value: reader.result,
}, () => {
// Publish the new value to the form
if (this.props.onChange) this.props.onChange(this.state.value);
// Trigger validation
this.triggerValidate();
});
};
reader.onerror = (error) => {
this.setState({
value: '',
error,
}, () => {
// Publish the new value to the form
if (this.props.onChange) this.props.onChange(this.state.value);
// Trigger validation
this.triggerValidate();
});
};
}
getBase64FromURL(url) {
if (typeof window !== 'undefined') {
const xhr = new XMLHttpRequest();
xhr.open('get', url);
xhr.responseType = 'blob';
xhr.onload = () => {
this.getBase64(xhr.response);
};
xhr.send();
}
}
/**
* UI EVENTS
* - triggerBrowseOrCancel
* - triggerChange
*/
triggerBrowseOrCancel() {
const { accepted } = this.state;
if (accepted.length) {
this.setState({
accepted: [],
value: '',
}, () => {
// Publish the new value to the form
if (this.props.onChange) this.props.onChange(this.state.value);
// Trigger validation
this.triggerValidate();
});
} else {
this.dropzone.open();
}
}
triggerChange(e) {
this.setState({
value: e.currentTarget.value,
}, () => {
// Publish the new value to the form
if (this.props.onChange) this.props.onChange(this.state.value);
// Trigger validation
this.triggerValidate();
});
}
/**
* HELPERS
* - getFileImageName
* - uploadFileImage
*/
getFileImageName() {
const { accepted } = this.state;
if (accepted.length) {
const current = accepted[0];
return current.name;
}
return 'Select file to upload';
}
render() {
const { properties } = this.props;
const { accepted } = this.state;
return (
<div className="c-file-image">
<Dropzone
accept=".jpg,.jpeg,.png"
ref={(node) => { this.dropzone = node; }}
className="file-dropzone"
disableClick
multiple={false}
onDrop={this.onDrop}
onDragEnter={this.onDragEnter}
onDragLeave={this.onDragLeave}
>
{!accepted.length
&& (
<div className="file-placeholder" onClick={this.triggerBrowseOrCancel}>
{properties.placeholder}
</div>
)}
{!!accepted.length && accepted[0].preview
&& (
<div className="file-preview">
<img className="file-image" src={accepted[0].preview} alt={accepted[0].name} />
<button onClick={this.triggerBrowseOrCancel} className="file-button c-button">
<Icon name="icon-cross" className="-small" />
</button>
</div>
)}
</Dropzone>
</div>
);
}
}
FileImage.propTypes = {
properties: PropTypes.object.isRequired,
validations: PropTypes.array,
onChange: PropTypes.func,
};
export default FileImage;
|
examples/js/custom/search/fully-custom-search-field.js | echaouchna/react-bootstrap-tab | /* eslint max-len: 0 */
/* eslint no-unused-vars: 0 */
/* eslint no-alert: 0 */
import React from 'react';
import ReactDOM from 'react-dom';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
class MySearchField extends React.Component {
// It's necessary to implement getValue
getValue() {
return ReactDOM.findDOMNode(this).value;
}
// It's necessary to implement setValue
setValue(value) {
ReactDOM.findDOMNode(this).value = value;
}
render() {
return (
<input
className={ `form-control` }
type='text'
defaultValue={ this.props.defaultValue }
placeholder={ this.props.placeholder }
onKeyUp={ this.props.search }/>
);
}
}
export default class FullyCustomSearchFieldTable extends React.Component {
render() {
const options = {
clearSearch: true,
searchField: (props) => (<MySearchField { ...props }/>)
};
return (
<BootstrapTable data={ products } options={ options } search>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
stories/Transform.js | unruffledBeaver/react-animation-components | import React from 'react';
import { storiesOf } from '@storybook/react';
import * as knobs from '@storybook/addon-knobs';
import { createCommonKnobs } from '../src/utilities';
import { Transform } from '../src/index';
storiesOf('Animations/Transform', module)
.addDecorator(knobs.withKnobs)
.add('default', () => {
const commonKnobs = createCommonKnobs(knobs);
const enterTransform = knobs.text('enterTransform', 'translateY(50vh)');
const exitTransform = knobs.text('exitTransform', 'none');
return (
<Transform
in={commonKnobs.inProp}
delay={commonKnobs.delay}
duration={commonKnobs.duration}
timingFn={commonKnobs.timingFn}
enterTransform={enterTransform}
exitTransform={exitTransform}
>
<h1>Example</h1>
</Transform>
);
});
|
src/js/index.js | Landerson352/rpga | import React from 'react';
import ReactDOM from 'react-dom';
import '../css/app.less';
import App from './components/App';
ReactDOM.render(<App/>,document.getElementById('app'));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.