path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
docs/app/Examples/modules/Embed/Types/EmbedExampleVimeo.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Embed } from 'semantic-ui-react'
const EmbedExampleVimeo = () => (
<Embed
id='125292332'
placeholder='http://semantic-ui.com/images/vimeo-example.jpg'
source='vimeo'
/>
)
export default EmbedExampleVimeo
|
src/routes/Selection/components/Selection.js | jobdoc/selections-app | import React from 'react'
import './Selection.scss'
import zip from 'lodash/zip'
import EditSelectionInfoForm from 'forms/EditSelectionInfo/EditSelectionInfoFormContainer'
import { Card, CardActions, CardMedia, CardTitle, CardText } from 'material-ui/Card'
import { Step, Stepper, StepLabel } from 'material-ui/Stepper'
import { Tabs, Tab } from 'material-ui/Tabs'
import { List, ListItem } from 'material-ui/List'
import Divider from 'material-ui/Divider'
import Avatar from 'material-ui/Avatar'
import TextField from 'material-ui/TextField'
import FlatButton from 'material-ui/FlatButton'
const statuses = [
'outstanding',
'options offered',
'selection made',
'ordered'
]
export class Selection extends React.Component {
componentWillMount () {
this.props.loadSelection(this.props.params.selectionId)
this.state = {
expanded: false
}
}
_handleSelectionInfoFormCancel = () => {
this.setState({
expanded: false
})
}
_handleExpandChange = (expanded) => {
this.setState({
expanded
})
}
render () {
return (
<div className='selection__container'>
<Card
expanded={this.state.expanded}
onExpandChange={this._handleExpandChange}
>
<CardTitle
title={this.props.selection.item}
subtitle={this.props.selection.room}
actAsExpander
showExpandableButton
/>
<CardMedia>
<Stepper activeStep={statuses.indexOf(this.props.selection.status)}>
<Step>
<StepLabel>Outstanding</StepLabel>
</Step>
<Step>
<StepLabel>Options offered</StepLabel>
</Step>
<Step>
<StepLabel>Selection made</StepLabel>
</Step>
<Step>
<StepLabel>Ordered</StepLabel>
</Step>
</Stepper>
</CardMedia>
<CardText>
{this.props.selection.description}
</CardText>
<CardText expandable>
<EditSelectionInfoForm onCancel={this._handleSelectionInfoFormCancel} />
</CardText>
</Card>
<Card>
<Tabs>
{this.props.options.map((option, idx) => {
return (
<Tab label={`Option ${++idx}`} key={option.id}>
<CardMedia>
<img src={option.image_url} alt={option.model} />
</CardMedia>
<List>
<a className='list-link' href={option.url} target='_blank'>
<ListItem
primaryText={option.model}
secondaryText={option.manufacturer}
/>
</a>
</List>
<CardText>{option.description}</CardText>
<CardActions>
<FlatButton label='Select this one' primary />
<FlatButton label='Add another option' />
</CardActions>
</Tab>
)
})}
</Tabs>
</Card>
<Card>
<List>
<ListItem
leftAvatar={<Avatar src='https://avatars0.githubusercontent.com/u/1718791?v=3&s=460' />}
primaryText='Mel'
disabled
secondaryText={
<TextField
hintText='Send a message...'
multiLine
fullWidth
rows={2}
rowsMax={4}
/>
}
/>
<Divider />
{zip(this.props.comments, this.props.commentUsers).map(([comment, user], idx) => {
return (
<div key={`comment-${idx}`}>
<ListItem
leftAvatar={<Avatar src={user.avatar_url} />}
primaryText={user.name}
secondaryText={comment.text}
disabled
/>
{idx < this.props.comments.length - 1 ? <Divider inset /> : ''}
</div>
)
})}
</List>
</Card>
</div>
)
}
}
Selection.propTypes = {
selection : React.PropTypes.shape({
item : React.PropTypes.string,
room : React.PropTypes.string,
status : React.PropTypes.string,
allowance : React.PropTypes.number,
description : React.PropTypes.string
}),
options : React.PropTypes.arrayOf(React.PropTypes.shape({
url : React.PropTypes.string,
manufacturer : React.PropTypes.string,
model : React.PropTypes.string,
item_code : React.PropTypes.string,
description : React.PropTypes.string,
id : React.PropTypes.string.isRequired
})),
comments : React.PropTypes.arrayOf(React.PropTypes.shape({
text : React.PropTypes.string
})),
commentUsers : React.PropTypes.arrayOf(React.PropTypes.shape({
name : React.PropTypes.string,
avatar_url : React.PropTypes.string
})),
loadSelection : React.PropTypes.func,
params : React.PropTypes.shape({
selectionId : React.PropTypes.string
})
}
Selection.defaultProps = {
selection: {
name: 'Faucet',
location: 'Kitchen',
description: 'This faucet is for the kitchen island.',
status: 'options offered',
allowance: 300
},
options: [
{
id: '23kj32kj2k',
image_url: 'https://www.rohlhome.com/Images/i21126.JPG',
url: 'https://www.rohlhome.com/Kitchen/Product_Detail.aspx?ProductID=U.4272-21652&Collection=1619&SubCollection=1652&ConnectionString=%22Product.Perrin%20^%20Rowe$S$$P$$C$0%22', // eslint-disable-line max-len
manufacturer: 'Perrin & Rowe',
model: 'Contemporary bridge kitchen faucet with sidespray',
item_code: 'FMHK11024WH',
description: `
Cutout: min. 1 1/8" , max. 1 3/8"
Deck mounted only, unions included
Hot and cold mix at the sidespray
Insulated brass sidespray
8" centers, offset unions not available, cannot use U.6793 unions
Patented diverter system
Ceramic disc control cartridge
16 1/2" spout height, 9" reach swivel spout
Brass construction
1.8 GPM
1 3/4" max. installation depth on deck
`
},
{
id: '2kj3kj99dsk',
image_url: 'http://kohler.scene7.com/is/image/PAWEB/Category_Template?$PDPcon$&$gradient_src=PAWEB%2Forganic-gradient&$shadow_src=PAWEB%2FBlank&$Badge1_src=PAWEB%2F2New&$Badge4_src=PAWEB%2FBlank&$Badge3_src=PAWEB%2FBlank&$Badge2_src=PAWEB%2FBlank&$product_src=is{PAWEB%2Fzab35855_rgb}', // eslint-disable-line max-len
url: 'http://www.us.kohler.com/us/baross-touchless-kitchen-faucet/productDetail/kitchen-sink-faucets/1280604.htm;jsessionid=A858D57DDCAF454CBA986C3FDEE36454.kohler-prod2-ecom2?skuId=1280602&brandId=1117946', // eslint-disable-line max-len
manufacturer: 'Kohler',
model: 'Barossa',
item_code: 'K-R78035-SD-VS',
description: 'With a state-of-the-art sensor conveniently located underneath the spout, the Barossa faucet with Response® touchless technology works with your hand’s natural position in the sink while helping prevent the spread of germs and reducing soap and water stains. Barossa\'s hidden sensor maintains the integrity of the easy-to-clean design, and simple installation makes for a quick and beautiful update to the busiest room in your home.' // eslint-disable-line max-len
}
],
comments: [
{
text: 'Love these options.',
user: {
name: 'Mel',
avatar_url: 'https://avatars0.githubusercontent.com/u/1718791?v=3&s=460'
}
},
{
text: 'Thanks took a while',
user: {
name: 'James',
avatar_url: 'https://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50'
}
}
],
commentUsers: [
{
name: 'Mel',
avatar_url: 'https://avatars0.githubusercontent.com/u/1718791?v=3&s=460'
},
{
name: 'James',
avatar_url: 'https://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50'
}
]
}
export default Selection
|
jenkins-design-language/src/js/components/material-ui/svg-icons/social/plus-one.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const SocialPlusOne = (props) => (
<SvgIcon {...props}>
<path d="M10 8H8v4H4v2h4v4h2v-4h4v-2h-4zm4.5-1.92V7.9l2.5-.5V18h2V5z"/>
</SvgIcon>
);
SocialPlusOne.displayName = 'SocialPlusOne';
SocialPlusOne.muiName = 'SvgIcon';
export default SocialPlusOne;
|
src/components/Feedback/Feedback.js | ZhouHengYi/https---github.com-ZhouHengYi-RenRen_react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import styles from './Feedback.less';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
class Feedback {
render() {
return (
<div className="Feedback">
<div className="Feedback-container">
<a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a>
<span className="Feedback-spacer">|</span>
<a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a>
</div>
</div>
);
}
}
export default Feedback;
|
Rate.UI/app/components/AddReviewContainer.js | tanos90/Rate | import React from 'react';
import SearchFlick from './SearchFlick';
import FlickStore from "../stores/FlickStore";
import Movie from './Movie';
import ReviewActions from "../actions/ReviewActions";
import AddReview from "./AddReview";
export default class AddReviewContainer extends React.Component {
constructor (props) {
super(props);
this.getFlick = this.getFlick.bind(this);
this.state = {
flick : {
title: ''
},
showMovie: false,
reviewText:"",
showReviewForm: false,
}
}
componentWillMount () {
FlickStore.addChangeListener(this.getFlick);
}
componentWillUnmount() {
FlickStore.removeChangeListener(this.getFlick);
}
getFlick(){
let flick = FlickStore.getFlick();
this.setState({
flick : flick,
showMovie: true
});
}
addReview(){
let {flick} = this.state;
let review = {
reviewText : this.state.reviewText,
flick_Id : flick.id,
id : +new Date()
}
ReviewActions.createReview(review);
resetAddReview();
}
resetAddReview(){
this.setState({showMovie: false});
toggleAddReview();
}
handleText(value){
this.setState({reviewText:value});
}
toggleAddReview() {
this.setState({showReviewForm: !this.state.showReviewForm});
}
render() {
let {flick, showReviewForm, showMovie} = this.state;
return (
<AddReview
flick={flick}
showReviewForm = {showReviewForm}
showMovie = {showMovie}
handleText ={this.handleText.bind(this)}
toggleAddReview= {this.toggleAddReview.bind(this)}
addReview={this.addReview.bind(this)}
resetAddReview={this.resetAddReview.bind(this)}/>
)
}
}
|
app/javascript/mastodon/features/mutes/index.js | yi0713/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import AccountContainer from '../../containers/account_container';
import { fetchMutes, expandMutes } from '../../actions/mutes';
import ScrollableList from '../../components/scrollable_list';
const messages = defineMessages({
heading: { id: 'column.mutes', defaultMessage: 'Muted users' },
});
const mapStateToProps = state => ({
accountIds: state.getIn(['user_lists', 'mutes', 'items']),
hasMore: !!state.getIn(['user_lists', 'mutes', 'next']),
isLoading: state.getIn(['user_lists', 'mutes', 'isLoading'], true),
});
export default @connect(mapStateToProps)
@injectIntl
class Mutes extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
accountIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchMutes());
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandMutes());
}, 300, { leading: true });
render () {
const { intl, hasMore, accountIds, multiColumn, isLoading } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.mutes' defaultMessage="You haven't muted any users yet." />;
return (
<Column bindToDocument={!multiColumn} icon='volume-off' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollableList
scrollKey='mutes'
onLoadMore={this.handleLoadMore}
hasMore={hasMore}
isLoading={isLoading}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
>
{accountIds.map(id =>
<AccountContainer key={id} id={id} />,
)}
</ScrollableList>
</Column>
);
}
}
|
src/components/form/DateTimeField.js | RelativeMedia/rm-frontend | import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import {OverlayTrigger, Tooltip} from 'react-bootstrap'
import DateTime from 'react-datetime'
const DateTimeField = ({ tooltip, tooltipPlacement, disabled, input, label, placeholder, meta: {valid, touched, error} }) => {
const classes = classNames('form-group', {
'has-error': (touched && !valid),
'has-success': (touched && valid)
})
return (<div className={classes}>
{label &&
<label htmlFor={input.name}>{label}</label>
}
{
(tooltip)
? <OverlayTrigger placement={tooltipPlacement || 'right'} overlay={<Tooltip id={`tooltip-${input.name}`}>{tooltip}</Tooltip>}>
<DateTime
name={input.name}
placeholder={placeholder || label}
inputProps={{
name: input.name,
placeholder: placeholder || label
}}
onChange={param => input.onChange(param)}
disabled={disabled}
/>
</OverlayTrigger>
: <DateTime
name={input.name}
placeholder={placeholder || label}
inputProps={{
name: input.name,
placeholder: placeholder || label
}}
onChange={param => input.onChange(param)}
disabled={disabled}
/>
}
{(!valid && touched) &&
<p className='help-block'>{error}</p>
}
</div>)
}
DateTimeField.propTypes = {
disabled: PropTypes.bool,
input: PropTypes.object.isRequired,
label: PropTypes.string.isRequired,
meta: PropTypes.object.isRequired,
placeholder: PropTypes.string,
tooltip: PropTypes.string,
tooltipPlacement: PropTypes.string
}
export default DateTimeField
|
app/components/Toggle/index.js | josh-butler/react-bp-demo | /**
*
* LocaleToggle
*
*/
import React from 'react';
import Select from './Select';
import ToggleOption from '../ToggleOption';
function Toggle(props) {
let content = (<option>--</option>);
// If we have items, render them
if (props.values) {
content = props.values.map((value) => (
<ToggleOption key={value} value={value} message={props.messages[value]} />
));
}
return (
<Select value={props.value} onChange={props.onToggle}>
{content}
</Select>
);
}
Toggle.propTypes = {
onToggle: React.PropTypes.func,
values: React.PropTypes.array,
value: React.PropTypes.string,
messages: React.PropTypes.object,
};
export default Toggle;
|
lib/shared/screens/admin/shared/components/page-builder-menu/tabs/index.js | relax/relax | import Component from 'components/component';
import React from 'react';
import PropTypes from 'prop-types';
import {setMenuTab} from 'actions/page-builder';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import elements from 'elements';
import Tabs from './tabs';
@connect(
(state) => ({
menuTab: state.pageBuilder.menuTab,
type: state.pageBuilder.type,
dataLinkable:
!!(state.pageBuilder.type === 'template' ||
state.pageBuilder.linkingData ||
( // linkable selected element
state.pageBuilder.selectedElement &&
elements[state.pageBuilder.selectedElement.tag].settings.dynamicLinkable
))
}),
(dispatch) => bindActionCreators({setMenuTab}, dispatch)
)
export default class TabsContainer extends Component {
static propTypes = {
type: PropTypes.string
};
render () {
return (
<Tabs
{...this.props}
/>
);
}
}
|
com/jessewarden/contacts/SearchResults.js | JesterXL/react-bootstrap-express-cassandra-contacts | import React from 'react';
import ReactDOM from 'react-dom';
import Button from 'react-bootstrap/lib/Button';
import ContactsModel from './models/ContactsModel';
import {Link, hashHistory} from 'react-router';
import EventBus from './EventBus';
class ContactList extends React.Component
{
constructor(props)
{
super(props);
this.state = {
contacts: []
};
}
search(query)
{
var me = this;
ContactsModel.instance.search(query)
.then(function(contacts)
{
console.log("SearchResults::search contacts:", contacts);
me.setState({contacts: contacts});
});
}
componentDidMount()
{
var me = this;
var query = me.props.params.query;
me.search(query);
EventBus.pubsub
.where(event => event.type === 'search')
.subscribe((event)=>
{
me.search(event.searchValue);
});
}
render()
{
console.log("SearchResults::render, contacts:", this.state.contacts);
var me = this;
if(this.state.contacts.length > 0)
{
var nodes = this.state.contacts.map(function(contact)
{
var link = "view/" + contact.id;
return (
<Link className="list-group-item" key={contact.id} to={link}>{contact.firstName}</Link>
);
});
return (
<div className="list-group">
{nodes}
</div>
);
}
else if(this.state.contacts.length === 0)
{
return (
<div>No contacts found for '{this.props.params.query}'</div>
);
}
else
{
return (
<div>Loading...</div>
);
}
}
}
ContactList.defaultProps = {
contacts: []
};
export default ContactList |
src/Dialog/Dialog.js | kradio3/react-mdc-web | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classnames from 'classnames';
import {
ANIMATING,
ROOT,
OPEN,
SURFACE,
BACKDROP,
SCROLL_LOCK,
} from './constants';
class Dialog extends Component {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
onClose: PropTypes.func,
open: PropTypes.bool,
}
constructor(props) {
super(props);
this.state = { animating: false };
}
componentWillReceiveProps({ open: nextOpen }) {
const { open } = this.props;
const onOpen = !open && nextOpen;
const onClose = open && !nextOpen;
if (onOpen) {
this.setState({ animating: true });
document.body.classList.add(SCROLL_LOCK);
document.addEventListener('keydown', (e) => { this.handleKeyDown(e); });
} else if (onClose) {
this.setState({ animating: true });
document.body.classList.remove(SCROLL_LOCK);
document.removeEventListener('keydown', (e) => { this.handleKeyDown(e); });
}
}
handleKeyDown(event) {
const { onClose } = this.props;
const isEscape = event.key && (event.key === 'Escape' || event.keyCode === 27);
if (onClose && isEscape) {
onClose();
}
}
render() {
const { className, children, onClose, open, ...otherProps } = this.props;
const ariaHiddenProp = open ? {} : { 'aria-hidden': true };
return (
<aside
className={classnames(ROOT, {
[ANIMATING]: this.state.animating,
[OPEN]: open,
}, className)}
onClick={(e) => { if (onClose) onClose(e); }}
onTransitionEnd={() => { this.setState({ animating: false }); }}
{...ariaHiddenProp}
>
<div
className={SURFACE}
onClick={(e) => { e.stopPropagation(); }}
{...otherProps}
>
{children}
</div>
<div className={BACKDROP} />
</aside>
);
}
}
export default Dialog;
|
admin/client/components/RelatedItemsList.js | pswoodworth/keystone | import React from 'react';
import Columns from '../columns';
import { Alert, Spinner } from 'elemental';
const RelatedItemsList = React.createClass({
propTypes: {
list: React.PropTypes.object.isRequired,
refList: React.PropTypes.object.isRequired,
relatedItemId: React.PropTypes.string.isRequired,
relationship: React.PropTypes.object.isRequired,
},
getInitialState () {
return {
columns: this.getColumns(),
err: null,
items: null,
};
},
componentDidMount () {
this.loadItems();
},
getColumns () {
const { relationship, refList } = this.props;
const columns = refList.expandColumns(refList.defaultColumns);
return columns.filter(i => i.path !== relationship.refPath);
},
loadItems () {
const { refList, relatedItemId, relationship } = this.props;
if (!refList.fields[relationship.refPath]) {
const err = (
<Alert type="danger">
<strong>Error:</strong> Related List <strong>{refList.label}</strong> has no field <strong>{relationship.refPath}</strong>
</Alert>
);
return this.setState({ err });
}
refList.loadItems({
columns: this.state.columns,
filters: [{
field: refList.fields[relationship.refPath],
value: { value: relatedItemId },
}],
}, (err, items) => {
// TODO: indicate pagination & link to main list view
this.setState({ items });
});
},
renderItems () {
return this.state.items.results.length ? (
<div className="ItemList-wrapper">
<table cellPadding="0" cellSpacing="0" className="Table ItemList">
{this.renderTableCols()}
{this.renderTableHeaders()}
<tbody>
{this.state.items.results.map(this.renderTableRow)}
</tbody>
</table>
</div>
) : (
<h4 className="Relationship__noresults">No related {this.props.refList.plural}</h4>
);
},
renderTableCols () {
const cols = this.state.columns.map((col) => <col width={col.width} key={col.path} />);
return <colgroup>{cols}</colgroup>;
},
renderTableHeaders () {
const cells = this.state.columns.map((col) => {
return <th key={col.path}>{col.label}</th>;
});
return <thead><tr>{cells}</tr></thead>;
},
renderTableRow (item) {
const cells = this.state.columns.map((col, i) => {
const ColumnType = Columns[col.type] || Columns.__unrecognised__;
const linkTo = !i ? `${Keystone.adminPath}/${this.props.refList.path}/${item.id}` : undefined;
return <ColumnType key={col.path} list={this.props.refList} col={col} data={item} linkTo={linkTo} />;
});
return <tr key={'i' + item.id}>{cells}</tr>;
},
render () {
if (this.state.err) {
return <div className="Relationship">{this.state.err}</div>;
}
const listHref = `${Keystone.adminPath}/${this.props.refList.path}`;
return (
<div className="Relationship">
<h3 className="Relationship__link"><a href={listHref}>{this.props.refList.label}</a></h3>
{this.state.items ? this.renderItems() : <Spinner size="sm" />}
</div>
);
},
});
module.exports = RelatedItemsList;
|
docs/client/components/shared/NavBar/index.js | koaninc/draft-js-plugins | import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './styles.css';
export default class NavBar extends Component {
render() {
return (
<div className={styles.pluginsWrapper}>
<div className={styles.wideContainer}>
<ul className={styles.plugins}>
<li className={styles.plugin}>
<Link to="/plugin/mention" className={styles.link}>
Mention
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/emoji" className={styles.link}>
Emoji
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/image" className={styles.link}>
Image
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/video" className={styles.link}>
Video
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/sticker" className={styles.link}>
Sticker
</Link>
</li>
</ul>
<ul className={styles.plugins}>
<li className={styles.plugin}>
<Link to="/plugin/hashtag" className={styles.link}>
Hashtag
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/inline-toolbar" className={styles.link}>
Inline Toolbar
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/side-toolbar" className={styles.link}>
Side Toolbar
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/undo" className={styles.link}>
Undo
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/counter" className={styles.link}>
Counter
</Link>
</li>
</ul>
<ul className={styles.plugins}>
<li className={styles.plugin}>
<Link to="/plugin/linkify" className={styles.link}>
Linkify
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/focus" className={styles.link}>
Focus
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/alignment" className={styles.link}>
Alignment
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/resizeable" className={styles.link}>
Resizeable
</Link>
</li>
<li className={styles.plugin}>
<Link to="/plugin/drag-n-drop" className={styles.link}>
{'Drag\'n\'Drop'}
</Link>
</li>
</ul>
</div>
<div style={{ textAlign: 'center', marginTop: '3rem', fontSize: 13, color: '#aaa' }}>
The documentation currently represents the 2.0.0-rc3 release.<br />For troubleshooting please checkout the
<a href="https://github.com/draft-js-plugins/draft-js-plugins/blob/master/FAQ.md" className={styles.link}>
FAQ
</a>
</div>
</div>
);
}
}
|
src/js/components/icons/base/Briefcase.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-briefcase`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'briefcase');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M1,6 L23,6 L23,21 L1,21 L1,6 Z M6,6 L6,21 M18,6 L18,21 M8,6 L8,3 L16,3 L16,6"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Briefcase';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
JotunheimenPlaces/src/components/ButtonWhite.js | designrad/Jotunheimen-tracking | import React, { Component } from 'react';
import ReactNative from 'react-native';
const {
StyleSheet,
Text,
View,
TouchableOpacity
} = ReactNative;
/**
* Button component
*/
export default class ButtonWhite extends Component {
/**
* Render a Button
* @return {jsxresult} result in jsx format
*/
render() {
return (
<TouchableOpacity style={styles.button} onPress={this.props.onPress}>
<Text style={styles.whiteFont}>{this.props.children}</Text>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
button: {
backgroundColor: 'white',
padding: 15,
paddingTop:5,
paddingBottom:5,
alignItems: 'center',
borderWidth: 1,
borderColor: '#333333',
width:'100%'
},
whiteFont: {
color: '#333333',
fontFamily: 'Roboto-Bold',
fontSize: 32
}
}); |
src/svg-icons/action/settings-input-antenna.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsInputAntenna = (props) => (
<SvgIcon {...props}>
<path d="M12 5c-3.87 0-7 3.13-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.87-3.13-7-7-7zm1 9.29c.88-.39 1.5-1.26 1.5-2.29 0-1.38-1.12-2.5-2.5-2.5S9.5 10.62 9.5 12c0 1.02.62 1.9 1.5 2.29v3.3L7.59 21 9 22.41l3-3 3 3L16.41 21 13 17.59v-3.3zM12 1C5.93 1 1 5.93 1 12h2c0-4.97 4.03-9 9-9s9 4.03 9 9h2c0-6.07-4.93-11-11-11z"/>
</SvgIcon>
);
ActionSettingsInputAntenna = pure(ActionSettingsInputAntenna);
ActionSettingsInputAntenna.displayName = 'ActionSettingsInputAntenna';
export default ActionSettingsInputAntenna;
|
frontend/src/Movie/History/MovieHistoryTable.js | geogolem/Radarr | import React from 'react';
import MovieHistoryTableContentConnector from './MovieHistoryTableContentConnector';
function MovieHistoryTable(props) {
const {
...otherProps
} = props;
return (
<MovieHistoryTableContentConnector
{...otherProps}
/>
);
}
MovieHistoryTable.propTypes = {
};
export default MovieHistoryTable;
|
PushApp/common/LoginScreen.js | bit6/bit6-react-native-samples | import React from 'react';
import { View, TextInput, Button } from 'react-native';
import { AccessToken } from 'bit6';
import { MySession } from './MySession';
export class LoginScreen extends React.Component {
static navigationOptions = {
title: 'Bit6',
};
constructor(props,context) {
super(props,context);
this.state = {
processing : true
}
}
componentDidMount() {
this._loadInitialState()
}
async _loadInitialState() {
var device = await MySession.getDevice()
var identity = await MySession.getIdentity()
//has logged before
if (device && identity) {
this.setState({device, identity})
this.fetchToken((jwt) => this.login(jwt))
}
else {
this.setState({device, identity, processing:false})
}
}
render() {
const { identity, processing } = this.state
return (
<View style={{padding: 10}}>
<TextInput style={{height: 40}} placeholder='Enter your username' onChangeText={(identity) => this.setState({identity})} autoCapitalize='none' value={identity}/>
<Button onPress={() => {this.fetchToken((jwt) => this.login(jwt))} } title='Login' disabled={processing}/>
</View>
)
}
fetchToken(handler) {
const { identity, device } = this.state
if (identity !== '') {
fetch('https://bit6-demo-token-svc.herokuapp.com/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({identity,device})
})
.then((response) => response.json())
.then((responseJson) => {
handler(responseJson.token);
})
.catch((error) => {
console.error(error);
this.setState({processing:false})
});
}
}
login(jwt) {
var accessToken = new AccessToken(jwt);
accessToken.on('expired', function(t) {
console.log('AccessToken expired, need to renew', t);
this.fetchToken((jwt) => {
accessToken.update(jwt)
})
}.bind(this));
MySession.setIdentity(this.state.identity)
this.props.navigation.navigate('Messaging', { accessToken })
this.setState({processing:false})
}
}
|
src/client/components/AdminPanel/Venues/New/index.js | mweslander/veery | // Imports
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// Components
import VenueForm from '../../../Base/VenueForm';
import Button from '../../../Base/Button';
// CSS
import './index.scss';
// Services
import adminVenuesService from '../../../../services/admin/venues';
// Utils
import mapFormValues from '../../../../utils/mapFormValues';
// PropTypes
const propTypes = {
removeAlert: PropTypes.func,
router: PropTypes.shape({
params: PropTypes.shape({
id: PropTypes.string
}),
push: PropTypes.func.isRequired
}),
setAlertMessage: PropTypes.func
};
/*
New
<New/>
*/
class NewVenue extends Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const values = mapFormValues(this.newVenueForm.elements);
return adminVenuesService
.createVenue(values)
.then(() => {
this.props.setAlertMessage({ successMessage: 'Venue successfully created.' });
return this.props.router.push('/admin');
});
}
render() {
return (
<form
className="c-new-venue o-fieldset o-container o-container--small"
ref={(form) => { this.newVenueForm = form; }}
onSubmit={this.handleSubmit}
>
<VenueForm
venue={{}}
/>
<Button value="Create Venue" />
</form>
);
}
}
NewVenue.propTypes = propTypes;
export default NewVenue;
|
examples/Example/pages/overrideRenderExample.js | thegamenicorus/react-native-timeline-listview | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image
} from 'react-native';
import Timeline from 'react-native-timeline-listview'
export default class Example extends Component {
constructor(){
super()
this.onEventPress = this.onEventPress.bind(this)
this.renderSelected = this.renderSelected.bind(this)
this.renderDetail = this.renderDetail.bind(this)
this.data = [
{
time: '09:00',
title: 'Archery Training',
description: 'The Beginner Archery and Beginner Crossbow course does not require you to bring any equipment, since everything you need will be provided for the course. ',
lineColor:'#009688',
icon: require('../img/archery.png'),
imageUrl: 'https://cloud.githubusercontent.com/assets/21040043/24240340/c0f96b3a-0fe3-11e7-8964-fe66e4d9be7a.jpg'
},
{
time: '10:45',
title: 'Play Badminton',
description: 'Badminton is a racquet sport played using racquets to hit a shuttlecock across a net.',
icon: require('../img/badminton.png'),
imageUrl: 'https://cloud.githubusercontent.com/assets/21040043/24240405/0ba41234-0fe4-11e7-919b-c3f88ced349c.jpg'
},
{
time: '12:00',
title: 'Lunch',
icon: require('../img/lunch.png'),
},
{
time: '14:00',
title: 'Watch Soccer',
description: 'Team sport played between two teams of eleven players with a spherical ball. ',
lineColor:'#009688',
icon: require('../img/soccer.png'),
imageUrl: 'https://cloud.githubusercontent.com/assets/21040043/24240419/1f553dee-0fe4-11e7-8638-6025682232b1.jpg'
},
{
time: '16:30',
title: 'Go to Fitness center',
description: 'Look out for the Best Gym & Fitness Centers around me :)',
icon: require('../img/dumbbell.png'),
imageUrl: 'https://cloud.githubusercontent.com/assets/21040043/24240422/20d84f6c-0fe4-11e7-8f1d-9dbc594d0cfa.jpg'
}
]
this.state = {selected: null}
}
onEventPress(data){
this.setState({selected: data})
}
renderSelected(){
if(this.state.selected)
return <Text style={{marginTop:10}}>Selected event: {this.state.selected.title} at {this.state.selected.time}</Text>
}
renderDetail(rowData, sectionID, rowID) {
let title = <Text style={[styles.title]}>{rowData.title}</Text>
var desc = null
if(rowData.description && rowData.imageUrl)
desc = (
<View style={styles.descriptionContainer}>
<Image source={{uri: rowData.imageUrl}} style={styles.image}/>
<Text style={[styles.textDescription]}>{rowData.description}</Text>
</View>
)
return (
<View style={{flex:1}}>
{title}
{desc}
</View>
)
}
render() {
return (
<View style={styles.container}>
{this.renderSelected()}
<Timeline
style={styles.list}
data={this.data}
circleSize={20}
circleColor='rgba(0,0,0,0)'
lineColor='rgb(45,156,219)'
timeContainerStyle={{minWidth:52, marginTop: -5}}
timeStyle={{textAlign: 'center', backgroundColor:'#ff9797', color:'white', padding:5, borderRadius:13}}
descriptionStyle={{color:'gray'}}
options={{
style:{paddingTop:5}
}}
innerCircle={'icon'}
onEventPress={this.onEventPress}
renderDetail={this.renderDetail}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
paddingTop:65,
backgroundColor:'white'
},
list: {
flex: 1,
marginTop:20,
},
title:{
fontSize:16,
fontWeight: 'bold'
},
descriptionContainer:{
flexDirection: 'row',
paddingRight: 50
},
image:{
width: 50,
height: 50,
borderRadius: 25
},
textDescription: {
marginLeft: 10,
color: 'gray'
}
}); |
src/blog/flux/views/pages/ArticleDetailPage.js | exseed/exseed-boilerplate | import React from 'react';
import connectToStores from 'alt-utils/lib/connectToStores';
import MenuLayout from '../layouts/MenuLayout';
import Widget from '../components/Widget';
import ArticleAction from '../../actions/ArticleAction';
import ArticleStore from '../../stores/ArticleStore';
@connectToStores
export default class ArticleDetailPage extends React.Component {
static getStores() {
return [ArticleStore];
}
static getPropsFromStores() {
return ArticleStore.getState();
}
componentDidMount() {
let { id } = this.props.params;
ArticleAction.fetch(id);
}
render() {
const {
title,
content,
} = this.props.article;
return (
<MenuLayout>
<div className="container right">
<div className="ui basic segment">
<h1 className="ui center aligned header">{title}</h1>
</div>
{content.map(widget =>
<Widget
key={widget.id}
display={true}
type={widget.type}
value={widget.value} />)}
</div>
</MenuLayout>
);
}
}; |
templates/rubix/demo/src/routes/Gallery.js | jeffthemaximum/Teachers-Dont-Pay-Jeff | import React from 'react';
import {
Row,
Col,
Icon,
Grid,
Panel,
Image,
Table,
Button,
PanelBody,
PanelHeader,
PanelContainer,
} from '@sketchpixy/rubix';
class GalleryItem extends React.Component {
constructor(props) {
super(props);
this.state = {
active: this.props.active || false,
counts: 0
};
}
handleIncrement(e) {
if(this.state.active) return;
this.setState({
active: true,
counts: this.state.counts+1
});
}
componentDidMount() {
this.setState({
counts: (Math.round(Math.random() * 20) + 4)
});
}
render() {
return (
<PanelContainer>
<Panel>
<PanelHeader>
<Grid className='gallery-item'>
<Row>
<Col xs={12} style={{padding: 12.5}}>
<a className='gallery-1 gallery-item-link' href={`/imgs/app/gallery/${this.props.image}.jpg`} title={this.props.title}>
<Image responsive src={`/imgs/app/gallery/${this.props.image}-thumb.jpg`} alt={this.props.title} width='200' height='150'/>
<div className='black-wrapper text-center'>
<Table style={{height: '100%', width: '100%'}}>
<tbody>
<tr>
<td>
<Icon glyph='icon-outlined-magnifier-plus icon-3x' />
</td>
</tr>
</tbody>
</Table>
</div>
</a>
<div className='text-center'>
<h4 className='fg-darkgrayishblue75 hidden-xs' style={{textTransform: 'uppercase'}}>{this.props.title}</h4>
<h6 className='fg-darkgrayishblue75 visible-xs' style={{textTransform: 'uppercase'}}>{this.props.title}</h6>
<h5 className='fg-darkgray50 hidden-xs' style={{textTransform: 'uppercase'}}>{this.props.subtitle}</h5>
<h6 className='visible-xs' style={{textTransform: 'uppercase'}}><small className='fg-darkgray50'>{this.props.subtitle}</small></h6>
<Button outlined onlyOnHover bsStyle='red' className='fav-btn' active={this.state.active} onClick={::this.handleIncrement}>
<Icon glyph='icon-flatline-heart' />
<span className='counts'>{this.state.counts}</span>
</Button>
</div>
</Col>
</Row>
</Grid>
</PanelHeader>
</Panel>
</PanelContainer>
);
}
}
export default class Gallery extends React.Component {
componentDidMount() {
var links = document.getElementsByClassName('gallery-1');
$('.gallery-1').unbind('click').bind('click', function(event) {
blueimp.Gallery(links, {
index: $(this).get(0),
event: event
});
});
}
render() {
return (
<Row className='gallery-view'>
<Col xs={6} sm={4} collapseRight>
<GalleryItem image='tumblr_n6es0tRk5w1st5lhmo1_1280' title='skyline' subtitle='10th Dec - 12th Dec' />
</Col>
<Col xs={6} sm={4} collapseRight>
<GalleryItem active image='tumblr_n6eszmeQMR1st5lhmo1_1280' title='me at ny' subtitle='11th Dec - 12th Dec' />
</Col>
<Col xs={6} sm={4} collapseRight>
<GalleryItem image='tumblr_n6rzkfxeOR1st5lhmo1_1280' title='vintage cameras' subtitle='13th Dec - 14th Dec' />
</Col>
<Col xs={6} sm={4} collapseRight>
<GalleryItem image='tumblr_n6rztipoQy1st5lhmo1_1280' title='columns' subtitle='13th Dec - 14th Dec' />
</Col>
<Col xs={6} sm={4} collapseRight>
<GalleryItem image='tumblr_n7fg2vYZ741st5lhmo1_1280' title='peak' subtitle='14th Dec - 15th Dec' />
</Col>
<Col xs={6} sm={4} collapseRight>
<GalleryItem image='tumblr_n7fgnop0bz1st5lhmo1_1280' title='Mac' subtitle='14th Dec - 15th Dec' />
</Col>
<Col xs={6} sm={4} collapseRight>
<GalleryItem image='tumblr_n7yhe1sTa41st5lhmo1_1280' title='Taxi cabs' subtitle='14th Dec - 15th Dec' />
</Col>
<Col xs={6} sm={4} collapseRight>
<GalleryItem image='tumblr_n8gxs0oWZ21st5lhmo1_1280' title='Golden gate' subtitle='14th Dec - 15th Dec' />
</Col>
<Col xs={6} sm={4} collapseRight>
<GalleryItem image='tumblr_n9hyqfJavs1st5lhmo1_1280' title='Empire state' subtitle='14th Dec - 15th Dec' />
</Col>
</Row>
);
}
}
|
src/modules/Sidebar/SidebarPusher.js | shengnian/shengnian-ui-react | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
customPropTypes,
getElementType,
getUnhandledProps,
META,
useKeyOnly,
} from '../../lib'
/**
* A pushable sub-component for Sidebar.
*/
function SidebarPusher(props) {
const { className, dimmed, children, content } = props
const classes = cx(
'pusher',
useKeyOnly(dimmed, 'dimmed'),
className,
)
const rest = getUnhandledProps(SidebarPusher, props)
const ElementType = getElementType(SidebarPusher, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
SidebarPusher._meta = {
name: 'SidebarPusher',
type: META.TYPES.MODULE,
parent: 'Sidebar',
}
SidebarPusher.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
/** Controls whether or not the dim is displayed. */
dimmed: PropTypes.bool,
}
export default SidebarPusher
|
src/routes/Home/components/CommentList.js | nnti3n/YouTime | import React from 'react'
import toStringTime from '../../../Helper/Helper'
class CommentList extends React.Component {
render () {
const {commentList, commentClickHandler} = this.props
return (
<div className='ViewBox-comments'>
<ul>
{
commentList
? commentList.map(comment =>
<li className='u-margin-bottom--12' key={commentList.indexOf(comment)} onClick={
() => commentClickHandler(comment)}>
<div><a>{toStringTime(comment.time)}</a> - {comment.content}</div>
</li>, this
)
: ' ' }
</ul>
<div className='ViewBox-listFilter' />
</div>
)
}
}
export default CommentList
|
geonode/contrib/monitoring/frontend/src/components/molecules/max-response-time/index.js | ingenieroariel/geonode | import React from 'react';
import PropTypes from 'prop-types';
import CircularProgress from 'material-ui/CircularProgress';
import HoverPaper from '../../atoms/hover-paper';
import styles from './styles';
class MaxResponseTime extends React.Component {
static propTypes = {
time: PropTypes.number,
}
static contextTypes = {
muiTheme: PropTypes.object.isRequired,
}
render() {
let time = this.props.time;
if (time === undefined) {
time = 'N/A';
} else if (typeof time === 'number') {
if (time === 0) {
time = <CircularProgress size={this.context.muiTheme.spinner.size} />;
} else {
time += ' ms';
}
}
return (
<HoverPaper style={styles.content}>
<h5>Max Response Time</h5>
<div style={styles.stat}>
<h3>{time}</h3>
</div>
</HoverPaper>
);
}
}
export default MaxResponseTime;
|
imports/ui/components/categories/MultiSelectCheckbox.js | hwillson/file-metadata-manager | import React, { Component } from 'react';
import { Form, Checkbox } from 'react-bootstrap';
import {
updateCategoryMultiSelectSetting,
} from '../../../api/categories/methods';
class MultiSelectCheckbox extends Component {
constructor(props) {
super(props);
this.state = {
checked: props.checked,
};
this.handleCheckbox = this.handleCheckbox.bind(this);
}
handleCheckbox(event) {
this.setState({
checked: event.target.checked,
});
updateCategoryMultiSelectSetting.call({
categoryId: this.props.categoryId,
multiselect: event.target.checked,
});
}
render() {
return (
<Form>
<Checkbox
checked={this.state.checked}
onChange={this.handleCheckbox}
>
Multiselect
</Checkbox>
</Form>
);
}
}
MultiSelectCheckbox.propTypes = {
categoryId: React.PropTypes.string.isRequired,
checked: React.PropTypes.bool.isRequired,
};
export default MultiSelectCheckbox;
|
src/svg-icons/action/line-style.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLineStyle = (props) => (
<SvgIcon {...props}>
<path d="M3 16h5v-2H3v2zm6.5 0h5v-2h-5v2zm6.5 0h5v-2h-5v2zM3 20h2v-2H3v2zm4 0h2v-2H7v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zM3 12h8v-2H3v2zm10 0h8v-2h-8v2zM3 4v4h18V4H3z"/>
</SvgIcon>
);
ActionLineStyle = pure(ActionLineStyle);
ActionLineStyle.displayName = 'ActionLineStyle';
ActionLineStyle.muiName = 'SvgIcon';
export default ActionLineStyle;
|
frontendsrc/indexFourbyfour.js | nongaap/minimax | import React from 'react';
import { render } from 'react-dom';
import Fourbyfour from './components/Fourbyfour';
import './assets/images/favicon.ico';
import styles from './style/application.scss';
render(
<Fourbyfour />,
document.getElementById('root')
);
|
app/javascript/mastodon/features/compose/components/privacy_dropdown.js | h3zjp/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl, defineMessages } from 'react-intl';
import IconButton from '../../../components/icon_button';
import Overlay from 'react-overlays/lib/Overlay';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import detectPassiveEvents from 'detect-passive-events';
import classNames from 'classnames';
import Icon from 'mastodon/components/icon';
const messages = defineMessages({
public_short: { id: 'privacy.public.short', defaultMessage: 'Public' },
public_long: { id: 'privacy.public.long', defaultMessage: 'Visible for all, shown in public timelines' },
unlisted_short: { id: 'privacy.unlisted.short', defaultMessage: 'Unlisted' },
unlisted_long: { id: 'privacy.unlisted.long', defaultMessage: 'Visible for all, but not in public timelines' },
private_short: { id: 'privacy.private.short', defaultMessage: 'Followers-only' },
private_long: { id: 'privacy.private.long', defaultMessage: 'Visible for followers only' },
direct_short: { id: 'privacy.direct.short', defaultMessage: 'Direct' },
direct_long: { id: 'privacy.direct.long', defaultMessage: 'Visible for mentioned users only' },
change_privacy: { id: 'privacy.change', defaultMessage: 'Adjust status privacy' },
});
const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false;
class PrivacyDropdownMenu extends React.PureComponent {
static propTypes = {
style: PropTypes.object,
items: PropTypes.array.isRequired,
value: PropTypes.string.isRequired,
placement: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
};
state = {
mounted: false,
};
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
handleKeyDown = e => {
const { items } = this.props;
const value = e.currentTarget.getAttribute('data-index');
const index = items.findIndex(item => {
return (item.value === value);
});
let element;
switch(e.key) {
case 'Escape':
this.props.onClose();
break;
case 'Enter':
this.handleClick(e);
break;
case 'ArrowDown':
element = this.node.childNodes[index + 1];
if (element) {
element.focus();
this.props.onChange(element.getAttribute('data-index'));
}
break;
case 'ArrowUp':
element = this.node.childNodes[index - 1];
if (element) {
element.focus();
this.props.onChange(element.getAttribute('data-index'));
}
break;
case 'Tab':
if (e.shiftKey) {
element = this.node.childNodes[index - 1] || this.node.lastChild;
} else {
element = this.node.childNodes[index + 1] || this.node.firstChild;
}
if (element) {
element.focus();
this.props.onChange(element.getAttribute('data-index'));
e.preventDefault();
e.stopPropagation();
}
break;
case 'Home':
element = this.node.firstChild;
if (element) {
element.focus();
this.props.onChange(element.getAttribute('data-index'));
}
break;
case 'End':
element = this.node.lastChild;
if (element) {
element.focus();
this.props.onChange(element.getAttribute('data-index'));
}
break;
}
}
handleClick = e => {
const value = e.currentTarget.getAttribute('data-index');
e.preventDefault();
this.props.onClose();
this.props.onChange(value);
}
componentDidMount () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
if (this.focusedItem) this.focusedItem.focus();
this.setState({ mounted: true });
}
componentWillUnmount () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
setFocusRef = c => {
this.focusedItem = c;
}
render () {
const { mounted } = this.state;
const { style, items, placement, value } = this.props;
return (
<Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}>
{({ opacity, scaleX, scaleY }) => (
// It should not be transformed when mounting because the resulting
// size will be used to determine the coordinate of the menu by
// react-overlays
<div className={`privacy-dropdown__dropdown ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null, zIndex: 2 }} role='listbox' ref={this.setRef}>
{items.map(item => (
<div role='option' tabIndex='0' key={item.value} data-index={item.value} onKeyDown={this.handleKeyDown} onClick={this.handleClick} className={classNames('privacy-dropdown__option', { active: item.value === value })} aria-selected={item.value === value} ref={item.value === value ? this.setFocusRef : null}>
<div className='privacy-dropdown__option__icon'>
<Icon id={item.icon} fixedWidth />
</div>
<div className='privacy-dropdown__option__content'>
<strong>{item.text}</strong>
{item.meta}
</div>
</div>
))}
</div>
)}
</Motion>
);
}
}
export default @injectIntl
class PrivacyDropdown extends React.PureComponent {
static propTypes = {
isUserTouching: PropTypes.func,
isModalOpen: PropTypes.bool.isRequired,
onModalOpen: PropTypes.func,
onModalClose: PropTypes.func,
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
state = {
open: false,
placement: 'bottom',
};
handleToggle = ({ target }) => {
if (this.props.isUserTouching()) {
if (this.state.open) {
this.props.onModalClose();
} else {
this.props.onModalOpen({
actions: this.options.map(option => ({ ...option, active: option.value === this.props.value })),
onClick: this.handleModalActionClick,
});
}
} else {
const { top } = target.getBoundingClientRect();
if (this.state.open && this.activeElement) {
this.activeElement.focus();
}
this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' });
this.setState({ open: !this.state.open });
}
}
handleModalActionClick = (e) => {
e.preventDefault();
const { value } = this.options[e.currentTarget.getAttribute('data-index')];
this.props.onModalClose();
this.props.onChange(value);
}
handleKeyDown = e => {
switch(e.key) {
case 'Escape':
this.handleClose();
break;
}
}
handleMouseDown = () => {
if (!this.state.open) {
this.activeElement = document.activeElement;
}
}
handleButtonKeyDown = (e) => {
switch(e.key) {
case ' ':
case 'Enter':
this.handleMouseDown();
break;
}
}
handleClose = () => {
if (this.state.open && this.activeElement) {
this.activeElement.focus();
}
this.setState({ open: false });
}
handleChange = value => {
this.props.onChange(value);
}
componentWillMount () {
const { intl: { formatMessage } } = this.props;
this.options = [
{ icon: 'globe', value: 'public', text: formatMessage(messages.public_short), meta: formatMessage(messages.public_long) },
{ icon: 'unlock', value: 'unlisted', text: formatMessage(messages.unlisted_short), meta: formatMessage(messages.unlisted_long) },
{ icon: 'lock', value: 'private', text: formatMessage(messages.private_short), meta: formatMessage(messages.private_long) },
{ icon: 'envelope', value: 'direct', text: formatMessage(messages.direct_short), meta: formatMessage(messages.direct_long) },
];
}
render () {
const { value, intl } = this.props;
const { open, placement } = this.state;
const valueOption = this.options.find(item => item.value === value);
return (
<div className={classNames('privacy-dropdown', placement, { active: open })} onKeyDown={this.handleKeyDown}>
<div className={classNames('privacy-dropdown__value', { active: this.options.indexOf(valueOption) === (placement === 'bottom' ? 0 : (this.options.length - 1)) })}>
<IconButton
className='privacy-dropdown__value-icon'
icon={valueOption.icon}
title={intl.formatMessage(messages.change_privacy)}
size={18}
expanded={open}
active={open}
inverted
onClick={this.handleToggle}
onMouseDown={this.handleMouseDown}
onKeyDown={this.handleButtonKeyDown}
style={{ height: null, lineHeight: '27px' }}
/>
</div>
<Overlay show={open} placement={placement} target={this}>
<PrivacyDropdownMenu
items={this.options}
value={value}
onClose={this.handleClose}
onChange={this.handleChange}
placement={placement}
/>
</Overlay>
</div>
);
}
}
|
cmd/elwinator/src/components/Segment.js | foolusion/choices | import React from 'react';
import { isClaimed } from '../nsconv';
const Segment = ({ namespaceSegments, experimentSegments, cellSize, spacing, rows }) => {
const cols = Math.ceil(128 / rows);
const segs = new Array(128).fill(false);
namespaceSegments.forEach((s, i) => {
for (let idx = 0; idx < 8; idx++) {
if (!isClaimed(s, idx)) {
continue;
}
const segIndex = (i*8)+idx
segs[segIndex] = <rect
key={segIndex}
fill="#00295b"
width={cellSize}
height={cellSize}
x={Math.floor(segIndex/rows) * (cellSize + spacing)}
y={(segIndex%rows) * (cellSize + spacing)}
/>;
}
});
experimentSegments.forEach((s, i) => {
for (let idx = 0; idx < 8; idx++) {
if (!isClaimed(s, idx)) {
continue;
}
const segIndex = (i*8)+idx
segs[segIndex] = <rect
key={segIndex}
fill="#69bd28"
width={cellSize}
height={cellSize}
x={Math.floor(segIndex / rows) * (cellSize + spacing)}
y={(segIndex % rows) * (cellSize + spacing)}
/>
}
});
const out = segs.map((s, i) => {
if (s) {
return s;
}
return <rect
key={i}
fill="#b5b6ba"
width={cellSize}
height={cellSize}
x={Math.floor(i/rows) * (cellSize + spacing)}
y={(i%rows) * (cellSize + spacing)}
/>
});
return (
<svg width={cellSize*cols + (cols-1)*spacing} height={cellSize*rows + (rows-1) * spacing}>
{out}
</svg>
);
}
Segment.defaultProps = {
namespaceSegments: [],
experimentSegments: [],
cellSize: 16,
spacing: 2,
rows: 4,
};
export default Segment;
|
content/gocms/src/admin/containers/adminPages/components/mainMenu/MainMenu.js | gocms-io/gocms | 'use strict';
import React from 'react';
import {connect} from 'react-redux'
import {logout} from '../../../../services/authentication'
import {browserHistory} from 'react-router'
class BasicComponent extends React.Component {
constructor(props) {
super(props);
this.handleMenuOpenCloseClick = this.handleMenuOpenCloseClick.bind(this);
this.handleSignOut = this.handleSignOut.bind(this);
this.state = {
menuIsOpen: true
};
}
componentDidMount() {
}
handleSignOut(e){
e.preventDefault();
logout();
browserHistory.push("/login");
}
handleMenuOpenCloseClick(e) {
this.setState({menuIsOpen: !this.state.menuIsOpen});
}
render() {
// console.log("user: ", this.state.user);
return (
<div>
<div
className={"g-container g-a-main-menu-container" + (this.state.menuIsOpen ? " g-a-main-menu-container-open" : " g-a-main-menu-container-close")}>
<div
className={"g-container g-a-main-menu-title-container" + (this.state.menuIsOpen ? " g-a-main-menu-title-container-open" : " g-a-main-menu-title-container-close")}>
<div className="g-a-main-menu-profile-img-container">
<a href="" className="g-a-main-menu-profile-img">
<i className="gocms-icon-user"/>
</a>
</div>
<div className="g-container-col">
<h1 className="g-a-main-menu-title">{GOCMS_LOGIN_TITLE}</h1>
<h2 className="g-a-main-menu-sub-title"><a className="" href="">{this.props.user.fullName}</a><span className="g-a-main-menu-sign-out"><a href="" onClick={this.handleSignOut}>Sign Out</a></span></h2>
</div>
</div>
</div>
<button
className={"g-a-main-menu-btn" + (this.state.menuIsOpen ? " g-a-main-menu-btn-open" : " g-a-main-menu-btn-close")}
onClick={this.handleMenuOpenCloseClick}><i className="gocms-icon-menu"/></button>
</div>
);
}
}
function mapStateToProps(state) {
return {
user: state.auth.user
}
}
export default connect(mapStateToProps, {
})(BasicComponent); |
client/modules/users/components/.stories/friend_requests.js | kaibagoh/PitchSpot | import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { setComposerStub } from 'react-komposer';
import FriendRequests from '../friend_requests.jsx';
storiesOf('users.FriendRequests', module)
.add('default view', () => {
return (
<FriendRequests />
);
})
|
examples/breadcrumbs/app.js | rubengrill/react-router | import React from 'react'
import { render } from 'react-dom'
import { createHistory, useBasename } from 'history'
import { Router, Route, Link } from 'react-router'
require('./app.css')
const history = useBasename(createHistory)({
basename: '/breadcrumbs'
})
class App extends React.Component {
static title = 'Home'
static path = '/'
render() {
const depth = this.props.routes.length
return (
<div>
<aside>
<ul>
<li><Link to={Products.path}>Products</Link></li>
<li><Link to={Orders.path}>Orders</Link></li>
</ul>
</aside>
<main>
<ul className="breadcrumbs-list">
{this.props.routes.map((item, index) =>
<li key={index}>
<Link
onlyActiveOnIndex={true}
activeClassName="breadcrumb-active"
to={item.path || ''}>
{item.component.title}
</Link>
{(index + 1) < depth && '\u2192'}
</li>
)}
</ul>
{this.props.children}
</main>
</div>
)
}
}
class Products extends React.Component {
static title = 'Products'
static path = '/products'
render() {
return (
<div className="Page">
<h1>Products</h1>
</div>
)
}
}
class Orders extends React.Component {
static title = 'Orders'
static path = '/orders'
render() {
return (
<div className="Page">
<h1>Orders</h1>
</div>
)
}
}
render((
<Router history={history}>
<Route path={App.path} component={App}>
<Route path={Products.path} component={Products} />
<Route path={Orders.path} component={Orders} />
</Route>
</Router>
), document.getElementById('example'))
|
app/javascript/mastodon/components/media_gallery.js | tateisu/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { is } from 'immutable';
import IconButton from './icon_button';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { isIOS } from '../is_mobile';
import classNames from 'classnames';
import { autoPlayGif, displayMedia } from '../initial_state';
import { decode } from 'blurhash';
const messages = defineMessages({
toggle_visible: { id: 'media_gallery.toggle_visible', defaultMessage: 'Toggle visibility' },
});
class Item extends React.PureComponent {
static propTypes = {
attachment: ImmutablePropTypes.map.isRequired,
standalone: PropTypes.bool,
index: PropTypes.number.isRequired,
size: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired,
displayWidth: PropTypes.number,
visible: PropTypes.bool.isRequired,
};
static defaultProps = {
standalone: false,
index: 0,
size: 1,
};
state = {
loaded: false,
};
handleMouseEnter = (e) => {
if (this.hoverToPlay()) {
e.target.play();
}
}
handleMouseLeave = (e) => {
if (this.hoverToPlay()) {
e.target.pause();
e.target.currentTime = 0;
}
}
hoverToPlay () {
const { attachment } = this.props;
return !autoPlayGif && attachment.get('type') === 'gifv';
}
handleClick = (e) => {
const { index, onClick } = this.props;
if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
if (this.hoverToPlay()) {
e.target.pause();
e.target.currentTime = 0;
}
e.preventDefault();
onClick(index);
}
e.stopPropagation();
}
componentDidMount () {
if (this.props.attachment.get('blurhash')) {
this._decode();
}
}
componentDidUpdate (prevProps) {
if (prevProps.attachment.get('blurhash') !== this.props.attachment.get('blurhash') && this.props.attachment.get('blurhash')) {
this._decode();
}
}
_decode () {
const hash = this.props.attachment.get('blurhash');
const pixels = decode(hash, 32, 32);
if (pixels) {
const ctx = this.canvas.getContext('2d');
const imageData = new ImageData(pixels, 32, 32);
ctx.putImageData(imageData, 0, 0);
}
}
setCanvasRef = c => {
this.canvas = c;
}
handleImageLoad = () => {
this.setState({ loaded: true });
}
render () {
const { attachment, index, size, standalone, displayWidth, visible } = this.props;
let width = 50;
let height = 100;
let top = 'auto';
let left = 'auto';
let bottom = 'auto';
let right = 'auto';
if (size === 1) {
width = 100;
}
if (size === 4 || (size === 3 && index > 0)) {
height = 50;
}
if (size === 2) {
if (index === 0) {
right = '2px';
} else {
left = '2px';
}
} else if (size === 3) {
if (index === 0) {
right = '2px';
} else if (index > 0) {
left = '2px';
}
if (index === 1) {
bottom = '2px';
} else if (index > 1) {
top = '2px';
}
} else if (size === 4) {
if (index === 0 || index === 2) {
right = '2px';
}
if (index === 1 || index === 3) {
left = '2px';
}
if (index < 2) {
bottom = '2px';
} else {
top = '2px';
}
}
let thumbnail = '';
if (attachment.get('type') === 'unknown') {
return (
<div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
<a className='media-gallery__item-thumbnail' href={attachment.get('remote_url')} target='_blank' style={{ cursor: 'pointer' }} title={attachment.get('description')}>
<canvas width={32} height={32} ref={this.setCanvasRef} className='media-gallery__preview' />
</a>
</div>
);
} else if (attachment.get('type') === 'image') {
const previewUrl = attachment.get('preview_url');
const previewWidth = attachment.getIn(['meta', 'small', 'width']);
const originalUrl = attachment.get('url');
const originalWidth = attachment.getIn(['meta', 'original', 'width']);
const hasSize = typeof originalWidth === 'number' && typeof previewWidth === 'number';
const srcSet = hasSize ? `${originalUrl} ${originalWidth}w, ${previewUrl} ${previewWidth}w` : null;
const sizes = hasSize && (displayWidth > 0) ? `${displayWidth * (width / 100)}px` : null;
const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0;
const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0;
const x = ((focusX / 2) + .5) * 100;
const y = ((focusY / -2) + .5) * 100;
thumbnail = (
<a
className='media-gallery__item-thumbnail'
href={attachment.get('remote_url') || originalUrl}
onClick={this.handleClick}
target='_blank'
>
<img
src={previewUrl}
srcSet={srcSet}
sizes={sizes}
alt={attachment.get('description')}
title={attachment.get('description')}
style={{ objectPosition: `${x}% ${y}%` }}
onLoad={this.handleImageLoad}
/>
</a>
);
} else if (attachment.get('type') === 'gifv') {
const autoPlay = !isIOS() && autoPlayGif;
thumbnail = (
<div className={classNames('media-gallery__gifv', { autoplay: autoPlay })}>
<video
className='media-gallery__item-gifv-thumbnail'
aria-label={attachment.get('description')}
title={attachment.get('description')}
role='application'
src={attachment.get('url')}
onClick={this.handleClick}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
autoPlay={autoPlay}
loop
muted
/>
<span className='media-gallery__gifv__label'>GIF</span>
</div>
);
}
return (
<div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
<canvas width={32} height={32} ref={this.setCanvasRef} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && this.state.loaded })} />
{visible && thumbnail}
</div>
);
}
}
export default @injectIntl
class MediaGallery extends React.PureComponent {
static propTypes = {
sensitive: PropTypes.bool,
standalone: PropTypes.bool,
media: ImmutablePropTypes.list.isRequired,
size: PropTypes.object,
height: PropTypes.number.isRequired,
onOpenMedia: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
defaultWidth: PropTypes.number,
cacheWidth: PropTypes.func,
visible: PropTypes.bool,
onToggleVisibility: PropTypes.func,
};
static defaultProps = {
standalone: false,
};
state = {
visible: this.props.visible !== undefined ? this.props.visible : (displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all'),
width: this.props.defaultWidth,
};
componentWillReceiveProps (nextProps) {
if (!is(nextProps.media, this.props.media) && nextProps.visible === undefined) {
this.setState({ visible: displayMedia !== 'hide_all' && !nextProps.sensitive || displayMedia === 'show_all' });
} else if (!is(nextProps.visible, this.props.visible) && nextProps.visible !== undefined) {
this.setState({ visible: nextProps.visible });
}
}
handleOpen = () => {
if (this.props.onToggleVisibility) {
this.props.onToggleVisibility();
} else {
this.setState({ visible: !this.state.visible });
}
}
handleClick = (index) => {
this.props.onOpenMedia(this.props.media, index);
}
handleRef = (node) => {
if (node /*&& this.isStandaloneEligible()*/) {
// offsetWidth triggers a layout, so only calculate when we need to
if (this.props.cacheWidth) this.props.cacheWidth(node.offsetWidth);
this.setState({
width: node.offsetWidth,
});
}
}
isStandaloneEligible() {
const { media, standalone } = this.props;
return standalone && media.size === 1 && media.getIn([0, 'meta', 'small', 'aspect']);
}
render () {
const { media, intl, sensitive, height, defaultWidth } = this.props;
const { visible } = this.state;
const width = this.state.width || defaultWidth;
let children, spoilerButton;
const style = {};
if (this.isStandaloneEligible()) {
if (width) {
style.height = width / this.props.media.getIn([0, 'meta', 'small', 'aspect']);
}
} else if (width) {
style.height = width / (16/9);
} else {
style.height = height;
}
const size = media.take(4).size;
if (this.isStandaloneEligible()) {
children = <Item standalone onClick={this.handleClick} attachment={media.get(0)} displayWidth={width} visible={visible} />;
} else {
children = media.take(4).map((attachment, i) => <Item key={attachment.get('id')} onClick={this.handleClick} attachment={attachment} index={i} size={size} displayWidth={width} visible={visible} />);
}
if (visible) {
spoilerButton = <IconButton title={intl.formatMessage(messages.toggle_visible)} icon='eye-slash' overlay onClick={this.handleOpen} />;
} else {
spoilerButton = (
<button type='button' onClick={this.handleOpen} className='spoiler-button__overlay'>
<span className='spoiler-button__overlay__label'>{sensitive ? <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' /> : <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />}</span>
</button>
);
}
return (
<div className='media-gallery' style={style} ref={this.handleRef}>
<div className={classNames('spoiler-button', { 'spoiler-button--minified': visible })}>
{spoilerButton}
</div>
{children}
</div>
);
}
}
|
src/CollapsibleMixin.js | xiaoking/react-bootstrap | import React from 'react';
import TransitionEvents from './utils/TransitionEvents';
import deprecationWarning from './utils/deprecationWarning';
const CollapsibleMixin = {
propTypes: {
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState() {
const defaultExpanded = this.props.defaultExpanded != null ?
this.props.defaultExpanded : !!this.props.expanded;
return {
expanded: defaultExpanded,
collapsing: false
};
},
componentWillMount() {
deprecationWarning('CollapsibleMixin', 'Collapse Component');
},
componentWillUpdate(nextProps, nextState) {
let willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded;
if (willExpanded === this.isExpanded()) {
return;
}
// if the expanded state is being toggled, ensure node has a dimension value
// this is needed for the animation to work and needs to be set before
// the collapsing class is applied (after collapsing is applied the in class
// is removed and the node's dimension will be wrong)
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = '0';
if (!willExpanded) {
value = this.getCollapsibleDimensionValue();
}
node.style[dimension] = value + 'px';
this._afterWillUpdate();
},
componentDidUpdate(prevProps, prevState) {
// check if expanded is being toggled; if so, set collapsing
this._checkToggleCollapsing(prevProps, prevState);
// check if collapsing was turned on; if so, start animation
this._checkStartAnimation();
},
// helps enable test stubs
_afterWillUpdate() {
},
_checkStartAnimation() {
if (!this.state.collapsing) {
return;
}
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let value = this.getCollapsibleDimensionValue();
// setting the dimension here starts the transition animation
let result;
if (this.isExpanded()) {
result = value + 'px';
} else {
result = '0px';
}
node.style[dimension] = result;
},
_checkToggleCollapsing(prevProps, prevState) {
let wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded;
let isExpanded = this.isExpanded();
if (wasExpanded !== isExpanded) {
if (wasExpanded) {
this._handleCollapse();
} else {
this._handleExpand();
}
}
},
_handleExpand() {
let node = this.getCollapsibleDOMNode();
let dimension = this.dimension();
let complete = () => {
this._removeEndEventListener(node, complete);
// remove dimension value - this ensures the collapsible item can grow
// in dimension after initial display (such as an image loading)
node.style[dimension] = '';
this.setState({
collapsing:false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
_handleCollapse() {
let node = this.getCollapsibleDOMNode();
let complete = () => {
this._removeEndEventListener(node, complete);
this.setState({
collapsing: false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
// helps enable test stubs
_addEndEventListener(node, complete) {
TransitionEvents.addEndEventListener(node, complete);
},
// helps enable test stubs
_removeEndEventListener(node, complete) {
TransitionEvents.removeEndEventListener(node, complete);
},
dimension() {
return (typeof this.getCollapsibleDimension === 'function') ?
this.getCollapsibleDimension() :
'height';
},
isExpanded() {
return this.props.expanded != null ? this.props.expanded : this.state.expanded;
},
getCollapsibleClassSet(className) {
let classes = {};
if (typeof className === 'string') {
className.split(' ').forEach(subClasses => {
if (subClasses) {
classes[subClasses] = true;
}
});
}
classes.collapsing = this.state.collapsing;
classes.collapse = !this.state.collapsing;
classes.in = this.isExpanded() && !this.state.collapsing;
return classes;
}
};
export default CollapsibleMixin;
|
StudyNotes/ReactNative_/component/message.js | coderZsq/coderZsq.target.swift | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image
} from 'react-native';
var Message = React.createClass({
render(){
return (
<Text>message</Text>
)
},
});
const styles = StyleSheet.create({
});
module.exports = Message
|
src/Nav.js | kishoreyarram/my-portfolio | import React, { Component } from 'react';
import { Link } from 'react-router';
class Nav extends Component {
constructor(props) {
super(props);
this.state = {
showNavBar: false,
};
this.renderNav = this.renderNav.bind(this);
this.onNavshow = this.onNavshow.bind(this);
}
onNavshow() {
const { showNavBar } = this.state;
this.setState({
showNavBar: !showNavBar,
});
}
renderNav() {
if (this.state.showNavBar) {
return (
<nav className="navbar">
<ul className="nav nav-pills nav-stacked">
<li><Link to="/about">About</Link></li>
<li><Link to="/experience">Experience</Link></li>
<li><Link to="/social">Social Media</Link></li>
<li><Link to="/contact">Contact me</Link></li>
</ul>
</nav>
);
}
return null;
}
render() {
return (
<div className="nav-bar col-md-2 col-sm-2 col-xs-12">
<button onClick={this.onNavshow} className="menu-button"><span className={this.state.showNavBar ? 'glyphicon glyphicon-remove menu-remove' : 'glyphicon glyphicon-menu-hamburger menu-add'} /></button>
{this.renderNav()}
</div>
);
}
}
export default Nav;
|
src/components/splitPane/SplitPane.js | sanjay1909/WeaveReact | import React from 'react';
import ReactDOM from "react-dom";
import Style from "../../utils/Style";
import SplitPaneConfig from "./SplitPaneConfig";
import Pane from './Pane';
import Resizer from './Resizer';
//code logic taken from https://github.com/tomkp/react-split-pane
class SplitPane extends React.Component {
constructor(props) {
super(props);
this.settings = this.props.settings ? this.props.settings : new SplitPaneConfig();
this.onMouseDown = this.onMouseDown.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
}
componentDidMount() {
this.settings.active.addGroupedCallback(this, this.forceUpdate);
this.settings.resized.addGroupedCallback(this, this.forceUpdate);
this.settings.position.addGroupedCallback(this, this.forceUpdate);
this.settings.unFocusCount.addImmediateCallback(this, this.unFocus);
document.addEventListener('mouseup', this.onMouseUp);
document.addEventListener('mousemove', this.onMouseMove);
const ref = this.refs.pane1;
if (ref && this.props.defaultSize && !this.settings.resized.value) {
this.settings.pane1.size.value = this.props.defaultSize;
//ref.setSessionState( this.props.defaultSize);
}
}
componentWillUnmount() {
this.settings.active.removeCallback(this, this.forceUpdate);
this.settings.resized.removeCallback(this, this.forceUpdate);
this.settings.position.removeCallback(this, this.forceUpdate);
this.settings.unFocusCount.removeCallback(this, this.unFocus);
document.removeEventListener('mouseup', this.onMouseUp);
document.removeEventListener('mousemove', this.onMouseMove);
}
onMouseDown(event) {
this.settings.updateUnFocus();
let position = this.props.split === 'vertical' ? event.clientX : event.clientY;
this.settings.position.value = position;
this.settings.active.value = true;
}
onMouseMove(event) {
if (this.settings.active.value) {
this.settings.updateUnFocus();
const ref = this.refs.pane1;
if (ref) {
const node = ReactDOM.findDOMNode(ref);
if (node.getBoundingClientRect) {
const width = node.getBoundingClientRect().width;
const height = node.getBoundingClientRect().height;
const current = this.props.split === 'vertical' ? event.clientX : event.clientY;
const size = this.props.split === 'vertical' ? width : height;
const position = this.settings.position.value;
const newSize = size - (position - current);
this.settings.position.value = current;
this.settings.resized.value = true;
if (newSize >= this.props.minSize) {
if (this.props.onChange) {
this.props.onChange(newSize);
}
this.settings.pane1.size.value = newSize;
}
}
}
}
}
onMouseUp() {
if (this.settings.active.value) {
if (this.props.onDragFinished) {
this.props.onDragFinished();
}
this.settings.active.value = false;
}
}
unFocus() { // need to be called change of session value so that we can see them in session Log
if (document.selection) {
document.selection.empty();
} else {
window.getSelection().removeAllRanges()
}
}
componentWillReceiveProps(nextProps){
if(this.props.settings !== nextProps.settings){
this.settings.active.removeCallback(this, this.forceUpdate);
this.settings.resized.removeCallback(this, this.forceUpdate);
this.settings.position.removeCallback(this, this.forceUpdate);
this.settings.unFocusCount.removeCallback(this, this.unFocus);
this.settings = nextProps.settings;
this.settings.active.addGroupedCallback(this, this.forceUpdate);
this.settings.resized.addGroupedCallback(this, this.forceUpdate);
this.settings.position.addGroupedCallback(this, this.forceUpdate);
this.settings.unFocusCount.addImmediateCallback(this, this.unFocus);
}
}
render() {
const split = this.props.split;
let styleObj = Style.appendVendorPrefix({
display: 'flex',
flex: 1,
position: 'relative',
outline: 'none',
overflow: 'hidden',
MozUserSelect: 'text',
WebkitUserSelect: 'text',
msUserSelect: 'text',
userSelect: 'text'
});
if (split === 'vertical') {
Style.mergeStyleObjects(styleObj, {
flexDirection: 'row',
height: '100%',
position: 'absolute',
left: 0,
right: 0
}, true);
} else {
Style.mergeStyleObjects(styleObj, {
flexDirection: 'column',
height: '100%',
minHeight: '100%',
position: 'absolute',
top: 0,
bottom: 0,
width: '100%'
}, true);
}
const children = this.props.children;
const classes = ['SplitPane', split];
return ( <div className = {classes.join(' ')} style = { styleObj } ref = "splitPane">
<Pane ref = "pane1" key = "pane1" split = {split} settings = { this.settings.pane1 } >
{children[0]}
</Pane>
<Resizer ref = "resizer" key = "resizer" onMouseDown = { this.onMouseDown } split = { split } />
<Pane ref = "pane2" key = "pane2" split = { split } settings = { this.settings.pane2 } >
{children[1]}
</Pane>
</div>
);
}
}
SplitPane.defaultProps = {
minSize: 0,
split: "vertical"
};
export default SplitPane;
|
src/client/auth/index.react.js | laxplaer/este | import Component from '../components/component.react';
import DocumentTitle from 'react-document-title';
import Login from './login.react';
import React from 'react';
export default class AuthIndex extends Component {
static propTypes = {
msg: React.PropTypes.object.isRequired
}
render() {
const {msg} = this.props;
return (
<DocumentTitle title={msg.auth.index.title}>
<div className="login-page">
<Login {...this.props} />
</div>
</DocumentTitle>
);
}
}
|
app/components/main.js | tatsuhino/electron-react-redux-boilerplate | import React from 'react'
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import rootReducer from '../reducers/index.js'
import Root from './Root.js'
var TodoApp = React.createClass({
getInitialState: function(){
return {
todos: []
}
},
onAdd: function(newTodo){
this.setState({
todos : this.state.todos.concat({item:newTodo, status:0})
});
},
onDelete: function(i){
var targetTodo = this.state.todos[i];
targetTodo.status = 1;
this.setState({
todos: this.state.todos
});
},
render: function(){
return (
<div className="TodoApp">
<TodoCreator onAdd={this.onAdd}/>
<TodoList todos={this.state.todos} onDelete={this.onDelete}/>
</div>
);
}
});
var TodoCreator = React.createClass({
getInitialState: function(){
return {
value: ""
}
},
_onAdd: function(){
var newTodo = TodoCreator.value;
this.props.onAdd(newTodo);
this.setState({value: ""});
},
_onChange: function(e){
this.setState({
value: e.target.value
});
},
render: function(){
return (
<div className="TodoCreator">
<input type="text" value={this.state.value} ref="inputText" placeholder="Input your new todo" onChange={this._onChange}/>
<button onClick={this._onAdd}>Add</button>
</div>
);
}
});
var TodoList = React.createClass({
_onDelete: function(i){
this.props.onDelete(i);
},
render: function() {
return (
<ul>
{
this.props.todos.map(function(todo,i){
if (todo.status == 0) {
return (
<li key={i}>
<input type="checkbox"
onClick={this._onDelete.bind(this,i )}/>{todo.item}
</li>
)
} else {
return <li key={i}><s>{todo.item}</s></li>
}
},this)
}
</ul>
);
}
});
ReactDOM.render(
<TodoApp/>,
document.getElementById('myApp')
);
|
src/containers/WeatherList.js | omarchacinortega13/react-redux-weather-map | import React from 'react';
import {connect} from 'react-redux';
import Chart from '../components/Chart';
import GoogleMap from '../components/GoogleMap';
class WeatherList extends React.Component {
renderWeather(cityData) {
const name = cityData.city.name;
const temps = cityData.list.map((weather) => weather.main.temp);
const humidities = cityData.list.map((weather) => weather.main.humidity);
const pressures = cityData.list.map((weather) => weather.main.pressure);
const { lon, lat } = cityData.city.coord;
return (
<tr key={name}>
<td>
<GoogleMap lat={lat} lon={lon}/>
</td>
<td>
<Chart data={temps} color="red" unit={"K"}/>
</td>
<td>
<Chart data={pressures} color="yellow" unit={"hPa"}/>
</td>
<td>
<Chart data={humidities} color="blue" unit={"%"}/>
</td>
</tr>
)
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (K)</th>
<th>Pressure (hPa)</th>
<th>Humidity (%)</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
)
}
}
function mapStateToprops({weather}) {
return {
weather
}
}
export default connect(mapStateToprops)(WeatherList); |
packages/demos/todomvc/src/components/Footer/index.js | yusufsafak/cerebral | import React from 'react'
import { connect } from 'cerebral/react'
import { state, signal } from 'cerebral/tags'
import counts from '../../computed/counts'
import classnames from 'classnames'
const filters = ['All', 'Active', 'Completed']
export default connect(
{
filter: state`filter`,
counts,
filterClicked: signal`filterClicked`,
clearCompletedClicked: signal`clearCompletedClicked`,
},
function Footer({ filter, counts, filterClicked, clearCompletedClicked }) {
return (
<footer className="footer">
<span className="todo-count">
<strong>
{counts.remaining} {counts.remaining === 1 ? 'item' : 'items'} left
</strong>
</span>
<ul className="filters">
{filters.map(filterName => (
<li key={filterName}>
<a
onClick={() =>
filterClicked({ filter: filterName.toLowerCase() })}
className={classnames({
selected: filter === filterName.toLowerCase(),
})}
>
{filterName}
</a>
</li>
))}
</ul>
{!!counts.completed &&
<button
className="clear-completed"
onClick={() => clearCompletedClicked()}
>
Clear completed ({counts.completed})
</button>}
</footer>
)
}
)
|
src/web/components/PatientView/index.js | asha-nepal/AshaFusionCross | /**
* Copyright 2017 Yuichiro Tsuchiya
* Copyright 2017 Yuguan Xing
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* @flow */
import React, { Component } from 'react';
import _get from 'lodash.get';
import Header from './Header';
import PatientInfoOneline from './PatientInfoOneline';
import RecordsTab from './RecordsTab';
import Footer from './Footer';
import RecordChartToggle from '../../containers/PatientView/RecordChartToggle';
import RecordChartSelector from '../../containers/PatientView/RecordChartSelector';
import DynamicForm from '../../forms/DynamicForm';
import Select from '../Select';
type Props = {
init: () => void,
isFetching: boolean,
patient: PatientObject,
records: Array<RecordObject>,
addNewActiveRecord: () => void,
putActivePatient: () => void,
putActiveRecord: (index: number) => void,
putDformStyles: () => void,
removeActivePatient: () => void,
isNew: boolean,
isPuttingPatient: boolean,
isPuttingRecord: boolean,
patientFormVisibility: boolean,
setPatientFormVisibility: (visibility: boolean) => void,
selectedActiveRecordIndex: number,
selectActiveRecord: (id: string) => void,
setRecordFormStyleId: (styleId: string) => void,
patientFormStyle: DformStyle,
recordFormStyles: List<Map<string, DformStyle | string>>,
recordFormStyleId: string,
recordFormStyle: ?DformStyle,
params: ?Object,
patientId: ?string,
duplicatedPatientsExist: {
name: boolean,
number: boolean,
},
activeRecordsFormPristineness: Array<boolean>,
nextPatientNumber: number,
};
export default class PatientView extends Component {
componentWillMount() {
this.props.init();
}
props: Props;
render() {
const {
isFetching,
patient,
records,
addNewActiveRecord,
putActivePatient,
putActiveRecord,
putDformStyles,
removeActivePatient,
isNew,
isPuttingPatient,
isPuttingRecord,
patientFormVisibility,
setPatientFormVisibility,
selectedActiveRecordIndex,
selectActiveRecord,
setRecordFormStyleId,
patientFormStyle,
recordFormStyles,
recordFormStyleId,
recordFormStyle,
duplicatedPatientsExist,
activeRecordsFormPristineness,
nextPatientNumber = 1,
} = this.props;
if (isFetching) {
return <div>Fetching...</div>;
}
const showRecord = !isNew && recordFormStyle;
return (
<div>
<Header
patient={patient}
record={selectedActiveRecordIndex > -1 ? records[selectedActiveRecordIndex] : null}
onBackClick={() => {
if (activeRecordsFormPristineness.some(x => !x)) {
return confirm('Record(s) is (are) changed but not saved.\nIs it ok to go back?');
}
return true;
}}
/>
{/* TODO: <Refactoring> Extract the block below to another component */}
<div className="card">
<div className="card-content">
<div className="container">
{(isNew || patientFormVisibility)
?
<div className="columns">
<div className="column">
<DynamicForm
model="activePatient"
style={patientFormStyle}
freeze={isPuttingPatient}
onSubmit={putActivePatient}
onRemove={isNew ? null : (() => {
if (confirm('Are you sure?')) {
removeActivePatient();
}
})}
warnings={duplicatedPatientsExist ? {
name: duplicatedPatientsExist.name && 'Duplicated',
number: duplicatedPatientsExist.number && 'Duplicated',
} : undefined}
fieldOptions={{
number: { nextPatientNumber },
}}
/>
</div>
{!isNew &&
<div className="column is-narrow">
<a
className="delete is-pulled-right"
aria-label="close"
onClick={e => {
e.preventDefault();
setPatientFormVisibility(false);
}}
/>
</div>
}
</div>
:
<div className="columns">
<div className="column">
<PatientInfoOneline
patient={patient}
/>
</div>
<div className="column is-narrow">
<a
className="icon is-pulled-right"
aria-label="edit"
onClick={e => {
e.preventDefault();
setPatientFormVisibility(true);
}}
>
<i className="fa fa-pencil-square-o" />
</a>
</div>
</div>
}
</div>
</div>
</div>
{showRecord &&
<section className="section">
<div className="container">
<div className="columns">
<RecordsTab
records={records}
selectedActiveRecordIndex={selectedActiveRecordIndex}
selectActiveRecord={selectActiveRecord}
addNewActiveRecord={addNewActiveRecord}
pristinenessList={activeRecordsFormPristineness}
/>
<div className="column is-narrow">
{recordFormStyles.size > 1 &&
<Select
value={recordFormStyleId}
onChange={setRecordFormStyleId}
options={recordFormStyles.map(style =>
({ id: style.get('id'), label: style.get('label') })
)}
/>
}
<RecordChartToggle />
</div>
</div>
<RecordChartSelector records={records} />
{selectedActiveRecordIndex > -1 && (
<div className="container">
<DynamicForm
model={`activeRecords[${selectedActiveRecordIndex}]`}
formGroup="record"
formStyleId={recordFormStyleId}
style={recordFormStyle}
freeze={isPuttingRecord}
getPreviousData={(path: string) => {
// FIXME: Logics in view component.
// This function should be outside of this component.
const prevIndex = selectedActiveRecordIndex - 1;
const prevRecord = records[prevIndex];
if (prevRecord) {
return _get(prevRecord, path);
}
return null;
}}
onFormsSave={putDformStyles}
// customizable // TODO: Temporarily disabled
/>
</div>
)}
</div>
</section>
}
{showRecord &&
<Footer
onSubmit={
selectedActiveRecordIndex > -1
&& !activeRecordsFormPristineness[selectedActiveRecordIndex]
? () => putActiveRecord(selectedActiveRecordIndex) : undefined
}
freeze={isPuttingRecord}
/>
}
</div>
);
}
}
|
src/pages/configurator/CreatePackageCategoryPage.js | belaczek/BeerCheese-client | import React, { Component } from 'react';
import {
Row,
Col,
Button,
Nav,
NavItem,
NavLink,
NavbarBrand,
} from 'reactstrap';
import ProductList from '../../components/product/ProductList';
import localizedTexts from '../../text_localization/LocalizedStrings';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { categoriesApi } from '../../actions/categories';
class CreatePackageCategoryPage extends Component {
state = {
currentCategory: null,
filterCategoryId: null
};
componentDidMount() {
this.setCurrentCategory();
}
componentDidUpdate() {
if (this.state.currentCategory === null || (parseInt(this.state.currentCategory.id, 10) !== parseInt(this.props.location.query.category, 10) && this.props.location.query.category !== undefined)) {
this.setCurrentCategory();
}
}
setCurrentCategory() {
const { categories } = this.props.categories;
const currentCategory = this.props.location.query.category;
if (categories !== null && categories.length > 0) {
if (currentCategory === undefined) {
this.setState({ currentCategory: categories[0].category, filterCategoryId: categories[0].category.id });
} else {
categories.forEach((category) => {
category = category.category;
if (parseInt(category.id, 10) === parseInt(currentCategory, 10)) {
this.setState({ currentCategory: category, filterCategoryId: category.id });
}
});
}
}
}
renderSubCategories() {
const categories = this.props.categories;
const { currentCategory } = this.state;
if (currentCategory === null) {
return null;
}
return categories.categories.map((category) => {
category = category.category;
if (category.mainCategory === currentCategory.links.self) {
return (<NavItem key={category.id}>
<NavLink
tag={Link}
to="#"
onClick={(e)=>{this.setState({filterCategoryId: category.id}); e.preventDefault();}}
>
{category.name}
</NavLink>
</NavItem>)
} else {
return null;
}
});
}
render() {
return (
<Row>
<Col xl="2" lg="2" md="4" sm="12" xs="12">
<Nav vertical>
<NavbarBrand>{localizedTexts.HomePage.categories}</NavbarBrand>
{this.renderSubCategories()}
</Nav>
</Col>
<Col xl="10" lg="10" md="8" sm="12" xs="12">
<ProductList itemSize="250" categoryId={this.state.filterCategoryId} addCartButton={true} currentPackage={this.props.currentPackage}/>
<Button>{localizedTexts.HomePage.previous}</Button>
<Button>{localizedTexts.HomePage.next}</Button>
</Col>
</Row>
);
}
}
const mapSateToProps = state => ({
categories: state.categories
});
export default connect(mapSateToProps, { categoriesApi })(CreatePackageCategoryPage); |
fields/types/date/DateFilter.js | asifiqbal84/keystone | import _ from 'underscore';
import classNames from 'classnames';
import React from 'react';
import { FormField, FormInput, FormRow, FormSelect, SegmentedControl } from 'elemental';
const TOGGLE_OPTIONS = [
{ label: 'Matches', value: false },
{ label: 'Does NOT Match', value: true }
];
const MODE_OPTIONS = [
{ label: 'On', value: 'on' },
{ label: 'After', value: 'after' },
{ label: 'Before', value: 'before' },
{ label: 'Between', value: 'between' }
];
var NumberFilter = React.createClass({
getInitialState () {
return {
modeValue: MODE_OPTIONS[0].value, // 'on'
modeLabel: MODE_OPTIONS[0].label, // 'On'
inverted: TOGGLE_OPTIONS[0].value,
value: ''
};
},
componentDidMount () {
// focus the text input
React.findDOMNode(this.refs.input).focus();
},
toggleInverted (value) {
this.setState({
inverted: value
});
},
selectMode (mode) {
// TODO: implement w/o underscore
this.setState({
modeValue: mode,
modeLabel: _.findWhere(MODE_OPTIONS, { value: mode }).label
});
// focus the text input after a mode selection is made
React.findDOMNode(this.refs.input).focus();
},
renderToggle () {
return (
<FormField>
<SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.state.inverted} onChange={this.toggleInverted} />
</FormField>
);
},
renderControls () {
let controls;
let { field } = this.props;
let { modeLabel, modeValue } = this.state;
let placeholder = field.label + ' is ' + modeLabel.toLowerCase() + '...';
if (modeValue === 'between') {
controls = (
<FormRow>
<FormField width="one-half">
<FormInput ref="input" placeholder="From" />
</FormField>
<FormField width="one-half">
<FormInput placeholder="To" />
</FormField>
</FormRow>
);
} else {
controls = (
<FormField>
<FormInput ref="input" placeholder={placeholder} />
</FormField>
);
}
return controls;
},
render () {
let { modeLabel, modeValue } = this.state;
return (
<div>
{this.renderToggle()}
<FormSelect options={MODE_OPTIONS} onChange={this.selectMode} value={modeValue} />
{this.renderControls()}
</div>
);
}
});
module.exports = NumberFilter;
|
src/components/common/icons/Comment.js | WendellLiu/GoodJobShare | import React from 'react';
/* eslint-disable */
const Comment = (props) => (
<svg {...props} width="148" height="148" viewBox="0 0 148 148">
<path d="M137.990055,26.1850909 C131.387,18.1457182 122.417969,11.7956045 111.085273,7.13532273 C99.7528672,2.47561364 87.3720312,0.145186364 73.9471016,0.145186364 C63.9331094,0.145186364 54.3596484,1.52116364 45.2267187,4.27369091 C36.0937891,7.02593182 28.226375,10.7460818 21.6238984,15.4332818 C15.0202656,20.1210545 9.76713281,25.6942636 5.86016406,32.1526227 C1.95319531,38.6112682 0,45.3840545 0,52.4698364 C0,60.6452318 2.48882812,68.3057455 7.46850781,75.4459364 C12.4481875,82.5852682 19.2558984,88.5817227 27.8948203,93.4327227 C27.2889453,95.6122364 26.5738047,97.6840773 25.7482422,99.6448091 C24.9229687,101.606973 24.1803672,103.216909 23.5201484,104.470323 C22.8593516,105.723736 21.9661484,107.114318 20.8373594,108.64035 C19.7103047,110.166095 18.8575703,111.243109 18.2797344,111.8691 C17.7024766,112.496236 16.7534844,113.533445 15.4321797,114.975859 C14.1126094,116.421423 13.2592969,117.360982 12.8745547,117.797973 C12.8187656,117.823459 12.5990781,118.070591 12.2140469,118.533068 C11.8293047,118.995545 11.6362109,119.226927 11.6362109,119.226927 L11.1410469,119.961736 C10.8655703,120.371523 10.7418516,120.630109 10.7690234,120.736923 C10.7967734,120.843736 10.7418516,121.118073 10.6042578,121.553345 C10.466375,121.990336 10.4805391,122.31765 10.6453047,122.536432 L10.6453047,122.617759 C10.8664375,123.5997 11.3477266,124.389491 12.0900391,124.987991 C12.8323516,125.587064 13.6723672,125.832764 14.6071953,125.721941 C18.1843437,125.286095 21.3200937,124.689314 24.0156016,123.924723 C38.4311484,120.271295 51.0860156,113.678059 61.9793359,104.137855 C66.1048359,104.5737 70.0938984,104.792482 73.9453672,104.792482 C87.3700078,104.792482 99.7502656,102.462055 111.083828,97.8003409 C122.417391,93.1406318 131.385555,86.7902318 137.987453,78.7522909 C144.590508,70.7163545 147.891602,61.9533409 147.891602,52.46955 C147.891891,42.9854727 144.591086,34.2230318 137.990055,26.1850909 Z" transform="translate(0 12)"/>
</svg>
);
/* eslint-enable */
export default Comment;
|
app/javascript/components/borrow_booking_calendar/DateInput.js | leihs/leihs_legacy | import React from 'react'
import createReactClass from 'create-react-class'
const DateInput = createReactClass({
displayName: 'DateInput ',
propTypes: {
},
getInitialState () {
return {
dateString: this.props.dateString
}
},
componentDidMount () {
},
componentWillReceiveProps(nextProps) {
if (this.props.dateString != nextProps.dateString) {
this.setState({dateString: nextProps.dateString})
}
},
onChangeCallback(event) {
const val = event.target.value
this.setState({dateString: val},
() => {
const date = moment(val, i18n.date.L, true)
if (date.isValid()) {
this.props.onChangeCallback(date)
}
}
)
},
render () {
return (
<input
autoComplete="off"
type="text"
id={this.props.id}
value={this.state.dateString}
onChange={this.onChangeCallback}
/>
)
}
})
export default DateInput
|
docs/src/app/components/pages/components/Paper/Page.js | nathanmarks/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import paperReadmeText from './README';
import PaperExampleSimple from './ExampleSimple';
import paperExampleSimpleCode from '!raw!./ExampleSimple';
import PaperExampleRounded from './ExampleRounded';
import paperExampleRoundedCode from '!raw!./ExampleRounded';
import PaperExampleCircle from './ExampleCircle';
import paperExampleCircleCode from '!raw!./ExampleCircle';
import paperCode from '!raw!material-ui/Paper/Paper';
const descriptions = {
simple: 'Paper examples showing the range of `zDepth`.',
rounded: 'Corners are rounded by default. Set the `rounded` property to `false` for square corners.',
circle: 'Set the `circle` property for circular Paper.',
};
const PaperPage = () => (
<div>
<Title render={(previousTitle) => `Paper - ${previousTitle}`} />
<MarkdownElement text={paperReadmeText} />
<CodeExample
title="Simple example"
description={descriptions.simple}
code={paperExampleSimpleCode}
>
<PaperExampleSimple />
</CodeExample>
<CodeExample
title="Non-rounded corners"
description={descriptions.rounded}
code={paperExampleRoundedCode}
>
<PaperExampleRounded />
</CodeExample>
<CodeExample
title="Circular Paper"
description={descriptions.circle}
code={paperExampleCircleCode}
>
<PaperExampleCircle />
</CodeExample>
<PropTypeDescription code={paperCode} />
</div>
);
export default PaperPage;
|
src/components/popup/IndexComponent.js | Philin-Anton/prototypeApp | 'use strict';
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
require('styles/popup/Index.scss');
import FileChoose from '../FileChooseComponent';
import EditImage from '../EditImageComponent';
import EditLinkText from '../EditLinkTextComponent';
import { actionPopUpBlock } from '../../actions/index';
const openPopUp = actionPopUpBlock.openPopUp;
const closePopUp = actionPopUpBlock.closePopUp;
const changeStepPopUp = actionPopUpBlock.changeStepPopUp;
const setImagePopUp = actionPopUpBlock.setImagePopUp;
class IndexComponent extends React.Component {
eachContent(){
const {popUpBlock} = this.props;
this.content = null;
switch (popUpBlock.step){
case null:{
this.content = null;
break;
}
case 'choose-img':{
this.content = <FileChoose />;
break;
}
case 'edit-img':{
this.content = <EditImage imageURL={popUpBlock.image}/>;
break;
}
case 'edit-link-text':{
this.content = <EditLinkText/>;
break;
}
}
return this.content
}
closePopUp(e){
if(!e.target.closest('.close-popUp') && e.target.closest('.popUpContainer')) return false;
const {closePopUp, setImagePopUp} = this.props;
closePopUp(false);
setImagePopUp(null);
}
render() {
const {popUpBlock} = this.props;
if(!popUpBlock.open){
return null;
}
return (
<div className="popupindex-component">
<div className="popUpBackground" onClick={this.closePopUp.bind(this)}></div>
<div className={'popUpContainer ' + popUpBlock.step}>
<div className="headerPopUp">
{popUpBlock.title || popUpBlock.step}
<div className="close-popUp" onClick={this.closePopUp.bind(this)}>
<span className="action-icon action-icon-close"></span>
</div>
</div>
<div className="contentPopUp">
{this.eachContent.apply(this)}
</div>
</div>
</div>
);
}
}
IndexComponent.displayName = 'PopupIndexComponent';
// Uncomment properties you need
// IndexComponent.propTypes = {};
// IndexComponent.defaultProps = {};
const getPopUpBlockState = state => state.PopUpBlock;
const getWidgetBlocksState = state => state.WidgetBlocks;
const select = createSelector([getPopUpBlockState, getWidgetBlocksState], (popUpBlock, widgetBlocks) => {
return {popUpBlock, widgetBlocks};
});
export default connect(select, { openPopUp, closePopUp, changeStepPopUp, setImagePopUp })(IndexComponent);
|
src/svg-icons/navigation/subdirectory-arrow-left.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationSubdirectoryArrowLeft = (props) => (
<SvgIcon {...props}>
<path d="M11 9l1.42 1.42L8.83 14H18V4h2v12H8.83l3.59 3.58L11 21l-6-6 6-6z"/>
</SvgIcon>
);
NavigationSubdirectoryArrowLeft = pure(NavigationSubdirectoryArrowLeft);
NavigationSubdirectoryArrowLeft.displayName = 'NavigationSubdirectoryArrowLeft';
NavigationSubdirectoryArrowLeft.muiName = 'SvgIcon';
export default NavigationSubdirectoryArrowLeft;
|
src/components/Project.js | ZachShaw/portfolio-react | import React, { Component } from 'react';
import { Link, IndexLink } from 'react-router';
import '../styles/components/Project.scss';
class Project extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
}
render() {
return (
<Link className="project-flip" to={`/projects/${this.props.project.url}`}>
<div className="project-container">
<div className="project">
<div className="topFlip">
{this.props.project.title}
<div className="fw-overlay">
<img className="fw-logo" src={require(`../assets/images/${this.props.project.fwImg}`)} />
</div>
</div>
<div className="bottomFlop">
<div>
<p>Find out more</p>
</div>
</div>
</div>
</div>
</Link>
)
}
}
export default Project
|
ReactJS_Redux_CartApp/src/components/CartItem.js | canhphong/canhphong.github.io | import React, { Component } from 'react';
import * as Message from './../constants/Message';
class CartItem extends Component {
render() {
var { item } = this.props;
var { quantity } = item;
return (
<tr>
<th scope="row">
<img src={item.product.image}
alt={item.product.name} className="img-fluid z-depth-0" />
</th>
<td>
<h5>
<strong>{item.product.name}</strong>
</h5>
</td>
<td>{item.product.price}$</td>
<td className="center-on-small-only">
<span className="qty">{quantity}</span>
<div className="btn-group radio-group" data-toggle="buttons">
<label
onClick={ () => this.onUpdateQuantity(item.product, item.quantity - 1) }
className="btn btn-sm btn-primary
btn-rounded waves-effect waves-light">
<a>—</a>
</label>
<label
onClick={ () => this.onUpdateQuantity(item.product, item.quantity - 1) }
className="btn btn-sm btn-primary
btn-rounded waves-effect waves-light">
<a>+</a>
</label>
</div>
</td>
<td>{this.showSubTotal(item.product.price, item.quantity)} $</td>
<td>
<button
type="button"
className="btn btn-sm btn-primary waves-effect waves-light"
data-toggle="tooltip" data-placement="top"
title="" data-original-title="Remove item"
onClick = { () => this.onDelete(item.product)}
>
X
</button>
</td>
</tr>
);
}
onUpdateQuantity = (product, quantity) => {
if(quantity > 0) {
var { onUpdateProductInCart, onChangeMessage } = this.props;
onUpdateProductInCart(product, quantity);
onChangeMessage(Message.MSG_UPDATE_CART_SUCESS);
}
}
onDelete = (product) => {
var { onDeleteProductInCart, onChangeMessage } = this.props;
onDeleteProductInCart(product);
onChangeMessage(Message.MSG_DELETE_PRODUCT_IN_CART_SUCCESS);
}
showSubTotal = (price, quantity) => {
return price * quantity;
}
}
export default CartItem;
|
webapp/app/components/Notifications/Form/Groups/index.js | EIP-SAM/SAM-Solution-Server | //
// Component groups form notifications
//
import React from 'react';
import { Col } from 'react-bootstrap';
import AllGroups from 'containers/Notifications/Form/Groups/AllGroups';
import SelectedGroups from 'containers/Notifications/Form/Groups/SelectedGroups';
import Buttons from 'containers/Notifications/Form/Groups/Buttons';
import styles from 'components/Notifications/styles.css';
/* eslint-disable react/prefer-stateless-function */
export default class NotificationsFormGroups extends React.Component {
componentWillMount() {
this.props.getGroupsRequest();
}
render() {
return (
<div className={styles.groups}>
<Col lg={5} md={5} sm={5} xs={5}>
<AllGroups />
</Col>
<Col lg={2} md={2} sm={2} xs={2}>
<Buttons />
</Col>
<Col lg={5} md={5} sm={5} xs={5}>
<SelectedGroups />
</Col>
</div>
);
}
}
NotificationsFormGroups.propTypes = {
getGroupsRequest: React.PropTypes.func,
};
|
app/modules/layout/components/Grid/index.js | anton-drobot/frontend-starter | import React from 'react';
import { observer } from 'mobx-react';
import { bem, mix } from 'app/libs/bem';
const b = bem('Grid');
function Grid(props) {
const {
className,
children
} = props;
return (
<div className={mix(b(), className)}>{children}</div>
);
}
export default observer(Grid);
|
node_modules/semantic-ui-react/src/views/Comment/CommentContent.js | SuperUncleCat/ServerMonitoring | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A comment can contain content.
*/
function CommentContent(props) {
const { className, children } = props
const classes = cx(className, 'content')
const rest = getUnhandledProps(CommentContent, props)
const ElementType = getElementType(CommentContent, props)
return <ElementType {...rest} className={classes}>{children}</ElementType>
}
CommentContent._meta = {
name: 'CommentContent',
parent: 'Comment',
type: META.TYPES.VIEW,
}
CommentContent.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
}
export default CommentContent
|
node_modules/rebass/src/Embed.js | HasanSa/hackathon |
import React from 'react'
import Base from './Base'
/**
* Responsive media embed wrapper
*/
const Embed = ({ ratio, children, ...props }, { rebass }) => {
const childProps = {
style: {
position: 'absolute',
width: '100%',
height: '100%',
top: 0,
bottom: 0,
left: 0,
border: 0
}
}
const styledChildren = React.Children.map(children, (child) => {
return React.cloneElement(child, childProps)
})
return (
<Base
{...props}
className='Embed'
children={styledChildren}
baseStyle={{
position: 'relative',
height: 0,
padding: 0,
paddingBottom: `${ratio * 100}%`,
overflow: 'hidden'
}} />
)
}
Embed.propTypes = {
/**
* Aspect ratio for the embed.
* Divide height over width to calculate.
* E.g. ratio={9/16}
*/
ratio: React.PropTypes.number
}
Embed.defaultProps = {
ratio: 9 / 16
}
Embed.contextTypes = {
rebass: React.PropTypes.object
}
export default Embed
|
src/javascripts/views/invoices/index.react.js | him0/nem-invoice | import React, { Component } from 'react';
export default class InvoicesIndex extends Component {
constructor(props) {
super(props);
}
static get propTypes() {
return {
}
}
static get defaultProps() {
const initialProps = JSON.parse(document.getElementById('initial-data').getAttribute('data-json'));
return Object.assign({}, initialProps);
}
render() {
return (
<div className="InvoicesIndex">
<span>InvoicesIndex</span>
</div>
);
}
} |
src/RadioGroup.js | lenxeon/react-ui | import React from 'react'
import classnames from 'classnames'
import PropTypes from './utils/proptypes'
import Fetch from './higherOrders/Fetch'
import FormItem from './higherOrders/FormItem'
import Radio from './Radio'
import { compose } from './utils/compose'
import TextValue from './higherOrders/TextValue'
import Styles from './styles/_radio-checkbox.scss'
const RadioGroup = (props) => {
let { className, data, inline, block, onChange, style, readOnly } = props
// old inline prop
if (block === undefined && inline !== undefined) {
block = !inline
}
const items = data.map(function (item, i) {
return (
<Radio key={item.$key}
block={block}
index={i}
onClick={onChange}
readOnly={readOnly}
checked={item.$checked}
text={item.$text}
checkValue={item.$value}
/>
)
}, this)
return (
<div style={style} className={classnames(className, Styles.group)}>{items}</div>
)
}
RadioGroup.propTypes = {
block: PropTypes.bool,
className: PropTypes.string,
data: PropTypes.array,
inline: PropTypes.bool,
onChange: PropTypes.func,
readOnly: PropTypes.bool,
style: PropTypes.object
}
export default compose(
FormItem.register('radio-group', {}),
Fetch(false),
TextValue(true)
)(RadioGroup)
|
src/fluxtable/lib/Decorators.js | MirekSz/avem | /**
* Created by Mirek on 2015-10-09.
*/
import React, { Component } from 'react';
var Perf = React.addons.Perf;
export function observe(target) {
target.prototype.addListenersToStore = function () {
var listener = ()=> {
this.setState(this.getData());
};
this.listener = listener;
this.props.store.addListener(listener);
if (!this.props.store.initialized) {
this.props.store.init();
}
};
target.prototype.removeListenersToStore = function () {
this.props.store.removeListener(this.listener);
}
}
export function observable(target) {
target.listeners = [];
target.prototype.addListener = function (listener) {
target.listeners.push(listener);
};
target.prototype.removeListener = function (listener) {
var index = target.listeners.indexOf(listener);
target.listeners.splice(index, 1);
};
target.prototype.emmit = function (event) {
for (var i = 0; i < target.listeners.length; i++) {
var listener = target.listeners[i];
listener(event);
}
};
}
|
node_modules/react-bootstrap/es/Tab.js | chenjic215/search-doctor | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import PropTypes from 'prop-types';
import TabContainer from './TabContainer';
import TabContent from './TabContent';
import TabPane from './TabPane';
var propTypes = _extends({}, TabPane.propTypes, {
disabled: PropTypes.bool,
title: PropTypes.node,
/**
* tabClassName is used as className for the associated NavItem
*/
tabClassName: PropTypes.string
});
var Tab = function (_React$Component) {
_inherits(Tab, _React$Component);
function Tab() {
_classCallCheck(this, Tab);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Tab.prototype.render = function render() {
var props = _extends({}, this.props);
// These props are for the parent `<Tabs>` rather than the `<TabPane>`.
delete props.title;
delete props.disabled;
delete props.tabClassName;
return React.createElement(TabPane, props);
};
return Tab;
}(React.Component);
Tab.propTypes = propTypes;
Tab.Container = TabContainer;
Tab.Content = TabContent;
Tab.Pane = TabPane;
export default Tab; |
src/index.js | dillonliang224/react-gallery | import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
src/Thumbnail.js | jakubsikora/react-bootstrap | import React from 'react';
import classSet from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import SafeAnchor from './SafeAnchor';
const Thumbnail = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
alt: React.PropTypes.string,
href: React.PropTypes.string,
src: React.PropTypes.string
},
getDefaultProps() {
return {
bsClass: 'thumbnail'
};
},
render() {
let classes = this.getBsClassSet();
if(this.props.href) {
return (
<SafeAnchor {...this.props} href={this.props.href} className={classSet(this.props.className, classes)}>
<img src={this.props.src} alt={this.props.alt} />
</SafeAnchor>
);
}
else {
if(this.props.children) {
return (
<div {...this.props} className={classSet(this.props.className, classes)}>
<img src={this.props.src} alt={this.props.alt} />
<div className="caption">
{this.props.children}
</div>
</div>
);
}
else {
return (
<div {...this.props} className={classSet(this.props.className, classes)}>
<img src={this.props.src} alt={this.props.alt} />
</div>
);
}
}
}
});
export default Thumbnail;
|
clients/privacy/components/FieldPrivacySettings.js | CalderaWP/Caldera-Forms | import React from 'react';
import PropTypes from 'prop-types';
import {FormGroup, FormControl, ControlLabel, HelpBlock, Panel, PanelGroup, Checkbox} from 'react-bootstrap';
import {IsEmailIdentifyingField} from "./IsEmailIdentifyingField";
import {IsPiiField} from "./IsPiiField";
/**
* Privacy Settings for one field of a form
*
* @since 1.7.0
*
* @param props
* @returns {*}
* @constructor
*/
export const FieldPrivacySettings = (props) => {
return (
<section
style={{
backgroundColor: '#fff',
margin: '1em',
}}
className={'row'}
>
<h4
style={{
margin: 0,
padding: '.7em 1em',
borderBottom: '1px solid #eee'
}}
>
{props.field.name}
</h4>
<div
className={'col-xs-6'}
style={{
padding: '12px'
}}
>
<IsPiiField
field={props.field}
privacySettings={props.privacySettings}
onCheck={props.onCheckIsPii}
/>
</div>
<div
className={'col-xs-6'}
style={{
padding: '12px'
}}
>
<IsEmailIdentifyingField
className={'col-xs-6'}
field={props.field}
privacySettings={props.privacySettings}
onCheck={props.onCheckIsEmail}
/>
</div>
</section>
);
};
FieldPrivacySettings.propTypes = {
field: PropTypes.object.isRequired,
formId: PropTypes.string.isRequired,
privacySettings: PropTypes.object.isRequired,
onCheckIsEmail: PropTypes.func.isRequired,
onCheckIsPii: PropTypes.func.isRequired
}; |
examples/huge-apps/routes/Grades/components/Grades.js | Dodelkin/react-router | import React from 'react'
class Grades extends React.Component {
render() {
return (
<div>
<h2>Grades</h2>
</div>
)
}
}
export default Grades
|
src/components/LocationEdit.js | brianyamasaki/rideshare | import _ from 'lodash';
import React, { Component } from 'react';
import { ScrollView, Alert } from 'react-native';
import { connect } from 'react-redux';
import LocationForm from './LocationForm.js';
import { locationUpdate, locationUpdateAll, locationSave, locationDelete } from '../actions';
import { Card, CardSection, Button } from './common';
class LocationEdit extends Component {
componentWillMount() {
const { id, name, description, address1, city, state } = this.props.location;
this.props.locationUpdateAll(id, name, description, address1, city, state);
}
onSaveChanges() {
const {
name,
description,
address1,
city,
state
} = this.props;
this.props.locationSave({
name,
description,
address1,
city,
state,
id: this.props.id
});
}
onDelete() {
Alert.alert(
'Really Delete Location?',
'Do you really want to delete this location permanently?',
[
{
text: 'Delete',
onPress: () => this.props.locationDelete({ id: this.props.id })
},
{
text: 'Cancel',
onPress: () => console.log('delete cancelled'),
style: 'cancel'
}
]
);
}
render() {
return (
<ScrollView>
<Card>
<LocationForm {...this.props} />
<CardSection>
<Button onPress={this.onSaveChanges.bind(this)}>
Save Changes
</Button>
</CardSection>
<CardSection>
<Button onPress={this.onDelete.bind(this)}>
Delete Location
</Button>
</CardSection>
</Card>
</ScrollView>
);
}
}
const mapStateToProps = state => {
const { id, name, description, address1, city } = state.location;
return {
id,
name,
description,
address1,
city,
state: state.location.state
};
};
export default connect(mapStateToProps,
{ locationUpdate,
locationUpdateAll,
locationSave,
locationDelete }
)(LocationEdit);
|
docs/client.js | Lucifier129/react-bootstrap | import CodeMirror from 'codemirror';
import 'codemirror/addon/runmode/runmode';
import 'codemirror/mode/htmlmixed/htmlmixed';
import './assets/javascript';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import React from 'react';
import ReactDOM from 'react-dom';
import {Router} from 'react-router';
import Root from './src/Root';
import routes from './src/Routes';
import 'bootstrap/less/bootstrap.less';
import './assets/docs.css';
import './assets/style.css';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/solarized.css';
import './assets/CodeMirror.css';
import './assets/carousel.png';
import './assets/logo.png';
import './assets/favicon.ico';
import './assets/thumbnail.png';
import './assets/thumbnaildiv.png';
import './assets/TheresaKnott_castle.svg';
global.CodeMirror = CodeMirror;
Root.assetBaseUrl = window.ASSET_BASE_URL;
Root.propData = window.PROP_DATA;
const history = createBrowserHistory();
ReactDOM.render(
<Router history={history} children={routes} />,
document.body
);
|
src/components/Routes.js | daviddelusenet/reactjs-stat-tracker | import React from 'react';
import {
Route,
Link
} from 'react-router-dom';
// import components
import StatsTracker from './StatsTracker/StatsTracker';
import GameDetail from './GameDetail/GameDetail';
const GameDetailPage = (props) => {
return(
<GameDetail test="test" {...props} />
);
};
const Routes = () => {
return(
<div>
<ul>
<li><Link to="/">StatsTracker</Link></li>
<li><Link to="/game/sick">Game</Link></li>
</ul>
<Route exact path="/" component={StatsTracker}/>
<Route path="/game/:id" render={GameDetailPage} />
</div>
);
};
export default Routes;
|
src/App/App.js | Baekwoo-s/EnactVoteApp | import kind from '@enact/core/kind';
import MoonstoneDecorator from '@enact/moonstone/MoonstoneDecorator';
import Panels from '@enact/moonstone/Panels';
import React from 'react';
import MainPanel from '../views/MainPanel';
import css from './App.less';
const App = kind({
name: 'App',
styles: {
css,
className: 'app'
},
render: (props) => (
<div {...props}>
<Panels>
<MainPanel />
</Panels>
</div>
)
});
export default MoonstoneDecorator(App);
|
examples/pinterest/app.js | zipongo/react-router | import React from 'react'
import { render } from 'react-dom'
import { createHistory, useBasename } from 'history'
import { Router, Route, IndexRoute, Link } from 'react-router'
const history = useBasename(createHistory)({
basename: '/pinterest'
})
const PICTURES = [
{ id: 0, src: 'http://placekitten.com/601/601' },
{ id: 1, src: 'http://placekitten.com/610/610' },
{ id: 2, src: 'http://placekitten.com/620/620' }
]
const Modal = React.createClass({
styles: {
position: 'fixed',
top: '20%',
right: '20%',
bottom: '20%',
left: '20%',
padding: 20,
boxShadow: '0px 0px 150px 130px rgba(0, 0, 0, 0.5)',
overflow: 'auto',
background: '#fff'
},
render() {
return (
<div style={this.styles}>
<p><Link to={this.props.returnTo}>Back</Link></p>
{this.props.children}
</div>
)
}
})
const App = React.createClass({
componentWillReceiveProps(nextProps) {
// if we changed routes...
if ((
nextProps.location.key !== this.props.location.key &&
nextProps.location.state &&
nextProps.location.state.modal
)) {
// save the old children (just like animation)
this.previousChildren = this.props.children
}
},
render() {
let { location } = this.props
let isModal = (
location.state &&
location.state.modal &&
this.previousChildren
)
return (
<div>
<h1>Pinterest Style Routes</h1>
<div>
{isModal ?
this.previousChildren :
this.props.children
}
{isModal && (
<Modal isOpen={true} returnTo={location.state.returnTo}>
{this.props.children}
</Modal>
)}
</div>
</div>
)
}
})
const Index = React.createClass({
render() {
return (
<div>
<p>
The url `/pictures/:id` can be rendered anywhere in the app as a modal.
Simply put `modal: true` in the `state` prop of links.
</p>
<p>
Click on an item and see its rendered as a modal, then copy/paste the
url into a different browser window (with a different session, like
Chrome -> Firefox), and see that the image does not render inside the
overlay. One URL, two session dependent screens :D
</p>
<div>
{PICTURES.map(picture => (
<Link key={picture.id} to={`/pictures/${picture.id}`} state={{ modal: true, returnTo: this.props.location.pathname }}>
<img style={{ margin: 10 }} src={picture.src} height="100" />
</Link>
))}
</div>
<p><Link to="/some/123/deep/456/route">Go to some deep route</Link></p>
</div>
)
}
})
const Deep = React.createClass({
render() {
return (
<div>
<p>You can link from anywhere really deep too</p>
<p>Params stick around: {this.props.params.one} {this.props.params.two}</p>
<p>
<Link to={`/pictures/0`} state={{ modal: true, returnTo: this.props.location.pathname }}>
Link to picture with Modal
</Link><br/>
<Link to={`/pictures/0`}>
Without modal
</Link>
</p>
</div>
)
}
})
const Picture = React.createClass({
render() {
return (
<div>
<img src={PICTURES[this.props.params.id].src} style={{ height: '80%' }} />
</div>
)
}
})
render((
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="/pictures/:id" component={Picture}/>
<Route path="/some/:one/deep/:two/route" component={Deep}/>
</Route>
</Router>
), document.getElementById('example'))
|
docs/src/app/components/pages/components/TimePicker/ExampleComplex.js | IsenrichO/mui-with-arrows | import React from 'react';
import TimePicker from 'material-ui/TimePicker';
export default class TimePickerExampleComplex extends React.Component {
constructor(props) {
super(props);
this.state = {value24: null, value12: null};
}
handleChangeTimePicker24 = (event, date) => {
this.setState({value24: date});
};
handleChangeTimePicker12 = (event, date) => {
this.setState({value12: date});
};
render() {
return (
<div>
<TimePicker
format="ampm"
hintText="12hr Format"
value={this.state.value12}
onChange={this.handleChangeTimePicker12}
/>
<TimePicker
format="24hr"
hintText="24hr Format"
value={this.state.value24}
onChange={this.handleChangeTimePicker24}
/>
</div>
);
}
}
|
src/docs/components/date-time/DateTimeExamplesDoc.js | karatechops/grommet-docs | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import DateTime from 'grommet/components/DateTime';
import Form from 'grommet/components/Form';
import FormField from 'grommet/components/FormField';
import InteractiveExample from '../../../components/InteractiveExample';
const PROPS_SCHEMA = {
format: {
options: ['M/D/YYYY h:mm a', 'M/D/YYYY', 'D/M/YYYY', 'H:mm:ss', 'h a']
},
step: { options: [1, 5] }
};
export default class HeadlineExamplesDoc extends Component {
constructor () {
super();
this._onChange = this._onChange.bind(this);
this.state = { elementProps: {} };
}
_onChange (value) {
this.setState({ value: value });
}
render () {
const { elementProps, value } = this.state;
const element = (
<Form>
<FormField>
<DateTime id="id" name="name" {...elementProps}
onChange={this._onChange} value={value} />
</FormField>
</Form>
);
return (
<InteractiveExample contextLabel='DateTime' contextPath='/docs/date-time'
preamble={`import DateTime from 'grommet/components/DateTime';`}
propsSchema={PROPS_SCHEMA}
element={element}
onChange={elementProps => this.setState({ elementProps })} />
);
}
};
|
src/svg-icons/device/signal-wifi-1-bar-lock.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi1BarLock = (props) => (
<SvgIcon {...props}>
<path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z"/><path d="M15.5 14.5c0-2.8 2.2-5 5-5 .4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4C5.3 3 .8 6.7.4 7L12 21.5l3.5-4.3v-2.7z" opacity=".3"/><path d="M6.7 14.9l5.3 6.6 3.5-4.3v-2.6c0-.2 0-.5.1-.7-.9-.5-2.2-.9-3.6-.9-3 0-5.1 1.7-5.3 1.9z"/>
</SvgIcon>
);
DeviceSignalWifi1BarLock = pure(DeviceSignalWifi1BarLock);
DeviceSignalWifi1BarLock.displayName = 'DeviceSignalWifi1BarLock';
DeviceSignalWifi1BarLock.muiName = 'SvgIcon';
export default DeviceSignalWifi1BarLock;
|
definitions/npm/react-addons-test-utils_v15.x.x/flow_v0.15.x-/react-addons-test-utils_v15.x.x.js | echenley/flow-typed | import React from 'react';
declare module 'react-addons-test-utils' {
declare var Simulate: {
[eventName: string]: (element: Element, eventData?: Object) => void;
};
declare function renderIntoDocument(instance: React.Element<any>): React.Component;
declare function mockComponent(componentClass: React.ElementType, mockTagName?: string): Object;
declare function isElement(element: React.Element<any>): boolean;
declare function isElementOfType(element: React.Element<any>, componentClass: React.ElementType): boolean;
declare function isDOMComponent(instance: React.Component): boolean;
declare function isCompositeComponent(instance: React.Component): boolean;
declare function isCompositeComponentWithType(instance: React.Component, componentClass: React.ElementType): boolean;
declare function findAllInRenderedTree(tree: React.Component, test: (child: React.Component) => boolean): Array<React.Component>;
declare function scryRenderedDOMComponentsWithClass(tree: React.Component, className: string): Array<Element>;
declare function findRenderedDOMComponentWithClass(tree: React.Component, className: string): ?Element;
declare function scryRenderedDOMComponentsWithTag(tree: React.Component, tagName: string): Array<Element>;
declare function findRenderedDOMComponentWithTag(tree: React.Component, tagName: string): ?Element;
declare function scryRenderedComponentsWithType(tree: React.Component, componentClass: React.ElementType): Array<React.Component>;
declare function findRenderedComponentWithType(tree: React.Component, componentClass: React.ElementType): ?React.Component;
declare class ReactShallowRender {
render(element: React.Element<any>): void;
getRenderOutput(): React.Element<any>;
}
declare function createRenderer(): ReactShallowRender;
}
|
src/popup/components/PackEdit/index.js | victorvoid/fluany | /**
* @fileOverview A component to edit a specific package
* @name index.js<PackEdit>
* @license GNU General Public License v3.0
*/
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import * as translator from 'shared/constants/internacionalization'
import isNil from 'ramda/src/isNil'
import TitlePack from 'components/Pack/TitlePack'
import Cards from 'components/Card/Cards'
import Time from './Time'
import Either from 'components/Either'
import { isEditPackage } from 'actions/flags'
import { getIndexThingById } from 'reducers/stateManipulate'
import {
changePackageTitle,
changePackageDescription
} from 'actions/pack'
let PackEdit = ({
onChangePackageTitle,
onChangePackageDescription,
onIsEditPackage,
isEdit,
packflag,
packs,
loading
}) => {
let inRefToTitle = ''
const handlePackTitle = (e) => {
onChangePackageTitle(isEdit.packageid, e.target.value)
}
const handleComeBack = () => {
onIsEditPackage({ inewPackage: false, packageid: null })
}
const indexOfPack = getIndexThingById(packs, isEdit.packageid)
const titleProps = {
onChange: handlePackTitle,
title: (!isNil(isEdit.packageid) ?
packs[indexOfPack].title :
packflag.title),
refToComponent: (el) => {}
}
const Container = () => (
<section className='config-package'>
<nav>
<button className='btn btn-back' onClick={handleComeBack}>
<svg className='arrow-back'>
<use xlinkHref='#icon-arrow' />
</svg>
{ translator.BACK_LABEL }
</button>
</nav>
<div>
<div className={`load-packages-container ${loading ? 'loading' : ''}`} />
<TitlePack {...titleProps} />
<Time {...{ packs, packageid: isEdit.packageid }} />
<Cards {...{ packs, indexOfPack, packageid: isEdit.packageid }} />
</div>
</section>
)
return <Either when={!!isEdit} right={Container()} left={<div/>} />
}
const mapStateToProps = (
state
) => {
return {
isEdit: state.flags.isEditPackage,
packflag: state.flags.newPackage,
loading: state.flags.editPackageLoading,
packs: state.packs
}
}
function mapDispatchToProps(dispatch) {
return {
onChangePackageTitle: (...props) => dispatch(changePackageTitle(...props)),
onChangePackageDescription: (...props) => dispatch(changePackageDescription(...props)),
onIsEditPackage: (...props) => dispatch(isEditPackage(...props))
}
}
const {
func, bool, object, array
} = PropTypes
/**
* PropTypes
* @property {Function} onChangePackageTitle A action to change the package title
* @property {Function} onChangePackageDescription A action to change the package description
* @property {Function} onIsEditPackage A function to dispatch action to edit package
* @property {Object} isEdit A flag to know if is editing any package
* @property {Object} packflag A flag to know if is editing to new package or edit
* @property {Array} packs All availables packages
* @property {Boolean} loading A flag to know if container is loading
*/
PackEdit.propTypes = {
onChangePackageTitle: func.isRequired,
onChangePackageDescription: func.isRequired,
onIsEditPackage: func.isRequired,
isEdit: object.isRequired,
packflag: object.isRequired,
packs: array.isRequired,
loading: bool.isRequired
}
export default connect(mapStateToProps, mapDispatchToProps)(PackEdit)
|
app/javascript/mastodon/features/ui/components/column_header.js | 5thfloor/ichiji-social | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from 'mastodon/components/icon';
export default class ColumnHeader extends React.PureComponent {
static propTypes = {
icon: PropTypes.string,
type: PropTypes.string,
active: PropTypes.bool,
onClick: PropTypes.func,
columnHeaderId: PropTypes.string,
};
handleClick = () => {
this.props.onClick();
}
render () {
const { icon, type, active, columnHeaderId } = this.props;
let iconElement = '';
if (icon) {
iconElement = <Icon id={icon} fixedWidth className='column-header__icon' />;
}
return (
<h1 className={classNames('column-header', { active })} id={columnHeaderId || null}>
<button onClick={this.handleClick}>
{iconElement}
{type}
</button>
</h1>
);
}
}
|
src/components/icons/CheckmarkOutlineIcon.js | InsideSalesOfficial/insidesales-components | import React from 'react';
const CheckmarkOutlineIcon = props => (
<svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 100 100">
{props.title && <title>{props.title}</title>}
<g transform="translate(-594.000000, -328.000000)">
<path d="M635.6,395.3l3.8,3.5l1,0.9l0.8-1.1l3-4.2l21.8-30.8l0.7-1l-1-0.7l-7.4-5l-1-0.6l-0.7,0.9l-18,25.2l-10.4-9.4l-7,7.2l-0.9,0.9l0.9,0.8L635.6,395.3L635.6,395.3z M623.7,381.2l4.5-4.7l10.7,9.6l18.9-26.5l5.5,3.6l-23.3,33L623.7,381.2z" />
</g>
</svg>
);
export default CheckmarkOutlineIcon;
|
apps/marketplace/components/Teams/Flows/ChangeToTeamLeadMessage.js | AusDTO/dto-digitalmarketplace-frontend | import React from 'react'
import styles from './TeamStages.scss'
const ChangeToTeamLeadMessage = props => {
const { name } = props
return (
<div>
<p>
Are you sure you want to change <span className={styles.bold}>{name}</span> to a team lead?
</p>
<p>They will be able to add and remove members, specify permissions and create other team leads.</p>
</div>
)
}
export default ChangeToTeamLeadMessage
|
sample/components/spinner.js | LINKIWI/react-elemental | import React from 'react';
import { Spacing, Spinner, Text, colors } from 'react-elemental';
const SampleSpinner = () => (
<div>
<Spacing size="huge" bottom>
<Text size="gamma" color="primary" uppercase>
Spinners
</Text>
<Text>
Spinners indicate indeterminate progress when there is no clearly defined container in the
interface.
</Text>
</Spacing>
<Spacing size="huge" bottom>
<Spacing bottom>
<Text size="iota" color="gray70" uppercase bold>
Sizes
</Text>
</Spacing>
<Spacing bottom>
<Spacing size="tiny" bottom>
<Text size="kilo" color="gray30" uppercase bold>
Alpha
</Text>
</Spacing>
<Spinner size="alpha" />
</Spacing>
<Spacing bottom>
<Spacing size="tiny" bottom>
<Text size="kilo" color="gray30" uppercase bold>
Beta
</Text>
</Spacing>
<Spinner size="beta" />
</Spacing>
<Spacing bottom>
<Spacing size="tiny" bottom>
<Text size="kilo" color="gray30" uppercase bold>
Gamma
</Text>
</Spacing>
<Spinner size="gamma" />
</Spacing>
<Spacing bottom>
<Spacing size="tiny" bottom>
<Text size="kilo" color="gray30" uppercase bold>
Delta
</Text>
</Spacing>
<Spinner size="delta" />
</Spacing>
</Spacing>
<Spacing size="huge" bottom>
<Spacing bottom>
<Text size="iota" color="gray70" uppercase bold>
Customizable colors
</Text>
</Spacing>
<Spacing size="small" bottom>
<Spacing size="small" right inline>
<Spinner size="delta" accentColor={colors.green} />
</Spacing>
<Text color="gray50" size="kilo" uppercase bold inline>
Succeeding
</Text>
</Spacing>
<Spacing size="small" bottom>
<Spacing size="small" right inline>
<Spinner size="delta" accentColor={colors.red} />
</Spacing>
<Text color="gray50" size="kilo" uppercase bold inline>
Erroring
</Text>
</Spacing>
<Spacing size="small" bottom>
<Spacing size="small" right inline>
<Spinner size="delta" accentColor={colors.orange} />
</Spacing>
<Text color="gray50" size="kilo" uppercase bold inline>
Why not orange?
</Text>
</Spacing>
</Spacing>
<Spacing size="huge" bottom>
<Spacing bottom>
<Text size="iota" color="gray70" uppercase bold>
Customizable thickness and duration
</Text>
</Spacing>
<Spacing size="small" bottom>
<Spacing size="small" right inline>
<Spinner size="delta" thickness={1} />
</Spacing>
<Text color="gray50" size="kilo" uppercase bold inline>
Thin spinner
</Text>
</Spacing>
<Spacing size="small" bottom>
<Spacing size="small" right inline>
<Spinner size="alpha" thickness={5} />
</Spacing>
<Text color="gray50" size="kilo" uppercase bold inline>
Thick spinner
</Text>
</Spacing>
<Spacing size="small" bottom>
<Spacing size="small" right inline>
<Spinner size="delta" duration={1.2} />
</Spacing>
<Text color="gray50" size="kilo" uppercase bold inline>
Slow spinner
</Text>
</Spacing>
</Spacing>
</div>
);
export default SampleSpinner;
|
public/js/components/user_student.js | AC287/wdi_final_arrowlense2.0_FE | import React from 'react'
import {Link} from 'react-router'
import Firebase from 'firebase'
import EditImgUrl from './user_img_edit.js'
export default React.createClass({
contextTypes: {
user: React.PropTypes.string,
userinfo: React.PropTypes.object,
router: React.PropTypes.object.isRequired,
},
render: function(){
return(
<div className="container-fluid">
<div className="row">
<div className="col-md-3 imgdiv">
<img src={this.context.userinfo.imgurl} className="profileimage"/>
<br/>
<br/>
<EditImgUrl />
</div>
<div className="col-md-4">
<p>Name: <strong>{this.context.userinfo.firstname} {this.context.userinfo.lastname}</strong></p>
<p>Email: {this.context.userinfo.email}</p>
<br/>
<br/>
<button type="button" className="btn btn-default btn-lg btn-block"> Create A Blog </button>
<button type="button" className="btn btn-default btn-lg btn-block"> Enroll In Class </button>
</div>
<div className="col-md-5">
<div className="row alertbox shadowbox">
<h4><u>Announcement</u></h4>
</div>
<div className="row alertbox shadowbox">
<h4><u>Assignment & Due-Dates</u></h4>
</div>
</div>
</div>
<hr/>
<div>
<div className="container title">
<h3>My Classes</h3>
</div>
<div className="row">
<div className="col-md-6">
<h4>Current Classes</h4>
<div className="renderclasses">
</div>
</div>
<div className="col-md-6">
<h4>Past Classes</h4>
<div className="renderclasses">
</div>
</div>
</div>
</div>
</div>
)
}
})
|
packages/material-ui-icons/src/IndeterminateCheckBox.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let IndeterminateCheckBox = props =>
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10H7v-2h10v2z" />
</SvgIcon>;
IndeterminateCheckBox = pure(IndeterminateCheckBox);
IndeterminateCheckBox.muiName = 'SvgIcon';
export default IndeterminateCheckBox;
|
codes/chapter05/react-router-v4/advanced/demo02/app/components/App.js | atlantis1024/react-step-by-step | import React from 'react';
import { Link } from 'react-router-dom';
class App extends React.PureComponent {
render() {
return (
<div>
<h1>React Router Tutorial</h1>
<ul role="nav">
<li><Link to="/about">关于</Link></li>
<li><Link to="/topics">主题</Link></li>
<li><Link to="/redirect">重定向到关于页面</Link></li>
<li><Link to="/nomatch">无法匹配的页面</Link></li>
</ul>
</div>
)
}
}
export default App;
|
notebook/book/ecmascript/JavaScript-Application-Design/practice/React/react-redux-webpack/lesson1/client/client.js | JMwill/wiki | import React from 'react';
import {render} from 'react-dom';
import App from '../components/App/app';
import configureStore from '../redux/store';
import { Provider } from 'react-redux';
let initialState = {
todos: [
{
id: 0,
completed: false,
text: 'Initial todo Item'
}
],
user: {
username: 'JMwill',
id: 0
}
};
let store = configureStore(initialState);
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
|
components/ParkingList.js | sophiatao/mhacksx | import React from 'react';
import {FlatList, Text, StyleSheet, View, TouchableOpacity} from 'react-native';
import { Col, Grid, Row } from "react-native-easy-grid";
const extractKey = ({id}) => id
export default class ParkingList extends React.Component {
resetMap(lat, long) {
this.props.resetMap(lat, long)
}
renderItem = ({item}) => {
var lat = item.latitude;
var long = item.longitude;
return (
<TouchableOpacity onPress={() => this.resetMap(lat, long)}><Row style={styles.row}>
<Col><Text style={styles.text}>{item.name}</Text></Col>
<Col><Text style={styles.text}>{item.distance+'km'}</Text></Col>
<Col><Text style={styles.text}>{item.paid? "paid" : "free"}</Text></Col>
<Col><Text style={styles.text} style={item.spots > 18? {color: '#22485e'} : item.spots > 15? {color: '#416275'} : item.spots > 12? {color: '#617C8C'} : item.spots > 9? {color: '#8096A3'} : item.spots > 6? {color: '#A0B0BA'} : item.spots > 3? {color: '#A0B0BA'} : {color: '#dfe4e8'} }>{item.spots}</Text></Col>
</Row>
</TouchableOpacity>
)
}
render() {
return (
<View style={styles.container}>
<Text style={styles.header}>it's a walk in the park.</Text>
<FlatList
data={this.props.parkingLots}
renderItem={this.renderItem}
keyExtractor={extractKey}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 0,
flex: 1,
backgroundColor: 'skyblue',
},
row: {
padding: 15,
backgroundColor: 'transparent',
},
text: {
color: '#fff',
fontFamily: 'Roboto',
fontWeight: '100',
},
header: {
padding: 15,
fontSize: 24,
marginLeft: 0,
backgroundColor: 'skyblue',
marginTop: 0,
color: '#22485e',
fontFamily: 'Roboto',
fontWeight: '100',
},
})
|
app/containers/UGClientListing/index.js | perry-ugroop/ugroop-react-dup2 | import React from 'react';
import { push } from 'react-router-redux';
// import backgroundPhoto from './assets/background-features.png';
// ************************************************************************
// Collection of styled-components for Client Listing in the homepage
// ************************************************************************
import clientList from './list';
import UGClientListingTitleStyle from './UGClientListingTitleStyle';
import UGClientListingBox from './UGClientListingBox';
// ************************************************************************
// Wrapper Components
// ************************************************************************
const cList = clientList.map((items, key) =>
<a href={items.url} alt={items.clientName} key={key}>
<img src={items.logo} alt={items.description} width="131" height="132" />
</a>
);
export class UGClientListing extends React.Component {
openUGClientListing = () => {
this.props.dispatch(push('/'));
};
render() {
return (
<div className={'clients'}>
<UGClientListingBox>
<UGClientListingTitleStyle><h1> Our Clients </h1></UGClientListingTitleStyle>
{cList}
</UGClientListingBox>
</div>
);
}
}
// ************************************************************************
// Components Props type definition
// ************************************************************************
UGClientListing.propTypes = {
dispatch: React.PropTypes.func,
};
export default UGClientListing;
|
src/geo-objects/Placemark.js | gribnoysup/react-yandex-maps | import React from 'react';
import PropTypes from 'prop-types';
import { withParentContext } from '../Context';
import withYMaps from '../withYMaps';
import { BaseGeoObject } from './BaseGeoObject';
export function Placemark(props) {
return <BaseGeoObject {...props} name="Placemark" />;
}
if (process.env.NODE_ENV !== 'production') {
const PlacemarkGeometryPropTypes = PropTypes.arrayOf(PropTypes.number);
Placemark.propTypes = {
/**
* Placemark [geometry](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/Placemark-docpage/#param-geometry)
*/
geometry: PlacemarkGeometryPropTypes,
/**
* Uncontrolled Placemark [geometry](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/Placemark-docpage/#param-geometry)
*/
defaultGeometry: PlacemarkGeometryPropTypes,
/**
* Placemark [properties](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/Placemark-docpage/#param-properties)
*/
properties: PropTypes.shape({}),
/**
* Uncontrolled Placemark [properties](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/Placemark-docpage/#param-properties)
*/
defaultProperties: PropTypes.shape({}),
/**
* Placemark [options](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/Placemark-docpage/#param-options)
*/
options: PropTypes.shape({}),
/**
* Uncontrolled Placemark [options](https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/Placemark-docpage/#param-options)
*/
defaultOptions: PropTypes.shape({}),
};
}
export default withParentContext(withYMaps(Placemark, true, ['Placemark']));
|
src/components/app.js | MohammadHasham/Redux-YouOwn | import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
|
cm19/ReactJS/your-first-react-app-exercises-master/exercise-18/shared/Page.js | Brandon-J-Campbell/codemash | import React from 'react';
import classNames from 'classnames';
import ThemeContext from '../theme/context';
import styles from './Page.css';
export default function Page({ children }) {
return (
<ThemeContext.Consumer>
{({ theme }) => (
<div className={classNames(styles.page, styles[theme])}>
<div className={styles.content}>{children}</div>
</div>
)}
</ThemeContext.Consumer>
);
}
|
test/helpers/shallowRenderHelper.js | Aikk/gallery-by-react | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
src/Transition.js | coderstudy/react-bootstrap | import React from 'react';
import TransitionEvents from './utils/TransitionEvents';
import classnames from 'classnames';
export const UNMOUNTED = 0;
export const EXITED = 1;
export const ENTERING = 2;
export const ENTERED = 3;
export const EXITING = 4;
class Transition extends React.Component {
constructor(props, context) {
super(props, context);
let initialStatus;
if (props.in) {
// Start enter transition in componentDidMount.
initialStatus = props.transitionAppear ? EXITED : ENTERED;
} else {
initialStatus = props.unmountOnExit ? UNMOUNTED : EXITED;
}
this.state = {status: initialStatus};
this.nextCallback = null;
}
componentDidMount() {
if (this.props.transitionAppear && this.props.in) {
this.performEnter(this.props);
}
}
componentWillReceiveProps(nextProps) {
const status = this.state.status;
if (nextProps.in) {
if (status === EXITING) {
this.performEnter(nextProps);
} else if (this.props.unmountOnExit) {
if (status === UNMOUNTED) {
// Start enter transition in componentDidUpdate.
this.setState({status: EXITED});
}
} else if (status === EXITED) {
this.performEnter(nextProps);
}
// Otherwise we're already entering or entered.
} else {
if (status === ENTERING || status === ENTERED) {
this.performExit(nextProps);
}
// Otherwise we're already exited or exiting.
}
}
componentDidUpdate() {
if (this.props.unmountOnExit && this.state.status === EXITED) {
// EXITED is always a transitional state to either ENTERING or UNMOUNTED
// when using unmountOnExit.
if (this.props.in) {
this.performEnter(this.props);
} else {
this.setState({status: UNMOUNTED});
}
}
}
componentWillUnmount() {
this.cancelNextCallback();
}
performEnter(props) {
this.cancelNextCallback();
const node = React.findDOMNode(this);
// Not this.props, because we might be about to receive new props.
props.onEnter(node);
this.safeSetState({status: ENTERING}, () => {
this.props.onEntering(node);
this.onTransitionEnd(node, () => {
this.safeSetState({status: ENTERED}, () => {
this.props.onEntered(node);
});
});
});
}
performExit(props) {
this.cancelNextCallback();
const node = React.findDOMNode(this);
// Not this.props, because we might be about to receive new props.
props.onExit(node);
this.safeSetState({status: EXITING}, () => {
this.props.onExiting(node);
this.onTransitionEnd(node, () => {
this.safeSetState({status: EXITED}, () => {
this.props.onExited(node);
});
});
});
}
cancelNextCallback() {
if (this.nextCallback !== null) {
this.nextCallback.cancel();
this.nextCallback = null;
}
}
safeSetState(nextState, callback) {
// This shouldn't be necessary, but there are weird race conditions with
// setState callbacks and unmounting in testing, so always make sure that
// we can cancel any pending setState callbacks after we unmount.
this.setState(nextState, this.setNextCallback(callback));
}
setNextCallback(callback) {
let active = true;
this.nextCallback = (event) => {
if (active) {
active = false;
this.nextCallback = null;
callback(event);
}
};
this.nextCallback.cancel = () => {
active = false;
};
return this.nextCallback;
}
onTransitionEnd(node, handler) {
this.setNextCallback(handler);
if (node) {
TransitionEvents.addEndEventListener(node, this.nextCallback);
setTimeout(this.nextCallback, this.props.duration);
} else {
setTimeout(this.nextCallback, 0);
}
}
render() {
const status = this.state.status;
if (status === UNMOUNTED) {
return null;
}
const {children, className, ...childProps} = this.props;
Object.keys(Transition.propTypes).forEach(key => delete childProps[key]);
let transitionClassName;
if (status === EXITED) {
transitionClassName = this.props.exitedClassName;
} else if (status === ENTERING) {
transitionClassName = this.props.enteringClassName;
} else if (status === ENTERED) {
transitionClassName = this.props.enteredClassName;
} else if (status === EXITING) {
transitionClassName = this.props.exitingClassName;
}
const child = React.Children.only(children);
return React.cloneElement(
child,
{
...childProps,
className: classnames(
child.props.className,
className,
transitionClassName
)
}
);
}
}
Transition.propTypes = {
/**
* Show the component; triggers the enter or exit animation
*/
in: React.PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is not shown
*/
unmountOnExit: React.PropTypes.bool,
/**
* Run the enter animation when the component mounts, if it is initially
* shown
*/
transitionAppear: React.PropTypes.bool,
/**
* Duration of the animation in milliseconds, to ensure that finishing
* callbacks are fired even if the original browser transition end events are
* canceled
*/
duration: React.PropTypes.number,
/**
* CSS class or classes applied when the component is exited
*/
exitedClassName: React.PropTypes.string,
/**
* CSS class or classes applied while the component is exiting
*/
exitingClassName: React.PropTypes.string,
/**
* CSS class or classes applied when the component is entered
*/
enteredClassName: React.PropTypes.string,
/**
* CSS class or classes applied while the component is entering
*/
enteringClassName: React.PropTypes.string,
/**
* Callback fired before the "entering" classes are applied
*/
onEnter: React.PropTypes.func,
/**
* Callback fired after the "entering" classes are applied
*/
onEntering: React.PropTypes.func,
/**
* Callback fired after the "enter" classes are applied
*/
onEntered: React.PropTypes.func,
/**
* Callback fired before the "exiting" classes are applied
*/
onExit: React.PropTypes.func,
/**
* Callback fired after the "exiting" classes are applied
*/
onExiting: React.PropTypes.func,
/**
* Callback fired after the "exited" classes are applied
*/
onExited: React.PropTypes.func
};
// Name the function so it is clearer in the documentation
function noop() {}
Transition.defaultProps = {
in: false,
duration: 300,
unmountOnExit: false,
transitionAppear: false,
onEnter: noop,
onEntering: noop,
onEntered: noop,
onExit: noop,
onExiting: noop,
onExited: noop
};
export default Transition;
|
ui/src/components/group/AddGroup.js | yahoo/athenz | /*
* Copyright 2020 Verizon Media
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import Button from '../denali/Button';
import Input from '../denali/Input';
import InputLabel from '../denali/InputLabel';
import Member from '../member/Member';
import styled from '@emotion/styled';
import { colors } from '../denali/styles';
import AddModal from '../modal/AddModal';
import DateUtils from '../utils/DateUtils';
import RequestUtils from '../utils/RequestUtils';
import {
GROUP_MEMBER_NAME_REGEX,
GROUP_MEMBER_PLACEHOLDER,
GROUP_NAME_REGEX,
} from '../constants/constants';
import MemberUtils from '../utils/MemberUtils';
const SectionDiv = styled.div`
align-items: flex-start;
display: flex;
flex-flow: row nowrap;
padding: 10px 10px;
`;
const StyledInputLabel = styled(InputLabel)`
float: left;
font-size: 14px;
font-weight: 700;
width: 17%;
`;
const StyledInputLabelPadding = styled(InputLabel)`
float: left;
font-size: 14px;
font-weight: 700;
width: 17%;
padding-top: 5px;
`;
const StyledInput = styled(Input)`
width: 500px;
`;
const StyledInputUser = styled(Input)`
margin-top: 5px;
`;
const ContentDiv = styled.div`
flex: 1 1;
margin-right: 10px;
`;
const AddMemberDiv = styled.div`
display: flex;
`;
const StyledIncludedMembersDiv = styled.div`
width: 65%;
`;
const SectionsDiv = styled.div`
width: 780px;
text-align: left;
background-color: ${colors.white};
`;
const ButtonDiv = styled.div`
margin-left: 10px;
`;
const StyledButton = styled(Button)`
width: 125px;
`;
export default class AddGroup extends React.Component {
constructor(props) {
super(props);
this.api = props.api;
this.addMember = this.addMember.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.dateUtils = new DateUtils();
this.state = {
saving: 'nope',
name: '',
newMemberName: '',
members: [],
justification: '',
};
}
inputChanged(key, evt) {
let value = '';
if (evt.target) {
value = evt.target.value;
} else {
value = evt ? evt : '';
}
this.setState({ [key]: value });
}
getJustification() {
if (this.props.justificationRequired) {
return (
<SectionDiv>
<StyledInputLabel>Justification</StyledInputLabel>
<ContentDiv>
<StyledInput
id='justification'
name='justification'
value={this.state.justification}
onChange={this.inputChanged.bind(
this,
'justification'
)}
autoComplete={'off'}
placeholder='Enter justification here'
/>
</ContentDiv>
</SectionDiv>
);
}
}
addMember() {
let name = this.state.newMemberName;
let members = this.state.members;
if (!name) {
return;
}
let names = MemberUtils.getUserNames(name, GROUP_MEMBER_NAME_REGEX);
names.validUsers.forEach((name) => {
members.push({
memberName: name,
});
});
if (names.invalidUsers.length !== 0) {
this.setState({
members,
newMemberName: names.invalidUsers.toString(),
errorMessage:
"Member name doesn't match regex: " +
GROUP_MEMBER_NAME_REGEX,
});
} else {
this.setState({
members,
newMemberName: '',
errorMessage: '',
});
}
}
deleteMember(idx) {
let members = this.state.members;
// this if is done to avoid [null] condition
if (members.length === 1) {
members = null;
} else {
delete members[idx];
}
this.setState({ members });
}
onSubmit() {
let groupName = this.state.name;
if (!groupName || groupName === '') {
this.setState({
errorMessage: 'Group name is required.',
});
return;
}
if (!MemberUtils.matchRegexName(groupName, GROUP_NAME_REGEX)) {
this.setState({
errorMessage:
"Group name doesn't match regex: " + GROUP_NAME_REGEX,
});
return;
}
let group = { name: groupName };
group.groupMembers =
this.state.members.filter((member) => {
return member != null || member != undefined;
}) || [];
if (this.state.newMemberName && this.state.newMemberName !== '') {
let names = MemberUtils.getUserNames(
this.state.newMemberName,
GROUP_MEMBER_NAME_REGEX
);
names.validUsers.forEach((name) => {
group.groupMembers.push({
memberName: name,
});
});
if (names.invalidUsers.length !== 0) {
this.setState({
newMemberName: names.invalidUsers.toString(),
errorMessage:
"Member name doesn't match regex: " +
GROUP_MEMBER_NAME_REGEX,
});
return;
}
}
if (
this.props.justificationRequired &&
(this.state.justification === undefined ||
this.state.justification.trim() === '')
) {
this.setState({
errorMessage: 'Justification is required to add a group.',
});
return;
}
this.api
.listGroups(this.props.domain)
.then((groups) => {
if (
groups.includes(this.props.domain + ':group.' + groupName)
) {
this.setState({
errorMessage: 'Group already exists.',
});
return;
}
let auditRef = this.state.justification
? this.state.justification
: ''; // no UX for this
this.api
.addGroup(
this.props.domain,
groupName,
group,
auditRef,
this.props._csrf
)
.then(() => {
this.props.onSubmit(
`Successfully created group ${groupName}`,
groupName
);
})
.catch((err) => {
let message = '';
if (err.statusCode === 0) {
message = 'Okta expired. Please refresh the page';
} else {
message = `Status: ${err.statusCode}. Message: ${err.body.message}`;
}
this.setState({
errorMessage: message,
});
});
})
.catch((err) => {
this.setState({
errorMessage: RequestUtils.xhrErrorCheckHelper(err),
});
});
}
render() {
let memberNameChanged = this.inputChanged.bind(this, 'newMemberName');
let nameChanged = this.inputChanged.bind(this, 'name');
let members = this.state.members
? this.state.members.map((item, idx) => {
// dummy place holder so that it can be be used in the form
item.approved = true;
let remove = this.deleteMember.bind(this, idx);
return (
<Member
key={idx}
item={item}
onClickRemove={remove}
noanim
/>
);
})
: '';
let sections = (
<SectionsDiv>
<SectionDiv>
<StyledInputLabel>Group Name</StyledInputLabel>
<ContentDiv>
<StyledInput
placeholder='Enter New Group Name'
value={this.state.name}
onChange={nameChanged}
noanim
fluid
/>
</ContentDiv>
</SectionDiv>
{
<SectionDiv>
<StyledInputLabelPadding>
Add Member(s)
</StyledInputLabelPadding>
<ContentDiv>
<AddMemberDiv>
<StyledInputUser
placeholder={GROUP_MEMBER_PLACEHOLDER}
value={this.state.newMemberName}
onChange={memberNameChanged}
noanim
fluid
/>
<ButtonDiv>
<StyledButton
secondary
size={'small'}
onClick={this.addMember}
>
Add
</StyledButton>
</ButtonDiv>
</AddMemberDiv>
</ContentDiv>
</SectionDiv>
}
<SectionDiv>
<StyledInputLabel />
<StyledIncludedMembersDiv>
{members}
</StyledIncludedMembersDiv>
</SectionDiv>
{this.getJustification()}
</SectionsDiv>
);
return (
<div data-testid='add-group'>
<AddModal
isOpen={this.props.showAddGroup}
cancel={this.props.onCancel}
submit={this.onSubmit}
title={`Add Group to ${this.props.domain}`}
errorMessage={this.state.errorMessage}
sections={sections}
/>
</div>
);
}
}
|
src/Accordion.js | kwnccc/react-bootstrap | import React from 'react';
import PanelGroup from './PanelGroup';
const Accordion = React.createClass({
render() {
return (
<PanelGroup {...this.props} accordion>
{this.props.children}
</PanelGroup>
);
}
});
export default Accordion;
|
docs/src/CodeExample.js | HPate-Riptide/react-bootstrap | import React from 'react';
import ReactDOM from 'react-dom';
export default class CodeExample extends React.Component {
render() {
return (
<pre className="cm-s-solarized cm-s-light">
<code>
{this.props.codeText}
</code>
</pre>
);
}
componentDidMount() {
if (CodeMirror === undefined) {
return;
}
CodeMirror.runMode(
this.props.codeText,
this.props.mode,
ReactDOM.findDOMNode(this).children[0]
);
}
}
|
client/extensions/woocommerce/app/promotions/promotion-create.js | Automattic/woocommerce-connect-client | /** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { difference } from 'lodash';
import { localize } from 'i18n-calypso';
import page from 'page';
/**
* Internal dependencies
*/
import Main from 'components/main';
import { editPromotion, clearPromotionEdits } from 'woocommerce/state/ui/promotions/actions';
import { getLink } from 'woocommerce/lib/nav-utils';
import { getSelectedSiteWithFallback } from 'woocommerce/state/sites/selectors';
import { fetchProductCategories } from 'woocommerce/state/sites/product-categories/actions';
import { fetchPromotions, createPromotion } from 'woocommerce/state/sites/promotions/actions';
import { fetchSettingsGeneral } from 'woocommerce/state/sites/settings/general/actions';
import { getPaymentCurrencySettings } from 'woocommerce/state/sites/settings/general/selectors';
import { areProductsLoading, getAllProducts } from 'woocommerce/state/sites/products/selectors';
import {
getCurrentlyEditingPromotionId,
getPromotionEdits,
getPromotionWithLocalEdits,
} from 'woocommerce/state/selectors/promotions';
import { getSaveErrorMessage } from './save-error-message';
import PromotionHeader from './promotion-header';
import PromotionForm from './promotion-form';
import { ProtectFormGuard } from 'lib/protect-form';
import { recordTrack } from 'woocommerce/lib/analytics';
import { successNotice, errorNotice } from 'state/notices/actions';
import { validateAll } from './promotion-models';
class PromotionCreate extends React.Component {
static propTypes = {
className: PropTypes.string,
currency: PropTypes.string,
hasEdits: PropTypes.bool.isRequired,
site: PropTypes.shape( {
ID: PropTypes.number,
slug: PropTypes.string,
} ),
promotion: PropTypes.shape( {
id: PropTypes.isRequired,
} ),
editPromotion: PropTypes.func.isRequired,
clearPromotionEdits: PropTypes.func.isRequired,
createPromotion: PropTypes.func.isRequired,
fetchProductCategories: PropTypes.func.isRequired,
fetchPromotions: PropTypes.func.isRequired,
fetchSettingsGeneral: PropTypes.func.isRequired,
};
constructor( props ) {
super( props );
this.state = {
busy: false,
saveAttempted: false,
};
}
componentDidMount() {
const { site } = this.props;
if ( site && site.ID ) {
this.props.fetchProductCategories( site.ID, { offset: 0 } );
this.props.fetchPromotions( site.ID );
this.props.fetchSettingsGeneral( site.ID );
}
}
UNSAFE_componentWillReceiveProps( newProps ) {
const { site } = this.props;
const newSiteId = ( newProps.site && newProps.site.ID ) || null;
const oldSiteId = ( site && site.ID ) || null;
if ( oldSiteId !== newSiteId ) {
this.props.fetchProductCategories( newSiteId, { offset: 0 } );
this.props.fetchPromotions( newSiteId );
this.props.fetchSettingsGeneral( newSiteId );
}
// Track user starting to edit this promotion.
if ( ! this.props.hasEdits && newProps.hasEdits ) {
const editedFields = difference( Object.keys( newProps.promotion ), [
'id',
'name',
'type',
] );
const initial_field = 1 === editedFields.length ? editedFields[ 0 ] : 'multiple';
recordTrack( 'calypso_woocommerce_promotion_new_edit_start', { initial_field } );
}
}
componentWillUnmount() {
const { site } = this.props;
if ( site ) {
this.props.clearPromotionEdits( site.ID );
}
}
onSave = () => {
const { site, promotion, currency, translate } = this.props;
const validatingPromotion = promotion || { type: 'fixed_product' };
const errors = validateAll( validatingPromotion, currency, true );
if ( errors ) {
this.setState( () => ( { busy: false, saveAttempted: true } ) );
this.props.errorNotice(
translate(
'There is missing or invalid information. Please correct the highlighted fields and try again.'
),
{
duration: 8000,
}
);
return;
}
this.setState( () => ( { busy: true, saveAttempted: true } ) );
const getSuccessNotice = () => {
return successNotice(
translate( 'Promotion successfully created.', {
args: { promotion: promotion.name },
} ),
{
displayOnNextPage: true,
duration: 8000,
}
);
};
const successAction = dispatch => {
this.props.clearPromotionEdits( site.ID );
dispatch( getSuccessNotice( promotion ) );
page.redirect( getLink( '/store/promotions/:site', site ) );
};
const failureAction = error => {
this.setState( () => ( { busy: false } ) );
const errorSlug = ( error && error.error ) || undefined;
return errorNotice( getSaveErrorMessage( errorSlug, promotion.name, translate ), {
duration: 8000,
} );
};
this.props.createPromotion( site.ID, promotion, successAction, failureAction );
recordTrack( 'calypso_woocommerce_promotion_create', {
type: promotion.type,
sale_price: promotion.salePrice,
percent_discount: promotion.percentDiscount,
fixed_discount: promotion.fixedDiscount,
start_date: promotion.startDate,
end_date: promotion.endDate,
} );
};
render() {
const { site, currency, className, promotion, hasEdits, products } = this.props;
const { saveAttempted, busy } = this.state;
return (
<Main className={ className } wideLayout>
<PromotionHeader
site={ site }
promotion={ promotion }
onSave={ this.onSave }
isBusy={ busy }
/>
<ProtectFormGuard isChanged={ hasEdits } />
<PromotionForm
siteId={ site && site.ID }
currency={ currency }
promotion={ promotion }
editPromotion={ this.props.editPromotion }
products={ products }
showEmptyValidationErrors={ saveAttempted }
/>
</Main>
);
}
}
function mapStateToProps( state ) {
const site = getSelectedSiteWithFallback( state );
const currencySettings = getPaymentCurrencySettings( state );
const currency = currencySettings ? currencySettings.value : null;
const promotionId = getCurrentlyEditingPromotionId( state, site.ID );
const promotion = promotionId ? getPromotionWithLocalEdits( state, promotionId, site.ID ) : null;
const hasEdits = Boolean( getPromotionEdits( state, promotionId, site.ID ) );
const productsLoading = areProductsLoading( state, site.ID );
const products = productsLoading ? null : getAllProducts( state, site.ID );
return {
hasEdits,
site,
promotion,
currency,
products,
};
}
function mapDispatchToProps( dispatch ) {
return bindActionCreators(
{
editPromotion,
errorNotice,
clearPromotionEdits,
createPromotion,
fetchProductCategories,
fetchPromotions,
fetchSettingsGeneral,
},
dispatch
);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)( localize( PromotionCreate ) );
|
node_modules/babel-preset-react-hmre/test/Test.js | rajendrav5/webpack2.0 | import React from 'react'
export default
class Test extends React.Component {
render() {
return (
<div>Winning?</div>
)
}
}
|
classic/src/scenes/wbfa/generated/FARServer.pro.js | wavebox/waveboxapp | import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faServer } from '@fortawesome/pro-regular-svg-icons/faServer'
export default class FARServer extends React.Component {
render () {
return (<FontAwesomeIcon {...this.props} icon={faServer} />)
}
}
|
server/src/assets/javascripts/index.js | joe-re/automock | import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import App from './containers/app';
import reducers from './reducers';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
const middleware = process.env.NODE_ENV === 'production' ?
[ thunk ] :
[ thunk, logger() ];
const createStoreWithMiddleware = applyMiddleware(...middleware)(createStore);
const store = createStoreWithMiddleware(reducers);
const rootElement = document.getElementById('application');
render(
<Provider store={store}>
<App />
</Provider>,
rootElement
);
|
YEAR 3/SEM 1/MOBILE/mobile_exam_prep/screens/Experiment/Contests/Contests.js | Zephyrrus/ubb | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Alert,
ScrollView,
FlatList,
Button
} from 'react-native';
import PropTypes from 'prop-types'
import ContestComponent from './ContestComponent';
export default class Contests extends Component {
static propTypes = {
contests: PropTypes.array.isRequired,
}
static defaultProps = {
contests: []
}
constructor(props) {
super(props);
}
render() {
const {
contests
} = this.props;
return (
<View style={styles.container}>
<FlatList
style={styles.list}
contentContainerStyle={styles.listContainer}
data={contests}
keyExtractor= {(item) => {
return item.id.toString();
}}
ItemSeparatorComponent={() => {
return (
<View style={styles.separator}/>
)
}}
renderItem={(post) => {
const item = post.item;
return (
<ContestComponent {...item} />
)
}}/>
</View>
);
}
}
const styles = StyleSheet.create({
container:{
flex:1,
},
list: {
backgroundColor:"#fff",
},
listContainer: {
paddingVertical: 10,
},
separator: {
marginTop: 1,
},
});
|
src/hooks/useFormElement.js | tannerlinsley/react-form | import React from 'react'
//
import { FormContextProvider } from './useFormContext'
export default function useFormElement(contextValue) {
const FormRef = React.useRef()
const FormApiRef = React.useRef()
FormApiRef.current = contextValue
// Create a new form element
if (!FormRef.current) {
FormRef.current = function Form({ children, noFormElement, ...rest }) {
const {
handleSubmit,
meta: { isSubmitting },
debugForm,
} = FormApiRef.current
return (
<FormContextProvider value={FormApiRef.current}>
{noFormElement ? (
children
) : (
<form onSubmit={handleSubmit} disabled={isSubmitting} {...rest}>
{children}
{debugForm ? (
<div
style={{
margin: '2rem 0',
}}
>
<div
style={{
fontWeight: 'bolder',
}}
>
Form State
</div>
<pre>
<code>
{JSON.stringify(
{ ...FormApiRef.current, formContext: undefined },
safeStringifyReplace(new Set()),
2
)}
</code>
</pre>
</div>
) : null}
</form>
)}
</FormContextProvider>
)
}
}
// Return the form element
return FormRef.current
}
function safeStringifyReplace(set) {
return (key, value) => {
if (typeof value === 'object' || Array.isArray(value)) {
if (set.has(value)) {
return '(circular value)'
}
set.add(value)
}
return typeof value === 'function' ? undefined : value
}
}
|
client-app/src/album/CreateAlbumForm.js | mskorsur/music-app | import React from 'react';
import axios from 'axios';
import GenreFormItem from './GenreFormItem';
class CreateAlbumForm extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
artist: '',
genres: [],
releaseDate: new Date(),
created: false,
creationMessage: '',
apiArtists: [],
apiGenres: []
};
this._genreHelper = [];
this.handleNameChange = this.handleNameChange.bind(this);
this.handleArtistChange = this.handleArtistChange.bind(this);
this.handleGenreChange = this.handleGenreChange.bind(this);
this.handleReleaseDateChange = this.handleReleaseDateChange.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.convertGenreArrayToString = this.convertGenreArrayToString.bind(this);
this.renderArtistSelect = this.renderArtistSelect.bind(this);
this.renderGenreCheckboxes = this.renderGenreCheckboxes.bind(this);
this.renderCreationMessage = this.renderCreationMessage.bind(this);
this.setGenresToState = this.setGenresToState.bind(this);
}
componentDidMount() {
axios.get('http://localhost:3030/api/artist/list')
.then(response => {
this.setState({apiArtists: response.data});
});
axios.get('http://localhost:3030/api/genre/list')
.then(response => {
this.setState({apiGenres: response.data});
});
}
handleNameChange(event) {
this.setState({name: event.target.value});
}
handleArtistChange(event) {
this.setState({artist: event.target.value});
}
handleGenreChange(genreId, isChecked) {
if (isChecked) {
let genres = [...this._genreHelper, genreId];
this._genreHelper = [...genres];
}
else { //!isChecked
let genres = [...this._genreHelper];
let genreToBeRemovedIndex = genres.indexOf(genreId);
genres.splice(genreToBeRemovedIndex, 1);
this._genreHelper = genres;
}
}
setGenresToState() {
this.setState({
genres: this._genreHelper
});
}
handleReleaseDateChange(event) {
this.setState({releaseDate: event.target.value});
}
convertGenreArrayToString(genres) {
return genres.join(',');
}
handleFormSubmit(event) {
event.preventDefault();
axios.post('http://localhost:3030/api/album/create', {
name: this.state.name,
artist: this.state.artist,
genre: this.convertGenreArrayToString(this.state.genres),
releaseDate: this.state.releaseDate
})
.then(response => {
this.setState({created: true, creationMessage: response.data.message});
});
}
renderArtistSelect() {
return (
<select value={this.state.artist} onChange={this.handleArtistChange}>
{this.state.apiArtists.map(artist => {
return <option key={artist.id} value={artist.id}>{artist.name}</option>;
})}
</select>
);
}
renderGenreCheckboxes() {
return (
<label>
Genres:
{this.state.apiGenres.map(genre => {
return <GenreFormItem key={genre.id} genre={genre} checked={false} handleCheck={this.handleGenreChange} />
})}
<button type="button" onClick={this.setGenresToState}>Update Genres</button>
</label>
);
}
renderCreationMessage() {
if (this.state.created) {
return <p>{this.state.creationMessage}</p>;
}
}
render() {
return (
<div className="one-third column content-column">
<h4>Create a new album</h4>
<form onSubmit={this.handleFormSubmit}>
<label>
Name:
<input type="text" value={this.state.name} onChange={this.handleNameChange} />
</label>
<label>
Artist:
{this.renderArtistSelect()}
</label>
{this.renderGenreCheckboxes()}
<label>
Release date:
<input type="date" value={this.state.releaseDate} onChange={this.handleReleaseDateChange} />
</label>
<input type="submit" value="Submit" className="padding-right"/>
<button onClick={this.props.handleCancel}>Cancel</button>
</form>
{this.renderCreationMessage()}
</div>
);
}
}
export default CreateAlbumForm; |
packages/ringcentral-widgets/components/Switch/index.js | ringcentral/ringcentral-js-widget | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import styles from './styles.scss';
function Switch(props) {
const onChange = props.onChange
? (e) => !props.disable && props.onChange(e.currentTarget.checked)
: undefined;
return (
<label
title={props.title}
data-sign={props.dataSign}
className={classnames(
styles.switch,
props.className,
props.disable && styles.disable,
)}
>
<input
data-sign="switch"
type="checkbox"
checked={props.checked}
onChange={onChange}
/>
<div className={styles.slider} />
</label>
);
}
Switch.propTypes = {
checked: PropTypes.bool,
disable: PropTypes.bool,
title: PropTypes.string,
onChange: PropTypes.func,
dataSign: PropTypes.string,
className: PropTypes.string,
};
Switch.defaultProps = {
checked: false,
disable: false,
onChange: undefined,
title: undefined,
dataSign: undefined,
className: undefined,
};
export default Switch;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.