path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
client/components/categories/item.js | jankeromnes/kresus | import React from 'react';
import PropTypes from 'prop-types';
import { translate as $t, NONE_CATEGORY_ID, assert } from '../../helpers';
import ConfirmDeleteModal from '../ui/confirm-delete-modal';
import ColorPicker from '../ui/color-picker';
class CategoryListItem extends React.Component {
constructor(props) {
super(props);
if (this.isCreating()) {
assert(this.props.createCategory instanceof Function);
assert(this.props.onCancelCreation instanceof Function);
} else {
assert(this.props.updateCategory instanceof Function);
assert(this.props.deleteCategory instanceof Function);
}
this.handleKeyUp = this.handleKeyUp.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.handleSave = this.handleSave.bind(this);
this.handleColorSave = this.handleColorSave.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.colorInput = null;
this.titleInput = null;
this.replacementSelector = null;
}
isEditing() {
return (typeof this.props.cat.id !== 'undefined');
}
isCreating() {
return !this.isEditing();
}
handleKeyUp(e) {
if (e.key === 'Enter') {
return this.handleSave(e);
} else if (e.key === 'Escape') {
if (this.isEditing()) {
e.target.value = this.props.cat.title;
} else {
this.props.onCancelCreation(e);
}
}
return true;
}
handleColorSave(e) {
if (this.isEditing() || this.titleInput.value.trim().length) {
this.handleSave(e);
}
}
handleSave(e) {
let cat = this.props.cat;
let title = this.titleInput.value.trim();
let color = this.colorInput.getValue();
if (!title || !color || ((color === cat.color) && (title === cat.title))) {
if (this.isCreating()) {
this.props.onCancelCreation(e);
} else if (!this.title) {
this.titleInput.value = this.props.cat.title;
}
return false;
}
let category = {
title,
color
};
if (this.isEditing()) {
this.props.updateCategory(cat, category);
} else {
this.props.createCategory(category);
this.titleInput.value = '';
this.props.onCancelCreation(e);
}
if (e && e instanceof Event) {
e.preventDefault();
}
}
handleBlur(e) {
if (this.isEditing()) {
this.handleSave(e);
}
}
handleDelete(e) {
if (this.isEditing()) {
let replaceCategory = this.replacementSelector.value;
this.props.deleteCategory(this.props.cat, replaceCategory);
} else {
this.props.onCancelCreation(e);
}
}
selectTitle() {
this.titleInput.select();
}
render() {
let c = this.props.cat;
let replacementOptions = this.props.categories
.filter(cat => cat.id !== c.id)
.map(cat => (
<option
key={ cat.id }
value={ cat.id }>
{ cat.title }
</option>
));
replacementOptions = [
<option
key="none"
value={ NONE_CATEGORY_ID }>
{ $t('client.category.dont_replace') }
</option>
].concat(replacementOptions);
let deleteButton;
let maybeModal;
if (this.isCreating()) {
deleteButton = (<span
className="fa fa-times-circle"
aria-label="remove"
onClick={ this.handleDelete }
title={ $t('client.general.delete') }
/>);
} else {
deleteButton = (<span
className="fa fa-times-circle"
aria-label="remove"
data-toggle="modal"
data-target={ `#confirmDeleteCategory${c.id}` }
title={ $t('client.general.delete') }
/>);
let refReplacementSelector = selector => {
this.replacementSelector = selector;
};
let modalBody = (<div>
<div className="alert alert-info">
{ $t('client.category.erase', { title: c.title }) }
</div>
<div>
<select
className="form-control"
ref={ refReplacementSelector }>
{ replacementOptions }
</select>
</div>
</div>);
maybeModal = (<ConfirmDeleteModal
modalId={ `confirmDeleteCategory${c.id}` }
modalBody={ modalBody }
onDelete={ this.handleDelete }
/>);
}
let refColorInput = input => {
this.colorInput = input;
};
let refTitleInput = input => {
this.titleInput = input;
};
return (
<tr key={ c.id }>
<td>
<ColorPicker
defaultValue={ c.color }
onChange={ this.handleColorSave }
ref={ refColorInput }
/>
</td>
<td>
<input
type="text"
className="form-control"
placeholder={ $t('client.category.label') }
defaultValue={ c.title }
onKeyUp={ this.handleKeyUp }
onBlur={ this.handleBlur }
ref={ refTitleInput }
/>
</td>
<td>
{ deleteButton }
{ maybeModal }
</td>
</tr>
);
}
}
CategoryListItem.propTypes = {
// The category related to this item.
cat: PropTypes.object.isRequired,
// The list of categories.
categories: PropTypes.array.isRequired,
// The method to create a category.
createCategory: PropTypes.func,
// The method to update a category.
updateCategory: PropTypes.func,
// The method to delete a category.
deleteCategory: PropTypes.func,
// A method to call when the creation of a category is cancelled.
onCancelCreation: PropTypes.func
};
export default CategoryListItem;
|
packages/pix-web/src/ui/index.js | madjam002/pix | import React from 'react'
import {Spinner} from '@blueprintjs/core'
import styles from './index.less'
export * from '@blueprintjs/core'
export * from './atom'
export * from './blueprints'
export * from './form'
export * from './layout'
export * from './typography'
export const FormButton = props => <button {...props} />
export const LoadingScreen = () => (
<div className={styles.loading}>
<Spinner />
</div>
)
export const SideBySide = props => (
<div className={styles.sideBySide} style={{ alignItems: props.align }}>
{props.children}
</div>
)
export const ContentWithRight = props => (
<div className={styles.sideBySide} style={{ alignItems: props.align }}>
<div className={styles.fill}>{props.content}</div>
<div>{props.right}</div>
</div>
)
export const FixedWidth = props => (
<div style={{ width: props.width }}>
{props.children}
</div>
)
|
docs/app/Examples/elements/List/Content/ListExampleDescription.js | ben174/Semantic-UI-React | import React from 'react'
import { List } from 'semantic-ui-react'
const ListExampleDescription = () => (
<List>
<List.Item>
<List.Icon name='map marker' />
<List.Content>
<List.Header as='a'>Krowlewskie Jadlo</List.Header>
<List.Description>An excellent polish restaurant, quick delivery and hearty, filling meals.</List.Description>
</List.Content>
</List.Item>
<List.Item>
<List.Icon name='map marker' />
<List.Content>
<List.Header as='a'>Xian Famous Foods</List.Header>
<List.Description>
A taste of Shaanxi's delicious culinary traditions, with delights like spicy cold noodles and lamb burgers.
</List.Description>
</List.Content>
</List.Item>
<List.Item>
<List.Icon name='map marker' />
<List.Content>
<List.Header as='a'>Sapporo Haru</List.Header>
<List.Description>Greenpoint's best choice for quick and delicious sushi.</List.Description>
</List.Content>
</List.Item>
<List.Item>
<List.Icon name='map marker' />
<List.Content>
<List.Header as='a'>Enid's</List.Header>
<List.Description>At night a bar, during the day a delicious brunch spot.</List.Description>
</List.Content>
</List.Item>
</List>
)
export default ListExampleDescription
|
app/javascript/mastodon/features/notifications/components/notification.js | palon7/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import StatusContainer from '../../../containers/status_container';
import AccountContainer from '../../../containers/account_container';
import { FormattedMessage } from 'react-intl';
import Permalink from '../../../components/permalink';
import emojify from '../../../emoji';
import escapeTextContentForBrowser from 'escape-html';
import ImmutablePureComponent from 'react-immutable-pure-component';
export default class Notification extends ImmutablePureComponent {
static propTypes = {
notification: ImmutablePropTypes.map.isRequired,
};
renderFollow (account, link) {
return (
<div className='notification notification-follow'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-user-plus' />
</div>
<FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} />
</div>
<AccountContainer id={account.get('id')} withNote={false} />
</div>
);
}
renderMention (notification) {
return <StatusContainer id={notification.get('status')} withDismiss />;
}
renderFavourite (notification, link) {
return (
<div className='notification notification-favourite'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-star star-icon' />
</div>
<FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} />
</div>
<StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss />
</div>
);
}
renderReblog (notification, link) {
return (
<div className='notification notification-reblog'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-retweet' />
</div>
<FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} />
</div>
<StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss />
</div>
);
}
render () {
const { notification } = this.props;
const account = notification.get('account');
const displayName = account.get('display_name').length > 0 ? account.get('display_name') : account.get('username');
const displayNameHTML = { __html: emojify(escapeTextContentForBrowser(displayName)) };
const link = <Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHTML} />;
switch(notification.get('type')) {
case 'follow':
return this.renderFollow(account, link);
case 'mention':
return this.renderMention(notification);
case 'favourite':
return this.renderFavourite(notification, link);
case 'reblog':
return this.renderReblog(notification, link);
}
return null;
}
}
|
scripts/Admin/Default.js | krulmacius/sdasdasdasfgasdawsdwadawd | import React from 'react';
class Default extends React.Component {
constructor(props)
{
super(props);
}
render()
{
return(
<div>
</div>
);
}
}
export default Default;
|
src/components/app.js | JennerChen/simple-personal-cloudyService | import React from 'react';
import Radium from 'radium';
import { Menu, Icon } from 'antd';
import {Link} from 'react-router';
import { Layout } from 'antd';
const { Header, Sider, Content } = Layout;
@Radium
class App extends React.Component {
render() {
const {children} = this.props;
return (<Layout>
<Header>
<Menu
style={{ lineHeight: '64px' }}
theme="dark"
mode="horizontal"
>
<Menu.Item key="file">
<Link to="/file" style={ { fontSize: 20+"px"} }><Icon type="hdd" />文件</Link>
</Menu.Item>
</Menu>
</Header>
<Content>
{ children }
</Content>
</Layout>);
}
}
export default App; |
src/svg-icons/communication/stay-primary-landscape.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationStayPrimaryLandscape = (props) => (
<SvgIcon {...props}>
<path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/>
</SvgIcon>
);
CommunicationStayPrimaryLandscape = pure(CommunicationStayPrimaryLandscape);
CommunicationStayPrimaryLandscape.displayName = 'CommunicationStayPrimaryLandscape';
CommunicationStayPrimaryLandscape.muiName = 'SvgIcon';
export default CommunicationStayPrimaryLandscape;
|
frontend/src/pages/credits/credits.js | petar-prog91/go-bank-web | import React from 'react';
import { connect } from 'react-redux';
const Credits = () => (
<div>
<h1>Exchange page</h1>
<p>Work in progress</p>
</div>
);
export default connect()(Credits);
|
src/views/components/chatroom/comment/comment.js | EragonJ/Kaku | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactEmoji from 'react-emoji';
class CommentComponent extends Component {
constructor(props) {
super(props);
}
render() {
let data = this.props.data;
// TODO
// drop ReactEmoji since we do have emoji-mart now.
// need to figure out the way to parse strings to <span>
let emojifiedComment = ReactEmoji.emojify(data.comment);
return (
<div className="comment">
<span className="comment-author">{data.userName}</span>
<div className="comment-text">
{emojifiedComment}
</div>
</div>
);
}
}
CommentComponent.propTypes = {
data: PropTypes.object.isRequired
};
CommentComponent.defaultProps = {
data: {}
};
export default CommentComponent;
|
assets/javascripts/kitten/components/structure/carousels/nav-tab-carousel/components/next.js | KissKissBankBank/kitten | import React from 'react'
import {
StyledRightArrowContainer,
StyledNextText,
StyledArrowIcon,
} from './styled-components'
export const Next = ({ children, hoverColor }) => {
return (
<StyledRightArrowContainer
hoverColor={hoverColor}
as="button"
className="k-u-reset-button"
>
<StyledNextText>{children}</StyledNextText>
<StyledArrowIcon fill="#fff" />
</StyledRightArrowContainer>
)
}
|
src/svg-icons/action/system-update-alt.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSystemUpdateAlt = (props) => (
<SvgIcon {...props}>
<path d="M12 16.5l4-4h-3v-9h-2v9H8l4 4zm9-13h-6v1.99h6v14.03H3V5.49h6V3.5H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-14c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
ActionSystemUpdateAlt = pure(ActionSystemUpdateAlt);
ActionSystemUpdateAlt.displayName = 'ActionSystemUpdateAlt';
ActionSystemUpdateAlt.muiName = 'SvgIcon';
export default ActionSystemUpdateAlt;
|
src/components/settlement/SettlementAddress/SettlementAddressInfo.js | HuZai/react_settlement | /**
* Created by zhengHu on 16-10-8.
* 图片list处理
*/
import React from 'react';
class SettlementAddressInfo extends React.Component {
render() {
let classArray=['cell','clell_border'],classes='',datas=this.props.data,title='收货人信息';
if(datas.onlyPickup){
classArray.push('ziti-section');
title='自提联系人';
}else{
classArray.push('address-section');
}
classes=classArray.join(' ');
return (
<a className={classes} href='javascript:;' onClick={()=>this.props.addressUpdate(datas)}>
<div>
<div className='bold'>{title}</div>
<div className='info'>
<div className='user-info'>{datas.name} {datas.phone}</div>
<div className={datas.onlyPickup?'user-address hide':'user-address'}>{datas.address}</div>
</div>
</div>
<span className='secoo_icon_next in_pl'></span>
</a>
);
}
}
SettlementAddressInfo.defaultProps = {
};
export default SettlementAddressInfo;
|
app/modules/header/style.js | donofkarma/react-starter | // import React from 'react';
import styled from 'styled-components';
import clearfix from 'styles/utilities/clearfix';
import { colors } from 'styles/tokens/color';
export const SiteHeader = styled.header`
${ clearfix }
padding: 10px;
background: ${ colors.grey.light };
`;
|
actor-apps/app-web/src/app/components/activity/ActivityHeader.react.js | hejunbinlan/actor-platform | import React from 'react';
import ReactMixin from 'react-mixin';
import addons from 'react/addons';
const {addons: { PureRenderMixin }} = addons;
@ReactMixin.decorate(PureRenderMixin)
class ActivityHeader extends React.Component {
static propTypes = {
close: React.PropTypes.func,
title: React.PropTypes.string
};
constructor(props) {
super(props);
}
render() {
const title = this.props.title;
const close = this.props.close;
let headerTitle;
if (typeof title !== 'undefined') {
headerTitle = <span className="activity__header__title">{title}</span>;
}
return (
<header className="activity__header toolbar">
<a className="activity__header__close material-icons" onClick={close}>clear</a>
{headerTitle}
</header>
);
}
}
export default ActivityHeader;
|
src/components/ListItem.js | merrettr/school-ui | import React from 'react';
import Panel from 'react-bootstrap/lib/Panel';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
const ListItem = ({ children, icon, style, onClick }) =>
<Panel
onClick={onClick}
style={{
padding: '1em',
marginBottom: 0,
cursor: 'pointer',
...style,
}}
>
<div style={{ display: 'flex' }}>
<div style={{ width: '100%' }} >{children}</div>
{ icon || <Glyphicon glyph="menu-right" /> }
</div>
</Panel>;
export default ListItem; |
src/example/WithDeprecationWarningExample.js | klarna/higher-order-components | import React from 'react'
import { withDeprecationWarning } from '../'
export default withDeprecationWarning({
readMore: 'http://example.com/why-old-component-is-deprecated',
useInstead: 'Underlined',
name: 'DeprecatedComponent',
})(function DeprecatedComponent() {
return (
<article>
<h1>withDeprecationWarning</h1>
<code>
<pre
style={{
color: 'lightgreen',
backgroundColor: 'black',
padding: 10,
overflowX: 'scroll',
}}
>{`import React from 'react'
import { withDeprecationWarning } from '@klarna/higher-order-components'
export default withDeprecationWarning({
readMore: 'http://example.com/why-old-component-is-deprecated',
useInstead: 'Underlined',
name: 'DeprecatedComponent',
})(function DeprecatedComponent() {
return (
<article>
<h1>withDeprecationWarning</h1>
<p>This one will log a deprecation warning in the console</p>
</article>
)
})`}</pre>
</code>
<p>This one will log a deprecation warning in the console</p>
</article>
)
})
|
packages/vulcan-i18n/lib/modules/provider.js | VulcanJS/Vulcan | import React, { Component } from 'react';
import { getString } from 'meteor/vulcan:lib';
import { intlShape } from './shape.js';
export default class IntlProvider extends Component {
formatMessage = ({ id, defaultMessage }, values = null) => {
const { messages, locale } = this.props;
return getString({ id, defaultMessage, values, messages, locale });
};
formatStuff = something => {
return something;
};
getChildContext() {
return {
intl: {
formatDate: this.formatStuff,
formatTime: this.formatStuff,
formatRelative: this.formatStuff,
formatNumber: this.formatStuff,
formatPlural: this.formatStuff,
formatMessage: this.formatMessage,
formatHTMLMessage: this.formatStuff,
now: this.formatStuff,
locale: this.props.locale,
},
};
}
render() {
return this.props.children;
}
}
IntlProvider.childContextTypes = {
intl: intlShape,
};
|
src/svg-icons/action/lock.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLock = (props) => (
<SvgIcon {...props}>
<path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/>
</SvgIcon>
);
ActionLock = pure(ActionLock);
ActionLock.displayName = 'ActionLock';
ActionLock.muiName = 'SvgIcon';
export default ActionLock;
|
packages/wix-style-react/src/Loader/docs/index.story.js | wix/wix-style-react | import { Category } from '../../../stories/storiesHierarchy';
import Loader from '..';
import {
api,
example,
description,
divider,
header,
importExample,
playground,
tab,
tabs,
testkit,
title,
} from 'wix-storybook-utils/dist/src/Sections';
import React from 'react';
import * as examples from './examples';
export default {
category: Category.COMPONENTS,
storyName: 'Loader',
component: Loader,
componentPath: '..',
componentProps: {
status: 'loading',
statusMessage: 'some message here',
text: '',
size: 'medium',
color: 'blue',
},
sections: [
header({
component: (
<div style={{ width: '50%' }}>
<Loader />
</div>
),
}),
tabs([
tab({
title: 'Description',
sections: [
description(`Provides a spinner to be used for async operations.`),
importExample("import { Loader } from 'wix-style-react';"),
divider(),
title('Examples'),
example({
title: 'Size',
text:
'There are four possible sizes : `tiny`, `small`, `medium` (default) and `large`',
source: examples.sizes,
}),
example({
title: 'Status',
text:
'There are four statuses types: `loading` (default), `success` and `error`',
source: examples.status,
}),
],
}),
...[
{ title: 'API', sections: [api()] },
{ title: 'Testkit', sections: [testkit()] },
{ title: 'Playground', sections: [playground()] },
].map(tab),
]),
],
};
|
admin/client/components/Popout.js | stunjiturner/keystone | import classnames from 'classnames';
import React from 'react';
import { Button, Checkbox, InputGroup, SegmentedControl } from 'elemental';
import Portal from './Portal';
import Transition from 'react-addons-css-transition-group';
const sizes = {
arrowHeight: 12
};
var Popout = React.createClass({
displayName: 'Popout',
propTypes: {
isOpen: React.PropTypes.bool,
onCancel: React.PropTypes.func,
onSubmit: React.PropTypes.func,
relativeToID: React.PropTypes.string.isRequired,
width: React.PropTypes.number,
},
getInitialState () {
return {};
},
getDefaultProps () {
return {
width: 320,
};
},
componentDidMount () {
if (this.props.isOpen) this.calculatePosition();
},
componentWillReceiveProps (nextProps) {
if (!this.props.isOpen && nextProps.isOpen) this.calculatePosition();
},
calculatePosition () {
let posNode = document.getElementById(this.props.relativeToID);
let pos = {
top: 0,
left: 0,
width: posNode.offsetWidth,
height: posNode.offsetHeight
};
while (posNode.offsetParent) {
pos.top += posNode.offsetTop;
pos.left += posNode.offsetLeft;
posNode = posNode.offsetParent;
}
let leftOffset = pos.left + (pos.width / 2) - (this.props.width / 2);
let topOffset = pos.top + pos.height + sizes.arrowHeight;
this.setState({
leftOffset: leftOffset,
topOffset: topOffset
});
},
renderPopout () {
if (!this.props.isOpen) return;
return (
<div className="Popout" style={{ left: this.state.leftOffset, top: this.state.topOffset, width: this.props.width }}>
<span className="Popout__arrow" />
<div className="Popout__inner">
{this.props.children}
</div>
</div>
);
},
renderBlockout () {
if (!this.props.isOpen) return;
return <div className="blockout" onClick={this.props.onCancel} />;
},
render () {
return (
<Portal className="Popout-wrapper">
<Transition className="Popout-animation" transitionName="Popout" component="div">
{this.renderPopout()}
</Transition>
{this.renderBlockout()}
</Portal>
);
}
});
module.exports = Popout;
// expose the child to the top level export
module.exports.Header = require('./PopoutHeader');
module.exports.Body = require('./PopoutBody');
module.exports.Footer = require('./PopoutFooter');
module.exports.Pane = require('./PopoutPane');
|
packages/idyll-cli/test/basic-project/src/components/functional-component.js | idyll-lang/idyll | import React from 'react';
export default () => {
return <div>Let's put the fun back in functional!</div>;
};
|
code/schritte/redux/6-redux/src/main.js | st-he/react-workshop | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import GreetingController from './GreetingController';
import { rootReducer } from './reducers';
import {loadGreetings} from './actions';
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk))
);
// init
store.dispatch(loadGreetings);
const mountNode = document.getElementById('mount');
ReactDOM.render(
<Provider store={store}>
<GreetingController />
</Provider>,
mountNode
); |
frontend/src/app/home/components/HeroCard.js | migcruz/dota2analytics | import React from 'react';
import { Card, Image, Icon } from 'semantic-ui-react'
import {NavLink} from "react-router-dom";
const src = "http://cdn.dota2.com/apps/dota2/images/heroes/queenofpain_vert.jpg";
class HeroCard extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
}
render() {
const staticRoot = window.django.urls.staticRoot;
return (
<div className="HeroCard-card">
<Card color="blue" image={src} centered/>
</div>
);
}
}
export default HeroCard;
{/* https://www.reddit.com/r/DotA2/comments/27d6vl/dota_2_animated_hero_portraits/
<div className="HeroCard-card">
<Card color="blue" centered>
<div className="HeroCard-avatar">
<Image src="http://cdn.dota2.com/apps/dota2/images/heroes/queenofpain_vert.jpg" centered/>
</div>
<Card.Content>
<Card.Header>{this.props.name}</Card.Header>
<Card.Meta>Joined in 2016</Card.Meta>
<Card.Description>Daniel is a comedian living in Nashville.</Card.Description>
</Card.Content>
<Card.Content extra>
<a>
<Icon name='user' />
10 Friends
</a>
</Card.Content>
</Card>
</div>
*/} |
node_modules/eslint-config-airbnb/test/test-react-order.js | Jzucca/Car.ly | import test from 'tape';
import { CLIEngine } from 'eslint';
import eslintrc from '../';
import reactRules from '../rules/react';
const cli = new CLIEngine({
useEslintrc: false,
baseConfig: eslintrc,
// This rule fails when executing on text.
rules: { indent: 0 },
});
function lint(text) {
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext
const linter = cli.executeOnText(text);
return linter.results[0];
}
function wrapComponent(body) {
return `
import React from 'react';
export default class MyComponent extends React.Component {
${body}
}
`;
}
test('validate react prop order', t => {
t.test('make sure our eslintrc has React and JSX linting dependencies', t => {
t.plan(1);
t.deepEqual(reactRules.plugins, ['jsx-a11y', 'react']);
});
t.test('passes a good component', t => {
t.plan(3);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
someMethod() {}
renderDogs() {}
render() { return <div />; }
`));
t.notOk(result.warningCount, 'no warnings');
t.notOk(result.errorCount, 'no errors');
t.deepEquals(result.messages, [], 'no messages in results');
});
t.test('order: when random method is first', t => {
t.plan(2);
const result = lint(wrapComponent(`
someMethod() {}
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
t.test('order: when random method after lifecycle methods', t => {
t.plan(2);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
someMethod() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
});
|
src/svg-icons/editor/space-bar.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorSpaceBar = (props) => (
<SvgIcon {...props}>
<path d="M18 9v4H6V9H4v6h16V9z"/>
</SvgIcon>
);
EditorSpaceBar = pure(EditorSpaceBar);
EditorSpaceBar.displayName = 'EditorSpaceBar';
export default EditorSpaceBar;
|
src/containers/Asians/BreaksCalculator/RoomTypes/returnRoundColumn.js | westoncolemanl/tabbr-web | import React from 'react'
import { TableCell } from 'material-ui/Table'
export default (rounds, type) =>
rounds.map((round, roundIndex) =>
<TableCell
key={roundIndex}
children={round[type]}
style={{
textAlign: 'center'
}}
/>
)
|
src/react-cropper.js | TAPP-TV/react-cropperjs | import React from 'react';
import Cropper from 'cropperjs';
import 'cropperjs';
import 'cropperjs/dist/cropper.css';
const CropperJS = React.createClass({
propTypes: {
// react cropper options
crossOrigin: React.PropTypes.string,
src: React.PropTypes.string,
alt: React.PropTypes.string,
style: React.PropTypes.object,
// cropper options
aspectRatio: React.PropTypes.number,
crop: React.PropTypes.func,
preview: React.PropTypes.string,
strict: React.PropTypes.bool,
responsive: React.PropTypes.bool,
checkImageOrigin: React.PropTypes.bool,
background: React.PropTypes.bool,
modal: React.PropTypes.bool,
guides: React.PropTypes.bool,
highlight: React.PropTypes.bool,
autoCrop: React.PropTypes.bool,
autoCropArea: React.PropTypes.number,
dragCrop: React.PropTypes.bool,
movable: React.PropTypes.bool,
cropBoxMovable: React.PropTypes.bool,
cropBoxResizable: React.PropTypes.bool,
doubleClickToggle: React.PropTypes.bool,
zoomable: React.PropTypes.bool,
mouseWheelZoom: React.PropTypes.bool,
touchDragZoom: React.PropTypes.bool,
rotatable: React.PropTypes.bool,
minContainerWidth: React.PropTypes.number,
minContainerHeight: React.PropTypes.number,
minCanvasWidth: React.PropTypes.number,
minCanvasHeight: React.PropTypes.number,
minCropBoxWidth: React.PropTypes.number,
minCropBoxHeight: React.PropTypes.number,
// cropper callbacks
build: React.PropTypes.func,
built: React.PropTypes.func,
cropstart: React.PropTypes.func,
cropmove: React.PropTypes.func,
cropend: React.PropTypes.func,
zoom: React.PropTypes.func
},
getDefaultProps() {
return {
src: null
};
},
componentDidMount() {
var options = {};
for (var prop in this.props) {
if (prop !== 'src' && prop !== 'alt' && prop !== 'crossOrigin') {
options[prop] = this.props[prop];
}
}
this.cropper = new Cropper(this.refs.img, options);
},
componentWillReceiveProps(nextProps) {
if (nextProps.src !== this.props.src) {
this.replace(nextProps.src);
}
if (nextProps.aspectRatio !== this.props.aspectRatio) {
this.setAspectRatio(nextProps.aspectRatio);
}
},
componentWillUnmount() {
if (this.cropper) {
// Destroy the cropper, this makes sure events such as resize are cleaned up and do not leak
this.cropper.destroy();
// While we're at it remove our reference to the jQuery instance
// delete this.$img;
}
},
move(offsetX, offsetY) {
return this.cropper.move(offsetX, offsetY);
},
zoom(ratio) {
return this.cropper.zoom(ratio);
},
rotate(degree) {
return this.cropper.rotate(degree);
},
enable() {
return this.cropper.enable();
},
disable() {
return this.cropper.disable();
},
reset() {
return this.cropper.reset();
},
clear() {
return this.cropper.clear();
},
replace(url) {
return this.cropper.replace(url);
},
getData(rounded) {
return this.cropper.getData(rounded);
},
setData(data) {
return this.cropper.setData(data);
},
getContainerData() {
return this.cropper.getContainerData();
},
getImageData() {
return this.cropper.getImageData();
},
getCanvasData() {
return this.cropper.getCanvasData();
},
setCanvasData(data) {
return this.cropper.setCanvasData(data);
},
getCropBoxData() {
return this.cropper.getCropBoxData();
},
setCropBoxData(data) {
return this.cropper.setCropBoxData(data);
},
getCroppedCanvas(options) {
return this.cropper.getCroppedCanvas(options);
},
setAspectRatio(aspectRatio) {
return this.cropper.setAspectRatio(aspectRatio);
},
setDragMode() {
return this.cropper.setDragMode();
},
render() {
const imgStyle = {
opacity: 0
};
return (
<div
style={this.props.style}
src={null}
crossOrigin={null}
alt={null}>
<img
crossOrigin={this.props.crossOrigin}
ref='img'
src={this.props.src}
alt={this.props.alt === undefined ? 'picture' : this.props.alt}
style={imgStyle} />
</div>
);
}
});
export default CropperJS;
|
fixtures/nesting/src/modern/HomePage.js | billfeller/react | import React from 'react';
import {useContext} from 'react';
import {Link} from 'react-router-dom';
import ThemeContext from './shared/ThemeContext';
import Clock from './shared/Clock';
export default function HomePage({counter, dispatch}) {
const theme = useContext(ThemeContext);
return (
<>
<h2>src/modern/HomePage.js</h2>
<h3 style={{color: theme}}>
This component is rendered by the outer React ({React.version}).
</h3>
<Clock />
<b>
<Link to="/about">Go to About</Link>
</b>
</>
);
}
|
examples/src/components/ValuesAsNumbersField.js | bezreyhan/react-select | import React from 'react';
import Select from 'react-select';
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
var ValuesAsNumbersField = React.createClass({
displayName: 'ValuesAsNumbersField',
propTypes: {
label: React.PropTypes.string
},
getInitialState () {
return {
options: [
{ value: 10, label: 'Ten' },
{ value: 11, label: 'Eleven' },
{ value: 12, label: 'Twelve' },
{ value: 23, label: 'Twenty-three' },
{ value: 24, label: 'Twenty-four' }
],
matchPos: 'any',
matchValue: true,
matchLabel: true,
value: null,
multi: false
};
},
onChangeMatchStart(event) {
this.setState({
matchPos: event.target.checked ? 'start' : 'any'
});
},
onChangeMatchValue(event) {
this.setState({
matchValue: event.target.checked
});
},
onChangeMatchLabel(event) {
this.setState({
matchLabel: event.target.checked
});
},
onChange(value, values) {
this.setState({
value: value
});
logChange(value, values);
},
onChangeMulti(event) {
this.setState({
multi: event.target.checked
});
},
render () {
var matchProp = 'any';
if (this.state.matchLabel && !this.state.matchValue) {
matchProp = 'label';
}
if (!this.state.matchLabel && this.state.matchValue) {
matchProp = 'value';
}
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select
searchable={true}
matchProp={matchProp}
matchPos={this.state.matchPos}
options={this.state.options}
onChange={this.onChange}
value={this.state.value}
multi={this.state.multi}
/>
<div className="checkbox-list">
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.multi} onChange={this.onChangeMulti} />
<span className="checkbox-label">Multi-Select</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchValue} onChange={this.onChangeMatchValue} />
<span className="checkbox-label">Match value only</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchLabel} onChange={this.onChangeMatchLabel} />
<span className="checkbox-label">Match label only</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchPos === 'start'} onChange={this.onChangeMatchStart} />
<span className="checkbox-label">Only include matches from the start of the string</span>
</label>
</div>
</div>
);
}
});
module.exports = ValuesAsNumbersField; |
project/react-ant/src/containers/FundChannelCfg/Add/index.js | FFF-team/generator-earth | import React from 'react'
import moment from 'moment'
import { DatePicker, Button, Form, Input, Col } from 'antd'
import BaseContainer from 'ROOT_SOURCE/base/BaseContainer'
import request from 'ROOT_SOURCE/utils/request'
import { mapMoment } from 'ROOT_SOURCE/utils/fieldFormatter'
import Rules from 'ROOT_SOURCE/utils/validateRules'
const FormItem = Form.Item
export default Form.create()(class extends BaseContainer {
/**
* 提交表单
*/
submitForm = (e) => {
e && e.preventDefault()
const { form } = this.props
form.validateFieldsAndScroll(async (err, values) => {
if (err) {
return;
}
// 提交表单最好新一个事务,不受其他事务影响
await this.sleep()
let _formData = { ...form.getFieldsValue() }
// _formData里的一些值需要适配
_formData = mapMoment(_formData, 'YYYY-MM-DD HH:mm:ss')
// action
await request.post('/asset/addAsset', _formData)
// 提交后返回list页
this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`)
})
}
render() {
let { form } = this.props
let { getFieldDecorator } = form
return (
<div className="ui-background">
<Form layout="inline" onSubmit={this.submitForm}>
<FormItem label="资产方名称">
{getFieldDecorator('assetName', {
rules: [{ required: true }]
})(<Input/>)}
</FormItem>
<FormItem label="签约主体">
{getFieldDecorator('contract', {
rules: [{ required: true }]
})(<Input/>)}
</FormItem>
<FormItem label="签约时间">
{getFieldDecorator('contractDate', {
rules: [{ type: 'object', required: true }]
})(<DatePicker showTime format='YYYY年MM月DD HH:mm:ss' style={{ width: '100%' }}/>)}
</FormItem>
<FormItem label="联系人">
{getFieldDecorator('contacts')(<Input/>)}
</FormItem>
<FormItem label="联系电话" hasFeedback>
{getFieldDecorator('contactsPhone', {
rules: [{ pattern: Rules.phone, message: '无效' }]
})(<Input maxLength="11"/>)}
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit"> 提交 </Button>
</FormItem>
<FormItem>
<Button type="primary" onClick={e => window.history.back()}> 取消/返回 </Button>
</FormItem>
</Form>
</div>
)
}
})
|
actor-apps/app-web/src/app/components/common/MessageItem.react.js | HKMOpen/actor-platform | import _ from 'lodash';
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import memoize from 'memoizee';
import classNames from 'classnames';
import emojify from 'emojify.js';
import hljs from 'highlight.js';
import marked from 'marked';
import emojiCharacters from 'emoji-named-characters';
import VisibilitySensor from 'react-visibility-sensor';
import AvatarItem from 'components/common/AvatarItem.react';
import Image from './Image.react';
import DialogActionCreators from 'actions/DialogActionCreators';
import { MessageContentTypes } from 'constants/ActorAppConstants';
let lastMessageSenderId = null,
lastMessageContentType = null;
var MessageItem = React.createClass({
displayName: 'MessageItem',
propTypes: {
message: React.PropTypes.object.isRequired,
newDay: React.PropTypes.bool,
index: React.PropTypes.number,
onVisibilityChange: React.PropTypes.func
},
mixins: [PureRenderMixin],
onClick() {
DialogActionCreators.selectDialogPeerUser(this.props.message.sender.peer.id);
},
onVisibilityChange(isVisible) {
this.props.onVisibilityChange(this.props.message, isVisible);
},
render() {
const message = this.props.message;
const newDay = this.props.newDay;
const isFirstMessage = this.props.index === 0;
let header,
visibilitySensor,
leftBlock;
let isSameSender = message.sender.peer.id === lastMessageSenderId &&
lastMessageContentType !== MessageContentTypes.SERVICE &&
message.content.content !== MessageContentTypes.SERVICE &&
!isFirstMessage &&
!newDay;
let messageClassName = classNames({
'message': true,
'row': true,
'message--same-sender': isSameSender
});
if (isSameSender) {
leftBlock = (
<div className="message__info text-right">
<time className="message__timestamp">{message.date}</time>
<MessageItem.State message={message}/>
</div>
);
} else {
leftBlock = (
<div className="message__info message__info--avatar">
<a onClick={this.onClick}>
<AvatarItem image={message.sender.avatar}
placeholder={message.sender.placeholder}
title={message.sender.title}/>
</a>
</div>
);
header = (
<header className="message__header">
<h3 className="message__sender">
<a onClick={this.onClick}>{message.sender.title}</a>
</h3>
<time className="message__timestamp">{message.date}</time>
<MessageItem.State message={message}/>
</header>
);
}
if (message.content.content === MessageContentTypes.SERVICE) {
leftBlock = null;
header = null;
}
if (this.props.onVisibilityChange) {
visibilitySensor = <VisibilitySensor onChange={this.onVisibilityChange}/>;
}
lastMessageSenderId = message.sender.peer.id;
lastMessageContentType = message.content.content;
return (
<li className={messageClassName}>
{leftBlock}
<div className="message__body col-xs">
{header}
<MessageItem.Content content={message.content}/>
{visibilitySensor}
</div>
</li>
);
}
});
emojify.setConfig({
mode: 'img',
img_dir: 'assets/img/emoji' // eslint-disable-line
});
const mdRenderer = new marked.Renderer();
// target _blank for links
mdRenderer.link = function(href, title, text) {
let external, newWindow, out;
external = /^https?:\/\/.+$/.test(href);
newWindow = external || title === 'newWindow';
out = '<a href=\"' + href + '\"';
if (newWindow) {
out += ' target="_blank"';
}
if (title && title !== 'newWindow') {
out += ' title=\"' + title + '\"';
}
return (out + '>' + text + '</a>');
};
const markedOptions = {
sanitize: true,
breaks: true,
highlight: function (code) {
return hljs.highlightAuto(code).value;
},
renderer: mdRenderer
};
const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character));
const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), function(name) {
return name.replace(/\+/g, '\\+');
});
const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi');
const processText = function(text) {
let markedText = marked(text, markedOptions);
// need hack with replace because of https://github.com/Ranks/emojify.js/issues/127
const noPTag = markedText.replace(/<p>/g, '<p> ');
let emojifiedText = emojify
.replace(noPTag.replace(emojiRegexp, (match) => ':' + inversedEmojiCharacters[match] + ':'));
return emojifiedText;
};
const memoizedProcessText = memoize(processText, {
length: 1000,
maxAge: 60 * 60 * 1000,
max: 10000
});
MessageItem.Content = React.createClass({
propTypes: {
content: React.PropTypes.object.isRequired
},
render() {
const content = this.props.content;
// TODO: move all types to subcomponents
let contentClassName = classNames('message__content', {
'message__content--service': content.content === MessageContentTypes.SERVICE,
'message__content--text': content.content === MessageContentTypes.TEXT,
'message__content--document': content.content === MessageContentTypes.DOCUMENT,
'message__content--unsupported': content.content === MessageContentTypes.UNSUPPORTED
});
switch (content.content) {
case 'service':
return (
<div className={contentClassName}>
{content.text}
</div>
);
case 'text':
return (
<div className={contentClassName}
dangerouslySetInnerHTML={{__html: memoizedProcessText(content.text)}}>
</div>
);
case 'photo':
return (
<Image content={content}
loadingClassName="message__content--photo"
loadedClassName="message__content--photo message__content--photo--loaded"/>
);
case 'document':
contentClassName = classNames(contentClassName, 'row');
let availableActions;
if (content.isUploading === true) {
availableActions = <span>Loading...</span>;
} else {
availableActions = <a href={content.fileUrl}>Open</a>;
}
return (
<div className={contentClassName}>
<div className="document row">
<div className="document__icon">
<i className="material-icons">attach_file</i>
</div>
<div className="col-xs">
<span className="document__filename">{content.fileName}</span>
<div className="document__meta">
<span className="document__meta__size">{content.fileSize}</span>
<span className="document__meta__ext">{content.fileExtension}</span>
</div>
<div className="document__actions">
{availableActions}
</div>
</div>
</div>
<div className="col-xs"></div>
</div>
);
default:
}
}
});
MessageItem.State = React.createClass({
propTypes: {
message: React.PropTypes.object.isRequired
},
render() {
const message = this.props.message;
if (message.content.content === MessageContentTypes.SERVICE) {
return null;
} else {
let icon = null;
switch(message.state) {
case 'pending':
icon = <i className="status status--penging material-icons">access_time</i>;
break;
case 'sent':
icon = <i className="status status--sent material-icons">done</i>;
break;
case 'received':
icon = <i className="status status--received material-icons">done_all</i>;
break;
case 'read':
icon = <i className="status status--read material-icons">done_all</i>;
break;
case 'error':
icon = <i className="status status--error material-icons">report_problem</i>;
break;
default:
}
return (
<div className="message__status">{icon}</div>
);
}
}
});
export default MessageItem;
|
src/svg-icons/notification/airline-seat-flat-angled.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationAirlineSeatFlatAngled = (props) => (
<SvgIcon {...props}>
<path d="M22.25 14.29l-.69 1.89L9.2 11.71l2.08-5.66 8.56 3.09c2.1.76 3.18 3.06 2.41 5.15zM1.5 12.14L8 14.48V19h8v-1.63L20.52 19l.69-1.89-19.02-6.86-.69 1.89zm5.8-1.94c1.49-.72 2.12-2.51 1.41-4C7.99 4.71 6.2 4.08 4.7 4.8c-1.49.71-2.12 2.5-1.4 4 .71 1.49 2.5 2.12 4 1.4z"/>
</SvgIcon>
);
NotificationAirlineSeatFlatAngled = pure(NotificationAirlineSeatFlatAngled);
NotificationAirlineSeatFlatAngled.displayName = 'NotificationAirlineSeatFlatAngled';
NotificationAirlineSeatFlatAngled.muiName = 'SvgIcon';
export default NotificationAirlineSeatFlatAngled;
|
src/bundle.js | palmg/pwfe-dom | /**
* Created by chkui on 2017/6/10.
*/
'use strict';
import React from 'react'
/**
* 页面分片高阶组件。该组件配合`routes`用于实现页面分片。
* @param initComponent
* @param getComponent
* @return {{new(...[*]): {async: (function(*=)), render: (function()), componentWillMount: (function())}}}
*/
const bundle = (initComponent, getComponent)=> {
return class extends React.Component {
constructor(...props) {
super(...props)
this.state = {
Comp: initComponent
}
this.async = this.async.bind(this)
}
async(Comp) {
this.setState({
Comp: Comp
})
}
componentDidMount() {
console.log('Mount');
0 !== window.scrollY && window.scrollTo(0, 0)
}
componentWillMount() {
!this.state.Comp && getComponent(this.async)
}
render() {
let {Comp} = this.state;
Comp && Comp.default &&
(Comp = Comp.default) &&
//增加注解说明需要将export default {} 替换为 module.exports = {}
(console.error("In current version 'require.ensure' has an issue that can't support es6 'export default {}' syntax. " +
"Now replace Comp=Comp.default with force, but it could lead to other problems." +
"If using 'require.ensure' to export a module, 'module.export = object' expression is appropriate."))
return Comp ? (<Comp {...this.props}/>) : null;
}
}
}
module.exports = bundle
module.exports.default = module.exports |
_course_exercises/rfe/_bck/src/Repo.js | David-Castelli/react-testing | import React from 'react';
import {render} from 'react-dom';
const Repo = ({repo, item}) =>
<article>
<h3>
{repo.name}
</h3>
<p>
{repo.description}
</p>
{item}
</article>
export default Repo; |
docs/app/Examples/collections/Menu/index.js | jcarbo/stardust | import React from 'react'
import Content from './Content'
import Types from './Types'
import States from './States'
import Variations from './Variations'
const MenuExamples = () => {
return (
<div>
<Types />
<Content />
<States />
<Variations />
</div>
)
}
export default MenuExamples
|
src/components/Loading.js | MMMalik/react-show-app | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Error from './Error';
import ContentBox from './ContentBox';
export default class Loading extends Component {
static propTypes = {
children: PropTypes.oneOfType(
[
PropTypes.element,
PropTypes.arrayOf(PropTypes.element)
]
),
loading: PropTypes.bool,
err: PropTypes.string
}
render() {
const { loading, children, err } = this.props;
return (
<div className={loading ? 'loading' : ''}>
{
err ? (
<ContentBox>
<Error status={err} />
</ContentBox>
) : children
}
</div>
);
}
}
|
tic-tac-toe/src/index.js | matija94/show-me-the-code | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
)
}
class Board extends React.Component {
renderSquare(i) {
return <Square
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
/>;
}
render() {
return (
<div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [{
squares: Array(9).fill(null),
}],
stepNumber: 0,
xIsNext: true,
};
}
handleClick(i) {
const history = this.state.history.slice(0, this.state.stepNumber+1);
const current = history[this.state.stepNumber];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat([{
squares: squares,
}]),
stepNumber: history.length,
xIsNext: !this.state.xIsNext,
});
}
jumpTo(step) {
this.setState({
stepNumber: step,
xIsNext: (step % 2) == 0,
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = calculateWinner(current.squares);
const moves = history.map((step, move) => {
const desc = move ?
"Go to move #" + move :
"Go to game start";
return (
<li key={move}>
<button onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
)
});
let status;
if (winner) {
status = 'Winner: ' + winner;
}
else {
status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
}
return (
<div className="game">
<div className="game-board">
<Board
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
}
}
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
|
src/components/Home.js | RicardoG2016/WRFD-project-site | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import '../App.css';
import Partners from './Partners';
import Purpose from './Purpose';
import Subscribe from './Subscribe';
import Video from './Video';
class Home extends Component {
componentDidMount(){
window.scrollTo(0, 0)
}
render() {
return (
<div id="home">
<div className="Homepage">
<div className="HomeContent">
<h1>World Rainforest Day</h1>
<hr />
<h3>June 22 2017</h3>
<br/>
<h4>Because the World Can't Wait</h4>
</div>
<br/>
<br/>
<br/>
<div className="btn-section">
<Link to="/worldrainforestday"><button className="HomeButton one" ><span>Learn More</span></button></Link>
<Link to="/act"><button className="HomeButton one" ><span>Take Action</span></button></Link>
<Link to="/donate"><button className="HomeButton third" ><span>Donate</span></button></Link>
</div>
</div>
<div>
<Purpose />
<hr/>
<br/>
<Partners />
<br/>
<Subscribe />
</div>
</div>
);
}
}
export default Home;
|
src/LocPresentational.js | derzunov/redux-react-i18n | import translate from 'translatr'
import React from 'react'
const Loc = ( { currentLanguage, locKey, number, dictionary, dispatch, ...rest } ) => {
return <span { ...rest }>
{ translate( dictionary, currentLanguage, locKey, number ) }
</span>
}
export default Loc
|
src/components/Navbar.js | hunterclarke/hunterclarke.me | import React from 'react'
import { Link } from 'gatsby'
const Navbar = class extends React.Component {
componentDidMount() {
// Get all "navbar-burger" elements
const $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0);
// Check if there are any navbar burgers
if ($navbarBurgers.length > 0) {
// Add a click event on each of them
$navbarBurgers.forEach( el => {
el.addEventListener('click', () => {
// Get the target from the "data-target" attribute
const target = el.dataset.target;
const $target = document.getElementById(target);
// Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
el.classList.toggle('is-active');
$target.classList.toggle('is-active');
});
});
}
}
render() {
return (
<nav className="navbar is-transparent" role="navigation" aria-label="main-navigation">
<div className="container">
<div className="navbar-brand">
<a className="navbar-item" href="/">
<h1>Hunter Clarke</h1>
</a>
{/* Hamburger menu */}
<div className="navbar-burger burger" data-target="navMenu">
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</div>
</div>
<div id="navMenu" className="navbar-menu">
<div className="navbar-start has-text-centered">
<Link className="navbar-item" to="/">
Home
</Link>
<Link className="navbar-item" to="/about">
About
</Link>
<Link className="navbar-item" to="/projects">
Projects
</Link>
</div>
</div>
</div>
</nav>
)}
}
export default Navbar
|
docs/src/NavMain.js | erictherobot/react-bootstrap | import React from 'react';
import { Link } from 'react-router';
import Navbar from '../../src/Navbar';
import Nav from '../../src/Nav';
const NAV_LINKS = {
'introduction': {
link: 'introduction',
title: 'Introduction'
},
'getting-started': {
link: 'getting-started',
title: 'Getting started'
},
'components': {
link: 'components',
title: 'Components'
},
'support': {
link: 'support',
title: 'Support'
}
};
const NavMain = React.createClass({
propTypes: {
activePage: React.PropTypes.string
},
render() {
let brand = <Link to="home" className="navbar-brand">React-Bootstrap</Link>;
let links = Object.keys(NAV_LINKS).map(this.renderNavItem).concat([
<li key="github-link">
<a href="https://github.com/react-bootstrap/react-bootstrap" target="_blank">GitHub</a>
</li>
]);
return (
<Navbar componentClass="header" brand={brand} staticTop className="bs-docs-nav" role="banner" toggleNavKey={0}>
<Nav className="bs-navbar-collapse" role="navigation" eventKey={0} id="top">
{links}
</Nav>
</Navbar>
);
},
renderNavItem(linkName) {
let link = NAV_LINKS[linkName];
return (
<li className={this.props.activePage === linkName ? 'active' : null} key={linkName}>
<Link to={link.link}>{link.title}</Link>
</li>
);
}
});
export default NavMain;
|
source/demo/NavLink.js | Vitamen/geneviz | /** @flow */
import React from 'react'
import { Link } from 'react-router'
import Icon from './Icon'
import styles from './NavLink.css'
export default function NavLink ({ children, href, iconType, to }) {
let link
let icon
if (iconType) {
icon = (
<Icon
className={styles.Icon}
type={iconType}
/>
)
}
if (to) {
link = (
<Link
activeClassName={styles.ActiveNavLink}
className={styles.NavLink}
to={to}
>
{icon} {children}
</Link>
)
} else {
link = (
<a
className={styles.NavLink}
href={href}
>
{icon} {children}
</a>
)
}
return (
<li className={styles.NavListItem}>
{link}
</li>
)
}
|
mobile/App.js | weirdsoft/coopcon | import './patches/moment-locale-patch'
import React from 'react'
import { configureStore } from './data/store'
import Bootstrap from './Bootstrap'
const store = configureStore()
const App = () => (
<Bootstrap store={store} />
)
export default App
|
app/components/SecondaryNavComponent/index.js | openexp/OpenEXP | import React, { Component } from 'react';
import { Grid, Header } from 'semantic-ui-react';
import styles from '../styles/secondarynav.css';
import SecondaryNavSegment from './SecondaryNavSegment';
interface Props {
title: string | React.ReactNode;
steps: { [string]: string };
activeStep: string;
onStepClick: string => void;
button?: React.ReactNode;
}
export default class SecondaryNavComponent extends Component<Props> {
shouldComponentUpdate(nextProps) {
return nextProps.activeStep !== this.props.activeStep;
}
renderTitle() {
if (typeof this.props.title === 'string') {
return <Header as="h2">{this.props.title}</Header>;
}
return this.props.title;
}
renderSteps() {
return (
<React.Fragment>
{Object.values(this.props.steps).map(stepTitle => (
<SecondaryNavSegment
key={stepTitle}
title={stepTitle}
style={
this.props.activeStep === stepTitle
? styles.activeSecondaryNavSegment
: styles.inactiveSecondaryNavSegment
}
onClick={() => this.props.onStepClick(stepTitle)}
/>
))}
{this.props.button ? (
<Grid.Column width="5" floated="right" textAlign="right">
{this.props.button}
</Grid.Column>
) : null}
</React.Fragment>
);
}
render() {
return (
<Grid verticalAlign="middle" className={styles.secondaryNavContainer}>
<Grid.Column width={3}>{this.renderTitle()}</Grid.Column>
{this.renderSteps()}
</Grid>
);
}
}
|
src/svg-icons/action/accessible.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAccessible = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="4" r="2"/><path d="M19 13v-2c-1.54.02-3.09-.75-4.07-1.83l-1.29-1.43c-.17-.19-.38-.34-.61-.45-.01 0-.01-.01-.02-.01H13c-.35-.2-.75-.3-1.19-.26C10.76 7.11 10 8.04 10 9.09V15c0 1.1.9 2 2 2h5v5h2v-5.5c0-1.1-.9-2-2-2h-3v-3.45c1.29 1.07 3.25 1.94 5 1.95zm-6.17 5c-.41 1.16-1.52 2-2.83 2-1.66 0-3-1.34-3-3 0-1.31.84-2.41 2-2.83V12.1c-2.28.46-4 2.48-4 4.9 0 2.76 2.24 5 5 5 2.42 0 4.44-1.72 4.9-4h-2.07z"/>
</SvgIcon>
);
ActionAccessible = pure(ActionAccessible);
ActionAccessible.displayName = 'ActionAccessible';
ActionAccessible.muiName = 'SvgIcon';
export default ActionAccessible;
|
server/server.js | bbviana/alexandria-mern | import Express from 'express';
import compression from 'compression';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import path from 'path';
// Webpack Requirements
import webpack from 'webpack';
import config from '../config/webpack/webpack.config.dev';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
// Initialize the Express App
const app = new Express();
// Run Webpack dev server in development mode
if (process.env.NODE_ENV === 'development') {
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
}
// React And Redux Setup
import { configureStore } from '../client/store';
import { Provider } from 'react-redux';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import Helmet from 'react-helmet';
import { fetchComponentData } from 'utils/fetchData';
// config
import serverConfig from './config';
// routes
import routes from '../client/routes';
import recipes from './routes/recipe.routes';
// Set native promises as mongoose promise
mongoose.Promise = global.Promise;
// MongoDB Connection
mongoose.connect(serverConfig.mongoURL, (error) => {
if (error) {
console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console
throw error;
}
});
// Apply body Parser and server public assets and routes
app.use(compression());
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use(Express.static(path.resolve(__dirname, '../dist')));
app.use('/api', recipes);
// Render Initial HTML
const renderFullPage = (html, initialState) => {
const head = Helmet.rewind();
// Import Manifests
const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets);
const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets);
return `
<!doctype html>
<html>
<head>
${head.base.toString()}
${head.title.toString()}
${head.meta.toString()}
${head.link.toString()}
${head.script.toString()}
${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''}
<link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/>
<link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" />
</head>
<body>
<div id="root">${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
${process.env.NODE_ENV === 'production' ?
`//<![CDATA[
window.webpackManifest = ${JSON.stringify(chunkManifest)};
//]]>` : ''}
</script>
<script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script>
<script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script>
</body>
</html>
`;
};
const renderError = err => {
const softTab = '    ';
const errTrace = process.env.NODE_ENV !== 'production' ?
`:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : '';
return renderFullPage(`Server Error${errTrace}`, {});
};
// Server Side Rendering based on routes matched by React-router.
app.use((req, res, next) => {
match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
if (err) {
return res.status(500).end(renderError(err));
}
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
if (!renderProps) {
return next();
}
const store = configureStore();
return fetchComponentData(store, renderProps.components, renderProps.params)
.then(() => {
const initialView = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
);
const finalState = store.getState();
res
.set('Content-Type', 'text/html')
.status(200)
.end(renderFullPage(initialView, finalState));
})
.catch((error) => next(error));
});
});
// start app
app.listen(serverConfig.port, (error) => {
if (!error) {
console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line
}
});
export default app;
|
node_modules/react-native-button/Button.js | RahulDesai92/PHR | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
TouchableOpacity,
View,
ViewPropTypes,
} from 'react-native';
import coalesceNonElementChildren from './coalesceNonElementChildren';
const systemButtonOpacity = 0.2;
export default class Button extends Component {
static propTypes = {
...TouchableOpacity.propTypes,
allowFontScaling: Text.propTypes.allowFontScaling,
containerStyle: ViewPropTypes.style,
disabled: PropTypes.bool,
style: Text.propTypes.style,
styleDisabled: Text.propTypes.style,
};
render() {
let touchableProps = {
activeOpacity: this._computeActiveOpacity(),
};
if (!this.props.disabled) {
touchableProps.onPress = this.props.onPress;
touchableProps.onPressIn = this.props.onPressIn;
touchableProps.onPressOut = this.props.onPressOut;
touchableProps.onLongPress = this.props.onLongPress;
touchableProps.delayPressIn = this.props.delayPressIn;
touchableProps.delayPressOut = this.props.delayPressOut;
touchableProps.delayLongPress = this.props.delayLongPress;
}
return (
<TouchableOpacity
{...touchableProps}
testID={this.props.testID}
style={this.props.containerStyle}
accessibilityTraits="button"
accessibilityComponentType="button">
{this._renderGroupedChildren()}
</TouchableOpacity>
);
}
_renderGroupedChildren() {
let { disabled } = this.props;
let style = [
styles.text,
disabled ? styles.disabledText : null,
this.props.style,
disabled ? this.props.styleDisabled : null,
];
let children = coalesceNonElementChildren(this.props.children, (children, index) => {
return (
<Text key={index} style={style} allowFontScaling={this.props.allowFontScaling}>
{children}
</Text>
);
});
switch (children.length) {
case 0:
return null;
case 1:
return children[0];
default:
return <View style={styles.group}>{children}</View>;
}
}
_computeActiveOpacity() {
if (this.props.disabled) {
return 1;
}
return this.props.activeOpacity != null ?
this.props.activeOpacity :
systemButtonOpacity;
}
};
const styles = StyleSheet.create({
text: {
color: '#007aff',
fontSize: 17,
fontWeight: '500',
textAlign: 'center',
},
disabledText: {
color: '#dcdcdc',
},
group: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
});
|
ajax/libs/react-select/1.0.0-rc.10/react-select.es.js | jonobr1/cdnjs | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import AutosizeInput from 'react-input-autosize';
import classNames from 'classnames';
function arrowRenderer(_ref) {
var onMouseDown = _ref.onMouseDown;
return React.createElement('span', {
className: 'Select-arrow',
onMouseDown: onMouseDown
});
}
arrowRenderer.propTypes = {
onMouseDown: PropTypes.func
};
var map = [{ 'base': 'A', 'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g }, { 'base': 'AA', 'letters': /[\uA732]/g }, { 'base': 'AE', 'letters': /[\u00C6\u01FC\u01E2]/g }, { 'base': 'AO', 'letters': /[\uA734]/g }, { 'base': 'AU', 'letters': /[\uA736]/g }, { 'base': 'AV', 'letters': /[\uA738\uA73A]/g }, { 'base': 'AY', 'letters': /[\uA73C]/g }, { 'base': 'B', 'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g }, { 'base': 'C', 'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g }, { 'base': 'D', 'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g }, { 'base': 'DZ', 'letters': /[\u01F1\u01C4]/g }, { 'base': 'Dz', 'letters': /[\u01F2\u01C5]/g }, { 'base': 'E', 'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g }, { 'base': 'F', 'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g }, { 'base': 'G', 'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g }, { 'base': 'H', 'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g }, { 'base': 'I', 'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g }, { 'base': 'J', 'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g }, { 'base': 'K', 'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g }, { 'base': 'L', 'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g }, { 'base': 'LJ', 'letters': /[\u01C7]/g }, { 'base': 'Lj', 'letters': /[\u01C8]/g }, { 'base': 'M', 'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g }, { 'base': 'N', 'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g }, { 'base': 'NJ', 'letters': /[\u01CA]/g }, { 'base': 'Nj', 'letters': /[\u01CB]/g }, { 'base': 'O', 'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g }, { 'base': 'OI', 'letters': /[\u01A2]/g }, { 'base': 'OO', 'letters': /[\uA74E]/g }, { 'base': 'OU', 'letters': /[\u0222]/g }, { 'base': 'P', 'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g }, { 'base': 'Q', 'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g }, { 'base': 'R', 'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g }, { 'base': 'S', 'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g }, { 'base': 'T', 'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g }, { 'base': 'TZ', 'letters': /[\uA728]/g }, { 'base': 'U', 'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g }, { 'base': 'V', 'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g }, { 'base': 'VY', 'letters': /[\uA760]/g }, { 'base': 'W', 'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g }, { 'base': 'X', 'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g }, { 'base': 'Y', 'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g }, { 'base': 'Z', 'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g }, { 'base': 'a', 'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g }, { 'base': 'aa', 'letters': /[\uA733]/g }, { 'base': 'ae', 'letters': /[\u00E6\u01FD\u01E3]/g }, { 'base': 'ao', 'letters': /[\uA735]/g }, { 'base': 'au', 'letters': /[\uA737]/g }, { 'base': 'av', 'letters': /[\uA739\uA73B]/g }, { 'base': 'ay', 'letters': /[\uA73D]/g }, { 'base': 'b', 'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g }, { 'base': 'c', 'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g }, { 'base': 'd', 'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g }, { 'base': 'dz', 'letters': /[\u01F3\u01C6]/g }, { 'base': 'e', 'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g }, { 'base': 'f', 'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g }, { 'base': 'g', 'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g }, { 'base': 'h', 'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g }, { 'base': 'hv', 'letters': /[\u0195]/g }, { 'base': 'i', 'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g }, { 'base': 'j', 'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g }, { 'base': 'k', 'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g }, { 'base': 'l', 'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g }, { 'base': 'lj', 'letters': /[\u01C9]/g }, { 'base': 'm', 'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g }, { 'base': 'n', 'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g }, { 'base': 'nj', 'letters': /[\u01CC]/g }, { 'base': 'o', 'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g }, { 'base': 'oi', 'letters': /[\u01A3]/g }, { 'base': 'ou', 'letters': /[\u0223]/g }, { 'base': 'oo', 'letters': /[\uA74F]/g }, { 'base': 'p', 'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g }, { 'base': 'q', 'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g }, { 'base': 'r', 'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g }, { 'base': 's', 'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g }, { 'base': 't', 'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g }, { 'base': 'tz', 'letters': /[\uA729]/g }, { 'base': 'u', 'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g }, { 'base': 'v', 'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g }, { 'base': 'vy', 'letters': /[\uA761]/g }, { 'base': 'w', 'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g }, { 'base': 'x', 'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g }, { 'base': 'y', 'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g }, { 'base': 'z', 'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g }];
function stripDiacritics(str) {
for (var i = 0; i < map.length; i++) {
str = str.replace(map[i].letters, map[i].base);
}
return str;
}
function filterOptions(options, filterValue, excludeOptions, props) {
var _this = this;
if (props.ignoreAccents) {
filterValue = stripDiacritics(filterValue);
}
if (props.ignoreCase) {
filterValue = filterValue.toLowerCase();
}
if (excludeOptions) excludeOptions = excludeOptions.map(function (i) {
return i[props.valueKey];
});
return options.filter(function (option) {
if (excludeOptions && excludeOptions.indexOf(option[props.valueKey]) > -1) return false;
if (props.filterOption) return props.filterOption.call(_this, option, filterValue);
if (!filterValue) return true;
var valueTest = String(option[props.valueKey]);
var labelTest = String(option[props.labelKey]);
if (props.ignoreAccents) {
if (props.matchProp !== 'label') valueTest = stripDiacritics(valueTest);
if (props.matchProp !== 'value') labelTest = stripDiacritics(labelTest);
}
if (props.ignoreCase) {
if (props.matchProp !== 'label') valueTest = valueTest.toLowerCase();
if (props.matchProp !== 'value') labelTest = labelTest.toLowerCase();
}
return props.matchPos === 'start' ? props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue || props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue : props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0 || props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0;
});
}
function menuRenderer(_ref) {
var focusedOption = _ref.focusedOption,
instancePrefix = _ref.instancePrefix,
labelKey = _ref.labelKey,
onFocus = _ref.onFocus,
onSelect = _ref.onSelect,
optionClassName = _ref.optionClassName,
optionComponent = _ref.optionComponent,
optionRenderer = _ref.optionRenderer,
options = _ref.options,
valueArray = _ref.valueArray,
valueKey = _ref.valueKey,
onOptionRef = _ref.onOptionRef;
var Option = optionComponent;
return options.map(function (option, i) {
var isSelected = valueArray && valueArray.indexOf(option) > -1;
var isFocused = option === focusedOption;
var optionClass = classNames(optionClassName, {
'Select-option': true,
'is-selected': isSelected,
'is-focused': isFocused,
'is-disabled': option.disabled
});
return React.createElement(
Option,
{
className: optionClass,
instancePrefix: instancePrefix,
isDisabled: option.disabled,
isFocused: isFocused,
isSelected: isSelected,
key: 'option-' + i + '-' + option[valueKey],
onFocus: onFocus,
onSelect: onSelect,
option: option,
optionIndex: i,
ref: function ref(_ref2) {
onOptionRef(_ref2, isFocused);
}
},
optionRenderer(option, i)
);
});
}
function clearRenderer() {
return React.createElement('span', {
className: 'Select-clear',
dangerouslySetInnerHTML: { __html: '×' }
});
}
var babelHelpers = {};
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
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 defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
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;
};
babelHelpers;
var Option = function (_React$Component) {
inherits(Option, _React$Component);
function Option(props) {
classCallCheck(this, Option);
var _this = possibleConstructorReturn(this, (Option.__proto__ || Object.getPrototypeOf(Option)).call(this, props));
_this.handleMouseDown = _this.handleMouseDown.bind(_this);
_this.handleMouseEnter = _this.handleMouseEnter.bind(_this);
_this.handleMouseMove = _this.handleMouseMove.bind(_this);
_this.handleTouchStart = _this.handleTouchStart.bind(_this);
_this.handleTouchEnd = _this.handleTouchEnd.bind(_this);
_this.handleTouchMove = _this.handleTouchMove.bind(_this);
_this.onFocus = _this.onFocus.bind(_this);
return _this;
}
createClass(Option, [{
key: 'blockEvent',
value: function blockEvent(event) {
event.preventDefault();
event.stopPropagation();
if (event.target.tagName !== 'A' || !('href' in event.target)) {
return;
}
if (event.target.target) {
window.open(event.target.href, event.target.target);
} else {
window.location.href = event.target.href;
}
}
}, {
key: 'handleMouseDown',
value: function handleMouseDown(event) {
event.preventDefault();
event.stopPropagation();
this.props.onSelect(this.props.option, event);
}
}, {
key: 'handleMouseEnter',
value: function handleMouseEnter(event) {
this.onFocus(event);
}
}, {
key: 'handleMouseMove',
value: function handleMouseMove(event) {
this.onFocus(event);
}
}, {
key: 'handleTouchEnd',
value: function handleTouchEnd(event) {
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if (this.dragging) return;
this.handleMouseDown(event);
}
}, {
key: 'handleTouchMove',
value: function handleTouchMove(event) {
// Set a flag that the view is being dragged
this.dragging = true;
}
}, {
key: 'handleTouchStart',
value: function handleTouchStart(event) {
// Set a flag that the view is not being dragged
this.dragging = false;
}
}, {
key: 'onFocus',
value: function onFocus(event) {
if (!this.props.isFocused) {
this.props.onFocus(this.props.option, event);
}
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
option = _props.option,
instancePrefix = _props.instancePrefix,
optionIndex = _props.optionIndex;
var className = classNames(this.props.className, option.className);
return option.disabled ? React.createElement(
'div',
{ className: className,
onMouseDown: this.blockEvent,
onClick: this.blockEvent },
this.props.children
) : React.createElement(
'div',
{ className: className,
style: option.style,
role: 'option',
onMouseDown: this.handleMouseDown,
onMouseEnter: this.handleMouseEnter,
onMouseMove: this.handleMouseMove,
onTouchStart: this.handleTouchStart,
onTouchMove: this.handleTouchMove,
onTouchEnd: this.handleTouchEnd,
id: instancePrefix + '-option-' + optionIndex,
title: option.title },
this.props.children
);
}
}]);
return Option;
}(React.Component);
Option.propTypes = {
children: PropTypes.node,
className: PropTypes.string, // className (based on mouse position)
instancePrefix: PropTypes.string.isRequired, // unique prefix for the ids (used for aria)
isDisabled: PropTypes.bool, // the option is disabled
isFocused: PropTypes.bool, // the option is focused
isSelected: PropTypes.bool, // the option is selected
onFocus: PropTypes.func, // method to handle mouseEnter on option element
onSelect: PropTypes.func, // method to handle click on option element
onUnfocus: PropTypes.func, // method to handle mouseLeave on option element
option: PropTypes.object.isRequired, // object that is base for that option
optionIndex: PropTypes.number // index of the option, used to generate unique ids for aria
};
var Value = function (_React$Component) {
inherits(Value, _React$Component);
function Value(props) {
classCallCheck(this, Value);
var _this = possibleConstructorReturn(this, (Value.__proto__ || Object.getPrototypeOf(Value)).call(this, props));
_this.handleMouseDown = _this.handleMouseDown.bind(_this);
_this.onRemove = _this.onRemove.bind(_this);
_this.handleTouchEndRemove = _this.handleTouchEndRemove.bind(_this);
_this.handleTouchMove = _this.handleTouchMove.bind(_this);
_this.handleTouchStart = _this.handleTouchStart.bind(_this);
return _this;
}
createClass(Value, [{
key: 'handleMouseDown',
value: function handleMouseDown(event) {
if (event.type === 'mousedown' && event.button !== 0) {
return;
}
if (this.props.onClick) {
event.stopPropagation();
this.props.onClick(this.props.value, event);
return;
}
if (this.props.value.href) {
event.stopPropagation();
}
}
}, {
key: 'onRemove',
value: function onRemove(event) {
event.preventDefault();
event.stopPropagation();
this.props.onRemove(this.props.value);
}
}, {
key: 'handleTouchEndRemove',
value: function handleTouchEndRemove(event) {
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if (this.dragging) return;
// Fire the mouse events
this.onRemove(event);
}
}, {
key: 'handleTouchMove',
value: function handleTouchMove(event) {
// Set a flag that the view is being dragged
this.dragging = true;
}
}, {
key: 'handleTouchStart',
value: function handleTouchStart(event) {
// Set a flag that the view is not being dragged
this.dragging = false;
}
}, {
key: 'renderRemoveIcon',
value: function renderRemoveIcon() {
if (this.props.disabled || !this.props.onRemove) return;
return React.createElement(
'span',
{ className: 'Select-value-icon',
'aria-hidden': 'true',
onMouseDown: this.onRemove,
onTouchEnd: this.handleTouchEndRemove,
onTouchStart: this.handleTouchStart,
onTouchMove: this.handleTouchMove },
'\xD7'
);
}
}, {
key: 'renderLabel',
value: function renderLabel() {
var className = 'Select-value-label';
return this.props.onClick || this.props.value.href ? React.createElement(
'a',
{ className: className, href: this.props.value.href, target: this.props.value.target, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleMouseDown },
this.props.children
) : React.createElement(
'span',
{ className: className, role: 'option', 'aria-selected': 'true', id: this.props.id },
this.props.children
);
}
}, {
key: 'render',
value: function render() {
return React.createElement(
'div',
{ className: classNames('Select-value', this.props.value.className),
style: this.props.value.style,
title: this.props.value.title
},
this.renderRemoveIcon(),
this.renderLabel()
);
}
}]);
return Value;
}(React.Component);
Value.propTypes = {
children: PropTypes.node,
disabled: PropTypes.bool, // disabled prop passed to ReactSelect
id: PropTypes.string, // Unique id for the value - used for aria
onClick: PropTypes.func, // method to handle click on value label
onRemove: PropTypes.func, // method to handle removal of the value
value: PropTypes.object.isRequired // the option object for this value
};
/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/react-select
*/
var stringifyValue = function stringifyValue(value) {
return typeof value === 'string' ? value : value !== null && JSON.stringify(value) || '';
};
var stringOrNode = PropTypes.oneOfType([PropTypes.string, PropTypes.node]);
var instanceId = 1;
var Select$1 = function (_React$Component) {
inherits(Select, _React$Component);
function Select(props) {
classCallCheck(this, Select);
var _this = possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props));
['clearValue', 'focusOption', 'handleInputBlur', 'handleInputChange', 'handleInputFocus', 'handleInputValueChange', 'handleKeyDown', 'handleMenuScroll', 'handleMouseDown', 'handleMouseDownOnArrow', 'handleMouseDownOnMenu', 'handleRequired', 'handleTouchOutside', 'handleTouchMove', 'handleTouchStart', 'handleTouchEnd', 'handleTouchEndClearValue', 'handleValueClick', 'getOptionLabel', 'onOptionRef', 'removeValue', 'selectValue'].forEach(function (fn) {
return _this[fn] = _this[fn].bind(_this);
});
_this.state = {
inputValue: '',
isFocused: false,
isOpen: false,
isPseudoFocused: false,
required: false
};
return _this;
}
createClass(Select, [{
key: 'componentWillMount',
value: function componentWillMount() {
this._instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId) + '-';
var valueArray = this.getValueArray(this.props.value);
if (this.props.required) {
this.setState({
required: this.handleRequired(valueArray[0], this.props.multi)
});
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
if (this.props.autofocus) {
this.focus();
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var valueArray = this.getValueArray(nextProps.value, nextProps);
if (nextProps.required) {
this.setState({
required: this.handleRequired(valueArray[0], nextProps.multi)
});
} else if (this.props.required) {
// Used to be required but it's not any more
this.setState({ required: false });
}
}
}, {
key: 'componentWillUpdate',
value: function componentWillUpdate(nextProps, nextState) {
if (nextState.isOpen !== this.state.isOpen) {
this.toggleTouchOutsideEvent(nextState.isOpen);
var handler = nextState.isOpen ? nextProps.onOpen : nextProps.onClose;
handler && handler();
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps, prevState) {
// focus to the selected option
if (this.menu && this.focused && this.state.isOpen && !this.hasScrolledToOption) {
var focusedOptionNode = ReactDOM.findDOMNode(this.focused);
var menuNode = ReactDOM.findDOMNode(this.menu);
menuNode.scrollTop = focusedOptionNode.offsetTop;
this.hasScrolledToOption = true;
} else if (!this.state.isOpen) {
this.hasScrolledToOption = false;
}
if (this._scrollToFocusedOptionOnUpdate && this.focused && this.menu) {
this._scrollToFocusedOptionOnUpdate = false;
var focusedDOM = ReactDOM.findDOMNode(this.focused);
var menuDOM = ReactDOM.findDOMNode(this.menu);
var focusedRect = focusedDOM.getBoundingClientRect();
var menuRect = menuDOM.getBoundingClientRect();
if (focusedRect.bottom > menuRect.bottom) {
menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight;
} else if (focusedRect.top < menuRect.top) {
menuDOM.scrollTop = focusedDOM.offsetTop;
}
}
if (this.props.scrollMenuIntoView && this.menuContainer) {
var menuContainerRect = this.menuContainer.getBoundingClientRect();
if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) {
window.scrollBy(0, menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight);
}
}
if (prevProps.disabled !== this.props.disabled) {
this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state
this.closeMenu();
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (!document.removeEventListener && document.detachEvent) {
document.detachEvent('ontouchstart', this.handleTouchOutside);
} else {
document.removeEventListener('touchstart', this.handleTouchOutside);
}
}
}, {
key: 'toggleTouchOutsideEvent',
value: function toggleTouchOutsideEvent(enabled) {
if (enabled) {
if (!document.addEventListener && document.attachEvent) {
document.attachEvent('ontouchstart', this.handleTouchOutside);
} else {
document.addEventListener('touchstart', this.handleTouchOutside);
}
} else {
if (!document.removeEventListener && document.detachEvent) {
document.detachEvent('ontouchstart', this.handleTouchOutside);
} else {
document.removeEventListener('touchstart', this.handleTouchOutside);
}
}
}
}, {
key: 'handleTouchOutside',
value: function handleTouchOutside(event) {
// handle touch outside on ios to dismiss menu
if (this.wrapper && !this.wrapper.contains(event.target)) {
this.closeMenu();
}
}
}, {
key: 'focus',
value: function focus() {
if (!this.input) return;
this.input.focus();
}
}, {
key: 'blurInput',
value: function blurInput() {
if (!this.input) return;
this.input.blur();
}
}, {
key: 'handleTouchMove',
value: function handleTouchMove(event) {
// Set a flag that the view is being dragged
this.dragging = true;
}
}, {
key: 'handleTouchStart',
value: function handleTouchStart(event) {
// Set a flag that the view is not being dragged
this.dragging = false;
}
}, {
key: 'handleTouchEnd',
value: function handleTouchEnd(event) {
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if (this.dragging) return;
// Fire the mouse events
this.handleMouseDown(event);
}
}, {
key: 'handleTouchEndClearValue',
value: function handleTouchEndClearValue(event) {
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if (this.dragging) return;
// Clear the value
this.clearValue(event);
}
}, {
key: 'handleMouseDown',
value: function handleMouseDown(event) {
// if the event was triggered by a mousedown and not the primary
// button, or if the component is disabled, ignore it.
if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
return;
}
if (event.target.tagName === 'INPUT') {
return;
}
// prevent default event handlers
event.stopPropagation();
event.preventDefault();
// for the non-searchable select, toggle the menu
if (!this.props.searchable) {
// TODO: This code means that if a select is searchable, onClick the options menu will not appear, only on subsequent click will it open.
this.focus();
return this.setState({
isOpen: !this.state.isOpen
});
}
if (this.state.isFocused) {
// On iOS, we can get into a state where we think the input is focused but it isn't really,
// since iOS ignores programmatic calls to input.focus() that weren't triggered by a click event.
// Call focus() again here to be safe.
this.focus();
var input = this.input;
if (typeof input.getInput === 'function') {
// Get the actual DOM input if the ref is an <AutosizeInput /> component
input = input.getInput();
}
// clears the value so that the cursor will be at the end of input when the component re-renders
input.value = '';
// if the input is focused, ensure the menu is open
this.setState({
isOpen: true,
isPseudoFocused: false
});
} else {
// otherwise, focus the input and open the menu
this._openAfterFocus = this.props.openOnClick;
this.focus();
}
}
}, {
key: 'handleMouseDownOnArrow',
value: function handleMouseDownOnArrow(event) {
// if the event was triggered by a mousedown and not the primary
// button, or if the component is disabled, ignore it.
if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
return;
}
// If the menu isn't open, let the event bubble to the main handleMouseDown
if (!this.state.isOpen) {
return;
}
// prevent default event handlers
event.stopPropagation();
event.preventDefault();
// close the menu
this.closeMenu();
}
}, {
key: 'handleMouseDownOnMenu',
value: function handleMouseDownOnMenu(event) {
// if the event was triggered by a mousedown and not the primary
// button, or if the component is disabled, ignore it.
if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
return;
}
event.stopPropagation();
event.preventDefault();
this._openAfterFocus = true;
this.focus();
}
}, {
key: 'closeMenu',
value: function closeMenu() {
if (this.props.onCloseResetsInput) {
this.setState({
isOpen: false,
isPseudoFocused: this.state.isFocused && !this.props.multi,
inputValue: this.handleInputValueChange('')
});
} else {
this.setState({
isOpen: false,
isPseudoFocused: this.state.isFocused && !this.props.multi
});
}
this.hasScrolledToOption = false;
}
}, {
key: 'handleInputFocus',
value: function handleInputFocus(event) {
if (this.props.disabled) return;
var isOpen = this.state.isOpen || this._openAfterFocus || this.props.openOnFocus;
if (this.props.onFocus) {
this.props.onFocus(event);
}
this.setState({
isFocused: true,
isOpen: isOpen
});
this._openAfterFocus = false;
}
}, {
key: 'handleInputBlur',
value: function handleInputBlur(event) {
// The check for menu.contains(activeElement) is necessary to prevent IE11's scrollbar from closing the menu in certain contexts.
if (this.menu && (this.menu === document.activeElement || this.menu.contains(document.activeElement))) {
this.focus();
return;
}
if (this.props.onBlur) {
this.props.onBlur(event);
}
var onBlurredState = {
isFocused: false,
isOpen: false,
isPseudoFocused: false
};
if (this.props.onBlurResetsInput) {
onBlurredState.inputValue = this.handleInputValueChange('');
}
this.setState(onBlurredState);
}
}, {
key: 'handleInputChange',
value: function handleInputChange(event) {
var newInputValue = event.target.value;
if (this.state.inputValue !== event.target.value) {
newInputValue = this.handleInputValueChange(newInputValue);
}
this.setState({
isOpen: true,
isPseudoFocused: false,
inputValue: newInputValue
});
}
}, {
key: 'handleInputValueChange',
value: function handleInputValueChange(newValue) {
if (this.props.onInputChange) {
var nextState = this.props.onInputChange(newValue);
// Note: != used deliberately here to catch undefined and null
if (nextState != null && (typeof nextState === 'undefined' ? 'undefined' : _typeof(nextState)) !== 'object') {
newValue = '' + nextState;
}
}
return newValue;
}
}, {
key: 'handleKeyDown',
value: function handleKeyDown(event) {
if (this.props.disabled) return;
if (typeof this.props.onInputKeyDown === 'function') {
this.props.onInputKeyDown(event);
if (event.defaultPrevented) {
return;
}
}
switch (event.keyCode) {
case 8:
// backspace
if (!this.state.inputValue && this.props.backspaceRemoves) {
event.preventDefault();
this.popValue();
}
return;
case 9:
// tab
if (event.shiftKey || !this.state.isOpen || !this.props.tabSelectsValue) {
return;
}
this.selectFocusedOption();
return;
case 13:
// enter
if (!this.state.isOpen) return;
event.stopPropagation();
this.selectFocusedOption();
break;
case 27:
// escape
if (this.state.isOpen) {
this.closeMenu();
event.stopPropagation();
} else if (this.props.clearable && this.props.escapeClearsValue) {
this.clearValue(event);
event.stopPropagation();
}
break;
case 38:
// up
this.focusPreviousOption();
break;
case 40:
// down
this.focusNextOption();
break;
case 33:
// page up
this.focusPageUpOption();
break;
case 34:
// page down
this.focusPageDownOption();
break;
case 35:
// end key
if (event.shiftKey) {
return;
}
this.focusEndOption();
break;
case 36:
// home key
if (event.shiftKey) {
return;
}
this.focusStartOption();
break;
case 46:
// backspace
if (!this.state.inputValue && this.props.deleteRemoves) {
event.preventDefault();
this.popValue();
}
return;
default:
return;
}
event.preventDefault();
}
}, {
key: 'handleValueClick',
value: function handleValueClick(option, event) {
if (!this.props.onValueClick) return;
this.props.onValueClick(option, event);
}
}, {
key: 'handleMenuScroll',
value: function handleMenuScroll(event) {
if (!this.props.onMenuScrollToBottom) return;
var target = event.target;
if (target.scrollHeight > target.offsetHeight && target.scrollHeight - target.offsetHeight - target.scrollTop <= 0) {
this.props.onMenuScrollToBottom();
}
}
}, {
key: 'handleRequired',
value: function handleRequired(value, multi) {
if (!value) return true;
return multi ? value.length === 0 : Object.keys(value).length === 0;
}
}, {
key: 'getOptionLabel',
value: function getOptionLabel(op) {
return op[this.props.labelKey];
}
/**
* Turns a value into an array from the given options
* @param {String|Number|Array} value - the value of the select input
* @param {Object} nextProps - optionally specify the nextProps so the returned array uses the latest configuration
* @returns {Array} the value of the select represented in an array
*/
}, {
key: 'getValueArray',
value: function getValueArray(value, nextProps) {
var _this2 = this;
/** support optionally passing in the `nextProps` so `componentWillReceiveProps` updates will function as expected */
var props = (typeof nextProps === 'undefined' ? 'undefined' : _typeof(nextProps)) === 'object' ? nextProps : this.props;
if (props.multi) {
if (typeof value === 'string') value = value.split(props.delimiter);
if (!Array.isArray(value)) {
if (value === null || value === undefined) return [];
value = [value];
}
return value.map(function (value) {
return _this2.expandValue(value, props);
}).filter(function (i) {
return i;
});
}
var expandedValue = this.expandValue(value, props);
return expandedValue ? [expandedValue] : [];
}
/**
* Retrieve a value from the given options and valueKey
* @param {String|Number|Array} value - the selected value(s)
* @param {Object} props - the Select component's props (or nextProps)
*/
}, {
key: 'expandValue',
value: function expandValue(value, props) {
var valueType = typeof value === 'undefined' ? 'undefined' : _typeof(value);
if (valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') return value;
var options = props.options,
valueKey = props.valueKey;
if (!options) return;
for (var i = 0; i < options.length; i++) {
if (options[i][valueKey] === value) return options[i];
}
}
}, {
key: 'setValue',
value: function setValue(value) {
var _this3 = this;
if (this.props.autoBlur) {
this.blurInput();
}
if (this.props.required) {
var required = this.handleRequired(value, this.props.multi);
this.setState({ required: required });
}
if (this.props.onChange) {
if (this.props.simpleValue && value) {
value = this.props.multi ? value.map(function (i) {
return i[_this3.props.valueKey];
}).join(this.props.delimiter) : value[this.props.valueKey];
}
this.props.onChange(value);
}
}
}, {
key: 'selectValue',
value: function selectValue(value) {
var _this4 = this;
// NOTE: we actually add/set the value in a callback to make sure the
// input value is empty to avoid styling issues in Chrome
if (this.props.closeOnSelect) {
this.hasScrolledToOption = false;
}
if (this.props.multi) {
var updatedValue = this.props.onSelectResetsInput ? '' : this.state.inputValue;
this.setState({
focusedIndex: null,
inputValue: this.handleInputValueChange(updatedValue),
isOpen: !this.props.closeOnSelect
}, function () {
_this4.addValue(value);
});
} else {
this.setState({
inputValue: this.handleInputValueChange(''),
isOpen: !this.props.closeOnSelect,
isPseudoFocused: this.state.isFocused
}, function () {
_this4.setValue(value);
});
}
}
}, {
key: 'addValue',
value: function addValue(value) {
var valueArray = this.getValueArray(this.props.value);
var visibleOptions = this._visibleOptions.filter(function (val) {
return !val.disabled;
});
var lastValueIndex = visibleOptions.indexOf(value);
this.setValue(valueArray.concat(value));
if (visibleOptions.length - 1 === lastValueIndex) {
// the last option was selected; focus the second-last one
this.focusOption(visibleOptions[lastValueIndex - 1]);
} else if (visibleOptions.length > lastValueIndex) {
// focus the option below the selected one
this.focusOption(visibleOptions[lastValueIndex + 1]);
}
}
}, {
key: 'popValue',
value: function popValue() {
var valueArray = this.getValueArray(this.props.value);
if (!valueArray.length) return;
if (valueArray[valueArray.length - 1].clearableValue === false) return;
this.setValue(this.props.multi ? valueArray.slice(0, valueArray.length - 1) : null);
}
}, {
key: 'removeValue',
value: function removeValue(value) {
var valueArray = this.getValueArray(this.props.value);
this.setValue(valueArray.filter(function (i) {
return i !== value;
}));
this.focus();
}
}, {
key: 'clearValue',
value: function clearValue(event) {
// if the event was triggered by a mousedown and not the primary
// button, ignore it.
if (event && event.type === 'mousedown' && event.button !== 0) {
return;
}
event.stopPropagation();
event.preventDefault();
this.setValue(this.getResetValue());
this.setState({
isOpen: false,
inputValue: this.handleInputValueChange('')
}, this.focus);
}
}, {
key: 'getResetValue',
value: function getResetValue() {
if (this.props.resetValue !== undefined) {
return this.props.resetValue;
} else if (this.props.multi) {
return [];
} else {
return null;
}
}
}, {
key: 'focusOption',
value: function focusOption(option) {
this.setState({
focusedOption: option
});
}
}, {
key: 'focusNextOption',
value: function focusNextOption() {
this.focusAdjacentOption('next');
}
}, {
key: 'focusPreviousOption',
value: function focusPreviousOption() {
this.focusAdjacentOption('previous');
}
}, {
key: 'focusPageUpOption',
value: function focusPageUpOption() {
this.focusAdjacentOption('page_up');
}
}, {
key: 'focusPageDownOption',
value: function focusPageDownOption() {
this.focusAdjacentOption('page_down');
}
}, {
key: 'focusStartOption',
value: function focusStartOption() {
this.focusAdjacentOption('start');
}
}, {
key: 'focusEndOption',
value: function focusEndOption() {
this.focusAdjacentOption('end');
}
}, {
key: 'focusAdjacentOption',
value: function focusAdjacentOption(dir) {
var options = this._visibleOptions.map(function (option, index) {
return { option: option, index: index };
}).filter(function (option) {
return !option.option.disabled;
});
this._scrollToFocusedOptionOnUpdate = true;
if (!this.state.isOpen) {
this.setState({
isOpen: true,
inputValue: '',
focusedOption: this._focusedOption || (options.length ? options[dir === 'next' ? 0 : options.length - 1].option : null)
});
return;
}
if (!options.length) return;
var focusedIndex = -1;
for (var i = 0; i < options.length; i++) {
if (this._focusedOption === options[i].option) {
focusedIndex = i;
break;
}
}
if (dir === 'next' && focusedIndex !== -1) {
focusedIndex = (focusedIndex + 1) % options.length;
} else if (dir === 'previous') {
if (focusedIndex > 0) {
focusedIndex = focusedIndex - 1;
} else {
focusedIndex = options.length - 1;
}
} else if (dir === 'start') {
focusedIndex = 0;
} else if (dir === 'end') {
focusedIndex = options.length - 1;
} else if (dir === 'page_up') {
var potentialIndex = focusedIndex - this.props.pageSize;
if (potentialIndex < 0) {
focusedIndex = 0;
} else {
focusedIndex = potentialIndex;
}
} else if (dir === 'page_down') {
var potentialIndex = focusedIndex + this.props.pageSize;
if (potentialIndex > options.length - 1) {
focusedIndex = options.length - 1;
} else {
focusedIndex = potentialIndex;
}
}
if (focusedIndex === -1) {
focusedIndex = 0;
}
this.setState({
focusedIndex: options[focusedIndex].index,
focusedOption: options[focusedIndex].option
});
}
}, {
key: 'getFocusedOption',
value: function getFocusedOption() {
return this._focusedOption;
}
}, {
key: 'getInputValue',
value: function getInputValue() {
return this.state.inputValue;
}
}, {
key: 'selectFocusedOption',
value: function selectFocusedOption() {
if (this._focusedOption) {
return this.selectValue(this._focusedOption);
}
}
}, {
key: 'renderLoading',
value: function renderLoading() {
if (!this.props.isLoading) return;
return React.createElement(
'span',
{ className: 'Select-loading-zone', 'aria-hidden': 'true' },
React.createElement('span', { className: 'Select-loading' })
);
}
}, {
key: 'renderValue',
value: function renderValue(valueArray, isOpen) {
var _this5 = this;
var renderLabel = this.props.valueRenderer || this.getOptionLabel;
var ValueComponent = this.props.valueComponent;
if (!valueArray.length) {
return !this.state.inputValue ? React.createElement(
'div',
{ className: 'Select-placeholder' },
this.props.placeholder
) : null;
}
var onClick = this.props.onValueClick ? this.handleValueClick : null;
if (this.props.multi) {
return valueArray.map(function (value, i) {
return React.createElement(
ValueComponent,
{
id: _this5._instancePrefix + '-value-' + i,
instancePrefix: _this5._instancePrefix,
disabled: _this5.props.disabled || value.clearableValue === false,
key: 'value-' + i + '-' + value[_this5.props.valueKey],
onClick: onClick,
onRemove: _this5.removeValue,
value: value
},
renderLabel(value, i),
React.createElement(
'span',
{ className: 'Select-aria-only' },
'\xA0'
)
);
});
} else if (!this.state.inputValue) {
if (isOpen) onClick = null;
return React.createElement(
ValueComponent,
{
id: this._instancePrefix + '-value-item',
disabled: this.props.disabled,
instancePrefix: this._instancePrefix,
onClick: onClick,
value: valueArray[0]
},
renderLabel(valueArray[0])
);
}
}
}, {
key: 'renderInput',
value: function renderInput(valueArray, focusedOptionIndex) {
var _classNames,
_this6 = this;
var className = classNames('Select-input', this.props.inputProps.className);
var isOpen = !!this.state.isOpen;
var ariaOwns = classNames((_classNames = {}, defineProperty(_classNames, this._instancePrefix + '-list', isOpen), defineProperty(_classNames, this._instancePrefix + '-backspace-remove-message', this.props.multi && !this.props.disabled && this.state.isFocused && !this.state.inputValue), _classNames));
var inputProps = _extends({}, this.props.inputProps, {
role: 'combobox',
'aria-expanded': '' + isOpen,
'aria-owns': ariaOwns,
'aria-haspopup': '' + isOpen,
'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value',
'aria-describedby': this.props['aria-describedby'],
'aria-labelledby': this.props['aria-labelledby'],
'aria-label': this.props['aria-label'],
className: className,
tabIndex: this.props.tabIndex,
onBlur: this.handleInputBlur,
onChange: this.handleInputChange,
onFocus: this.handleInputFocus,
ref: function ref(_ref) {
return _this6.input = _ref;
},
required: this.state.required,
value: this.state.inputValue
});
if (this.props.inputRenderer) {
return this.props.inputRenderer(inputProps);
}
if (this.props.disabled || !this.props.searchable) {
var _props$inputProps = this.props.inputProps,
inputClassName = _props$inputProps.inputClassName,
divProps = objectWithoutProperties(_props$inputProps, ['inputClassName']);
var _ariaOwns = classNames(defineProperty({}, this._instancePrefix + '-list', isOpen));
return React.createElement('div', _extends({}, divProps, {
role: 'combobox',
'aria-expanded': isOpen,
'aria-owns': _ariaOwns,
'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value',
className: className,
tabIndex: this.props.tabIndex || 0,
onBlur: this.handleInputBlur,
onFocus: this.handleInputFocus,
ref: function ref(_ref2) {
return _this6.input = _ref2;
},
'aria-readonly': '' + !!this.props.disabled,
style: { border: 0, width: 1, display: 'inline-block' } }));
}
if (this.props.autosize) {
return React.createElement(AutosizeInput, _extends({}, inputProps, { minWidth: '5' }));
}
return React.createElement(
'div',
{ className: className },
React.createElement('input', inputProps)
);
}
}, {
key: 'renderClear',
value: function renderClear() {
if (!this.props.clearable || this.props.value === undefined || this.props.value === null || this.props.multi && !this.props.value.length || this.props.disabled || this.props.isLoading) return;
var clear = this.props.clearRenderer();
return React.createElement(
'span',
{ className: 'Select-clear-zone', title: this.props.multi ? this.props.clearAllText : this.props.clearValueText,
'aria-label': this.props.multi ? this.props.clearAllText : this.props.clearValueText,
onMouseDown: this.clearValue,
onTouchStart: this.handleTouchStart,
onTouchMove: this.handleTouchMove,
onTouchEnd: this.handleTouchEndClearValue
},
clear
);
}
}, {
key: 'renderArrow',
value: function renderArrow() {
var onMouseDown = this.handleMouseDownOnArrow;
var isOpen = this.state.isOpen;
var arrow = this.props.arrowRenderer({ onMouseDown: onMouseDown, isOpen: isOpen });
return React.createElement(
'span',
{
className: 'Select-arrow-zone',
onMouseDown: onMouseDown
},
arrow
);
}
}, {
key: 'filterOptions',
value: function filterOptions$$1(excludeOptions) {
var filterValue = this.state.inputValue;
var options = this.props.options || [];
if (this.props.filterOptions) {
// Maintain backwards compatibility with boolean attribute
var filterOptions$$1 = typeof this.props.filterOptions === 'function' ? this.props.filterOptions : filterOptions;
return filterOptions$$1(options, filterValue, excludeOptions, {
filterOption: this.props.filterOption,
ignoreAccents: this.props.ignoreAccents,
ignoreCase: this.props.ignoreCase,
labelKey: this.props.labelKey,
matchPos: this.props.matchPos,
matchProp: this.props.matchProp,
valueKey: this.props.valueKey
});
} else {
return options;
}
}
}, {
key: 'onOptionRef',
value: function onOptionRef(ref, isFocused) {
if (isFocused) {
this.focused = ref;
}
}
}, {
key: 'renderMenu',
value: function renderMenu(options, valueArray, focusedOption) {
if (options && options.length) {
return this.props.menuRenderer({
focusedOption: focusedOption,
focusOption: this.focusOption,
instancePrefix: this._instancePrefix,
labelKey: this.props.labelKey,
onFocus: this.focusOption,
onSelect: this.selectValue,
optionClassName: this.props.optionClassName,
optionComponent: this.props.optionComponent,
optionRenderer: this.props.optionRenderer || this.getOptionLabel,
options: options,
selectValue: this.selectValue,
valueArray: valueArray,
valueKey: this.props.valueKey,
onOptionRef: this.onOptionRef
});
} else if (this.props.noResultsText) {
return React.createElement(
'div',
{ className: 'Select-noresults' },
this.props.noResultsText
);
} else {
return null;
}
}
}, {
key: 'renderHiddenField',
value: function renderHiddenField(valueArray) {
var _this7 = this;
if (!this.props.name) return;
if (this.props.joinValues) {
var value = valueArray.map(function (i) {
return stringifyValue(i[_this7.props.valueKey]);
}).join(this.props.delimiter);
return React.createElement('input', {
type: 'hidden',
ref: function ref(_ref3) {
return _this7.value = _ref3;
},
name: this.props.name,
value: value,
disabled: this.props.disabled });
}
return valueArray.map(function (item, index) {
return React.createElement('input', { key: 'hidden.' + index,
type: 'hidden',
ref: 'value' + index,
name: _this7.props.name,
value: stringifyValue(item[_this7.props.valueKey]),
disabled: _this7.props.disabled });
});
}
}, {
key: 'getFocusableOptionIndex',
value: function getFocusableOptionIndex(selectedOption) {
var options = this._visibleOptions;
if (!options.length) return null;
var valueKey = this.props.valueKey;
var focusedOption = this.state.focusedOption || selectedOption;
if (focusedOption && !focusedOption.disabled) {
var focusedOptionIndex = -1;
options.some(function (option, index) {
var isOptionEqual = option[valueKey] === focusedOption[valueKey];
if (isOptionEqual) {
focusedOptionIndex = index;
}
return isOptionEqual;
});
if (focusedOptionIndex !== -1) {
return focusedOptionIndex;
}
}
for (var i = 0; i < options.length; i++) {
if (!options[i].disabled) return i;
}
return null;
}
}, {
key: 'renderOuter',
value: function renderOuter(options, valueArray, focusedOption) {
var _this8 = this;
var menu = this.renderMenu(options, valueArray, focusedOption);
if (!menu) {
return null;
}
return React.createElement(
'div',
{ ref: function ref(_ref5) {
return _this8.menuContainer = _ref5;
}, className: 'Select-menu-outer', style: this.props.menuContainerStyle },
React.createElement(
'div',
{ ref: function ref(_ref4) {
return _this8.menu = _ref4;
}, role: 'listbox', tabIndex: -1, className: 'Select-menu', id: this._instancePrefix + '-list',
style: this.props.menuStyle,
onScroll: this.handleMenuScroll,
onMouseDown: this.handleMouseDownOnMenu },
menu
)
);
}
}, {
key: 'render',
value: function render() {
var _this9 = this;
var valueArray = this.getValueArray(this.props.value);
var options = this._visibleOptions = this.filterOptions(this.props.multi ? this.getValueArray(this.props.value) : null);
var isOpen = this.state.isOpen;
if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false;
var focusedOptionIndex = this.getFocusableOptionIndex(valueArray[0]);
var focusedOption = null;
if (focusedOptionIndex !== null) {
focusedOption = this._focusedOption = options[focusedOptionIndex];
} else {
focusedOption = this._focusedOption = null;
}
var className = classNames('Select', this.props.className, {
'Select--multi': this.props.multi,
'Select--single': !this.props.multi,
'is-clearable': this.props.clearable,
'is-disabled': this.props.disabled,
'is-focused': this.state.isFocused,
'is-loading': this.props.isLoading,
'is-open': isOpen,
'is-pseudo-focused': this.state.isPseudoFocused,
'is-searchable': this.props.searchable,
'has-value': valueArray.length
});
var removeMessage = null;
if (this.props.multi && !this.props.disabled && valueArray.length && !this.state.inputValue && this.state.isFocused && this.props.backspaceRemoves) {
removeMessage = React.createElement(
'span',
{ id: this._instancePrefix + '-backspace-remove-message', className: 'Select-aria-only', 'aria-live': 'assertive' },
this.props.backspaceToRemoveMessage.replace('{label}', valueArray[valueArray.length - 1][this.props.labelKey])
);
}
return React.createElement(
'div',
{ ref: function ref(_ref7) {
return _this9.wrapper = _ref7;
},
className: className,
style: this.props.wrapperStyle },
this.renderHiddenField(valueArray),
React.createElement(
'div',
{ ref: function ref(_ref6) {
return _this9.control = _ref6;
},
className: 'Select-control',
style: this.props.style,
onKeyDown: this.handleKeyDown,
onMouseDown: this.handleMouseDown,
onTouchEnd: this.handleTouchEnd,
onTouchStart: this.handleTouchStart,
onTouchMove: this.handleTouchMove
},
React.createElement(
'span',
{ className: 'Select-multi-value-wrapper', id: this._instancePrefix + '-value' },
this.renderValue(valueArray, isOpen),
this.renderInput(valueArray, focusedOptionIndex)
),
removeMessage,
this.renderLoading(),
this.renderClear(),
this.renderArrow()
),
isOpen ? this.renderOuter(options, !this.props.multi ? valueArray : null, focusedOption) : null
);
}
}]);
return Select;
}(React.Component);
Select$1.propTypes = {
'aria-describedby': PropTypes.string, // HTML ID(s) of element(s) that should be used to describe this input (for assistive tech)
'aria-label': PropTypes.string, // Aria label (for assistive tech)
'aria-labelledby': PropTypes.string, // HTML ID of an element that should be used as the label (for assistive tech)
addLabelText: PropTypes.string, // placeholder displayed when you want to add a label on a multi-value input
arrowRenderer: PropTypes.func, // Create drop-down caret element
autoBlur: PropTypes.bool, // automatically blur the component when an option is selected
autofocus: PropTypes.bool, // autofocus the component on mount
autosize: PropTypes.bool, // whether to enable autosizing or not
backspaceRemoves: PropTypes.bool, // whether backspace removes an item if there is no text input
backspaceToRemoveMessage: PropTypes.string, // Message to use for screenreaders to press backspace to remove the current item - {label} is replaced with the item label
className: PropTypes.string, // className for the outer element
clearAllText: stringOrNode, // title for the "clear" control when multi: true
clearRenderer: PropTypes.func, // create clearable x element
clearValueText: stringOrNode, // title for the "clear" control
clearable: PropTypes.bool, // should it be possible to reset value
closeOnSelect: PropTypes.bool, // whether to close the menu when a value is selected
deleteRemoves: PropTypes.bool, // whether backspace removes an item if there is no text input
delimiter: PropTypes.string, // delimiter to use to join multiple values for the hidden field value
disabled: PropTypes.bool, // whether the Select is disabled or not
escapeClearsValue: PropTypes.bool, // whether escape clears the value when the menu is closed
filterOption: PropTypes.func, // method to filter a single option (option, filterString)
filterOptions: PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values])
ignoreAccents: PropTypes.bool, // whether to strip diacritics when filtering
ignoreCase: PropTypes.bool, // whether to perform case-insensitive filtering
inputProps: PropTypes.object, // custom attributes for the Input
inputRenderer: PropTypes.func, // returns a custom input component
instanceId: PropTypes.string, // set the components instanceId
isLoading: PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded)
joinValues: PropTypes.bool, // joins multiple values into a single form field with the delimiter (legacy mode)
labelKey: PropTypes.string, // path of the label value in option objects
matchPos: PropTypes.string, // (any|start) match the start or entire string when filtering
matchProp: PropTypes.string, // (any|label|value) which option property to filter on
menuBuffer: PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu
menuContainerStyle: PropTypes.object, // optional style to apply to the menu container
menuRenderer: PropTypes.func, // renders a custom menu with options
menuStyle: PropTypes.object, // optional style to apply to the menu
multi: PropTypes.bool, // multi-value input
name: PropTypes.string, // generates a hidden <input /> tag with this field name for html forms
noResultsText: stringOrNode, // placeholder displayed when there are no matching search results
onBlur: PropTypes.func, // onBlur handler: function (event) {}
onBlurResetsInput: PropTypes.bool, // whether input is cleared on blur
onChange: PropTypes.func, // onChange handler: function (newValue) {}
onClose: PropTypes.func, // fires when the menu is closed
onCloseResetsInput: PropTypes.bool, // whether input is cleared when menu is closed through the arrow
onFocus: PropTypes.func, // onFocus handler: function (event) {}
onInputChange: PropTypes.func, // onInputChange handler: function (inputValue) {}
onInputKeyDown: PropTypes.func, // input keyDown handler: function (event) {}
onMenuScrollToBottom: PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options
onOpen: PropTypes.func, // fires when the menu is opened
onSelectResetsInput: PropTypes.bool, // whether input is cleared on select (works only for multiselect)
onValueClick: PropTypes.func, // onClick handler for value labels: function (value, event) {}
openOnClick: PropTypes.bool, // boolean to control opening the menu when the control is clicked
openOnFocus: PropTypes.bool, // always open options menu on focus
optionClassName: PropTypes.string, // additional class(es) to apply to the <Option /> elements
optionComponent: PropTypes.func, // option component to render in dropdown
optionRenderer: PropTypes.func, // optionRenderer: function (option) {}
options: PropTypes.array, // array of options
pageSize: PropTypes.number, // number of entries to page when using page up/down keys
placeholder: stringOrNode, // field placeholder, displayed when there's no value
required: PropTypes.bool, // applies HTML5 required attribute when needed
resetValue: PropTypes.any, // value to use when you clear the control
scrollMenuIntoView: PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged
searchable: PropTypes.bool, // whether to enable searching feature or not
simpleValue: PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false
style: PropTypes.object, // optional style to apply to the control
tabIndex: PropTypes.string, // optional tab index of the control
tabSelectsValue: PropTypes.bool, // whether to treat tabbing out while focused to be value selection
value: PropTypes.any, // initial field value
valueComponent: PropTypes.func, // value component to render
valueKey: PropTypes.string, // path of the label value in option objects
valueRenderer: PropTypes.func, // valueRenderer: function (option) {}
wrapperStyle: PropTypes.object // optional style to apply to the component wrapper
};
Select$1.defaultProps = {
addLabelText: 'Add "{label}"?',
arrowRenderer: arrowRenderer,
autosize: true,
backspaceRemoves: true,
backspaceToRemoveMessage: 'Press backspace to remove {label}',
clearable: true,
clearAllText: 'Clear all',
clearRenderer: clearRenderer,
clearValueText: 'Clear value',
closeOnSelect: true,
deleteRemoves: true,
delimiter: ',',
disabled: false,
escapeClearsValue: true,
filterOptions: filterOptions,
ignoreAccents: true,
ignoreCase: true,
inputProps: {},
isLoading: false,
joinValues: false,
labelKey: 'label',
matchPos: 'any',
matchProp: 'any',
menuBuffer: 0,
menuRenderer: menuRenderer,
multi: false,
noResultsText: 'No results found',
onBlurResetsInput: true,
onSelectResetsInput: true,
onCloseResetsInput: true,
openOnClick: true,
optionComponent: Option,
pageSize: 5,
placeholder: 'Select...',
required: false,
scrollMenuIntoView: true,
searchable: true,
simpleValue: false,
tabSelectsValue: true,
valueComponent: Value,
valueKey: 'value'
};
var propTypes = {
autoload: PropTypes.bool.isRequired, // automatically call the `loadOptions` prop on-mount; defaults to true
cache: PropTypes.any, // object to use to cache results; set to null/false to disable caching
children: PropTypes.func.isRequired, // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element
ignoreAccents: PropTypes.bool, // strip diacritics when filtering; defaults to true
ignoreCase: PropTypes.bool, // perform case-insensitive filtering; defaults to true
loadOptions: PropTypes.func.isRequired, // callback to load options asynchronously; (inputValue: string, callback: Function): ?Promise
loadingPlaceholder: PropTypes.oneOfType([// replaces the placeholder while options are loading
PropTypes.string, PropTypes.node]),
multi: PropTypes.bool, // multi-value input
noResultsText: PropTypes.oneOfType([// field noResultsText, displayed when no options come back from the server
PropTypes.string, PropTypes.node]),
onChange: PropTypes.func, // onChange handler: function (newValue) {}
onInputChange: PropTypes.func, // optional for keeping track of what is being typed
options: PropTypes.array.isRequired, // array of options
placeholder: PropTypes.oneOfType([// field placeholder, displayed when there's no value (shared with Select)
PropTypes.string, PropTypes.node]),
searchPromptText: PropTypes.oneOfType([// label to prompt for search input
PropTypes.string, PropTypes.node]),
value: PropTypes.any // initial field value
};
var defaultCache = {};
var defaultProps = {
autoload: true,
cache: defaultCache,
children: defaultChildren,
ignoreAccents: true,
ignoreCase: true,
loadingPlaceholder: 'Loading...',
options: [],
searchPromptText: 'Type to search'
};
var Async = function (_Component) {
inherits(Async, _Component);
function Async(props, context) {
classCallCheck(this, Async);
var _this = possibleConstructorReturn(this, (Async.__proto__ || Object.getPrototypeOf(Async)).call(this, props, context));
_this._cache = props.cache === defaultCache ? {} : props.cache;
_this.state = {
inputValue: '',
isLoading: false,
options: props.options
};
_this.onInputChange = _this.onInputChange.bind(_this);
return _this;
}
createClass(Async, [{
key: 'componentDidMount',
value: function componentDidMount() {
var autoload = this.props.autoload;
if (autoload) {
this.loadOptions('');
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (nextProps.options !== this.props.options) {
this.setState({
options: nextProps.options
});
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._callback = null;
}
}, {
key: 'loadOptions',
value: function loadOptions(inputValue) {
var _this2 = this;
var loadOptions = this.props.loadOptions;
var cache = this._cache;
if (cache && Object.prototype.hasOwnProperty.call(cache, inputValue)) {
this.setState({
options: cache[inputValue]
});
return;
}
var callback = function callback(error, data) {
if (callback === _this2._callback) {
_this2._callback = null;
var options = data && data.options || [];
if (cache) {
cache[inputValue] = options;
}
_this2.setState({
isLoading: false,
options: options
});
}
};
// Ignore all but the most recent request
this._callback = callback;
var promise = loadOptions(inputValue, callback);
if (promise) {
promise.then(function (data) {
return callback(null, data);
}, function (error) {
return callback(error);
});
}
if (this._callback && !this.state.isLoading) {
this.setState({
isLoading: true
});
}
}
}, {
key: 'onInputChange',
value: function onInputChange(inputValue) {
var _props = this.props,
ignoreAccents = _props.ignoreAccents,
ignoreCase = _props.ignoreCase,
onInputChange = _props.onInputChange;
var transformedInputValue = inputValue;
if (ignoreAccents) {
transformedInputValue = stripDiacritics(transformedInputValue);
}
if (ignoreCase) {
transformedInputValue = transformedInputValue.toLowerCase();
}
if (onInputChange) {
onInputChange(transformedInputValue);
}
this.setState({ inputValue: inputValue });
this.loadOptions(transformedInputValue);
// Return the original input value to avoid modifying the user's view of the input while typing.
return inputValue;
}
}, {
key: 'noResultsText',
value: function noResultsText() {
var _props2 = this.props,
loadingPlaceholder = _props2.loadingPlaceholder,
noResultsText = _props2.noResultsText,
searchPromptText = _props2.searchPromptText;
var _state = this.state,
inputValue = _state.inputValue,
isLoading = _state.isLoading;
if (isLoading) {
return loadingPlaceholder;
}
if (inputValue && noResultsText) {
return noResultsText;
}
return searchPromptText;
}
}, {
key: 'focus',
value: function focus() {
this.select.focus();
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var _props3 = this.props,
children = _props3.children,
loadingPlaceholder = _props3.loadingPlaceholder,
multi = _props3.multi,
onChange = _props3.onChange,
placeholder = _props3.placeholder;
var _state2 = this.state,
isLoading = _state2.isLoading,
options = _state2.options;
var props = {
noResultsText: this.noResultsText(),
placeholder: isLoading ? loadingPlaceholder : placeholder,
options: isLoading && loadingPlaceholder ? [] : options,
ref: function ref(_ref) {
return _this3.select = _ref;
}
};
return children(_extends({}, this.props, props, {
isLoading: isLoading,
onInputChange: this.onInputChange
}));
}
}]);
return Async;
}(Component);
Async.propTypes = propTypes;
Async.defaultProps = defaultProps;
function defaultChildren(props) {
return React.createElement(Select$1, props);
}
var CreatableSelect = function (_React$Component) {
inherits(CreatableSelect, _React$Component);
function CreatableSelect(props, context) {
classCallCheck(this, CreatableSelect);
var _this = possibleConstructorReturn(this, (CreatableSelect.__proto__ || Object.getPrototypeOf(CreatableSelect)).call(this, props, context));
_this.filterOptions = _this.filterOptions.bind(_this);
_this.menuRenderer = _this.menuRenderer.bind(_this);
_this.onInputKeyDown = _this.onInputKeyDown.bind(_this);
_this.onInputChange = _this.onInputChange.bind(_this);
_this.onOptionSelect = _this.onOptionSelect.bind(_this);
return _this;
}
createClass(CreatableSelect, [{
key: 'createNewOption',
value: function createNewOption() {
var _props = this.props,
isValidNewOption = _props.isValidNewOption,
newOptionCreator = _props.newOptionCreator,
onNewOptionClick = _props.onNewOptionClick,
_props$options = _props.options,
options = _props$options === undefined ? [] : _props$options;
if (isValidNewOption({ label: this.inputValue })) {
var option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey });
var _isOptionUnique = this.isOptionUnique({ option: option });
// Don't add the same option twice.
if (_isOptionUnique) {
if (onNewOptionClick) {
onNewOptionClick(option);
} else {
options.unshift(option);
this.select.selectValue(option);
}
}
}
}
}, {
key: 'filterOptions',
value: function filterOptions$$1() {
var _props2 = this.props,
filterOptions$$1 = _props2.filterOptions,
isValidNewOption = _props2.isValidNewOption,
options = _props2.options,
promptTextCreator = _props2.promptTextCreator;
// TRICKY Check currently selected options as well.
// Don't display a create-prompt for a value that's selected.
// This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array.
var excludeOptions = (arguments.length <= 2 ? undefined : arguments[2]) || [];
var filteredOptions = filterOptions$$1.apply(undefined, arguments) || [];
if (isValidNewOption({ label: this.inputValue })) {
var _newOptionCreator = this.props.newOptionCreator;
var option = _newOptionCreator({
label: this.inputValue,
labelKey: this.labelKey,
valueKey: this.valueKey
});
// TRICKY Compare to all options (not just filtered options) in case option has already been selected).
// For multi-selects, this would remove it from the filtered list.
var _isOptionUnique2 = this.isOptionUnique({
option: option,
options: excludeOptions.concat(filteredOptions)
});
if (_isOptionUnique2) {
var prompt = promptTextCreator(this.inputValue);
this._createPlaceholderOption = _newOptionCreator({
label: prompt,
labelKey: this.labelKey,
valueKey: this.valueKey
});
filteredOptions.unshift(this._createPlaceholderOption);
}
}
return filteredOptions;
}
}, {
key: 'isOptionUnique',
value: function isOptionUnique(_ref) {
var option = _ref.option,
options = _ref.options;
var isOptionUnique = this.props.isOptionUnique;
options = options || this.select.filterOptions();
return isOptionUnique({
labelKey: this.labelKey,
option: option,
options: options,
valueKey: this.valueKey
});
}
}, {
key: 'menuRenderer',
value: function menuRenderer$$1(params) {
var menuRenderer$$1 = this.props.menuRenderer;
return menuRenderer$$1(_extends({}, params, {
onSelect: this.onOptionSelect,
selectValue: this.onOptionSelect
}));
}
}, {
key: 'onInputChange',
value: function onInputChange(input) {
var onInputChange = this.props.onInputChange;
if (onInputChange) {
onInputChange(input);
}
// This value may be needed in between Select mounts (when this.select is null)
this.inputValue = input;
}
}, {
key: 'onInputKeyDown',
value: function onInputKeyDown(event) {
var _props3 = this.props,
shouldKeyDownEventCreateNewOption = _props3.shouldKeyDownEventCreateNewOption,
onInputKeyDown = _props3.onInputKeyDown;
var focusedOption = this.select.getFocusedOption();
if (focusedOption && focusedOption === this._createPlaceholderOption && shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })) {
this.createNewOption();
// Prevent decorated Select from doing anything additional with this keyDown event
event.preventDefault();
} else if (onInputKeyDown) {
onInputKeyDown(event);
}
}
}, {
key: 'onOptionSelect',
value: function onOptionSelect(option, event) {
if (option === this._createPlaceholderOption) {
this.createNewOption();
} else {
this.select.selectValue(option);
}
}
}, {
key: 'focus',
value: function focus() {
this.select.focus();
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props4 = this.props,
newOptionCreator = _props4.newOptionCreator,
shouldKeyDownEventCreateNewOption = _props4.shouldKeyDownEventCreateNewOption,
restProps = objectWithoutProperties(_props4, ['newOptionCreator', 'shouldKeyDownEventCreateNewOption']);
var children = this.props.children;
// We can't use destructuring default values to set the children,
// because it won't apply work if `children` is null. A falsy check is
// more reliable in real world use-cases.
if (!children) {
children = defaultChildren$1;
}
var props = _extends({}, restProps, {
allowCreate: true,
filterOptions: this.filterOptions,
menuRenderer: this.menuRenderer,
onInputChange: this.onInputChange,
onInputKeyDown: this.onInputKeyDown,
ref: function ref(_ref2) {
_this2.select = _ref2;
// These values may be needed in between Select mounts (when this.select is null)
if (_ref2) {
_this2.labelKey = _ref2.props.labelKey;
_this2.valueKey = _ref2.props.valueKey;
}
}
});
return children(props);
}
}]);
return CreatableSelect;
}(React.Component);
function defaultChildren$1(props) {
return React.createElement(Select$1, props);
}
function isOptionUnique(_ref3) {
var option = _ref3.option,
options = _ref3.options,
labelKey = _ref3.labelKey,
valueKey = _ref3.valueKey;
return options.filter(function (existingOption) {
return existingOption[labelKey] === option[labelKey] || existingOption[valueKey] === option[valueKey];
}).length === 0;
}
function isValidNewOption(_ref4) {
var label = _ref4.label;
return !!label;
}
function newOptionCreator(_ref5) {
var label = _ref5.label,
labelKey = _ref5.labelKey,
valueKey = _ref5.valueKey;
var option = {};
option[valueKey] = label;
option[labelKey] = label;
option.className = 'Select-create-option-placeholder';
return option;
}
function promptTextCreator(label) {
return 'Create option "' + label + '"';
}
function shouldKeyDownEventCreateNewOption(_ref6) {
var keyCode = _ref6.keyCode;
switch (keyCode) {
case 9: // TAB
case 13: // ENTER
case 188:
// COMMA
return true;
}
return false;
}
// Default prop methods
CreatableSelect.isOptionUnique = isOptionUnique;
CreatableSelect.isValidNewOption = isValidNewOption;
CreatableSelect.newOptionCreator = newOptionCreator;
CreatableSelect.promptTextCreator = promptTextCreator;
CreatableSelect.shouldKeyDownEventCreateNewOption = shouldKeyDownEventCreateNewOption;
CreatableSelect.defaultProps = {
filterOptions: filterOptions,
isOptionUnique: isOptionUnique,
isValidNewOption: isValidNewOption,
menuRenderer: menuRenderer,
newOptionCreator: newOptionCreator,
promptTextCreator: promptTextCreator,
shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption
};
CreatableSelect.propTypes = {
// Child function responsible for creating the inner Select component
// This component can be used to compose HOCs (eg Creatable and Async)
// (props: Object): PropTypes.element
children: PropTypes.func,
// See Select.propTypes.filterOptions
filterOptions: PropTypes.any,
// Searches for any matching option within the set of options.
// This function prevents duplicate options from being created.
// ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean
isOptionUnique: PropTypes.func,
// Determines if the current input text represents a valid option.
// ({ label: string }): boolean
isValidNewOption: PropTypes.func,
// See Select.propTypes.menuRenderer
menuRenderer: PropTypes.any,
// Factory to create new option.
// ({ label: string, labelKey: string, valueKey: string }): Object
newOptionCreator: PropTypes.func,
// input change handler: function (inputValue) {}
onInputChange: PropTypes.func,
// input keyDown handler: function (event) {}
onInputKeyDown: PropTypes.func,
// new option click handler: function (option) {}
onNewOptionClick: PropTypes.func,
// See Select.propTypes.options
options: PropTypes.array,
// Creates prompt/placeholder option text.
// (filterText: string): string
promptTextCreator: PropTypes.func,
// Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option.
shouldKeyDownEventCreateNewOption: PropTypes.func
};
function reduce(obj) {
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return Object.keys(obj).reduce(function (props, key) {
var value = obj[key];
if (value !== undefined) props[key] = value;
return props;
}, props);
}
var AsyncCreatableSelect = function (_React$Component) {
inherits(AsyncCreatableSelect, _React$Component);
function AsyncCreatableSelect() {
classCallCheck(this, AsyncCreatableSelect);
return possibleConstructorReturn(this, (AsyncCreatableSelect.__proto__ || Object.getPrototypeOf(AsyncCreatableSelect)).apply(this, arguments));
}
createClass(AsyncCreatableSelect, [{
key: 'focus',
value: function focus() {
this.select.focus();
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
return React.createElement(
Async,
this.props,
function (asyncProps) {
return React.createElement(
CreatableSelect,
_this2.props,
function (creatableProps) {
return React.createElement(Select$1, _extends({}, reduce(asyncProps, reduce(creatableProps, {})), {
onInputChange: function onInputChange(input) {
creatableProps.onInputChange(input);
return asyncProps.onInputChange(input);
},
ref: function ref(_ref) {
_this2.select = _ref;
creatableProps.ref(_ref);
asyncProps.ref(_ref);
}
}));
}
);
}
);
}
}]);
return AsyncCreatableSelect;
}(React.Component);
Select$1.Async = Async;
Select$1.AsyncCreatable = AsyncCreatableSelect;
Select$1.Creatable = CreatableSelect;
Select$1.Value = Value;
export { Async, AsyncCreatableSelect as AsyncCreatable, CreatableSelect as Creatable, Value };
export default Select$1;
|
Paths/React/05.Building Scalable React Apps/2-react-boilerplate-building-scalable-apps-m2-exercise-files/After/app/containers/App/index.js | phiratio/Pluralsight-materials | /**
*
* 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 neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import styles from './styles.css';
export default class App extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div className={styles.container}>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
assets/js/react/userList.js | ChrisBr/duell-um-die-geld |
import React, { Component } from 'react';
class UserList extends React.Component {
constructor(props) {
super(props);
this.renderUserNames = this.renderUserNames.bind(this);
this.renderAccountBalance = this.renderAccountBalance.bind(this);
this.renderIndex = this.renderIndex.bind(this);
this.renderAnswer = this.renderAnswer.bind(this);
this.renderBet = this.renderBet.bind(this);
}
renderUserNames(user){
if(user.id === this.props.user.id){
return <td>You</td>
} else {
return <td>{ user.name }</td>
}
}
renderAccountBalance(user){
return <td>{ user.account }</td>
}
renderAnswer(user){
if(user.id === this.props.user.id && this.props.user.answer !== ""){
return <td>{ user.answer }</td>
} else if(user.answer !== "") {
return <td>Submitted answer</td>
} else {
return <td>Waiting for answer</td>
}
}
renderIndex(index){
return <td>{index + 1 }</td>
}
renderBet(user){
return <td>{user.bet}</td>
}
render() {
var that = this;
return (
<table className="table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Balance</th>
<th>Bet</th>
<th>Answer</th>
</tr>
</thead>
<tbody>
{
this.props.users.map(function(user, index){
return(
<tr key={index} >
{that.renderIndex(index)}
{that.renderUserNames(user)}
{that.renderAccountBalance(user)}
{that.renderBet(user)}
{that.renderAnswer(user)}
</tr>
)
})
}
</tbody>
</table>
);
}
}
export default UserList;
|
_older/section-skills/SkillTags.es6.js | widged/SOT-skills-report | /* jshint esnext: true */
import React from 'react';
let {Component} = React;
class SkillList extends Component {
render() {
var {list} = this.props;
return (
<skills><ul>
{(list || []).map(((item) => {
return <li><SkillItem item={item}/></li>
}))}
</ul></skills>
);
}
}
class SkillItem extends Component {
constructor(props) {
super(props);
function handleClick(e) {
this.setState({selected: !this.state.selected});
}
this.state = {selected: false, handleClick: handleClick.bind(this)};
}
render() {
var {item} = this.props;
var {handleClick} = this.state;
var {name, type, primary, secondary, selected, students} = item;
var studentsQty = (selected && primary) ? primary.length : (secondary) ? secondary.users.split(' ').length.toString() : ' ';
return(<skill className={'type-'+type + (selected ? ' selected' : '') + (secondary ? ' secondary' : '')} onClick={handleClick}>{name}<qty>{studentsQty}</qty></skill>);
}
}
function skillsByCategory(skills) {
var dict = [], categories = [];
(skills || []).forEach(function ({name, type, category, levels}) {
var idx = dict.indexOf(category);
if (idx === -1) {
idx = dict.length;
dict.push(category);
categories[idx] = { name: category, skills: [] };
}
categories[idx].skills.push({name, type, category, levels});
});
categories.forEach((d) => {
let order = 'skill;tool'.split(';')
d.skills.sort((a, b) => { })
d.skills.sort((a, b) => {
var diff = (order.indexOf(a.type) - order.indexOf(b.type));
if(diff !== 0) return diff;
return a.name < b.name ? -1 : a.name > b.name ? +1 : 0;
});
});
let order = 'Web / Programming;Design;BA / Digital Marketing;Engineering Skills;Systems / Ops / DBA'.split(';');
categories.sort((a, b) => { return order.indexOf(a.name) - order.indexOf(b.name) })
return categories;
}
export default class SkillVis extends Component {
constructor(props) {
super(props);
let {secondarySkills, handlePrimaryChange} = this.props;
let level = 'Paid';
function getSecondary(skill, level) {
var sskill = (secondarySkills || []).filter((d) => { return d.name === skill; })[0];
var slevel = (sskill || {levels: []}).levels.filter((d) => { return d.name === level; })[0];
return (slevel || {}).skills;
}
function handleClick(e) {
var skill = e.target.innerText;
var secSkills = getSecondary(skill, level);
var secList = (secSkills || []).map(({name}) => { return name; });
var list = this.state.list;
var nlist = (list || []).map(({name, skills}) => {
var nskills = skills.map(({name, type, category, levels}) => {
var selected = (name === skill) ? true : false;
var primary = (levels[level] || {user_ids: []}).user_ids;
if(selected) { handlePrimaryChange(primary); }
var idx = secList.indexOf(name);
var secondary = ( idx !== -1) ? secSkills[idx] : undefined;
return {name, type, category, levels, selected, primary, secondary};
});
return {name, skills: nskills};
});
this.setState({list: nlist});
}
let {primarySkills} = this.props;
let categorySkills = skillsByCategory(primarySkills);
this.state = {list: categorySkills, handleClick: handleClick.bind(this)};
}
render() {
var {list, handleClick} = this.state;
return (
<categories onClick={handleClick}>{(list || []).map(({name, skills}) => {
return(
<div>
<h1>{name}</h1>
<SkillList list={skills}/>
</div>
);
})}</categories>
);
}
}
|
packages/wix-style-react/src/DragAndDrop/Draggable/components/DraggableSource.js | wix/wix-style-react | import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { DragSource } from 'react-dnd';
import { getEmptyImage } from 'react-dnd-html5-backend';
import noop from 'lodash/noop';
import DragLayer from './DragLayer';
import { ItemTypes } from '../types';
/* eslint-disable new-cap */
const source = {
beginDrag: ({
id,
index,
containerId,
groupName,
item,
onMoveOut,
onDragStart,
onDrop,
}) => {
if (onDragStart) {
onDragStart({
id,
index,
containerId,
groupName,
item,
});
}
/** we setup monitor.getItem() snapshot, so we will be always able to get info about item that we drag */
return {
id,
index,
containerId,
groupName,
originalIndex: index, // as index is mutable during d&d, we need another storage for original index
originalItem: item,
onMoveOut,
realTime: {
onMoveOut,
onDrop,
containerId,
},
};
},
endDrag: (
{ id, index, containerId, groupName, item, onDragEnd },
monitor,
) => {
/** if drop was called, on drop target and drag is end, then we notify parent about this */
const { onDrop } = monitor.getItem().realTime;
if (onDragEnd) {
onDragEnd({
id,
index,
containerId,
groupName,
item,
});
}
if (monitor.getDropResult()) {
const isSameGroup =
groupName &&
monitor.getItem().groupName &&
groupName === monitor.getDropResult().groupName;
const isSameContainer =
containerId === monitor.getDropResult().containerId;
if (isSameGroup || isSameContainer) {
onDrop({
payload: monitor.getItem().originalItem, // original item
removedIndex: monitor.getItem().originalIndex, // original item index
addedIndex: monitor.getItem().index, // new item index
addedToContainerId: monitor.getDropResult().containerId, // new container for item
removedFromContainerId: containerId, // original item container
});
}
}
},
canDrag: ({ id, index, containerId, groupName, item, canDrag }) => {
return canDrag
? canDrag({
id,
index,
containerId,
groupName,
item,
})
: true;
},
isDragging: ({ id, containerId, groupName }, monitor) => {
const item = monitor.getItem();
const isSameGroup =
groupName && item.groupName && groupName === item.groupName;
const isSameContainer = containerId === item.containerId;
return (isSameGroup || isSameContainer) && item.id === id;
},
};
const collect = (connect, monitor) => ({
connectDragSource: connect.dragSource(),
connectDragPreview: connect.dragPreview(),
isDragging: monitor.isDragging(),
});
class DraggableSource extends React.Component {
state = {
offsetOfHandle: { x: 0, y: 0 },
itemWidth: null,
};
rootNode = null;
componentDidMount() {
if (this.props.connectDragPreview) {
this.props.connectDragPreview(getEmptyImage(), {
captureDraggingState: true,
});
}
this.updateDiff();
this.updateItemWidth();
}
componentDidUpdate(prevProps) {
if (
prevProps.id !== this.props.id ||
prevProps.containerId !== this.props.containerId
) {
this.updateDiff();
}
if (prevProps.isDragging !== this.props.isDragging) {
this.updateItemWidth();
}
}
updateDiff() {
/* in case if we have handle, the drag will start in wrong position and we need to fix this */
if (this.props.withHandle && this.handleNode) {
this.setState({
offsetOfHandle: {
x:
this.handleNode.getBoundingClientRect().x -
this.rootNode.getBoundingClientRect().x,
y:
this.handleNode.getBoundingClientRect().y -
this.rootNode.getBoundingClientRect().y,
},
});
}
}
updateItemWidth = () => {
if (this.rootNode) {
this.setState({ itemWidth: this.rootNode.getBoundingClientRect().width });
}
};
_getWrapperStyles() {
const {
shift,
ignoreMouseEvents,
animationDuration,
animationTiming,
} = this.props;
const [xShift, yShift] = shift || [0, 0];
const hasShift = xShift || yShift;
const transition = ignoreMouseEvents
? `transform ${animationDuration}ms ${animationTiming}`
: undefined;
const transform = hasShift
? `translate(${xShift}px, ${yShift}px)`
: undefined;
const willChange = hasShift ? 'transform' : undefined;
const pointerEvents = ignoreMouseEvents || hasShift ? 'none' : undefined;
return {
willChange,
transition,
transform,
pointerEvents,
};
}
_renderDraggableItem() {
const {
isDragging,
connectDragSource,
withHandle,
renderItem,
id,
item,
delayed,
withStrip,
isInitialPositionToDrop,
} = this.props;
const content = withHandle
? renderItem({
id,
item,
isPlaceholder: isDragging,
connectHandle: handle => {
const handleWithRef = React.cloneElement(handle, {
ref: node => (this.handleNode = ReactDOM.findDOMNode(node)),
});
return connectDragSource(handleWithRef);
},
delayed,
withStrip,
isInitialPositionToDrop,
})
: connectDragSource(
renderItem({
id,
item,
isPlaceholder: isDragging,
connectHandle: noop,
delayed,
withStrip,
isInitialPositionToDrop,
}),
);
return <div style={this._getWrapperStyles()}>{content}</div>;
}
_setRootNode = node => {
// Don't need to reset the values if node remains the same
if (node && this.rootNode !== node) {
this.rootNode = node;
}
};
_renderPreview = ({ previewStyles }) => {
const { renderItem, id, item, delayed } = this.props;
return renderItem({
id,
item,
previewStyles: { width: this.state.itemWidth, ...previewStyles },
isPreview: true,
connectHandle: noop,
delayed,
});
};
_renderPreviewItem() {
const { id, usePortal } = this.props;
return (
<DragLayer
offsetOfHandle={this.state.offsetOfHandle}
usePortal={usePortal}
renderPreview={this._renderPreview}
id={id}
// pass 'width' this prop to rerender element with changed width from state
width={this.state.itemWidth}
draggedType={ItemTypes.DRAGGABLE}
/>
);
}
render() {
const { connectDragSource } = this.props;
return connectDragSource ? (
<div ref={this._setRootNode}>
{this._renderDraggableItem()}
{this._renderPreviewItem()}
</div>
) : null;
}
}
DraggableSource.propTypes = {
isDragging: PropTypes.bool, // from react-dnd
connectDragSource: PropTypes.func, // from react-dnd
connectDragPreview: PropTypes.func, // from react-dnd
usePortal: PropTypes.bool,
groupName: PropTypes.string,
containerId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
renderItem: PropTypes.func,
index: PropTypes.number,
id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
item: PropTypes.object,
withHandle: PropTypes.bool,
onDrop: PropTypes.func,
onMoveOut: PropTypes.func,
onDragStart: PropTypes.func,
onDragEnd: PropTypes.func,
/** visual positioning shifting for an element (transform: translate) without moving it from its real position at DOM (left, top) */
shift: PropTypes.arrayOf(PropTypes.number),
ignoreMouseEvents: PropTypes.bool,
/** animation duration in ms, default = 0 - disabled */
animationDuration: PropTypes.number,
/** animation timing function, default = linear */
animationTiming: PropTypes.string,
/** callback that could prevent item from dragging */
canDrag: PropTypes.func,
/** Is delay timer still waiting before user can drag the item */
delayed: PropTypes.bool,
};
export default DragSource(
ItemTypes.DRAGGABLE,
source,
collect,
)(DraggableSource);
|
examples/Example/index.ios.js | thegamenicorus/react-native-timeline-listview | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
} from 'react-native';
import App from './app'
AppRegistry.registerComponent('Example', () => App);
|
app/javascript/mastodon/features/getting_started/components/announcements.js | tootcafe/mastodon | import React from 'react';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ReactSwipeableViews from 'react-swipeable-views';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from 'mastodon/components/icon_button';
import Icon from 'mastodon/components/icon';
import { defineMessages, injectIntl, FormattedMessage, FormattedDate } from 'react-intl';
import { autoPlayGif, reduceMotion, disableSwiping } from 'mastodon/initial_state';
import elephantUIPlane from 'mastodon/../images/elephant_ui_plane.svg';
import { mascot } from 'mastodon/initial_state';
import unicodeMapping from 'mastodon/features/emoji/emoji_unicode_mapping_light';
import classNames from 'classnames';
import EmojiPickerDropdown from 'mastodon/features/compose/containers/emoji_picker_dropdown_container';
import AnimatedNumber from 'mastodon/components/animated_number';
import TransitionMotion from 'react-motion/lib/TransitionMotion';
import spring from 'react-motion/lib/spring';
import { assetHost } from 'mastodon/utils/config';
const messages = defineMessages({
close: { id: 'lightbox.close', defaultMessage: 'Close' },
previous: { id: 'lightbox.previous', defaultMessage: 'Previous' },
next: { id: 'lightbox.next', defaultMessage: 'Next' },
});
class Content extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
announcement: ImmutablePropTypes.map.isRequired,
};
setRef = c => {
this.node = c;
}
componentDidMount () {
this._updateLinks();
}
componentDidUpdate () {
this._updateLinks();
}
_updateLinks () {
const node = this.node;
if (!node) {
return;
}
const links = node.querySelectorAll('a');
for (var i = 0; i < links.length; ++i) {
let link = links[i];
if (link.classList.contains('status-link')) {
continue;
}
link.classList.add('status-link');
let mention = this.props.announcement.get('mentions').find(item => link.href === item.get('url'));
if (mention) {
link.addEventListener('click', this.onMentionClick.bind(this, mention), false);
link.setAttribute('title', mention.get('acct'));
} else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) {
link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false);
} else {
let status = this.props.announcement.get('statuses').find(item => link.href === item.get('url'));
if (status) {
link.addEventListener('click', this.onStatusClick.bind(this, status), false);
}
link.setAttribute('title', link.href);
link.classList.add('unhandled-link');
}
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
}
}
onMentionClick = (mention, e) => {
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/accounts/${mention.get('id')}`);
}
}
onHashtagClick = (hashtag, e) => {
hashtag = hashtag.replace(/^#/, '');
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/timelines/tag/${hashtag}`);
}
}
onStatusClick = (status, e) => {
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/statuses/${status.get('id')}`);
}
}
handleMouseEnter = ({ currentTarget }) => {
if (autoPlayGif) {
return;
}
const emojis = currentTarget.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
emoji.src = emoji.getAttribute('data-original');
}
}
handleMouseLeave = ({ currentTarget }) => {
if (autoPlayGif) {
return;
}
const emojis = currentTarget.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
emoji.src = emoji.getAttribute('data-static');
}
}
render () {
const { announcement } = this.props;
return (
<div
className='announcements__item__content translate'
ref={this.setRef}
dangerouslySetInnerHTML={{ __html: announcement.get('contentHtml') }}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
/>
);
}
}
class Emoji extends React.PureComponent {
static propTypes = {
emoji: PropTypes.string.isRequired,
emojiMap: ImmutablePropTypes.map.isRequired,
hovered: PropTypes.bool.isRequired,
};
render () {
const { emoji, emojiMap, hovered } = this.props;
if (unicodeMapping[emoji]) {
const { filename, shortCode } = unicodeMapping[this.props.emoji];
const title = shortCode ? `:${shortCode}:` : '';
return (
<img
draggable='false'
className='emojione'
alt={emoji}
title={title}
src={`${assetHost}/emoji/${filename}.svg`}
/>
);
} else if (emojiMap.get(emoji)) {
const filename = (autoPlayGif || hovered) ? emojiMap.getIn([emoji, 'url']) : emojiMap.getIn([emoji, 'static_url']);
const shortCode = `:${emoji}:`;
return (
<img
draggable='false'
className='emojione custom-emoji'
alt={shortCode}
title={shortCode}
src={filename}
/>
);
} else {
return null;
}
}
}
class Reaction extends ImmutablePureComponent {
static propTypes = {
announcementId: PropTypes.string.isRequired,
reaction: ImmutablePropTypes.map.isRequired,
addReaction: PropTypes.func.isRequired,
removeReaction: PropTypes.func.isRequired,
emojiMap: ImmutablePropTypes.map.isRequired,
style: PropTypes.object,
};
state = {
hovered: false,
};
handleClick = () => {
const { reaction, announcementId, addReaction, removeReaction } = this.props;
if (reaction.get('me')) {
removeReaction(announcementId, reaction.get('name'));
} else {
addReaction(announcementId, reaction.get('name'));
}
}
handleMouseEnter = () => this.setState({ hovered: true })
handleMouseLeave = () => this.setState({ hovered: false })
render () {
const { reaction } = this.props;
let shortCode = reaction.get('name');
if (unicodeMapping[shortCode]) {
shortCode = unicodeMapping[shortCode].shortCode;
}
return (
<button className={classNames('reactions-bar__item', { active: reaction.get('me') })} onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} title={`:${shortCode}:`} style={this.props.style}>
<span className='reactions-bar__item__emoji'><Emoji hovered={this.state.hovered} emoji={reaction.get('name')} emojiMap={this.props.emojiMap} /></span>
<span className='reactions-bar__item__count'><AnimatedNumber value={reaction.get('count')} /></span>
</button>
);
}
}
class ReactionsBar extends ImmutablePureComponent {
static propTypes = {
announcementId: PropTypes.string.isRequired,
reactions: ImmutablePropTypes.list.isRequired,
addReaction: PropTypes.func.isRequired,
removeReaction: PropTypes.func.isRequired,
emojiMap: ImmutablePropTypes.map.isRequired,
};
handleEmojiPick = data => {
const { addReaction, announcementId } = this.props;
addReaction(announcementId, data.native.replace(/:/g, ''));
}
willEnter () {
return { scale: reduceMotion ? 1 : 0 };
}
willLeave () {
return { scale: reduceMotion ? 0 : spring(0, { stiffness: 170, damping: 26 }) };
}
render () {
const { reactions } = this.props;
const visibleReactions = reactions.filter(x => x.get('count') > 0);
const styles = visibleReactions.map(reaction => ({
key: reaction.get('name'),
data: reaction,
style: { scale: reduceMotion ? 1 : spring(1, { stiffness: 150, damping: 13 }) },
})).toArray();
return (
<TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}>
{items => (
<div className={classNames('reactions-bar', { 'reactions-bar--empty': visibleReactions.isEmpty() })}>
{items.map(({ key, data, style }) => (
<Reaction
key={key}
reaction={data}
style={{ transform: `scale(${style.scale})`, position: style.scale < 0.5 ? 'absolute' : 'static' }}
announcementId={this.props.announcementId}
addReaction={this.props.addReaction}
removeReaction={this.props.removeReaction}
emojiMap={this.props.emojiMap}
/>
))}
{visibleReactions.size < 8 && <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} button={<Icon id='plus' />} />}
</div>
)}
</TransitionMotion>
);
}
}
class Announcement extends ImmutablePureComponent {
static propTypes = {
announcement: ImmutablePropTypes.map.isRequired,
emojiMap: ImmutablePropTypes.map.isRequired,
addReaction: PropTypes.func.isRequired,
removeReaction: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
selected: PropTypes.bool,
};
state = {
unread: !this.props.announcement.get('read'),
};
componentDidUpdate () {
const { selected, announcement } = this.props;
if (!selected && this.state.unread !== !announcement.get('read')) {
this.setState({ unread: !announcement.get('read') });
}
}
render () {
const { announcement } = this.props;
const { unread } = this.state;
const startsAt = announcement.get('starts_at') && new Date(announcement.get('starts_at'));
const endsAt = announcement.get('ends_at') && new Date(announcement.get('ends_at'));
const now = new Date();
const hasTimeRange = startsAt && endsAt;
const skipYear = hasTimeRange && startsAt.getFullYear() === endsAt.getFullYear() && endsAt.getFullYear() === now.getFullYear();
const skipEndDate = hasTimeRange && startsAt.getDate() === endsAt.getDate() && startsAt.getMonth() === endsAt.getMonth() && startsAt.getFullYear() === endsAt.getFullYear();
const skipTime = announcement.get('all_day');
return (
<div className='announcements__item'>
<strong className='announcements__item__range'>
<FormattedMessage id='announcement.announcement' defaultMessage='Announcement' />
{hasTimeRange && <span> · <FormattedDate value={startsAt} hour12={false} year={(skipYear || startsAt.getFullYear() === now.getFullYear()) ? undefined : 'numeric'} month='short' day='2-digit' hour={skipTime ? undefined : '2-digit'} minute={skipTime ? undefined : '2-digit'} /> - <FormattedDate value={endsAt} hour12={false} year={(skipYear || endsAt.getFullYear() === now.getFullYear()) ? undefined : 'numeric'} month={skipEndDate ? undefined : 'short'} day={skipEndDate ? undefined : '2-digit'} hour={skipTime ? undefined : '2-digit'} minute={skipTime ? undefined : '2-digit'} /></span>}
</strong>
<Content announcement={announcement} />
<ReactionsBar
reactions={announcement.get('reactions')}
announcementId={announcement.get('id')}
addReaction={this.props.addReaction}
removeReaction={this.props.removeReaction}
emojiMap={this.props.emojiMap}
/>
{unread && <span className='announcements__item__unread' />}
</div>
);
}
}
export default @injectIntl
class Announcements extends ImmutablePureComponent {
static propTypes = {
announcements: ImmutablePropTypes.list,
emojiMap: ImmutablePropTypes.map.isRequired,
dismissAnnouncement: PropTypes.func.isRequired,
addReaction: PropTypes.func.isRequired,
removeReaction: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
state = {
index: 0,
};
static getDerivedStateFromProps(props, state) {
if (props.announcements.size > 0 && state.index >= props.announcements.size) {
return { index: props.announcements.size - 1 };
} else {
return null;
}
}
componentDidMount () {
this._markAnnouncementAsRead();
}
componentDidUpdate () {
this._markAnnouncementAsRead();
}
_markAnnouncementAsRead () {
const { dismissAnnouncement, announcements } = this.props;
const { index } = this.state;
const announcement = announcements.get(announcements.size - 1 - index);
if (!announcement.get('read')) dismissAnnouncement(announcement.get('id'));
}
handleChangeIndex = index => {
this.setState({ index: index % this.props.announcements.size });
}
handleNextClick = () => {
this.setState({ index: (this.state.index + 1) % this.props.announcements.size });
}
handlePrevClick = () => {
this.setState({ index: (this.props.announcements.size + this.state.index - 1) % this.props.announcements.size });
}
render () {
const { announcements, intl } = this.props;
const { index } = this.state;
if (announcements.isEmpty()) {
return null;
}
return (
<div className='announcements'>
<img className='announcements__mastodon' alt='' draggable='false' src={mascot || elephantUIPlane} />
<div className='announcements__container'>
<ReactSwipeableViews animateHeight={!reduceMotion} adjustHeight={reduceMotion} index={index} onChangeIndex={this.handleChangeIndex}>
{announcements.map((announcement, idx) => (
<Announcement
key={announcement.get('id')}
announcement={announcement}
emojiMap={this.props.emojiMap}
addReaction={this.props.addReaction}
removeReaction={this.props.removeReaction}
intl={intl}
selected={index === idx}
disabled={disableSwiping}
/>
)).reverse()}
</ReactSwipeableViews>
{announcements.size > 1 && (
<div className='announcements__pagination'>
<IconButton disabled={announcements.size === 1} title={intl.formatMessage(messages.previous)} icon='chevron-left' onClick={this.handlePrevClick} size={13} />
<span>{index + 1} / {announcements.size}</span>
<IconButton disabled={announcements.size === 1} title={intl.formatMessage(messages.next)} icon='chevron-right' onClick={this.handleNextClick} size={13} />
</div>
)}
</div>
</div>
);
}
}
|
src/app/component/color-card-list/color-card-list.story.js | all3dp/printing-engine-client | import React from 'react'
import {storiesOf} from '@storybook/react'
import range from 'lodash/range'
import ColorCard from '../color-card'
import ColorCardList from '.'
import MaterialImage from '../material-image'
import Price from '../price'
import Button from '../button'
storiesOf('ColorCardList', module).add('default', () => (
<ColorCardList>
{range(20).map(i => (
<ColorCard
key={i}
colorTrait={<MaterialImage color="#ff0000" />}
title={`Color ${i}`}
price={<Price value="$19.44" prefix="+" />}
button={<Button label="Select" minor tiny />}
/>
))}
</ColorCardList>
))
|
pages/_document.js | nvbf/pepper | import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
render() {
const sheet = new ServerStyleSheet();
const main = sheet.collectStyles(<Main />);
const styleTags = sheet.getStyleElement();
return (
<html lang="no">
<Head>
<title>Pepper</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet" />
<link href="/static/base.css" rel="stylesheet" type="text/css" />
{styleTags}
</Head>
<body>
<div className="root">{main}</div>
<NextScript />
</body>
</html>
);
}
}
|
src/components/pages/search/sub/PaxNumSpinner.js | filtudo/eebook | import React, { Component } from 'react';
import Button from '../../../common/Button';
import './PaxNumSpinner.scss'
export default class PaxNumSpinner extends Component {
paxNumberChange(operation){
this.props.onPaxNumberChange(this.props.paxType, operation);
}
render() {
let fromTo = this.props.to !== false ? this.props.from + '-' + this.props.to : this.props.from + '+';
let minusDisabled = this.props.num > this.props.minNum ? false : true;
let plusDisabled = this.props.num >= this.props.maxNum ? true : false;
return (
<div className={"paxnum-spinner " + this.props.className}>
<div className="content" tabIndex="0">
<label className="label">{this.props.label}</label>
<div className="row compact">
<div className="col-xs-6">
<strong className="number">{this.props.num}</strong>
</div>
<div className="col-xs-6">
<span className="range">{fromTo}<br/>{this.props.unit}</span>
</div>
</div>
<div className="row compact actions">
<div className="col-xs-6">
<Button className="default block" disabled={plusDisabled} onClick={this.paxNumberChange.bind(this, '+')} tabIndex={-1}>+</Button>
</div>
<div className="col-xs-6">
<Button className="default block" disabled={minusDisabled} onClick={this.paxNumberChange.bind(this, '-')} tabIndex={-1}>-</Button>
</div>
</div>
</div>
</div>
);
}
}
PaxNumSpinner.defaultProps = {
className: "",
label: "Number",
from: false,
to: false,
unit: "",
num: 1,
minNum: 0,
maxNum: 9,
paxType: "numAdt",
onPaxNumberChange: ""
};
|
docs/src/app/components/pages/components/Slider/ExampleAxis.js | lawrence-yu/material-ui | import React from 'react';
import Slider from 'material-ui/Slider';
const styles = {
root: {
display: 'flex',
height: 124,
flexDirection: 'row',
justifyContent: 'space-around',
},
};
/**
* The orientation of the slider can be reversed and rotated using the `axis` prop.
*/
const SliderExampleAxis = () => (
<div style={styles.root}>
<Slider style={{height: 100}} axis="y" defaultValue={0.5} />
<Slider style={{width: 200}} axis="x-reverse" />
<Slider style={{height: 100}} axis="y-reverse" defaultValue={1} />
</div>
);
export default SliderExampleAxis;
|
lib/panels/Clip/index.js | Kitware/light-viz | import equals from 'mout/src/array/equals';
import objEquals from 'mout/src/object/equals';
import DoubleSliderElement from 'paraviewweb/src/React/Widgets/DoubleSliderWidget';
import React from 'react';
import PropTypes from 'prop-types';
import ToggleButton from 'paraviewweb/src/React/Widgets/ToggleIconButtonWidget';
import style from 'LightVizStyle/ClipPanel.mcss';
import AbstractPanel from '../AbstractPanel';
import {
getState,
updateClipInsideOut,
updateClipPosition,
updateClipBoxPosition,
enableClipBox,
} from '../../client';
export default class ClipPanel extends React.Component {
constructor(props) {
super(props);
this.oldState = {
xPosition:
(props.dataset.data.bounds[0] + props.dataset.data.bounds[1]) * 0.5,
yPosition:
(props.dataset.data.bounds[2] + props.dataset.data.bounds[3]) * 0.5,
zPosition:
(props.dataset.data.bounds[4] + props.dataset.data.bounds[5]) * 0.5,
xInsideOut: false,
yInsideOut: false,
zInsideOut: false,
};
this.state = Object.assign({}, this.oldState);
}
componentDidMount() {
getState('clip', this, this.modulePanel);
}
componentWillReceiveProps(nextProps) {
const previous = this.props.dataset.data.bounds;
const next = nextProps.dataset.data.bounds;
if (!equals(previous, next)) {
this.setState({
xPosition: (next[0] + next[1]) * 0.5,
yPosition: (next[2] + next[3]) * 0.5,
zPosition: (next[4] + next[5]) * 0.5,
});
}
if (this.props.dataset.autoApply !== nextProps.dataset.autoApply) {
this.onApply();
}
}
onApply() {
const { xPosition, yPosition, zPosition } = this.state;
const pos = {
xPosition,
yPosition,
zPosition,
};
updateClipPosition(pos);
enableClipBox(false);
updateClipInsideOut(
this.state.xInsideOut,
this.state.yInsideOut,
this.state.zInsideOut
);
this.oldState = Object.assign({}, this.state);
// This is to force a re-render so that the apply button will be disabled again
this.setState({ applyUpdate: true });
this.oldState.applyUpdate = true;
}
onReset() {
this.setState(this.oldState);
}
updateState(newState) {
this.oldState = {
xPosition: newState.xPosition,
yPosition: newState.yPosition,
zPosition: newState.zPosition,
xInsideOut: newState.xInsideOut,
yInsideOut: newState.yInsideOut,
zInsideOut: newState.zInsideOut,
};
this.setState(Object.assign({}, this.oldState));
}
toggleInsideOut(onOff, name) {
const { xInsideOut, yInsideOut, zInsideOut } = this.state;
const insideOut = {
xInsideOut,
yInsideOut,
zInsideOut,
};
this.setState({
[name]: onOff,
applyUpdate: false,
});
this.oldState.applyUpdate = false;
insideOut[name] = onOff;
if (this.props.dataset.autoApply) {
updateClipInsideOut(
insideOut.xInsideOut,
insideOut.yInsideOut,
insideOut.zInsideOut
);
}
}
positionChange(name, value) {
const { xPosition, yPosition, zPosition } = this.state;
const pos = {
xPosition,
yPosition,
zPosition,
};
this.setState({
[name]: value,
applyUpdate: false,
});
this.oldState.applyUpdate = false;
// Update server
pos[name] = value;
if (this.props.dataset.autoApply) {
updateClipPosition(pos);
} else {
enableClipBox(true);
updateClipBoxPosition(pos);
}
}
render() {
const needsApply = !objEquals(this.oldState, this.state);
return (
<AbstractPanel
ref={(c) => {
this.modulePanel = c;
}}
name="clip"
dataset={this.props.dataset}
hideAllButVisibility={this.props.hideAdditionalControls}
hideInputSelection
onApply={this.onApply}
onReset={this.onReset}
needsApply={needsApply}
moduleName="Clip"
>
<div className={style.line}>
<ToggleButton
alwaysOn
value={this.state.xInsideOut}
icon={
this.state.xInsideOut
? style.insideOutToggleIconLeft
: style.insideOutToggleIconRight
}
name="xInsideOut"
onChange={this.toggleInsideOut}
style={{ width: '30px' }}
/>
<DoubleSliderElement
min={this.props.dataset.data.bounds[0]}
max={this.props.dataset.data.bounds[1]}
value={this.state.xPosition}
name="xPosition"
onChange={this.positionChange}
/>
</div>
<div className={style.line}>
<ToggleButton
alwaysOn
value={this.state.yInsideOut}
icon={
this.state.yInsideOut
? style.insideOutToggleIconLeft
: style.insideOutToggleIconRight
}
name="yInsideOut"
onChange={this.toggleInsideOut}
style={{ width: '30px' }}
/>
<DoubleSliderElement
min={this.props.dataset.data.bounds[2]}
max={this.props.dataset.data.bounds[3]}
value={this.state.yPosition}
name="yPosition"
onChange={this.positionChange}
/>
</div>
<div className={style.line}>
<ToggleButton
alwaysOn
value={this.state.zInsideOut}
icon={
this.state.zInsideOut
? style.insideOutToggleIconLeft
: style.insideOutToggleIconRight
}
name="zInsideOut"
onChange={this.toggleInsideOut}
style={{ width: '30px' }}
/>
<DoubleSliderElement
min={this.props.dataset.data.bounds[4]}
max={this.props.dataset.data.bounds[5]}
value={this.state.zPosition}
name="zPosition"
onChange={this.positionChange}
/>
</div>
</AbstractPanel>
);
}
}
ClipPanel.propTypes = {
dataset: PropTypes.object,
hideAdditionalControls: PropTypes.bool,
};
ClipPanel.defaultProps = {
dataset: {
data: {
bounds: [0, 1, 0, 1, 0, 1],
},
},
hideAdditionalControls: false,
};
|
src/containers/wrapper.js | MoveOnOrg/mop-frontend | import React from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { scrollToTop } from '../lib'
import { loadSession, loadCohort } from '../actions/sessionActions'
import { appLocation } from '../routes'
import { checkServerError } from '../actions/serverErrorActions'
import { Error404 } from 'Theme/error404'
import { Error500 } from 'Theme/error500'
import WrapperComponent from 'Theme/wrapper'
function hasRouteBool(name, routes) {
return !!routes[routes.length - 1][name]
}
class Wrapper extends React.Component {
componentDidMount() {
this.props.dispatch(checkServerError())
this.props.dispatch(loadSession(this.props.location))
this.props.dispatch(loadCohort(this.props.location))
}
componentDidUpdate() {
if (hasRouteBool('authenticated', this.props.routes)) {
this.checkAuthenticationAndRedirect()
}
if (this.props.error && this.props.error.response_code) {
// Normally we scroll to top on route change, however we can display an
// error without a route change
scrollToTop()
}
}
checkAuthenticationAndRedirect() {
const { user, location } = this.props
if (user.anonymous || user.authenticated === false) {
appLocation.push({
pathname: '/login/index.html',
query: {
redirect: location.pathname + (location.search || '')
}
})
}
}
render() {
const { petitionEntity, location, children, routes, error } = this.props
let entity = petitionEntity
if (location.pathname.indexOf('/pac/') !== -1) {
entity = 'pac'
}
return (
<WrapperComponent
entity={entity}
minimalNav={hasRouteBool('minimalNav', routes)}
hideNav={hasRouteBool('hideNav', routes)}
hideFooter={hasRouteBool('hideFooter', routes)}
offWhiteBg={hasRouteBool('offWhiteBg', routes)}
>
{error.response_code === 404 && <Error404 error={error} />}
{error.response_code === 500 && <Error500 error={error} />}
{!error.response_code && children}
</WrapperComponent>
)
}
}
Wrapper.propTypes = {
petitionEntity: PropTypes.string,
location: PropTypes.object,
children: PropTypes.object.isRequired,
routes: PropTypes.array.isRequired,
dispatch: PropTypes.func.isRequired,
user: PropTypes.object,
error: PropTypes.object
}
function mapStateToProps(store, ownProps) {
// Fetch the petition only if the route has a `petitionName` param
const name = ownProps.params && ownProps.params.petitionName
const petition = name && store.petitionStore.petitions[name.split('.')[0]]
return {
petitionEntity: petition && petition.entity,
user: store.userStore,
error: store.errorStore
}
}
export default connect(mapStateToProps)(Wrapper)
|
demo/App.js | saulshanabrook/cerebral | import React from 'react';
import {Decorator as Cerebral} from './CustomController.js';
import AddTodo from './components/AddTodo.js';
import TodosList from './components/TodosList.js';
import TodosFooter from './components/TodosFooter.js';
@Cerebral({
visibleTodos: ['visibleTodos'],
todos: ['todos']
})
class App extends React.Component {
record() {
this.props.recorder.record(this.props.get().export());
}
stop() {
this.props.recorder.stop();
}
play() {
this.props.recorder.seek(0, true);
}
render() {
return (
<div id="todoapp-wrapper">
<div>
{
this.props.recorder.isRecording() ?
<button className="btn btn-stop" onClick={() => this.stop()}>Stop</button> :
null
}
{
this.props.recorder.isPlaying() ?
<button className="btn btn-play" disabled>Play</button> :
null
}
{
!this.props.recorder.isRecording() && !this.props.recorder.isPlaying() && this.props.recorder.getRecording() ?
<button className="btn btn-play" onClick={() => this.play()}>Play</button> :
null
}
{
!this.props.recorder.isRecording() && !this.props.recorder.isPlaying() && !this.props.recorder.getRecording() ?
<button className="btn btn-record" onClick={() => this.record()}>Record</button> :
null
}
</div>
<section id="todoapp">
<header id="header">
<h1>todos</h1>
<AddTodo/>
</header>
{this.props.visibleTodos.length ? <TodosList/> : null}
{Object.keys(this.props.todos).length ? <TodosFooter/> : null}
</section>
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Credits:
<a href="http://christianalfoni.com">Christian Alfoni</a>,
</p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>
</div>
);
}
}
module.exports = App;
|
src/svg-icons/maps/local-laundry-service.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalLaundryService = (props) => (
<SvgIcon {...props}>
<path d="M9.17 16.83c1.56 1.56 4.1 1.56 5.66 0 1.56-1.56 1.56-4.1 0-5.66l-5.66 5.66zM18 2.01L6 2c-1.11 0-2 .89-2 2v16c0 1.11.89 2 2 2h12c1.11 0 2-.89 2-2V4c0-1.11-.89-1.99-2-1.99zM10 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM7 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm5 16c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"/>
</SvgIcon>
);
MapsLocalLaundryService = pure(MapsLocalLaundryService);
MapsLocalLaundryService.displayName = 'MapsLocalLaundryService';
MapsLocalLaundryService.muiName = 'SvgIcon';
export default MapsLocalLaundryService;
|
public/js/cat_source/es6/components/modals/ModifyTeam.js | riccio82/MateCat | import TeamConstants from '../../constants/TeamConstants'
import TeamsStore from '../../stores/TeamsStore'
import ManageActions from '../../actions/ManageActions'
import React from 'react'
class ModifyTeam extends React.Component {
constructor(props) {
super(props)
this.state = {
team: this.props.team,
inputUserError: false,
inputNameError: false,
showRemoveMessageUserID: null,
readyToSend: false,
resendInviteArray: [],
}
this.updateTeam = this.updateTeam.bind(this)
this.onLabelCreate = this.onLabelCreate.bind(this)
}
onLabelCreate(value, text) {
var self = this
// if ( APP.checkEmail(text) && event.key === 'Enter') {
if (APP.checkEmail(text)) {
$(this.inputNewUSer).dropdown('set selected', value)
this.setState({
inputUserError: false,
})
this.addUsers()
return true
} else if (text.indexOf(',') > -1) {
let members = text.split(',')
members.forEach(function (item) {
self.createLabel(item)
})
return false
} else {
this.createLabel(text)
return false
}
// else {
// this.setState({
// inputUserError: true
// });
// $(this.inputNewUSer).dropdown('set text', text);
// return false;
// }
}
createLabel(text) {
var self = this
if (APP.checkEmail(text)) {
$(this.inputNewUSer).find('input.search').val('')
$(this.inputNewUSer).dropdown('set selected', text)
this.setState({
inputUserError: false,
})
return true
} else if (text.indexOf(',') > -1) {
let members = text.split(',')
members.forEach(function (item) {
self.createLabel(item)
})
return false
} else {
this.setState({
inputUserError: true,
})
$(this.inputNewUSer).dropdown('set text', text)
return true
}
}
updateTeam(team) {
if (this.state.team.get('id') == team.get('id')) {
this.setState({
team: team,
})
}
}
showRemoveUser(userId) {
this.setState({
showRemoveMessageUserID: userId,
})
}
removeUser(user) {
ManageActions.removeUserFromTeam(this.state.team, user)
if (user.get('uid') === APP.USER.STORE.user.uid) {
APP.ModalWindow.onCloseModal()
}
this.setState({
showRemoveMessageUserID: null,
})
}
undoRemoveAction() {
this.setState({
showRemoveMessageUserID: null,
})
}
resendInvite(mail) {
ManageActions.addUserToTeam(this.state.team, mail)
var resendInviteArray = this.state.resendInviteArray
resendInviteArray.push(mail)
this.setState({
resendInviteArray: resendInviteArray,
})
}
handleKeyPressUserInput(e) {
let mail = $(this.inputNewUSer).find('input.search').val()
if (e.key == 'Enter') {
if (mail == '') {
this.addUsers()
}
return
}
if (e.key === ' ') {
e.stopPropagation()
e.preventDefault()
this.createLabel(mail)
} else {
this.setState({
inputUserError: false,
})
}
return false
}
addUsers() {
var members =
$(this.inputNewUSer).dropdown('get value').length > 0
? $(this.inputNewUSer).dropdown('get value').split(',')
: []
if (members.length > 0) {
ManageActions.addUserToTeam(this.state.team, members)
$(this.inputNewUSer).dropdown('restore defaults')
}
}
addUser() {
if (APP.checkEmail(this.inputNewUSer.value)) {
ManageActions.addUserToTeam(this.state.team, this.inputNewUSer.value)
var resendInviteArray = this.state.resendInviteArray
resendInviteArray.push(this.inputNewUSer.value)
this.inputNewUSer.value = ''
this.setState({
resendInviteArray: resendInviteArray,
})
return true
} else {
this.setState({
inputUserError: true,
})
return false
}
}
onKeyPressEvent(e) {
if (e.key === 'Enter') {
this.changeTeamName()
return false
} else if (this.inputName.value.length == 0) {
this.setState({
inputNameError: true,
})
} else {
this.setState({
inputNameError: false,
})
}
}
changeTeamName() {
if (
this.inputName &&
this.inputName.value.length > 0 &&
this.inputName.value != this.state.team.get('name')
) {
ManageActions.changeTeamName(this.state.team.toJS(), this.inputName.value)
$(this.inputName).blur()
this.setState({
readyToSend: true,
})
return true
} else if (this.inputName && this.inputName.value.length == 0) {
this.setState({
inputNameError: true,
})
return false
}
return true
}
applyChanges() {
var teamNameOk = this.changeTeamName()
if ($(this.inputNewUSer).dropdown('get value').length > 0) {
this.addUsers()
}
if (teamNameOk) {
APP.ModalWindow.onCloseModal()
}
}
getUserList() {
let self = this
return this.state.team.get('members').map(function (member, i) {
let user = member.get('user')
if (
user.get('uid') == APP.USER.STORE.user.uid &&
self.state.showRemoveMessageUserID == user.get('uid')
) {
if (self.state.team.get('members').size > 1) {
return (
<div className="item" key={'user' + user.get('uid')}>
<div className="right floated content top-5 bottom-5">
<div
className="ui mini primary button"
onClick={self.removeUser.bind(self, user)}
>
<i className="icon-check icon" />
Confirm
</div>
<div
className="ui icon mini button red"
onClick={self.undoRemoveAction.bind(self)}
>
<i className="icon-cancel3 icon" />
</div>
</div>
<div className="content pad-top-10 pad-bottom-8">
Are you sure you want to leave this team?
</div>
</div>
)
} else {
return (
<div className="item" key={'user' + user.get('uid')}>
<div className="right floated content top-20 bottom-5">
<div
className="ui mini primary button"
onClick={self.removeUser.bind(self, user)}
>
<i className="icon-check icon" />
Confirm
</div>
<div
className="ui icon mini button red"
onClick={self.undoRemoveAction.bind(self)}
>
<i className="icon-cancel3 icon" />
</div>
</div>
<div className="content pad-top-10 pad-bottom-8">
By removing the last member the team will be deleted. All
projects will be moved to your Personal area.
</div>
</div>
)
}
} else if (self.state.showRemoveMessageUserID == user.get('uid')) {
return (
<div className="item" key={'user' + user.get('uid')}>
<div className="right floated content top-5 bottom-5">
<div
className="ui mini primary button"
onClick={self.removeUser.bind(self, user)}
>
<i className="icon-check icon" /> Confirm
</div>
<div
className="mini ui icon button red"
onClick={self.undoRemoveAction.bind(self)}
>
<i className="icon-cancel3 icon" />
</div>
</div>
<div className="content pad-top-10 pad-bottom-8">
Are you sure you want to remove this user?
</div>
</div>
)
} else {
return (
<div className="item" key={'user' + user.get('uid')}>
<div
className="mini ui button right floated"
onClick={self.showRemoveUser.bind(self, user.get('uid'))}
>
Remove
</div>
{member.get('user_metadata') ? (
<img
className="ui mini circular image"
src={
member.get('user_metadata').get('gplus_picture') + '?sz=80'
}
/>
) : (
<div className="ui tiny image label">
{APP.getUserShortName(user.toJS())}
</div>
)}
<div className="middle aligned content">
<div className="content user">
{' ' + user.get('first_name') + ' ' + user.get('last_name')}
</div>
<div className="content email-user-invited">
{user.get('email')}
</div>
</div>
</div>
)
}
})
}
getPendingInvitations() {
let self = this
if (
!this.state.team.get('pending_invitations') ||
!this.state.team.get('pending_invitations').size > 0
)
return
return this.state.team.get('pending_invitations').map(function (mail, i) {
var inviteResended = self.state.resendInviteArray.indexOf(mail) > -1
return (
<div className="item pending-invitation" key={'user-invitation' + i}>
{inviteResended ? (
<div className="ui right floated content invite-sent-msg">
Invite sent
</div>
) : (
<div>
<div
className="mini ui button right floated"
onClick={self.resendInvite.bind(self, mail)}
>
Resend Invite
</div>
<div className="ui right floated content pending-msg">
Pending user
</div>
</div>
)}
<div className="ui tiny image label">
{mail.substring(0, 1).toUpperCase()}
</div>
<div className="middle aligned content">
<div className="content user">{mail}</div>
</div>
</div>
)
})
}
componentDidUpdate() {
var self = this
clearTimeout(this.inputTimeout)
if (this.state.readyToSend) {
this.inputTimeout = setTimeout(function () {
self.setState({
readyToSend: false,
})
}, 1000)
}
}
componentDidMount() {
$(this.inputNewUSer).dropdown({
allowAdditions: true,
action: this.onLabelCreate,
})
TeamsStore.addListener(TeamConstants.UPDATE_TEAM, this.updateTeam)
}
componentWillUnmount() {
TeamsStore.removeListener(TeamConstants.UPDATE_TEAM, this.updateTeam)
}
shouldComponentUpdate(nextProps, nextState) {
return (
nextState.team !== this.state.team ||
nextState.inputUserError !== this.state.inputUserError ||
nextState.inputNameError !== this.state.inputNameError ||
nextState.showRemoveMessageUserID !==
this.state.showRemoveMessageUserID ||
nextState.readyToSend !== this.state.readyToSend
)
}
render() {
let usersError = this.state.inputUserError ? 'error' : ''
let orgNameError = this.state.inputNameError ? 'error' : ''
let userlist = this.getUserList()
let pendingUsers = this.getPendingInvitations()
let icon =
this.state.readyToSend && !this.state.inputNameError ? (
<i className="icon-checkmark green icon" />
) : (
<i className="icon-pencil icon" />
)
let applyButtonClass =
this.state.inputUserError || this.state.inputNameError ? 'disabled' : ''
let middleContainerStyle = this.props.hideChangeName
? {paddingTop: '20px'}
: {}
return (
<div className="modify-team-modal">
{!this.props.hideChangeName ? (
<div className="matecat-modal-top">
<div className="ui one column grid left aligned">
<div className="column">
<h2>Change Team Name</h2>
<div className={'ui fluid icon input ' + orgNameError}>
<input
type="text"
defaultValue={this.state.team.get('name')}
onKeyUp={this.onKeyPressEvent.bind(this)}
ref={(inputName) => (this.inputName = inputName)}
/>
{icon}
</div>
{this.state.inputNameError ? (
<div className="validation-error">
<span
className="text"
style={{color: 'red', fontSize: '14px'}}
>
Team name is required
</span>
</div>
) : (
''
)}
</div>
</div>
</div>
) : (
''
)}
{this.state.team.get('type') !== 'personal' ? (
<div className="matecat-modal-middle" style={middleContainerStyle}>
<div className="ui grid left aligned">
<div className="sixteen wide column">
<h2>Invite Members</h2>
{/* <div className={"ui fluid icon input " + usersError }>
<input type="text" placeholder="insert email and press enter"
onKeyUp={this.handleKeyPressUserInput.bind(this)}
ref={(inputNewUSer) => this.inputNewUSer = inputNewUSer}/>
</div>
{this.state.inputUserError ? (
<div className="validation-error"><span className="text" style={{color: 'red', fontSize: '14px'}}>A valid email is required</span></div>
): ''}*/}
<div
className={
'ui multiple search selection dropdown ' + usersError
}
onKeyUp={this.handleKeyPressUserInput.bind(this)}
ref={(inputNewUSer) => (this.inputNewUSer = inputNewUSer)}
>
<input name="tags" type="hidden" />
<div className="default text">
insert email or emails separated by commas or press enter
</div>
</div>
{this.state.inputUserError ? (
<div className="validation-error">
<span
className="text"
style={{color: 'red', fontSize: '14px'}}
>
A valid email is required
</span>
</div>
) : (
''
)}
</div>
<div className="sixteen wide column">
<div className="ui members-list team">
<div className="ui divided list">
{pendingUsers}
{userlist}
</div>
</div>
</div>
</div>
</div>
) : (
''
)}
<div className="matecat-modal-bottom">
<div className="ui one column grid right aligned">
<div className="column">
<button
className={
'create-team ui primary button open ' + applyButtonClass
}
onClick={this.applyChanges.bind(this)}
>
Close
</button>
</div>
</div>
</div>
</div>
)
}
}
export default ModifyTeam
|
src/Alert.js | egauci/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import bootstrapUtils, { bsStyles, bsClass } from './utils/bootstrapUtils';
import { State } from './styleMaps';
let Alert = React.createClass({
propTypes: {
onDismiss: React.PropTypes.func,
dismissAfter: React.PropTypes.number,
closeLabel: React.PropTypes.string
},
getDefaultProps() {
return {
closeLabel: 'Close Alert'
};
},
renderDismissButton() {
return (
<button
type="button"
className="close"
onClick={this.props.onDismiss}
aria-hidden="true"
tabIndex="-1">
<span>×</span>
</button>
);
},
renderSrOnlyDismissButton() {
return (
<button
type="button"
className="close sr-only"
onClick={this.props.onDismiss}>
{this.props.closeLabel}
</button>
);
},
render() {
let classes = bootstrapUtils.getClassSet(this.props);
let isDismissable = !!this.props.onDismiss;
classes[bootstrapUtils.prefix(this.props, 'dismissable')] = isDismissable;
return (
<div {...this.props} role="alert" className={classNames(this.props.className, classes)}>
{isDismissable ? this.renderDismissButton() : null}
{this.props.children}
{isDismissable ? this.renderSrOnlyDismissButton() : null}
</div>
);
},
componentDidMount() {
if (this.props.dismissAfter && this.props.onDismiss) {
this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter);
}
},
componentWillUnmount() {
clearTimeout(this.dismissTimer);
}
});
export default bsStyles(State.values(), State.INFO,
bsClass('alert', Alert)
);
|
docs/app/Examples/elements/Segment/Variations/SegmentExampleEmphasis.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Segment } from 'semantic-ui-react'
const SegmentExampleEmphasis = () => (
<div>
<Segment>
I'm here to tell you something, and you will probably read me first.
</Segment>
<Segment secondary>
I am pretty noticeable but you might check out other content before you look at me.
</Segment>
<Segment tertiary>
If you notice me you must be looking very hard.
</Segment>
</div>
)
export default SegmentExampleEmphasis
|
modules/gui/src/app/home/map/labelsLayer.js | openforis/sepal | import {GoogleLabelsLayer} from './layer/googleLabelsLayer'
import PropTypes from 'prop-types'
import React from 'react'
export class LabelsLayer extends React.Component {
render() {
return null
}
componentDidMount() {
this.setLayer()
}
componentDidUpdate() {
this.setLayer()
}
componentWillUnmount() {
const {id, map} = this.props
map.removeLayer(id)
}
setLayer() {
const {id, layerIndex, map} = this.props
const layer = new GoogleLabelsLayer({map, layerIndex})
map.setLayer({id, layer})
}
}
LabelsLayer.propTypes = {
id: PropTypes.string.isRequired,
layerIndex: PropTypes.number,
map: PropTypes.any
}
|
app/javascript/mastodon/features/notifications/components/setting_toggle.js | palon7/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
export default class SettingToggle extends React.PureComponent {
static propTypes = {
prefix: PropTypes.string,
settings: ImmutablePropTypes.map.isRequired,
settingKey: PropTypes.array.isRequired,
label: PropTypes.node.isRequired,
meta: PropTypes.node,
onChange: PropTypes.func.isRequired,
}
onChange = ({ target }) => {
this.props.onChange(this.props.settingKey, target.checked);
}
onKeyDown = e => {
if (e.key === ' ') {
this.props.onChange(this.props.settingKey, !e.target.checked);
}
}
render () {
const { prefix, settings, settingKey, label, meta } = this.props;
const id = ['setting-toggle', prefix, ...settingKey].filter(Boolean).join('-');
return (
<div className='setting-toggle'>
<Toggle id={id} checked={settings.getIn(settingKey)} onChange={this.onChange} onKeyDown={this.onKeyDown} />
<label htmlFor={id} className='setting-toggle__label'>{label}</label>
{meta && <span className='setting-meta__label'>{meta}</span>}
</div>
);
}
}
|
services/product-list/src/index.js | slamdev/catalog | import React from 'react'
import {render} from 'react-dom';
import ProductPageContainer from './ProductPageContainer';
window.customElements.define('product-list', class ProductList extends HTMLElement {
static get observedAttributes() {
return ['error-mode', 'title'];
}
getTitle() {
return this.getAttribute('title');
}
get errorMode() {
return this.hasAttribute('error-mode');
}
set errorMode(val) {
if (val) {
this.setAttribute('error-mode', '');
} else {
this.removeAttribute('error-mode');
}
}
produceError(e) {
this.dispatchEvent(new CustomEvent('error', {detail: e}));
}
constructor() {
super();
console.log('ReactApp constructor', this);
}
connectedCallback() {
try {
if (this.errorMode) {
throw new Error('Application failed at load');
}
} catch (e) {
this.produceError(e);
return;
}
console.log('ReactApp connected');
this.render();
}
render() {
render(<ProductPageContainer/>, this);
}
disconnectedCallback() {
console.log('ReactApp disconnected',);
}
attributeChangedCallback(attrName, oldVal, newVal) {
console.log('ReactApp attributeChanged', attrName, oldVal, newVal);
switch (attrName) {
case 'title':
this.render();
}
}
});
|
service_2/src/app-client.js | cleverbridge/spike_living_styleguide | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from './components/app_routes';
window.onload = () => {
ReactDOM.render(<AppRoutes/>, document.getElementById('main'));
}; |
packages/mineral-ui-icons/src/IconSuccess.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 IconSuccess(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M12 3c4.968 0 9 4.032 9 9s-4.032 9-9 9-9-4.032-9-9 4.032-9 9-9zm-4.247 8.445L6.5 12.698l3.838 3.838 7.198-7.198-1.253-1.254-5.945 5.945-2.585-2.585z"/>
</g>
</Icon>
);
}
IconSuccess.displayName = 'IconSuccess';
IconSuccess.category = 'alert';
|
apps/app/src/components/Loader.js | argos-ci/argos | import React from 'react'
import { Box } from '@xstyled/styled-components'
export const Loader = props => (
<Box
forwardedAs="svg"
width="2rem"
height="2rem"
viewBox="0 0 135 140"
fill="currentColor"
{...props}
>
<rect y={10} width={15} height={120} rx={6}>
<animate
attributeName="height"
begin="0.5s"
dur="1s"
values="120;110;100;90;80;70;60;50;40;140;120"
calcMode="linear"
repeatCount="indefinite"
/>
<animate
attributeName="y"
begin="0.5s"
dur="1s"
values="10;15;20;25;30;35;40;45;50;0;10"
calcMode="linear"
repeatCount="indefinite"
/>
</rect>
<rect x={30} y={10} width={15} height={120} rx={6}>
<animate
attributeName="height"
begin="0.25s"
dur="1s"
values="120;110;100;90;80;70;60;50;40;140;120"
calcMode="linear"
repeatCount="indefinite"
/>
<animate
attributeName="y"
begin="0.25s"
dur="1s"
values="10;15;20;25;30;35;40;45;50;0;10"
calcMode="linear"
repeatCount="indefinite"
/>
</rect>
<rect x={60} width={15} height={140} rx={6}>
<animate
attributeName="height"
begin="0s"
dur="1s"
values="120;110;100;90;80;70;60;50;40;140;120"
calcMode="linear"
repeatCount="indefinite"
/>
<animate
attributeName="y"
begin="0s"
dur="1s"
values="10;15;20;25;30;35;40;45;50;0;10"
calcMode="linear"
repeatCount="indefinite"
/>
</rect>
<rect x={90} y={10} width={15} height={120} rx={6}>
<animate
attributeName="height"
begin="0.25s"
dur="1s"
values="120;110;100;90;80;70;60;50;40;140;120"
calcMode="linear"
repeatCount="indefinite"
/>
<animate
attributeName="y"
begin="0.25s"
dur="1s"
values="10;15;20;25;30;35;40;45;50;0;10"
calcMode="linear"
repeatCount="indefinite"
/>
</rect>
<rect x={120} y={10} width={15} height={120} rx={6}>
<animate
attributeName="height"
begin="0.5s"
dur="1s"
values="120;110;100;90;80;70;60;50;40;140;120"
calcMode="linear"
repeatCount="indefinite"
/>
<animate
attributeName="y"
begin="0.5s"
dur="1s"
values="10;15;20;25;30;35;40;45;50;0;10"
calcMode="linear"
repeatCount="indefinite"
/>
</rect>
</Box>
)
|
src/svg-icons/hardware/watch.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareWatch = (props) => (
<SvgIcon {...props}>
<path d="M20 12c0-2.54-1.19-4.81-3.04-6.27L16 0H8l-.95 5.73C5.19 7.19 4 9.45 4 12s1.19 4.81 3.05 6.27L8 24h8l.96-5.73C18.81 16.81 20 14.54 20 12zM6 12c0-3.31 2.69-6 6-6s6 2.69 6 6-2.69 6-6 6-6-2.69-6-6z"/>
</SvgIcon>
);
HardwareWatch = pure(HardwareWatch);
HardwareWatch.displayName = 'HardwareWatch';
HardwareWatch.muiName = 'SvgIcon';
export default HardwareWatch;
|
examples/redux/components/Github.js | dlmr/react-router-redial | import React, { Component } from 'react';
import { Link } from 'react-router';
export default class Github extends Component {
constructor(props) {
super(props);
this.state = { value: '' };
}
onChange = (e) => {
this.setState({ value: e.target.value.toLowerCase() });
};
render() {
return (
<div>
<h2>Github</h2>
<div>
<p>Please select a user by typing and clicking the link</p>
<input onChange={this.onChange} />
<Link to={{ pathname: `/github/user/${this.state.value}` }}>Open user!</Link>
</div>
{this.props.children}
</div>
);
}
}
|
create-react-app/src/index.js | highmind/Study | 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/routes/Counter/components/Counter.js | Havoc-Todo/havoc-web | import React from 'react'
export const Counter = (props) => (
<div style={{ margin: '0 auto' }} >
<h2>Counter: {props.count}, Clicks: {props.clicks}</h2>
<button className='btn btn-default' onClick={() => {
props.increment()
props.click()
}}>
Increment
</button>
{' '}
<button className='btn btn-default' onClick={() => {
props.doubleAsync()
props.click()
}}>
Double (Async)
</button>
{' '}
<button className='btn btn-default' onClick={() => {
props.triple()
props.click()
}}>
Triple
</button>
</div>
)
Counter.propTypes = {
count : React.PropTypes.number.isRequired,
clicks : React.PropTypes.number.isRequired,
doubleAsync : React.PropTypes.func.isRequired,
increment : React.PropTypes.func.isRequired,
click : React.PropTypes.func.isRequired,
triple : React.PropTypes.func.isRequired
}
export default Counter
|
src/svg-icons/toggle/check-box-outline-blank.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ToggleCheckBoxOutlineBlank = (props) => (
<SvgIcon {...props}>
<path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
ToggleCheckBoxOutlineBlank = pure(ToggleCheckBoxOutlineBlank);
ToggleCheckBoxOutlineBlank.displayName = 'ToggleCheckBoxOutlineBlank';
ToggleCheckBoxOutlineBlank.muiName = 'SvgIcon';
export default ToggleCheckBoxOutlineBlank;
|
app/jsx/calendar/scheduler/components/FindAppointment.js | djbender/canvas-lms | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import {Button} from '@instructure/ui-buttons'
import Modal from '../../../shared/components/InstuiModal'
import I18n from 'i18n!react_scheduler'
import Actions from '../actions'
import preventDefault from 'compiled/fn/preventDefault'
export default class FindAppointment extends React.Component {
static propTypes = {
courses: PropTypes.array.isRequired,
store: PropTypes.object.isRequired
}
state = {
isModalOpen: false,
selectedCourse: {}
}
handleSubmit() {
this.props.store.dispatch(Actions.actions.setCourse(this.state.selectedCourse))
this.props.store.dispatch(
Actions.actions.setFindAppointmentMode(!this.props.store.getState().inFindAppointmentMode)
)
this.setState({
isModalOpen: false,
selectedCourse: {}
})
}
selectCourse(courseId) {
this.setState({
selectedCourse: this.props.courses.filter(c => c.id === courseId)[0]
})
}
openModal() {
this.setState({
isModalOpen: true,
selectedCourse: this.props.courses.length > 0 ? this.props.courses[0] : {}
})
}
endAppointmentMode() {
this.props.store.dispatch(Actions.actions.setFindAppointmentMode(false))
this.setState({isModalOpen: false})
}
render() {
return (
<div>
<h2>{I18n.t('Appointments')}</h2>
{this.props.store.getState().inFindAppointmentMode ? (
<button
onClick={() => this.endAppointmentMode()}
id="FindAppointmentButton"
className="Button"
>
{I18n.t('Close')}
</button>
) : (
<button onClick={() => this.openModal()} id="FindAppointmentButton" className="Button">
{I18n.t('Find Appointment')}
</button>
)}
<Modal
as="form"
onSubmit={preventDefault(() => this.handleSubmit())}
open={this.state.isModalOpen}
size="small"
onDismiss={() => this.setState({isModalOpen: false})}
label={I18n.t('Select Course')}
>
<Modal.Body>
<div className="ic-Form-control">
<select
onChange={e => this.selectCourse(e.target.value)}
value={this.state.selectedCourse.id}
className="ic-Input"
>
{this.props.courses.map(c => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
</div>
</Modal.Body>
<Modal.Footer>
<Button variant="primary" type="submit">
{I18n.t('Submit')}
</Button>
</Modal.Footer>
</Modal>
</div>
)
}
}
|
src/components/Credits/Credits.stories.js | wfp/ui | import React from 'react';
import Credits from '../Credits';
import markdown from './README.mdx';
export default {
title: 'Components/UI Elements/Credits',
component: Credits,
parameters: {
componentSubtitle: 'Component',
status: 'released',
mdx: markdown,
},
/*argTypes: {
children: { control: 'text' },
},*/
};
export const RegularCredits = (args) => (
<Credits {...args}>
<img
alt="Default illustration"
src="http://www1.wfp.org/sites/default/files/images/hp_yem_20170717_wfp-reem_nada_0109_3.jpg"
/>
</Credits>
);
RegularCredits.args = {
children: 'Credits',
info: 'Photo: WFP/ Rein Skullerud',
};
|
example/src/components/bar.js | jerairrest/react-chartjs-2 | import React from 'react';
import {Bar} from 'react-chartjs-2';
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'My First dataset',
backgroundColor: 'rgba(255,99,132,0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
export default React.createClass({
displayName: 'BarExample',
render() {
return (
<div>
<h2>Bar Example (custom size)</h2>
<Bar
data={data}
width={100}
height={50}
options={{
maintainAspectRatio: false
}}
/>
</div>
);
}
});
|
docs-ui/components/emptyStateWarning.stories.js | ifduyue/sentry | import React from 'react';
import {storiesOf} from '@storybook/react';
import {withInfo} from '@storybook/addon-info';
import EmptyStateWarning from 'app/components/emptyStateWarning';
storiesOf('EmptyStateWarning', module).add(
'default',
withInfo('Default')(() => (
<EmptyStateWarning data="https://example.org/foo/bar/">
<p>There are no events found!</p>
</EmptyStateWarning>
))
);
|
hackupc/node_modules/react-router/es/Redirect.js | IKholopov/HackUPC2017 | import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { formatPattern } from './PatternUtils';
import { falsy } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes,
string = _React$PropTypes.string,
object = _React$PropTypes.object;
/**
* A <Redirect> is used to declare another URL path a client should
* be sent to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration
* and are traversed in the same manner.
*/
/* eslint-disable react/require-render-return */
var Redirect = React.createClass({
displayName: 'Redirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element) {
var route = _createRouteFromReactElement(element);
if (route.from) route.path = route.from;
route.onEnter = function (nextState, replace) {
var location = nextState.location,
params = nextState.params;
var pathname = void 0;
if (route.to.charAt(0) === '/') {
pathname = formatPattern(route.to, params);
} else if (!route.to) {
pathname = location.pathname;
} else {
var routeIndex = nextState.routes.indexOf(route);
var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1);
var pattern = parentPattern.replace(/\/*$/, '/') + route.to;
pathname = formatPattern(pattern, params);
}
replace({
pathname: pathname,
query: route.query || location.query,
state: route.state || location.state
});
};
return route;
},
getRoutePattern: function getRoutePattern(routes, routeIndex) {
var parentPattern = '';
for (var i = routeIndex; i >= 0; i--) {
var route = routes[i];
var pattern = route.path || '';
parentPattern = pattern.replace(/\/*$/, '/') + parentPattern;
if (pattern.indexOf('/') === 0) break;
}
return '/' + parentPattern;
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Redirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default Redirect; |
app/components/MyContribute.js | Toreant/monster_web | /**
* Created by apache on 15-12-15.
*/
import React from 'react';
import MyContributeActions from '../actions/MyContributeActions';
import MyContributeStore from '../stores/MyContributeStore';
import {Link} from 'react-router';
import Loading from './Loading';
class MyContribute extends React.Component {
constructor(props) {
super(props);
this.state = MyContributeStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
MyContributeStore.listen(this.onChange);
MyContributeActions.getContribute(this.props.params.column,0);
}
componentDidUpdate(prevProps) {
if(prevProps.params.column !== this.props.params.column) {
MyContributeActions.getContribute(this.props.params.column,0);
}
}
componentWillUnmount() {
MyContributeStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
delete(column,_id,target) {
MyContributeActions.delete(column,_id,'#'+target);
}
update(column,_id) {
MyContributeActions.get(column,_id);
}
render() {
let List;
if(this.state.loading) {
List = <Loading />;
} else if(this.state.list.length !== 0) {
List = this.state.list.map((data,index) => {
let option = 'article';
switch(this.props.params.column) {
case 'articles' :
option = 'article';
break;
case 'musics' :
option = 'music';
break;
case 'animtes' :
option = 'animate';
break;
}
return (
<div id={"myContribute_"+data.data._id} className="media mon-conlist-item" key={'contribute:'+data.data._id}>
<div className="media-left">
<Link to={'/'+option+'/'+data.data._id}>
<img src={data.data.abbreviations || '/img/abbreviations.png'} alt="loading" width='80'/>
</Link>
</div>
<div className="media-body">
<Link to={'/'+option+'/'+data.data._id} className='text-primary mon-conlist-title'>
{data.data.title}
</Link>
<p className='text-muted mon-conlist-info'>
<span>投稿日期:{new Date(data.data.create_time).toLocaleDateString()}</span>
<span>浏览次数:{data.data.browser_count}</span>
</p>
<p className='text-muted'>
{data.data.summary}
</p>
<div className="mon-fixed-btn">
<button className="btn btn-danger" onClick={this.delete.bind(this,option,data.data._id,"myContribute_"+data.data._id)}>
删除
</button>
<button className="btn btn-primary" onClick={this.update.bind(this,option,data.data._id)}>
更改
</button>
</div>
</div>
<span className='mon-conlist-index'>{index+1}</span>
</div>
);
});
} else if(this.state.error) {
List = (
<div>
<a href="javascript:;">
<span className="fa fa-circle"></span>
刷新
</a>
</div>
);
}
return (
<div className='animated flipInX mon-contribute'>
{List}
</div>
);
}
}
export default MyContribute; |
information/blendle-frontend-react-source/app/modules/deeplink/components/DeeplinkHeader.js | BramscoChill/BlendleParser | import React from 'react';
import PropTypes from 'prop-types';
import Settings from 'controllers/settings';
import { translate, translateElement } from 'instances/i18n';
import LogoLink from 'components/navigation/LogoLink';
import BrowserEnvironment from 'instances/browser_environment';
import LoginDropdownContainer from 'containers/navigation/LoginDropdownContainer';
export default class DeeplinkHeader extends React.Component {
static propTypes = {
variant: PropTypes.oneOf(['login', 'signUp']),
onToSignUp: PropTypes.func.isRequired,
};
openLoginDropdown() {
if (this.refs.loginDropdown) {
this.refs.loginDropdown.openLoginDropdown();
}
}
openReset() {
if (this.refs.loginDropdown) {
this.refs.loginDropdown.openLoginDropdown('resetPassword');
}
}
_renderLogo() {
const { width, height } = BrowserEnvironment.isMobile()
? { width: 70, height: 19 }
: { width: 84, height: 22 };
return <LogoLink height={height} width={width} />;
}
_renderSignUpHeader() {
return (
<div className="v-primary-navigation">
{this._renderLogo()}
<div className="deeplink-login">
<LoginDropdownContainer className="deeplink-login-dropdown" ref="loginDropdown" />
</div>
</div>
);
}
_renderLoginHeader() {
return (
<div className="v-primary-navigation">
{this._renderLogo()}
<div className="deeplink-login">
<p>{translateElement('deeplink.header.no_account')} </p>
<a className="btn btn-green btn-signup" href="#" onClick={this.props.onToSignUp}>
{translateElement('deeplink.header.signup')}
</a>
</div>
</div>
);
}
render() {
let headerFn = this._renderSignUpHeader;
if (this.props.variant === 'login') {
headerFn = this._renderLoginHeader;
}
return <div className="v-deeplink-header">{headerFn.call(this)}</div>;
}
}
// WEBPACK FOOTER //
// ./src/js/app/modules/deeplink/components/DeeplinkHeader.js |
src/svg-icons/device/settings-system-daydream.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSettingsSystemDaydream = (props) => (
<SvgIcon {...props}>
<path d="M9 16h6.5c1.38 0 2.5-1.12 2.5-2.5S16.88 11 15.5 11h-.05c-.24-1.69-1.69-3-3.45-3-1.4 0-2.6.83-3.16 2.02h-.16C7.17 10.18 6 11.45 6 13c0 1.66 1.34 3 3 3zM21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02z"/>
</SvgIcon>
);
DeviceSettingsSystemDaydream = pure(DeviceSettingsSystemDaydream);
DeviceSettingsSystemDaydream.displayName = 'DeviceSettingsSystemDaydream';
DeviceSettingsSystemDaydream.muiName = 'SvgIcon';
export default DeviceSettingsSystemDaydream;
|
src/components/common/svg-icons/action/watch-later.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionWatchLater = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm4.2 14.2L11 13V7h1.5v5.2l4.5 2.7-.8 1.3z"/>
</SvgIcon>
);
ActionWatchLater = pure(ActionWatchLater);
ActionWatchLater.displayName = 'ActionWatchLater';
ActionWatchLater.muiName = 'SvgIcon';
export default ActionWatchLater;
|
jenkins-design-language/src/js/components/material-ui/svg-icons/navigation/close.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const NavigationClose = (props) => (
<SvgIcon {...props}>
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
</SvgIcon>
);
NavigationClose.displayName = 'NavigationClose';
NavigationClose.muiName = 'SvgIcon';
export default NavigationClose;
|
js/components/home/jobAlert.js | baskoropn/kerjain |
import React, { Component } from 'react';
import { Image, TouchableOpacity } from 'react-native';
import { Container, Content, Card, CardItem, Text, View, Body, List, ListItem, Icon, Right, Button, Label, DeckSwiper, Left, Thumbnail } from 'native-base';
import styles from './styles';
const dataon = require('../../../img/companyLogo/dataon.jpg');
const traveloka = require('../../../img/companyLogo/traveloka.jpg');
const bukalapak = require('../../../img/companyLogo/bukalapak.jpg');
const datas = [
{
img : dataon,
time: '10 minutes ago',
jobPosition: 'Software Developer',
companyName : 'PT Indodev Niaga',
salary : 'IDR 5.000.000 - 7.000.000',
location : 'Tangerang Selatan - Bintaro',
},
{
img : traveloka,
time: '17 minutes ago',
jobPosition: 'Project Manager',
companyName : 'PT Traveloka',
salary : 'IDR 6.000.000 - 8.000.000',
location : 'Jakarta Barat - Slipi',
},
{
img : bukalapak,
time: '5 Agustus 2017',
jobPosition: 'Quality Insurance',
companyName : 'PT BukaLapak',
salary : 'IDR 4.000.000 - 6.000.000',
location : 'Jakarta Selatan - Kemang',
},
];
export default class JobAlert extends Component { // eslint-disable-line
render() { // eslint-disable-line
return (
<Content style={{backgroundColor : '#E0E0E0'}}>
<View style={{height : 500}}>
<View style={{flexDirection : 'row', marginBottom : 20, marginTop : 20}}>
<Text style={{color : '#189DAE', fontSize : 18}}> Trending Jobs </Text>
<Right>
<Icon name="search" style={{marginRight : 20, color : '#189DAE'}}/>
</Right>
</View >
<DeckSwiper
dataSource={datas}
renderItem={item =>
<Card style={{ elevation: 3, marginBottom : 20, marginRight : 20, marginLeft : 20}}>
<CardItem>
<Text style={{color : 'grey'}}>{item.time}</Text>
</CardItem>
<View style={{alignItems : 'center'}}>
<CardItem>
<Thumbnail large source={item.img} style={{height : 60, width : 100}} />
</CardItem>
<CardItem>
<View style={{alignItems : 'center'}}>
<Body>
<Text style={{fontSize : 20, color : '#189DAE'}}>{item.companyName}</Text>
<Text style= {{marginTop : 20}}>{item.jobPosition}</Text>
<View style={{flexDirection : 'row'}}>
<Icon name="cash"/>
<Text> {item.salary}</Text>
</View>
<View style={{flexDirection : 'row'}}>
<Icon name="pin"/>
<Text> {item.location}</Text>
</View>
</Body>
</View>
</CardItem>
<CardItem style={{backgroundColor : '#ecf0f1'}}>
<View style={{flexDirection : 'row', flex : 2, alignItems : 'center'}}>
<Button info style={{flex : 1, marginRight : 5, marginLeft : 5}}>
<Text style={{fontSize : 12}}> Not Interested</Text>
</Button>
<Button info style={{flex : 1, marginRight : 5, marginLeft : 5}}>
<Text style={{fontSize : 12}}> Apply</Text>
</Button>
</View>
</CardItem>
</View>
</Card>
}
/>
</View>
</Content>
);
}
}
|
fields/types/cloudinaryimages/CloudinaryImagesField.js | developer-prosenjit/keystone | import _ from 'underscore';
import React from 'react';
import Field from '../Field';
import { Button, FormField, FormInput, FormNote } from 'elemental';
const SUPPORTED_TYPES = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/x-icon', 'application/pdf', 'image/x-tiff', 'image/x-tiff', 'application/postscript', 'image/vnd.adobe.photoshop', 'image/svg+xml'];
var Thumbnail = React.createClass({
displayName: 'CloudinaryImagesFieldThumbnail',
propTypes: {
deleted: React.PropTypes.bool,
height: React.PropTypes.number,
isQueued: React.PropTypes.bool,
shouldRenderActionButton: React.PropTypes.bool,
toggleDelete: React.PropTypes.func,
url: React.PropTypes.string,
width: React.PropTypes.number,
},
renderActionButton () {
if (!this.props.shouldRenderActionButton || this.props.isQueued) return null;
return <Button type={this.props.deleted ? 'link-text' : 'link-cancel'} block onClick={this.props.toggleDelete}>{this.props.deleted ? 'Undo' : 'Remove'}</Button>;
},
render () {
var iconClassName;
if (this.props.deleted) {
iconClassName = 'delete-pending mega-octicon octicon-x';
} else if (this.props.isQueued) {
iconClassName = 'img-uploading mega-octicon octicon-cloud-upload';
}
var previewClassName = 'image-preview';
if (this.props.deleted || this.props.isQueued) previewClassName += ' action';
var title = '';
var width = this.props.width;
var height = this.props.height;
if (width && height) title = width + ' x ' + height;
return (
<div className="image-field image-sortable row col-sm-3 col-md-12" title={title}>
<div className={previewClassName}>
<a href={this.props.url} className="img-thumbnail" target="__blank">
<img style={{ height: '90' }} className="img-load" src={this.props.url} />
<span className={iconClassName} />
</a>
</div>
{this.renderActionButton()}
</div>
);
}
});
module.exports = Field.create({
getInitialState () {
var thumbnails = [];
var self = this;
_.each(this.props.value, function (item) {
self.pushThumbnail(item, thumbnails);
});
return { thumbnails: thumbnails };
},
removeThumbnail (i) {
var thumbs = this.state.thumbnails;
var thumb = thumbs[i];
if (thumb.props.isQueued) {
thumbs[i] = null;
} else {
thumb.props.deleted = !thumb.props.deleted;
}
this.setState({ thumbnails: thumbs });
},
pushThumbnail (args, thumbs) {
thumbs = thumbs || this.state.thumbnails;
var i = thumbs.length;
args.toggleDelete = this.removeThumbnail.bind(this, i);
args.shouldRenderActionButton = this.shouldRenderField();
thumbs.push(<Thumbnail key={i} {...args} />);
},
fileFieldNode () {
return this.refs.fileField.getDOMNode();
},
getCount (key) {
var count = 0;
_.each(this.state.thumbnails, function (thumb) {
if (thumb && thumb.props[key]) count++;
});
return count;
},
renderFileField () {
if (!this.shouldRenderField()) return null;
return <input ref="fileField" type="file" name={this.props.paths.upload} multiple className="field-upload" onChange={this.uploadFile} tabIndex="-1" />;
},
clearFiles () {
this.fileFieldNode().value = '';
this.setState({
thumbnails: this.state.thumbnails.filter(function (thumb) {
return !thumb.props.isQueued;
})
});
},
uploadFile (event) {
var self = this;
var files = event.target.files;
_.each(files, function (f) {
if (!_.contains(SUPPORTED_TYPES, f.type)) {
alert('Unsupported file type. Supported formats are: GIF, PNG, JPG, BMP, ICO, PDF, TIFF, EPS, PSD, SVG');
return;
}
if (window.FileReader) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
self.pushThumbnail({ isQueued: true, url: e.target.result });
self.forceUpdate();
};
fileReader.readAsDataURL(f);
} else {
self.pushThumbnail({ isQueued: true, url: '#' });
self.forceUpdate();
}
});
},
changeImage () {
this.fileFieldNode().click();
},
hasFiles () {
return this.refs.fileField && this.fileFieldNode().value;
},
renderToolbar () {
if (!this.shouldRenderField()) return null;
var body = [];
var push = function (queueType, alertType, count, action) {
if (count <= 0) return;
var imageText = count === 1 ? 'image' : 'images';
body.push(<div key={queueType + '-toolbar'} className={queueType + '-queued' + ' u-float-left'}>
<FormInput noedit>{count} {imageText} {action} - save to confirm</FormInput>
</div>);
};
push('upload', 'success', this.getCount('isQueued'), 'queued for upload');
push('delete', 'danger', this.getCount('deleted'), 'removed');
var clearFilesButton;
if (this.hasFiles()) {
clearFilesButton = <Button type="link-cancel" onClick={this.clearFiles} className="ml-5">Clear selection</Button>;
}
return (
<div className="images-toolbar">
<div className="u-float-left">
<Button onClick={this.changeImage}>Select files</Button>
{clearFilesButton}
</div>
{body}
</div>
);
},
renderPlaceholder () {
return (
<div className="image-field image-upload row col-sm-3 col-md-12" onClick={this.changeImage}>
<div className="image-preview">
<span className="img-thumbnail">
<span className="img-dropzone" />
<div className="img-uploading mega-octicon octicon-file-media" />
</span>
</div>
<div className="image-details">
<span className="image-message">Click to upload</span>
</div>
</div>
);
},
renderContainer () {
return (
<div className="images-container">
{this.state.thumbnails}
</div>
);
},
renderFieldAction () {
if (!this.shouldRenderField()) return null;
var value = '';
var remove = [];
_.each(this.state.thumbnails, function (thumb) {
if (thumb && thumb.props.deleted) remove.push(thumb.props.public_id);
});
if (remove.length) value = 'remove:' + remove.join(',');
return <input ref="action" className="field-action" type="hidden" value={value} name={this.props.paths.action} />;
},
renderUploadsField () {
if (!this.shouldRenderField()) return null;
return <input ref="uploads" className="field-uploads" type="hidden" name={this.props.paths.uploads} />;
},
renderNote () {
if (!this.props.note) return null;
return <FormNote note={this.props.note} />;
},
renderUI () {
return (
<FormField label={this.props.label} className="field-type-cloudinaryimages">
{this.renderFieldAction()}
{this.renderUploadsField()}
{this.renderFileField()}
{this.renderContainer()}
{this.renderToolbar()}
{this.renderNote()}
</FormField>
);
}
});
|
app/containers/LanguageProvider/index.js | 7ruth/PadStats2 | /*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { makeSelectLocale } from './selectors';
export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: React.PropTypes.string,
messages: React.PropTypes.object,
children: React.PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
(locale) => ({ locale })
);
export default connect(mapStateToProps)(LanguageProvider);
|
information/blendle-frontend-react-source/app/modules/settings/containers/EmailsContainer.js | BramscoChill/BlendleParser | import React from 'react';
import Emails from 'modules/settings/components/Emails';
import Auth from 'controllers/auth.js';
import ErrorDialogue from 'components/dialogues/ErrorDialogue';
import DialoguesController from 'controllers/dialogues';
import Analytics from 'instances/analytics';
function trackAnalytics(property, didOptOut) {
const optInOut = didOptOut ? 'Opt Out' : 'Opt In';
const label = property.replace(/_opt_out$/i, '');
Analytics.track(`${optInOut}: ${label}`);
return Promise.resolve();
}
function onError(error) {
const onClose = DialoguesController.openComponent(<ErrorDialogue onClose={() => onClose()} />);
throw error;
}
export default class EmailsContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
user: Auth.getUser(),
loadingProperties: [],
killSwitchLoading: false,
};
}
componentWillMount() {
this._updateUser = () => {
this.setState({ user: Auth.getUser() });
};
Auth.getUser().on('change', this._updateUser);
}
componentWillUnmount() {
Auth.getUser().off('change', this._updateUser);
}
_onToggleOption(propertyName) {
if (this.state.loadingProperties.includes(propertyName)) {
return;
}
this.setState({
loadingProperties: this.state.loadingProperties.concat([propertyName]),
});
const propertyValue = !this.state.user.get(propertyName);
this.state.user
.saveProperty(propertyName, propertyValue)
.then(() => trackAnalytics(propertyName, propertyValue))
.then(() =>
this.setState({
user: this.state.user,
loadingProperties: this.state.loadingProperties.filter(name => name !== propertyName),
}),
)
.catch(onError);
}
_onToggleKillSwitch() {
if (this.state.killSwitchLoading) {
return;
}
this.setState({ killSwitchLoading: true });
const masterOptOut = 'master_opt_out';
const newValue = !this.state.user.get(masterOptOut);
this.state.user
.saveProperty(masterOptOut, newValue)
.then(() => trackAnalytics(masterOptOut, newValue))
.then(() => Auth.renewJWT()) // Refresh user to get all opt_outs
.then(() => Auth.fetchUser())
.then(user =>
this.setState({
user,
killSwitchLoading: false,
}),
)
.catch(onError);
}
render() {
return (
<Emails
user={this.state.user}
onToggleOption={e => this._onToggleOption(e)}
loadingProperties={this.state.loadingProperties}
onToggleKillSwitch={() => this._onToggleKillSwitch()}
killSwitchLoading={this.state.killSwitchLoading}
/>
);
}
}
// WEBPACK FOOTER //
// ./src/js/app/modules/settings/containers/EmailsContainer.js |
docs/app/Examples/collections/Grid/Content/index.js | mohammed88/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const GridContentExamples = () => (
<ExampleSection title='Content'>
<ComponentExample
title='Rows'
description='A row is a horizontal grouping of columns.'
examplePath='collections/Grid/Content/GridExampleRows'
/>
<ComponentExample
title='Columns'
description='Columns each contain gutters giving them equal spacing from other columns.'
examplePath='collections/Grid/Content/GridExampleColumns'
/>
</ExampleSection>
)
export default GridContentExamples
|
app/components/Navigation/index.js | seanng/jobmaster-web | /**
*
* Navigation
*
*/
import React from 'react';
// import styled from 'styled-components';
import { FormattedMessage } from 'react-intl';
import { Link } from 'react-router';
import messages from './messages';
class Navigation extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<nav className="navbar navbar-default navbar-static-top">
<div className="container">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed btn-info" data-toggle="collapse" data-target="#navbar-collapse">
<span className="sr-only">Toggle Navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<a className="navbar-brand" href="#">
GoGenie
</a>
</div>
<div className="collapse navbar-collapse" id="navbar-collapse">
<ul className="nav navbar-nav navbar-right">
<li className="nav-item">
<Link className="nav-link" to="/myposts">
<FormattedMessage {...messages.myPosts} />
</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/chats">
<FormattedMessage {...messages.chats} />
</Link>
</li>
<li className="nav-item">
<Link className="nav-link " to="/help">
<FormattedMessage {...messages.help} />
</Link>
</li>
<li className="nav-item">
<Link className="nav-link " to="/account">
<FormattedMessage {...messages.account} />
</Link>
</li>
</ul>
</div>
</div>
</nav>
)
}
}
Navigation.propTypes = {
};
export default Navigation;
|
webpack/move_to_foreman/components/common/table/formatters/headerFormatter.js | mccun934/katello | import React from 'react';
import { Table as PfTable } from 'patternfly-react';
export default value => <PfTable.Heading>{value}</PfTable.Heading>;
|
app/src/components/CardBase.js | cs-cordero/mtgls | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {removeReminderText} from '../util';
import {getCardColor} from '../util';
export default class CardBase extends React.Component {
static PropTypes = {
cardImg: PropTypes.string.isRequired,
cardData: PropTypes.shape({
name: PropTypes.string.isRequired,
manaCost: PropTypes.string,
colors: PropTypes.arrayOf(PropTypes.string),
types: PropTypes.arrayOf(PropTypes.string).isRequired,
text: PropTypes.string,
power: PropTypes.string,
toughness: PropTypes.string,
cmc: PropTypes.number,
type: PropTypes.string,
loyalty: PropTypes.string,
}).isRequired,
};
render = () => {
const {cardData, previewMode} = this.props;
const {name, manaCost, colors, type, types, text, rarity,
loyalty, power, toughness} = cardData;
const cardColor = `mtg-card-is-${getCardColor(colors)}`;
const cardType = previewMode ? type : types[0];
const isCreature = types.includes('Creature');
const isPlaneswalker = types.includes('Planeswalker');
const previewClass = {'mtg-card-preview-font': previewMode};
const cleanedText = removeReminderText(text);
return (
<div className={classNames('mtg-card-inner', previewClass)}>
<div className={classNames('mtg-card-header', cardColor)}>
<div className='mtg-card-name-box'>{name}</div>
<div className='mtg-card-cost'>{manaCost}</div>
</div>
<div className={classNames('mtg-card-body', previewClass)}>
<div className={classNames('mtg-card-overlay', cardColor)}/>
<p>{cleanedText}</p>
</div>
<div className={classNames('mtg-card-footer', {
'mtg-card-hide': !previewMode,
})}>
<div className='mtg-card-type'>
{cardType}
</div>
</div>
<div className='mtg-card-footer'>
<div className='mtg-card-type'>
{previewMode ? rarity : cardType}
</div>
<div className={classNames('mtg-card-ptstats', {
'mtg-card-hide': !(isCreature || isPlaneswalker),
})}>
{isCreature && `${power}/${toughness}`}
{isPlaneswalker && `${loyalty}`}
</div>
</div>
</div>
);
};
}
|
src/components/Alert.js | edauenhauer/google-drive-copy-folder | /**
* Basic panel to hold content
*/
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import Paper from 'material-ui/Paper';
export default function Alert(props) {
return (
<Paper zDepth={1}>
<div className={['alert', props.className].join(' ')}>
{props.label && (
<h3>
{props.icon}
{props.label}
</h3>
)}
{props.children}
</div>
</Paper>
);
}
Alert.propTypes = {
label: PropTypes.string
};
|
frontend/src/Components/Link/ClipboardButton.js | geogolem/Radarr | import Clipboard from 'clipboard';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import FormInputButton from 'Components/Form/FormInputButton';
import Icon from 'Components/Icon';
import { icons, kinds } from 'Helpers/Props';
import getUniqueElememtId from 'Utilities/getUniqueElementId';
import styles from './ClipboardButton.css';
class ClipboardButton extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this._id = getUniqueElememtId();
this._successTimeout = null;
this._testResultTimeout = null;
this.state = {
showSuccess: false,
showError: false
};
}
componentDidMount() {
this._clipboard = new Clipboard(`#${this._id}`, {
text: () => this.props.value,
container: document.getElementById(this._id)
});
this._clipboard.on('success', this.onSuccess);
}
componentDidUpdate() {
const {
showSuccess,
showError
} = this.state;
if (showSuccess || showError) {
this._testResultTimeout = setTimeout(this.resetState, 3000);
}
}
componentWillUnmount() {
if (this._clipboard) {
this._clipboard.destroy();
}
if (this._testResultTimeout) {
clearTimeout(this._testResultTimeout);
}
}
//
// Control
resetState = () => {
this.setState({
showSuccess: false,
showError: false
});
}
//
// Listeners
onSuccess = () => {
this.setState({
showSuccess: true
});
}
onError = () => {
this.setState({
showError: true
});
}
//
// Render
render() {
const {
value,
className,
...otherProps
} = this.props;
const {
showSuccess,
showError
} = this.state;
const showStateIcon = showSuccess || showError;
const iconName = showError ? icons.DANGER : icons.CHECK;
const iconKind = showError ? kinds.DANGER : kinds.SUCCESS;
return (
<FormInputButton
id={this._id}
className={className}
{...otherProps}
>
<span className={showStateIcon ? styles.showStateIcon : undefined}>
{
showSuccess &&
<span className={styles.stateIconContainer}>
<Icon
name={iconName}
kind={iconKind}
/>
</span>
}
{
<span className={styles.clipboardIconContainer}>
<Icon name={icons.CLIPBOARD} />
</span>
}
</span>
</FormInputButton>
);
}
}
ClipboardButton.propTypes = {
className: PropTypes.string.isRequired,
value: PropTypes.string.isRequired
};
ClipboardButton.defaultProps = {
className: styles.button
};
export default ClipboardButton;
|
front/app/js/components/TopicCard.js | nudoru/learning-map | import React from 'react';
import {Grid} from "../rh-components/rh-Grid";
export const TopicCard = ({title, summary, children}) => {
const titleEl = title ? <h1>{title}</h1> : null;
const summaryEl = summary ? <div className="text-summary"
dangerouslySetInnerHTML={{__html: summary}}></div> : null
return (<div className="period-topic">
{titleEl}
{summaryEl}
<Grid>
{children}
</Grid>
</div>);
}; |
src/DropdownToggle.js | xiaoking/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import Button from './Button';
import CustomPropTypes from './utils/CustomPropTypes';
import SafeAnchor from './SafeAnchor';
const CARET = <span> <span className="caret" /></span>;
export default class DropdownToggle extends React.Component {
render() {
const caret = this.props.noCaret ? null : CARET;
const classes = {
'dropdown-toggle': true
};
const Component = this.props.useAnchor ? SafeAnchor : Button;
return (
<Component
{...this.props}
className={classNames(classes, this.props.className)}
type="button"
aria-haspopup
aria-expanded={this.props.open}>
{this.props.title || this.props.children}{caret}
</Component>
);
}
}
const titleAndChildrenValidation = CustomPropTypes.singlePropFrom([
'title',
'children'
]);
DropdownToggle.defaultProps = {
open: false,
useAnchor: false,
bsRole: 'toggle'
};
DropdownToggle.propTypes = {
bsRole: React.PropTypes.string,
children: titleAndChildrenValidation,
noCaret: React.PropTypes.bool,
open: React.PropTypes.bool,
title: titleAndChildrenValidation,
useAnchor: React.PropTypes.bool
};
DropdownToggle.isToggle = true;
DropdownToggle.titleProp = 'title';
DropdownToggle.onClickProp = 'onClick';
|
13. ReactJS Fundamentals - Feb 2019/05. Higher Order Components/Warning/warning/src/components/Navigation/Navigation.js | zrusev/SoftwareUniversity2016 | import React, { Component } from 'react';
class Navigation extends Component {
render() {
return (
<nav>
<header><span className="title">Navigation</span></header>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Catalog</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</nav>
)
}
}
export default Navigation; |
examples/universal/client.js | usufruct/redux | import 'babel-core/polyfill';
import React from 'react';
import configureStore from './store/configureStore';
import { Provider } from 'react-redux';
import App from './containers/App';
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState);
const rootElement = document.getElementById('app');
React.render(
<Provider store={store}>
{() => <App/>}
</Provider>,
rootElement
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.