path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/components/CardSection.js | shabib87/Albums | import React from 'react';
import { View } from 'react-native';
const CardSection = (props) => (
<View style={styles.containerStyle}>
{props.children}
</View>
);
const styles = {
containerStyle: {
borderBottomWidth: 1,
padding: 5,
backgroundColor: '#fff',
justifyContent: 'flex-start',
flexDirection: 'row',
borderColor: '#ddd',
position: 'relative'
}
};
export default CardSection;
|
actor-apps/app-web/src/app/components/activity/UserProfile.react.js | gaolichuang/actor-platform | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import _ from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import classnames from 'classnames';
import ActorClient from 'utils/ActorClient';
import confirm from 'utils/confirm'
import ContactActionCreators from 'actions/ContactActionCreators';
import DialogActionCreators from 'actions/DialogActionCreators';
import PeerStore from 'stores/PeerStore';
import DialogStore from 'stores/DialogStore';
import AvatarItem from 'components/common/AvatarItem.react';
import Fold from 'components/common/Fold.React';
const getStateFromStores = (userId) => {
const thisPeer = PeerStore.getUserPeer(userId);
return {
thisPeer: thisPeer,
isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer)
};
};
@ReactMixin.decorate(IntlMixin) class UserProfile extends React.Component {
static propTypes = {
user: React.PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.state = _.assign({
isActionsDropdownOpen: false
}, getStateFromStores(props.user.id));
DialogStore.addNotificationsListener(this.onChange);
}
componentWillUnmount() {
DialogStore.removeNotificationsListener(this.onChange);
}
componentWillReceiveProps(newProps) {
this.setState(getStateFromStores(newProps.user.id));
}
addToContacts = () => {
ContactActionCreators.addContact(this.props.user.id);
};
removeFromContacts = () => {
const { user } = this.props;
const confirmText = 'You really want to remove ' + user.name + ' from your contacts?';
confirm(confirmText).then(
() => ContactActionCreators.removeContact(user.id)
);
};
onNotificationChange = (event) => {
const { thisPeer } = this.state;
DialogActionCreators.changeNotificationsEnabled(thisPeer, event.target.checked);
};
onChange = () => {
const { user } = this.props;
this.setState(getStateFromStores(user.id));
};
toggleActionsDropdown = () => {
const { isActionsDropdownOpen } = this.state;
if (!isActionsDropdownOpen) {
this.setState({isActionsDropdownOpen: true});
document.addEventListener('click', this.closeActionsDropdown, false);
} else {
this.closeActionsDropdown();
}
};
closeActionsDropdown = () => {
this.setState({isActionsDropdownOpen: false});
document.removeEventListener('click', this.closeActionsDropdown, false);
};
clearChat = (uid) => {
confirm('Do you really want to delete this conversation?').then(
() => {
const peer = ActorClient.getUserPeer(uid);
DialogActionCreators.clearChat(peer);
},
() => {
}
);
};
deleteChat = (uid) => {
confirm('Do you really want to delete this conversation?').then(
() => {
const peer = ActorClient.getUserPeer(uid);
DialogActionCreators.deleteChat(peer);
},
() => {
}
);
};
render() {
const { user } = this.props;
const { isNotificationsEnabled, isActionsDropdownOpen } = this.state;
const actions = (user.isContact === false) ? (
<li className="dropdown__menu__item" onClick={this.addToContacts}>
<FormattedMessage message={this.getIntlMessage('addToContacts')}/>
</li>
) : (
<li className="dropdown__menu__item" onClick={this.removeFromContacts}>
<FormattedMessage message={this.getIntlMessage('removeFromContacts')}/>
</li>
);
const dropdownClassNames = classnames('dropdown pull-left', {
'dropdown--opened': isActionsDropdownOpen
});
const about = user.about ? (
<div className="user_profile__meta__about">
{user.about}
</div>
) : null;
const nickname = user.nick ? (
<li>
<svg className="icon icon--pink"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#username"/>'}}/>
<span className="title">{user.nick}</span>
<span className="description">nickname</span>
</li>
) : null;
const email = user.email ? (
<li className="hide">
<i className="material-icons icon icon--blue">mail</i>
<span className="title">{user.email}</span>
<span className="description">email</span>
</li>
) : null;
const phone = user.phones[0] ? (
<li>
<i className="material-icons icon icon--green">call</i>
<span className="title">{'+' + user.phones[0].number}</span>
<span className="description">mobile</span>
</li>
) : null;
return (
<div className="activity__body user_profile">
<ul className="profile__list">
<li className="profile__list__item user_profile__meta">
<header>
<AvatarItem image={user.bigAvatar}
placeholder={user.placeholder}
size="large"
title={user.name}/>
<h3 className="user_profile__meta__title">{user.name}</h3>
<div className="user_profile__meta__presence">{user.presence}</div>
</header>
{about}
<footer>
<div className={dropdownClassNames}>
<button className="dropdown__button button button--flat" onClick={this.toggleActionsDropdown}>
<i className="material-icons">more_horiz</i>
<FormattedMessage message={this.getIntlMessage('actions')}/>
</button>
<ul className="dropdown__menu dropdown__menu--left">
{actions}
<li className="dropdown__menu__item dropdown__menu__item--light"
onClick={() => this.clearChat(user.id)}>
<FormattedMessage message={this.getIntlMessage('clearConversation')}/>
</li>
<li className="dropdown__menu__item dropdown__menu__item--light"
onClick={() => this.deleteChat(user.id)}>
<FormattedMessage message={this.getIntlMessage('deleteConversation')}/>
</li>
</ul>
</div>
</footer>
</li>
<li className="profile__list__item user_profile__contact_info no-p">
<ul className="user_profile__contact_info__list">
{nickname}
{phone}
{email}
</ul>
</li>
<li className="profile__list__item user_profile__media no-p hide">
<Fold icon="attach_file" iconClassName="icon--gray" title={this.getIntlMessage('sharedMedia')}>
<ul>
<li><a>230 Shared Photos and Videos</a></li>
<li><a>49 Shared Links</a></li>
<li><a>49 Shared Files</a></li>
</ul>
</Fold>
</li>
<li className="profile__list__item user_profile__notifications no-p">
<label htmlFor="notifications">
<i className="material-icons icon icon--squash">notifications_none</i>
<FormattedMessage message={this.getIntlMessage('notifications')}/>
<div className="switch pull-right">
<input checked={isNotificationsEnabled}
id="notifications"
onChange={this.onNotificationChange}
type="checkbox"/>
<label htmlFor="notifications"></label>
</div>
</label>
</li>
</ul>
</div>
);
}
}
export default UserProfile;
|
internals/templates/app.js | mmaedel/react-boilerplate | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import 'babel-polyfill';
/* eslint-disable import/no-unresolved, import/extensions */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: selectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (translatedMessages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={translatedMessages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(System.import('intl'));
}))
.then(() => Promise.all([
System.import('intl/locale-data/jsonp/de.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
|
src/GoalProgressBarGeneral/index.js | christianalfoni/ducky-components | import Typography from '../Typography';
import IconImage from '../IconImage';
import ProgressCircle from '../ProgressCircle';
import LabelSmall from '../LabelSmall';
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import styles from './styles.css';
function GoalProgressBarGeneral(props) {
let opt = (
<Typography
className={styles.typo}
type={'header1'}
>
{props.percentage}{" %"}
</Typography>
);
let labelIcon = 'icon-assignment_turned_in';
if (props.type.toUpperCase() === 'ACTIVITY') {
labelIcon = 'icon-check_circle';
} else if (props.type.toUpperCase() === 'CO2') {
labelIcon = 'icon-leaf';
} else if (props.type.toUpperCase() === 'POINTS') {
labelIcon = 'icon-brightness_high';
}
if (props.type.toUpperCase() === 'HABIT' || props.type.toUpperCase() === 'ACTIVITY') {
opt = (
<IconImage
className={styles.innerElement}
icon={props.icon}
size={"large"}
/>
);
}
return (
<div
className={classNames(styles.wrapper, {
[props.className]: props.className
})}
>
<div>
<ProgressCircle
percent={props.percentage}
type={props.type}
/>
{opt}
</div>
<div className={styles.innerWrapper}>
<LabelSmall
className={classNames(styles.labelSmall,
{[styles.pointsIcon]: labelIcon === 'icon-brightness_high'},
{[styles.co2Icon]: labelIcon === 'icon-leaf'},
{[styles.activityIcon]: labelIcon === 'icon-check_circle'},
{[styles.habitIcon]: labelIcon === 'icon-assignment_turned_in'},
)}
content={props.content}
icon={labelIcon}
onClick={props.handleButtonClick}
type={"caption2Normal"}
/>
</div>
</div>
);
}
GoalProgressBarGeneral.propTypes = {
className: PropTypes.string,
content: PropTypes.string,
handleButtonClick: PropTypes.func,
icon: PropTypes.string,
percentage: PropTypes.number,
type: PropTypes.string
};
export default GoalProgressBarGeneral;
|
node_modules/react-bootstrap/es/NavbarHeader.js | firdiansyah/crud-req | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { prefix } from './utils/bootstrapUtils';
var contextTypes = {
$bs_navbar: PropTypes.shape({
bsClass: PropTypes.string
})
};
var NavbarHeader = function (_React$Component) {
_inherits(NavbarHeader, _React$Component);
function NavbarHeader() {
_classCallCheck(this, NavbarHeader);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavbarHeader.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' };
var bsClassName = prefix(navbarProps, 'header');
return React.createElement('div', _extends({}, props, { className: classNames(className, bsClassName) }));
};
return NavbarHeader;
}(React.Component);
NavbarHeader.contextTypes = contextTypes;
export default NavbarHeader; |
stories/Durations.js | intljusticemission/react-big-calendar | import React from 'react'
import { storiesOf } from '@storybook/react'
import moment from 'moment'
import { Calendar, Views, DragableCalendar } from './helpers'
storiesOf('Event Durations', module)
.add('Daylight savings starts', () => {
return (
<DragableCalendar
defaultView={Views.DAY}
min={moment('12:00am', 'h:mma').toDate()}
max={moment('11:59pm', 'h:mma').toDate()}
events={[
{
title: 'on DST',
start: new Date(2017, 2, 12, 1),
end: new Date(2017, 2, 12, 2, 30),
allDay: false,
},
{
title: 'crosses DST',
start: new Date(2017, 2, 12, 1),
end: new Date(2017, 2, 12, 6, 30),
allDay: false,
},
{
title: 'After DST',
start: new Date(2017, 2, 12, 7),
end: new Date(2017, 2, 12, 9, 30),
allDay: false,
},
]}
defaultDate={new Date(2017, 2, 12)}
/>
)
})
.add('Daylight savings ends', () => {
return (
<DragableCalendar
defaultView={Views.DAY}
min={moment('12:00am', 'h:mma').toDate()}
max={moment('11:59pm', 'h:mma').toDate()}
events={[
{
title: 'on DST',
start: new Date(2017, 10, 5, 1),
end: new Date(2017, 10, 5, 3, 30),
allDay: false,
},
{
title: 'crosses DST',
start: new Date(2017, 10, 5, 1),
end: new Date(2017, 10, 5, 6, 30),
allDay: false,
},
{
title: 'After DST',
start: new Date(2017, 10, 5, 7),
end: new Date(2017, 10, 5, 7, 45),
allDay: false,
},
]}
defaultDate={new Date(2017, 10, 5)}
/>
)
})
.add('Daylight savings starts, after 2am', () => {
return (
<DragableCalendar
defaultView={Views.DAY}
min={moment('3:00am', 'h:mma').toDate()}
max={moment('11:59pm', 'h:mma').toDate()}
events={[
{
title: 'After DST',
start: new Date(2017, 2, 12, 7),
end: new Date(2017, 2, 12, 9, 30),
allDay: false,
},
]}
defaultDate={new Date(2017, 2, 12)}
/>
)
})
.add('Daylight savings ends, after 2am', () => {
return (
<DragableCalendar
defaultView={Views.DAY}
min={moment('3:00am', 'h:mma').toDate()}
max={moment('11:59pm', 'h:mma').toDate()}
events={[
{
title: 'After DST',
start: new Date(2017, 10, 5, 7),
end: new Date(2017, 10, 5, 9, 30),
allDay: false,
},
]}
defaultDate={new Date(2017, 10, 5)}
/>
)
})
|
app/javascript/mastodon/components/button.js | pso2club/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
export default class Button extends React.PureComponent {
static propTypes = {
text: PropTypes.node,
onClick: PropTypes.func,
disabled: PropTypes.bool,
block: PropTypes.bool,
secondary: PropTypes.bool,
size: PropTypes.number,
className: PropTypes.string,
style: PropTypes.object,
children: PropTypes.node,
};
static defaultProps = {
size: 36,
};
handleClick = (e) => {
if (!this.props.disabled) {
this.props.onClick(e);
}
}
setRef = (c) => {
this.node = c;
}
focus() {
this.node.focus();
}
render () {
const style = {
padding: `0 ${this.props.size / 2.25}px`,
height: `${this.props.size}px`,
lineHeight: `${this.props.size}px`,
...this.props.style,
};
const className = classNames('button', this.props.className, {
'button-secondary': this.props.secondary,
'button--block': this.props.block,
});
return (
<button
className={className}
disabled={this.props.disabled}
onClick={this.handleClick}
ref={this.setRef}
style={style}
>
{this.props.text || this.props.children}
</button>
);
}
}
|
src/containers/Asians/TabControls/PreliminaryRounds/CreateRooms/6_AdjudicatorsPreview/AdjudicatorTable/AdjudicatorDragAndDrop.js | westoncolemanl/tabbr-web | import React from 'react'
import ItemTypes from './ItemTypes'
import { DragSource } from 'react-dnd'
import { connect } from 'react-redux'
import withStyles from 'material-ui/styles/withStyles'
import AdjudicatorChip from 'containers/Asians/TabControls/_components/AdjudicatorChips/AdjudicatorChip'
const styles = theme => ({
root: {
marginBottom: theme.spacing.unit
}
})
const adjudicatorSource = {
beginDrag (props) {
props.onDrag(true)
return {
adjudicator: props.adjudicator,
position: props.position,
room: props.room
}
},
endDrag (props) {
props.onDrag(false)
}
}
function collect (connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
}
}
const AdjudicatorDragAndDrop = connect(mapStateToProps)(withStyles(styles)(({
isDragging,
connectDragSource,
adjudicator,
adjudicatorsById,
adjudicatorStandings,
institutionsById,
round,
minimumRelevantAdjudicatorPoint,
margin,
room,
classes
}) => {
return connectDragSource(
<div
className={margin ? classes.root : ''}
>
<AdjudicatorChip
room={room}
adjudicator={adjudicator}
round={round}
minimumRelevantAdjudicatorPoint={minimumRelevantAdjudicatorPoint}
/>
</div>
)
}))
export default DragSource(ItemTypes.ADJUDICATOR, adjudicatorSource, collect)(AdjudicatorDragAndDrop)
function mapStateToProps (state, ownProps) {
return {
institutionsById: state.institutions.data,
adjudicatorsById: state.adjudicators.data,
adjudicatorStandings: state.standings.adjudicators
}
}
|
awsmobilecognitocustomui/src/components/Loading.js | adrianhall/blog-code | import React from 'react';
import { StyleSheet, View } from 'react-native';
import Spinner from 'react-native-spinkit';
import colors from '../theme/colors';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: colors.headerBackgroundColor,
}
});
const Loading = (props) => {
return (
<View style={styles.container}>
<Spinner type="Wave" size={100} color="white" isVisible={true} />
</View>
);
};
export default Loading;
|
src/App.js | isuruAb/chat.susi.ai | import Blog from './components/Blog/Blog.react';
import ChatApp from './components/ChatApp/ChatApp.react';
import Contact from './components/Contact/Contact.react';
import Devices from './components/Devices/Devices.react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import Logout from './components/Auth/Logout.react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import PropTypes from 'prop-types';
import NotFound from './components/NotFound/NotFound.react';
import Overview from './components/Overview/Overview.react';
import Settings from './components/ChatApp/Settings/Settings.react';
import Support from './components/Support/Support.react';
import Team from './components/Team/Team.react';
import Terms from './components/Terms/Terms.react';
import Privacy from './components/Privacy/Privacy.react';
import { Switch, Route } from 'react-router-dom';
import React, { Component } from 'react';
const muiTheme = getMuiTheme({
toggle: {
thumbOnColor: '#5ab1fc',
trackOnColor: '#4285f4'
}
});
class App extends Component{
closeVideo = () => this.setState({
video: false
})
render(){
if(location.pathname!=='/'){
document.body.className = 'white-body';
}
return(
<MuiThemeProvider muiTheme={muiTheme}>
<div>
<Switch>
<Route exact path='/' component={ChatApp}/>
<Route exact path="/overview" component={Overview} />
<Route exact path="/devices" component={Devices} />
<Route exact path='/team' component={Team} />
<Route exact path='/blog' component={Blog} />
<Route exact path='/contact' component={Contact} />
<Route exact path="/support" component={Support} />
<Route exact path="/terms" component={Terms} />
<Route exact path="/privacy" component={Privacy} />
<Route exact path="/logout" component={Logout} />
<Route exact path="/settings" component={Settings} />
<Route exact path="*" component={NotFound} />
</Switch>
</div>
</MuiThemeProvider>
);
}
}
App.propTypes = {
history: PropTypes.object,
location: PropTypes.object,
closeVideo: PropTypes.func
}
export default App;
|
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js | zomeelee/actor-platform | import React from 'react';
import { PureRenderMixin } from 'react/addons';
import AvatarItem from 'components/common/AvatarItem.react';
var ContactItem = React.createClass({
displayName: 'ContactItem',
propTypes: {
contact: React.PropTypes.object,
onSelect: React.PropTypes.func
},
mixins: [PureRenderMixin],
_onSelect() {
this.props.onSelect(this.props.contact);
},
render() {
let contact = this.props.contact;
return (
<li className="contacts__list__item row">
<AvatarItem image={contact.avatar}
placeholder={contact.placeholder}
size="small"
title={contact.name}/>
<div className="col-xs">
<span className="title">
{contact.name}
</span>
</div>
<div className="controls">
<a className="material-icons" onClick={this._onSelect}>add</a>
</div>
</li>
);
}
});
export default ContactItem;
|
src/svg-icons/content/clear.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentClear = (props) => (
<SvgIcon {...props}>
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
</SvgIcon>
);
ContentClear = pure(ContentClear);
ContentClear.displayName = 'ContentClear';
ContentClear.muiName = 'SvgIcon';
export default ContentClear;
|
src/components_youtube_p/video_detail.js | vikasv/ReactWithRedux | import React from 'react';
const VideoDetail = ({video}) => {
if(!video){
return <div>Loading...</div>;
}
const videoId = video.id.videoId;
const url = 'https://www.youtube.com/embed/' + videoId; //Below es6 syntax
//const url = `https://www.youtube.com/embed/$(videoId)`;
return (
<div className = "video-detail col-md-8">
<div className = "embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src={url} allowFullScreen></iframe>
</div>
<div className="details">
<div>{video.snippet.title}</div>
<div>{video.snippet.description}</div>
</div>
</div>
);
};
export default VideoDetail;
|
src/components/orders/orders_table.js | hojberg/mastering-react | import React from 'react';
import OrderRow from './order_row';
class OrdersTable extends React.Component {
render() {
const rows = this.props.orders.map((order, i) => {
return <OrderRow order={order} key={i} />;
});
return (
<table className='orders-table'>
<thead>
<tr>
<th>Order #</th>
<th>Customer</th>
<th className='sorted-by'>Ordered at</th>
<th>Product(s)</th>
<th className='amount'>Amount</th>
<th className='status'>Payment status</th>
<th className='status'>Order status</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
);
}
}
export default OrdersTable;
|
tests/format/misc/flow-babel-only/class_with_generics.js | jlongster/prettier | import React from 'react';
/*:: type Props = {
foo?: ?string,
bar: number,
}; */
/*:: type State = { baz: number }; */
class Component extends React.Component/*:: <Props, State> */ {
}
|
src/internal/Overlay.js | rscnt/material-ui | import React from 'react';
import transitions from '../styles/transitions';
import AutoLockScrolling from './AutoLockScrolling';
function getStyles(props, context) {
const {overlay} = context.muiTheme;
const style = {
root: {
position: 'fixed',
height: '100%',
width: '100%',
top: 0,
left: '-100%',
opacity: 0,
backgroundColor: overlay.backgroundColor,
WebkitTapHighlightColor: 'rgba(0, 0, 0, 0)', // Remove mobile color flashing (deprecated)
// Two ways to promote overlay to its own render layer
willChange: 'opacity',
transform: 'translateZ(0)',
transition:
props.transitionEnabled && `${transitions.easeOut('0ms', 'left', '400ms')}, ${
transitions.easeOut('400ms', 'opacity')}`,
},
};
if (props.show) {
Object.assign(style.root, {
left: 0,
opacity: 1,
transition: `${transitions.easeOut('0ms', 'left')}, ${
transitions.easeOut('400ms', 'opacity')}`,
});
}
return style;
}
class Overlay extends React.Component {
static propTypes = {
autoLockScrolling: React.PropTypes.bool,
show: React.PropTypes.bool.isRequired,
/**
* Override the inline-styles of the root element.
*/
style: React.PropTypes.object,
transitionEnabled: React.PropTypes.bool,
};
static defaultProps = {
autoLockScrolling: true,
transitionEnabled: true,
style: {},
};
static contextTypes = {
muiTheme: React.PropTypes.object.isRequired,
};
setOpacity(opacity) {
this.refs.overlay.style.opacity = opacity;
}
render() {
const {
autoLockScrolling,
show,
style,
...other,
} = this.props;
const {prepareStyles} = this.context.muiTheme;
const styles = getStyles(this.props, this.context);
return (
<div {...other} ref="overlay" style={prepareStyles(Object.assign(styles.root, style))}>
{autoLockScrolling && <AutoLockScrolling lock={show} />}
</div>
);
}
}
export default Overlay;
|
app/javascript/mastodon/features/account_timeline/components/moved_note.js | yi0713/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import AvatarOverlay from '../../../components/avatar_overlay';
import DisplayName from '../../../components/display_name';
import Icon from 'mastodon/components/icon';
export default class MovedNote extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
from: ImmutablePropTypes.map.isRequired,
to: ImmutablePropTypes.map.isRequired,
};
handleAccountClick = e => {
if (e.button === 0) {
e.preventDefault();
this.context.router.history.push(`/@${this.props.to.get('acct')}`);
}
e.stopPropagation();
}
render () {
const { from, to } = this.props;
const displayNameHtml = { __html: from.get('display_name_html') };
return (
<div className='account__moved-note'>
<div className='account__moved-note__message'>
<div className='account__moved-note__icon-wrapper'><Icon id='suitcase' className='account__moved-note__icon' fixedWidth /></div>
<FormattedMessage id='account.moved_to' defaultMessage='{name} has moved to:' values={{ name: <bdi><strong dangerouslySetInnerHTML={displayNameHtml} /></bdi> }} />
</div>
<a href={to.get('url')} onClick={this.handleAccountClick} className='detailed-status__display-name'>
<div className='detailed-status__display-avatar'><AvatarOverlay account={to} friend={from} /></div>
<DisplayName account={to} />
</a>
</div>
);
}
}
|
src/test/xy-plot.js | jameskraus/react-vis | // Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import test from 'tape';
import React from 'react';
import {shallow} from 'enzyme';
import VerticalBarSeries from '../lib/plot/series/vertical-bar-series';
import XAxis from '../lib/plot/axis/x-axis';
import XYPlot from '../lib/plot/xy-plot';
test('Render a stacked bar chart', assert => {
const wrapper = shallow(
<XYPlot width={300} height={300} stackBy="y">
<VerticalBarSeries
data={[
{x: 1, y: 0},
{x: 2, y: 1},
{x: 3, y: 2}
]}
/>
<VerticalBarSeries
data={[
{x: 1, y: 2},
{x: 2, y: 1},
{x: 3, y: 0}
]}/>
</XYPlot>
);
const renderedVerticalBarsWrapper =
wrapper.find(VerticalBarSeries);
assert.deepEqual(
renderedVerticalBarsWrapper.at(0).prop('data'),
[
{x: 1, y: 0},
{x: 2, y: 1},
{x: 3, y: 2}
],
'First bar series data is the same'
);
assert.deepEqual(
renderedVerticalBarsWrapper.at(1).prop('data'),
[
{x: 1, y: 2, y0: 0},
{x: 2, y: 2, y0: 1},
{x: 3, y: 2, y0: 2}
],
'Second bar series data contains y0 values'
);
assert.end();
});
test('Render a stacked bar chart with other children', assert => {
const wrapper = shallow(
<XYPlot width={300} height={300} stackBy="y">
<XAxis />
<VerticalBarSeries
data={[
{x: 1, y: 0}
]}
/>
<VerticalBarSeries
data={[
{x: 1, y: 2}
]}/>
{
/*
Empty div here is intentional, for testing series children handling
*/
}
<div></div>
</XYPlot>
);
const renderedVerticalBarsWrapper =
wrapper.find(VerticalBarSeries);
assert.deepEqual(
renderedVerticalBarsWrapper.at(0).prop('data'),
[
{x: 1, y: 0}
],
'First bar series data is the same'
);
assert.deepEqual(
renderedVerticalBarsWrapper.at(1).prop('data'),
[
{x: 1, y: 2, y0: 0}
],
'Second bar series data contains y0 values'
);
assert.end();
});
|
app/javascript/mastodon/features/account/components/account_note.js | glitch-soc/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Textarea from 'react-textarea-autosize';
import { is } from 'immutable';
const messages = defineMessages({
placeholder: { id: 'account_note.placeholder', defaultMessage: 'Click to add a note' },
});
class InlineAlert extends React.PureComponent {
static propTypes = {
show: PropTypes.bool,
};
state = {
mountMessage: false,
};
static TRANSITION_DELAY = 200;
componentWillReceiveProps (nextProps) {
if (!this.props.show && nextProps.show) {
this.setState({ mountMessage: true });
} else if (this.props.show && !nextProps.show) {
setTimeout(() => this.setState({ mountMessage: false }), InlineAlert.TRANSITION_DELAY);
}
}
render () {
const { show } = this.props;
const { mountMessage } = this.state;
return (
<span aria-live='polite' role='status' className='inline-alert' style={{ opacity: show ? 1 : 0 }}>
{mountMessage && <FormattedMessage id='generic.saved' defaultMessage='Saved' />}
</span>
);
}
}
export default @injectIntl
class AccountNote extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
value: PropTypes.string,
onSave: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
state = {
value: null,
saving: false,
saved: false,
};
componentWillMount () {
this._reset();
}
componentWillReceiveProps (nextProps) {
const accountWillChange = !is(this.props.account, nextProps.account);
const newState = {};
if (accountWillChange && this._isDirty()) {
this._save(false);
}
if (accountWillChange || nextProps.value === this.state.value) {
newState.saving = false;
}
if (this.props.value !== nextProps.value) {
newState.value = nextProps.value;
}
this.setState(newState);
}
componentWillUnmount () {
if (this._isDirty()) {
this._save(false);
}
}
setTextareaRef = c => {
this.textarea = c;
}
handleChange = e => {
this.setState({ value: e.target.value, saving: false });
};
handleKeyDown = e => {
if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
this._save();
if (this.textarea) {
this.textarea.blur();
}
} else if (e.keyCode === 27) {
e.preventDefault();
this._reset(() => {
if (this.textarea) {
this.textarea.blur();
}
});
}
}
handleBlur = () => {
if (this._isDirty()) {
this._save();
}
}
_save (showMessage = true) {
this.setState({ saving: true }, () => this.props.onSave(this.state.value));
if (showMessage) {
this.setState({ saved: true }, () => setTimeout(() => this.setState({ saved: false }), 2000));
}
}
_reset (callback) {
this.setState({ value: this.props.value }, callback);
}
_isDirty () {
return !this.state.saving && this.props.value !== null && this.state.value !== null && this.state.value !== this.props.value;
}
render () {
const { account, intl } = this.props;
const { value, saved } = this.state;
if (!account) {
return null;
}
return (
<div className='account__header__account-note'>
<label htmlFor={`account-note-${account.get('id')}`}>
<FormattedMessage id='account.account_note_header' defaultMessage='Note' /> <InlineAlert show={saved} />
</label>
<Textarea
id={`account-note-${account.get('id')}`}
className='account__header__account-note__content'
disabled={this.props.value === null || value === null}
placeholder={intl.formatMessage(messages.placeholder)}
value={value || ''}
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
onBlur={this.handleBlur}
ref={this.setTextareaRef}
/>
</div>
);
}
}
|
www/components/Navigation/Navigation.js | DremyGit/dremy-blog | import React from 'react';
import { Link, withRouter } from 'react-router';
import CSSModules from 'react-css-modules';
import styles from './Navigation.scss';
@withRouter
@CSSModules(styles)
class Navigation extends React.Component {
constructor(props) {
super(props);
this.state = {
searchInput: false,
searchContent: '',
};
}
isActiveMenu(menu) {
const { routes } = this.props;
const part = (routes[1] && routes[1].path) || 'blog';
return menu.pattern.test(part);
}
doSearch() {
const { router } = this.props;
router.push(`/search/${this.state.searchContent}`);
}
handleSearch() {
if (!this.state.searchInput) {
this.setState({ searchInput: true });
this.input.focus();
} else if (this.state.searchContent) {
this.doSearch();
setTimeout(() => this.setState({ searchContent: '' }), 500);
} else {
this.setState({ searchInput: false });
}
}
handleKeyDown(e) {
if (e.keyCode === 13 && this.state.searchContent !== '') {
this.doSearch();
}
}
render() {
const menus = [
{ href: '', pattern: /blog/, name: '首页' },
{ href: 'category', pattern: /category/, name: '分类' },
{ href: 'tag', pattern: /tag/, name: '标签' },
{ href: 'archive', pattern: /archive/, name: '归档' },
{ href: 'about', pattern: /about/, name: '关于' },
];
const { maxWidth } = this.props;
const menuList = menus.map((menu) => {
return (
<li key={menu.href} className={styles.listItem} styleName={this.isActiveMenu(menu) ? 'active' : null}>
<Link styleName={'menuLink'} to={`/${menu.href}`}>{menu.name}</Link>
</li>
);
});
return (
<div styleName="header">
<div styleName="navigation" style={{ maxWidth }}>
<Link to="/">
<span styleName="logo">Dremy_博客</span>
</Link>
<ul styleName="menu">
{menuList}
</ul>
<div className={styles.search} styleName={this.state.searchInput && 'active'}>
<input
styleName="searchInput"
ref={(input) => { this.input = input; }}
value={this.state.searchContent}
onChange={e => this.setState({ searchContent: e.target.value })}
onKeyDown={e => this.handleKeyDown(e)}
placeholder="搜索标题或关键词"
onBlur={() => setTimeout(() => this.setState({ searchInput: false }), 300)}
/>
<a onClick={() => this.handleSearch()}>
<i className="fa fa-search" aria-hidden="true" />
</a>
</div>
</div>
</div>
);
}
}
Navigation.PropTypes = {
maxWidth: React.PropTypes.string.isRequired,
};
export default Navigation;
|
src/client/course/EditVenturerCourse.js | jmicmoore/merit-badge-university | import React from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import TextArea from "../common/components/TextArea";
import SingleSelect from '../common/components/SingleSelect';
import SimpleList from '../common/components/SimpleList';
import {updateCourse, getCourseById, resetCurrentCourse, getVenturingClassNames} from './courseActions';
import {validate} from '../common/util/validation';
import validationConfig from './VenturerCourseValidationConfig';
import {COURSE_TYPE} from './constants';
const recommendedLengthChoices = [
{value: '1 hour', label: '1 hour'},
{value: '2 hours', label: '2 hours'},
{value: '3 hours', label: '3 hours'},
{value: '4 hours', label: '4 hours'},
{value: 'more than 4 hours', label: 'more than 4 hours'}
];
const recommendedSizeChoices = [
{value: '2-6 students', label: '2-6 students'},
{value: '4-8 students', label: '4-8 students'},
{value: '6-12 students', label: '6-12 students'},
{value: '10-20 students', label: '10-20 students'},
{value: 'more than 20 students', label: 'more than 20 students'}
];
class EditVenturerCourse extends React.Component {
constructor(){
super();
this.state = {
venturingClass: '',
recommendedLength: '',
recommendedSize: '',
notes: '',
teachers: ['Joe Smith']
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleAddMe = this.handleAddMe.bind(this);
this.handleRemoveMe = this.handleRemoveMe.bind(this);
}
componentDidMount() {
if(this.props.match.params.courseId){
getCourseById(this.props.match.params.courseId);
}
getVenturingClassNames();
};
componentWillUnmount(){
resetCurrentCourse();
}
currentCourseIsChanging(nextProps){
return nextProps.currentCourse !== this.props.currentCourse;
}
componentWillReceiveProps(nextProps){
if(this.currentCourseIsChanging(nextProps)){
const courseLocalCopy = Object.assign({}, nextProps.currentCourse);
this.setState(courseLocalCopy);
}
};
handleAddMe(){
const newTeachers = this.state.teachers.slice();
newTeachers.push("Jerry Moore");
this.setState({teachers: newTeachers});
}
handleRemoveMe(){
const index = this.state.teachers.indexOf("Jerry Moore");
let newTeachers = this.state.teachers.slice();
if(index !== -1){
newTeachers.splice(index, 1);
}
this.setState({teachers: newTeachers})
}
handleChange(field, value) {
this.setState({[field]: value});
};
handleSubmit(event) {
event.preventDefault();
const report = validate(this.state, validationConfig);
if(report.allValid){
const newCourse = Object.assign(
{},
this.state,
{
courseType : COURSE_TYPE.Venturing,
}
);
updateCourse(newCourse);
this.setState({ displayErrors: false });
this.props.history.push('/admin/venturer-courses'); // go back to courses screen
} else {
this.setState({ displayErrors: true });
}
this.setState({errorReport: report});
};
render(){
const venturingClassChoices = this.props.venturingClassNames || [];
const classInfo = this.state;
const index = this.state.teachers.indexOf("Jerry Moore");
let teachingAlready = false;
if(index !== -1){
teachingAlready = true;
}
return (
<div className="container">
<div className="row">
<div id="form-container-registration" className="col-sm-offset-1 col-sm-10 well">
<form onSubmit={this.handleSubmit} noValidate className={this.state.displayErrors ? 'displayErrors' : ''} >
<h2 className="text-info">Edit Course</h2>
<div className="col-sm-4 col-xs-12">
<SingleSelect propertyName='venturingClass' propertyValue={classInfo.venturingClass} displayName='Venturing Class' options={venturingClassChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/>
</div>
<div className="col-sm-4 col-xs-12">
<SingleSelect propertyName='recommendedLength' propertyValue={classInfo.recommendedLength} displayName='Recommended Class Length' options={recommendedLengthChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/>
</div>
<div className="col-sm-4 col-xs-12">
<SingleSelect propertyName='recommendedSize' propertyValue={classInfo.recommendedSize} displayName='Recommended Number of Students' options={recommendedSizeChoices} errors={this.state.errorReport} changeHandler={this.handleChange}/>
</div>
<div className="clearfix"></div>
<div className="col-sm-8 col-xs-12">
<TextArea propertyName='notes' propertyValue={classInfo.notes} displayName='Notes' errors={this.state.errorReport} changeHandler={this.handleChange}/>
</div>
<div className="col-sm-4 col-xs-12">
<div className="row">
<div className="col-sm-12 col-xs-12">
<SimpleList propertyName='teachers' displayName='Venturer Instructors' dataList={classInfo.teachers}/>
</div>
</div>
<div className="row">
<div className="col-sm-3 col-xs-12">
<button type="button" className="btn btn-sm" disabled={teachingAlready} onClick={this.handleAddMe}>Add Me</button>
</div>
<div className="col-sm-3 col-xs-12">
<button type="button" className="btn btn-sm" onClick={this.handleRemoveMe}>Remove Me</button>
</div>
</div>
</div>
<div className="clearfix"></div>
<div style={{marginTop: '20px'}} className="col-sm-offset-4 col-sm-2 col-xs-12 pull-right">
<button type="submit" className="btn btn-success btn-lg btn-block">Save</button>
</div>
</form>
</div>
</div>
</div>
);
}
};
const mapStateToProps = ({course}) => {
return course;
};
export default withRouter(connect(mapStateToProps)(EditVenturerCourse)); |
src/index.js | JasonAForral/quiz-client-json-rpc-react | import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import App from './containers/App'
import reducer from './reducers'
import './index.css';
const middleware = [ thunk ]
if ('production' !== process.env.NODE_ENV) {
middleware.push(createLogger())
}
const store = createStore(
reducer,
applyMiddleware(...middleware)
)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
) |
packages/material-ui-icons/src/PanoramaVertical.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M19.94 21.12c-1.1-2.94-1.64-6.03-1.64-9.12 0-3.09.55-6.18 1.64-9.12.04-.11.06-.22.06-.31 0-.34-.23-.57-.63-.57H4.63c-.4 0-.63.23-.63.57 0 .1.02.2.06.31C5.16 5.82 5.71 8.91 5.71 12c0 3.09-.55 6.18-1.64 9.12-.05.11-.07.22-.07.31 0 .33.23.57.63.57h14.75c.39 0 .63-.24.63-.57-.01-.1-.03-.2-.07-.31zM6.54 20c.77-2.6 1.16-5.28 1.16-8 0-2.72-.39-5.4-1.16-8h10.91c-.77 2.6-1.16 5.28-1.16 8 0 2.72.39 5.4 1.16 8H6.54z" /></g>
, 'PanoramaVertical');
|
src/Main.js | connectordb/connectordb-android | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as Actions from './actions';
import { StatusBar, View } from 'react-native';
import FacebookTabBar from './components/FacebookTabBar';
import ErrorBar from './components/ErrorBar';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import Downlinks from './Downlinks';
import Inputs from './Inputs';
import Settings from './Settings';
const Main = ({state, actions}) => (
<View style={{ flex: 1 }}>
<StatusBar
backgroundColor="#009e42"
barStyle="light-content"
/>
<ScrollableTabView renderTabBar={() => <FacebookTabBar />} locked={true} >
<Inputs tabLabel="ios-star" />
<Downlinks tabLabel="ios-bulb" />
<Settings tabLabel="ios-settings" />
</ScrollableTabView>
<ErrorBar error={state.error} />
</View>
);
export default connect(
(state) => ({ state: state }),
(dispatch) => ({ actions: bindActionCreators(Actions, dispatch) })
)(Main); |
webpack/scenes/RedHatRepositories/components/RepositorySetRepositories.js | cfouant/katello | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Alert, Spinner } from 'patternfly-react';
import loadRepositorySetRepos from '../../../redux/actions/RedHatRepositories/repositorySetRepositories';
import RepositorySetRepository from './RepositorySetRepository/';
import { yStream } from './RepositorySetRepositoriesHelpers';
class RepositorySetRepositories extends Component {
componentDidMount() {
const { contentId, productId } = this.props;
if (this.props.data.loading) {
this.props.loadRepositorySetRepos(contentId, productId);
}
}
sortedRepos = repos => [...repos.filter(({ enabled }) => !enabled)]
.sort((repo1, repo2) => {
const repo1YStream = yStream(repo1.releasever || '');
const repo2YStream = yStream(repo2.releasever || '');
if (repo1YStream < repo2YStream) {
return -1;
}
if (repo2YStream < repo1YStream) {
return 1;
}
if (repo1.arch === repo2.arch) {
const repo1MajorMinor = repo1.releasever.split('.');
const repo2MajorMinor = repo2.releasever.split('.');
const repo1Major = parseInt(repo1MajorMinor[0], 10);
const repo2Major = parseInt(repo2MajorMinor[0], 10);
if (repo1Major === repo2Major) {
const repo1Minor = parseInt(repo1MajorMinor[1], 10);
const repo2Minor = parseInt(repo2MajorMinor[1], 10);
if (repo1Minor === repo2Minor) {
return 0;
} return (repo1Minor > repo2Minor) ? -1 : 1;
} return (repo1Major > repo2Major) ? -1 : 1;
} return (repo1.arch > repo2.arch) ? -1 : 1;
});
render() {
const { data, type } = this.props;
if (data.error) {
return (
<Alert type="danger">
<span>{data.error.displayMessage}</span>
</Alert>
);
}
const availableRepos = this.sortedRepos(data.repositories).map(repo => (
<RepositorySetRepository key={repo.arch + repo.releasever} type={type} {...repo} />
));
const repoMessage = (data.repositories.length > 0 && availableRepos.length === 0 ?
__('All available architectures for this repo are enabled.') : __('No repositories available.'));
return (
<Spinner loading={data.loading}>
{availableRepos.length ? availableRepos : <div>{repoMessage}</div>}
</Spinner>
);
}
}
RepositorySetRepositories.propTypes = {
loadRepositorySetRepos: PropTypes.func.isRequired,
contentId: PropTypes.number.isRequired,
productId: PropTypes.number.isRequired,
type: PropTypes.string,
data: PropTypes.shape({
loading: PropTypes.bool.isRequired,
repositories: PropTypes.arrayOf(PropTypes.object),
}).isRequired,
};
RepositorySetRepositories.defaultProps = {
type: '',
};
const mapStateToProps = (
{ katello: { redHatRepositories: { repositorySetRepositories } } },
props,
) => ({
data: repositorySetRepositories[props.contentId] || {
loading: true,
repositories: [],
error: null,
},
});
export default connect(mapStateToProps, {
loadRepositorySetRepos,
})(RepositorySetRepositories);
|
docs/app/Examples/addons/Radio/States/ReadOnly.js | jamiehill/stardust | import React from 'react'
import { Radio } from 'stardust'
const RadioReadOnlyExample = () => (
<Radio label='This radio is read-only' readOnly />
)
export default RadioReadOnlyExample
|
src/components/user/avatar-editor.js | Lokiedu/libertysoil-site | /*
This file is a part of libertysoil.org website
Copyright (C) 2016 Loki Education (Social Enterprise)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import PropTypes from 'prop-types';
import React from 'react';
import { User as UserPropType } from '../../prop-types/users';
import { AVATAR_SIZE } from '../../consts/profileConstants';
import UpdatePicture from '../update-picture/update-picture';
export default class AvatarEditor extends React.Component {
static displayName = 'AvatarEditor';
static propTypes = {
flexible: PropTypes.bool,
limits: PropTypes.shape({}),
onUpdateAvatar: PropTypes.func,
preview: PropTypes.shape({}),
user: UserPropType.isRequired
};
static defaultProps = {
flexible: false,
limits: {
min: AVATAR_SIZE
},
preview: AVATAR_SIZE,
onUpdateAvatar: () => {}
};
render() {
const {
user,
flexible,
limits,
preview,
onUpdateAvatar
} = this.props;
let modalName = <span className="font-bold">{user.get('username')}</span>;
if (user.getIn(['more', 'firstName']) || user.getIn(['more', 'lastName'])) {
modalName = [
<span className="font-bold" key="avatarEditorName">{user.getIn(['more', 'firstName'])} {user.getIn(['more', 'lastName'])}</span>,
` (${user.get('username')})`
];
}
return (
<UpdatePicture
flexible={flexible}
limits={limits}
preview={preview}
what="profile picture"
where={modalName}
onSubmit={onUpdateAvatar}
/>
);
}
}
|
src/main.js | luigiplr/area51-launcher | import React from 'react'
import ReactDOM from 'react-dom'
import Framework from './js/components/Framework.react'
import webUtil from './js/utils/webUtil'
webUtil.disableGlobalBackspace()
ReactDOM.render(<Framework />, document.getElementById('app')) |
src/components/mail/mailTags.js | EncontrAR/backoffice | import React from 'react';
const tags = [
'Friend',
'Family',
'Colleague',
'Teachers',
'Students',
'ClassMates',
];
const tagColor = [
'#CD3131',
'#74B49B',
'#0962EA',
'#141829',
'#FFCD38',
'#61105E',
];
function gettags(mails, filterAttr) {
const tags = {};
mails.forEach(mail => {
if (mail.tags && mail.bucket === filterAttr.bucket) {
mail.tags.split(' ').forEach(tag => tags[tag] = 1);
}
});
return tags;
}
export default function mailtags(
mails,
filterAction,
filterAttr,
onDrawerClose,
) {
const Tags = gettags(mails, filterAttr);
const renderSingleTag = (tag, key) => {
const onClick = () => {
filterAction({ tag });
if (onDrawerClose) {
onDrawerClose();
}
};
const selectedTag = tag === filterAttr.tag;
const activeClass = selectedTag ? 'active' : '';
const background = tagColor[tags.findIndex(tags => tags === tag)];
return (
<li
key={`tag${key}`}
onClick={onClick}
className={`isoMailTag ${activeClass}`}
>
<span className="isoLabelIndicatorColor" style={{ background }} />
<span>{tag}</span>
</li>
);
};
return (
<ul className="isoMailTagList">
<p className="isoSectionLabel">Label</p>
{Object.keys(Tags).map((tag, index) => renderSingleTag(tag, index))}
</ul>
);
}
export { tags, tagColor };
|
submissions/masiulis/src/components/components/components/sith-list-item.js | staltz/flux-challenge | import React from 'react';
export default class extends React.Component {
static propTypes = {
name: React.PropTypes.string,
homeworld: React.PropTypes.string,
obiPlanet: React.PropTypes.string,
}
render() {
const textColor = this.props.homeworld === this.props.obiPlanet ? 'red' : '';
return (
<li className="css-slot" style={{color: textColor}}>
<h3>{this.props.name}</h3>
<h6>{this.props.homeworld && `Homeworld: ${this.props.homeworld}`}</h6>
</li>
)
}
}
|
packages/bonde-admin/src/components/navigation/tabs/tab-border.js | ourcities/rebu-client | import PropTypes from 'prop-types'
import React from 'react'
import classnames from 'classnames'
if (require('exenv').canUseDOM) {
require('./tab-border.scss')
}
const TabBorder = ({ children, Component, path, className, isActive, style }) => {
const optionalProps = {}
if (path) optionalProps.to = path
return (
<Component
{...optionalProps}
className={classnames(
'tab components--tab-border',
{ 'is-active': isActive },
className
)}
style={style}
>
{children}
</Component>
)
}
TabBorder.propTypes = {
children: PropTypes.node.isRequired,
Component: PropTypes.node.isRequired,
className: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
path: PropTypes.string,
isActive: PropTypes.bool,
style: PropTypes.string
}
export default TabBorder
|
src/components/Elements/SocialIcons/index.js | jmikrut/keen-2017 | import React, { Component } from 'react';
import Facebook from '../../Icons/Facebook';
import LinkedIn from '../../Icons/LinkedIn';
import Dribbble from '../../Icons/Dribbble';
import Behance from '../../Icons/Behance';
import YouTube from '../../Icons/YouTube';
import Medium from '../../Icons/Medium';
import GitHub from '../../Icons/GitHub';
import './SocialIcons.css';
class SocialIcons extends Component {
render() {
const originalClasses = "social-icons";
const additionalClasses = this.props.className;
const classes = additionalClasses ? `${originalClasses} ${additionalClasses}` : originalClasses
return (
<ul className={classes}>
<li>
<a href="https://www.facebook.com/keen2015/" target="_blank" rel="noopener noreferrer">
<Facebook />
</a>
</li>
<li>
<a href="https://www.linkedin.com/company/10183058/" target="_blank" rel="noopener noreferrer">
<LinkedIn />
</a>
</li>
<li>
<a href="https://dribbble.com/keen_studio" target="_blank" rel="noopener noreferrer">
<Dribbble />
</a>
</li>
<li>
<a href="https://www.behance.net/keenstudio" target="_blank" rel="noopener noreferrer">
<Behance />
</a>
</li>
<li>
<a href="https://www.youtube.com/channel/UCOrm7cXv_flN9Hzah-5ucKg/videos" target="_blank" rel="noopener noreferrer">
<YouTube />
</a>
</li>
<li>
<a href="https://medium.com/keen-studio" target="_blank" rel="noopener noreferrer">
<Medium/>
</a>
</li>
<li>
<a href="https://github.com/keen-studio" target="_blank" rel="noopener noreferrer">
<GitHub/>
</a>
</li>
</ul>
);
}
}
export default SocialIcons;
|
packages/veritone-react-common/src/components/FilePicker/FileUploader/index.js | veritone/veritone-sdk | import React, { Component } from 'react';
import { noop, startsWith, endsWith } from 'lodash';
import cx from 'classnames';
import Button from '@material-ui/core/Button';
import { DropTarget } from 'react-dnd';
import { string, func, arrayOf, bool, shape, any } from 'prop-types';
import { withStyles } from '@material-ui/styles';
import { NativeTypes } from 'react-dnd-html5-backend';
const { FILE } = NativeTypes;
import ExtensionPanel from './ExtensionPanel';
import styles from './styles';
const boxTarget = {
drop(props, monitor) {
const droppedFiles = monitor.getItem().files;
const allowableDroppedFiles = droppedFiles.filter(({ type }) => {
// only accept dropped files of the correct type. This tries to duplicate
// the functionality of the html5 file input.
return (
props.acceptedFileTypes.includes(type) ||
props.acceptedFileTypes.some(acceptedType => {
// deal with video/*, audio/* etc
if (endsWith(acceptedType, '/*')) {
const typePrefix = acceptedType.match(/(.*)\/\*/)[1];
return startsWith(type, typePrefix);
}
return false;
})
);
});
if (props.acceptedFileTypes.length) {
if (allowableDroppedFiles.length) {
props.onFilesSelected(allowableDroppedFiles);
}
const numRejectedFiles =
droppedFiles.length - allowableDroppedFiles.length;
if (numRejectedFiles > 0) {
props.onFilesRejected(numRejectedFiles);
}
} else {
props.onFilesSelected(droppedFiles);
}
}
};
const collect = (connect, monitor) => {
return {
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver(),
canDrop: monitor.canDrop()
};
};
@DropTarget(FILE, boxTarget, collect)
@withStyles(styles)
class FileUploader extends Component {
static propTypes = {
acceptedFileTypes: arrayOf(string),
onFilesSelected: func.isRequired,
useFlatStyle: bool,
// eslint-disable-next-line react/no-unused-prop-types
onFilesRejected: func,
isOver: bool.isRequired,
connectDropTarget: func.isRequired,
multiple: bool,
classes: shape({ any }),
};
static defaultProps = {
acceptedFileTypes: [],
onFilesRejected: noop
};
state = {
showExtensionList: false
};
handleFileSelection = () => {
if (this._input.files.length > 0) {
this.props.onFilesSelected(Array.from(this._input.files));
}
this._input.value = null;
};
openExtensionList = () => {
this.setState({ showExtensionList: true });
};
closeExtensionList = () => {
this.setState({ showExtensionList: false });
};
setInputRef = r => (this._input = r);
render() {
const { acceptedFileTypes, connectDropTarget, isOver, classes } = this.props;
const { showExtensionList } = this.state;
const acceptMessage = 'Drag & Drop';
const subMessage = 'your file(s) here, or ';
return connectDropTarget(
<div className={cx([
classes.fileUploader,
{ [classes.flat]: this.props.useFlatStyle }
])}>
{showExtensionList ? (
<ExtensionPanel
acceptedFileTypes={acceptedFileTypes}
closeExtensionList={this.closeExtensionList} />
) : (
<div className={classes.uploaderContainer}>
{!!acceptedFileTypes.length && (
<span
className={classes.extensionListOpenButton}
data-veritone-element="uploader-extension-open-btn"
onClick={this.openExtensionList}>
Extension Types
</span>
)}
<span>
<i className={cx(classes.fileUploadIcon, 'icon-ingest')} />
</span>
<span className={classes.fileUploaderAcceptText}>{acceptMessage}</span>
<label htmlFor="file">
<Button
component="span"
disableFocusRipple
disableRipple>
<span className={classes.fileUploaderSubtext}>{subMessage}</span>
<span className={cx(classes.fileUploaderSubtext, classes.subtextBlue)}>browse</span>
</Button>
</label>
<input
accept={acceptedFileTypes.join(',')}
style={{ display: 'none' }}
id="file"
multiple={this.props.multiple}
type="file"
onChange={this.handleFileSelection}
ref={this.setInputRef}
/>
</div>
)}
{isOver && <div className={classes.uploaderOverlay} />}
</div>
);
}
}
export default FileUploader;
|
src/components/CodeForm.js | MattMcFarland/codepix-client | import React from 'react';
import ajax from 'superagent';
import Select from 'react-select';
import { Expander, Radio } from './partials/Elements';
import { ProtoFormClass, FormErrors } from './partials';
import { codeOptions } from './config';
export class CodeForm extends React.Component {
constructor() {
super();
var isOptionsExpanded = localStorage.getItem('isOptionsExpanded');
if (isOptionsExpanded && isOptionsExpanded === 'false') {
isOptionsExpanded = false;
}
this.state = { isOptionsExpanded,
visibility: localStorage.getItem('visibility') || 'public',
codeLang: localStorage.getItem('pform_codeLang') || 'auto',
textAreaValue: localStorage.getItem('pform_textAreaValue') || '',
titleValue: localStorage.getItem('pform_titleValue') || '',
descriptionValue: localStorage.getItem('pform_descriptionValue') || ''
};
}
clearLocalStorage = () => {
localStorage.removeItem('pform_textAreaValue');
localStorage.removeItem('pform_titleValue');
localStorage.removeItem('pform_descriptionValue');
}
clearState = () => {
this.setState({textAreaValue: ''});
}
handleTextAreaChange = (e) => {
let val = e.target.value;
this.setState({textAreaValue: val});
localStorage.setItem('pform_textAreaValue', val);
}
handleTitleChange = (e) => {
let val = e.target.value;
this.setState({titleValue: val});
localStorage.setItem('pform_titleValue', val);
}
handleDescriptionChange = (e) => {
let val = e.target.value;
this.setState({descriptionValue: val});
localStorage.setItem('pform_descriptionValue', val);
}
handleVisibilityChange = (e) => {
this.setState({visibility: e.currentTarget.value});
localStorage.setItem('visibility', e.currentTarget.value);
}
handleCodeStyleChange = (value) => {
this.setState({codeLang: value});
localStorage.setItem('pform_codeLang', value);
}
handleToggleOptions = () => {
let newSetting = !this.state.isOptionsExpanded;
localStorage.setItem('isOptionsExpanded', newSetting);
this.setState({isOptionsExpanded: newSetting});
}
componentWillMount() {
window.ga('send', 'pageview', window.location.pathname);
}
validate = () => {
var errors = [];
var { textAreaValue, codeLang } = this.state;
const rules = [
{
failOn: textAreaValue.trim().length < 10,
error: 'Please use at least 10 characters.'
},
{
failOn: codeLang === '',
error: 'Please select a language.'
}
];
rules.forEach((rule) => {
if (rule.failOn) {
errors.push(rule);
}
});
if (errors.length) {
return {
errors: errors,
valid: false
};
} else {
return {
errors: null,
valid: true
};
}
}
handleSubmit = (e) => {
e.preventDefault();
let val = this.state.textAreaValue.trim();
this.setState({textAreaValue: val});
localStorage.setItem('pform_textAreaValue', val);
var valid = this.validate();
if (valid.errors) {
let article = valid.errors.length > 1 ? 'are' : 'is';
let noun = valid.errors.length > 1 ? 'errors' : 'error';
let count = valid.errors.length > 1 ? valid.errors.length : 'one';
this.setState({
error: {
message: `There ${article} ${count} ${noun}, please try again.`,
data: valid.errors
}
});
return;
}
{ /* Ajax Post */
ajax.post('/api/add')
.send({
title: this.state.titleValue,
content: this.state.descriptionValue,
language: this.state.codeLang,
visibility: this.state.visibility,
code: this.state.textAreaValue
})
.set('Content-Type', 'application/json')
.set('Accept', 'application/json')
.set('X-no-legacy')
.end((err, res) => {
if (!err) {
this.clearLocalStorage();
this.clearState();
this.props.history.pushState(null, '/code/' + res.body.shasum);
}
});
}
}
render() {
// handlers
let {
handleSubmit,
handleTextAreaChange,
handleToggleOptions,
handleVisibilityChange,
handleCodeStyleChange,
handleTitleChange,
handleDescriptionChange
} = this;
// state
let {
codeLang,
isOptionsExpanded,
error,
textAreaValue,
titleValue,
descriptionValue,
visibility
} = this.state;
return (
<section>
{error ? <FormErrors {...error} /> : ''}
<ProtoFormClass onSubmit={handleSubmit}>
<textarea
placeholder="Put some code in here to convert to an image."
value = {textAreaValue}
onChange = {handleTextAreaChange} />
<div style={{ marginTop: '-15px',
marginLeft: '-10px',
marginBottom: '10px'}}>
<Expander
isExpanded={isOptionsExpanded}
onToggle={handleToggleOptions}
title="Options">
<hr/>
<div style={{marginLeft: '15px'}}>
<fieldset className="form-group">
<label style={{display: 'block'}}>Language:
<Select
name="codestyle"
value={codeLang}
options={codeOptions}
onChange={handleCodeStyleChange}/>
</label>
</fieldset>
<fieldset className="form-group">
<Radio name="visibility" value="public"
set={visibility} onChange={handleVisibilityChange}>
Public
</Radio>
<Radio disabled name="visibility" value="private"
set={visibility} onChange={handleVisibilityChange}>
Private (soon)
</Radio>
</fieldset>
<fieldset className="form-group">
<label style={{display: 'block'}}>Title:
<input
type="text"
value={titleValue}
onChange={handleTitleChange}
className="form-control"/>
</label>
</fieldset>
<fieldset className="form-group">
<label style={{display: 'block'}}>Description:
<textarea
value={descriptionValue}
onChange={handleDescriptionChange}
className="form-control"/>
</label>
</fieldset>
</div>
</Expander>
</div>
</ProtoFormClass>
</section>
);
}
}
|
src/components/Timetable/TimetableBackground.js | momomods/momomods | import React from 'react';
import _ from 'lodash';
import classnames from 'classnames';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { CELLS_COUNT } from '../../utils/timetable';
import s from './timetable.scss';
// Ref: https://github.com/yangshun/nusmods-v3/tree/master/src/js
const TimetableBackground = () => (
<div className={classnames('timetable', 'timetable-bg')}>
<div className={classnames('timetable-day')}>
<div className={classnames('timetable-day-row')}>
<div className={classnames('timetable-day-cell', 'timetable-d')}><span /></div>
{_.map(_.range(CELLS_COUNT), (i) =>
(
<div
key={i} className={classnames('timetable-cell', {
'timetable-cell-alt': i % 4 < 2,
})}
/>
)
)}
</div>
</div>
</div>
);
export default withStyles(s)(TimetableBackground);
|
src/card.js | joxoo/react-material | import React from 'react';
import { getClassesStatic } from './addons/get-classes';
const Card = (props) => (
<div className={ getClassesStatic('card', props) }>
{ props.children }
</div>
);
export default Card;
|
src/components/common/svg-icons/notification/airline-seat-legroom-normal.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationAirlineSeatLegroomNormal = (props) => (
<SvgIcon {...props}>
<path d="M5 12V3H3v9c0 2.76 2.24 5 5 5h6v-2H8c-1.66 0-3-1.34-3-3zm15.5 6H19v-7c0-1.1-.9-2-2-2h-5V3H6v8c0 1.65 1.35 3 3 3h7v7h4.5c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5z"/>
</SvgIcon>
);
NotificationAirlineSeatLegroomNormal = pure(NotificationAirlineSeatLegroomNormal);
NotificationAirlineSeatLegroomNormal.displayName = 'NotificationAirlineSeatLegroomNormal';
NotificationAirlineSeatLegroomNormal.muiName = 'SvgIcon';
export default NotificationAirlineSeatLegroomNormal;
|
src/handleReactRouter.js | nheyn/express-react-router | /**
* @flow
*/
import React from 'react';
import { Router } from 'react-router';
import ReactDOMServer from 'react-dom/server';
import express from 'express';
import { match, RouterContext } from 'react-router';
import getReactRouterRoute from './router-traversal/getReactRouterRoute';
import getExpressRouter from './router-traversal/getExpressRouter';
import wasMadeUsing from './router-traversal/wasMadeUsing';
import addPropsToRouter from './addPropsToRouter';
import type { $Request as Request, Router as ExpressRouter } from 'express';
type ReactRouter = React.Element<*>;
type PropArg = Object | (req: Request) => Object;
/**
* Create an express router for the given react-router routes.
*
* @param routes {ReactRouter} The router to render
* @param PageComponent {ReactClass} A class that takes the render html string, reactHtml, and a
* express request, req, as a prop and returns markup for the
* entire page.
* NOTE: This is render using 'renderToStaticMarkdown(...)' with
* '<!DOCTYPE html>' placed before it.
* @param ...propArgs {Array<Object | Func>} All arguments after routes is used to add props to the top-level
* components in the router
*
* @return {ExpressRouter} The express router to add to the express application
*/
export default function handleReactRouter(
routes: ReactRouter,
//ERROR, aperently React.Component<*, *, *> is not a component: "Expected React component instead of React$Component"
PageComponent: any,
...propArgs: Array<PropArg>
): ExpressRouter {
// Check args route
if(!routes) throw new Error('Route is required for the server');
if(!PageComponent) throw new Error('PageComponent is required for the server');
// Combine props
const getAllProps = (req) => {
let currProps = {};
propArgs.forEach((nextProps) => {
const newProps = typeof nextProps === 'function'? nextProps(req): nextProps;
currProps = { ...currProps, ...newProps };
});
return currProps;
};
// Parse Routes
const reactRouterRoutes = getReactRouterRoute(routes);
const expressRouterFromRoute = getExpressRouter(routes);
// Create express router
let router = express.Router();
//$FlowFixMe
router.use(expressRouterFromRoute);
// $FlowFixMe
router.use((req, res, next) => {
// Skip wrapper components (like react-redux Provider)
const { routes, rewrapRouter } = unwrapRouter(reactRouterRoutes);
// Render current route
match({ routes, location: req.url }, (err, redirectLocation, renderProps) => {
if(err) {
// Handle errors below
next(err);
}
else if(redirectLocation) {
// Handle redirect
res.redirect(302, redirectLocation.pathname + redirectLocation.search)
}
else if(renderProps) {
let routerContextElement = <RouterContext {...renderProps} />;
// Add props
if(propArgs.length) routerContextElement = addPropsToRouter(routerContextElement, getAllProps(req));
// Render page with current element from router
const renderedReactHtml = ReactDOMServer.renderToString(rewrapRouter(routerContextElement));
const pageHtml = ReactDOMServer.renderToStaticMarkup(
//TODO, rewrap router agian because match(...) is a horibly written function
<PageComponent req={req} reactHtml={renderedReactHtml} />
);
// Send entire page to client
res
.status(isPageNotFoundRoutes(renderProps.routes)? 404: 200)
.send(`<!DOCTYPE html> ${pageHtml}`);
}
else {
// Render page with error
const pageHtml = ReactDOMServer.renderToStaticMarkup(
<PageComponent req={req} error={new Error(`Invalid url: ${req.url}`)} is404 />
);
// Send entire page to client
res
.status(404)
.send(`<!DOCTYPE html> ${pageHtml}`);
}
});
});
// $FlowFixMe
router.use((err, req, res, next) => {
// Skip this middleware if the request doesn't not accept html
if(!req.accepts('html')) {
next(err);
return;
}
// Render page with error
const pageHtml = ReactDOMServer.renderToStaticMarkup(
<PageComponent req={req} error={err} />
);
// Send entire page to client
res
.status(500)
.send(`<!DOCTYPE html> ${pageHtml}`);
});
return router;
}
function isPageNotFoundRoutes(routes: Array<any>): bool {
const currRoutes = routes[routes.length - 1];
if(!currRoutes.path) return false;
// Check if last char is wild chard, NOTE: means any wildcard (non-404) pages must use params
const lastCharInPath = currRoutes.path.charAt(currRoutes.path.length-1);
return lastCharInPath === '*';
}
function unwrapRouter(
el: React.Element<*>,
rewrapRouter?: (el: React.Element<*>) => React.Element<*>,
): { routes: React.Element<*>, rewrapRouter: (el: React.Element<*>) => React.Element<*> } {
if(wasMadeUsing(el, Router)) {
return {
routes: el,
rewrapRouter(currEl) {
return rewrapRouter? rewrapRouter(currEl): currEl;
},
};
}
if(React.Children.count(el.props.children) !== 1) throw new Error('Must be given a single root Router.');
const child = React.Children.only(el.props.children);
return unwrapRouter(
child,
(childEl) => {
const wrappedEl = React.cloneElement(el, null, childEl);
return rewrapRouter? rewrapRouter(wrappedEl): wrappedEl;
},
);
}
|
src/core/markers/PolylineMarker.js | mocheer/react-map | import React from 'react';
export const PolylineMarker = React.createClass({
render: function () {
var state = this.state;
return null;
}
}); |
app/containers/LanguageProvider/index.js | fenderface66/spotify-smart-playlists | /*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { makeSelectLocale } from './selectors';
export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: React.PropTypes.string,
messages: React.PropTypes.object,
children: React.PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
(locale) => ({ locale })
);
export default connect(mapStateToProps)(LanguageProvider);
|
src/index.js | tomorrowshine/cra-app | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import leaveWord from './containers/leaveWord';
import list from './containers/list/list';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux'
import store from './store';
import { Router, Route,Switch } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import history from './component/History'
syncHistoryWithStore(history, store)//时光之旅
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Switch>
<Route exact path='/' component={App}/>
<Route path='/leaveWord' component={leaveWord}/>
<Route path='/list' component={list}/>
</Switch>
</Router>
</Provider>, document.getElementById('root'));
registerServiceWorker(); |
src/components/Dock/Dock.js | bibleexchange/be-front-new | import React from 'react';
import {
createFragmentContainer,
graphql,
} from 'react-relay/compat';
import { Link } from 'react-router';
import Loading from '../ListWidget/Loading'
//import SoundCloudPlayer from './SoundCloudPlayer'
import NoteEditor from '../NoteEditor/NoteEditorWidget'
import './Dock.scss';
import NoteOptions from '../Note/NoteOptions';
import NotesWidget from '../Note/NotesWidget';
import MagnifyingGlass from '../Svg/MagnifyingGlass';
import Bookmark from '../Bookmark/BookmarkComponent';
class Search extends React.Component {
render() {
let that = 'p';
return (
<form id='main-search' onSubmit={this.props.searchIt} >
<input id='search-text' type='text' name='search' placeholder='search notes...' onChange={this.props.handleUpdateSearch} />
<button onClick={this.props.searchIt}>
<MagnifyingGlass />
</button>
</form>
);
}
}
class Dock extends React.Component {
componentWillMount() {
this.state = {
filterBy: this.props.notesWidget.filter
};
}
render() {
let status = this.props.status
let playStatus = null
let notepadButton = null
let notepadMain = null
let audioButton = null
let verseButton = null
let verseMain= null
let audioMain = null
let shareMain = null
let shareButton = null
if (this.props.user.authenticated){
notepadButton = <li className={"menu-"+ status.notepad}><button onClick={this.props.showInDockMenu} data-name="notepad">notepad</button></li>
notepadMain = <li id="notepad" className={"main-"+ status.notepad}> <NoteEditor myNotesWidget={this.props.myNotesWidget} handleUpdateMyNoteFilter={this.props.handleUpdateMyNoteFilter} handleUpdateNote={this.props.handleUpdateNote} moreNotes={this.props.moreMyNotes} user={this.props.user} note={this.props.note} notes={this.props.myNotes} handleEditThis={this.props.handleEditThisNote}/> </li>
}else{
notepadButton = null
notepadMain = null
}
if(this.props.player.playStatus === true){
playStatus = '(!)'
}
if(this.props.player === undefined || this.props.player === null || this.props.player.playStatus === false){
audioButton = null
audioMain = null
}else{
audioButton = <li id="audio-player" className={"menu-"+ status.soundcloud}><button onClick={this.props.showInDockMenu} data-name="soundcloud">audio {playStatus}</button></li>
//audioMain = <li id="soundcloud" className={"main-"+ status.soundcloud}><SoundCloudPlayer id={this.props.player.currentSoundId} status={this.props.player.playStatus} handleCloseAudio={this.props.handleCloseAudio}/></li>
}
if(this.props.bibleVerse === undefined || this.props.bibleVerse === null || this.props.bibleVerse.reference === null){
verseButton = null
verseMain = null
}else{
verseButton = <li id="verse" className={"menu-"+ status.verse}><button onClick={this.props.showInDockMenu} data-name="verse">{this.props.crossReferences.edges.length} related verses ({this.props.bibleVerse.reference})</button></li>
verseMain = <li id="verse" className={"main-"+ status.verse}>{this.renderVerse()}</li>
}
shareButton = <li id="share" className={"menu-"+ status.share}><button onClick={this.props.showInDockMenu} data-name="share">share</button></li>
shareMain = <li id="share" className={"main-"+ status.share}> <NoteOptions note={this.props.note} user={this.props.user} editThisNote={this.props.handleEditThisNote} location={this.props.location}/></li>
let notesButton = <li id="notes" className={"menu-"+ status.notes}><button onClick={this.props.showInDockMenu} data-name="notes">{this.props.notesWidget.filter} ({this.props.notes.totalCount} notes)</button></li>
let notesMain = <li id="notes" className={"main-"+ status.notes}>{this.renderNotes()}</li>
return (
<div id='dock-widget'>
<div id="dock-main">
<nav id="dock-menu">
<ul>
{audioButton}
{notepadButton}
{shareButton}
{verseButton}
{notesButton}
</ul>
</nav>
<ul className="main">
{shareMain}
{audioMain}
{notepadMain}
{verseMain}
{notesMain}
</ul>
</div>
</div>
);
}
renderNotes(){
return (<NotesWidget
status={this.props.notesWidget}
notes={this.props.notes}
selectNote={this.props.handleEditThisNote}
handleUpdateNoteFilter={this.props.handleUpdateNoteFilter}
handleNextNotePage={this.props.handleNextNotePage}
handleNotesAreReady={this.props.handleNotesAreReady}
user={this.props.user}
/>)
}
renderVerse(){
let cr = []
if(this.props.crossReferences !== undefined && this.props.crossReferences.edges !== undefined){
cr = this.props.crossReferences.edges
}
return ( <span>
<p>
<strong> {this.props.reference} cross references: </strong>
{cr.map(function(c){
let verses = ''
c.node.verses.edges.map(function(v){
verses += v.node.order_by + " " + v.node.body + " "
})
return <Link key={c.node.id} to={c.node.url} title={verses} >| {c.node.reference} </Link>;
})}
</p>
</span>)
}
}
Dock.propTypes = {
user: React.PropTypes.object.isRequired,
note: React.PropTypes.object,
notes: React.PropTypes.object.isRequired,
relay: React.PropTypes.object.isRequired
};
Dock.contextTypes = {
router: React.PropTypes.object.isRequired
};
export default createFragmentContainer(Dock, {
note: ()=> Relay.QL`fragment on Note {
...NoteEditor_note
...NoteOptions_note
id
title
type
body
tags_string
verse{
id
reference
}
}`,
user: graphql`
fragment Dock_user on User {
...NoteOptions_user
...NotesWidget_user
authenticated
name
email
...NoteEditor_user
}
`,
bibleVerse: () => Relay.QL`fragment on BibleVerse {
id
reference
notesCount
}`,
crossReferences: () => Relay.QL`fragment on CrossReferenceConnection {
pageInfo{hasNextPage}
edges{
node {
id
url
reference
verses(first:50){
edges{
node{
id
order_by
body
}
}
}
}
}
}`,
notes: graphql`
fragment Dock_notes on NoteConnection {
...NotesWidget_notes
pageInfo{hasNextPage}
totalCount
totalPagesCount
currentPage
edges{
node {
id
title
verse {id, reference}
}
}
}`,
});
|
examples/cra/src/components/RandomButton.js | styleguidist/react-styleguidist | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import sample from 'lodash/sample';
import './RandomButton.css';
/**
* Button that changes label on every click.
*/
export default class RandomButton extends Component {
static propTypes = {
/**
* List of possible labels.
*/
variants: PropTypes.array.isRequired,
};
constructor(props) {
super();
this.state = {
label: sample(props.variants),
};
}
handleClick = () => {
this.setState({
label: sample(this.props.variants),
});
};
render() {
return (
<button className="random-button" onClick={this.handleClick}>
{this.state.label}
</button>
);
}
}
|
src/containers/App/index.js | hasibsahibzada/quran.com-frontend | /* eslint-disable react/prefer-stateless-function */
import React, { Component } from 'react';
import * as customPropTypes from 'customPropTypes';
import { metrics } from 'react-metrics';
import { connect } from 'react-redux';
import { asyncConnect } from 'redux-connect';
import Helmet from 'react-helmet';
import Modal from 'react-bootstrap/lib/Modal';
import Loadable from 'react-loadable';
import ComponentLoader from 'components/ComponentLoader';
import debug from 'helpers/debug';
import config from 'config';
import metricsConfig from 'helpers/metrics';
import Footer from 'components/Footer';
import NoScript from 'components/NoScript';
import PropTypes from 'prop-types';
import { removeMedia } from 'redux/actions/media';
import Loader from 'quran-components/lib/Loader';
import authConnect from './connect';
const ModalHeader = Modal.Header;
const ModalTitle = Modal.Title;
const ModalBody = Modal.Body;
const GlobalNav = Loadable({
loader: () =>
import(/* webpackChunkName: "globalnav" */ 'components/GlobalNav'),
LoadingComponent: ComponentLoader
});
const GlobalSidebar = Loadable({
loader: () =>
import(/* webpackChunkName: "globalsidebar" */ 'components/GlobalSidebar'),
LoadingComponent: ComponentLoader
});
const SmartBanner = Loadable({
loader: () =>
import(/* webpackChunkName: "smartbanner" */ 'components/SmartBanner'),
LoadingComponent: ComponentLoader
});
class App extends Component {
static contextTypes = {
store: PropTypes.object.isRequired
};
state = {
sidebarOpen: false
};
renderModalBody() {
const { media } = this.props;
if (media.loading) {
return (
<div className="embed-responsive embed-responsive-16by9">
<Loader isActive relative />
</div>
);
}
return (
<div
className={`embed-responsive embed-responsive-16by9 ${media.wrapperClass}`}
dangerouslySetInnerHTML={{ __html: media.content.body }}
/>
);
}
render() {
const {
main,
nav,
footer,
children,
media,
removeMedia, // eslint-disable-line no-shadow
...props
} = this.props;
debug('component:APPLICATION', 'Render');
return (
<div>
<Helmet {...config.app.head} />
<NoScript>
<div className="row noscript-warning">
<div className="col-md-12">
<p>
Looks like either your browser does not support Javascript or its disabled.
Quran.com workes best with JavaScript enabled.
For more instruction on how to enable javascript
<a href="http://www.enable-javascript.com/">
Click here
</a>
</p>
</div>
</div>
</NoScript>
{React.cloneElement(nav || <GlobalNav isStatic {...props} />, {
handleSidebarToggle: () =>
this.setState({ sidebarOpen: !this.state.sidebarOpen })
})}
{__CLIENT__ &&
<GlobalSidebar
open={this.state.sidebarOpen}
handleOpen={open => this.setState({ sidebarOpen: open })}
/>}
{children || main}
<SmartBanner title="The Noble Quran - القرآن الكريم" button="Install" />
{footer || <Footer />}
{__CLIENT__ &&
media.show &&
<Modal bsSize={media.size} show={media.show} onHide={removeMedia}>
<ModalHeader closeButton>
<ModalTitle className="montserrat">
{media.content.title}
</ModalTitle>
</ModalHeader>
<ModalBody>
{this.renderModalBody()}
</ModalBody>
</Modal>}
</div>
);
}
}
const metricsApp = metrics(metricsConfig)(App);
const AsyncApp = asyncConnect([{ promise: authConnect }])(metricsApp);
App.propTypes = {
media: customPropTypes.media.isRequired,
removeMedia: PropTypes.func.isRequired,
children: PropTypes.element,
main: PropTypes.element,
nav: PropTypes.element,
footer: PropTypes.element,
sidebar: PropTypes.element,
footNote: customPropTypes.footNoteType,
loadingFootNote: PropTypes.bool
};
export default connect(
state => ({
media: state.media
}),
{ removeMedia }
)(AsyncApp);
|
ui/js/dfv/src/fields/pick/checkbox-select.js | pods-framework/pods | import React from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import { PICK_OPTIONS } from 'dfv/src/config/prop-types';
import './checkbox-select.scss';
const CheckboxSelect = ( {
htmlAttributes,
name,
value,
options = [],
setValue,
isMulti,
readOnly = false,
} ) => {
const toggleValueOption = ( option ) => {
if ( value.some( ( valueItem ) => valueItem.toString() === option.toString() ) ) {
setValue(
value.filter( ( item ) => item.toString() !== option.toString() )
);
} else {
setValue( [ ...value, option ] );
}
};
const totalOptions = options.length;
return (
<ul
className={
classnames(
'pods-checkbox-pick',
options.length === 1 && 'pods-checkbox-pick--single'
)
}
id={ name }
>
{ options.map( (
{
id: optionValue,
name: optionLabel,
},
optionIndex,
allOptions
) => {
const nameBase = htmlAttributes.name || name;
const nameAttribute = allOptions.length > 1
? `${ nameBase }[${ optionIndex }]`
: nameBase;
let idAttribute = !! htmlAttributes.id ? htmlAttributes.id : `pods-form-ui-${ name }`;
if ( 1 < totalOptions ) {
idAttribute += `-${ optionValue }`;
}
return (
<li
key={ optionValue }
className={
classnames(
'pods-checkbox-pick__option',
options.length === 1 && 'pods-checkbox-pick__option--single'
)
}
>
<div className="pods-field pods-boolean">
{ /* eslint-disable-next-line jsx-a11y/label-has-for */ }
<label
className="pods-form-ui-label pods-checkbox-pick__option__label"
>
<input
name={ nameAttribute }
id={ idAttribute }
checked={
isMulti
? value.some( ( valueItem ) => valueItem.toString() === optionValue.toString() )
: value.toString() === optionValue.toString()
}
className="pods-form-ui-field-type-pick"
type="checkbox"
value={ optionValue }
onChange={ () => {
if ( readOnly ) {
return;
}
if ( isMulti ) {
toggleValueOption( optionValue );
} else {
// Workaround for boolean fields:
const unsetValue = ( 1 === options.length && optionValue === '1' )
? '0'
: undefined;
setValue( value === optionValue ? unsetValue : optionValue );
}
} }
readOnly={ !! readOnly }
/>
{ optionLabel }
</label>
</div>
</li>
);
} ) }
</ul>
);
};
CheckboxSelect.propTypes = {
htmlAttributes: PropTypes.shape( {
id: PropTypes.string,
class: PropTypes.string,
name: PropTypes.string,
} ),
name: PropTypes.string.isRequired,
value: PropTypes.oneOfType( [
PropTypes.arrayOf(
PropTypes.oneOfType( [
PropTypes.string,
PropTypes.number,
] )
),
PropTypes.string,
PropTypes.number,
] ),
setValue: PropTypes.func.isRequired,
options: PICK_OPTIONS.isRequired,
isMulti: PropTypes.bool.isRequired,
readOnly: PropTypes.bool,
};
export default CheckboxSelect;
|
src/Calendar.js | Hanse/react-calendar | import React, { Component } from 'react';
import moment from 'moment';
import PropTypes from 'prop-types';
import cx from 'classnames';
import createDateObjects from './createDateObjects';
export default class Calendar extends Component {
static propTypes = {
/** Week offset*/
weekOffset: PropTypes.number.isRequired,
/** The current date as a moment objecct */
date: PropTypes.object.isRequired,
/** Function to render a day cell */
renderDay: PropTypes.func,
/** Function to render the header */
renderHeader: PropTypes.func,
/** Called on next month click */
onNextMonth: PropTypes.func,
/** Called on prev month click */
onPrevMonth: PropTypes.func,
/** Called when some of the navigation controls are clicked */
onChangeMonth: PropTypes.func,
/** Called when a date is clicked */
onPickDate: PropTypes.func,
/** classname for div wrapping the whole calendar */
containerClassName: PropTypes.string,
/** classname for the div wrapping the grid */
contentClassName: PropTypes.string
};
static defaultProps = {
weekOffset: 0,
renderDay: ({ day, classNames, onPickDate }) => (
<div
key={day.format()}
className={cx(
'Calendar-grid-item',
day.isSame(moment(), 'day') && 'Calendar-grid-item--current',
classNames
)}
onClick={e => onPickDate(day)}
>
{day.format('D')}
</div>
),
renderHeader: ({ date, onPrevMonth, onNextMonth }) => (
<div className="Calendar-header">
<button onClick={onPrevMonth}>«</button>
<div className="Calendar-header-currentDate">
{date.format('MMMM YYYY')}
</div>
<button onClick={onNextMonth}>»</button>
</div>
)
};
handleNextMonth = () => {
if (this.props.onNextMonth) {
return this.props.onNextMonth();
}
this.props.onChangeMonth(this.props.date.clone().add(1, 'months'));
};
handlePrevMonth = () => {
if (this.props.onPrevMonth) {
return this.props.onPrevMonth();
}
this.props.onChangeMonth(this.props.date.clone().subtract(1, 'months'));
};
render() {
const {
date,
weekOffset,
renderDay,
renderHeader,
onPickDate,
contentClassName,
containerClassName
} = this.props;
return (
<div className={cx('Calendar', containerClassName)}>
{renderHeader({
date,
onPrevMonth: this.handlePrevMonth,
onNextMonth: this.handleNextMonth
})}
<div className={cx('Calendar-grid', contentClassName)}>
{createDateObjects(date, weekOffset).map((day, i) =>
renderDay({ ...day, onPickDate })
)}
</div>
</div>
);
}
}
|
src/components/Auth/PrivateRoute.js | dovydasvenckus/time-tracker-web | import React from 'react';
import PropTypes from 'prop-types';
import { Route } from 'react-router-dom';
import { AuthConsumer } from '../../utils/auth/authProvider';
const PrivateRoute = ({ component, ...rest }) => {
const renderFn = (Component) => (props) => (
<AuthConsumer>
{({ isAuthenticated, signInRedirect }) => {
if (!!Component && isAuthenticated()) {
return <Component {...props} />;
}
signInRedirect();
return <span>loading</span>;
}}
</AuthConsumer>
);
return <Route {...rest} render={renderFn(component)} />;
};
PrivateRoute.propTypes = {
component: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
};
export default PrivateRoute;
|
src/todo/input.js | corgisamurai/spary_react | import React from 'react'
import { Component } from 'react'
class TodoInput extends Component {
_onAddToDo(){
var newTodo = this.refs.todo.value.trim();
this.props.onAddToDo(newTodo);
this.refs.todo.value="";
}
_getOnsen(){
axios.post('/api/onsen/list')
.then(function (res) {
console.log(res.data);
});
}
render () {
return (
<div>
<input type="text" ref="todo" />
<input type="button" value="submit" onClick={this._onAddToDo.bind(this)} />
<input type="button" value="温泉を取得" onClick={this._getOnsen.bind(this)} />
</div>
)
}
}
export default TodoInput
|
src/components/Main.js | jerwu/graduationProject | require('normalize.css/normalize.css');
require('styles/App.scss');
import React from 'react';
import ReactDOM from 'react-dom';
//获取图片相关的数据
var imageDatas = require('../data/imageDatas.json');
//利用自执行函数,将图片名信息转成图片URL路径信息
imageDatas=(function genImageURL(imageDatasArr){
for(var i = 0,j = imageDatas.length;i < j;i++){
var singleImageData=imageDatasArr[i];
singleImageData.imageURL=require('../images/'+singleImageData.fileName);
imageDatasArr[i]=singleImageData;
}
return imageDatasArr;
})(imageDatas);
//获取区间的一个随机值
function getRangeRandom(low,high){
return Math.ceil(Math.random() * (high - low) + low);
}
//获取0~30度的旋转角度值
function get30DegRandom(){
return ((Math.random() > 0.5 ? '' : '') + Math.ceil(Math.random() * 30));
}
class ImgFigureComponent extends React.Component{
//聚焦到该图片所对应的位置
focus(){
var map = new BMap.Map(this.props.data.id);
// map.centerAndZoom(new BMap.Point(this.props.data.geoPos[0],this.props.data.geoPos[1]), 15);
var lng = this.props.data.geoPos[0];
var lat = this.props.data.geoPos[1];
var point = new BMap.Point(lng, lat);
map.centerAndZoom(point, 13);
//设置点的弹跳动画
var marker = new BMap.Marker(point); // 创建标注
map.addOverlay(marker); // 将标注添加到地图中
marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
//缩放地图
setTimeout(function(){
map.setZoom(15);
}, 2000);
map.enableScrollWheelZoom(true);//允许缩放地图
// map.disableDragging();//禁止拖拽
}
//mapClick
mapClick = (ev) => {
ev.preventDefault();
ev.stopPropagation();
}
//imgFigure的点击处理函数
handleClick = (ev) => {
if (this.props.arrange.isCenter) {
this.props.inverse();
this.focus();
}else{
this.props.center();
}
ev.preventDefault();
ev.stopPropagation();
}
shareBtnClick = (ev) => {
ev.preventDefault();
ev.stopPropagation();
}
render(){
let styleObj = {};
//如果props属性中指定了这张图片的位置,则使用
if (this.props.arrange.pos) {
styleObj = this.props.arrange.pos;
}
//如何图片有软砖角度且不为0,添加旋转角度
if (this.props.arrange.rotate) {
(['MozTransform','msTransform','WebkitTransform','transform']).forEach((value => {
styleObj[value] = 'rotate('+this.props.arrange.rotate + 'deg)';
}).bind(this));
}
//把中心图片的zindex设成11
if (this.props.arrange.isCenter) {
styleObj.zIndex = 11;
}
let imgFigureClassName = 'img-figure';
imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : '';
return (
<figure className={imgFigureClassName}
style={styleObj}
onClick={this.handleClick}
>
<img src={this.props.data.imageURL}
alt={this.props.data.title}/>
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
<div className="img-back" onClick={this.handleClick}>
<div className="bd-map" id={this.props.data.id} onClick={this.mapClick} >
</div>
</div>
</figcaption>
</figure>
);
}
}
// <div className="shareBlock">
// <button type="button">分享到微博</button>
// </div>
//添加控制组件coomponent
class ControllerUnitComponent extends React.Component{
// 写法有问题:会提示报错cannot read property 'props' of null 在95行
//原因:还不知道?????
// handleClick(ev){
// //如果点击的是当前正在选中态的图片,则翻转图片,否则将对应的图片居中
// if (this.props.arrange.isCenter) {
// this.props.inverse();
// }else{
// this.props.center();
// }
// ev.preventDefault();
// ev.stopPropagation();
// }
handleClick = (ev) => {
//如果点击的是当前正在选中态的图片,则翻转图片,否则将对应的图片居中
if (this.props.arrange.isCenter) {
this.props.inverse();
}else{
this.props.center();
}
ev.preventDefault();
ev.stopPropagation();
}
render(){
let controllerUnitClassName = 'controller-unit';
//如果对应的是居中图片,显示控制按钮的居中态
if (this.props.arrange.isCenter) {
controllerUnitClassName += ' is-center';
if (this.props.arrange.isInverse) {
controllerUnitClassName += ' is-inverse';
}
}
return(
<span className={controllerUnitClassName}
onClick={this.handleClick}
/>
);
}
}
class AppComponent extends React.Component {
//因为react版本太高,要使用支持es6语法把下面属性定义到app类的构造函数中
// Constant:{
// centerPos:{
// left:0,
// top:0
// },
// hPosRange:{ //水平方向的取值范围(左右分区)
// leftSecX:[0,0],
// rightSecX:[0,0],
// y:[0,0]
// },
// vPosRange:{ //垂直方向上的取值范围(上分区)
// x:[0,0],
// topY:[0,0]
// }
// };
//闭包this问题
center(index){
return (() =>{this.reArrange(index)}).bind(this);
}
// getInitialState(){
// return {
// imgsArrangeArr:[
// {
// pos:{
// left:'0',
// top:'0'
// },
// rotate: 0, //图片旋转
// isInverse: false //图片翻转
// isCenter:false
// }
// ]
// }
// }
//因为getInitialState不支持es6 classes
constructor(props){
super(props);
this.state = {
imgsArrangeArr:[
{
pos:{
left:'0',
top:'0'
},
rotate: 0,
isInverse: false,
isCenter: false
}
]
};
this.Constant = {
centerPos:{
left:0,
top:0
},
hPosRange:{ //水平方向的取值范围(左右分区)
leftSecX:[0,0],
rightSecX:[0,0],
y:[0,0]
},
vPosRange:{ //垂直方向上的取值范围(上分区)
x:[0,0],
topY:[0,0]
}
};
// this.inverse = function (){
// return function (){
// var imgsArrangeArr = this.state.imgsArrangeArr;
// imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;
// this.setState({
// imgsArrangeArr:imgsArrangeArr
// });
// }.bind(this)
// }
}
/*
*翻转图片
*@params index 输出当前被执行inverse操作的图片在对应的图片信息数组中的index值
*@return {function} 返回一个闭包函数,其内return一个真正待被执行的函数
*?????:搞清楚为什么使用闭包(图片翻转课程05;55)
*/
//闭包this问题:说return is not defined;
inverse(index){
return ((()=>{
var imgsArrangeArr = this.state.imgsArrangeArr;
imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;
this.setState({
imgsArrangeArr:imgsArrangeArr
});
}).bind(this));
}
//重新布局所有图片,
//@params centerIndex 指定居中排布哪个图片
reArrange(centerIndex){
var imgsArrangeArr = this.state.imgsArrangeArr,
Constant = this.Constant,
centerPos = Constant.centerPos,
hPosRange = Constant.hPosRange,
vPosRange = Constant.vPosRange,
hPosRangeLeftSecX = hPosRange.leftSecX,
hPosRangeRightSecX = hPosRange.rightSecX,
hPosRangeY = hPosRange.y,
vPosRangeX = vPosRange.x,
vPosRangeTopY = vPosRange.topY,
imgsArrangeTopArr = [],
topImgNum = Math.floor(Math.random() * 2), //取1个或者不取
topImgSpliceIndex = 0,
imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1);
//首先居中 centerIndex 的图片,centerIndex 的图片不用旋转
imgsArrangeCenterArr[0] = {
pos:centerPos,
rotate:0,
isCenter:true
}
//取出要布局上侧图片的状态信息???????
topImgSpliceIndex = Math.ceil(Math.random() *(imgsArrangeArr.length - topImgNum));
imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex,topImgNum);
//布局位于上侧的图片
imgsArrangeTopArr.forEach(function(value,index){
imgsArrangeTopArr[index]={
pos:{
left:getRangeRandom(vPosRangeX[0],vPosRangeX[1]),
top:getRangeRandom(vPosRangeTopY[0],vPosRangeTopY[1])
},
rotate:get30DegRandom(),
isCenter:false
};
});
//布局左右两侧的图片
for(var i = 0, j = imgsArrangeArr.length, k = j / 2;i < j;i++){
var hPosRangeLORX = null;
//前半部分布局左边,后半部分布局右边
if (i < k) {
hPosRangeLORX = hPosRangeLeftSecX;
}else{
hPosRangeLORX = hPosRangeRightSecX;
}
imgsArrangeArr[i] = {
pos:{
left:getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1]),
top:getRangeRandom(hPosRangeY[0],hPosRangeY[1])
},
rotate:get30DegRandom(),
isCenter:false
};
}
if (imgsArrangeTopArr && imgsArrangeTopArr[0]){
imgsArrangeArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]);
}
imgsArrangeArr.splice(centerIndex,0,imgsArrangeCenterArr[0]);
this.setState({
imgsArrangeArr:imgsArrangeArr
});
}
//组件加载之后,为每张图片计算其位置的范围
componentDidMount(){
//首先拿到舞台的大小
let stageDOM = ReactDOM.findDOMNode(this.refs.stage),
stageW =stageDOM.scrollWidth,
stageH = stageDOM.scrollHeight,
halfStageW = Math.ceil(stageW / 2),
halfStageH = Math.ceil(stageH / 2);
//拿到imgFigure的大小
let imgFigureDom = ReactDOM.findDOMNode(this.refs.imgFigure0),
imgW = imgFigureDom.scrollWidth,
imgH = imgFigureDom.scrollHeight,
halfImgW = Math.ceil(imgW / 2),
halfImgH = Math.ceil(imgH / 2);
//计算中心图片的位置点
this.Constant.centerPos={
left:halfStageW - halfImgW,
top:halfStageH - halfImgH
};
//计算左右分区图片排布位置的取值范围
this.Constant.hPosRange.leftSecX[0] = -halfImgW;
this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
this.Constant.hPosRange.y[0] = -halfImgH;
this.Constant.hPosRange.y[0] = stageH - halfImgH;
//计算上分区图片排布位置的取值范围
this.Constant.vPosRange.x[0] = halfStageW - imgW;
this.Constant.vPosRange.x[1] = halfStageW;
this.Constant.vPosRange.topY[0] = -halfImgH;
this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
this.reArrange(0);
}
render() {
let controllerUnits = [],
imgFigures=[];
imageDatas.forEach(((value,index) => {
if(!this.state.imgsArrangeArr[index]){
this.state.imgsArrangeArr[index] = {
pos:{
left:'0',
top:'0'
},
rotate: 0,
isInverse: false,
isCenter: false
}
}
//在遍历或者循环输出去渲染子组件的时候,key必不可少
imgFigures.push(<ImgFigureComponent key={index}
index={index}
data={value}
ref={'imgFigure'+index}
arrange={this.state.imgsArrangeArr[index]}
inverse={this.inverse(index)}
center={this.center(index)}
/>);
controllerUnits.push(<ControllerUnitComponent key={index}
arrange={this.state.imgsArrangeArr[index]}
inverse={this.inverse(index)}
center={this.center(index)}
/>);
}).bind(this));
// imageDatas.forEach(function(value,index){
// if(!this.state.imgsArrangeArr[index]){
// this.state.imgsArrangeArr[index] = {
// pos:{
// left:'0',
// top:'0'
// }
// };
// }
// imgFigures.push(<ImgFigure data={value} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]}/>)
// }.bind(this));
return (
<section className="stage" ref="stage">
<section className="img-sec">
{imgFigures}
</section>
<nav className="controller-nav">
{controllerUnits}
</nav>
</section>
);
}
}
AppComponent.defaultProps = {
};
export default AppComponent;
|
client/src/app/routes/graphs/containers/ChartJs.js | zraees/sms-project | import React from 'react'
import request from 'then-request'
import {Stats, BigBreadcrumbs, WidgetGrid, JarvisWidget} from '../../../components'
import ChartJsGraph from '../../../components/graphs/chartjs/ChartJsGraph'
export default class ChartJs extends React.Component {
state = {};
componentWillMount() {
request('GET', 'assets/api/graphs/chartjs.json', {json: true}).done((res)=> {
this.setState(JSON.parse(res.getBody()));
})
}
render() {
return (
<div id="content">
<div className="row">
<BigBreadcrumbs items={['ChartJs']} icon="fa fa-fw fa-bar-chart-o" className="col-xs-12 col-sm-7 col-md-7 col-lg-4"/>
<Stats />
</div>
<WidgetGrid>
<div className="row">
<article className="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<JarvisWidget editbutton={false}>
<header>
<span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span>
<h2>Line Chart</h2>
</header>
<div>
<div className="widget-body">
<ChartJsGraph type="line" data={this.state['line-chart']}/>
</div>
</div>
</JarvisWidget>
<JarvisWidget editbutton={false}>
<header>
<span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span>
<h2>Radar Chart</h2>
</header>
<div>
<div className="widget-body">
<ChartJsGraph type="radar" data={this.state['radar-chart']}/>
</div>
</div>
</JarvisWidget>
<JarvisWidget editbutton={false}>
<header>
<span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span>
<h2>Polar Chart</h2>
</header>
<div>
<div className="widget-body">
<ChartJsGraph type="polarArea" data={this.state['polar-chart']}/>
</div>
</div>
</JarvisWidget>
</article>
<article className="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<JarvisWidget editbutton={false}>
<header>
<span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span>
<h2>Bar Chart</h2>
</header>
<div>
<div className="widget-body">
<ChartJsGraph type="bar" data={this.state['bar-chart']}/>
</div>
</div>
</JarvisWidget>
<JarvisWidget editbutton={false}>
<header>
<span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span>
<h2>Doughnut Chart</h2>
</header>
<div>
<div className="widget-body">
<ChartJsGraph type="doughnut" data={this.state['doughnut-chart']}/>
</div>
</div>
</JarvisWidget>
<JarvisWidget editbutton={false}>
<header>
<span className="widget-icon"> <i className="fa fa-bar-chart-o"/> </span>
<h2>Pie Chart</h2>
</header>
<div>
<div className="widget-body">
<ChartJsGraph type="pie" data={this.state['pie-chart']}/>
</div>
</div>
</JarvisWidget>
</article>
</div>
</WidgetGrid>
</div>
)
}
} |
samples/react-redux-patient-demographics-example/src/routes/Patient/Demographics/PatientDemographicsComponent.js | GoTeamEpsilon/angular-to-react-redux | import React from 'react'
import { browserHistory } from 'react-router'
import Basic from './Basic/BasicComponent'
import Contact from './Contact/ContactComponent'
class PatientDemographics extends React.Component {
constructor() {
super()
this.TABS = {
BASIC: 'basic',
CONTACTS: 'contacts'
}
this.state = {
tab: this.TABS.BASIC,
isLoading: false
}
}
setPatientInContext() {
this.setState({ isLoading: true })
this.props.setPatientInContext(this.props.routeParams.pid)
.then(() => {
this.setState({ isLoading: false })
});
}
addNewContact() {
this.props.startAddingNewContact(this.props.routeParams.pid)
}
determineIfRouteIsValid() {
return this.props.routeParams.pid
}
componentDidMount() {
if (!this.determineIfRouteIsValid()) {
browserHistory.push('/patient/1337')
location.reload()
} else {
this.setPatientInContext()
}
}
mockedTab() {
alert('This tab is just here for completeness. The real tabs are basic and contacts')
}
changeTab(newTab) {
console.debug(`Setting tab to ${newTab}`)
this.setState({ tab: newTab })
}
render() {
let children = null
let addContactVisibility = 'hidden'
switch (this.state.tab) {
case this.TABS.BASIC:
children = <Basic basic={this.props.basic}
updatePatientData={this.props.updatePatientData} />
break;
case this.TABS.CONTACTS:
if (this.props.contacts) {
children = this.props.contacts.map((contact) => {
return <Contact updateContactData={this.props.updateContactData}
deleteContact={this.props.deleteContact}
key={contact.id}
contact={contact}/>
}
)
}
addContactVisibility = 'visible'
break;
}
return (
<div>
<h3 className={this.state.isLoading ? '' : 'hidden'}>Loading...</h3>
<div className={this.state.isLoading ? 'hidden' : ''}>
<div>
<ul className='nav nav-tabs'>
<li className={this.state.tab === this.TABS.BASIC ? 'active' : ''}>
<a onClick={() => this.changeTab(this.TABS.BASIC)}>Basic</a>
</li>
<li className={this.state.tab === this.TABS.CONTACTS ? 'active' : ''}>
<a onClick={() => this.changeTab(this.TABS.CONTACTS)}>Contacts</a>
</li>
<li><a onClick={this.mockedTab}>Choices</a></li>
<li><a onClick={this.mockedTab}>Employer</a></li>
<li><a onClick={this.mockedTab}>Stats</a></li>
<li><a onClick={this.mockedTab}>Misc</a></li>
</ul>
</div>
{children}
<br />
<button type='button'
className={['btn', 'btn-default', 'btn-sm', addContactVisibility].join(' ')}
onClick={this.addNewContact.bind(this)}>ADD NEW CONTACT</button>
</div>
</div>
)
}
}
export default PatientDemographics
|
fields/types/color/ColorColumn.js | webteckie/keystone | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var ColorColumn = React.createClass({
displayName: 'ColorColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value) return null;
const colorBoxStyle = {
backgroundColor: value,
borderRadius: 3,
display: 'inline-block',
height: 18,
marginRight: 10,
verticalAlign: 'middle',
width: 18,
};
return (
<ItemsTableValue truncate={false} field={this.props.col.type}>
<div style={{ lineHeight: '18px' }}>
<span style={colorBoxStyle} />
<span style={{ display: 'inline-block', verticalAlign: 'middle' }}>{value}</span>
</div>
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
},
});
module.exports = ColorColumn;
|
app/javascript/mastodon/components/icon_button.js | ashfurrow/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from 'mastodon/components/icon';
import AnimatedNumber from 'mastodon/components/animated_number';
export default class IconButton extends React.PureComponent {
static propTypes = {
className: PropTypes.string,
title: PropTypes.string.isRequired,
icon: PropTypes.string.isRequired,
onClick: PropTypes.func,
onMouseDown: PropTypes.func,
onKeyDown: PropTypes.func,
onKeyPress: PropTypes.func,
size: PropTypes.number,
active: PropTypes.bool,
pressed: PropTypes.bool,
expanded: PropTypes.bool,
style: PropTypes.object,
activeStyle: PropTypes.object,
disabled: PropTypes.bool,
inverted: PropTypes.bool,
animate: PropTypes.bool,
overlay: PropTypes.bool,
tabIndex: PropTypes.string,
counter: PropTypes.number,
obfuscateCount: PropTypes.bool,
href: PropTypes.string,
};
static defaultProps = {
size: 18,
active: false,
disabled: false,
animate: false,
overlay: false,
tabIndex: '0',
};
state = {
activate: false,
deactivate: false,
}
componentWillReceiveProps (nextProps) {
if (!nextProps.animate) return;
if (this.props.active && !nextProps.active) {
this.setState({ activate: false, deactivate: true });
} else if (!this.props.active && nextProps.active) {
this.setState({ activate: true, deactivate: false });
}
}
handleClick = (e) => {
e.preventDefault();
if (!this.props.disabled) {
this.props.onClick(e);
}
}
handleKeyPress = (e) => {
if (this.props.onKeyPress && !this.props.disabled) {
this.props.onKeyPress(e);
}
}
handleMouseDown = (e) => {
if (!this.props.disabled && this.props.onMouseDown) {
this.props.onMouseDown(e);
}
}
handleKeyDown = (e) => {
if (!this.props.disabled && this.props.onKeyDown) {
this.props.onKeyDown(e);
}
}
render () {
const style = {
fontSize: `${this.props.size}px`,
width: `${this.props.size * 1.28571429}px`,
height: `${this.props.size * 1.28571429}px`,
lineHeight: `${this.props.size}px`,
...this.props.style,
...(this.props.active ? this.props.activeStyle : {}),
};
const {
active,
className,
disabled,
expanded,
icon,
inverted,
overlay,
pressed,
tabIndex,
title,
counter,
obfuscateCount,
href,
} = this.props;
const {
activate,
deactivate,
} = this.state;
const classes = classNames(className, 'icon-button', {
active,
disabled,
inverted,
activate,
deactivate,
overlayed: overlay,
'icon-button--with-counter': typeof counter !== 'undefined',
});
if (typeof counter !== 'undefined') {
style.width = 'auto';
}
let contents = (
<React.Fragment>
<Icon id={icon} fixedWidth aria-hidden='true' /> {typeof counter !== 'undefined' && <span className='icon-button__counter'><AnimatedNumber value={counter} obfuscate={obfuscateCount} /></span>}
</React.Fragment>
);
if (href) {
contents = (
<a href={href} target='_blank' rel='noopener noreferrer'>
{contents}
</a>
);
}
return (
<button
aria-label={title}
aria-pressed={pressed}
aria-expanded={expanded}
title={title}
className={classes}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
onKeyDown={this.handleKeyDown}
onKeyPress={this.handleKeyPress}
style={style}
tabIndex={tabIndex}
disabled={disabled}
>
{contents}
</button>
);
}
}
|
packages/@lyra/google-maps-input/src/GeopointInput.js | VegaPublish/vega-studio | import PropTypes from 'prop-types'
import React from 'react'
import config from 'config:@lyra/google-maps-input'
import Button from 'part:@lyra/components/buttons/default'
import Dialog from 'part:@lyra/components/dialogs/default'
import Fieldset from 'part:@lyra/components/fieldsets/default'
import {
PatchEvent,
set,
setIfMissing,
unset
} from 'part:@lyra/form-builder/patch-event'
import styles from '../styles/GeopointInput.css'
import GeopointSelect from './GeopointSelect'
import GoogleMapsLoadProxy from './GoogleMapsLoadProxy'
const getLocale = context => {
const intl = context.intl || {}
return (
intl.locale ||
(typeof window !== 'undefined' && window.navigator.language) ||
'en'
)
}
const getStaticImageUrl = value => {
const loc = `${value.lat},${value.lng}`
const params = {
key: config.apiKey,
center: loc,
markers: loc,
zoom: 13,
scale: 2,
size: '640x300'
}
const qs = Object.keys(params).reduce((res, param) => {
return res.concat(`${param}=${encodeURIComponent(params[param])}`)
}, [])
return `https://maps.googleapis.com/maps/api/staticmap?${qs.join('&')}`
}
class GeopointInput extends React.Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
markers: PropTypes.arrayOf(
PropTypes.shape({
type: PropTypes.string
})
),
value: PropTypes.shape({
lat: PropTypes.number,
lng: PropTypes.number
}),
type: PropTypes.shape({
title: PropTypes.string.isRequired,
description: PropTypes.string
})
}
static defaultProps = {
markers: []
}
static contextTypes = {
intl: PropTypes.shape({
locale: PropTypes.string
})
}
constructor() {
super()
this.handleToggleModal = this.handleToggleModal.bind(this)
this.handleCloseModal = this.handleCloseModal.bind(this)
this.state = {
modalOpen: false
}
}
handleToggleModal() {
this.setState(prevState => ({modalOpen: !prevState.modalOpen}))
}
handleChange = latLng => {
const {type, onChange} = this.props
onChange(
PatchEvent.from([
setIfMissing({
_type: type.name
}),
set(latLng.lat(), ['lat']),
set(latLng.lng(), ['lng'])
])
)
}
handleClear = () => {
const {onChange} = this.props
onChange(PatchEvent.from(unset()))
}
handleCloseModal() {
this.setState({modalOpen: false})
}
render() {
const {value, type, markers} = this.props
if (!config || !config.apiKey) {
return (
<div>
<p>
The{' '}
<a href="https://vegapublish.com/docs/schema-types/geopoint-type">
Geopoint type
</a>{' '}
needs a Google Maps API key with access to:
</p>
<ul>
<li>Google Maps JavaScript API</li>
<li>Google Places API Web Service</li>
<li>Google Static Maps API</li>
</ul>
<p>
Please enter the API key with access to these services in
<code style={{whitespace: 'nowrap'}}>
`<project-root>/config/@lyra/google-maps-input.json`
</code>
</p>
</div>
)
}
return (
<Fieldset
legend={type.title}
description={type.description}
className={styles.root}
markers={markers}
>
{value && (
<div>
<img
className={styles.previewImage}
src={getStaticImageUrl(value)}
/>
</div>
)}
<div className={styles.functions}>
<Button onClick={this.handleToggleModal}>
{value ? 'Edit' : 'Set location'}
</Button>
{value && (
<Button type="button" onClick={this.handleClear}>
Remove
</Button>
)}
</div>
{this.state.modalOpen && (
<Dialog
title="Place on map"
onClose={this.handleCloseModal}
onCloseClick={this.handleCloseModal}
onOpen={this.handleOpenModal}
message="Select location by dragging the marker or search for a place"
isOpen={this.state.modalOpen}
>
<div className={styles.dialogInner}>
<GoogleMapsLoadProxy
value={value}
apiKey={config.apiKey}
onChange={this.handleChange}
defaultLocation={config.defaultLocation}
defaultZoom={config.defaultZoom}
locale={getLocale(this.context)}
component={GeopointSelect}
/>
</div>
</Dialog>
)}
</Fieldset>
)
}
}
export default GeopointInput
|
src/components/Header/index.js | jefflau/jefflau.net | import React from 'react'
import Link from 'gatsby-link'
const Header = ({ pages }) =>
<header className="site-header">
<h1 className="logo">
<Link
to="/"
style={{
color: 'white',
textDecoration: 'none',
}}
>
Jeff Lau
</Link>
</h1>
<ul>
{pages.map(({node: page}) =>
<li key={page.id}><Link to={page.frontmatter.slug}>{page.frontmatter.title}</Link></li>
)}
<li key="mentorship"><Link to="/mentorship">Mentorship</Link></li>
</ul>
</header>
export default Header |
client/components/users/email-enrollment-form.js | ShannChiang/meteor-react-redux-base | import React from 'react';
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {uiState: 'INIT'};
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(e) {
e.preventDefault();
this.setState({uiState: 'SENDING'});
this.props.enrollWithEmail(this._input.value, (err) => {
if (err) {
console.log(err);
this.setState({uiState: 'FAIL'});
} else {
this.setState({uiState: 'SUCCESS'});
}
});
}
render() {
if (this.state.uiState === 'SENDING') return <div>正在发送邮件...</div>;
if (this.state.uiState === 'SUCCESS') return <div>邮件已发送,请查看您的邮箱</div>;
return (
<div className="row">
<div className="col-sm-12">
{this.state.uiState === 'FAIL' && <p>邮件发送失败,请重试</p>}
<p>请填写登录用的邮箱地址,我们将发送一个链接到你邮箱,通过该链接设置登录密码</p>
<form onSubmit={this.onSubmit}>
<div className="input-group">
<input className="form-control" type="text" ref={(c) => this._input = c}/>
<span className="input-group-btn">
<button className="btn btn-default" type="submit">提交</button>
</span>
</div>
</form>
</div>
</div>
);
}
}
|
es/components/sidebar/panel-element-editor/attributes-editor/attributes-editor.js | dearkaran/react-planner | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ItemAttributesEditor from './item-attributes-editor';
import LineAttributesEditor from './line-attributes-editor';
import HoleAttributesEditor from './hole-attributes-editor';
export default function AttributesEditor(_ref) {
var element = _ref.element,
onUpdate = _ref.onUpdate,
attributeFormData = _ref.attributeFormData,
state = _ref.state;
switch (element.prototype) {
case 'items':
return React.createElement(ItemAttributesEditor, { element: element, onUpdate: onUpdate, attributeFormData: attributeFormData,
state: state });
case 'lines':
return React.createElement(LineAttributesEditor, { element: element, onUpdate: onUpdate, attributeFormData: attributeFormData,
state: state });
case 'holes':
return React.createElement(HoleAttributesEditor, { element: element, onUpdate: onUpdate, attributeFormData: attributeFormData,
state: state });
case 'areas':
return null;
}
return null;
}
AttributesEditor.propTypes = {
element: PropTypes.object.isRequired,
onUpdate: PropTypes.func.isRequired,
attributeFormData: PropTypes.object.isRequired,
state: PropTypes.object.isRequired
}; |
examples/todos-with-undo/src/index.js | heyesther/redux | import React from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import App from './components/App'
import reducer from './reducers'
const store = createStore(reducer)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
docs/src/components/Playground/Atoms/TextLink/TextLink.js | seekinternational/seek-asia-style-guide | import styles from './TextLink.less';
import React from 'react';
import PropTypes from 'prop-types';
import ChevronIcon from 'seek-asia-style-guide/react/ChevronIcon/ChevronIcon';
import classnames from 'classnames';
const renderChevron = chevron => {
if (!chevron) {
return null;
}
return (
<ChevronIcon
className={styles.chevron}
direction={chevron}
svgClassName={styles.chevronSvg}
/>
);
};
export default function TextLink({ component: Root, className, shouting, yelling, screaming, children, chevron, ...restProps }) {
const allProps = {
...restProps,
className: classnames(styles.link, {
[className]: className,
[styles.shouting]: shouting,
[styles.yelling]: yelling,
[styles.screaming]: screaming,
[styles.touchable]: !shouting && !yelling && !screaming
})
};
return (
<Root {...allProps}>
{children}
{renderChevron(chevron)}
</Root>
);
}
TextLink.displayName = 'TextLink';
TextLink.propTypes = {
component: PropTypes.any,
className: PropTypes.string,
children: PropTypes.node,
chevron: PropTypes.oneOf(['up', 'down', 'right', 'left']),
shouting: PropTypes.bool,
yelling: PropTypes.bool,
screaming: PropTypes.bool
};
TextLink.defaultProps = {
component: 'a'
};
|
app/javascript/mastodon/features/ui/index.js | amazedkoumei/mastodon | import classNames from 'classnames';
import React from 'react';
import { HotKeys } from 'react-hotkeys';
import { defineMessages, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { Redirect, withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import NotificationsContainer from './containers/notifications_container';
import LoadingBarContainer from './containers/loading_bar_container';
import TabsBar from './components/tabs_bar';
import ModalContainer from './containers/modal_container';
import { isMobile } from '../../is_mobile';
import { debounce } from 'lodash';
import { uploadCompose, resetCompose } from '../../actions/compose';
import { expandHomeTimeline } from '../../actions/timelines';
import { expandNotifications } from '../../actions/notifications';
import { fetchFilters } from '../../actions/filters';
import { clearHeight } from '../../actions/height_cache';
import { WrappedSwitch, WrappedRoute } from './util/react_router_helpers';
import UploadArea from './components/upload_area';
import ColumnsAreaContainer from './containers/columns_area_container';
import {
Compose,
Status,
GettingStarted,
KeyboardShortcuts,
PublicTimeline,
CommunityTimeline,
AccountTimeline,
AccountGallery,
HomeTimeline,
Followers,
Following,
Reblogs,
Favourites,
DirectTimeline,
HashtagTimeline,
Notifications,
FollowRequests,
GenericNotFound,
FavouritedStatuses,
ListTimeline,
Blocks,
DomainBlocks,
Mutes,
PinnedStatuses,
Lists,
} from './util/async-components';
import { me } from '../../initial_state';
import { previewState } from './components/media_modal';
// Dummy import, to make sure that <Status /> ends up in the application bundle.
// Without this it ends up in ~8 very commonly used bundles.
import '../../components/status';
const messages = defineMessages({
beforeUnload: { id: 'ui.beforeunload', defaultMessage: 'Your draft will be lost if you leave Mastodon.' },
});
const mapStateToProps = state => ({
isComposing: state.getIn(['compose', 'is_composing']),
hasComposingText: state.getIn(['compose', 'text']) !== '',
dropdownMenuIsOpen: state.getIn(['dropdown_menu', 'openId']) !== null,
});
const keyMap = {
help: '?',
new: 'n',
search: 's',
forceNew: 'option+n',
focusColumn: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
reply: 'r',
favourite: 'f',
boost: 'b',
mention: 'm',
open: ['enter', 'o'],
openProfile: 'p',
moveDown: ['down', 'j'],
moveUp: ['up', 'k'],
back: 'backspace',
goToHome: 'g h',
goToNotifications: 'g n',
goToLocal: 'g l',
goToFederated: 'g t',
goToDirect: 'g d',
goToStart: 'g s',
goToFavourites: 'g f',
goToPinned: 'g p',
goToProfile: 'g u',
goToBlocked: 'g b',
goToMuted: 'g m',
goToRequests: 'g r',
toggleHidden: 'x',
};
class SwitchingColumnsArea extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
location: PropTypes.object,
onLayoutChange: PropTypes.func.isRequired,
};
state = {
mobile: isMobile(window.innerWidth),
};
componentWillMount () {
window.addEventListener('resize', this.handleResize, { passive: true });
}
componentDidUpdate (prevProps) {
if (![this.props.location.pathname, '/'].includes(prevProps.location.pathname)) {
this.node.handleChildrenContentChange();
}
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
}
shouldUpdateScroll (_, { location }) {
return location.state !== previewState;
}
handleResize = debounce(() => {
// The cached heights are no longer accurate, invalidate
this.props.onLayoutChange();
this.setState({ mobile: isMobile(window.innerWidth) });
}, 500, {
trailing: true,
});
setRef = c => {
this.node = c.getWrappedInstance().getWrappedInstance();
}
render () {
const { children } = this.props;
const { mobile } = this.state;
const redirect = mobile ? <Redirect from='/' to='/timelines/home' exact /> : <Redirect from='/' to='/getting-started' exact />;
return (
<ColumnsAreaContainer ref={this.setRef} singleColumn={mobile}>
<WrappedSwitch>
{redirect}
<WrappedRoute path='/getting-started' component={GettingStarted} content={children} />
<WrappedRoute path='/keyboard-shortcuts' component={KeyboardShortcuts} content={children} />
<WrappedRoute path='/timelines/home' component={HomeTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/timelines/public' exact component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/timelines/public/media' component={PublicTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} />
<WrappedRoute path='/timelines/public/local' exact component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/timelines/public/local/media' component={CommunityTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, onlyMedia: true }} />
<WrappedRoute path='/timelines/direct' component={DirectTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/timelines/tag/:id' component={HashtagTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/timelines/list/:id' component={ListTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/notifications' component={Notifications} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/favourites' component={FavouritedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/pinned' component={PinnedStatuses} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/search' component={Compose} content={children} componentParams={{ isSearchPage: true }} />
<WrappedRoute path='/statuses/new' component={Compose} content={children} />
<WrappedRoute path='/statuses/:statusId' exact component={Status} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/statuses/:statusId/reblogs' component={Reblogs} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/statuses/:statusId/favourites' component={Favourites} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/accounts/:accountId' exact component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/accounts/:accountId/with_replies' component={AccountTimeline} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll, withReplies: true }} />
<WrappedRoute path='/accounts/:accountId/followers' component={Followers} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/accounts/:accountId/following' component={Following} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/accounts/:accountId/media' component={AccountGallery} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/follow_requests' component={FollowRequests} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/blocks' component={Blocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/domain_blocks' component={DomainBlocks} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/mutes' component={Mutes} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute path='/lists' component={Lists} content={children} componentParams={{ shouldUpdateScroll: this.shouldUpdateScroll }} />
<WrappedRoute component={GenericNotFound} content={children} />
</WrappedSwitch>
</ColumnsAreaContainer>
);
}
}
@connect(mapStateToProps)
@injectIntl
@withRouter
export default class UI extends React.PureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
children: PropTypes.node,
isComposing: PropTypes.bool,
hasComposingText: PropTypes.bool,
location: PropTypes.object,
intl: PropTypes.object.isRequired,
dropdownMenuIsOpen: PropTypes.bool,
};
state = {
draggingOver: false,
};
handleBeforeUnload = (e) => {
const { intl, isComposing, hasComposingText } = this.props;
if (isComposing && hasComposingText) {
// Setting returnValue to any string causes confirmation dialog.
// Many browsers no longer display this text to users,
// but we set user-friendly message for other browsers, e.g. Edge.
e.returnValue = intl.formatMessage(messages.beforeUnload);
}
}
handleLayoutChange = () => {
// The cached heights are no longer accurate, invalidate
this.props.dispatch(clearHeight());
}
handleDragEnter = (e) => {
e.preventDefault();
if (!this.dragTargets) {
this.dragTargets = [];
}
if (this.dragTargets.indexOf(e.target) === -1) {
this.dragTargets.push(e.target);
}
if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files')) {
this.setState({ draggingOver: true });
}
}
handleDragOver = (e) => {
e.preventDefault();
e.stopPropagation();
try {
e.dataTransfer.dropEffect = 'copy';
} catch (err) {
}
return false;
}
handleDrop = (e) => {
e.preventDefault();
this.setState({ draggingOver: false });
if (e.dataTransfer && e.dataTransfer.files.length === 1) {
this.props.dispatch(uploadCompose(e.dataTransfer.files));
}
}
handleDragLeave = (e) => {
e.preventDefault();
e.stopPropagation();
this.dragTargets = this.dragTargets.filter(el => el !== e.target && this.node.contains(el));
if (this.dragTargets.length > 0) {
return;
}
this.setState({ draggingOver: false });
}
closeUploadModal = () => {
this.setState({ draggingOver: false });
}
handleServiceWorkerPostMessage = ({ data }) => {
if (data.type === 'navigate') {
this.context.router.history.push(data.path);
} else {
console.warn('Unknown message type:', data.type);
}
}
componentWillMount () {
window.addEventListener('beforeunload', this.handleBeforeUnload, false);
document.addEventListener('dragenter', this.handleDragEnter, false);
document.addEventListener('dragover', this.handleDragOver, false);
document.addEventListener('drop', this.handleDrop, false);
document.addEventListener('dragleave', this.handleDragLeave, false);
document.addEventListener('dragend', this.handleDragEnd, false);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.addEventListener('message', this.handleServiceWorkerPostMessage);
}
this.props.dispatch(expandHomeTimeline());
this.props.dispatch(expandNotifications());
setTimeout(() => this.props.dispatch(fetchFilters()), 500);
}
componentDidMount () {
this.hotkeys.__mousetrap__.stopCallback = (e, element) => {
return ['TEXTAREA', 'SELECT', 'INPUT'].includes(element.tagName);
};
}
componentWillUnmount () {
window.removeEventListener('beforeunload', this.handleBeforeUnload);
document.removeEventListener('dragenter', this.handleDragEnter);
document.removeEventListener('dragover', this.handleDragOver);
document.removeEventListener('drop', this.handleDrop);
document.removeEventListener('dragleave', this.handleDragLeave);
document.removeEventListener('dragend', this.handleDragEnd);
}
setRef = c => {
this.node = c;
}
handleHotkeyNew = e => {
e.preventDefault();
const element = this.node.querySelector('.compose-form__autosuggest-wrapper textarea');
if (element) {
element.focus();
}
}
handleHotkeySearch = e => {
e.preventDefault();
const element = this.node.querySelector('.search__input');
if (element) {
element.focus();
}
}
handleHotkeyForceNew = e => {
this.handleHotkeyNew(e);
this.props.dispatch(resetCompose());
}
handleHotkeyFocusColumn = e => {
const index = (e.key * 1) + 1; // First child is drawer, skip that
const column = this.node.querySelector(`.column:nth-child(${index})`);
if (column) {
const status = column.querySelector('.focusable');
if (status) {
status.focus();
}
}
}
handleHotkeyBack = () => {
if (window.history && window.history.length === 1) {
this.context.router.history.push('/');
} else {
this.context.router.history.goBack();
}
}
setHotkeysRef = c => {
this.hotkeys = c;
}
handleHotkeyToggleHelp = () => {
if (this.props.location.pathname === '/keyboard-shortcuts') {
this.context.router.history.goBack();
} else {
this.context.router.history.push('/keyboard-shortcuts');
}
}
handleHotkeyGoToHome = () => {
this.context.router.history.push('/timelines/home');
}
handleHotkeyGoToNotifications = () => {
this.context.router.history.push('/notifications');
}
handleHotkeyGoToLocal = () => {
this.context.router.history.push('/timelines/public/local');
}
handleHotkeyGoToFederated = () => {
this.context.router.history.push('/timelines/public');
}
handleHotkeyGoToDirect = () => {
this.context.router.history.push('/timelines/direct');
}
handleHotkeyGoToStart = () => {
this.context.router.history.push('/getting-started');
}
handleHotkeyGoToFavourites = () => {
this.context.router.history.push('/favourites');
}
handleHotkeyGoToPinned = () => {
this.context.router.history.push('/pinned');
}
handleHotkeyGoToProfile = () => {
this.context.router.history.push(`/accounts/${me}`);
}
handleHotkeyGoToBlocked = () => {
this.context.router.history.push('/blocks');
}
handleHotkeyGoToMuted = () => {
this.context.router.history.push('/mutes');
}
handleHotkeyGoToRequests = () => {
this.context.router.history.push('/follow_requests');
}
render () {
const { draggingOver } = this.state;
const { children, isComposing, location, dropdownMenuIsOpen } = this.props;
const handlers = {
help: this.handleHotkeyToggleHelp,
new: this.handleHotkeyNew,
search: this.handleHotkeySearch,
forceNew: this.handleHotkeyForceNew,
focusColumn: this.handleHotkeyFocusColumn,
back: this.handleHotkeyBack,
goToHome: this.handleHotkeyGoToHome,
goToNotifications: this.handleHotkeyGoToNotifications,
goToLocal: this.handleHotkeyGoToLocal,
goToFederated: this.handleHotkeyGoToFederated,
goToDirect: this.handleHotkeyGoToDirect,
goToStart: this.handleHotkeyGoToStart,
goToFavourites: this.handleHotkeyGoToFavourites,
goToPinned: this.handleHotkeyGoToPinned,
goToProfile: this.handleHotkeyGoToProfile,
goToBlocked: this.handleHotkeyGoToBlocked,
goToMuted: this.handleHotkeyGoToMuted,
goToRequests: this.handleHotkeyGoToRequests,
};
return (
<HotKeys keyMap={keyMap} handlers={handlers} ref={this.setHotkeysRef}>
<div className={classNames('ui', { 'is-composing': isComposing })} ref={this.setRef} style={{ pointerEvents: dropdownMenuIsOpen ? 'none' : null }}>
<TabsBar />
<SwitchingColumnsArea location={location} onLayoutChange={this.handleLayoutChange}>
{children}
</SwitchingColumnsArea>
<NotificationsContainer />
<LoadingBarContainer className='loading-bar' />
<ModalContainer />
<UploadArea active={draggingOver} onClose={this.closeUploadModal} />
</div>
</HotKeys>
);
}
}
|
generators/app/templates/app/assets/javascript/containers/home/index.js | ajaykumaryadav/react-bootstrap | import React, { Component } from 'react';
import { browserHistory } from 'react-router';
import Header from '../../components/shared/header'
class homeContainer extends Component {
render() {
return (
<section>
<Header />
{this.props.children}
<div className="container">
<hr/>
<footer>
<p>© 2016.</p>
</footer>
</div>
</section>
);
}
}
export default homeContainer;
|
src/components/ui/content/index.js | boxal/boxal | import React from 'react';
function Content({
children,
isVisible = true,
}) {
return (
<div style={style[isVisible]}>
{isVisible ? children : null}
</div>
);
}
const style = {
[true]: {},
[false]: {
display: 'none',
},
};
Content.propTypes = {
children: React.PropTypes.node,
isVisible: React.PropTypes.bool,
};
export default Content;
|
src/Tag.js | captainill/react-tag-select | /* eslint react/no-multi-comp: 0 */
import React, { Component } from 'react';
class Tag extends Component {
static propTypes = {
labelField: React.PropTypes.string,
onDelete: React.PropTypes.func.isRequired,
tag: React.PropTypes.object.isRequired,
removeComponent: React.PropTypes.func,
readOnly: React.PropTypes.bool
}
static defaultProps = {
labelField: 'text'
}
render() {
const label = this.props.tag[this.props.labelField];
const { readOnly } = this.props;
const CustomRemoveComponent = this.props.removeComponent;
class RemoveComponent extends Component {
render() {
if (readOnly) {
return <span/>;
}
if (CustomRemoveComponent) {
return <CustomRemoveComponent {...this.props} />;
}
return <a {...this.props}>x</a>;
}
}
return (
<span className="ReactTags-tag">
<RemoveComponent className="ReactTags-remove"
onClick={this.props.onDelete} />
<span className="ReactTags-label">{label}</span>
</span>
);
}
}
module.exports = Tag;
|
cm19/ReactJS/your-first-react-app-exercises-master/exercise-17/Header.js | Brandon-J-Campbell/codemash | import React from 'react';
import classNames from 'classnames';
// import theme from './theme/static';
import ThemeContext from './theme/context';
import ThemeSwitcher from './theme/Switcher';
import styles from './Header.css';
export default function Header() {
return (
<ThemeContext.Consumer>
{({ theme }) => (
<header className={classNames(styles.appHeader, styles[theme])}>
<h1 className={styles.appTitle}>Exercise 17</h1>
<h2 className={styles.subTitle}>Testing Component Render</h2>
<div className={styles.switcherWrapper}>
<ThemeSwitcher />
</div>
</header>
)}
</ThemeContext.Consumer>
);
}
|
src/svg-icons/action/perm-phone-msg.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPermPhoneMsg = (props) => (
<SvgIcon {...props}>
<path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM12 3v10l3-3h6V3h-9z"/>
</SvgIcon>
);
ActionPermPhoneMsg = pure(ActionPermPhoneMsg);
ActionPermPhoneMsg.displayName = 'ActionPermPhoneMsg';
ActionPermPhoneMsg.muiName = 'SvgIcon';
export default ActionPermPhoneMsg;
|
pages/discover-more/related-projects.js | cherniavskii/material-ui | import React from 'react';
import withRoot from 'docs/src/modules/components/withRoot';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from 'docs/src/pages/discover-more/related-projects/related-projects.md';
function Page() {
return <MarkdownDocs markdown={markdown} />;
}
export default withRoot(Page);
|
components/styled-links.js | kentcdodds/glamorous-website | import React from 'react'
import Link from 'next/link'
import glamorous from 'glamorous'
import {colors} from '../styles/global-styles'
const getPathname = pathname => {
return pathname === undefined ? '' : pathname
}
const basicLinkStyles =
// @css
{cursor: 'pointer'}
const anchorStyles =
// @css
{
textDecoration: 'underline',
color: colors.primaryMed,
}
const activeLinkStyles = props => ({
color:
props.active || props.external ?
props.theme.colors.primary :
props.theme.colors.primaryMed,
textDecoration: props.active || props.external ? 'underline' : 'none',
})
const slugStyles =
// @css
{
position: 'relative',
display: 'block',
'& svg': {
display: 'none',
position: 'absolute',
top: 0,
left: '-2.5rem',
width: '1.75em',
height: '2.827em',
},
'&:hover svg': {
display: 'block',
},
}
const StyledAnchor = glamorous.a(
basicLinkStyles,
anchorStyles,
activeLinkStyles,
props => (props.isSlug ? slugStyles : ''),
)
const Anchor = ({href, prefetch, external, pathname, isSlug, ...rest}) => {
if (external) {
return <StyledAnchor href={href} external {...rest} />
}
if (isSlug) {
return <StyledAnchor href={href} external isSlug {...rest} />
}
return (
<Link prefetch={prefetch} href={href}>
<StyledAnchor
href={href}
active={getPathname(pathname) === href}
{...rest}
/>
</Link>
)
}
const solidColors =
// @css
{backgroundColor: colors.primaryMed, color: 'white'}
const transparentColors =
// @css
{
backgroundColor: 'rgba(255, 255, 255, 0.5)',
color: colors.primary,
}
const secondaryButtonStyles =
// @css
{...transparentColors, ':hover': solidColors}
const Button = glamorous(Anchor)(
basicLinkStyles,
{
fontSize: '1em',
border: `1px solid ${colors.primaryMed}`,
width: '11em',
padding: '0.7em 0',
textDecoration: 'none',
borderRadius: 4,
display: 'inline-block',
margin: '.5em 1em',
transition: 'all .3s',
...solidColors,
':hover': transparentColors,
},
props => ({...(props.secondary ? secondaryButtonStyles : {})}),
)
export {Button, Anchor}
|
examples/async/index.js | dimaip/redux | import 'babel-core/polyfill';
import React from 'react';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
const store = configureStore();
React.render(
<Provider store={store}>
{() => <App />}
</Provider>,
document.getElementById('root')
);
|
src/svg-icons/maps/local-taxi.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalTaxi = (props) => (
<SvgIcon {...props}>
<path d="M18.92 6.01C18.72 5.42 18.16 5 17.5 5H15V3H9v2H6.5c-.66 0-1.21.42-1.42 1.01L3 12v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 16c-.83 0-1.5-.67-1.5-1.5S5.67 13 6.5 13s1.5.67 1.5 1.5S7.33 16 6.5 16zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 11l1.5-4.5h11L19 11H5z"/>
</SvgIcon>
);
MapsLocalTaxi = pure(MapsLocalTaxi);
MapsLocalTaxi.displayName = 'MapsLocalTaxi';
MapsLocalTaxi.muiName = 'SvgIcon';
export default MapsLocalTaxi;
|
frontend/src/components/app.js | bhtucker/streamkov | import React from 'react'
import VisibleChainList from '../containers/VisibleChainList'
import Sampler from './Sampler'
import UrlEntryBox from './UrlEntryBox'
const App = () => (
<div>
<h1>Streamkov</h1>
<VisibleChainList />
<Sampler />
<UrlEntryBox />
</div>
)
export default App
|
ui/src/components/footer.js | jollopre/mps | import React from 'react';
const style = {
position: 'absolute',
right: 0,
bottom: 0,
left:0,
minHeight: '50px',
padding: '1rem',
textAlign: 'center',
backgroundColor: '#222',
color: '#fff',
fontSize: 'small',
};
export const Footer = function(){
return (
<div style={style}>
<ul className="list-inline">
<li>
© {new Date().getFullYear()} <a
className="text-warning"
href="http://marshallpackaging.com"
target="_blank"
rel="noopener noreferrer">
Marshall Packaging Ltd
</a>
</li>
<li>|</li>
<li>
<a
className="text-warning"
href="https://github.com/jollopre"
target="_blank"
rel="noopener noreferrer">
Powered by jollopre
</a>
</li>
</ul>
</div>
);
}
|
src/index.js | weixing2014/iTodo | import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'
let store = createStore(todoApp)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
app/src/components/AliasModal.js | GetStream/Winds | import React from 'react';
import PropTypes from 'prop-types';
import ReactModal from 'react-modal';
import { Img } from 'react-image';
import { connect } from 'react-redux';
import fetch from '../util/fetch';
import { getAliases } from '../api';
import saveIcon from '../images/icons/save.svg';
import exitIcon from '../images/buttons/exit.svg';
class AliasModal extends React.Component {
constructor(props) {
super(props);
this.state = {
error: false,
submitting: false,
success: false,
};
}
closeModal = () => {
this.setState({ error: false, submitting: false, success: false });
this.props.toggleModal();
};
handleSubmit = (e) => {
e.preventDefault();
const alias = new FormData(e.target).get('alias');
const id = this.props.isRss
? { rss: this.props.feedID }
: { podcast: this.props.feedID };
this.setState({ submitting: true });
fetch('POST', '/aliases', { alias, ...id })
.then((res) => {
if (res.data) {
this.setState({ success: true, submitting: false });
getAliases(this.props.dispatch);
setTimeout(() => this.closeModal(), 500);
}
})
.catch(() => this.setState({ error: true, submitting: false }));
};
render() {
let buttonText = 'SAVE';
if (this.state.submitting) {
buttonText = 'Submitting...';
} else if (this.state.success) {
buttonText = 'Success!';
}
return (
<ReactModal
className="modal add-new-content-modal"
isOpen={this.props.isOpen}
onRequestClose={this.closeModal}
overlayClassName="modal-overlay"
shouldCloseOnOverlayClick={true}
>
<header>
<h1>Rename Feed</h1>
<Img className="exit" onClick={this.closeModal} src={exitIcon} />
</header>
<form onSubmit={this.handleSubmit}>
<div className="input-box">
<input
autoComplete="false"
defaultValue={this.props.defVal}
name="alias"
placeholder="Enter new name"
type="text"
/>
</div>
{this.state.error && (
<div className="error-message">
Oops, something went wrong. Please try again later.
</div>
)}
<div className="buttons">
<button
className="btn primary alt with-circular-icon"
disabled={this.state.submitting}
type="submit"
>
<Img src={saveIcon} />
{buttonText}
</button>
<button
className="btn link cancel"
onClick={this.closeModal}
type="cancel"
>
Cancel
</button>
</div>
</form>
</ReactModal>
);
}
}
AliasModal.defaultProps = {
isOpen: false,
};
AliasModal.propTypes = {
isOpen: PropTypes.bool,
toggleModal: PropTypes.func.isRequired,
defVal: PropTypes.string,
isRss: PropTypes.bool,
feedID: PropTypes.string,
dispatch: PropTypes.func.isRequired,
};
export default connect()(AliasModal);
|
docs/src/app/pages/components/Avatar/FallbackAvatar.js | GetAmbassador/react-ions | import React from 'react'
import Avatar from 'react-ions/lib/components/Avatar'
import Button from 'react-ions/lib/components/Button'
import style from './style.scss'
class ExampleAvatar extends React.Component {
constructor(props) {
super(props)
}
state = {
letters: 'cf',
size: '100'
}
randomize = () => {
const possible = 'abcdefghijklmnopqrstuvwxyz'
let letters = ''
for (let i = 0; i < 2; i++) {letters += possible.charAt(Math.floor(Math.random() * possible.length))}
const size = (Math.floor(Math.random() * 200) + 30).toString()
this.setState({ letters, size })
}
render = () => {
return (
<div>
<Avatar letters={this.state.letters} size={this.state.size} />
<div className={style['avatar-controls']}>
<Button onClick={this.randomize}>Random letters/size</Button>
</div>
</div>
)
}
}
export default ExampleAvatar
|
Libraries/TabBar/TabBar.web.js | brainpoint/citong-react-web | /**
* Copyright (c) 2015-present, Alibaba Group Holding Limited.
* All rights reserved.
*
* @providesModule ReactTabBar
*/
'use strict';
import React from 'react';
import View from 'ReactView';
import TabBarItem from './TabBarItem.web';
import TabBarContents from './TabBarContents.web';
import assign from 'object-assign';
import StyleSheet from 'ReactStyleSheet';
let TabBar = React.createClass({
getInitialState() {
return {
selectedIndex: 0
};
},
statics: {
Item: TabBarItem
},
propTypes: {
style: React.PropTypes.object,
/**
* Color of the currently selected tab icon
*/
tintColor: React.PropTypes.string,
/**
* Background color of the tab bar
*/
barTintColor: React.PropTypes.string,
clientHeight: React.PropTypes.number
},
getStyles() {
return StyleSheet.create({
container: {
width: '100%',
height: this.props.clientHeight || document.documentElement.clientHeight,
position: 'relative',
overflow: 'hidden'
},
content: {
width: '100%',
height: '100%'
},
bar: {
width: '100%',
position: 'absolute',
padding: 0,
margin: 0,
listStyle: 'none',
left: 0,
bottom: 0,
// borderTop: '1px solid #e1e1e1',
backgroundColor: 'rgba(250,250,250,.96)',
display: 'table'
}
});
},
handleTouchTap(index) {
this.setState({
selectedIndex: index
});
},
render() {
let self = this;
let styles = self.getStyles();
let barStyle = assign(styles.bar, this.props.style || {}, this.props.barTintColor ? {
backgroundColor: this.props.barTintColor
} : {});
let tabContent = [];
let tabs = React.Children.map(this.props.children, (tab,
index) => {
if (tab.type.displayName === 'TabBarItem') {
if (tab.props.children) {
tabContent.push(React.createElement(TabBarContents, {
key: index,
selected: self.state.selectedIndex === index
}, tab.props.children));
} else {
tabContent.push(undefined);
}
return React.cloneElement(tab, {
index: index,
selected: self.state.selectedIndex === index,
selectedColor: self.props.tintColor,
handleTouchTap: self.handleTouchTap
});
} else {
let type = tab.type.displayName || tab.type;
throw 'Tabbar only accepts TabBar.Item Components as children. Found ' + type + ' as child number ' + (index + 1) + ' of Tabbar';
}
});
return (
<View style={styles.container}>
<View style={styles.content}>{tabContent}</View>
<ul style={barStyle}>
{tabs}
</ul>
</View>
);
}
});
TabBar.isReactNativeComponent = true;
export default TabBar;
|
react-flux-mui/js/material-ui/src/svg-icons/av/replay.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvReplay = (props) => (
<SvgIcon {...props}>
<path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/>
</SvgIcon>
);
AvReplay = pure(AvReplay);
AvReplay.displayName = 'AvReplay';
AvReplay.muiName = 'SvgIcon';
export default AvReplay;
|
app/static/src/diagnostic/EquipmentForm_modules/NewManufacturerForm.js | SnowBeaver/Vision | import React from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import Button from 'react-bootstrap/lib/Button';
import Panel from 'react-bootstrap/lib/Panel';
import {findDOMNode} from 'react-dom';
import { hashHistory } from 'react-router';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
import {NotificationContainer, NotificationManager} from 'react-notifications';
var NewManufacturerForm = React.createClass({
getInitialState: function () {
return {
loading: false,
errors: {},
fields: [
'name',
'markings',
'location',
'description'
],
changedFields: []
}
},
_create: function () {
var fields = this.state.changedFields;
var data = {};
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
var value = this.state[key];
if (value == ""){
value = null;
}
data[key] = value;
}
return $.authorizedAjax({
url: '/api/v1.0/manufacturer/',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
beforeSend: function () {
this.setState({loading: true});
}.bind(this)
})
},
_onSubmit: function (e) {
e.preventDefault();
if (!this.is_valid()){
NotificationManager.error('Please correct the errors');
return false;
}
var xhr = this._create();
xhr.done(this._onSuccess)
.fail(this._onError)
.always(this.hideLoading)
},
hideLoading: function () {
this.setState({loading: false});
},
_onSuccess: function (data) {
this.props.handleClose();
this.props.onCreate(data, this.props.fieldName);
NotificationManager.success("Manufacturer added.");
},
_onError: function (data) {
var message = "Failed to create";
var res = data.responseJSON;
if (res.message) {
message = data.responseJSON.message;
}
if (res.error) {
// We get list of errors
if (data.status >= 500) {
message = res.error.join(". ");
} else if (res.error instanceof Object){
// We get object of errors with field names as key
for (var field in res.error) {
var errorMessage = res.error[field];
if (Array.isArray(errorMessage)) {
errorMessage = errorMessage.join(". ");
}
res.error[field] = errorMessage;
}
this.setState({
errors: res.error
});
} else {
message = res.error;
}
}
NotificationManager.error(message);
},
_onChange: function (e) {
var state = {};
if (e.target.type == 'checkbox') {
state[e.target.name] = e.target.checked;
} else if (e.target.type == 'select-one') {
state[e.target.name] = e.target.value;
} else {
state[e.target.name] = e.target.value;
}
state.changedFields = this.state.changedFields.concat([e.target.name]);
var errors = this._validate(e);
state = this._updateFieldErrors(e.target.name, state, errors);
this.setState(state);
},
_validate: function (e) {
var errors = [];
var error;
error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type"));
if (error){
errors.push(error);
}
error = this._validateFieldLength(e.target.value, e.target.getAttribute("data-len"));
if (error){
errors.push(error);
}
return errors;
},
_validateFieldType: function (value, type){
var error = "";
if (type != undefined && value){
var typePatterns = {
"float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/,
"int": /^(-|\+)?(0|[1-9]\d*)$/
};
if (!typePatterns[type].test(value)){
error = "Invalid " + type + " value";
}
}
return error;
},
_validateFieldLength: function (value, length){
var error = "";
if (value && length){
if (value.length > length){
error = "Value should be maximum " + length + " characters long"
}
}
return error;
},
_updateFieldErrors: function (fieldName, state, errors){
// Clear existing errors related to the current field as it has been edited
state.errors = this.state.errors;
delete state.errors[fieldName];
// Update errors with new ones, if present
if (Object.keys(errors).length){
state.errors[fieldName] = errors.join(". ");
}
return state;
},
is_valid: function () {
return (Object.keys(this.state.errors).length <= 0);
},
_formGroupClass: function (field) {
var className = "form-group ";
if (field) {
className += " has-error"
}
return className;
},
handleClick: function () {
document.getElementById('test_prof').remove();
},
render: function () {
return (
<div className="form-container">
<form method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}>
<div className="row">
<div className="col-md-12">
<FormGroup validationState={this.state.errors.name ? 'error' : null}>
<FormControl type="text"
placeholder="Name *"
name="name"
required
data-len="50"
/>
<HelpBlock className="warning">{this.state.errors.name}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</div>
</div>
<div className="row">
<div className="col-md-12">
<FormGroup validationState={this.state.errors.markings ? 'error' : null}>
<FormControl componentClass="textarea"
placeholder="Markings"
name="markings"/>
<HelpBlock className="warning">{this.state.errors.markings}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</div>
</div>
<div className="row">
<div className="col-md-12">
<FormGroup validationState={this.state.errors.location ? 'error' : null}>
<FormControl type="text"
placeholder="Location"
name="location"
data-len="256"
/>
<HelpBlock className="warning">{this.state.errors.location}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</div>
</div>
<div className="row">
<div className="col-md-12">
<FormGroup validationState={this.state.errors.description ? 'error' : null}>
<FormControl componentClass="textarea"
placeholder="Description"
name="description"/>
<HelpBlock className="warning">{this.state.errors.description}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</div>
</div>
<div className="row">
<div className="col-md-12 ">
<Button bsStyle="success"
className="pull-right"
type="submit">Save</Button>
<Button bsStyle="danger"
className="pull-right margin-right-xs"
onClick={this.props.handleClose}
>Cancel</Button>
</div>
</div>
</form>
</div>
);
}
});
export default NewManufacturerForm;
|
src/lib/topics.js | trujunzhang/IEATTA-web | import Telescope from '../components/lib/index';
import React from 'react';
let _ = require('underscore');
const Topics = {};
export default Topics;
|
react/src/components/dashboard/settings/settings.daemonStdoutPanel.js | pbca26/EasyDEX-GUI | import React from 'react';
import translate from '../../../translate/translate';
import { connect } from 'react-redux';
import { coindGetStdout } from '../../../actions/actionCreators';
import Store from '../../../store';
class DaemonStdoutPanel extends React.Component {
constructor() {
super();
this.state = {
coindStdOut: translate('INDEX.LOADING') + '...',
coin: null,
textareaHeight: '100px',
};
this.getCoindGetStdout = this.getCoindGetStdout.bind(this);
this.updateInput = this.updateInput.bind(this);
}
componentWillMount() {
this.getCoindGetStdout();
}
getCoindGetStdout() {
const _coin = this.state.coin || this.props.ActiveCoin.coin;
coindGetStdout(_coin)
.then((res) => {
this.setState({
coindStdOut: res.msg === 'success' ? res.result : `${translate('INDEX.ERROR_READING')} ${_coin} stdout`,
});
setTimeout(() => {
const _ta = document.querySelector('#settingsCoindStdoutTextarea');
_ta.style.height = '1px';
_ta.style.height = `${(15 + _ta.scrollHeight)}px`;
}, 100);
});
}
updateInput(e) {
this.setState({
[e.target.name]: e.target.value,
});
this.getCoindGetStdout();
}
renderCoinListSelectorOptions(coin) {
let _items = [];
let _nativeCoins = this.props.Main.coins.native;
_nativeCoins.sort();
for (let i = 0; i < _nativeCoins.length; i++) {
_items.push(
<option
key={ `coind-stdout-coins-${i}` }
value={ `${_nativeCoins[i]}` }>
{ `${_nativeCoins[i]}` }
</option>
);
}
return _items;
}
render() {
return (
<div>
<div className="row">
<div className="col-sm-12 padding-bottom-10">
<div>
<div className="col-sm-3 no-padding-left">
<select
className="form-control form-material"
name="coin"
value={
this.state.coin ||
this.props.ActiveCoin.coin ||
''
}
onChange={ (event) => this.updateInput(event) }
autoFocus>
{ this.renderCoinListSelectorOptions() }
</select>
</div>
<div className="col-sm-1">
<i
className="icon fa-refresh coind-stdout-refresh-icon pointer"
onClick={ this.getCoindGetStdout }></i>
</div>
</div>
</div>
<div className="col-sm-12">
<div className="form-group form-material floating col-sm-8 no-padding-left">
<textarea
readOnly
id="settingsCoindStdoutTextarea"
className="form-control settings-coind-stdout-textarea"
value={ this.state.coindStdOut }
style={{ height: this.state.textareaHeight }}></textarea>
</div>
</div>
</div>
</div>
);
};
}
const mapStateToProps = (state) => {
return {
ActiveCoin: {
coin: state.ActiveCoin.coin,
mode: state.ActiveCoin.mode,
},
Main: state.Main,
};
};
export default connect(mapStateToProps)(DaemonStdoutPanel); |
src/components/ShareMenu/WaitingOverlay.js | Charlie9830/pounder | import React from 'react';
import { Modal, Grid, CircularProgress, Typography } from '@material-ui/core';
const WaitingOverlay = (props) => {
let gridStyle = {
width: '100%',
height: '100%',
}
return (
<Modal open={props.open} disableAutoFocus={true}>
<Grid container style={gridStyle}
direction="column"
justify="center"
alignItems="center">
<Grid item>
<CircularProgress />
</Grid>
<Grid item>
<Typography align="center" variant="h6"> {props.message} </Typography>
</Grid>
<Grid item style={{marginTop: '32px'}}>
<Typography align="center" variant="h6"> {props.subMessage} </Typography>
</Grid>
</Grid>
</Modal>
)
}
export default WaitingOverlay; |
app/javascript/mastodon/components/domain.js | salvadorpla/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unhide {domain}' },
});
export default @injectIntl
class Account extends ImmutablePureComponent {
static propTypes = {
domain: PropTypes.string,
onUnblockDomain: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleDomainUnblock = () => {
this.props.onUnblockDomain(this.props.domain);
}
render () {
const { domain, intl } = this.props;
return (
<div className='domain'>
<div className='domain__wrapper'>
<span className='domain__domain-name'>
<strong>{domain}</strong>
</span>
<div className='domain__buttons'>
<IconButton active icon='unlock' title={intl.formatMessage(messages.unblockDomain, { domain })} onClick={this.handleDomainUnblock} />
</div>
</div>
</div>
);
}
}
|
src/jsx/components/AddTransaction.js | luckychain/lucky | import React from 'react';
import Textarea from 'react-textarea-autosize';
import {Grid, Row, Col, Panel, FormGroup, Radio} from 'react-bootstrap';
import AppActions from '../actions/AppActions';
class AddTransaction extends React.Component {
handleSubmit(event) {
event.preventDefault();
var type = event.target.transactionType.value;
var data = event.target.transactionData.value;
if (!data) {
AppActions.emptyTransaction();
this.refs.transactionDataField.focus();
}
else {
AppActions.addTransaction(type, data);
}
}
render() {
return (
<Grid>
<Row>
<Col sm={12}>
<Panel header={(<h4>Add Transaction</h4>)}>
<form onSubmit={this.handleSubmit.bind(this)}>
<div className={'form-group ' + this.props.addTransactionState}>
<label className="control-label">Transaction</label>
<Textarea type="text" maxRows={20} className="form-control" name="transactionData" ref="transactionDataField" autoFocus />
<span className="help-block">{this.props.addTransactionHelp}</span>
</div>
<FormGroup>
<Radio inline defaultChecked name="transactionType" value="data">
Data
</Radio>
{' '}
<Radio inline name="transactionType" value="address">
IPFS Address
</Radio>
</FormGroup>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</Panel>
</Col>
</Row>
</Grid>
);
}
}
export default AddTransaction; |
node_modules/eslint-config-airbnb/test/test-react-order.js | edsrupp/eds-mess | import test from 'tape';
import { CLIEngine } from 'eslint';
import eslintrc from '../';
import baseConfig from '../base';
import reactRules from '../rules/react';
const cli = new CLIEngine({
useEslintrc: false,
baseConfig: eslintrc,
// This rule fails when executing on text.
rules: {indent: 0},
});
function lint(text) {
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext
return cli.executeOnText(text).results[0];
}
function wrapComponent(body) {
return `
import React from 'react';
export default class MyComponent extends React.Component {
${body}
}
`;
}
test('validate react prop order', t => {
t.test('make sure our eslintrc has React linting dependencies', t => {
t.plan(1);
t.equal(reactRules.plugins[0], 'react', 'uses eslint-plugin-react');
});
t.test('passes a good component', t => {
t.plan(3);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
someMethod() {}
renderDogs() {}
render() { return <div />; }
`));
t.notOk(result.warningCount, 'no warnings');
t.notOk(result.errorCount, 'no errors');
t.deepEquals(result.messages, [], 'no messages in results');
});
t.test('order: when random method is first', t => {
t.plan(2);
const result = lint(wrapComponent(`
someMethod() {}
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
t.test('order: when random method after lifecycle methods', t => {
t.plan(2);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
someMethod() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
});
|
src/v2/stories/EmbeddedChannel.stories.js | aredotna/ervell | import React from 'react'
import { storiesOf } from '@storybook/react'
import Specimen from 'v2/stories/__components__/Specimen'
import { EmbeddedChannel } from 'v2/pages/channel/EmbeddedChannelPage/components/EmbeddedChannel'
storiesOf('EmbeddedChannel', module).add('default', () => (
<Specimen>
<EmbeddedChannel id="hello" />
</Specimen>
))
|
react/L3/src/pages/Child.js | luolisave/starters | import React from 'react';
import {bindActionCreators} from 'redux';
import { connect } from 'react-redux';
import uuidv4 from 'uuid/v4';
// functions, should put to seperate file later.
function clone(obj) {
if (null === obj || "object" !== typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
//Functions, should put to seperate file later.
var special = ['zeroth','first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth'];
var deca = ['twent', 'thirt', 'fort', 'fift', 'sixt', 'sevent', 'eight', 'ninet'];
function stringifyNumber(n) {
if (n < 20) return special[n];
if (n%10 === 0) return deca[Math.floor(n/10)-2] + 'ieth';
return deca[Math.floor(n/10)-2] + 'y-' + special[n%10];
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
//component
class Child extends React.Component {
child = {};
componentDidMount(){
this.child = clone(this.props.child);
console.log("this.child = ", this.child);
}
render() {
if(this.props.child.saved){
return (
<div className="childRow">
<div className="row">
<div className="col col-sm-2">
<h4>{capitalizeFirstLetter(stringifyNumber(this.props.myindex+1))} Child</h4>
<p><a className="removeBtn" onClick={()=>{
this.props.removeChild(this.props.child);
}} >Remove</a></p>
</div>
<div className="col col-sm-2">
First Name: <input type="text" name="first" defaultValue={this.props.child.first} disabled />
</div>
<div className="col col-sm-2">
Last Name: <input type="text" name="last" defaultValue={this.props.child.last} disabled />
</div>
<div className="col col-sm-2">
</div>
</div>
</div>
);
}else{
return (
<div className="childRow">
<div className="row">
<div className="col col-sm-2">
<h4>{capitalizeFirstLetter(stringifyNumber(this.props.myindex+1))} Child</h4>
<p><a
className="removeBtn"
onClick={
()=>{
this.props.removeChild(this.props.child);
this.props.resetHasMoreChildRadio();
}
} >Remove</a></p>
</div>
<div className="col col-sm-2">
First Name: <input type="text" name="first" defaultValue={this.props.child.first} onChange={(event)=>{
this.child.first = event.target.value;
console.log("child = ",this.child, " ||| event.target.value = ", event.target.value, " ||| uuidv4 = ", uuidv4());
}} />
</div>
<div className="col col-sm-2">
Last Name: <input type="text" name="last" defaultValue={this.props.child.last} onChange={(event)=>{
this.child.last = event.target.value;
console.log("child = ",this.child, " ||| event.target.value = ", event.target.value, " ||| uuidv4 = ", uuidv4());
}} />
</div>
</div>
<div className="row">
<div className="col col-sm-2"></div>
<div className="col col-sm-2"></div>
<div className="col col-sm-2">
<p> </p>
<button title="Cancel" className="btn btn-primary">Cancel</button>
<button title="Save" className="btn btn-primary" onClick={
(event)=>{
console.log("!!! this.props.children", this.props.children);
//let myChildren = clone(this.props.children);
//myChildren.push(this.child);
//console.log("!!! myChildren", myChildren);
this.props.saveChild(this.child);
this.props.resetHasMoreChildRadio();
}
}>Save</button></div>
</div>
</div>
);
}
}
}
function mapStateToProps(state) {
return {
children: state.children
}
}
// Get actions and pass them as props to to UserList
// > now UserList has this.props.selectUser
function matchDispatchToProps(dispatch){
return bindActionCreators(
{
saveChild: function(payload) {
console.log("action: Should Save Child to Children Reducer.");
return {
type: 'SAVE_CHILD',
payload: payload
}
},
removeChild: function(payload) {
console.log("action: Should Save Child to Children Reducer.");
return {
type: 'REMOVE_CHILD',
payload: payload
}
}
},
dispatch
);
}
export default connect(mapStateToProps, matchDispatchToProps)(Child);
//export default Child;
|
src/containers/Asians/TabControls/PreliminaryRounds/EnterRoundResults/TraineeFeedback/index.js | westoncolemanl/tabbr-web | import React from 'react'
import { connect } from 'react-redux'
import Instance from './Instance'
import ListSubheader from 'material-ui/List/ListSubheader'
export default connect(mapStateToProps)(({
round,
rooms,
adjudicatorScores
}) => {
const filterRooms = roomToMatch => roomToMatch.round === round._id
const roomsThisRound = rooms.filter(filterRooms)
const adjudicatorScoresThisRound = adjudicatorScores.filter(filterRooms)
const arr = []
roomsThisRound.forEach(room => {
if (room.trainees.length > 0) {
arr.push(
<Instance
key={room._id}
room={room}
adjudicatorScoresThisRound={adjudicatorScoresThisRound}
/>
)
}
})
return (
<div>
{arr.length > 0 &&
<ListSubheader
disableSticky
>
{'Trainee feedback'}
</ListSubheader>
}
{arr}
</div>
)
})
function mapStateToProps (state, ownProps) {
return {
rooms: Object.values(state.rooms.data),
adjudicatorScores: Object.values(state.adjudicatorScores.data)
}
}
|
js/Details.js | aurimas-darguzis/react-intro | import React from 'react'
import { connect } from 'react-redux'
import { getOMDBDetails } from './actionCreators'
import Header from './Header'
const { shape, string, func } = React.PropTypes
const Details = React.createClass({
propTypes: {
show: shape({
title: string,
year: string,
poster: string,
trailer: string,
description: string,
imdbID: string
}),
omdbData: shape({
imdbID: string
}),
dispatch: func
},
componentDidMount () {
if (!this.props.omdbData.imdbRating) {
this.props.dispatch(getOMDBDetails(this.props.show.imdbID))
}
},
render () {
const { title, description, year, poster, trailer } = this.props.show
let rating
if (this.props.omdbData.imdbRating) {
rating = <h3>{this.props.omdbData.imdbRating}</h3>
} else {
rating = <img src='/public/img/loading.png' alt='loading indicator' />
}
return (
<div className='details'>
<Header />
<section>
<h1>{title}</h1>
<h2>({year})</h2>
{rating}
<img src={`/public/img/posters/${poster}`} />
<p>{description}</p>
</section>
<div>
<iframe src={`https://www.youtube-nocookie.com/embed/${trailer}?rel=0&controls=0&showinfo=0`} frameBorder='0' allowFullScreen />
</div>
</div>
)
}
})
const mapStateToProps = (state, ownProps) => {
const omdbData = state.omdbData[ownProps.show.imdbID] ? state.omdbData[ownProps.show.imdbID] : {}
return {
omdbData
}
}
export default connect(mapStateToProps)(Details)
|
src/svg-icons/editor/vertical-align-bottom.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorVerticalAlignBottom = (props) => (
<SvgIcon {...props}>
<path d="M16 13h-3V3h-2v10H8l4 4 4-4zM4 19v2h16v-2H4z"/>
</SvgIcon>
);
EditorVerticalAlignBottom = pure(EditorVerticalAlignBottom);
EditorVerticalAlignBottom.displayName = 'EditorVerticalAlignBottom';
export default EditorVerticalAlignBottom;
|
assets/node_modules/recompose/renderComponent.js | janta-devs/nyumbani | 'use strict';
exports.__esModule = true;
var _createHelper = require('./createHelper');
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = require('./createEagerFactory');
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// import React from 'react'
var renderComponent = function renderComponent(Component) {
return function (_) {
var factory = (0, _createEagerFactory2.default)(Component);
var RenderComponent = function RenderComponent(props) {
return factory(props);
};
// const RenderComponent = props => <Component {...props} />
if (process.env.NODE_ENV !== 'production') {
/* eslint-disable global-require */
var wrapDisplayName = require('./wrapDisplayName').default;
/* eslint-enable global-require */
RenderComponent.displayName = wrapDisplayName(Component, 'renderComponent');
}
return RenderComponent;
};
};
exports.default = (0, _createHelper2.default)(renderComponent, 'renderComponent', false); |
frontend/src/main/web/src/legacy.js | mvehar/zanata-server | /*
* Copyright 2016, Red Hat, Inc. and individual contributors as indicated by the
* @author tags. See the copyright.txt file in the distribution for a full
* listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { mapValues } from 'lodash'
import { Icons } from './components'
import WebFont from 'webfontloader'
import Nav from './components/Nav'
import './styles/base.css'
import './styles/atomic.css'
import './styles/extras.css'
import { isJsonString } from './utils/StringUtils'
/**
* Root component that display only side menu bar.
* Used jsf page that only needs side menu bar from frontend.
*/
WebFont.load({
google: {
families: [
'Source Sans Pro:200,400,600',
'Source Code Pro:400,600'
]
},
timeout: 2000
})
window.config = mapValues(window.config, (value) =>
isJsonString(value) ? JSON.parse(value) : value)
// baseUrl should be /zanata or ''
window.config.baseUrl = window.config.baseUrl || ''
const links = {
'context': window.config.baseUrl,
'/login': window.config.links.loginUrl,
'/signup': window.config.links.registerUrl
}
const activePath = window.location.pathname
render(
<div className='H(a) H(100%)--sm'>
<Icons />
<Nav active={activePath} isJsfPage links={links} />
</div>
,
document.getElementById('root')
)
|
src/BasicHtmlEditor.js | dburrows/draft-js-basic-html-editor | import React from 'react';
import ReactDOM from 'react-dom';
import debounce from 'lodash/debounce';
import {
Editor,
EditorState,
ContentState,
Entity,
RichUtils,
convertToRaw,
CompositeDecorator,
Modifier
} from 'draft-js';
import htmlToContent from './utils/htmlToContent';
import draftRawToHtml from './utils/draftRawToHtml';
import Link from './components/Link';
import EntityControls from './components/EntityControls';
import InlineStyleControls from './components/InlineStyleControls';
import BlockStyleControls from './components/BlockStyleControls';
import findEntities from './utils/findEntities';
export default class BasicHtmlEditor extends React.Component {
constructor(props) {
super(props);
let { value } = props;
const decorator = new CompositeDecorator([
{
strategy: findEntities.bind(null, 'link'),
component: Link
}
]);
this.ENTITY_CONTROLS = [
{label: 'Add Link', action: this._addLink.bind(this) },
{label: 'Remove Link', action: this._removeLink.bind(this) }
];
this.INLINE_STYLES = [
{label: 'Bold', style: 'BOLD'},
{label: 'Italic', style: 'ITALIC'},
{label: 'Underline', style: 'UNDERLINE'},
{label: 'Monospace', style: 'CODE'},
{label: 'Strikethrough', style: 'STRIKETHROUGH'}
];
this.BLOCK_TYPES = [
{label: 'P', style: 'unstyled'},
{label: 'H1', style: 'header-one'},
{label: 'H2', style: 'header-two'},
{label: 'Blockquote', style: 'blockquote'},
{label: 'UL', style: 'unordered-list-item'},
{label: 'OL', style: 'ordered-list-item'},
{label: 'Code Block', style: 'code-block'}
];
this.state = {
editorState: value ?
EditorState.createWithContent(
ContentState.createFromBlockArray(htmlToContent(value)),
decorator
) :
EditorState.createEmpty(decorator)
};
// this.focus = () => this.refs.editor.focus();
this.onChange = (editorState) => {
let previousContent = this.state.editorState.getCurrentContent();
this.setState({editorState});
// only emit html when content changes
if( previousContent !== editorState.getCurrentContent() ) {
this.emitHTML(editorState);
}
};
function emitHTML(editorState) {
let raw = convertToRaw( editorState.getCurrentContent() );
let html = draftRawToHtml(raw);
this.props.onChange(html);
}
this.emitHTML = debounce(emitHTML, this.props.debounce);
this.handleKeyCommand = (command) => this._handleKeyCommand(command);
this.toggleBlockType = (type) => this._toggleBlockType(type);
this.toggleInlineStyle = (style) => this._toggleInlineStyle(style);
this.handleReturn = (e) => this._handleReturn(e);
this.addLink = this._addLink.bind(this);
this.removeLink = this._removeLink.bind(this);
}
_handleKeyCommand(command) {
const {editorState} = this.state;
const newState = RichUtils.handleKeyCommand(editorState, command);
if (newState) {
this.onChange(newState);
return true;
}
return false;
}
_handleReturn(e) {
if (e.metaKey === true) {
return this._addLineBreak();
} else {
return false;
}
}
_toggleBlockType(blockType) {
this.onChange(
RichUtils.toggleBlockType(
this.state.editorState,
blockType
)
);
}
_toggleInlineStyle(inlineStyle) {
this.onChange(
RichUtils.toggleInlineStyle(
this.state.editorState,
inlineStyle
)
);
}
_addLineBreak(/* e */) {
let newContent, newEditorState;
const {editorState} = this.state;
const content = editorState.getCurrentContent();
const selection = editorState.getSelection();
const block = content.getBlockForKey(selection.getStartKey());
console.log(content.toJS(), selection.toJS(), block.toJS());
if (block.type === 'code-block') {
newContent = Modifier.insertText(content, selection, '\n');
newEditorState = EditorState.push(editorState, newContent, 'add-new-line');
this.onChange(newEditorState);
return true;
} else {
return false;
}
}
_addLink(/* e */) {
const {editorState} = this.state;
const selection = editorState.getSelection();
if (selection.isCollapsed()) {
return;
}
const href = window.prompt('Enter a URL');
const entityKey = Entity.create('link', 'MUTABLE', {href});
this.onChange(RichUtils.toggleLink(editorState, selection, entityKey));
}
_removeLink(/* e */) {
const {editorState} = this.state;
const selection = editorState.getSelection();
if (selection.isCollapsed()) {
return;
}
this.onChange( RichUtils.toggleLink(editorState, selection, null));
}
render() {
const {editorState} = this.state;
// If the user changes block type before entering any text, we can
// either style the placeholder or hide it. Let's just hide it now.
let className = 'RichEditor-editor';
var contentState = editorState.getCurrentContent();
if (!contentState.hasText()) {
if (contentState.getBlockMap().first().getType() !== 'unstyled') {
className += ' RichEditor-hidePlaceholder';
}
}
return (
<div className="RichEditor-root draftjs-bhe">
<BlockStyleControls
editorState={editorState}
blockTypes={this.BLOCK_TYPES}
onToggle={this.toggleBlockType}
/>
<InlineStyleControls
editorState={editorState}
onToggle={this.toggleInlineStyle}
inlineStyles={this.INLINE_STYLES}
/>
<EntityControls
editorState={editorState}
entityControls={this.ENTITY_CONTROLS}
/>
<div className={className} /* onClick={this.focus} */>
<Editor
blockStyleFn={getBlockStyle}
customStyleMap={styleMap}
editorState={editorState}
handleKeyCommand={this.handleKeyCommand}
handleReturn={this.handleReturn}
onChange={this.onChange}
placeholder="Tell a story..."
ref="editor"
spellCheck={true}
/>
</div>
</div>
);
}
}
// Custom overrides for "code" style.
const styleMap = {
CODE: {
backgroundColor: 'rgba(0, 0, 0, 0.05)',
fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace',
fontSize: 16,
padding: 2
}
};
function getBlockStyle(block) {
switch (block.getType()) {
case 'blockquote': return 'RichEditor-blockquote';
default: return null;
}
}
|
app/react-icons/fa/gift.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaGift extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m23.7 30.3v-16h-7.1v16q0 0.5 0.4 0.8t1 0.3h4.3q0.6 0 1-0.3t0.4-0.8z m-10.2-18.9h4.4l-2.8-3.6q-0.6-0.7-1.6-0.7-0.9 0-1.5 0.7t-0.6 1.5 0.6 1.5 1.5 0.6z m15.4-2.1q0-0.9-0.6-1.5t-1.6-0.7q-0.9 0-1.5 0.7l-2.8 3.6h4.4q0.8 0 1.5-0.6t0.6-1.5z m8.4 5.7v7.1q0 0.4-0.2 0.6t-0.5 0.2h-2.2v9.2q0 0.9-0.6 1.6t-1.5 0.6h-24.3q-0.9 0-1.5-0.6t-0.6-1.6v-9.2h-2.2q-0.3 0-0.5-0.2t-0.2-0.6v-7.1q0-0.3 0.2-0.5t0.5-0.2h9.8q-2 0-3.5-1.5t-1.5-3.5 1.5-3.6 3.5-1.4q2.4 0 3.8 1.7l2.8 3.7 2.9-3.7q1.4-1.7 3.8-1.7 2 0 3.5 1.4t1.4 3.6-1.4 3.5-3.6 1.5h9.9q0.3 0 0.5 0.2t0.2 0.5z"/></g>
</IconBase>
);
}
}
|
template/src/renderer/components/tempaltes/Main/Main.js | my-dish/template-electron | // @flow
import React from 'react';
import styles from './style.css';
type Props = {
left: React.Component<*>;
right: React.Component<*>;
children: React.Component<*>;
};
const Main = (props: Props) => (
<div className={styles.container}>
<div className={styles.left}>{props.left}</div>
{
props.children
}
<div className={styles.right}>{props.right}</div>
</div>
);
export default Main;
|
hello world/1.7 - router/src/components/routerList.js | wumouren/react-demo | import React from 'react';
export default class IndexList extends React.Component{
render(){
return (
<div>
<h1>这是主要内容列表</h1>
</div>
)
}
} |
frontend/node_modules/react-recaptcha/example/main.js | andres81/auth-service | import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import Recaptcha from '../src';
// site key
const sitekey = 'xxxxxxx';
// specifying your onload callback function
const callback = () => {
console.log('Done!!!!');
};
const verifyCallback = (response) => {
console.log(response);
};
const expiredCallback = () => {
console.log(`Recaptcha expired`);
};
// define a variable to store the recaptcha instance
let recaptchaInstance;
// handle reset
const resetRecaptcha = () => {
recaptchaInstance.reset();
};
class App extends React.Component {
render() {
return (
<div>
<h1>Google Recaptcha</h1>
<Recaptcha
ref={e => recaptchaInstance = e}
sitekey={sitekey}
size="compact"
render="explicit"
verifyCallback={verifyCallback}
onloadCallback={callback}
expiredCallback={expiredCallback}
/>
<br/>
<button
onClick={resetRecaptcha}
>
Reset
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
client/extensions/woocommerce/app/promotions/fields/checkbox-field.js | Automattic/woocommerce-connect-client | /** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { omit } from 'lodash';
/**
* Internal dependencies
*/
import FormCheckbox from 'components/forms/form-checkbox';
import FormField from './form-field';
const CheckboxField = props => {
const { fieldName, explanationText, placeholderText, value, edit } = props;
const renderedValue = 'undefined' !== typeof value ? value : false;
const onChange = () => {
edit( fieldName, ! value );
};
return (
<FormField { ...omit( props, 'explanationText' ) }>
<FormCheckbox
id={ fieldName + '-label' }
aria-describedby={ explanationText && fieldName + '-description' }
checked={ renderedValue }
placeholder={ placeholderText }
onChange={ onChange }
/>
<span>{ explanationText }</span>
</FormField>
);
};
CheckboxField.propTypes = {
fieldName: PropTypes.string,
explanationText: PropTypes.string,
placeholderText: PropTypes.string,
value: PropTypes.bool,
edit: PropTypes.func,
};
export default CheckboxField;
|
old_examples/conditional/app.js | reactjs/react-tabs | import React from 'react';
import { render } from 'react-dom';
import { Tab, Tabs, TabList, TabPanel } from '../../src/index';
import '../../style/react-tabs.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
showA: true,
showB: true,
showC: true,
};
}
handleCheckClicked = (e) => {
this.setState({
[e.target.name]: e.target.checked,
});
}
render() {
return (
<div style={{ padding: 50 }}>
<p>
<label>
<input type="checkbox" checked={this.state.showA} name="showA" onChange={this.handleCheckClicked} />
Show A
</label><br />
<label>
<input type="checkbox" checked={this.state.showB} name="showB" onChange={this.handleCheckClicked} />
Show B
</label><br />
<label>
<input type="checkbox" checked={this.state.showC} name="showC" onChange={this.handleCheckClicked} />
Show C
</label><br />
</p>
<Tabs>
<TabList>
{this.state.showA && <Tab>Tab A</Tab>}
{this.state.showB && <Tab>Tab B</Tab>}
{this.state.showC && <Tab>Tab C</Tab>}
</TabList>
{this.state.showA && <TabPanel>This is tab A</TabPanel>}
{this.state.showB && <TabPanel>This is tab B</TabPanel>}
{this.state.showC && <TabPanel>This is tab C</TabPanel>}
</Tabs>
</div>
);
}
}
render(<App />, document.getElementById('example'));
|
src/svg-icons/maps/directions-bike.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsDirectionsBike = (props) => (
<SvgIcon {...props}>
<path d="M15.5 5.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM5 12c-2.8 0-5 2.2-5 5s2.2 5 5 5 5-2.2 5-5-2.2-5-5-5zm0 8.5c-1.9 0-3.5-1.6-3.5-3.5s1.6-3.5 3.5-3.5 3.5 1.6 3.5 3.5-1.6 3.5-3.5 3.5zm5.8-10l2.4-2.4.8.8c1.3 1.3 3 2.1 5.1 2.1V9c-1.5 0-2.7-.6-3.6-1.5l-1.9-1.9c-.5-.4-1-.6-1.6-.6s-1.1.2-1.4.6L7.8 8.4c-.4.4-.6.9-.6 1.4 0 .6.2 1.1.6 1.4L11 14v5h2v-6.2l-2.2-2.3zM19 12c-2.8 0-5 2.2-5 5s2.2 5 5 5 5-2.2 5-5-2.2-5-5-5zm0 8.5c-1.9 0-3.5-1.6-3.5-3.5s1.6-3.5 3.5-3.5 3.5 1.6 3.5 3.5-1.6 3.5-3.5 3.5z"/>
</SvgIcon>
);
MapsDirectionsBike = pure(MapsDirectionsBike);
MapsDirectionsBike.displayName = 'MapsDirectionsBike';
MapsDirectionsBike.muiName = 'SvgIcon';
export default MapsDirectionsBike;
|
src/Thumbnail.js | Cellule/react-bootstrap | import React from 'react';
import classSet from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Thumbnail = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'thumbnail'
};
},
render() {
let classes = this.getBsClassSet();
if(this.props.href) {
return (
<a {...this.props} href={this.props.href} className={classSet(this.props.className, classes)}>
<img src={this.props.src} alt={this.props.alt} />
</a>
);
}
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;
|
test/test-cases/public-path/src/app.js | seek-oss/sku | import React from 'react';
import styles from './app.less';
export default () => <div className={styles.root} />;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.