path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/components/TextInput/index.js
|
IDEOorg/steps-guide-builder
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import './index.less';
export default class TextInput extends Component {
constructor(props) {
super(props);
this.state = {value: this.props.value ? this.props.value : ""};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({value: e.target.value}, () => {
if(this.props.onChange) {
this.props.onChange(this.state.value);
}
});
}
render() {
return (
<input className={classNames(this.props.className, "textinput")}
type="text" value={this.state.value}
onChange={this.handleChange}
placeholder={this.props.placeholder}
ref={this.props.parentRef}
/>
);
}
}
TextInput.propTypes = {
value: PropTypes.string,
onChange: PropTypes.func.isRequired,
className: PropTypes.string,
placeholder: PropTypes.string
};
TextInput.displayName = 'TextInput';
|
src/client.js
|
twomoonsfactory/custom-poll
|
/**
* THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER.
*/
import 'babel/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import createHistory from 'history/lib/createBrowserHistory';
import useScroll from 'scroll-behavior/lib/useStandardScroll';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import io from 'socket.io-client';
import {Provider} from 'react-redux';
import {reduxReactRouter, ReduxRouter} from 'redux-router';
import getRoutes from './routes';
import makeRouteHooksSafe from './helpers/makeRouteHooksSafe';
const client = new ApiClient();
// Three different types of scroll behavior available.
// Documented here: https://github.com/rackt/scroll-behavior
const scrollablehistory = useScroll(createHistory);
const dest = document.getElementById('content');
const store = createStore(reduxReactRouter, makeRouteHooksSafe(getRoutes), scrollablehistory, client, window.__data);
function initSocket() {
const socket = io('', {path: '/api/ws', transports: ['polling']});
socket.on('news', (data) => {
console.log(data);
socket.emit('my other event', { my: 'data from client' });
});
socket.on('msg', (data) => {
console.log(data);
});
return socket;
}
global.socket = initSocket();
const component = (
<ReduxRouter routes={getRoutes(store)} />
);
ReactDOM.render(
<Provider store={store} key="provider">
{component}
</Provider>,
dest
);
if (process.env.NODE_ENV !== 'production') {
window.React = React; // enable debugger
if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) {
console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
}
}
if (__DEVTOOLS__ && !window.devToolsExtension) {
const DevTools = require('./containers/DevTools/DevTools');
ReactDOM.render(
<Provider store={store} key="provider">
<div>
{component}
<DevTools />
</div>
</Provider>,
dest
);
}
|
blueocean-material-icons/src/js/components/svg-icons/social/person-outline.js
|
kzantow/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const SocialPersonOutline = (props) => (
<SvgIcon {...props}>
<path d="M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z"/>
</SvgIcon>
);
SocialPersonOutline.displayName = 'SocialPersonOutline';
SocialPersonOutline.muiName = 'SvgIcon';
export default SocialPersonOutline;
|
node_modules/react-bootstrap/es/ButtonGroup.js
|
okristian1/react-info
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import all from 'react-prop-types/lib/all';
import Button from './Button';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
vertical: React.PropTypes.bool,
justified: React.PropTypes.bool,
/**
* Display block buttons; only useful when used with the "vertical" prop.
* @type {bool}
*/
block: all(React.PropTypes.bool, function (_ref) {
var block = _ref.block,
vertical = _ref.vertical;
return block && !vertical ? new Error('`block` requires `vertical` to be set to have any effect') : null;
})
};
var defaultProps = {
block: false,
justified: false,
vertical: false
};
var ButtonGroup = function (_React$Component) {
_inherits(ButtonGroup, _React$Component);
function ButtonGroup() {
_classCallCheck(this, ButtonGroup);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ButtonGroup.prototype.render = function render() {
var _extends2;
var _props = this.props,
block = _props.block,
justified = _props.justified,
vertical = _props.vertical,
className = _props.className,
props = _objectWithoutProperties(_props, ['block', 'justified', 'vertical', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps)] = !vertical, _extends2[prefix(bsProps, 'vertical')] = vertical, _extends2[prefix(bsProps, 'justified')] = justified, _extends2[prefix(Button.defaultProps, 'block')] = block, _extends2));
return React.createElement('div', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return ButtonGroup;
}(React.Component);
ButtonGroup.propTypes = propTypes;
ButtonGroup.defaultProps = defaultProps;
export default bsClass('btn-group', ButtonGroup);
|
packages/reactor-kitchensink/src/examples/Charts/3DColumn/Basic3DColumn/Basic3DColumn.js
|
sencha/extjs-reactor
|
import React, { Component } from 'react';
import { Container } from '@extjs/ext-react';
import { Cartesian } from '@extjs/ext-react-charts';
import ChartToolbar from '../../ChartToolbar';
import createData from './createData';
Ext.require([
'Ext.chart.interactions.PanZoom',
'Ext.chart.axis.Numeric',
'Ext.chart.axis.Category',
'Ext.chart.axis.Numeric3D',
'Ext.chart.grid.HorizontalGrid3D',
'Ext.chart.series.Bar3D',
'Ext.chart.axis.Category3D'
]);
export default class Basic3DColumnChartExample extends Component {
constructor() {
super();
this.refresh();
}
store = Ext.create('Ext.data.Store', {
fields: ['id', 'g0', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'name']
});
state = {
theme: 'default'
};
refresh = () => {
this.store.loadData(createData(15));
}
changeTheme = theme => this.setState({theme})
render() {
const { theme } = this.state;
return (
<Container padding={!Ext.os.is.Phone && 10} layout="fit">
<ChartToolbar
onThemeChange={this.changeTheme}
onRefreshClick={this.refresh}
theme={theme}
/>
<Cartesian
shadow
store={this.store}
theme={theme}
series={{
type: 'bar3d',
xField: 'name',
yField: ['g1', 'g2', 'g3']
}}
axes={[{
type: 'numeric3d',
position: 'left',
fields: ['g1', 'g2', 'g3'],
grid: true,
label: {
rotate: {
degrees: -30
}
}
}, {
type: 'category3d',
position: 'bottom',
fields: 'name'
}]}
/>
</Container>
)
}
}
|
app/containers/App/index.js
|
nandakishore2009/smart-will
|
/**
*
* 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 Helmet from 'react-helmet';
import withProgressBar from 'components/ProgressBar';
import Header from 'components/Header';
import Footer from 'components/Footer';
class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div>
<Helmet
titleTemplate="%s - Smart Will"
defaultTitle="Smart Will"
meta={[
{ name: 'description', content: 'Make your will' },
]}
/>
<Header />
{React.Children.toArray(this.props.children)}
<Footer />
</div>
);
}
}
export default withProgressBar(App);
|
modules/RouteContext.js
|
andreftavares/react-router
|
import React from 'react'
const { object } = React.PropTypes
/**
* The RouteContext mixin provides a convenient way for route
* components to set the route in context. This is needed for
* routes that render elements that want to use the Lifecycle
* mixin to prevent transitions.
*/
const RouteContext = {
propTypes: {
route: object.isRequired
},
childContextTypes: {
route: object.isRequired
},
getChildContext() {
return {
route: this.props.route
}
}
}
export default RouteContext
|
app/javascript/mastodon/features/pinned_statuses/index.js
|
Arukas/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchPinnedStatuses } from '../../actions/pin_statuses';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import StatusList from '../../components/status_list';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'column.pins', defaultMessage: 'Pinned toot' },
});
const mapStateToProps = state => ({
statusIds: state.getIn(['status_lists', 'pins', 'items']),
hasMore: !!state.getIn(['status_lists', 'pins', 'next']),
});
@connect(mapStateToProps)
@injectIntl
export default class PinnedStatuses extends ImmutablePureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
intl: PropTypes.object.isRequired,
hasMore: PropTypes.bool.isRequired,
};
componentWillMount () {
this.props.dispatch(fetchPinnedStatuses());
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
render () {
const { intl, statusIds, hasMore } = this.props;
return (
<Column icon='thumb-tack' heading={intl.formatMessage(messages.heading)} ref={this.setRef}>
<ColumnBackButtonSlim />
<StatusList
statusIds={statusIds}
scrollKey='pinned_statuses'
hasMore={hasMore}
/>
</Column>
);
}
}
|
src/PaginationButton.js
|
xsistens/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import createSelectedEvent from './utils/createSelectedEvent';
import CustomPropTypes from './utils/CustomPropTypes';
const PaginationButton = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
className: React.PropTypes.string,
eventKey: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]),
onSelect: React.PropTypes.func,
disabled: React.PropTypes.bool,
active: React.PropTypes.bool,
/**
* You can use a custom element for this component
*/
buttonComponentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
active: false,
disabled: false
};
},
handleClick(event) {
if (this.props.disabled) {
return;
}
if (this.props.onSelect) {
let selectedEvent = createSelectedEvent(this.props.eventKey);
this.props.onSelect(event, selectedEvent);
}
},
render() {
let classes = {
active: this.props.active,
disabled: this.props.disabled,
...this.getBsClassSet()
};
let {
className,
...anchorProps
} = this.props;
let ButtonComponentClass = this.props.buttonComponentClass;
return (
<li className={classNames(className, classes)}>
<ButtonComponentClass
{...anchorProps}
onClick={this.handleClick} />
</li>
);
}
});
export default PaginationButton;
|
src/svg-icons/social/party-mode.js
|
lawrence-yu/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPartyMode = (props) => (
<SvgIcon {...props}>
<path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 3c1.63 0 3.06.79 3.98 2H12c-1.66 0-3 1.34-3 3 0 .35.07.69.18 1H7.1c-.06-.32-.1-.66-.1-1 0-2.76 2.24-5 5-5zm0 10c-1.63 0-3.06-.79-3.98-2H12c1.66 0 3-1.34 3-3 0-.35-.07-.69-.18-1h2.08c.07.32.1.66.1 1 0 2.76-2.24 5-5 5z"/>
</SvgIcon>
);
SocialPartyMode = pure(SocialPartyMode);
SocialPartyMode.displayName = 'SocialPartyMode';
SocialPartyMode.muiName = 'SvgIcon';
export default SocialPartyMode;
|
app/javascript/mastodon/components/account.js
|
narabo/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Avatar from './avatar';
import DisplayName from './display_name';
import Permalink from './permalink';
import IconButton from './icon_button';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
follow: { id: 'account.follow', defaultMessage: 'Follow' },
unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' },
requested: { id: 'account.requested', defaultMessage: 'Awaiting approval' },
unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' },
unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' },
});
class Account extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
me: PropTypes.number.isRequired,
onFollow: PropTypes.func.isRequired,
onBlock: PropTypes.func.isRequired,
onMute: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleFollow = () => {
this.props.onFollow(this.props.account);
}
handleBlock = () => {
this.props.onBlock(this.props.account);
}
handleMute = () => {
this.props.onMute(this.props.account);
}
render () {
const { account, me, intl } = this.props;
if (!account) {
return <div />;
}
let buttons;
if (account.get('id') !== me && account.get('relationship', null) !== null) {
const following = account.getIn(['relationship', 'following']);
const requested = account.getIn(['relationship', 'requested']);
const blocking = account.getIn(['relationship', 'blocking']);
const muting = account.getIn(['relationship', 'muting']);
if (requested) {
buttons = <IconButton disabled={true} icon='hourglass' title={intl.formatMessage(messages.requested)} />;
} else if (blocking) {
buttons = <IconButton active={true} icon='unlock-alt' title={intl.formatMessage(messages.unblock, { name: account.get('username') })} onClick={this.handleBlock} />;
} else if (muting) {
buttons = <IconButton active={true} icon='volume-up' title={intl.formatMessage(messages.unmute, { name: account.get('username') })} onClick={this.handleMute} />;
} else {
buttons = <IconButton icon={following ? 'user-times' : 'user-plus'} title={intl.formatMessage(following ? messages.unfollow : messages.follow)} onClick={this.handleFollow} active={following} />;
}
}
return (
<div className='account'>
<div className='account__wrapper'>
<Permalink key={account.get('id')} className='account__display-name' href={account.get('url')} to={`/accounts/${account.get('id')}`}>
<div className='account__avatar-wrapper'><Avatar src={account.get('avatar')} staticSrc={account.get('avatar_static')} size={36} /></div>
<DisplayName account={account} />
</Permalink>
<div className='account__relationship'>
{buttons}
</div>
</div>
</div>
);
}
}
export default injectIntl(Account);
|
src/svg-icons/editor/border-horizontal.js
|
pancho111203/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderHorizontal = (props) => (
<SvgIcon {...props}>
<path d="M3 21h2v-2H3v2zM5 7H3v2h2V7zM3 17h2v-2H3v2zm4 4h2v-2H7v2zM5 3H3v2h2V3zm4 0H7v2h2V3zm8 0h-2v2h2V3zm-4 4h-2v2h2V7zm0-4h-2v2h2V3zm6 14h2v-2h-2v2zm-8 4h2v-2h-2v2zm-8-8h18v-2H3v2zM19 3v2h2V3h-2zm0 6h2V7h-2v2zm-8 8h2v-2h-2v2zm4 4h2v-2h-2v2zm4 0h2v-2h-2v2z"/>
</SvgIcon>
);
EditorBorderHorizontal = pure(EditorBorderHorizontal);
EditorBorderHorizontal.displayName = 'EditorBorderHorizontal';
EditorBorderHorizontal.muiName = 'SvgIcon';
export default EditorBorderHorizontal;
|
src/js/components/tabs/tab_button.js
|
working-minds/realizejs
|
import React, { Component } from 'react';
import PropTypes from '../../prop_types';
import { mixin } from '../../utils/decorators';
import {
CssClassMixin,
ContainerMixin,
FormContainerMixin
} from '../../mixins';
@mixin(
CssClassMixin,
ContainerMixin,
FormContainerMixin
)
export default class TabButton extends Component {
static propTypes = {
id: PropTypes.string,
title: PropTypes.string,
active: PropTypes.bool
};
static defaultProps = {
themeClassKey: 'tabs.tabButton',
errorThemeClassKey: 'tabs.tabButton.error',
className: 's1',
active: false
};
render () {
return (
<li className={this.formContainerClassName()}>
<a href={'#' + this.props.id} className={this.props.active ? "active" : ""}>
{this.props.title}
</a>
</li>
);
}
}
|
src/Item.js
|
karote00/todo-react
|
require('../stylesheets/item.scss');
import React, { Component } from 'react';
import FontAwesome from 'react-fontawesome';
import { tabStore } from './tabStore';
import classNames from 'classnames';
export class Item extends Component {
constructor(props) {
super(props);
this.state = {
list: tabStore.getState(),
complete: this.props.data.complete,
starred: this.props.data.starred,
path: this.props.path,
todo: this.props.data.todo,
changeInput: false
};
}
complete() {
this.setState({complete: !this.state.complete});
var idx = this.state.list.indexOf(this.props.data);
this.state.list[idx].complete = !this.state.complete;
tabStore.dispatch({
type: 'Complete',
item: this.props.data,
path: this.state.path,
});
this.props.onUpdate();
}
starred() {
this.setState({starred: !this.state.starred});
var idx = this.state.list.indexOf(this.props.data);
this.state.list[idx].starred = !this.state.starred;
tabStore.dispatch({
type: 'Starred',
item: this.props.data,
path: this.state.path,
});
this.props.onUpdate();
}
delete() {
tabStore.dispatch({
type: 'Delete',
item: this.props.data,
path: this.state.path
});
this.props.onUpdate();
}
handleChange(e) {
this.setState({todo: e.target.value});
}
changeInput(e) {
if (!this.state.complete) {
this.setState({changeInput: !this.state.changeInput});
if (!this.state.changeInput) {
var _item = this.refs.todoInput;
setTimeout(function() {
_item.focus();
_item.selectionStart = 10000;
_item.selectionEnd = 10000;
}, 50);
}
}
}
showInput(e) {
if (!this.state.complete) {
this.setState({changeInput: true});
var _item = this.refs.todoInput;
setTimeout(function() {
_item.focus();
_item.selectionStart = 10000;
_item.selectionEnd = 10000;
}, 50);
}
}
render() {
var name = {};
name[this.state.path] = true;
name['item-container'] = true;
var container = classNames(name);
var complete = classNames({
'complete': true,
'hidden': this.state.complete,
'edit': this.state.changeInput
});
var star = classNames({
'star': true,
'hidden': !this.state.starred
});
var star_o = classNames({
'star_o': true,
'hidden': this.state.starred,
'active': this.state.starred
});
var todoContainer = classNames({
'todo': true,
'edit': this.state.changeInput
})
var todoText = classNames({
'strike': this.state.complete && this.state.path != 'Complete'
});
return (
<div className={container}>
<div className="check">
<div className={complete} onClick={this.complete.bind(this)} ></div>
<FontAwesome name="check-circle" className={this.state.complete? '': 'hidden'} onClick={this.complete.bind(this)} />
</div>
<div className={todoContainer} onClick={this.showInput.bind(this)}>
<div className={this.state.changeInput? 'hidden': ''}><span onClick={this.changeInput.bind(this)} className={todoText}>{this.state.todo}</span></div>
<input type="text" ref="todoInput" onBlur={this.changeInput.bind(this)} onChange={this.handleChange.bind(this)} value={this.state.todo} className={!this.state.changeInput? 'hidden': ''} />
</div>
<ul className="menu">
<li className={star_o} onClick={this.starred.bind(this)}><FontAwesome name="star-o" /></li>
<li className={star} onClick={this.starred.bind(this)}><FontAwesome name="star" /></li>
<li className="bottom" onClick={this.delete.bind(this)}><FontAwesome name="trash-o" /></li>
</ul>
</div>
)
}
}
|
dist/react-input-autosize.es.js
|
JedWatson/react-input-autosize
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
var asyncGenerator = function () {
function AwaitValue(value) {
this.value = value;
}
function AsyncGenerator(gen) {
var front, back;
function send(key, arg) {
return new Promise(function (resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null
};
if (back) {
back = back.next = request;
} else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
if (value instanceof AwaitValue) {
Promise.resolve(value.value).then(function (arg) {
resume("next", arg);
}, function (arg) {
resume("throw", arg);
});
} else {
settle(result.done ? "return" : "normal", result.value);
}
} catch (err) {
settle("throw", err);
}
}
function settle(type, value) {
switch (type) {
case "return":
front.resolve({
value: value,
done: true
});
break;
case "throw":
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false
});
break;
}
front = front.next;
if (front) {
resume(front.key, front.arg);
} else {
back = null;
}
}
this._invoke = send;
if (typeof gen.return !== "function") {
this.return = undefined;
}
}
if (typeof Symbol === "function" && Symbol.asyncIterator) {
AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
return this;
};
}
AsyncGenerator.prototype.next = function (arg) {
return this._invoke("next", arg);
};
AsyncGenerator.prototype.throw = function (arg) {
return this._invoke("throw", arg);
};
AsyncGenerator.prototype.return = function (arg) {
return this._invoke("return", arg);
};
return {
wrap: function (fn) {
return function () {
return new AsyncGenerator(fn.apply(this, arguments));
};
},
await: function (value) {
return new AwaitValue(value);
}
};
}();
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
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;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (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;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var sizerStyle = {
position: 'absolute',
top: 0,
left: 0,
visibility: 'hidden',
height: 0,
overflow: 'scroll',
whiteSpace: 'pre'
};
var INPUT_PROPS_BLACKLIST = ['extraWidth', 'injectStyles', 'inputClassName', 'inputRef', 'inputStyle', 'minWidth', 'onAutosize', 'placeholderIsMinWidth'];
var cleanInputProps = function cleanInputProps(inputProps) {
INPUT_PROPS_BLACKLIST.forEach(function (field) {
return delete inputProps[field];
});
return inputProps;
};
var copyStyles = function copyStyles(styles, node) {
node.style.fontSize = styles.fontSize;
node.style.fontFamily = styles.fontFamily;
node.style.fontWeight = styles.fontWeight;
node.style.fontStyle = styles.fontStyle;
node.style.letterSpacing = styles.letterSpacing;
node.style.textTransform = styles.textTransform;
};
var isIE = typeof window !== 'undefined' && window.navigator ? /MSIE |Trident\/|Edge\//.test(window.navigator.userAgent) : false;
var generateId = function generateId() {
// we only need an auto-generated ID for stylesheet injection, which is only
// used for IE. so if the browser is not IE, this should return undefined.
return isIE ? '_' + Math.random().toString(36).substr(2, 12) : undefined;
};
var AutosizeInput = function (_Component) {
inherits(AutosizeInput, _Component);
createClass(AutosizeInput, null, [{
key: 'getDerivedStateFromProps',
value: function getDerivedStateFromProps(props, state) {
var id = props.id;
return id !== state.prevId ? { inputId: id || generateId(), prevId: id } : null;
}
}]);
function AutosizeInput(props) {
classCallCheck(this, AutosizeInput);
var _this = possibleConstructorReturn(this, (AutosizeInput.__proto__ || Object.getPrototypeOf(AutosizeInput)).call(this, props));
_this.inputRef = function (el) {
_this.input = el;
if (typeof _this.props.inputRef === 'function') {
_this.props.inputRef(el);
}
};
_this.placeHolderSizerRef = function (el) {
_this.placeHolderSizer = el;
};
_this.sizerRef = function (el) {
_this.sizer = el;
};
_this.state = {
inputWidth: props.minWidth,
inputId: props.id || generateId(),
prevId: props.id
};
return _this;
}
createClass(AutosizeInput, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.mounted = true;
this.copyInputStyles();
this.updateInputWidth();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps, prevState) {
if (prevState.inputWidth !== this.state.inputWidth) {
if (typeof this.props.onAutosize === 'function') {
this.props.onAutosize(this.state.inputWidth);
}
}
this.updateInputWidth();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.mounted = false;
}
}, {
key: 'copyInputStyles',
value: function copyInputStyles() {
if (!this.mounted || !window.getComputedStyle) {
return;
}
var inputStyles = this.input && window.getComputedStyle(this.input);
if (!inputStyles) {
return;
}
copyStyles(inputStyles, this.sizer);
if (this.placeHolderSizer) {
copyStyles(inputStyles, this.placeHolderSizer);
}
}
}, {
key: 'updateInputWidth',
value: function updateInputWidth() {
if (!this.mounted || !this.sizer || typeof this.sizer.scrollWidth === 'undefined') {
return;
}
var newInputWidth = void 0;
if (this.props.placeholder && (!this.props.value || this.props.value && this.props.placeholderIsMinWidth)) {
newInputWidth = Math.max(this.sizer.scrollWidth, this.placeHolderSizer.scrollWidth) + 2;
} else {
newInputWidth = this.sizer.scrollWidth + 2;
}
// add extraWidth to the detected width. for number types, this defaults to 16 to allow for the stepper UI
var extraWidth = this.props.type === 'number' && this.props.extraWidth === undefined ? 16 : parseInt(this.props.extraWidth) || 0;
newInputWidth += extraWidth;
if (newInputWidth < this.props.minWidth) {
newInputWidth = this.props.minWidth;
}
if (newInputWidth !== this.state.inputWidth) {
this.setState({
inputWidth: newInputWidth
});
}
}
}, {
key: 'getInput',
value: function getInput() {
return this.input;
}
}, {
key: 'focus',
value: function focus() {
this.input.focus();
}
}, {
key: 'blur',
value: function blur() {
this.input.blur();
}
}, {
key: 'select',
value: function select() {
this.input.select();
}
}, {
key: 'renderStyles',
value: function renderStyles() {
// this method injects styles to hide IE's clear indicator, which messes
// with input size detection. the stylesheet is only injected when the
// browser is IE, and can also be disabled by the `injectStyles` prop.
var injectStyles = this.props.injectStyles;
return isIE && injectStyles ? React.createElement('style', { dangerouslySetInnerHTML: {
__html: 'input#' + this.state.inputId + '::-ms-clear {display: none;}'
} }) : null;
}
}, {
key: 'render',
value: function render() {
var sizerValue = [this.props.defaultValue, this.props.value, ''].reduce(function (previousValue, currentValue) {
if (previousValue !== null && previousValue !== undefined) {
return previousValue;
}
return currentValue;
});
var wrapperStyle = _extends({}, this.props.style);
if (!wrapperStyle.display) wrapperStyle.display = 'inline-block';
var inputStyle = _extends({
boxSizing: 'content-box',
width: this.state.inputWidth + 'px'
}, this.props.inputStyle);
var inputProps = objectWithoutProperties(this.props, []);
cleanInputProps(inputProps);
inputProps.className = this.props.inputClassName;
inputProps.id = this.state.inputId;
inputProps.style = inputStyle;
return React.createElement(
'div',
{ className: this.props.className, style: wrapperStyle },
this.renderStyles(),
React.createElement('input', _extends({}, inputProps, { ref: this.inputRef })),
React.createElement(
'div',
{ ref: this.sizerRef, style: sizerStyle },
sizerValue
),
this.props.placeholder ? React.createElement(
'div',
{ ref: this.placeHolderSizerRef, style: sizerStyle },
this.props.placeholder
) : null
);
}
}]);
return AutosizeInput;
}(Component);
AutosizeInput.propTypes = {
className: PropTypes.string, // className for the outer element
defaultValue: PropTypes.any, // default field value
extraWidth: PropTypes.oneOfType([// additional width for input element
PropTypes.number, PropTypes.string]),
id: PropTypes.string, // id to use for the input, can be set for consistent snapshots
injectStyles: PropTypes.bool, // inject the custom stylesheet to hide clear UI, defaults to true
inputClassName: PropTypes.string, // className for the input element
inputRef: PropTypes.func, // ref callback for the input element
inputStyle: PropTypes.object, // css styles for the input element
minWidth: PropTypes.oneOfType([// minimum width for input element
PropTypes.number, PropTypes.string]),
onAutosize: PropTypes.func, // onAutosize handler: function(newWidth) {}
onChange: PropTypes.func, // onChange handler: function(event) {}
placeholder: PropTypes.string, // placeholder text
placeholderIsMinWidth: PropTypes.bool, // don't collapse size to less than the placeholder
style: PropTypes.object, // css styles for the outer element
value: PropTypes.any // field value
};
AutosizeInput.defaultProps = {
minWidth: 1,
injectStyles: true
};
export default AutosizeInput;
|
ext_frontend/src/index.js
|
per-garden/webapp
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
src/svg-icons/image/timer-3.js
|
mmrtnz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageTimer3 = (props) => (
<SvgIcon {...props}>
<path d="M11.61 12.97c-.16-.24-.36-.46-.62-.65-.25-.19-.56-.35-.93-.48.3-.14.57-.3.8-.5.23-.2.42-.41.57-.64.15-.23.27-.46.34-.71.08-.24.11-.49.11-.73 0-.55-.09-1.04-.28-1.46-.18-.42-.44-.77-.78-1.06-.33-.28-.73-.5-1.2-.64-.45-.13-.97-.2-1.53-.2-.55 0-1.06.08-1.52.24-.47.17-.87.4-1.2.69-.33.29-.6.63-.78 1.03-.2.39-.29.83-.29 1.29h1.98c0-.26.05-.49.14-.69.09-.2.22-.38.38-.52.17-.14.36-.25.58-.33.22-.08.46-.12.73-.12.61 0 1.06.16 1.36.47.3.31.44.75.44 1.32 0 .27-.04.52-.12.74-.08.22-.21.41-.38.57-.17.16-.38.28-.63.37-.25.09-.55.13-.89.13H6.72v1.57H7.9c.34 0 .64.04.91.11.27.08.5.19.69.35.19.16.34.36.44.61.1.24.16.54.16.87 0 .62-.18 1.09-.53 1.42-.35.33-.84.49-1.45.49-.29 0-.56-.04-.8-.13-.24-.08-.44-.2-.61-.36-.17-.16-.3-.34-.39-.56-.09-.22-.14-.46-.14-.72H4.19c0 .55.11 1.03.32 1.45.21.42.5.77.86 1.05s.77.49 1.24.63.96.21 1.48.21c.57 0 1.09-.08 1.58-.23.49-.15.91-.38 1.26-.68.36-.3.64-.66.84-1.1.2-.43.3-.93.3-1.48 0-.29-.04-.58-.11-.86-.08-.25-.19-.51-.35-.76zm9.26 1.4c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39s.03-.28.09-.41c.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11.19.07.35.17.48.29.13.12.22.26.29.42.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59-.43-.15-.92-.22-1.46-.22-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.68.23.96c.15.28.37.52.64.73.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.7.93.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02z"/>
</SvgIcon>
);
ImageTimer3 = pure(ImageTimer3);
ImageTimer3.displayName = 'ImageTimer3';
ImageTimer3.muiName = 'SvgIcon';
export default ImageTimer3;
|
examples/huge-apps/routes/Course/routes/Announcements/routes/Announcement/components/Announcement.js
|
chf2/react-router
|
/*globals COURSES:true */
import React from 'react'
class Announcement extends React.Component {
render() {
let { courseId, announcementId } = this.props.params
let { title, body } = COURSES[courseId].announcements[announcementId]
return (
<div>
<h4>{title}</h4>
<p>{body}</p>
</div>
)
}
}
export default Announcement
|
src/Parser/ShadowPriest/CombatLogParser.js
|
mwwscott0/WoWAnalyzer
|
import React from 'react';
import MainCombatLogParser from 'Parser/Core/CombatLogParser';
import DamageDone from 'Parser/Core/Modules/DamageDone';
import SuggestionsTab from 'Main/SuggestionsTab';
import AbilityTracker from './Modules/Core/AbilityTracker';
import CastEfficiency from './Modules/Features/CastEfficiency';
import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting';
import Insanity from './Modules/Core/Insanity';
import Mindbender from './Modules/Spells/Mindbender';
import Shadowfiend from './Modules/Spells/Shadowfiend';
import VampiricTouch from './Modules/Spells/VampiricTouch';
import ShadowWordPain from './Modules/Spells/ShadowWordPain';
import Voidform from './Modules/Spells/Voidform';
import VoidformAverageStacks from './Modules/Spells/VoidformAverageStacks';
import VoidTorrent from './Modules/Spells/VoidTorrent';
import Dispersion from './Modules/Spells/Dispersion';
import CallToTheVoid from './Modules/Spells/CallToTheVoid';
class CombatLogParser extends MainCombatLogParser {
static specModules = {
damageDone: [DamageDone, { showStatistic: true }],
alwaysBeCasting: AlwaysBeCasting,
abilityTracker: AbilityTracker,
castEfficiency: CastEfficiency,
insanity: Insanity,
// Abilities
mindbender: Mindbender,
shadowfiend: Shadowfiend,
vampiricTouch: VampiricTouch,
shadowWordPain: ShadowWordPain,
voidform: Voidform,
voidformAverageStacks: VoidformAverageStacks,
voidTorrent: VoidTorrent,
dispersion: Dispersion,
callToTheVoid: CallToTheVoid,
};
generateResults() {
const results = super.generateResults();
results.statistics = [
...results.statistics,
];
results.items = [
...results.items,
];
results.tabs = [
{
title: 'Suggestions',
url: 'suggestions',
render: () => (
<SuggestionsTab issues={results.issues} />
),
},
...results.tabs,
// {
// title: 'Talents',
// url: 'talents',
// render: () => (
// <Tab title="Talents">
// <Talents combatant={this.selectedCombatant} />
// </Tab>
// ),
// },
];
return results;
}
}
export default CombatLogParser;
|
src/field/ImageRenderer.js
|
carab/Pinarium
|
import React from 'react';
import useFirebaseImage from '../hooks/useFirebaseImage';
function ImageRenderer({value, name, ...props}) {
const [src] = useFirebaseImage(value);
if (src) {
return <img src={src} alt={value} {...props} />;
}
return null;
}
export default ImageRenderer;
|
src/js/routes.js
|
julianburr/wp-react-theme
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Index from './templates';
import Loading from './templates/loading';
import Home from './templates/home';
import SearchResult from './templates/search-result';
import Content from './templates/content';
import { connect } from 'react-redux';
import { Router, Route, IndexRoute } from 'react-router';
import { history } from './store';
import { loadSettings } from './actions/settings';
class WPThemeRoutes extends Component {
componentDidMount () {
if (this.props.loadSettings) {
this.props.loadSettings();
}
}
getRoutes () {
const { settings } = this.props;
// Home route
let routes = []; // [{path: '/', component: Home, name: 'home'}];
settings.routes.lists.forEach((route, i) => {
// Loop through routes from API
// These are generated using the WP rewrite rules!
routes.push({path: route, component: SearchResult});
})
routes.push({path: settings.routes.content, component: Content, name: 'post'});
// Finally add the content rule for everything else
routes.push({path: '*', component: Content, name: 'fallback'});
return routes;
}
willReceiveProps = (nextProps) => {
console.log('ROUTES will receive props', nextProps)
}
render () {
const { settings } = this.props;
console.log('ROUTES render')
// Show loading screen while we wait for the settings
// After settings have been loaded, return the routes
return settings ? (
<Router history={history}>
<Route path='/' component={Index}>
<IndexRoute component={Home} />
{this.getRoutes().map((route, i) => (
<Route key={i} path={route.path} component={route.component} />
))}
</Route>
</Router>
) : <Loading />;
}
}
/**
* Connect component to redux store
*/
const mapStateToProps = state => {
return {
settings: state.settings
};
}
const mapDispatchToProps = dispatch => {
return {
loadSettings: () => dispatch(loadSettings())
};
}
export default connect(mapStateToProps, mapDispatchToProps)(WPThemeRoutes)
|
app/static/src/diagnostic/EquipmentForm_modules/AditionalEqupmentParameters_modules/CableParams.js
|
vsilent/Vision
|
import React from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import Checkbox from 'react-bootstrap/lib/Checkbox';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import {findDOMNode} from 'react-dom';
import {hashHistory} from 'react-router';
import {Link} from 'react-router';
import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';
import Tooltip from 'react-bootstrap/lib/Tooltip';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
const TextField = React.createClass({
_onChange: function (e) {
this.props.onChange(e);
},
render: function () {
let tooltip = <Tooltip id={this.props.label}>{this.props.label}</Tooltip>;
var label = (this.props.label != null) ? this.props.label : "";
var name = (this.props.name != null) ? this.props.name : "";
var type = (this.props["data-type"] != null) ? this.props["data-type"]: undefined;
var len = (this.props["data-len"] != null) ? this.props["data-len"]: undefined;
var validationState = (this.props.errors[name]) ? 'error' : null;
var error = this.props.errors[name];
var value = (this.props["value"] != null) ? this.props["value"]: "";
return (
<OverlayTrigger overlay={tooltip} placement="top">
<FormGroup validationState={validationState}>
<ControlLabel>{label}</ControlLabel>
<FormControl type="text"
placeholder={label}
name={name}
data-type={type}
data-len={len}
onChange={this._onChange}
value={value}
/>
<HelpBlock className="warning">{error}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</OverlayTrigger>
);
}
});
var SelectField = React.createClass({
handleChange: function (event, index, value) {
this.setState({
value: event.target.value
});
},
getInitialState: function () {
return {
items: [],
isVisible: false,
value: -1
};
},
isVisible: function () {
return this.state.isVisible;
},
componentDidMount: function () {
var source = '/api/v1.0/' + this.props.source + '/';
this.serverRequest = $.authorizedGet(source, function (result) {
this.setState({items: (result['result'])});
}.bind(this), 'json');
},
componentWillUnmount: function () {
this.serverRequest.abort();
},
setVisible: function () {
this.state.isVisible = true;
},
render: function () {
var label = (this.props.label != null) ? this.props.label : "";
var value = (this.props.value != null) ? this.props.value : "";
var name = (this.props.name != null) ? this.props.name : "";
var validationState = (this.props.errors[name]) ? 'error' : null;
var error = this.props.errors[name];
var menuItems = [];
for (var key in this.state.items) {
menuItems.push(<option key={this.state.items[key].id}
value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>);
}
return (
<FormGroup validationState={validationState}>
<ControlLabel>{label}</ControlLabel>
<FormControl componentClass="select"
onChange={this.handleChange}
value={value}
name={this.props.name}
>
<option>{this.props.label}</option>);
{menuItems}
</FormControl>
<HelpBlock className="warning">{error}</HelpBlock>
</FormGroup>
);
}
});
var CableParams = React.createClass({
getInitialState: function () {
return {
'phase_number':'',
'sealed':'',
'model':'',
'threephase':'',
'insulation_id':'',
'id':'',
'errors': {}
}
},
handleChange: function(e){
var state = this.state;
if (e.target.type == "checkbox"){
state[e.target.name] = e.target.checked;
}
else
state[e.target.name] = e.target.value;
this.setState(state);
},
load:function() {
this.setState(this.props.equipment_item)
},
render: function () {
var errors = (Object.keys(this.state.errors).length) ? this.state.errors : this.props.errors;
return (
<div className="row">
<div className="col-md-4">
<TextField onChange={this.handleChange}
label="Model"
name="model"
value={this.state.model}
errors={errors}
data-len="50"/>
</div>
<div className="col-md-3">
<SelectField
source="insulation"
label="Insulation"
name="insulation_id"
value={this.state.insulation_id}
errors={errors}/>
</div>
<div className="col-md-2">
<Checkbox name="threephase" checked={this.state.threephase} onChange={this.handleChange}><b>Three Phase</b></Checkbox>
</div>
<div className="col-md-1">
<Checkbox name="sealed" checked={this.state.sealed} onChange={this.handleChange}><b>Sealed</b></Checkbox>
</div>
</div>
)
}
});
export default CableParams;
|
app/containers/MainContent.js
|
SiDevesh/Bootleg
|
// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import MainContentComponent from '../components/MainContentComponent';
const mapStateToProps = (state) => {
return {
selectedPane: state.navPaneState.selectedPane,
windowWidth: state.themeState.windowWidth,
windowHeight: state.themeState.windowHeight,
navPaneOpen: state.themeState.navPaneOpen
}
}
//const mapDispatchToProps = (dispatch) => {
// return {
// onPaneSelect: (name) => {
// dispatch(callPaneSelect(name));
// }
// }
//}
const MainContent = connect(
mapStateToProps
)(MainContentComponent)
export default MainContent;
|
src/js/index.js
|
nikdelig/react-redux-sass-starter-kit
|
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import App from './components/App';
const root = document.getElementById('root');
render(
<Provider>
<Router>
<App />
</Router>
</Provider>,
root,
);
|
docs/src/pages/styles/basics/AdaptingHOC.js
|
lgollut/material-ui
|
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
const styles = {
root: {
background: (props) =>
props.color === 'red'
? 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)'
: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
border: 0,
borderRadius: 3,
boxShadow: (props) =>
props.color === 'red'
? '0 3px 5px 2px rgba(255, 105, 135, .3)'
: '0 3px 5px 2px rgba(33, 203, 243, .3)',
color: 'white',
height: 48,
padding: '0 30px',
margin: 8,
},
};
function MyButtonRaw(props) {
const { classes, color, ...other } = props;
return <Button className={classes.root} {...other} />;
}
MyButtonRaw.propTypes = {
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object.isRequired,
color: PropTypes.oneOf(['blue', 'red']).isRequired,
};
const MyButton = withStyles(styles)(MyButtonRaw);
export default function AdaptingHOC() {
return (
<React.Fragment>
<MyButton color="red">Red</MyButton>
<MyButton color="blue">Blue</MyButton>
</React.Fragment>
);
}
|
src/components/Popovers.js
|
vonubisch/Cordova-PhoneGap-Babel-React-Hotloader-Webpack-OnsenUI-FontAwesome
|
import React from 'react';
import {Page, Toolbar, BackButton, Popover} from 'react-onsenui';
class Popovers extends React.Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
};
}
showPopover() {
this.setState({isOpen: true});
setTimeout(() => {
this.setState({isOpen: false});
}, 1000);
}
getTarget() {
return this.popover.target;
}
renderToolbar() {
return (
<Toolbar>
<div className="left">
<BackButton>Back</BackButton>
</div>
<div className="center">
Popovers
</div>
</Toolbar>
);
}
render() {
return (
<Page renderToolbar={this.renderToolbar}>
<div style={{textAlign: 'center'}}>
<br/>
<div
onClick={this.showPopover.bind(this)}
style={{
width: '100px',
height: '100px',
display: 'inline-block',
backgroundColor: 'rgba(0, 0, 0, 0.1)',
color: 'rgba(0, 0, 0, 0.6)',
lineHeight: '100px'
}}
ref={(popover) => { this.popover = popover; }}
>
Click me!
</div>
</div>
<Popover direction="down" isOpen={this.state.isOpen} getTarget={this.getTarget.bind(this)}>
<div
style={{
textAlign: 'center',
lineHeight: '100px'
}}
>
{"I'm a popover!"}
</div>
</Popover>
</Page>
);
}
}
export default Popovers;
|
ee/client/omnichannel/additionalForms/MaxChatsPerAgentDisplay.js
|
VoiSmart/Rocket.Chat
|
import React from 'react';
import { useTranslation } from '../../../../client/contexts/TranslationContext';
import UserInfo from '../../../../client/views/room/contextualBar/UserInfo';
const MaxChatsPerAgentDisplay = ({
data: { livechat: { maxNumberSimultaneousChat = '' } = {} } = {},
}) => {
const t = useTranslation();
return (
maxNumberSimultaneousChat && (
<>
<UserInfo.Label>{t('Max_number_of_chats_per_agent')}</UserInfo.Label>
<UserInfo.Info>{maxNumberSimultaneousChat}</UserInfo.Info>
</>
)
);
};
export default MaxChatsPerAgentDisplay;
|
next-express/components/Header.js
|
thoughtbit/node-web-starter
|
import React from 'react'
import Link from 'next/link'
import NProgress from 'nprogress'
import Router from 'next/router'
Router.onRouteChangeStart = (url) => {
console.log(`Loading: ${url}`)
NProgress.start()
}
Router.onRouteChangeComplete = () => NProgress.done()
Router.onRouteChangeError = () => NProgress.done()
export default () => (
<header>
<nav className="nav">
<Link href='/'><a>Home</a></Link>
<Link href='/blog'><a>blog</a></Link>
<Link href='/blog?id=first' as='/blog/first'><a>My first blog post</a></Link>
<Link href='/contact'><a>Contact</a></Link>
<Link href='/about'><a>About</a></Link>
<Link href='/error'><a>Error</a></Link>
</nav>
<style jsx global>{`
.nav {
text-align: center;
}
.nav a {
display: inline-block;
padding: 5px;
border: 1px solid #eee;
margin: 0 5px;
}
.nav a:hover {
background: #ccc;
}
`}</style>
</header>
)
|
node_modules/react-bootstrap/es/Tooltip.js
|
NickingMeSpace/questionnaire
|
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 PropTypes from 'prop-types';
import isRequiredForA11y from 'prop-types-extra/lib/isRequiredForA11y';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
/**
* An html id attribute, necessary for accessibility
* @type {string|number}
* @required
*/
id: isRequiredForA11y(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),
/**
* Sets the direction the Tooltip is positioned towards.
*/
placement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The "top" position value for the Tooltip.
*/
positionTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The "left" position value for the Tooltip.
*/
positionLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The "top" position value for the Tooltip arrow.
*/
arrowOffsetTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The "left" position value for the Tooltip arrow.
*/
arrowOffsetLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
};
var defaultProps = {
placement: 'right'
};
var Tooltip = function (_React$Component) {
_inherits(Tooltip, _React$Component);
function Tooltip() {
_classCallCheck(this, Tooltip);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Tooltip.prototype.render = function render() {
var _extends2;
var _props = this.props,
placement = _props.placement,
positionTop = _props.positionTop,
positionLeft = _props.positionLeft,
arrowOffsetTop = _props.arrowOffsetTop,
arrowOffsetLeft = _props.arrowOffsetLeft,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2));
var outerStyle = _extends({
top: positionTop,
left: positionLeft
}, style);
var arrowStyle = {
top: arrowOffsetTop,
left: arrowOffsetLeft
};
return React.createElement(
'div',
_extends({}, elementProps, {
role: 'tooltip',
className: classNames(className, classes),
style: outerStyle
}),
React.createElement('div', { className: prefix(bsProps, 'arrow'), style: arrowStyle }),
React.createElement(
'div',
{ className: prefix(bsProps, 'inner') },
children
)
);
};
return Tooltip;
}(React.Component);
Tooltip.propTypes = propTypes;
Tooltip.defaultProps = defaultProps;
export default bsClass('tooltip', Tooltip);
|
src/svg-icons/social/location-city.js
|
mtsandeep/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialLocationCity = (props) => (
<SvgIcon {...props}>
<path d="M15 11V5l-3-3-3 3v2H3v14h18V11h-6zm-8 8H5v-2h2v2zm0-4H5v-2h2v2zm0-4H5V9h2v2zm6 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V9h2v2zm0-4h-2V5h2v2zm6 12h-2v-2h2v2zm0-4h-2v-2h2v2z"/>
</SvgIcon>
);
SocialLocationCity = pure(SocialLocationCity);
SocialLocationCity.displayName = 'SocialLocationCity';
SocialLocationCity.muiName = 'SvgIcon';
export default SocialLocationCity;
|
src/components/pages/register.js
|
cosminseceleanu/react-sb-admin-bootstrap4
|
import React from 'react';
import {Link} from 'react-router-dom';
import {
Card,
CardBody,
CardHeader,
Form,
Input,
Label,
FormGroup,
Button,
Col
} from 'reactstrap';
const Register = () => {
return (
<Card className="card-register mx-auto mt-5">
<CardHeader>Register an Account</CardHeader>
<CardBody>
<Form>
<FormGroup>
<div className="form-row">
<Col md="6">
<Label>First name</Label>
<Input type="text" placeholder="Enter first name"/>
</Col>
</div>
</FormGroup>
<FormGroup>
<div className="form-row">
<Col md="6">
<Label>Last name</Label>
<Input type="text" placeholder="Enter last name"/>
</Col>
</div>
</FormGroup>
<FormGroup>
<div className="form-row">
<Col md="6">
<Label>Email address</Label>
<Input type="email" placeholder="Enter email"/>
</Col>
</div>
</FormGroup>
<FormGroup>
<div className="form-row">
<Col md="6">
<Label>Password</Label>
<Input type="password" placeholder="Password"/>
</Col>
</div>
</FormGroup>
<FormGroup>
<div className="form-row">
<Col md="6">
<Label>Confirm Password</Label>
<Input type="password" placeholder="Confirm password"/>
</Col>
</div>
</FormGroup>
<Button color="primary" block>Register</Button>
</Form>
<div className="text-center">
<Link className="d-block small mt-3" to="/login">Login</Link>
<Link className="d-block small" to="/forgot-password">Forgot Password?</Link>
</div>
</CardBody>
</Card>
)
};
export default Register;
|
app/src/components/RSSPanels/SuggestedFeeds.js
|
GetStream/Winds
|
import { Link } from 'react-router-dom';
import getPlaceholderImageURL from '../../util/getPlaceholderImageURL';
import { Img } from 'react-image';
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import Panel from '../Panel';
import { getSuggestedRss, followRss, unfollowRss } from '../../api';
class SuggestedFeeds extends React.Component {
componentDidMount() {
if (!this.props.suggestedRssFeeds.length) getSuggestedRss(this.props.dispatch);
}
render() {
return (
<Panel headerText="Suggested Feeds">
{this.props.suggestedRssFeeds.map((rssFeed) => {
const id = rssFeed._id;
const favicon = rssFeed.images ? rssFeed.images.favicon : null;
return (
<Link key={id} to={`/rss/${id}`}>
<Img src={[favicon, getPlaceholderImageURL(id)]} />
<div>{rssFeed.title}</div>
<div
className={`clickable ${
rssFeed.isFollowed ? 'active' : ''
}`}
onClick={(e) => {
e.preventDefault();
rssFeed.isFollowed
? unfollowRss(this.props.dispatch, id)
: followRss(this.props.dispatch, id);
}}
>
Follow
</div>
</Link>
);
})}
</Panel>
);
}
}
SuggestedFeeds.defaultProps = {
suggestedRssFeeds: [],
};
SuggestedFeeds.propTypes = {
dispatch: PropTypes.func.isRequired,
suggestedRssFeeds: PropTypes.arrayOf(PropTypes.shape()),
};
const mapStateToProps = (state) => {
if (!state.suggestedRssFeeds) return { suggestedRssFeeds: [] };
let suggestedRssFeeds = state.suggestedRssFeeds;
if (state.followedRssFeeds) {
suggestedRssFeeds = suggestedRssFeeds.map((item) => ({
...item,
isFollowed: !!state.followedRssFeeds[item._id],
}));
}
if (state.aliases) {
suggestedRssFeeds = suggestedRssFeeds.map((item) => {
if (state.aliases[item._id]) item.title = state.aliases[item._id].alias;
return item;
});
}
return {
suggestedRssFeeds,
};
};
export default connect(mapStateToProps)(SuggestedFeeds);
|
app/views/Proposals/Proposal/View/View.js
|
RcKeller/STF-Refresh
|
// NOTE: This abstraction isn't necessary, but directories will be super cluttered without.
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Alert } from 'antd'
import Head from './Head/Head'
import Overview from './Overview/Overview'
import Body from './Body/Body'
import Legacy from './Legacy/Legacy'
import Manifests from './Manifests/Manifests'
import { Loading } from '../../../../components'
/*
PROPOSAL PAGE / VIEW:
Container for proposal content rendering
Conditially renders sections based on if the data is present
(e.g. renders Overview and Body for new format proposals)
*/
@connect(state => ({
proposal: state.db.proposal._id,
isLegacy: state.db.proposal.body
? state.db.proposal.body.legacy.length > 0
: false,
published: state.db.proposal.published,
inReview: state.db.proposal.status === 'In Review'
}))
class View extends React.Component {
static propTypes = {
proposal: PropTypes.string,
isLegacy: PropTypes.bool,
published: PropTypes.bool
}
render ({ proposal, published, isLegacy, inReview } = this.props) {
// Once the proposal has loaded, render it. Only render body if published.
return (
<Loading render={proposal} title='proposal content'>
<section>
<Head />
{!published
? <Alert type='warning' showIcon
message='Unpublished Proposal'
description='This proposal has been withdrawn from publication by either an author or administrator. It exists for STF recordkeeping. For further inquiries, e-mail [email protected]'
/>
: <div>
{isLegacy ? <Legacy /> : <div><Overview /><hr /><Body /></div>}
<hr />
<Manifests />
{inReview &&
<Alert type='warning' style={{ marginTop: 28 }}
banner showIcon={false}
message={<h3>Like this proposal?</h3>}
description={<span>Endorse it - <b>it could make the difference that gets this approved!</b> Use the endorsement tab at the top to leave your remarks.</span>}
/>
}
</div>
}
</section>
</Loading>
)
}
}
export default View
|
fields/types/datetime/DatetimeField.js
|
davibe/keystone
|
import DateInput from '../../components/DateInput';
import Field from '../Field';
import moment from 'moment';
import React from 'react';
import { Button, FormField, FormInput, FormNote, InputGroup } from 'elemental';
module.exports = Field.create({
displayName: 'DatetimeField',
focusTargetRef: 'dateInput',
// default input formats
dateInputFormat: 'YYYY-MM-DD',
timeInputFormat: 'h:mm:ss a',
// parse formats (duplicated from lib/fieldTypes/datetime.js)
parseFormats: ['YYYY-MM-DD', 'YYYY-MM-DD h:m:s a', 'YYYY-MM-DD h:m a', 'YYYY-MM-DD H:m:s', 'YYYY-MM-DD H:m'],
getInitialState () {
return {
dateValue: this.props.value ? this.moment(this.props.value).format(this.dateInputFormat) : '',
timeValue: this.props.value ? this.moment(this.props.value).format(this.timeInputFormat) : ''
};
},
getDefaultProps () {
return {
formatString: 'Do MMM YYYY, h:mm:ss a'
};
},
moment (value) {
var m = moment(value);
if (this.props.isUTC) m.utc();
return m;
},
// TODO: Move isValid() so we can share with server-side code
isValid (value) {
return moment(value, this.parseFormats).isValid();
},
// TODO: Move format() so we can share with server-side code
format (value, format) {
format = format || this.dateInputFormat + ' ' + this.timeInputFormat;
return value ? this.moment(value).format(format) : '';
},
handleChange (dateValue, timeValue) {
var value = dateValue + ' ' + timeValue;
var datetimeFormat = this.dateInputFormat + ' ' + this.timeInputFormat;
this.props.onChange({
path: this.props.path,
value: this.isValid(value) ? moment(value, datetimeFormat).toISOString() : null
});
},
dateChanged (value) {
this.setState({ dateValue: value });
this.handleChange(value, this.state.timeValue);
},
timeChanged (event) {
this.setState({ timeValue: event.target.value });
this.handleChange(this.state.dateValue, event.target.value);
},
setNow () {
var dateValue = moment().format(this.dateInputFormat);
var timeValue = moment().format(this.timeInputFormat);
this.setState({
dateValue: dateValue,
timeValue: timeValue
});
this.handleChange(dateValue, timeValue);
},
renderNote () {
if (!this.props.note) return null;
return <FormNote note={this.props.note} />;
},
renderUI () {
var input;
var fieldClassName = 'field-ui';
if (this.shouldRenderField()) {
input = (
<InputGroup>
<InputGroup.Section grow>
<DateInput ref="dateInput" name={this.props.paths.date} value={this.state.dateValue} format={this.dateInputFormat} onChange={this.dateChanged} />
</InputGroup.Section>
<InputGroup.Section grow>
<FormInput name={this.props.paths.time} value={this.state.timeValue} placeholder="HH:MM:SS am/pm" onChange={this.timeChanged} autoComplete="off" />
</InputGroup.Section>
<InputGroup.Section>
<Button onClick={this.setNow}>Now</Button>
</InputGroup.Section>
</InputGroup>
);
} else {
input = <FormInput noedit>{this.format(this.props.value, this.props.formatString)}</FormInput>;
}
return (
<FormField label={this.props.label} className="field-type-datetime">
{input}
{this.renderNote()}
</FormField>
);
}
});
|
app/components/Icon.js
|
alexeyraspopov/evo
|
import React from 'react';
export default function Icon({type, className = ''}) {
return <span className={`material-icons ${className}`}>{type}</span>;
}
|
fields/components/columns/ArrayColumn.js
|
suryagh/keystone
|
import React from 'react';
import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue';
var ArrayColumn = React.createClass({
displayName: 'ArrayColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value || !value.length) return null;
return value.join(', ');
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = ArrayColumn;
|
frontend/src/Components/Table/VirtualTable.js
|
lidarr/Lidarr
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Grid, WindowScroller } from 'react-virtualized';
import Measure from 'Components/Measure';
import Scroller from 'Components/Scroller/Scroller';
import { scrollDirections } from 'Helpers/Props';
import hasDifferentItemsOrOrder from 'Utilities/Object/hasDifferentItemsOrOrder';
import styles from './VirtualTable.css';
function overscanIndicesGetter(options) {
const {
cellCount,
overscanCellsCount,
startIndex,
stopIndex
} = options;
// The default getter takes the scroll direction into account,
// but that can cause issues. Ignore the scroll direction and
// always over return more items.
const overscanStartIndex = startIndex - overscanCellsCount;
const overscanStopIndex = stopIndex + overscanCellsCount;
return {
overscanStartIndex: Math.max(0, overscanStartIndex),
overscanStopIndex: Math.min(cellCount - 1, overscanStopIndex)
};
}
class VirtualTable extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
width: 0
};
this._grid = null;
}
componentDidUpdate(prevProps, prevState) {
const {
items,
scrollIndex,
scrollTop,
onRecompute
} = this.props;
const {
width
} = this.state;
if (this._grid &&
(prevState.width !== width ||
hasDifferentItemsOrOrder(prevProps.items, items))) {
onRecompute(width);
// recomputeGridSize also forces Grid to discard its cache of rendered cells
this._grid.recomputeGridSize();
}
if (scrollIndex != null && scrollIndex !== prevProps.scrollIndex) {
this._grid.scrollToCell({
rowIndex: scrollIndex,
columnIndex: 0
});
}
if (this._grid && scrollTop !== undefined && scrollTop !== 0) {
this._grid.scrollToPosition({ scrollTop });
}
}
//
// Control
setGridRef = (ref) => {
this._grid = ref;
}
//
// Listeners
onMeasure = ({ width }) => {
this.setState({
width
});
}
//
// Render
render() {
const {
isSmallScreen,
className,
items,
scroller,
scrollTop: ignored,
header,
headerHeight,
rowHeight,
rowRenderer,
...otherProps
} = this.props;
const {
width
} = this.state;
const gridStyle = {
boxSizing: undefined,
direction: undefined,
height: undefined,
position: undefined,
willChange: undefined,
overflow: undefined,
width: undefined
};
const containerStyle = {
position: undefined
};
return (
<WindowScroller
scrollElement={isSmallScreen ? undefined : scroller}
>
{({ height, registerChild, onChildScroll, scrollTop }) => {
if (!height) {
return null;
}
return (
<Measure
whitelist={['width']}
onMeasure={this.onMeasure}
>
<Scroller
className={className}
scrollDirection={scrollDirections.HORIZONTAL}
>
{header}
<div ref={registerChild}>
<Grid
ref={this.setGridRef}
autoContainerWidth={true}
autoHeight={true}
autoWidth={true}
width={width}
height={height}
headerHeight={height - headerHeight}
rowHeight={rowHeight}
rowCount={items.length}
columnCount={1}
columnWidth={width}
scrollTop={scrollTop}
onScroll={onChildScroll}
overscanRowCount={2}
cellRenderer={rowRenderer}
overscanIndicesGetter={overscanIndicesGetter}
scrollToAlignment={'start'}
isScrollingOptout={true}
className={styles.tableBodyContainer}
style={gridStyle}
containerStyle={containerStyle}
{...otherProps}
/>
</div>
</Scroller>
</Measure>
);
}
}
</WindowScroller>
);
}
}
VirtualTable.propTypes = {
isSmallScreen: PropTypes.bool.isRequired,
className: PropTypes.string.isRequired,
items: PropTypes.arrayOf(PropTypes.object).isRequired,
scrollIndex: PropTypes.number,
scrollTop: PropTypes.number,
scroller: PropTypes.instanceOf(Element).isRequired,
header: PropTypes.node.isRequired,
headerHeight: PropTypes.number.isRequired,
rowHeight: PropTypes.oneOfType([PropTypes.func, PropTypes.number]).isRequired,
rowRenderer: PropTypes.func.isRequired,
onRecompute: PropTypes.func.isRequired
};
VirtualTable.defaultProps = {
className: styles.tableContainer,
headerHeight: 38,
rowHeight: 38,
onRecompute: () => {}
};
export default VirtualTable;
|
test/test_helper.js
|
kleavjames/SimpleYoutubeSearchApp
|
import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
fields/types/boolean/BooleanField.js
|
danielmahon/keystone
|
import React from 'react';
import Field from '../Field';
import Checkbox from '../../components/Checkbox';
import { FormField } from '../../../admin/client/App/elemental';
const NOOP = () => {};
module.exports = Field.create({
displayName: 'BooleanField',
statics: {
type: 'Boolean',
},
propTypes: {
indent: React.PropTypes.bool,
label: React.PropTypes.string,
onChange: React.PropTypes.func.isRequired,
path: React.PropTypes.string.isRequired,
value: React.PropTypes.bool,
},
valueChanged (value) {
this.props.onChange({
path: this.props.path,
value: value,
});
},
renderFormInput () {
if (!this.shouldRenderField()) return;
return (
<input
name={this.getInputName(this.props.path)}
type="hidden"
value={!!this.props.value}
/>
);
},
renderUI () {
const { indent, value, label, path } = this.props;
return (
<div data-field-name={path} data-field-type="boolean">
<FormField offsetAbsentLabel={indent}>
<label style={{ height: '2.3em' }}>
{this.renderFormInput()}
<Checkbox
checked={value}
onChange={(this.shouldRenderField() && this.valueChanged) || NOOP}
readonly={!this.shouldRenderField()}
/>
<span style={{ marginLeft: '.75em' }}>
{label}
</span>
</label>
{this.renderNote()}
</FormField>
</div>
);
},
});
|
src/applications/disability-benefits/all-claims/pages/contactInformation.js
|
department-of-veterans-affairs/vets-website
|
import React from 'react';
// import _ from 'platform/utilities/data';
import merge from 'lodash/merge';
import omit from 'platform/utilities/data/omit';
import fullSchema from 'vets-json-schema/dist/21-526EZ-ALLCLAIMS-schema.json';
// import dateUI from 'platform/forms-system/src/js/definitions/date';
// import dateRangeUI from 'platform/forms-system/src/js/definitions/dateRange';
import phoneUI from 'platform/forms-system/src/js/definitions/phone';
import emailUI from 'platform/forms-system/src/js/definitions/email';
import ReviewCardField from 'platform/forms-system/src/js/components/ReviewCardField';
import {
contactInfoDescription,
contactInfoUpdateHelpDescription,
// forwardingAddressDescription,
// ForwardingAddressViewField,
phoneEmailViewField,
} from '../content/contactInformation';
// import { isInFuture } from '../validations';
// import { hasForwardingAddress, forwardingCountryIsUSA } from '../utils';
import { addressUISchema } from '../utils/schemas';
import {
ADDRESS_PATHS,
USA,
MILITARY_STATE_LABELS,
MILITARY_STATE_VALUES,
MILITARY_CITIES,
STATE_LABELS,
STATE_VALUES,
} from '../constants';
import {
validateMilitaryCity,
validateMilitaryState,
validateZIP,
} from '../validations';
const {
// forwardingAddress,
phoneAndEmail,
} = fullSchema.properties;
const mailingAddress = merge(
{
properties: {
'view:livesOnMilitaryBase': {
type: 'boolean',
},
'view:livesOnMilitaryBaseInfo': {
type: 'object',
properties: {},
},
},
},
fullSchema.definitions.address,
);
const countryEnum = fullSchema.definitions.country.enum;
const citySchema = fullSchema.definitions.address.properties.city;
export const uiSchema = {
'ui:title': 'Contact information',
'ui:description': contactInfoDescription,
phoneAndEmail: {
'ui:title': 'Phone & email',
'ui:field': ReviewCardField,
'ui:options': {
viewComponent: phoneEmailViewField,
},
primaryPhone: phoneUI('Phone number'),
emailAddress: emailUI(),
},
mailingAddress: {
...omit(
['ui:order'],
addressUISchema(ADDRESS_PATHS.mailingAddress, 'Mailing address', true),
),
'view:livesOnMilitaryBase': {
'ui:title':
'I live on a United States military base outside of the United States',
},
'view:livesOnMilitaryBaseInfo': {
'ui:description': () => (
<div className="vads-u-padding-x--2p5">
<va-additional-info trigger="Learn more about military base addresses">
<span>
The United States is automatically chosen as your country if you
live on a military base outside of the country.
</span>
</va-additional-info>
</div>
),
},
country: {
'ui:title': 'Country',
'ui:autocomplete': 'country',
'ui:options': {
updateSchema: (formData, schema, uiSchemaCountry) => {
const uiSchemaDisabled = uiSchemaCountry;
if (formData.mailingAddress?.['view:livesOnMilitaryBase']) {
const formDataMailingAddress = formData.mailingAddress;
formDataMailingAddress.country = USA;
uiSchemaDisabled['ui:disabled'] = true;
return {
enum: [USA],
};
}
uiSchemaDisabled['ui:disabled'] = false;
return {
enum: countryEnum,
};
},
},
},
addressLine1: {
'ui:title': 'Street address (20 characters maximum)',
'ui:autocomplete': 'address-line1',
'ui:errorMessages': {
required: 'Please enter a street address',
},
},
addressLine2: {
'ui:title': 'Street address line 2 (20 characters maximum)',
'ui:autocomplete': 'address-line2',
'ui:errorMessages': {
pattern: 'Please enter a valid street address',
},
},
addressLine3: {
'ui:title': 'Street address line 3 (20 characters maximum)',
'ui:autocomplete': 'address-line3',
'ui:errorMessages': {
pattern: 'Please enter a valid street address',
},
},
city: {
'ui:autocomplete': 'address-level2',
'ui:errorMessages': {
pattern: 'Please enter a valid city',
required: 'Please enter a city',
},
'ui:options': {
replaceSchema: formData => {
if (formData.mailingAddress?.['view:livesOnMilitaryBase'] === true) {
return {
type: 'string',
title: 'APO/FPO/DPO',
enum: MILITARY_CITIES,
};
}
return merge(
{
title: 'City',
},
citySchema,
);
},
},
'ui:validations': [
{
options: { addressPath: 'mailingAddress' },
// pathWithIndex is called in validateMilitaryCity
validator: validateMilitaryCity,
},
],
},
state: {
'ui:title': 'State',
'ui:autocomplete': 'address-level1',
'ui:options': {
hideIf: formData =>
!formData.mailingAddress?.['view:livesOnMilitaryBase'] &&
formData.mailingAddress.country !== USA,
updateSchema: formData => {
if (
formData.mailingAddress?.['view:livesOnMilitaryBase'] ||
MILITARY_CITIES.includes(formData.mailingAddress.city)
) {
return {
enum: MILITARY_STATE_VALUES,
enumNames: MILITARY_STATE_LABELS,
};
}
return {
enum: STATE_VALUES,
enumNames: STATE_LABELS,
};
},
},
'ui:required': formData =>
formData.mailingAddress?.['view:livesOnMilitaryBase'] ||
formData.mailingAddress.country === USA,
'ui:validations': [
{
options: { addressPath: 'mailingAddress' },
// pathWithIndex is called in validateMilitaryState
validator: validateMilitaryState,
},
],
'ui:errorMessages': {
pattern: 'Please enter a valid state',
required: 'Please enter a state',
},
},
zipCode: {
'ui:title': 'Postal code',
'ui:autocomplete': 'postal-code',
'ui:validations': [validateZIP],
'ui:required': formData =>
formData.mailingAddress?.['view:livesOnMilitaryBase'] ||
formData.mailingAddress.country === USA,
'ui:errorMessages': {
required: 'Please enter a postal code',
pattern:
'Please enter a valid 5- or 9-digit postal code (dashes allowed)',
},
'ui:options': {
widgetClassNames: 'va-input-medium-large',
hideIf: formData =>
!formData.mailingAddress?.['view:livesOnMilitaryBase'] &&
formData.mailingAddress.country !== USA,
},
},
},
// 'view:hasForwardingAddress': {
// 'ui:title': 'My address will be changing soon.',
// },
// forwardingAddress: merge(
// addressUISchema(ADDRESS_PATHS.forwardingAddress, 'Forwarding address'),
// {
// 'ui:field': ReviewCardField,
// 'ui:subtitle': forwardingAddressDescription,
// 'ui:order': [
// 'effectiveDate',
// 'country',
// 'addressLine1',
// 'addressLine2',
// 'addressLine3',
// 'city',
// 'state',
// 'zipCode',
// ],
// 'ui:options': {
// viewComponent: ForwardingAddressViewField,
// expandUnder: 'view:hasForwardingAddress',
// },
// effectiveDate: merge(
// dateRangeUI(
// 'Start date',
// 'End date (optional)',
// 'End date must be after start date',
// ),
// {
// from: {
// 'ui:required': hasForwardingAddress,
// 'ui:validations': [isInFuture],
// },
// },
// ),
// country: {
// 'ui:required': hasForwardingAddress,
// },
// addressLine1: {
// 'ui:required': hasForwardingAddress,
// },
// city: {
// 'ui:required': hasForwardingAddress,
// },
// state: {
// 'ui:required': formData =>
// hasForwardingAddress(formData) && forwardingCountryIsUSA(formData),
// },
// zipCode: {
// 'ui:required': formData =>
// hasForwardingAddress(formData) && forwardingCountryIsUSA(formData),
// },
// },
// ),
'view:contactInfoDescription': {
'ui:description': contactInfoUpdateHelpDescription,
},
};
export const schema = {
type: 'object',
properties: {
phoneAndEmail,
mailingAddress,
// 'view:hasForwardingAddress': {
// type: 'boolean',
// },
// forwardingAddress,
'view:contactInfoDescription': {
type: 'object',
properties: {},
},
},
};
|
src/containers/auth/AuthenticateView.js
|
yursky/recommend
|
/**
* Authenticate Screen
* - Entry screen for all authentication
* - User can tap to login, forget password, signup...
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { Component } from 'react';
import {
View,
Image,
StyleSheet,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
// Consts and Libs
import { AppStyles, AppSizes, AppColors } from '@theme/';
// Components
import { Spacer, Text, Button } from '@ui/';
/* Styles ==================================================================== */
const styles = StyleSheet.create({
background: {
backgroundColor: AppColors.brand.primary,
height: AppSizes.screen.height,
width: AppSizes.screen.width,
},
logo: {
width: AppSizes.screen.width * 0.85,
resizeMode: 'contain',
},
whiteText: {
color: '#FFF',
},
});
/* Component ==================================================================== */
class Authenticate extends Component {
static componentName = 'Authenticate';
render = () => (
<View style={[AppStyles.containerCentered, AppStyles.container, styles.background]}>
<Image
source={require('../../images/wide.png')}
style={[styles.logo]}
/>
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]}>
<Button
title={'Login'}
icon={{ name: 'lock' }}
onPress={Actions.login}
backgroundColor={'#CB009E'}
/>
</View>
</View>
<Spacer size={10} />
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]}>
<Button
title={'Sign up'}
icon={{ name: 'face' }}
onPress={Actions.signUp}
backgroundColor={'#CB009E'}
/>
</View>
</View>
<Spacer size={15} />
<Text p style={[AppStyles.textCenterAligned, styles.whiteText]}>
- or -
</Text>
<Spacer size={10} />
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]} />
<View style={[AppStyles.flex2]}>
<Button
small
title={'Skip'}
onPress={Actions.app}
raised={false}
backgroundColor={'rgba(255,255,255,0.2)'}
/>
</View>
<View style={[AppStyles.flex1]} />
</View>
<Spacer size={40} />
</View>
)
}
/* Export Component ==================================================================== */
export default Authenticate;
|
app/javascript/mastodon/features/followers/index.js
|
lindwurm/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import {
lookupAccount,
fetchAccount,
fetchFollowers,
expandFollowers,
} from '../../actions/accounts';
import { FormattedMessage } from 'react-intl';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import HeaderContainer from '../account_timeline/containers/header_container';
import ColumnBackButton from '../../components/column_back_button';
import ScrollableList from '../../components/scrollable_list';
import MissingIndicator from 'mastodon/components/missing_indicator';
import TimelineHint from 'mastodon/components/timeline_hint';
const mapStateToProps = (state, { params: { acct, id } }) => {
const accountId = id || state.getIn(['accounts_map', acct]);
if (!accountId) {
return {
isLoading: true,
};
}
return {
accountId,
remote: !!(state.getIn(['accounts', accountId, 'acct']) !== state.getIn(['accounts', accountId, 'username'])),
remoteUrl: state.getIn(['accounts', accountId, 'url']),
isAccount: !!state.getIn(['accounts', accountId]),
accountIds: state.getIn(['user_lists', 'followers', accountId, 'items']),
hasMore: !!state.getIn(['user_lists', 'followers', accountId, 'next']),
isLoading: state.getIn(['user_lists', 'followers', accountId, 'isLoading'], true),
blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false),
};
};
const RemoteHint = ({ url }) => (
<TimelineHint url={url} resource={<FormattedMessage id='timeline_hint.resources.followers' defaultMessage='Followers' />} />
);
RemoteHint.propTypes = {
url: PropTypes.string.isRequired,
};
export default @connect(mapStateToProps)
class Followers extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.shape({
acct: PropTypes.string,
id: PropTypes.string,
}).isRequired,
accountId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
blockedBy: PropTypes.bool,
isAccount: PropTypes.bool,
remote: PropTypes.bool,
remoteUrl: PropTypes.string,
multiColumn: PropTypes.bool,
};
_load () {
const { accountId, isAccount, dispatch } = this.props;
if (!isAccount) dispatch(fetchAccount(accountId));
dispatch(fetchFollowers(accountId));
}
componentDidMount () {
const { params: { acct }, accountId, dispatch } = this.props;
if (accountId) {
this._load();
} else {
dispatch(lookupAccount(acct));
}
}
componentDidUpdate (prevProps) {
const { params: { acct }, accountId, dispatch } = this.props;
if (prevProps.accountId !== accountId && accountId) {
this._load();
} else if (prevProps.params.acct !== acct) {
dispatch(lookupAccount(acct));
}
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandFollowers(this.props.accountId));
}, 300, { leading: true });
render () {
const { accountIds, hasMore, blockedBy, isAccount, multiColumn, isLoading, remote, remoteUrl } = this.props;
if (!isAccount) {
return (
<Column>
<MissingIndicator />
</Column>
);
}
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
let emptyMessage;
if (blockedBy) {
emptyMessage = <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' />;
} else if (remote && accountIds.isEmpty()) {
emptyMessage = <RemoteHint url={remoteUrl} />;
} else {
emptyMessage = <FormattedMessage id='account.followers.empty' defaultMessage='No one follows this user yet.' />;
}
const remoteMessage = remote ? <RemoteHint url={remoteUrl} /> : null;
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<ScrollableList
scrollKey='followers'
hasMore={hasMore}
isLoading={isLoading}
onLoadMore={this.handleLoadMore}
prepend={<HeaderContainer accountId={this.props.accountId} hideTabs />}
alwaysPrepend
append={remoteMessage}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
>
{blockedBy ? [] : accountIds.map(id =>
<AccountContainer key={id} id={id} withNote={false} />,
)}
</ScrollableList>
</Column>
);
}
}
|
client/modules/core/components/error.js
|
open-dash/open-dash
|
import React from 'react';
const CustomError = ({error}) => (
<div style={{ color: 'red', textAlign: 'center' }}>
{error.message}
</div>
);
export default CustomError;
|
src/server.js
|
nobleach/react-redux-example
|
import Express from 'express';
import React from 'react';
import Router from 'react-router';
import Location from 'react-router/lib/Location';
import routes from './views/routes';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createRedux from './redux/create';
import { Provider } from 'redux/react';
import api from './api/api';
import ApiClient from './ApiClient';
const app = new Express();
const proxy = httpProxy.createProxyServer({
target: 'http://localhost:' + config.apiPort
});
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'favicon.ico')));
let webpackStats;
if (process.env.NODE_ENV === 'production') {
webpackStats = require('../webpack-stats.json');
}
if (app.get('env') === 'production') {
app.use(require('serve-static')(path.join(__dirname, '..', 'static')));
}
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
app.use((req, res) => {
const client = new ApiClient(req);
const redux = createRedux(client);
const location = new Location(req.path, req.query);
if (process.env.NODE_ENV === 'development') {
webpackStats = require('../webpack-stats.json');
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
delete require.cache[require.resolve('../webpack-stats.json')];
}
Router.run(routes, location, (error, initialState) => {
if (error) {
res.status(500).send(error);
} else {
Promise.all(initialState.components
.filter(component => component.fetchData)
.map(component => {
return component.fetchData(redux.dispatch);
}))
.then(() => {
const state = redux.getState();
res.send('<!doctype html>\n' + React.renderToString(
<html lang="en-us">
<head>
<meta charSet="utf-8"/>
<title>React Redux Isomorphic Example</title>
<link rel="shortcut icon" href="/favicon.ico"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css"
media="screen, projection" rel="stylesheet" type="text/css"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"
media="screen, projection" rel="stylesheet" type="text/css"/>
{webpackStats.css.map((css, i) => <link href={css} ref={i}
media="screen, projection" rel="stylesheet" type="text/css"/>)}
</head>
<body>
<div id="content" dangerouslySetInnerHTML={{__html: React.renderToString(
<Provider redux={redux}>
{() => <Router location={location} {...initialState}/>}
</Provider>)
}}/>
<script dangerouslySetInnerHTML={{__html: `window.__data=${JSON.stringify(state)};`}}/>
<script src={webpackStats.script[0]}/>
</body>
</html>));
}).catch((err) => {
res.status(500).send(err.stack);
});
}
});
});
if (config.port) {
app.listen(config.port, (err) => {
if (err) {
console.error(err);
} else {
api().then(() => {
console.info('==> ✅ Server is listening');
console.info('==> 🌎 %s running on port %s, API on port %s', config.app.name, config.port, config.apiPort);
});
}
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
src/containers/Main.js
|
WapGeaR/react-redux-boilerplate-auth
|
import React from 'react'
import {BreadCrumbs, PageHeading} from 'template/layout'
import {Block} from 'template/components'
export default class Main extends React.Component {
render() {
return(
<div className="page-content">
<BreadCrumbs childs={[
{name: 'Dashboard', url: '/', last: true}
]}/>
<PageHeading title="Dashboard" />
<div className="container-fluid">
<div>
<div className="row">
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="warning"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="danger"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="success"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="information"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="purple"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="teal"
additional="12 сайтов в цепи" />
</div>
</div>
</div>
</div>
</div>)
}
}
|
src/components/tab/tab_body.js
|
n7best/react-weui
|
import React from 'react';
import classNames from '../../utils/classnames';
/**
* Content Wrapper for Tab
*/
export default class TabBody extends React.Component {
render() {
const {children, className, ...others} = this.props;
const cls = classNames({
'weui-tab__panel': true
}, className);
return (
<div className={cls} {...others}>
{children}
</div>
);
}
}
|
examples/todomvc/src/components/Master.js
|
lore/lore
|
/**
* This component serves as the root of your application, and should typically be the only
* component subscribed to the store.
*
* It is also a good place to fetch the current user. Once you have configured 'models/currentUser'
* to fetch the current user (by pointing it to the correct API endpoint) uncomment the commented
* out code below in order to fetch the user, display a loading experience while they're being
* fetched, and store the user in the applications context so that components can retrieve it
* without having to pass it down through props or extract it from the Redux store directly.
**/
import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
import { connect } from 'lore-hook-connect';
import PayloadStates from '../constants/PayloadStates';
import RemoveLoadingScreen from './RemoveLoadingScreen';
import 'todomvc-common/base.css';
import 'todomvc-app-css/index.css';
export default connect(function(getState, props) {
return {
// user: getState('currentUser')
};
}, { subscribe: true })(
createReactClass({
displayName: 'Master',
// propTypes: {
// user: PropTypes.object.isRequired
// },
// childContextTypes: {
// user: PropTypes.object
// },
// getChildContext() {
// return {
// user: this.props.user
// };
// },
componentDidMount() {
// If you want to play with the router through the browser's dev console then
// uncomment out this line. React Router automatically provides 'router'
// to any components that are "routes" (such as Master and Layout), so this
// is a good location to attach it to the global lore object.
// lore.router = this.props.router;
},
render() {
// const { user } = this.props;
// if (user.state === PayloadStates.FETCHING) {
// return null;
// }
return (
<div>
<RemoveLoadingScreen/>
{React.cloneElement(this.props.children)}
</div>
);
}
})
);
|
client/components/PhotoDetailContainer.js
|
yinkyo/react-redux-learning
|
import React from 'react';
import PhotoDetail from './PhotoDetail';
// import Comment from ./Comment;
const PhotoDetailContainer = React.createClass({
render() {
const i = this.props.posts.findIndex(
(post) => post.code === this.props.params.postId
);
const post = this.props.posts[i];
const comment = this.props.comments[post.code] ? this.props.comments[post.code] : []
return (
<PhotoDetail
{...post} i={i}
onClick={this.props.increment.bind(null, i)}
comment={comment} />
)
}
});
export default PhotoDetailContainer;
|
src/components/Button/icons/mail.js
|
yante/halfof8
|
import React from 'react';
export default ({ color }) => <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 16">
<g fill="none" fill-rule="evenodd">
<path d="M-2-4h24v24H-2z"/>
<path fill={color || "#5261FF"} fill-rule="nonzero" d="M18 0H2C.9 0 .01.9.01 2L0 14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zm0 14H2V4l8 5 8-5v10zm-8-7L2 2h16l-8 5z"/>
</g>
</svg>
|
src/svg-icons/action/restore-page.js
|
mtsandeep/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionRestorePage = (props) => (
<SvgIcon {...props}>
<path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm-2 16c-2.05 0-3.81-1.24-4.58-3h1.71c.63.9 1.68 1.5 2.87 1.5 1.93 0 3.5-1.57 3.5-3.5S13.93 9.5 12 9.5c-1.35 0-2.52.78-3.1 1.9l1.6 1.6h-4V9l1.3 1.3C8.69 8.92 10.23 8 12 8c2.76 0 5 2.24 5 5s-2.24 5-5 5z"/>
</SvgIcon>
);
ActionRestorePage = pure(ActionRestorePage);
ActionRestorePage.displayName = 'ActionRestorePage';
ActionRestorePage.muiName = 'SvgIcon';
export default ActionRestorePage;
|
node_modules/semantic-ui-react/dist/es/modules/Accordion/AccordionTitle.js
|
SuperUncleCat/ServerMonitoring
|
import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _isNil from 'lodash/isNil';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly, createShorthandFactory } from '../../lib';
import Icon from '../../elements/Icon';
/**
* A title sub-component for Accordion component.
*/
var AccordionTitle = function (_Component) {
_inherits(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, AccordionTitle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = AccordionTitle.__proto__ || Object.getPrototypeOf(AccordionTitle)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e, _this.props);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(AccordionTitle, [{
key: 'render',
value: function render() {
var _props = this.props,
active = _props.active,
children = _props.children,
className = _props.className,
content = _props.content;
var classes = cx(useKeyOnly(active, 'active'), 'title', className);
var rest = getUnhandledProps(AccordionTitle, this.props);
var ElementType = getElementType(AccordionTitle, this.props);
if (_isNil(content)) {
return React.createElement(
ElementType,
_extends({}, rest, { className: classes, onClick: this.handleClick }),
children
);
}
return React.createElement(
ElementType,
_extends({}, rest, { className: classes, onClick: this.handleClick }),
React.createElement(Icon, { name: 'dropdown' }),
content
);
}
}]);
return AccordionTitle;
}(Component);
AccordionTitle._meta = {
name: 'AccordionTitle',
type: META.TYPES.MODULE,
parent: 'Accordion'
};
AccordionTitle.handledProps = ['active', 'as', 'children', 'className', 'content', 'onClick'];
export default AccordionTitle;
AccordionTitle.propTypes = process.env.NODE_ENV !== "production" ? {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Whether or not the title is in the open state. */
active: PropTypes.bool,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
/**
* Called on click.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick: PropTypes.func
} : {};
AccordionTitle.create = createShorthandFactory(AccordionTitle, function (content) {
return { content: content };
});
|
src/components/containers/Zones.js
|
aerendon/yik-yak
|
import React, { Component } from 'react';
import Zone from '../presentation/Zone.js';
import superagent from 'superagent';
class Zones extends Component {
constructor() {
super()
this.state = {
zone: {
name: '',
zipCode: ''
},
list: []
}
}
componentDidMount() {
console.log('componentDidMount');
superagent
.get('/api/zone')
.query(null)
.set('Accept', 'application/json')
.end((err, response) => {
if (err) {
alert('ERROR: ' + err);
}
console.log(JSON.stringify(response.body));
let results = response.body.results;
this.setState({
list: results
});
});
}
updateZone(event) {
console.log(event.target.value);
let updatedZone = Object.assign({}, this.state.zone);
updatedZone[event.target.id] = event.target.value;
this.setState({
zone: updatedZone
})
}
addZone() {
console.log('ADD ZONE: ' + JSON.stringify(this.state.zone));
let updatedList = Object.assign([], this.state.list);
updatedList.push(this.state.zone);
this.setState({
list: updatedList
});
}
render() {
const listItems = this.state.list.map((zone, i) => {
return (
<li key={i}><Zone currentZone={zone} /></li>
)
});
return (
<div>
<ol>
{listItems}
</ol>
<input id="name" onChange={this.updateZone.bind(this)} className="form-control" type="text" placeholder="Name" /><br />
<input id="zipCode" onChange={this.updateZone.bind(this)} className="form-control" type="text" placeholder="Zip Code" /><br />
<button onClick={this.addZone.bind(this)} className="btn btn-danger">Add Zone</button>
</div>
);
}
}
export default Zones
|
packages/material-ui-icons/src/PlusOne.js
|
cherniavskii/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M10 8H8v4H4v2h4v4h2v-4h4v-2h-4zm4.5-1.92V7.9l2.5-.5V18h2V5z" /></g>
, 'PlusOne');
|
examples/huge-apps/routes/Course/components/Dashboard.js
|
frankleng/react-router
|
import React from 'react';
class Dashboard extends React.Component {
render () {
return (
<div>
<h3>Course Dashboard</h3>
</div>
);
}
}
export default Dashboard;
|
src/components/Main.js
|
aframevr/aframe-inspector
|
import React from 'react';
THREE.ImageUtils.crossOrigin = '';
const Events = require('../lib/Events.js');
import ComponentsSidebar from './components/Sidebar';
import ModalTextures from './modals/ModalTextures';
import ModalHelp from './modals/ModalHelp';
import SceneGraph from './scenegraph/SceneGraph';
import CameraToolbar from './viewport/CameraToolbar';
import TransformToolbar from './viewport/TransformToolbar';
import ViewportHUD from './viewport/ViewportHUD';
import { injectCSS } from '../lib/utils';
// Megahack to include font-awesome.
injectCSS('https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css');
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
entity: null,
inspectorEnabled: true,
isModalTexturesOpen: false,
sceneEl: AFRAME.scenes[0],
visible: {
scenegraph: true,
attributes: true
}
};
Events.on('togglesidebar', event => {
if (event.which === 'all') {
if (this.state.visible.scenegraph || this.state.visible.attributes) {
this.setState({
visible: {
scenegraph: false,
attributes: false
}
});
} else {
this.setState({
visible: {
scenegraph: true,
attributes: true
}
});
}
} else if (event.which === 'attributes') {
this.setState(prevState => ({
visible: {
attributes: !prevState.visible.attributes
}
}));
} else if (event.which === 'scenegraph') {
this.setState(prevState => ({
visible: {
scenegraph: !prevState.visible.scenegraph
}
}));
}
this.forceUpdate();
});
}
componentDidMount() {
Events.on(
'opentexturesmodal',
function(selectedTexture, textureOnClose) {
this.setState({
selectedTexture: selectedTexture,
isModalTexturesOpen: true,
textureOnClose: textureOnClose
});
}.bind(this)
);
Events.on('entityselect', entity => {
this.setState({ entity: entity });
});
Events.on('inspectortoggle', enabled => {
this.setState({ inspectorEnabled: enabled });
});
Events.on('openhelpmodal', () => {
this.setState({ isHelpOpen: true });
});
}
onCloseHelpModal = value => {
this.setState({ isHelpOpen: false });
};
onModalTextureOnClose = value => {
this.setState({ isModalTexturesOpen: false });
if (this.state.textureOnClose) {
this.state.textureOnClose(value);
}
};
toggleEdit = () => {
if (this.state.inspectorEnabled) {
AFRAME.INSPECTOR.close();
} else {
AFRAME.INSPECTOR.open();
}
};
renderComponentsToggle() {
if (!this.state.entity || this.state.visible.attributes) {
return null;
}
return (
<div className="toggle-sidebar right">
<a
onClick={() => {
this.setState({ visible: { attributes: true } });
this.forceUpdate();
}}
className="fa fa-plus"
title="Show components"
/>
</div>
);
}
renderSceneGraphToggle() {
if (this.state.visible.scenegraph) {
return null;
}
return (
<div className="toggle-sidebar left">
<a
onClick={() => {
this.setState({ visible: { scenegraph: true } });
this.forceUpdate();
}}
className="fa fa-plus"
title="Show scenegraph"
/>
</div>
);
}
render() {
const scene = this.state.sceneEl;
const toggleButtonText = this.state.inspectorEnabled
? 'Back to Scene'
: 'Inspect Scene';
return (
<div>
<a className="toggle-edit" onClick={this.toggleEdit}>
{toggleButtonText}
</a>
{this.renderSceneGraphToggle()}
{this.renderComponentsToggle()}
<div
id="inspectorContainer"
className={this.state.inspectorEnabled ? '' : 'hidden'}
>
<SceneGraph
scene={scene}
selectedEntity={this.state.entity}
visible={this.state.visible.scenegraph}
/>
<div id="viewportBar">
<CameraToolbar />
<ViewportHUD />
<TransformToolbar />
</div>
<div id="rightPanel">
<ComponentsSidebar
entity={this.state.entity}
visible={this.state.visible.attributes}
/>
</div>
</div>
<ModalHelp
isOpen={this.state.isHelpOpen}
onClose={this.onCloseHelpModal}
/>
<ModalTextures
ref="modaltextures"
isOpen={this.state.isModalTexturesOpen}
selectedTexture={this.state.selectedTexture}
onClose={this.onModalTextureOnClose}
/>
</div>
);
}
}
|
app/demos/customView.js
|
asantebuil/room-reservation
|
import React from 'react';
import BigCalendar from '../../src/index';
import events from '../events';
import { navigate } from 'react-big-calendar/utils/constants';
import Week from 'react-big-calendar/Week';
import dates from 'react-big-calendar/utils/dates';
import localizer from 'react-big-calendar/localizer';
import TimeGrid from 'react-big-calendar/TimeGrid';
class MyWeek extends Week {
render() {
let { date } = this.props;
let { start, end } = MyWeek.range(date, this.props);
return (
<TimeGrid {...this.props} start={start} end={end} eventOffset={15} />
);
}
}
MyWeek.navigate = (date, action)=>{
switch (action){
case navigate.PREVIOUS:
return dates.add(date, -1, 'week');
case navigate.NEXT:
return dates.add(date, 1, 'week')
default:
return date;
}
}
MyWeek.range = (date, { culture }) => {
let firstOfWeek = localizer.startOfWeek(culture);
let start = dates.startOf(date, 'week', firstOfWeek);
let end = dates.endOf(date, 'week', firstOfWeek);
if (firstOfWeek === 1) {
end = dates.subtract(end, 2, 'day');
} else {
start = dates.add(start, 1, 'day');
end = dates.subtract(end, 1, 'day');
}
return { start, end };
}
let CustomView = React.createClass({
render(){
return (
<div>
<BigCalendar
events={events}
defaultDate={new Date(2015, 3, 1)}
views={{ month: true, week: MyWeek }}
test="io"
/>
</div>
)
}
})
export default CustomView;
|
docs/src/sections/FormInputGroupSection.js
|
dozoisch/react-bootstrap
|
import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function FormInputGroupSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="forms-input-groups">Input groups</Anchor> <small>InputGroup, InputGroup.Addon, InputGroup.Button</small>
</h2>
<h3><Anchor id="forms-input-addons">Input add-ons</Anchor></h3>
<p>Wrap your form control in an <code>{'<InputGroup>'}</code>, then use for normal add-ons and for button add-ons. Exotic configurations may require CSS on your side.</p>
<ReactPlayground codeText={Samples.FormInputAddons} />
<h3><Anchor id="forms-input-sizes">Input sizes</Anchor></h3>
<p>Use <code>bsSize</code> on <code>{'<FormGroup>'}</code> or <code>{'<InputGroup>'}</code> to change the size of inputs. It also works with add-ons and most other options.</p>
<ReactPlayground codeText={Samples.FormInputSizes} />
<h3><Anchor id="forms-input-groups-props">Props</Anchor></h3>
<h4><Anchor id="forms-props-input-group">InputGroup</Anchor></h4>
<PropTable component="InputGroup" />
<h4><Anchor id="forms-props-input-group-addon">InputGroup.Addon</Anchor></h4>
<PropTable component="InputGroupAddon" />
<h4><Anchor id="forms-props-input-group-button">InputGroup.Button</Anchor></h4>
<PropTable component="InputGroupButton" />
</div>
);
}
|
app/index.js
|
pratyk/react-signup-zxcvbn
|
import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
render(
<Router routes={routes} history={browserHistory}/>,
document.getElementById('app')
);
|
src/native/components/Header.js
|
TeodorKolev/Help
|
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import { Text, H1 } from 'native-base';
import Spacer from './Spacer';
const Header = ({ title, content }) => (
<View>
<Spacer size={25} />
<H1>{title}</H1>
{!!content &&
<View>
<Spacer size={10} />
<Text>{content}</Text>
</View>
}
<Spacer size={25} />
</View>
);
Header.propTypes = {
title: PropTypes.string,
content: PropTypes.string,
};
Header.defaultProps = {
title: 'Missing title',
content: '',
};
export default Header;
|
lib/editor/components/question_editors/parts/ValueEditorPart.js
|
jirokun/survey-designer-js
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import cuid from 'cuid';
import S from 'string';
import { List } from 'immutable';
import NumericInput from 'react-numeric-input';
import ExSelect from './ExSelect';
/**
* 直接値を入力するか、再掲値を選択するかを選ぶことのできるエディタ
*/
class ValueEditorPart extends Component {
static makeReferenceValue(od) {
return `{{${od.getId()}.answer}}`;
}
constructor(props) {
super(props);
this.cuid = cuid();
const { value } = props;
this.state = {
mode: S(value).isEmpty() || S(value).isNumeric() ? 'fixedValue' : 'answerValue',
};
}
handleChangeMode(mode) {
this.props.onChange('');
this.setState({ mode });
}
handleChangeQuestionAttribute(value) {
this.props.onChange(value);
}
createValueElement() {
const { node, options, survey, value } = this.props;
if (this.state.mode === 'fixedValue') {
if (options.isShowDetail()) {
return S(value).isEmpty() ? <span className="alert-value">未設定</span> : <span className="fixed-value">{value}</span>;
}
return (
<NumericInput
className="form-control fixed-value-input"
value={value}
placeholder="半角数字で入力"
onChange={(numValue, strValue) => this.handleChangeQuestionAttribute(strValue)}
/>
);
}
const keyBase = this.cuid;
let optionList = List().push(<option key={`${keyBase}-empty`} value="" data-error />);
const precedingOutputDefinitions = survey.findPrecedingOutputDefinition(node.getId(), true);
if (value !== '' && precedingOutputDefinitions.findIndex(od => ValueEditorPart.makeReferenceValue(od) === value) === -1) {
optionList = optionList.push(<option key={`${keyBase}-deleted`} value={value} data-error>エラー 不正な参照です</option>);
}
optionList = optionList.concat(
precedingOutputDefinitions.filter(od => od.getOutputType() === 'number')
.map(od => <option key={`${keyBase}-${od.getId()}`} value={ValueEditorPart.makeReferenceValue(od)}>{od.getLabelWithOutputNo()}</option>)
.toList());
return (
<ExSelect
className="form-control reference-select"
value={value}
onChange={e => this.handleChangeQuestionAttribute(e.target.value)}
detailMode={options.isShowDetail()}
>
{optionList}
</ExSelect>
);
}
render() {
const { options, style } = this.props;
return (
<div className="input-group value-editor-part" style={style}>
<ExSelect
className="form-control value-type"
value={this.state.mode}
onChange={e => this.handleChangeMode(e.target.value)}
detailMode={options.isShowDetail()}
>
<option value="fixedValue">固定値</option>
<option value="answerValue">回答値</option>
</ExSelect>
{this.createValueElement()}
</div>
);
}
}
const stateToProps = state => ({
survey: state.getSurvey(),
runtime: state.getRuntime(),
options: state.getOptions(),
});
export default connect(
stateToProps,
)(ValueEditorPart);
|
app/components/ToggleOption/index.js
|
MaleSharker/Qingyan
|
/**
*
* ToggleOption
*
*/
import React from 'react';
import { injectIntl, intlShape } from 'react-intl';
const ToggleOption = ({ value, message, intl }) => (
<option value={value}>
{message ? intl.formatMessage(message) : value}
</option>
);
ToggleOption.propTypes = {
value: React.PropTypes.string.isRequired,
message: React.PropTypes.object,
intl: intlShape.isRequired,
};
export default injectIntl(ToggleOption);
|
techCurriculum/ui/solutions/4.2/src/components/CardForm.js
|
tadas412/EngineeringEssentials
|
/**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
import TextInput from './TextInput.js'
class CardForm extends React.Component {
render() {
return (
<form className='card-form'>
<h2>Add a Card</h2>
<TextInput name='username' label='Username'/>
<TextInput name='message' label='Message'/>
</form>
);
}
}
export default CardForm;
|
lib/Navigation/Tabs/tabOne/views/TabOneNavigation.js
|
Ezeebube5/Nairasense
|
// React
import React from 'react';
// Redux
import { connect } from 'react-redux';
// Icon
import Icon from 'react-native-vector-icons/FontAwesome';
// Navigation
import { addNavigationHelpers } from 'react-navigation';
import { NavigatorTabOne } from '../navigationConfiguration';
class TabOneNavigation extends React.Component {
static navigationOptions = {
drawerLabel: 'Home',
drawerIcon: ({ tintColor }) => <Icon size={20} name={'home'} color={tintColor} />
}
render() {
const { navigationState, dispatch } = this.props;
return (
<NavigatorTabOne
navigation={
addNavigationHelpers({
dispatch,
state: navigationState
})
}
/>
);
}
}
const mapStateToProps = (state) => ({
navigationState: state.tabOne
});
export default connect(mapStateToProps)(TabOneNavigation);
|
demos/badges/index.js
|
isogon/styled-mdl-website
|
import React from 'react'
import DemoPage from '../../components/DemoPage'
import numberOnIcon from './demos/numberOnIcon'
import iconOnIcon from './demos/iconOnIcon'
import number from './demos/number'
import icon from './demos/icon'
import button from './demos/button'
const title = 'Badges'
const subtitle = 'Small status descriptors for UI elements.'
const demos = [
{ title: 'Badges with icons', demos: [numberOnIcon, iconOnIcon] },
{ title: 'Badges with text', demos: [number, icon] },
{ title: 'Badges with buttons', demos: [button] },
]
const usage = {
'<Badge>': {
sourceLink:
'https://github.com/isogon/styled-mdl/blob/master/src/badges/Badge.js',
props: [
{
name: 'text',
type: 'node',
default: 'undefined',
description:
'This is what will render inside the badge, can be any valid react node, but it will look strange if this is more than a few characters or a single icon',
},
{
name: 'forButton',
type: 'boolean',
default: 'false',
description:
'Set this to true if you are using the badge with a button',
},
{
name: 'overlap',
type: 'boolean',
default: 'false',
description:
'Slighly offsets the badge to the right. Set this to true if you are using the badge on top of an icon',
},
],
},
}
export default () => (
<DemoPage
title={title}
subtitle={subtitle}
demoGroups={demos}
usage={usage}
/>
)
|
jenkins-design-language/src/js/components/material-ui/svg-icons/device/battery-charging-90.js
|
alvarolobato/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const DeviceBatteryCharging90 = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h5.47L13 7v1h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L12.47 8H7v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8h-4v4.5z"/>
</SvgIcon>
);
DeviceBatteryCharging90.displayName = 'DeviceBatteryCharging90';
DeviceBatteryCharging90.muiName = 'SvgIcon';
export default DeviceBatteryCharging90;
|
src/routes/chart/Container.js
|
zhouchao0924/SLCOPY
|
import React from 'react'
import PropTypes from 'prop-types'
import styles from './Container.less'
import { ResponsiveContainer } from 'recharts'
const Container = ({ children, ratio = 5 / 2, minHeight = 250, maxHeight = 350 }) => <div className={styles.container} style={{ minHeight, maxHeight }}>
<div style={{ marginTop: `${100 / ratio}%` || '100%' }}></div>
<div className={styles.content} style={{ minHeight, maxHeight }}>
<ResponsiveContainer>
{children}
</ResponsiveContainer>
</div>
</div>
Container.propTypes = {
children: PropTypes.element.isRequired,
ratio: PropTypes.number,
minHeight: PropTypes.number,
maxHeight: PropTypes.number,
}
export default Container
|
app/components/ProgressBar/index.js
|
wenpengfei/react-boilerplate
|
import React from 'react'
import ProgressBar from './ProgressBar'
function withProgressBar(WrappedComponent) {
class AppWithProgressBar extends React.Component {
constructor(props) {
super(props)
this.state = {
progress: -1,
loadedRoutes: props.location && [props.location.pathname],
}
this.updateProgress = this.updateProgress.bind(this)
}
componentWillMount() {
// Store a reference to the listener.
/* istanbul ignore next */
this.unsubscribeHistory = this.props.router && this.props.router.listenBefore((location) => {
// Do not show progress bar for already loaded routes.
if (this.state.loadedRoutes.indexOf(location.pathname) === -1) {
this.updateProgress(0)
}
})
}
componentWillUpdate(newProps, newState) {
const { loadedRoutes, progress } = this.state
const { pathname } = newProps.location
// Complete progress when route changes. But prevent state update while re-rendering.
if (loadedRoutes.indexOf(pathname) === -1 && progress !== -1 && newState.progress < 100) {
this.updateProgress(100)
this.setState({
loadedRoutes: loadedRoutes.concat([pathname]),
})
}
}
componentWillUnmount() {
// Unset unsubscribeHistory since it won't be garbage-collected.
this.unsubscribeHistory = undefined
}
updateProgress(progress) {
this.setState({ progress })
}
render() {
return (
<div>
<ProgressBar percent={this.state.progress} updateProgress={this.updateProgress} />
<WrappedComponent {...this.props} />
</div>
)
}
}
AppWithProgressBar.propTypes = {
location: React.PropTypes.object,
router: React.PropTypes.object,
}
return AppWithProgressBar
}
export default withProgressBar
|
docs/app/Examples/elements/Image/Usage/index.js
|
clemensw/stardust
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const ImageUsageExamples = () => (
<ExampleSection title='Usage'>
<ComponentExample
title='Children'
description='An image can render children.'
examplePath='elements/Image/Usage/ImageExampleChildren'
/>
</ExampleSection>
)
export default ImageUsageExamples
|
examples/with-mobx/pages/other.js
|
nikvm/next.js
|
import React from 'react'
import { Provider } from 'mobx-react'
import { initStore } from '../store'
import Page from '../components/Page'
export default class Counter extends React.Component {
static getInitialProps ({ req }) {
const isServer = !!req
const store = initStore(isServer)
return { lastUpdate: store.lastUpdate, isServer }
}
constructor (props) {
super(props)
this.store = initStore(props.isServer, props.lastUpdate)
}
render () {
return (
<Provider store={this.store}>
<Page title='Other Page' linkTo='/' />
</Provider>
)
}
}
|
frontend/src/idPortal/users/newUser/newUserForm.js
|
unicef/un-partner-portal
|
import R from 'ramda';
import React from 'react';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import PropTypes from 'prop-types';
import TextFieldForm from '../../../components/forms/textFieldForm';
import GridColumn from '../../../components/common/grid/gridColumn';
import { email } from '../../../helpers/validation';
import RoleField from './roleField';
import { selectNormalizedOffices } from '../../../store';
import { AGENCY_ROLES } from '../../../helpers/permissions';
const messages = {
formName: 'newUserForm',
selectPartners: 'Select Partners',
selectionCriteria: 'Selection Criteria',
firstName: 'Full name',
email: 'E-mail',
};
const NewUserForm = (props) => {
const { handleSubmit, id } = props;
return (
<form onSubmit={handleSubmit}>
<div style={{ width: '40vw' }}>
<GridColumn>
<TextFieldForm
label={messages.firstName}
fieldName="fullname"
readOnly={!R.isNil(id)}
/>
<TextFieldForm
label={messages.email}
fieldName="email"
validation={[email]}
readOnly={!R.isNil(id)}
textFieldProps={{
"type": "email"
}}
/>
<RoleField id={id} formName="newUserForm" />
</GridColumn>
</div>
</form >
);
};
NewUserForm.propTypes = {
/**
* callback for form submit
*/
handleSubmit: PropTypes.func.isRequired,
id: PropTypes.number,
};
const formNewUser = reduxForm({
form: 'newUserForm',
})(NewUserForm);
const mapStateToProps = (state, ownProps) => {
let initialValues;
const offices = selectNormalizedOffices(state);
if (ownProps.id) {
const users = state.idPortalUsersList.users;
const user = R.find(R.propEq('id', ownProps.id))(users);
const fullname = user.fullname;
const email = user.email;
const office_memberships = R.map(item => R.assoc('office_id', item.office.id,
R.assoc('role', item.role, R.assoc('readOnly', state.session.officeId === item.office.id || state.session.officeRole === AGENCY_ROLES.HQ_EDITOR, null)))
, user.office_memberships);
initialValues = { fullname, email, office_memberships };
} else if (offices.length === 1) {
initialValues = { office_memberships: [{ office_id: offices[0].value }] };
}
return {
initialValues,
};
};
export default connect(
mapStateToProps,
)(formNewUser);
|
src/svg-icons/image/gradient.js
|
manchesergit/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageGradient = (props) => (
<SvgIcon {...props}>
<path d="M11 9h2v2h-2zm-2 2h2v2H9zm4 0h2v2h-2zm2-2h2v2h-2zM7 9h2v2H7zm12-6H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 18H7v-2h2v2zm4 0h-2v-2h2v2zm4 0h-2v-2h2v2zm2-7h-2v2h2v2h-2v-2h-2v2h-2v-2h-2v2H9v-2H7v2H5v-2h2v-2H5V5h14v6z"/>
</SvgIcon>
);
ImageGradient = pure(ImageGradient);
ImageGradient.displayName = 'ImageGradient';
ImageGradient.muiName = 'SvgIcon';
export default ImageGradient;
|
Realization/frontend/czechidm-core/src/components/advanced/IdentityContractInfo/IdentityContractInfo.js
|
bcvsolutions/CzechIdMng
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import * as Utils from '../../../utils';
import * as Basic from '../../basic';
import { IdentityContractManager } from '../../../redux';
import AbstractEntityInfo from '../EntityInfo/AbstractEntityInfo';
import DateValue from '../DateValue/DateValue';
import EntityInfo from '../EntityInfo/EntityInfo';
const manager = new IdentityContractManager();
/**
* Component for rendering nice identifier for identity contracts, similar function as roleInfo.
*
* @author Ondrej Kopr
* @author Radek Tomiška
*/
export class IdentityContractInfo extends AbstractEntityInfo {
getManager() {
return manager;
}
getNiceLabel() {
const _entity = this.getEntity();
const { showIdentity } = this.props;
//
return this.getManager().getNiceLabel(_entity, showIdentity);
}
/**
* Returns entity icon (null by default - icon will not be rendered)
*
* @param {object} entity
*/
getEntityIcon(entity) {
if (entity && entity.main) {
return 'component:main-contract';
}
return 'component:contract';
}
showLink() {
if (!super.showLink()) {
return false;
}
const { _permissions } = this.props;
if (!this.getManager().canRead(this.getEntity(), _permissions)) {
return false;
}
return true;
}
/**
* Returns true, when disabled decorator has to be used
*
* @param {object} entity
* @return {bool}
*/
isDisabled(entity) {
return !Utils.Entity.isValid(entity);
}
/**
* Get link to detail (`url`).
*
* @return {string}
*/
getLink() {
const { entityIdentifier } = this.props;
const _entity = this.getEntity();
//
if (!_entity._embedded || !_entity._embedded.identity) {
return null;
}
const identityIdentifier = encodeURIComponent(_entity._embedded.identity.username);
return `/identity/${ identityIdentifier }/identity-contract/${ entityIdentifier }/detail`;
}
/**
* Returns popovers title
*
* @param {object} entity
*/
getPopoverTitle() {
return this.i18n('entity.IdentityContract._type');
}
getTableChildren() {
// component are used in #getPopoverContent => skip default column resolving
return [
<Basic.Column property="label"/>,
<Basic.Column property="value"/>
];
}
/**
* Returns popover info content
*
* @param {array} table data
*/
getPopoverContent(entity) {
return [
{
label: this.i18n('entity.Identity._type'),
value: (
<EntityInfo
entityType="identity"
entity={ entity._embedded ? entity._embedded.identity : null }
entityIdentifier={ entity.identity }
face="link" />
)
},
{
label: this.i18n('entity.IdentityContract.position'),
value: entity.position
},
{
label: this.i18n('entity.IdentityContract.workPosition'),
value: (
<EntityInfo
entityType="treeNode"
entity={ entity._embedded ? entity._embedded.workPosition : null }
entityIdentifier={ entity.workPosition }
face="link" />
)
},
{
label: this.i18n('entity.TreeType._type'),
value: !entity._embedded || !entity._embedded.workPosition ||
<EntityInfo
entityType="treeType"
entity={ entity._embedded.workPosition._embedded.treeType }
entityIdentifier={ entity._embedded.workPosition.treeType }
face="link" />
},
{
label: this.i18n('entity.validFrom'),
value: (<DateValue value={ entity.validFrom }/>)
},
{
label: this.i18n('entity.validTill'),
value: (<DateValue value={ entity.validTill }/>)
}
];
}
}
IdentityContractInfo.propTypes = {
...AbstractEntityInfo.propTypes,
/**
* Selected entity - has higher priority
*/
entity: PropTypes.object,
/**
* Selected entity's id - entity will be loaded automatically
*/
entityIdentifier: PropTypes.string,
/**
* Show contract's identity
*/
showIdentity: PropTypes.bool,
//
_showLoading: PropTypes.bool,
_permissions: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.arrayOf(PropTypes.string)
])
};
IdentityContractInfo.defaultProps = {
...AbstractEntityInfo.defaultProps,
entity: null,
face: 'link',
_showLoading: true,
showIdentity: true,
};
function select(state, component) {
const entity = manager.getEntity(state, component.entityIdentifier);
return {
_entity: entity,
_showLoading: manager.isShowLoading(state, null, component.entityIdentifier),
_permissions: manager.getPermissions(state, null, component.entityIdentifier)
};
}
export default connect(select)(IdentityContractInfo);
|
app/containers/FooterContainer/index.js
|
josueorozco/parlay
|
import React from 'react';
import { connect } from 'react-redux';
import Footer from '../../components/Footer';
/*
|--------------------------------------------------------------------------
| FooterContainer
|--------------------------------------------------------------------------
|
| Container index.js
|
*/
export class FooterContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<Footer />
);
}
}
/**
* mapDispatchToProps
*
* @param dispatch
* @returns {object}
*/
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapDispatchToProps)(FooterContainer);
|
packages/mineral-ui-icons/src/IconCallMade.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconCallMade(props: IconProps) {
const iconProps = {
rtl: true,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M9 5v2h6.59L4 18.59 5.41 20 17 8.41V15h2V5z"/>
</g>
</Icon>
);
}
IconCallMade.displayName = 'IconCallMade';
IconCallMade.category = 'communication';
|
node_modules/react-bootstrap/es/BreadcrumbItem.js
|
Crisa221/Lista-Giocatori
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import SafeAnchor from './SafeAnchor';
var propTypes = {
/**
* If set to true, renders `span` instead of `a`
*/
active: React.PropTypes.bool,
/**
* `href` attribute for the inner `a` element
*/
href: React.PropTypes.string,
/**
* `title` attribute for the inner `a` element
*/
title: React.PropTypes.node,
/**
* `target` attribute for the inner `a` element
*/
target: React.PropTypes.string
};
var defaultProps = {
active: false
};
var BreadcrumbItem = function (_React$Component) {
_inherits(BreadcrumbItem, _React$Component);
function BreadcrumbItem() {
_classCallCheck(this, BreadcrumbItem);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
BreadcrumbItem.prototype.render = function render() {
var _props = this.props;
var active = _props.active;
var href = _props.href;
var title = _props.title;
var target = _props.target;
var className = _props.className;
var props = _objectWithoutProperties(_props, ['active', 'href', 'title', 'target', 'className']);
// Don't try to render these props on non-active <span>.
var linkProps = { href: href, title: title, target: target };
return React.createElement(
'li',
{ className: classNames(className, { active: active }) },
active ? React.createElement('span', props) : React.createElement(SafeAnchor, _extends({}, props, linkProps))
);
};
return BreadcrumbItem;
}(React.Component);
BreadcrumbItem.propTypes = propTypes;
BreadcrumbItem.defaultProps = defaultProps;
export default BreadcrumbItem;
|
test/test_helper.js
|
renamos/traderjoes-db
|
import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
packages/reactReduxFormBase/DEV/AppFormState.js
|
daniloster/react-experiments
|
import React, { Component } from 'react';
import Input from './Input';
import schemaData from './simpleSchemaData';
import { FormState, FormStateItem } from '../src';
export default class AppFormState extends Component {
state = {
person: {},
shouldValidate: false,
};
onValidate = (e) => {
e.preventDefault();
this.setState({ shouldValidate: true });
};
onSubmit = (e) => {
e.preventDefault();
alert('Submitting...');
};
render() {
const { shouldValidate } = this.state;
return (
<div>
<h2>FormState</h2>
<FormState schemaData={schemaData}>
<label htmlFor="firstname">Firstname</label>
<div key="name-group-data">
<FormStateItem path="firstname">
{({ onChange, value, validations }) => (
<span key="firstname" data-form-state-item>
<Input id="firstname" onChange={onChange} value={value} />
{validations && validations.map(({ message }) => message)}
</span>
)}
</FormStateItem>
<br />
<label htmlFor="lastname">Lastname</label>
<FormStateItem path="lastname">
{({ onChange, value, validations }) => (
<span key="lastname" data-form-state-item>
<Input id="lastname" onChange={onChange} value={value} />
{validations && validations.map(({ message }) => message)}
</span>
)}
</FormStateItem>
<br />
<FormStateItem>
{({ isAllValid }) => (
<button
key="validate"
onClick={this.onValidate}
disabled={!isAllValid(['fistname', 'lastname'])}
>
Validate Certificate
</button>
)}
</FormStateItem>
</div>
<label htmlFor="description">Certificate description</label>
<FormStateItem path="certificate.description">
{({ onChange, value, validations }) => (
<span key="description" data-form-state-item>
<Input id="description" onChange={onChange} value={value} />
{shouldValidate && validations && validations.map(({ message }) => message)}
</span>
)}
</FormStateItem>
<br />
<FormStateItem>
{({ isAllValid }) => (
<button key="submit" onClick={this.onSubmit} disabled={!isAllValid()}>
Submit
</button>
)}
</FormStateItem>
</FormState>
</div>
);
}
}
|
client/extensions/woocommerce/app/settings/payments/payment-method-cheque.js
|
Automattic/woocommerce-connect-client
|
/** @format */
/**
* External dependencies
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { localize } from 'i18n-calypso';
/**
* Internal dependencies
*/
import Dialog from 'components/dialog';
import FormFieldset from 'components/forms/form-fieldset';
import FormLabel from 'components/forms/form-label';
import FormTextarea from 'components/forms/form-textarea';
import FormTextInput from 'components/forms/form-text-input';
class PaymentMethodCheque extends Component {
static propTypes = {
method: PropTypes.shape( {
settings: PropTypes.shape( {
title: PropTypes.shape( {
id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
} ),
} ),
} ),
translate: PropTypes.func.isRequired,
onCancel: PropTypes.func.isRequired,
onEditField: PropTypes.func.isRequired,
onDone: PropTypes.func.isRequired,
};
onEditFieldHandler = e => {
this.props.onEditField( e.target.name, e.target.value );
};
buttons = [
{ action: 'cancel', label: this.props.translate( 'Cancel' ), onClick: this.props.onCancel },
{
action: 'save',
label: this.props.translate( 'Done' ),
onClick: this.props.onDone,
isPrimary: true,
},
];
render() {
const {
method,
method: { settings },
translate,
} = this.props;
return (
<Dialog
additionalClassNames="payments__dialog woocommerce"
buttons={ this.buttons }
isVisible
>
<FormFieldset className="payments__method-edit-field-container">
<FormLabel>{ translate( 'Title' ) }</FormLabel>
<FormTextInput
name="title"
onChange={ this.onEditFieldHandler }
value={ settings.title.value }
/>
</FormFieldset>
<FormFieldset className="payments__method-edit-field-container">
<FormLabel>{ translate( 'Instructions for customer at checkout' ) }</FormLabel>
<FormTextarea
name="description"
onChange={ this.onEditFieldHandler }
value={ method.description }
placeholder={ translate( 'Pay for this order by check.' ) }
/>
</FormFieldset>
<FormFieldset className="payments__method-edit-field-container">
<FormLabel>
{ translate( 'Instructions for customer in order email notification' ) }
</FormLabel>
<FormTextarea
name="instructions"
onChange={ this.onEditFieldHandler }
value={ settings.instructions.value }
placeholder={ translate( 'Make your check payable to…' ) }
/>
</FormFieldset>
</Dialog>
);
}
}
export default localize( PaymentMethodCheque );
|
src/components/buttons/FloatingActionButton.js
|
tuckerconnelly/carbon-ui
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Animated, TouchableOpacity, Platform } from 'react-native'
import { animate } from 'uranium'
import { Animations, TouchableRipple, Elevation, gu, connectTheme } from '../../index'
/**
* A floating action button represents the primary action in an application.
*
* The Android implementation is temporarily un-rippled until the React Native
* team implements `overflow: hidden` on Android.
*
* ### Examples
*
* import React from 'react'
* import { View } from 'react-native'
* import { FloatingActionButton, Icon, gu } from 'carbon-ui'
*
* export default () =>
* <View style={{ justifyContent: 'flex-start', flexDirection: 'row' }}>
* <FloatingActionButton style={{ marginRight: 2 * gu }}>
* <Icon name="add" style={{ color: 'white' }} />
* </FloatingActionButton>
* <FloatingActionButton accent>
* <Icon name="keyboard_voice" style={{ color: 'white' }} />
* </FloatingActionButton>
* </View>
*
*/
class FloatingActionButton extends Component {
_setPressed = e => {
Animations.standard(this._pressAV).start()
this.props.onPressIn && this.props.onPressIn(e)
}
_setNotPressed = e => {
Animations.standard(this._pressAV, { toValue: 0 }).start()
this.props.onPressOut && this.props.onPressOut(e)
}
_pressAV = new Animated.Value(0)
render() {
const { accent, children, style, theme, ...other } = this.props
// Until Android implements `overflow: hidden`. Until then, the "rippled"
// area would be square instead of round. See:
// https://github.com/facebook/react-native/issues/3198
const TouchableComponent = Platform.OS === 'android' ?
TouchableOpacity :
TouchableRipple
const styles = tStyles(theme)
return (
<Animated.View
style={[
styles.base,
animate(styles.base, styles.pressed, this._pressAV),
accent && { backgroundColor: theme.colors.accent },
].concat(style)}>
<TouchableComponent
rippleColor="white"
{...other}
style={styles.touchableRipple}
onPressIn={this._setPressed}
onPressOut={this._setNotPressed}>
{children}
</TouchableComponent>
</Animated.View>
)
}
}
FloatingActionButton.propTypes = {
/**
* Will set the background color to the accent color if set to true
*/
accent: PropTypes.bool,
/**
* Usually an <Icon />
*/
children: PropTypes.node,
style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
onPressIn: PropTypes.func,
onPressOut: PropTypes.func,
// connectTheme
theme: PropTypes.object.isRequired,
}
export default
connectTheme(
FloatingActionButton)
const tStyles = theme => ({
base: {
position: 'relative',
width: 14 * gu,
height: 14 * gu,
borderRadius: 7 * gu,
backgroundColor: theme.colors.primary,
...Elevation.dp6,
},
pressed: {
...Elevation.dp12,
},
touchableRipple: {
borderRadius: 7 * gu,
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
})
|
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js
|
chrisirhc/react-router
|
import React from 'react';
import { Link } from 'react-router';
export default class AnnouncementsSidebar extends React.Component {
render () {
var announcements = COURSES[this.props.params.courseId].announcements;
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{announcements.map(announcement => (
<li key={announcement.id}>
<Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}>
{announcement.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
|
src/components/chatbot/oldslick.js
|
gordongordon/hom
|
import React from 'react';
import { Carousel, WhiteSpace, WingBlank, Button } from 'antd-mobile';
import { Generic } from 'react-simple-chatbot';
import PropTypes from 'prop-types';
export default class Slick extends React.Component {
constructor( props ) {
super( props )
this.state = {
data: ['', '', ''],
initialHeight: 450,
value: null,
trigger: false
};
this.triggetNext = this.triggetNext.bind(this);
}
componentDidMount() {
// simulate img loading
setTimeout(() => {
this.setState({
data: ['AiyWuByWklrrUDlFignR', 'TekJlZRVCjLFexlOCuWn', 'IJOtIlfsYdTyaDTRVrLI'],
});
}, 100);
}
triggetNext() {
this.setState({ trigger: true }, () => {
this.props.triggerNextStep( { value: 'building', label : 'matching' });
});
}
render() {
const hProp = this.state.initialHeight ? { height: this.state.initialHeight } : {};
return (
<Carousel
className="my-carousel"
autoplay={false}
dots={true}
selectedIndex={0}
swipeSpeed={3}
beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}
afterChange={index => console.log('slide to', index)}
>
<Generic onClick={this.triggetNext} />
<Generic onClick={this.triggetNext} />
<Generic onClick={this.triggetNext} />
</Carousel>
);
}
}
Slick.propTypes = {
steps: PropTypes.object,
triggerNextStep: PropTypes.func,
};
Slick.defaultProps = {
steps: undefined,
triggerNextStep: undefined,
};
|
js/components/common/single-row-list-item/singleRowListItem.js
|
justarrived/p2p-client
|
import React, { Component } from 'react';
import { Text } from 'react-native';
import { CardItem, Left, Right, Icon } from 'native-base';
export default class SingleRowListItem extends Component {
static propTypes = {
text: React.PropTypes.string.isRequired,
icon: React.PropTypes.string,
};
static defaultProps = {
icon: undefined,
};
render() {
const { text, icon } = this.props;
let iconIfProvided = [];
if (icon !== undefined) {
iconIfProvided = (
<Right>
<Icon name={icon} />
</Right>
);
}
return (
<CardItem bordered button>
<Left>
<Text>{text}</Text>
</Left>
{iconIfProvided}
</CardItem>
);
}
}
|
src/icons/SignalWifi0BarIcon.js
|
kiloe/ui
|
import React from 'react';
import Icon from '../Icon';
export default class SignalWifi0BarIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path fillOpacity=".3" d="M24.02 42.98L47.28 14c-.9-.68-9.85-8-23.28-8C10.57 6 1.62 13.32.72 14l23.26 28.98.02.02.02-.02z"/></svg>;}
};
|
client/screens/Guia/index.js
|
francixcoag/trace_packages
|
import React from 'react';
import { Link } from 'react-router';
import AppNavBar from '../App/components/AppNavBar';
import AppSideBar from '../App/components/AppSideBar';
import GuiaContainer from './GuiaContainer.js';
import HeaderContainer from './HeaderContainer.js';
export default (props) => (
<div className="wrapper">
<AppNavBar label="Tracking Encomendas" screen="app/main" />
<div className="left side-menu open">
<AppSideBar label="Detalhes Guia" screen="guias/guia" />
</div>
<div className="content-page">
<div className="content">
<div className="container">
<div className="row">
<div className="col-sm-12 col-md-12 col-lg-12">
<div className="page-title-box">
<ol className="breadcrumb pull-right">
<li className="breadcrumb-item"><Link to="/app">Home</Link></li>
<li className="breadcrumb-item"><Link to="/guias">Guias</Link></li>
<li className="breadcrumb-item active">Guia Detalhes</li>
</ol>
<h4 className="page-title">Detalhes de Guia</h4>
</div>
</div>
</div>
<div className="row text-center">
<div className="col-sm-12 col-md-12 col-lg-12">
<div className="card-box">
<HeaderContainer codProcess={props.params.codProcess}/>
</div>
</div>
</div>
<div className="row text-center">
<div className="col-sm-12 col-md-12 col-lg-12">
<div className="card-box">
<GuiaContainer codProcess={props.params.codProcess}/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
|
src/DateHeader.js
|
TeaBough/react-big-calendar
|
import PropTypes from 'prop-types'
import React from 'react'
const DateHeader = ({ label, drilldownView, onDrillDown }) => {
if (!drilldownView) {
return <span>{label}</span>
}
return (
<a href="#" onClick={onDrillDown}>
{label}
</a>
)
}
DateHeader.propTypes = {
label: PropTypes.node,
date: PropTypes.instanceOf(Date),
drilldownView: PropTypes.string,
onDrillDown: PropTypes.func,
isOffRange: PropTypes.bool,
}
export default DateHeader
|
src/containers/ActivityContainer.js
|
zzelune/neam
|
/*
* @Author: zhaozheng1.zh
* @Date: 2017-09-09 22:10:22
* @Last Modified by: fishci
* @Last Modified time: 2017-10-27 16:39:14
*/
import React, { Component } from 'react';
import Activity from '../pages/activity'
import Icon from 'react-native-vector-icons/Ionicons';
export default class ActivityContainer extends Component {
static navigationOptions = {
header: null,
tabBarLabel: '活动',
tabBarIcon: ({tintColor}) => (
<Icon name='ios-home-outline' size={30} color={tintColor}/>
),
};
render() {
return (
<Activity {...this.props}/>
);
}
}
|
examples/huge-apps/routes/Course/components/Nav.js
|
cold-brew-coding/react-router
|
import React from 'react';
import { Link } from 'react-router';
import AnnouncementsRoute from '../routes/Announcements';
import AssignmentsRoute from '../routes/Assignments';
import GradesRoute from '../routes/Grades';
const styles = {};
styles.nav = {
borderBottom: '1px solid #aaa'
};
styles.link = {
display: 'inline-block',
padding: 10,
textDecoration: 'none',
};
styles.activeLink = Object.assign({}, styles.link, {
//color: 'red'
});
class Nav extends React.Component {
render () {
var { course } = this.props;
var pages = [
['announcements', 'Announcements'],
['assignments', 'Assignments'],
['grades', 'Grades'],
];
return (
<nav style={styles.nav}>
{pages.map((page, index) => (
<Link
key={page[0]}
activeStyle={index === 0 ?
Object.assign({}, styles.activeLink, { paddingLeft: 0 }) :
styles.activeLink}
style={index === 0 ?
Object.assign({}, styles.link, { paddingLeft: 0 }) :
styles.link }
to={`/course/${course.id}/${page[0]}`}
>{page[1]}</Link>
))}
</nav>
);
}
}
export default Nav;
|
frontend/src/components/pages/video.js
|
wilsonwen/kanmeiju
|
import React, { Component } from 'react';
import Config from '../../config'
import { browserHistory } from 'react-router';
import Spin from '../spin'
import { VelocityTransitionGroup } from 'velocity-react';
import './video.css'
class Video extends Component {
constructor(props) {
super(props);
this.state = {
fetchDone: false,
json : ""
}
this.config = Config();
this.fetchData = this.fetchData.bind(this);
this.handleError = this.handleError.bind(this);
}
/* callde first initialize */
componentDidMount() {
this.fetchData(this.props.params.episodeSid);
}
fetchData(episodeSid) {
let url = this.config.server + '/api/m3u8/' + episodeSid;
fetch(url).then((res) => res.json()).then((data) => {
this.setState({
fetchDone: true,
json: data
});
}).catch(function(error){
this.setState({
fetchDone: true
})
}.bind(this));
}
handleError() {
this.setState({json: {'data': undefined}});
}
render() {
let content = null;
/* Check search done */
if (this.state.fetchDone) {
if (this.state.json.data !== undefined &&
this.state.json.data.m3u8 !== undefined &&
this.state.json.data.m3u8.url !== "") {
content = <video className="col-xs-12"
src={this.state.json.data.m3u8.url}
type="video/mp4"
onError={this.handleError}
controls autoPlay>
</video>
} else {
content = <div className="alert alert-danger" role="alert">
<span className="sr-only">Error:</span>
抱歉,视频已经下线。<a href="#" onClick={browserHistory.goBack}>返回剧集</a>
</div>
}
} else {
content = <Spin />
}
return (
<div >
<VelocityTransitionGroup enter={{animation: "transition.slideLeftIn"}} leave={{animation: "transition.slideRightOut"}}
runOnMount={true}>
<p className="video-title">{this.props.params.title}</p>
{ content }
</VelocityTransitionGroup>
</div>
)
}
}
export default Video;
|
packages/babel-plugin-jsx-pragmatic/__tests__/__fixtures__/existing-imports.js
|
emotion-js/emotion
|
// inserted import has to go AFTER polyfills
import 'react-app-polyfill/ie11'
import 'react-app-polyfill/stable'
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(<App />, document.getElementById('root'))
|
node_modules/react-router/es6/Router.js
|
ottomajik/react-demo
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import warning from 'warning';
import React, { Component } from 'react';
import createHashHistory from 'history/lib/createHashHistory';
import { createRoutes } from './RouteUtils';
import RoutingContext from './RoutingContext';
import useRoutes from './useRoutes';
import { routes } from './PropTypes';
var _React$PropTypes = React.PropTypes;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;
/**
* A <Router> is a high-level API for automatically setting up
* a router that renders a <RoutingContext> with all the props
* it needs each time the URL changes.
*/
var Router = (function (_Component) {
_inherits(Router, _Component);
function Router(props, context) {
_classCallCheck(this, Router);
_Component.call(this, props, context);
this.state = {
location: null,
routes: null,
params: null,
components: null
};
}
Router.prototype.handleError = function handleError(error) {
if (this.props.onError) {
this.props.onError.call(this, error);
} else {
// Throw errors by default so we don't silently swallow them!
throw error; // This error probably occurred in getChildRoutes or getComponents.
}
};
Router.prototype.componentWillMount = function componentWillMount() {
var _this = this;
var _props = this.props;
var history = _props.history;
var children = _props.children;
var routes = _props.routes;
var parseQueryString = _props.parseQueryString;
var stringifyQuery = _props.stringifyQuery;
var createHistory = history ? function () {
return history;
} : createHashHistory;
this.history = useRoutes(createHistory)({
routes: createRoutes(routes || children),
parseQueryString: parseQueryString,
stringifyQuery: stringifyQuery
});
this._unlisten = this.history.listen(function (error, state) {
if (error) {
_this.handleError(error);
} else {
_this.setState(state, _this.props.onUpdate);
}
});
};
/* istanbul ignore next: sanity check */
Router.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
process.env.NODE_ENV !== 'production' ? warning(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : undefined;
process.env.NODE_ENV !== 'production' ? warning((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : undefined;
};
Router.prototype.componentWillUnmount = function componentWillUnmount() {
if (this._unlisten) this._unlisten();
};
Router.prototype.render = function render() {
var _state = this.state;
var location = _state.location;
var routes = _state.routes;
var params = _state.params;
var components = _state.components;
var _props2 = this.props;
var RoutingContext = _props2.RoutingContext;
var createElement = _props2.createElement;
var props = _objectWithoutProperties(_props2, ['RoutingContext', 'createElement']);
if (location == null) return null; // Async match
// Only forward non-Router-specific props to routing context, as those are
// the only ones that might be custom routing context props.
Object.keys(Router.propTypes).forEach(function (propType) {
return delete props[propType];
});
return React.createElement(RoutingContext, _extends({}, props, {
history: this.history,
createElement: createElement,
location: location,
routes: routes,
params: params,
components: components
}));
};
return Router;
})(Component);
Router.propTypes = {
history: object,
children: routes,
routes: routes, // alias for children
RoutingContext: func.isRequired,
createElement: func,
onError: func,
onUpdate: func,
parseQueryString: func,
stringifyQuery: func
};
Router.defaultProps = {
RoutingContext: RoutingContext
};
export default Router;
|
docs/src/app/components/pages/components/FlatButton/Page.js
|
rscnt/material-ui
|
import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import flatButtonReadmeText from './README';
import flatButtonExampleSimpleCode from '!raw!./ExampleSimple';
import FlatButtonExampleSimple from './ExampleSimple';
import flatButtonExampleComplexCode from '!raw!./ExampleComplex';
import FlatButtonExampleComplex from './ExampleComplex';
import flatButtonExampleIconCode from '!raw!./ExampleIcon';
import FlatButtonExampleIcon from './ExampleIcon';
import flatButtonCode from '!raw!material-ui/lib/FlatButton/FlatButton';
const descriptions = {
simple: '`FlatButton` with default color, `primary`, `secondary` and and `disabled` props applied.',
complex: 'The first example uses an `input` as a child component, ' +
'the next has next has an [SVG Icon](/#/components/svg-icon), with the label positioned after. ' +
'The final example uses a [Font Icon](/#/components/font-icon), and is wrapped in an anchor tag.',
icon: 'Examples of Flat Buttons using an icon without a label. The first example uses an' +
' [SVG Icon](/#/components/svg-icon), and has the default color. The second example shows' +
' how the icon and background color can be changed. The final example uses a' +
' [Font Icon](/#/components/font-icon), and is wrapped in an anchor tag.',
};
const FlatButtonPage = () => (
<div>
<Title render={(previousTitle) => `Flat Button - ${previousTitle}`} />
<MarkdownElement text={flatButtonReadmeText} />
<CodeExample
title="Simple examples"
description={descriptions.simple}
code={flatButtonExampleSimpleCode}
>
<FlatButtonExampleSimple />
</CodeExample>
<CodeExample
title="Complex examples"
description={descriptions.complex}
code={flatButtonExampleComplexCode}
>
<FlatButtonExampleComplex />
</CodeExample>
<CodeExample
title="Icon examples"
description={descriptions.icon}
code={flatButtonExampleIconCode}
>
<FlatButtonExampleIcon />
</CodeExample>
<PropTypeDescription code={flatButtonCode} />
</div>
);
export default FlatButtonPage;
|
src/containers/NotFound/NotFound.js
|
Trippstan/elephonky
|
import React from 'react';
export default function NotFound() {
return (
<div className="container">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
);
}
|
frontend/src/containers/AppContainer.js
|
SeaItRise/SeaItRise-webportal
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { browserHistory, Router } from 'react-router';
import { Provider } from 'react-redux';
class AppContainer extends Component {
static propTypes = {
routes: PropTypes.object.isRequired,
store: PropTypes.object.isRequired,
}
shouldComponentUpdate() {
return false;
}
render() {
const { routes, store } = this.props;
return (
<Provider store={store}>
<div style={{ height: '100%' }}>
<Router history={browserHistory} children={routes} />
</div>
</Provider>
);
}
}
export default AppContainer;
|
react/features/old-client-notification/components/OldElectronAPPNotificationDescription.js
|
bgrozev/jitsi-meet
|
// @flow
import React, { Component } from 'react';
import { translate } from '../../base/i18n';
/**
* The type of the React {@code Component} props of {@link OldElectronAPPNotificationDescription}.
*/
type Props = {
/**
* Invoked to obtain translated strings.
*/
t: Function
};
/**
* A component that renders the description of the notification for old Jitsi Meet Electron clients.
*
* @extends AbstractApp
*/
export class OldElectronAPPNotificationDescription extends Component<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { t } = this.props;
return (
<div>
{ t('notify.oldElectronClientDescription1') }
<a
href = 'https://github.com/jitsi/jitsi-meet-electron/releases/latest'
rel = 'noopener noreferrer'
target = '_blank'>
{ t('notify.oldElectronClientDescription2') }
</a>
{ t('notify.oldElectronClientDescription3') }
</div>);
}
}
export default translate(OldElectronAPPNotificationDescription);
|
client/src/components/Header/index.js
|
pahosler/freecodecamp
|
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'gatsby';
import FCCSearch from 'react-freecodecamp-search';
import NavLogo from './components/NavLogo';
import UserState from './components/UserState';
import './header.css';
function Header({ disableSettings }) {
return (
<header>
<nav id='top-nav'>
<a className='home-link' href='https://www.freecodecamp.org'>
<NavLogo />
</a>
{disableSettings ? null : <FCCSearch />}
<ul id='top-right-nav'>
<li>
<Link to='/learn'>Curriculum</Link>
</li>
<li>
<a
href='https://forum.freecodecamp.org'
rel='noopener noreferrer'
target='_blank'
>
Forum
</a>
</li>
<li>
<UserState disableSettings={disableSettings} />
</li>
</ul>
</nav>
</header>
);
}
Header.propTypes = {
disableSettings: PropTypes.bool
};
export default Header;
|
examples/IconSimple.js
|
mattBlackDesign/react-materialize
|
import React from 'react';
import Icon from '../src/Icon';
export default
<Icon>insert_chart</Icon>;
|
examples/passing-props-to-children/app.js
|
ryardley/react-router
|
import React from 'react';
import { Router, Route, Link, History } from 'react-router';
var App = React.createClass({
mixins: [ History ],
getInitialState() {
return {
tacos: [
{ name: 'duck confit' },
{ name: 'carne asada' },
{ name: 'shrimp' }
]
};
},
addTaco() {
var name = prompt('taco name?');
this.setState({
tacos: this.state.tacos.concat({name: name})
});
},
handleRemoveTaco(removedTaco) {
var tacos = this.state.tacos.filter(function (taco) {
return taco.name != removedTaco;
});
this.setState({tacos: tacos});
this.history.pushState(null, '/');
},
render() {
var links = this.state.tacos.map(function (taco, i) {
return (
<li key={i}>
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
</li>
);
});
return (
<div className="App">
<button onClick={this.addTaco}>Add Taco</button>
<ul className="Master">
{links}
</ul>
<div className="Detail">
{this.props.children && React.cloneElement(this.props.children, {
onRemoveTaco: this.handleRemoveTaco
})}
</div>
</div>
);
}
});
var Taco = React.createClass({
remove() {
this.props.onRemoveTaco(this.props.params.name);
},
render() {
return (
<div className="Taco">
<h1>{this.props.params.name}</h1>
<button onClick={this.remove}>remove</button>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="taco/:name" component={Taco} />
</Route>
</Router>
), document.getElementById('example'));
|
node_modules/react-bootstrap/es/ButtonGroup.js
|
Technaesthetic/ua-tools
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import all from 'react-prop-types/lib/all';
import Button from './Button';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
vertical: React.PropTypes.bool,
justified: React.PropTypes.bool,
/**
* Display block buttons; only useful when used with the "vertical" prop.
* @type {bool}
*/
block: all(React.PropTypes.bool, function (_ref) {
var block = _ref.block,
vertical = _ref.vertical;
return block && !vertical ? new Error('`block` requires `vertical` to be set to have any effect') : null;
})
};
var defaultProps = {
block: false,
justified: false,
vertical: false
};
var ButtonGroup = function (_React$Component) {
_inherits(ButtonGroup, _React$Component);
function ButtonGroup() {
_classCallCheck(this, ButtonGroup);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ButtonGroup.prototype.render = function render() {
var _extends2;
var _props = this.props,
block = _props.block,
justified = _props.justified,
vertical = _props.vertical,
className = _props.className,
props = _objectWithoutProperties(_props, ['block', 'justified', 'vertical', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps)] = !vertical, _extends2[prefix(bsProps, 'vertical')] = vertical, _extends2[prefix(bsProps, 'justified')] = justified, _extends2[prefix(Button.defaultProps, 'block')] = block, _extends2));
return React.createElement('div', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return ButtonGroup;
}(React.Component);
ButtonGroup.propTypes = propTypes;
ButtonGroup.defaultProps = defaultProps;
export default bsClass('btn-group', ButtonGroup);
|
src/components/TabBarIOS.js
|
RealOrangeOne/react-native-mock
|
import React from 'react';
import createMockComponent from './createMockComponent';
const TabBarIOS = React.createClass({
propTypes: {
children: React.PropTypes.node
},
statics: {
Item: createMockComponent('TabBarIOS.Item')
},
render() {
return null;
}
});
module.exports = TabBarIOS;
|
app/assets/javascripts/components/stories/StoryLink.js
|
Codeminer42/cm42-central
|
import React from 'react';
import hoverTemplate from 'templates/story_hover.ejs';
import noteTemplate from 'templates/note.ejs';
const STORY_STATE_ICONS = {
unstarted: 'access_time',
started: 'check_box_outline_blank',
finished: 'check_box',
delivered: 'hourglass_empty',
rejected: 'close',
accepted: 'done'
};
export default class StoryLink extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const { story } = this.props;
document.getElementById(`story-${story.get('id')}`).scrollIntoView();
story && _.each(story.views, view => view.highlight());
}
renderIcon(storyState) {
return (
<i className={`mi story-link-icon ${storyState}`}>
{STORY_STATE_ICONS[storyState]}
</i>
);
}
render() {
const { story } = this.props;
const storyState = story.get('state');
const id = story.get('id');
const popoverContent = hoverTemplate({
story: story,
noteTemplate: noteTemplate
});
return (
<a className={`story-link popover-activate ${storyState}`}
data-content={popoverContent}
data-original-title={story.get('title')}
id={`story-link-${id}`}
onClick={this.handleClick}>
{ `#${id}` }
{ (storyState !== 'unscheduled') && this.renderIcon(storyState) }
</a>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.