path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
docs/src/app/components/pages/components/Badge/Page.js | ArcanisCz/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import badgeReadmeText from './README';
import BadgeExampleSimple from './ExampleSimple';
import badgeExampleSimpleCode from '!raw!./ExampleSimple';
import BadgeExampleContent from './ExampleContent';
import badgeExampleContentCode from '!raw!./ExampleContent';
import badgeCode from '!raw!material-ui/Badge/Badge';
const descriptions = {
simple: 'Two examples of badges containing text, using primary and secondary colors. ' +
'The badge is applied to its children - an icon for the first example, and an ' +
'[Icon Button](/#/components/icon-button) with tooltip for the second.',
further: 'Badges containing an [Icon Button](/#/components/icon-button) and text, ' +
'applied to an icon, and text.',
};
const BadgePage = () => (
<div>
<Title render={(previousTitle) => `Badge - ${previousTitle}`} />
<MarkdownElement text={badgeReadmeText} />
<CodeExample
title="Simple examples"
description={descriptions.simple}
code={badgeExampleSimpleCode}
>
<BadgeExampleSimple />
</CodeExample>
<CodeExample
title="Further examples"
description={descriptions.further}
code={badgeExampleContentCode}
>
<BadgeExampleContent />
</CodeExample>
<PropTypeDescription code={badgeCode} />
</div>
);
export default BadgePage;
|
src/svg-icons/image/filter-2.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilter2 = (props) => (
<SvgIcon {...props}>
<path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-4-4h-4v-2h2c1.1 0 2-.89 2-2V7c0-1.11-.9-2-2-2h-4v2h4v2h-2c-1.1 0-2 .89-2 2v4h6v-2z"/>
</SvgIcon>
);
ImageFilter2 = pure(ImageFilter2);
ImageFilter2.displayName = 'ImageFilter2';
ImageFilter2.muiName = 'SvgIcon';
export default ImageFilter2;
|
featuring-react-gui/src/index.js | ccortezia/featuring | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import 'font-awesome/css/font-awesome.min.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// NOTE: Enable once https deployment is ready.
// registerServiceWorker();
|
app/containers/App.js | lgarcin/LatexElectronReact | // @flow
import React, { Component } from 'react';
export default class App extends Component {
props: {
children: HTMLElement
};
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
|
app/javascript/mastodon/features/mutes/index.js | ebihara99999/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import { ScrollContainer } from 'react-router-scroll';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import AccountContainer from '../../containers/account_container';
import { fetchMutes, expandMutes } from '../../actions/mutes';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'column.mutes', defaultMessage: 'Muted users' },
});
const mapStateToProps = state => ({
accountIds: state.getIn(['user_lists', 'mutes', 'items']),
});
class Mutes extends ImmutablePureComponent {
componentWillMount () {
this.props.dispatch(fetchMutes());
}
handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
if (scrollTop === scrollHeight - clientHeight) {
this.props.dispatch(expandMutes());
}
}
render () {
const { intl, accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
return (
<Column icon='volume-off' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollContainer scrollKey='mutes'>
<div className='scrollable mutes' onScroll={this.handleScroll}>
{accountIds.map(id =>
<AccountContainer key={id} id={id} />
)}
</div>
</ScrollContainer>
</Column>
);
}
}
Mutes.propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
};
export default connect(mapStateToProps)(injectIntl(Mutes));
|
node_modules/antd/es/date-picker/Calendar.js | ZSMingNB/react-news | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import CalendarLocale from 'rc-calendar/es/locale/zh_CN';
import RcCalendar from 'rc-calendar';
import warning from 'warning';
var Calendar = function (_React$Component) {
_inherits(Calendar, _React$Component);
function Calendar() {
_classCallCheck(this, Calendar);
return _possibleConstructorReturn(this, (Calendar.__proto__ || Object.getPrototypeOf(Calendar)).apply(this, arguments));
}
_createClass(Calendar, [{
key: 'render',
value: function render() {
warning(false, 'DatePicker.Calendar is deprecated, use Calendar instead.');
return React.createElement(RcCalendar, this.props);
}
}]);
return Calendar;
}(React.Component);
export default Calendar;
Calendar.defaultProps = {
locale: CalendarLocale,
prefixCls: 'ant-calendar'
}; |
src/components/Footer/index.js | andywillis/uws | // Dependencies
import React from 'react';
// Style
import './style.css';
/**
* @function Header
* @return {jsx} Component
*/
const Header = () => {
return (
<div className="Footer">
© Andy Willis 2017
</div>
);
};
export default Header;
|
node_modules/react-native-admob/RNAdMobBanner.js | odapplications/WebView-with-Lower-Tab-Menu | import React from 'react';
import {
NativeModules,
requireNativeComponent,
View,
NativeEventEmitter,
} from 'react-native';
const RNBanner = requireNativeComponent('RNAdMob', AdMobBanner);
export default class AdMobBanner extends React.Component {
constructor() {
super();
this.onSizeChange = this.onSizeChange.bind(this);
this.state = {
style: {},
};
}
onSizeChange(event) {
const { height, width } = event.nativeEvent;
this.setState({ style: { width, height } });
}
render() {
const { adUnitID, testDeviceID, bannerSize, style, didFailToReceiveAdWithError } = this.props;
return (
<View style={this.props.style}>
<RNBanner
style={this.state.style}
onSizeChange={this.onSizeChange.bind(this)}
onAdViewDidReceiveAd={this.props.adViewDidReceiveAd}
onDidFailToReceiveAdWithError={(event) => didFailToReceiveAdWithError(event.nativeEvent.error)}
onAdViewWillPresentScreen={this.props.adViewWillPresentScreen}
onAdViewWillDismissScreen={this.props.adViewWillDismissScreen}
onAdViewDidDismissScreen={this.props.adViewDidDismissScreen}
onAdViewWillLeaveApplication={this.props.adViewWillLeaveApplication}
testDeviceID={testDeviceID}
adUnitID={adUnitID}
bannerSize={bannerSize} />
</View>
);
}
}
AdMobBanner.propTypes = {
style: View.propTypes.style,
/**
* AdMob iOS library banner size constants
* (https://developers.google.com/admob/ios/banner)
* banner (320x50, Standard Banner for Phones and Tablets)
* largeBanner (320x100, Large Banner for Phones and Tablets)
* mediumRectangle (300x250, IAB Medium Rectangle for Phones and Tablets)
* fullBanner (468x60, IAB Full-Size Banner for Tablets)
* leaderboard (728x90, IAB Leaderboard for Tablets)
* smartBannerPortrait (Screen width x 32|50|90, Smart Banner for Phones and Tablets)
* smartBannerLandscape (Screen width x 32|50|90, Smart Banner for Phones and Tablets)
*
* banner is default
*/
bannerSize: React.PropTypes.string,
/**
* AdMob ad unit ID
*/
adUnitID: React.PropTypes.string,
/**
* Test device ID
*/
testDeviceID: React.PropTypes.string,
/**
* AdMob iOS library events
*/
adViewDidReceiveAd: React.PropTypes.func,
didFailToReceiveAdWithError: React.PropTypes.func,
adViewWillPresentScreen: React.PropTypes.func,
adViewWillDismissScreen: React.PropTypes.func,
adViewDidDismissScreen: React.PropTypes.func,
adViewWillLeaveApplication: React.PropTypes.func,
...View.propTypes,
};
AdMobBanner.defaultProps = { bannerSize: 'smartBannerPortrait', didFailToReceiveAdWithError: () => {} };
|
src/client/auth/login.react.js | terakilobyte/socketreact | import * as actions from './actions';
import Component from '../components/component.react';
import DocumentTitle from 'react-document-title';
import React from 'react';
import exposeRouter from '../components/exposerouter.react';
import immutable from 'immutable';
import {focusInvalidField} from '../../lib/validation';
import {msg} from '../intl/store';
require('./login.styl');
class Login extends Component {
getForm() {
return this.props.auth.get('form');
}
onFormSubmit(e) {
e.preventDefault();
const fields = this.getForm().fields.toJS();
actions.login(fields)
.then(() => {
this.redirectAfterLogin();
})
.catch(focusInvalidField(this));
}
redirectAfterLogin() {
const nextPath = this.props.router.getCurrentQuery().nextPath;
this.props.router.replaceWith(nextPath || '/');
}
render() {
const form = this.getForm();
return (
<DocumentTitle title={msg('auth.title')}>
<div className="login">
<form onSubmit={(e) => this.onFormSubmit(e)}>
<fieldset disabled={actions.login.pending}>
<legend>{msg('auth.form.legend')}</legend>
<input
autoFocus
name="email"
onChange={actions.updateFormField}
placeholder={msg('auth.form.placeholder.email')}
value={form.fields.email}
/>
<br />
<input
name="password"
onChange={actions.updateFormField}
placeholder={msg('auth.form.placeholder.password')}
type="password"
value={form.fields.password}
/>
<br />
<button
children={msg('auth.form.button.login')}
disabled={actions.login.pending}
type="submit"
/>
{/*
<button type="submit">{msg('auth.form.button.signup')}</button>
*/}
{form.error &&
<span className="error-message">{form.error.message}</span>
}
<div>{msg('auth.form.hint')}</div>
</fieldset>
</form>
</div>
</DocumentTitle>
);
}
}
Login.propTypes = {
auth: React.PropTypes.instanceOf(immutable.Map).isRequired,
router: React.PropTypes.func
};
export default exposeRouter(Login);
|
app/components/layout/newProject/MainStepTwo.js | communicode-source/communicode | import React from 'react';
import PropTypes from 'prop-types';
class newProject extends React.Component {
constructor(props) {
super(props);
this.props = props;
}
componentWillMount() {
if(this.props.location !== 2) {
this.props.moveToStepTwo();
}
}
render() {
return (
<div>
<h1>Step 2: Tell us more</h1>
{this.props.children}
</div>
);
}
}
newProject.propTypes = {
location: PropTypes.number,
children: PropTypes.array,
moveToStepTwo: PropTypes.func
};
export default newProject;
|
blueocean-material-icons/src/js/components/svg-icons/editor/format-strikethrough.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const EditorFormatStrikethrough = (props) => (
<SvgIcon {...props}>
<path d="M10 19h4v-3h-4v3zM5 4v3h5v3h4V7h5V4H5zM3 14h18v-2H3v2z"/>
</SvgIcon>
);
EditorFormatStrikethrough.displayName = 'EditorFormatStrikethrough';
EditorFormatStrikethrough.muiName = 'SvgIcon';
export default EditorFormatStrikethrough;
|
app/components/Users/Actions.js | klpdotorg/tada-frontend | import React from 'react';
import PropTypes from 'prop-types';
const ActionsView = (props) => {
return (
<div>
<button className="btn btn-primary delete-users-button" onClick={props.deleteUsers}>
Delete
</button>
<button className="btn btn-primary">Deactivate</button>
</div>
);
};
ActionsView.propTypes = {
deleteUsers: PropTypes.func,
};
export { ActionsView };
|
internals/templates/containers/HomePage/index.js | kaizen7-nz/gold-star-chart | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
src/components/views/delegatesList/components/introduction/Description.js | LiskHunt/LiskHunt | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { bindActionCreators } from 'redux';
class Description extends Component {
render() {
return (
<div className="column">
<h1>Delegates-hunt</h1>
<div className="delegate-hunt--description">
The delegates bringing Lisk to the next level, sorted by coolness
score. A super-duper index to show how the delegate is contributing to
the Lisk ecosystem.
</div>
<div className="delegate-hunt--description">
The coolness score is calculated by adding the amount of Apps the
delegate developed, the amount of received likes and the amount of
donations made.
</div>
<div className="delegates-participate">
<span> </span>
<div className="participate">
<div className="level-item topbar-button">
<a onClick={() => this.props.goSubmitHunt()}>
<div className="topbar-button-label">SIGN UP</div>
</a>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => ({});
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
goSubmitHunt: () => push('/submit-hunt'),
},
dispatch,
);
export default connect(mapStateToProps, mapDispatchToProps)(Description);
|
src/components/Feedback/Feedback.js | sbassan/Kingsthorpe | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Feedback.scss';
function Feedback() {
return (
<div className={s.root}>
<div className={s.container}>
<a
className={s.link}
href="https://gitter.im/kriasoft/react-starter-kit"
>Ask a question</a>
<span className={s.spacer}>|</span>
<a
className={s.link}
href="https://github.com/kriasoft/react-starter-kit/issues/new"
>Report an issue</a>
</div>
</div>
);
}
export default withStyles(Feedback, s);
|
native/app/components/Search.js | madison-kerndt/native | import React, { Component } from 'react';
import connect from 'react-redux';
import {
AsyncStorage,
StyleSheet,
Text,
TouchableHighlight,
View,
Button,
ScrollView,
TextInput,
Image,
WebView,
ListView,
Linking
} from 'react-native';
import { client_id, client_secret, grant_type } from '../../env.json';
let endPoint = "https://api.producthunt.com/v1/";
const headerInfo = {
accept: "application/json",
"content-type": "application/json",
host: "api.producthunt.com"
};
import postsContainer from '../containers/postsContainer';
import userContainer from '../containers/userContainer';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm: '',
credentials: {}
};
}
componentWillMount(){
this.authenticate();
}
authenticate() {
fetch(`${endPoint}oauth/token`, {
method: "POST",
headers: headerInfo,
body: JSON.stringify({
client_id: client_id,
client_secret: client_secret,
grant_type: grant_type,
})
})
.then((res) => { return res.json(); })
.then((response) => { this.setState({ credentials: response }); })
.catch((err) => { alert(err); })
}
fetchPosts() {
fetch(`${endPoint}posts/all?search[topic]=${this.state.searchTerm.toLowerCase()}`, {
method: "GET",
headers: {
headerInfo,
authorization: `Bearer ${this.state.credentials.access_token}`
}
})
.then((res) => { return res.json(); })
.then((response) => this.props.getPosts(response.posts))
.then(this.setState({ searchTerm: ''}))
.catch(() => { alert('Please try a different search term'); })
}
loadPosts() {
return this.props.posts.toJS().map((post, i) => {
return(
<View
key={i}
style={{ height: 70 }}>
<Image
style={ styles.searchItemImg }
source={{ uri: `${post.thumbnail.image_url}` }}/>
<Text
style={ styles.searchItemTitle}>
{ post.name }
</Text>
</View>
)
})
}
render() {
return (
<View style={ styles.searchMain }>
<Text>Search for Products</Text>
<TextInput
style={ styles.searchInput }
onChangeText={ (searchTerm) => this.setState({ searchTerm })}
value={ this.state.searchTerm }
/>
<Button
onPress={ () => this.fetchPosts() }
title='Get Posts'
/>
<ScrollView style={ styles.ScrollView }>
{ this.loadPosts() }
</ScrollView>
</View>
)
}
}
export default postsContainer(
userContainer(Search)
)
const styles = StyleSheet.create({
searchMain: {
backgroundColor: '#fff',
margin: 20,
marginTop: 75,
},
searchInput: {
height: 55,
borderRadius: 3,
borderWidth: 1,
borderColor: '#999999',
marginTop: 10
},
postName: {
width: 100,
height: 100,
},
scrollView: {
top: 20,
height: 400
},
searchItemImg: {
width: 50,
height: 50,
marginLeft: 10
},
searchItemTitle: {
width: 300,
height: 50,
marginLeft: 70,
marginTop: -35,
}
});
|
src/common/SpellLink.js | mwwscott0/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import SPELLS from './SPELLS';
const SpellLink = ({ id, children, category = undefined, ...other }) => {
if (process.env.NODE_ENV === 'development' && !children && !SPELLS[id]) {
throw new Error(`Unknown spell: ${id}`);
}
return (
<a href={`http://www.wowhead.com/spell=${id}`} target="_blank" rel="noopener noreferrer" className={category} {...other}>
{children || SPELLS[id].name}
</a>
);
};
SpellLink.propTypes = {
id: PropTypes.number.isRequired,
children: PropTypes.node,
category: PropTypes.string,
};
export default SpellLink;
|
components/Perfil.js | wrariza/wrariza | import React from 'react'
import styled, { keyframes } from 'styled-components'
import { Row, Col , BASE_CONF} from 'react-styled-flexboxgrid'
import Icon from 'react-icons-kit'
import { linkedinSquare, github, graduationCap } from 'react-icons-kit/fa/'
const Container = styled(Row)`
width: 100%;
margin-top: 10px;
`
const Imgen = styled.div`
width: 160px;
height: 160px;
border-radius: 100%;
background-image: url('/static/img/perfil.jpg');
margin: auto;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
background-repeat: no-repeat;
background-position: 0px 0px;
color: transparent;
margin: auto;
background-size: contain;
&:hover {
opacity: 0.5;
color: white;
}
`
const Info = styled(Row)`
{
padding: 15px 0px 15px 2px;
font-size: 10px;
height: 50px;
display: flex;
justify-content: center;
}
`
function Perfil() {
return(
<Container xs={12}>
<Col xs={4} xsOffset={4} >
<Imgen>WILLIAM RICARDO ARIZA VÉLEZ</Imgen>
<Info center="xs" center="lg">
<Col>
<a href="https://www.linkedin.com/in/wrariza/" target="_blank">
<Icon icon={linkedinSquare}/>
</a>
</Col>
<Col>
<a href="https://github.com/wrariza" target="_blank">
<Icon icon={github}/>
</a>
</Col>
<Col>
<a href="https://platzi.com/@wrariza/" target="_blank">
<Icon icon={graduationCap}/>
</a>
</Col>
</Info>
</Col>
</Container>
)
}
export default Perfil |
www/src/pages/components/jumbotron.js | glenjamin/react-bootstrap | import { graphql } from 'gatsby';
import React from 'react';
import LinkedHeading from '../../components/LinkedHeading';
import ComponentApi from '../../components/ComponentApi';
import ReactPlayground from '../../components/ReactPlayground';
import JumbotronBasic from '../../examples/Jumbotron/Basic';
import JumbotronFluid from '../../examples/Jumbotron/Fluid';
import withLayout from '../../withLayout';
export default withLayout(function JumbotronSection({ data }) {
return (
<>
<LinkedHeading h="1" id="jumbotron">
Jumbotron
</LinkedHeading>
<p className="lead">
A lightweight, flexible component that can optionally extend the entire
viewport to showcase key content on your site.
</p>
<ReactPlayground codeText={JumbotronBasic} />
<ReactPlayground codeText={JumbotronFluid} />
<LinkedHeading h="2" id="jumbotron-api">
API
</LinkedHeading>
<ComponentApi metadata={data.Jumbotron} />
</>
);
});
export const query = graphql`
query JumbotronQuery {
Jumbotron: componentMetadata(displayName: { eq: "Jumbotron" }) {
displayName
...ComponentApi_metadata
}
}
`;
|
app/js/components/layout.js | leon-4A6C/tplay | import React from 'react';
import MainInfo from "./mainInfo.js";
import Page from "./page.js";
// import Settings from "./settings.js";
// import Nav from "./nav.js";
import Player from "./player.js";
export default class Layout extends React.Component {
constructor(props) {
super(props)
this.state = {
pages: [
<Page key="tv" type="tv" name="tv-shows"></Page>
]
}
}
render() {
return (
<div className="main">
<nav>
</nav>
<main>
{this.state.pages}
</main>
<MainInfo></MainInfo>
<Player></Player>
</div>
)
}
}
|
app/views/Routes.js | bboysathish/react-boilerplate | import React from 'react';
import { Link, Match, Miss } from 'react-router';
import Home from './Home';
const NoMatch = () => (<div className="text-center">
<h3 className="text-danger">{ `404: Page not found!` } </h3>
<Link to="/">{ `Back To Home` }</Link>
</div>);
const RouteConfig = () => (
<div>
<Match exactly pattern="/" component={ Home } />
<Miss component={ NoMatch } />
</div>
);
export default RouteConfig;
|
services/ui/src/components/errors/ProjectNotFound.js | amazeeio/lagoon | import React from 'react';
import ErrorPage from 'pages/_error';
export default ({ variables }) => (
<ErrorPage
statusCode={404}
errorMessage={`Project "${variables.name}" not found`}
/>
);
|
js/components/home.js | frequencyasia/website | import React from 'react';
import $ from 'jquery';
import { Link } from 'react-router-component';
require('swiper');
import i18next from 'i18next';
import Constants from './../constants';
module.exports = React.createClass({
propTypes: {
nowPlayingSlug: React.PropTypes.string.isRequired,
},
numShowcaseItems: 5,
getInitialState: function getInitialState() {
return {
episodes: [],
};
},
componentDidMount: function componentDidMount() {
document.title = 'Frequency Asia';
$.getJSON(`${Constants.API_URL}episodes/released?length=${this.numShowcaseItems}&showcase=true`)
.done((data) => {
this.setState({ episodes: data.episodes });
});
},
renderNowPlaying: function renderNowPlaying(episodeSlug) {
if (episodeSlug === this.props.nowPlayingSlug) {
return ` [${i18next.t('nowPlaying')}]`;
}
return '';
},
renderSlide: function renderSlide(episode) {
const style = {
'background': 'linear-gradient(to right, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("/static/files/' + episode.wide_image_path + '") no-repeat center center',
'WebkitBackgroundSize': 'cover',
'MozBackgroundSize': 'cover',
'OBackgroundSize': 'cover',
'backgroundSize': 'cover',
};
const link = '/shows/' + episode.show.slug;
return (
<div className="swiper-slide" style={ style } key={ episode.id }>
<div className="c-featured-item">
<div className="c-featured-item__background"></div>
<article className="c-featured-item__container">
<h1 className="c-featured-item__container__title">{ episode.show.name }{ this.renderNowPlaying(episode) }</h1>
<p className="c-featured-item__container__tagline">{ episode.tagline }</p>
<p className="c-featured-item__container__tagline"><Link href={ link }>{ i18next.t('seeAllEpisodes') }</Link></p>
</article>
</div>
</div>
);
},
render: function render() {
return (
<div className="o-feature-slider">
<div className="swiper-container">
<div className="swiper-wrapper">
{ this.state.episodes.map((episode) => { return this.renderSlide(episode); }) }
</div>
<div className="swiper-pagination"></div>
<div className="swiper-button-next"></div>
<div className="swiper-button-prev"></div>
</div>
</div>
);
},
componentDidUpdate: function componentDidUpdate() {
this.initSwiper();
},
initSwiper: function initSwiper() {
// Needs to be triggered after Virtual DOM is attached.
if ($('.swiper-container').length) {
this.swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
preventClicks: false,
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
keyboardControl: true,
autoplay: 5000,
});
}
},
});
|
src/svg-icons/editor/short-text.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorShortText = (props) => (
<SvgIcon {...props}>
<path d="M4 9h16v2H4zm0 4h10v2H4z"/>
</SvgIcon>
);
EditorShortText = pure(EditorShortText);
EditorShortText.displayName = 'EditorShortText';
EditorShortText.muiName = 'SvgIcon';
export default EditorShortText;
|
local-cli/templates/HelloWorld/index.android.js | Ehesp/react-native | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class HelloWorld extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
|
frontend/src/courses/index.js | OptimusCrime/youkok2 | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import LoaderWrapperContainer from './containers/loader-wrapper/loader-wrapper';
import configureStore from './redux/configureStore';
import {getSearchFromUrl, queryPresentInUrl} from "./prefill";
import {COURSES_UPDATE_SEARCH} from "./redux/courses/constants";
export const run = () => {
const preloadedState = window.__INITIAL_STATE__;
const store = configureStore(preloadedState);
ReactDOM.render((
<Provider store={store}>
<LoaderWrapperContainer />
</Provider>
), document.getElementById('courses')
);
// Check if we have search parameters from the URI
if (queryPresentInUrl()) {
const searchValue = getSearchFromUrl();
if (searchValue !== null) {
store.dispatch({ type: COURSES_UPDATE_SEARCH, value: searchValue });
}
}
};
|
modules/SearchResults/Carousel2.js | cloudytimemachine/frontend | import React from 'react'
import Carousel from 'nuka-carousel'
import moment from 'moment'
export default React.createClass({
mixins: [Carousel.ControllerMixin],
getInitialState() {
return { finished: false,
slideIndex: 0,
sliderVal: 0,
sliderMin: 0,
sliderMax: 0,
leftLabel: 0,
rightLabel: 0 }
},
setSliderState(val) {
this.setState({slideIndex: val});
console.log("setting slideIndex: "+ val);
},
handleChange(e) {
var oldSlider = this.state.sliderVal;
var newSlider = e.target.value;
if (newSlider > oldSlider) {
this.refs.carousel.nextSlide();
} else {
this.refs.carousel.previousSlide();
}
this.setSliderState(newSlider);
},
getMetaData() {
if (this.state.finished) {
let data = this.props.results[this.state.slideIndex];
let timeAgo = moment(data.createdAt).fromNow();
return (
<div className="meta-information">
<dl>
<dt>ID:</dt><dd> {data.id} </dd>
<dt>Created:</dt><dd> {timeAgo} </dd>
<dt>Host:</dt><dd> {data.host}</dd>
<dt>Req'd Url:</dt><dd> {data.requestedUrl}</dd>
</dl>
</div>);
}
else return (<div>Loading</div>);
},
componentWillReceiveProps: function(nextprops) {
this.initializeSlider(nextprops);
},
initializeSlider: function(p) {
console.log('initializing slider with new data from nextprops');
let sliderMin = 0;
let length = p.results.length;
console.log(`length: ${length}`);
let sliderMax = length-1;
console.log(`sliderMax: ${sliderMax}`);
let leftlabel = moment(p.results[0].createdAt).fromNow();
console.log(`leftLabel: ${leftlabel}`);
let rightlabel = moment(p.results[length-1].createdAt).fromNow();
console.log(`rightLabel: ${rightlabel}`);
this.setState({ finished: true,
slideIndex: sliderMax,
sliderMin: sliderMin,
sliderMax: sliderMax,
leftLabel: leftlabel,
rightLabel: rightlabel });
},
render() {
var carouselNodes = this.props.results.map(function(result) {
return ( <img key={result.id} src={result.originalImage} onLoad={() => {window.dispatchEvent(new Event('resize'));}} /> );
});
var Decorators = [{
component: React.createClass({
render() {
return ( null );
}
}),
}];
return (
<div>
<div className="capture-details">
<fieldset>
<input type="range" min={this.state.sliderMin} max={this.state.sliderMax} value={this.state.slideIndex} onChange={(e)=>this.handleChange(e)}/>
<label className="leftlabel pull-left">{this.state.leftLabel}</label>
<label className="rightlabel pull-right">{this.state.rightLabel}</label>
</fieldset>
<Carousel
ref="carousel"
decorators={Decorators}
data={this.setCarouselData.bind(this, 'carousel')}
slideIndex={parseInt(this.state.slideIndex)}
afterSlide={newSlideIndex => this.setState({ slideIndex: newSlideIndex })}
dragging={false}>
{carouselNodes}
</Carousel>
</div>
{this.getMetaData()}
</div>
)
}
})
|
frontend/jqwidgets/jqwidgets-react/react_jqxcheckbox.js | yevgeny-sergeyev/nexl-js | /*
jQWidgets v5.7.2 (2018-Apr)
Copyright (c) 2011-2018 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxCheckBox extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['animationShowDelay','animationHideDelay','boxSize','checked','disabled','enableContainerClick','groupName','height','hasThreeStates','locked','rtl','theme','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxCheckBox(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxCheckBox('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxCheckBox(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
animationShowDelay(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('animationShowDelay', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('animationShowDelay');
}
};
animationHideDelay(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('animationHideDelay', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('animationHideDelay');
}
};
boxSize(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('boxSize', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('boxSize');
}
};
checked(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('checked', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('checked');
}
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('disabled');
}
};
enableContainerClick(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('enableContainerClick', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('enableContainerClick');
}
};
groupName(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('groupName', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('groupName');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('height', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('height');
}
};
hasThreeStates(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('hasThreeStates', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('hasThreeStates');
}
};
locked(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('locked', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('locked');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('rtl');
}
};
theme(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('theme', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('theme');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('width', arg)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('width');
}
};
check() {
JQXLite(this.componentSelector).jqxCheckBox('check');
};
disable() {
JQXLite(this.componentSelector).jqxCheckBox('disable');
};
destroy() {
JQXLite(this.componentSelector).jqxCheckBox('destroy');
};
enable() {
JQXLite(this.componentSelector).jqxCheckBox('enable');
};
focus() {
JQXLite(this.componentSelector).jqxCheckBox('focus');
};
indeterminate() {
JQXLite(this.componentSelector).jqxCheckBox('indeterminate');
};
performRender() {
JQXLite(this.componentSelector).jqxCheckBox('render');
};
toggle() {
JQXLite(this.componentSelector).jqxCheckBox('toggle');
};
uncheck() {
JQXLite(this.componentSelector).jqxCheckBox('uncheck');
};
val(value) {
if (value !== undefined) {
JQXLite(this.componentSelector).jqxCheckBox('val', value)
} else {
return JQXLite(this.componentSelector).jqxCheckBox('val');
}
};
render() {
let id = 'jqxCheckBox' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}><span>{this.props.value}</span></div>
)
};
};
|
web/src/client/main.js | neozhangthe1/framedrop-web | import React from 'react';
import ReactDOM from 'react-dom';
import Router from 'react-router';
import {configureStore} from '../../../common';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import createRoutes from './createRoutes';
import {IntlProvider} from 'react-intl';
import {Provider} from 'react-redux';
const app = document.getElementById('app');
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState);
const routes = createRoutes(() => store.getState());
ReactDOM.render(
<Provider store={store}>
<IntlProvider>
<Router history={createBrowserHistory()}>
{routes}
</Router>
</IntlProvider>
</Provider>,
app
);
|
src/components/youtube/VideoDetail.js | notMasterpiece/youtube | import React from 'react';
const VideoDetail = ({video}) => {
console.log(video);
if( !video ) return <div className="col-sm-8"><div>Loading...</div></div>;
console.log(video);
const videoId = video.id.videoId;
// console.log(videoId);
const videoUrl = `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={videoUrl} frameBorder="0"></iframe>
</div>
<div className="video-detail">
<h1 className='video-detail__title'>{video.snippet.title}</h1>
<div className='video-detail__descr'>{video.snippet.description}</div>
</div>
</div>
)
};
export default VideoDetail; |
packages/xo-web/src/common/timezone-picker.js | vatesfr/xo-web | import ActionButton from 'action-button'
import map from 'lodash/map'
import moment from 'moment-timezone'
import PropTypes from 'prop-types'
import React from 'react'
import _ from './intl'
import Component from './base-component'
import { getXoServerTimezone } from './xo'
import { Select } from './form'
const SERVER_TIMEZONE_TAG = 'server'
const LOCAL_TIMEZONE = moment.tz.guess()
export default class TimezonePicker extends Component {
static propTypes = {
defaultValue: PropTypes.string,
onChange: PropTypes.func.isRequired,
required: PropTypes.bool,
value: PropTypes.string,
}
componentDidMount() {
getXoServerTimezone.then(serverTimezone => {
this.setState({
timezone: this.props.value || this.props.defaultValue || SERVER_TIMEZONE_TAG,
options: [
...map(moment.tz.names(), value => ({ label: value, value })),
{
label: _('serverTimezoneOption', {
value: serverTimezone,
}),
value: SERVER_TIMEZONE_TAG,
},
],
})
})
}
componentWillReceiveProps(props) {
if (props.value !== this.props.value) {
this.setState({ timezone: props.value || SERVER_TIMEZONE_TAG })
}
}
get value() {
return this.state.timezone === SERVER_TIMEZONE_TAG ? null : this.state.timezone
}
set value(value) {
this.setState({ timezone: value || SERVER_TIMEZONE_TAG })
}
_onChange = option => {
if (option && option.value === this.state.timezone) {
return
}
this.setState(
{
timezone: (option != null && option.value) || SERVER_TIMEZONE_TAG,
},
() => this.props.onChange(this.state.timezone === SERVER_TIMEZONE_TAG ? null : this.state.timezone)
)
}
_useLocalTime = () => {
this._onChange({ value: LOCAL_TIMEZONE })
}
render() {
const { timezone, options } = this.state
return (
<div>
<Select
className='mb-1'
onChange={this._onChange}
options={options}
placeholder={_('selectTimezone')}
required={this.props.required}
value={timezone}
/>
<div className='pull-right'>
<ActionButton handler={this._useLocalTime} icon='time'>
{_('timezonePickerUseLocalTime')}
</ActionButton>
</div>
</div>
)
}
}
|
templates/rubix/rubix-bootstrap/src/Well.js | jeffthemaximum/Teachers-Dont-Pay-Jeff | import React from 'react';
import classNames from 'classnames';
import BWell from 'react-bootstrap/lib/Well';
export default class Well extends React.Component {
static propTypes = {
sm: React.PropTypes.bool,
lg: React.PropTypes.bool,
noMargin: React.PropTypes.bool,
};
render() {
let props = {...this.props};
if (props.hasOwnProperty('sm')) {
props.bsSize = 'sm';
delete props.sm;
}
if (props.hasOwnProperty('lg')) {
props.bsSize = 'lg'
delete props.lg;
}
if (props.hasOwnProperty('noMargin')) {
props.style = props.style || {};
props.style.margin = 0;
}
return <BWell {...props} />;
}
}
|
src/components/Todo/TodoFooter.js | divyanshu013/impulse-tabs | import React from 'react';
import FontIcon from 'material-ui/FontIcon';
import { BottomNavigation, BottomNavigationItem } from 'material-ui/BottomNavigation';
const recentsIcon = <FontIcon className="material-icons">home</FontIcon>;
const favoritesIcon = <FontIcon className="material-icons">favorite</FontIcon>;
let selectedIndex = 0;
const select = (index) => {
selectedIndex = index;
console.log('selected', index);
};
const TodoFooter = () => (
<BottomNavigation selectedIndex={selectedIndex}>
<BottomNavigationItem
label="Recents"
icon={recentsIcon}
onTouchTap={() => select(0)}
/>
<BottomNavigationItem
label="Favorites"
icon={favoritesIcon}
onTouchTap={() => select(1)}
/>
</BottomNavigation>
);
export default TodoFooter;
|
src/client.js | taekungngamonosus/monoreact | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import deepForceUpdate from 'react-deep-force-update';
import queryString from 'query-string';
import { createPath } from 'history/PathUtils';
import App from './components/App';
import createFetch from './createFetch';
import history from './history';
import { updateMeta } from './DOMUtils';
import router from './router';
/* eslint-disable global-require */
// Global (context) variables that can be easily accessed from any React component
// https://facebook.github.io/react/docs/context.html
const context = {
// Enables critical path CSS rendering
// https://github.com/kriasoft/isomorphic-style-loader
insertCss: (...styles) => {
// eslint-disable-next-line no-underscore-dangle
const removeCss = styles.map(x => x._insertCss());
return () => {
removeCss.forEach(f => f());
};
},
// Universal HTTP client
fetch: createFetch(self.fetch, {
baseUrl: window.App.apiUrl,
}),
};
// Switch off the native scroll restoration behavior and handle it manually
// https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration
const scrollPositionsHistory = {};
if (window.history && 'scrollRestoration' in window.history) {
window.history.scrollRestoration = 'manual';
}
let onRenderComplete = function initialRenderComplete() {
const elem = document.getElementById('css');
if (elem) elem.parentNode.removeChild(elem);
onRenderComplete = function renderComplete(route, location) {
document.title = route.title;
updateMeta('description', route.description);
// Update necessary tags in <head> at runtime here, ie:
// updateMeta('keywords', route.keywords);
// updateCustomMeta('og:url', route.canonicalUrl);
// updateCustomMeta('og:image', route.imageUrl);
// updateLink('canonical', route.canonicalUrl);
// etc.
let scrollX = 0;
let scrollY = 0;
const pos = scrollPositionsHistory[location.key];
if (pos) {
scrollX = pos.scrollX;
scrollY = pos.scrollY;
} else {
const targetHash = location.hash.substr(1);
if (targetHash) {
const target = document.getElementById(targetHash);
if (target) {
scrollY = window.pageYOffset + target.getBoundingClientRect().top;
}
}
}
// Restore the scroll position if it was saved into the state
// or scroll to the given #hash anchor
// or scroll to top of the page
window.scrollTo(scrollX, scrollY);
// Google Analytics tracking. Don't send 'pageview' event after
// the initial rendering, as it was already sent
if (window.ga) {
window.ga('send', 'pageview', createPath(location));
}
};
};
const container = document.getElementById('app');
let appInstance;
let currentLocation = history.location;
// Re-render the app when window.location changes
async function onLocationChange(location, action) {
// Remember the latest scroll position for the previous location
scrollPositionsHistory[currentLocation.key] = {
scrollX: window.pageXOffset,
scrollY: window.pageYOffset,
};
// Delete stored scroll position for next page if any
if (action === 'PUSH') {
delete scrollPositionsHistory[location.key];
}
currentLocation = location;
try {
// Traverses the list of routes in the order they are defined until
// it finds the first route that matches provided URL path string
// and whose action method returns anything other than `undefined`.
const route = await router.resolve({
...context,
path: location.pathname,
query: queryString.parse(location.search),
});
// Prevent multiple page renders during the routing process
if (currentLocation.key !== location.key) {
return;
}
if (route.redirect) {
history.replace(route.redirect);
return;
}
appInstance = ReactDOM.render(
<App context={context}>
{route.component}
</App>,
container,
() => onRenderComplete(route, location),
);
} catch (error) {
if (__DEV__) {
throw error;
}
console.error(error);
// Do a full page reload if error occurs during client-side navigation
if (action && currentLocation.key === location.key) {
window.location.reload();
}
}
}
// Handle client-side navigation by using HTML5 History API
// For more information visit https://github.com/mjackson/history#readme
history.listen(onLocationChange);
onLocationChange(currentLocation);
// Enable Hot Module Replacement (HMR)
if (module.hot) {
module.hot.accept('./router', () => {
if (appInstance) {
// Force-update the whole tree, including components that refuse to update
deepForceUpdate(appInstance);
}
onLocationChange(currentLocation);
});
}
|
src/components/Result.js | lukaszmakuch/quiz | import React, { Component } from 'react';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';
import Paper from 'material-ui/Paper';
import Table, { TableBody, TableCell, TableRow, TableFooter } from 'material-ui/Table';
const Frame = props =>
<Grid
container
style={({
flex: 1,
display: 'flex',
maxWidth: "100%"
})}
align="center"
justify="center"
direction="column"
>
{props.children}
</Grid>
export default class Result extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
const result = this.props.result();
return <Frame>
<Grid
item
xs={12}
>
<Paper>
<Table className="result">
<TableBody>
<TableRow>
<TableCell>Correct answers</TableCell>
<TableCell numeric>
<span className="result-correct-answers">
{result.correctAnswers}
</span>
</TableCell>
</TableRow>
<TableRow>
<TableCell>Wrong answers</TableCell>
<TableCell numeric>
<span className="result-wrong-answers">
{result.wrongAnswers}
</span>
</TableCell>
</TableRow>
<TableRow>
<TableCell>Number of questions</TableCell>
<TableCell numeric>
<span className="result-number-of-questions">
{result.questions}
</span>
</TableCell>
</TableRow>
</TableBody>
{this.props.finished && <TableFooter>
<TableRow>
<TableCell colSpan={2} style={{textAlign: "right"}}>
<Button onClick={this.props.tryAgain}>
Try again
</Button>
</TableCell>
</TableRow>
</TableFooter>}
</Table>
</Paper>
</Grid>
</Frame>
};
} |
packages/material-ui-icons/src/Subscriptions.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Subscriptions = props =>
<SvgIcon {...props}>
<path d="M20 8H4V6h16v2zm-2-6H6v2h12V2zm4 10v8c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2v-8c0-1.1.9-2 2-2h16c1.1 0 2 .9 2 2zm-6 4l-6-3.27v6.53L16 16z" />
</SvgIcon>;
Subscriptions = pure(Subscriptions);
Subscriptions.muiName = 'SvgIcon';
export default Subscriptions;
|
views/decoration_toggle.js | jacobmarshall/black-screen | import React from 'react';
export default React.createClass({
getInitialState() {
return {enabled: this.props.invocation.state.decorate};
},
handleClick(event) {
stopBubblingUp(event);
var newState = !this.state.enabled;
this.setState({enabled: newState});
this.props.invocation.setState({decorate: newState});
},
render() {
var classes = ['decoration-toggle'];
if (!this.state.enabled) {
classes.push('disabled');
}
return (
<a href="#" className={classes.join(' ')} onClick={this.handleClick}>
<i className="fa fa-magic"></i>
</a>
);
}
});
|
test/integration/client-navigation/pages/link.js | azukaru/next.js | import React from 'react'
import Link from 'next/link'
export default () => (
<div>
Hello World.{' '}
<Link href="/about">
<a>About</a>
</Link>
</div>
)
|
src/js/components/Qikshot.js | grommet/grommet-qikshot | import React, { Component } from 'react';
import { browserHistory } from 'react-router';
import Anchor from 'grommet/components/Anchor';
import Button from 'grommet/components/Button';
import Box from 'grommet/components/Box';
import FormField from 'grommet/components/FormField';
import Form from 'grommet/components/Form';
import ImageField from 'grommet/components/ImageField';
import FormFields from 'grommet/components/FormFields';
import Footer from 'grommet/components/Footer';
import Notification from 'grommet/components/Notification';
import Header from 'grommet/components/Header';
import Heading from 'grommet/components/Heading';
import Responsive from 'grommet/utils/Responsive';
import PreviousIcon from 'grommet/components/icons/base/LinkPrevious';
import CameraIcon from 'grommet/components/icons/base/Camera';
import SpinningIcon from 'grommet/components/icons/Spinning';
import { hrefExtractorHandler, setDocumentTitle } from '../utils/qikshot';
import { addPost } from '../Api';
export default class Qikshot extends Component {
constructor () {
super();
this._onResponsive = this._onResponsive.bind(this);
this._onSubmit = this._onSubmit.bind(this);
this._onTitleChange = this._onTitleChange.bind(this);
this._onHashtagChange = this._onHashtagChange.bind(this);
this._onImageChange = this._onImageChange.bind(this);
this._onImageDescriptionChange = this._onImageDescriptionChange.bind(this);
this._onAddPostSucceed = this._onAddPostSucceed.bind(this);
this._onAddPostFailed = this._onAddPostFailed.bind(this);
this.state = {
small: false,
errors: {},
post: {},
adding: false
};
}
componentDidMount () {
setDocumentTitle('Take Quickshot');
this._responsive = Responsive.start(this._onResponsive);
}
componentWillUnmount () {
this._responsive.stop();
}
_onSubmit (event) {
event.preventDefault();
const post = this.state.post;
this.setState({
errors: {}
});
let errors = {};
let noErrors = true;
if (!post.image) {
errors.image = 'required';
noErrors = false;
} else if (post.image && !/^image.*$/.exec(post.image.type)) {
errors.image = 'not an image';
noErrors = false;
}
if (!post.title || post.title === '') {
errors.title = 'required';
noErrors = false;
}
if (!post.hashtag || post.hashtag === '') {
errors.hashtag = 'required';
noErrors = false;
}
if (!post.imageDescription || post.imageDescription === '') {
errors.imageDescription = 'required';
noErrors = false;
}
if (noErrors) {
this.setState({ adding: true });
post.hashtag = post.hashtag.replace(/#/g, '');
addPost(post).then(
this._onAddPostSucceed, this._onAddPostFailed
);
} else {
this.setState({ errors: errors });
}
}
_onAddPostSucceed () {
browserHistory.push('/');
}
_onAddPostFailed (error) {
this.setState({
error: 'Could not add post, please try again.',
adding: false
});
}
_onResponsive (small) {
this.setState({ small: small });
}
_onTitleChange (event) {
let post = { ...this.state.post };
post.title = event.target.value;
this.setState({ post: post });
}
_onHashtagChange (event) {
let post = { ...this.state.post };
post.hashtag = event.target.value;
this.setState({ post: post });
}
_onImageDescriptionChange (event) {
let post = { ...this.state.post };
post.imageDescription = event.target.value;
this.setState({ post: post });
}
_onImageChange (image) {
let post = { ...this.state.post };
post.image = image;
this.setState({ post: post });
}
render () {
const { adding, error, errors, post } = this.state;
let errorNode;
if (error) {
errorNode = (
<Box pad={{ vertical: 'small' }}>
<Notification status="critical"
message={this.state.error} size='small' />
</Box>
);
}
let tag = 'h2';
let footerNode;
let buttonNode;
const loading = (
<Box direction="row" responsive={false}
pad={{between: 'small'}}>
<SpinningIcon />
<span>Adding...</span>
</Box>
);
if (this.state.small) {
tag = 'h3';
let onClick = this._onSubmit;
let heading = <Heading tag='h4' strong={true}>Post Quickshot</Heading>;
if (adding) {
onClick = undefined;
heading = loading;
}
footerNode = (
<Footer colorIndex='brand' flush={true} justify='center' size='small'
float={true} fixed={true} pad='large' onClick={onClick}>
{heading}
</Footer>
);
} else {
let buttonBody = (
<Button primary={true} type="submit" label={"Post Quickshot"}
onClick={this._onSubmit} />
);
if (adding) {
buttonBody = loading;
}
buttonNode = (
<Footer pad={{vertical: 'small'}}>
{buttonBody}
</Footer>
);
}
return (
<div>
<Header direction="row" large={true} justify='between'
pad={{horizontal: 'medium', vertical: 'small'}}>
<Anchor href='/' onClick={hrefExtractorHandler}
icon={
<PreviousIcon size='medium'
colorIndex='brand' a11yTitle='Go Back' />
} />
<Heading tag={tag} strong={true}>
Qikshot
</Heading>
<span style={{width: "48px"}} />
</Header>
<Box pad={{horizontal: 'large'}}>
<Heading tag='h2'>Upload</Heading>
{errorNode}
<Form onSubmit={this._onSubmit}>
<FormFields>
<fieldset>
<ImageField id="image" label="Image" name="image"
value={post.image} error={errors.image} icon={CameraIcon}
onChange={this._onImageChange} />
<FormField label="Title" htmlFor="titleInput"
error={errors.title}>
<input id="titleInput" name="title" type="text"
ref="titleInput" onChange={this._onTitleChange} />
</FormField>
<FormField label="Tags" htmlFor="hashtagInput"
help='event hashtag, text-only no hash'
error={errors.hashtag}>
<input id="hashtagInput" name="hashtag" type="text"
ref="hashtagInput" onChange={this._onHashtagChange} />
</FormField>
<FormField label="Image Description"
htmlFor="imageDescriptionInput"
help='important for accessibility'
error={errors.imageDescription}>
<textarea id="imageDescriptionInput" name="imageDescription"
rows="5" ref="imageDescriptionInput"
onChange={this._onImageDescriptionChange} />
</FormField>
</fieldset>
{buttonNode}
</FormFields>
</Form>
</Box>
{footerNode}
</div>
);
}
};
|
public/js/cat_source/es6/components/header/manage/SearchInput.js | matecat/MateCat | import React from 'react'
import _ from 'lodash'
class SearchInput extends React.Component {
constructor(props) {
super(props)
this.onKeyPressEvent = this.onKeyPressEvent.bind(this)
let self = this
this.filterByNameDebounce = _.debounce(function (e) {
self.filterByName(e)
}, 500)
}
filterByName(e) {
if ($(this.textInput).val().length) {
$(this.closeIcon).show()
} else {
$(this.closeIcon).hide()
}
this.props.onChange($(this.textInput).val())
return false
}
closeSearch() {
$(this.textInput).val('')
$(this.closeIcon).hide()
this.props.onChange($(this.textInput).val())
}
onKeyPressEvent(e) {
if (e.which == 27) {
this.closeSearch()
} else {
if (e.which == 13 || e.keyCode == 13) {
e.preventDefault()
return false
}
}
}
componentDidUpdate() {
$(this.textInput).val('')
}
render() {
return (
<input
className="search-projects"
type="text"
placeholder="Search by project name"
ref={(input) => (this.textInput = input)}
onChange={this.filterByNameDebounce.bind(this)}
onKeyPress={this.onKeyPressEvent.bind(this)}
data-testid="input-search-projects"
/>
/*<div className="input-field">
<div className="ui fluid icon input">
<input id="search" type="search" required="required"
placeholder="Search by project name"
ref={(input) => this.textInput = input}
onChange={this.filterByNameDebounce.bind(this)}
onKeyPress={this.onKeyPressEvent.bind(this)}/>
{/!*<i className="search icon"/>*!/}
</div>
</div>*/
)
}
}
export default SearchInput
|
app/components/common/Spinner.js | klpdotorg/tada-frontend | import React from 'react';
import PropTypes from 'prop-types';
const SpinnerView = (props, style) => {
if (!props.show) {
return <div />;
}
return (
<div className="loading-spinner">
<div style={style}>
<i className="fa fa-cog fa-spin fa-lg fa-fw" />
<span className="text-muted">{props.loadingText || 'Loading...'}</span>
</div>
</div>
);
};
SpinnerView.propTypes = {
loadingText: PropTypes.string,
show: PropTypes.bool,
};
export { SpinnerView };
|
packages/example-phone/src/scripts/containers/page-sections/call-page-header.js | udaysrinath/spark-js-sdk | import React from 'react';
import {connect} from 'react-redux';
import {PageHeader} from 'react-bootstrap';
function CallPageHeader({callStatus}) {
return (
<PageHeader>Call Status: <small className="call-status">{callStatus}</small></PageHeader>
);
}
CallPageHeader.propTypes = {
callStatus: React.PropTypes.string.isRequired
};
export default connect(
(state) => ({
callStatus: state.activeCall.status
})
)(CallPageHeader);
|
src/svg-icons/image/lens.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLens = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z"/>
</SvgIcon>
);
ImageLens = pure(ImageLens);
ImageLens.displayName = 'ImageLens';
export default ImageLens;
|
src/components/Footer.js | ayastreb/bandwidth-hero | import React from 'react'
import { Button, Container } from 'semantic-ui-react'
export default () => {
return (
<Container className="footer" textAlign="right">
<Button
basic
content="How it works?"
href="https://bandwidth-hero.com/"
target="_blank"
icon="home"
/>
<Button
basic
color="orange"
href="https://paypal.me/ayastreb"
target="_blank"
content="Donate!"
icon="heart outline"
/>
</Container>
)
}
|
src/LoadingLine.js | jgallegoweb/react-loading-line | import React, { Component } from 'react';
import '../assets/css/LoadingLine.css';
class LoadingLine extends Component {
constructor(props) {
super(props);
this.calculate = this.calculate.bind(this);
this.run = this.run.bind(this);
this.finalize = this.finalize.bind(this);
this.init = this.init.bind(this);
this.state = {
porcentage: 0,
init: true
}
}
componentDidMount() {
this.init()
}
init() {
this.setState({
porcentage: 0,
init: true,
runner: setInterval(this.run, 500)
})
}
componentDidUpdate() {
if (this.props.finish && !this.props.error && this.state.init) {
this.finalize();
clearInterval(this.state.runner);
}
if (this.props.error && !this.props.finish && this.state.init) {
this.error();
clearInterval(this.state.runner);
}
if (!this.props.error && !this.props.finish && !this.state.init) {
this.init()
}
}
run() {
//TODO: Function coefficient calc.
let coefficient = 30;
if (this.state.porcentage > 90) {
coefficient = 0;
} else if (this.state.porcentage > 80) {
coefficient = 0.1;
} else if (this.state.porcentage > 70) {
coefficient = 1;
} else if (this.state.porcentage > 55) {
coefficient = 5;
} else if (this.state.porcentage > 30) {
coefficient = 10;
}
let increment = Math.random() * coefficient;
let nextPer = this.state.porcentage + increment;
this.setState({
porcentage: nextPer >= 100 ? 100 : nextPer
})
}
calculate() {
if (this.state.porcentage === 100) {
clearInterval(this.state.runner);
}
return {width:`${this.state.porcentage}%`};
}
finalize() {
this.setState({
porcentage: 100,
init: false
});
}
error() {
this.setState({
init: false
});
}
render() {
//afinar el inicio
let claseFin = this.props.finish ? "ll-hide" : "";
let claseError = this.props.error ? "ll-error ll-hide" : "";
return (
<div className="ll-container">
<div className={`ll-line ${claseFin} ${claseError}`} style={this.calculate()}>
</div>
</div>
);
}
}
export default LoadingLine;
|
src/statics/Help.js | Sekhmet/busy | import React from 'react';
import { FormattedMessage } from 'react-intl';
import MenuHelp from '../app/Menu/MenuHelp';
export default () =>
<div className="main-panel">
<MenuHelp />
<div className="container text-center my-5">
<h1><FormattedMessage id="help" defaultMessage="Help" /></h1>
<h2>
<FormattedMessage
id="@statics/report_issue"
defaultMessage="Report an issue"
/>
</h2>
<p>
<FormattedMessage
id="@statics/contact_if_problem_0"
defaultMessage="If you spot a problem with Busy, please"
/>
{' '}
<a href="mailto:contact@busy.org">
<FormattedMessage
id="@statics/contact_if_problem_1"
defaultMessage="contact us"
/>
</a>
{' '}
<FormattedMessage
id="@statics/contact_if_problem_2"
defaultMessage="or submit an issue on"
/>
{' '}
<a
href="https://github.com/adcpm/busy/issues"
target="_blank"
rel="noopener noreferrer"
>
GitHub
</a>.
</p>
</div>
</div>;
|
packages/showcase/axes/parallel-coordinates-example.js | uber-common/react-vis | // Copyright (c) 2016 - 2017 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 React from 'react';
import {scaleLinear} from 'd3-scale';
import CarData from '../datasets/car-data.json';
import {XYPlot, DecorativeAxis, LineSeries} from 'react-vis';
const DEFAULT_DOMAIN = {min: Infinity, max: -Infinity};
// begin by figuring out the domain of each of the columns
const domains = CarData.reduce((res, row) => {
Object.keys(row).forEach(key => {
if (!res[key]) {
res[key] = {...DEFAULT_DOMAIN};
}
res[key] = {
min: Math.min(res[key].min, row[key]),
max: Math.max(res[key].max, row[key])
};
});
return res;
}, {});
// use that to generate columns that map the data to a unit scale
const scales = Object.keys(domains).reduce((res, key) => {
const domain = domains[key];
res[key] = scaleLinear()
.domain([domain.min, domain.max])
.range([0, 1]);
return res;
}, {});
// break each object into an array and rescale it
const mappedData = CarData.map(row => {
return Object.keys(row)
.filter(key => key !== 'name')
.map(key => ({
x: key,
y: scales[key](Number(row[key]))
}));
});
const MARGIN = {
left: 10,
right: 10,
top: 10,
bottom: 10
};
function ParallelCoordinatesExample() {
return (
<XYPlot
width={500}
height={300}
xType="ordinal"
margin={MARGIN}
className="parallel-coordinates-example"
>
{mappedData.map((series, index) => {
return <LineSeries data={series} key={`series-${index}`} />;
})}
{mappedData[0].map((cell, index) => {
return (
<DecorativeAxis
key={`${index}-axis`}
axisStart={{x: cell.x, y: 0}}
axisEnd={{x: cell.x, y: 1}}
axisDomain={[domains[cell.x].min, domains[cell.x].max]}
/>
);
})}
</XYPlot>
);
}
export default ParallelCoordinatesExample;
|
blueocean-material-icons/src/js/components/svg-icons/notification/airline-seat-legroom-reduced.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const NotificationAirlineSeatLegroomReduced = (props) => (
<SvgIcon {...props}>
<path d="M19.97 19.2c.18.96-.55 1.8-1.47 1.8H14v-3l1-4H9c-1.65 0-3-1.35-3-3V3h6v6h5c1.1 0 2 .9 2 2l-2 7h1.44c.73 0 1.39.49 1.53 1.2zM5 12V3H3v9c0 2.76 2.24 5 5 5h4v-2H8c-1.66 0-3-1.34-3-3z"/>
</SvgIcon>
);
NotificationAirlineSeatLegroomReduced.displayName = 'NotificationAirlineSeatLegroomReduced';
NotificationAirlineSeatLegroomReduced.muiName = 'SvgIcon';
export default NotificationAirlineSeatLegroomReduced;
|
app/routes.js | websash/q-and-a-react-redux-app | import React from 'react'
import {Route, IndexRoute} from 'react-router'
import App from './containers/App'
import Login from './containers/Login'
import Questions from './containers/Questions'
import Answers from './containers/Answers'
import AskQuestion from './containers/AskQuestion'
import User from './containers/User'
import NoMatch from './components/NoMatch'
import {
resetSearchBox as resetSBox,
updateSearchQuery as updateSQuery
} from './actions'
const requireAuth = (store) => (nextState, replace) => {
if (!store.getState().auth.isLoggedIn) {
replace({
pathname: '/login',
state: {nextPathname: nextState.location.pathname}
})
}
}
const resetSearchBox = (store) => (prevState, nextState) => {
if (!nextState.location.search) store.dispatch(resetSBox())
}
const updateSearchBox = (store) => (nextState, replace) => {
if (nextState.location.query.q)
store.dispatch(updateSQuery(nextState.location.query.q))
}
const configureRoutes = (store) =>
<Route path="/" component={App} onChange={resetSearchBox(store)}>
<IndexRoute component={Questions} />
<Route path="/login" component={Login} />
<Route path="/questions/ask" component={AskQuestion} onEnter={requireAuth(store)} />
<Route path="/questions/:slugId" component={Answers} />
<Route path="/search" component={Questions} onEnter={updateSearchBox(store)} />
<Route path="/answered" component={Questions} />
<Route path="/unanswered" component={Questions} />
<Route path="/users/:username" component={User} />
<Route path="*" component={NoMatch} />
</Route>
export default configureRoutes
|
modules/Route.js | Dodelkin/react-router | import React from 'react'
import warning from 'warning'
import invariant from 'invariant'
import { createRouteFromReactElement } from './RouteUtils'
import { component, components } from './PropTypes'
const { string, bool, func } = React.PropTypes
/**
* A <Route> is used to declare which components are rendered to the page when
* the URL matches a given pattern.
*
* Routes are arranged in a nested tree structure. When a new URL is requested,
* the tree is searched depth-first to find a route whose path matches the URL.
* When one is found, all routes in the tree that lead to it are considered
* "active" and their components are rendered into the DOM, nested in the same
* order as they are in the tree.
*/
const Route = React.createClass({
statics: {
createRouteFromReactElement(element) {
const route = createRouteFromReactElement(element)
if (route.handler) {
warning(
false,
'<Route handler> is deprecated, use <Route component> instead'
)
route.component = route.handler
delete route.handler
}
return route
}
},
propTypes: {
path: string,
ignoreScrollBehavior: bool,
handler: component, // deprecated
component,
components,
getComponents: func
},
render() {
invariant(
false,
'<Route> elements are for router configuration only and should not be rendered'
)
}
})
export default Route
|
_site/src/components/header/index.js | eemp/elasticsearch-scribe | import React from 'react'
import Paper from 'material-ui/lib/paper'
import Toolbar from 'material-ui/lib/toolbar/toolbar'
import ToolbarTitle from 'material-ui/lib/toolbar/toolbar-title'
import ToolbarGroup from 'material-ui/lib/toolbar/toolbar-group'
import FontIcon from 'material-ui/lib/font-icon'
import Popover from 'material-ui/lib/popover/popover'
import TextField from 'material-ui/lib/text-field'
import Autocomplete from 'material-ui/lib/auto-complete'
import Divider from 'material-ui/lib/divider'
import RaisedButton from 'material-ui/lib/raised-button'
import colors from 'material-ui/lib/styles/colors'
import Path from './path'
import SettingsDialog from './settings-dialog'
class Header extends React.Component {
constructor() {
super();
this.state = {
index: '',
mapping: '',
id: '',
mappingOpts: [],
settings_dialog_open: false,
};
}
shouldComponentUpdate(nextProps, nextState) {
return this.state.settings_dialog_open !== nextState.settings_dialog_open;
}
handleRefresh() {
this.props.handleFetchClick(this.props.index, this.props.type, this.props.id);
}
handleSave() {
this.props.handleSaveClick(this.props.changed_doc);
}
showSettingsDialog() {
this.setState({settings_dialog_open: true});
}
closeSettingsDialog() {
this.setState({settings_dialog_open: false});
}
render() {
return (
<Paper zDepth={1} rounded={false} circle={false}>
<Toolbar style={{backgroundColor: colors.cyan700}}>
<ToolbarGroup firstChild={true} float="left">
<ToolbarTitle text="{editor}" style={{left: 20, color: colors.white}}/>
<Path onComplete={this.props.handleFetchClick}/>
</ToolbarGroup>
<ToolbarGroup float="right">
<FontIcon className="material-icons" onClick={this.handleRefresh.bind(this)}>refresh</FontIcon>
<FontIcon className="material-icons" onClick={this.handleSave.bind(this)}>done</FontIcon>
<FontIcon className="material-icons" onClick={this.showSettingsDialog.bind(this)}>settings</FontIcon>
</ToolbarGroup>
</Toolbar>
<SettingsDialog {...this.props} open={this.state.settings_dialog_open} close={this.closeSettingsDialog.bind(this)}/>
</Paper>
);
}
}
module.exports = Header;
|
cb_browser_ui/src/toolbar.js | citybound/citybound | import React from 'react';
import { Tooltip } from 'antd';
export function Toolbar(props) {
return <div id={props.id} className="toolbar">{Object.keys(props.options).filter(key => props.options[key]).map(key => {
const { description, color, disabled } = props.options[key];
return <Tooltip title={description} arrowPointAtCenter={true} mouseEnterDelay={0.6} mouseLeaveDelay={0}>
<button id={key} key={key}
className={(key == props.value ? "active" : "") + (disabled ? " disabled" : "")}
onClick={!disabled && (() => props.onChange(key))}
><div style={{ backgroundColor: color }} className="button-icon"></div></button>
</Tooltip>
})}</div>
} |
monkey/monkey_island/cc/ui/src/components/attack/techniques/T1105.js | guardicore/monkey | import React from 'react';
import ReactTable from 'react-table';
import {ScanStatus} from './Helpers'
import MitigationsComponent from './MitigationsComponent';
class T1105 extends React.Component {
constructor(props) {
super(props);
}
static getFilesColumns() {
return ([{
Header: 'Files copied',
columns: [
{Header: 'Src. Machine', id: 'srcMachine', accessor: x => x.src, style: {'whiteSpace': 'unset'}, width: 170},
{Header: 'Dst. Machine', id: 'dstMachine', accessor: x => x.dst, style: {'whiteSpace': 'unset'}, width: 170},
{Header: 'Filename', id: 'filename', accessor: x => x.filename, style: {'whiteSpace': 'unset'}}
]
}])
}
render() {
return (
<div>
<div>{this.props.data.message_html}</div>
<br/>
{this.props.data.status !== ScanStatus.UNSCANNED ?
<ReactTable
columns={T1105.getFilesColumns()}
data={this.props.data.files}
showPagination={false}
defaultPageSize={this.props.data.files.length}
/> : ''}
<MitigationsComponent mitigations={this.props.data.mitigations}/>
</div>
);
}
}
export default T1105;
|
client/components/CommentList.js | parthi22/forum | import React from 'react';
import Comment from './Comment';
class CommentList extends React.Component{
handleSubmit(){
this.props.addComment(12,this.refs.comment,this.props.postId,'Parthi',new Date());
}
render(){
return(
<div className="wallComments">
<div className="comments">
{this.props.filteredComments.map((comment, i) => {
return(
<Comment {...this.props} key={i} index={i} comment={comment} />
)
})}
</div>
<form
ref="commentForm"
onSubmit={this.handleSubmit.bind(this)}>
<div className="divTextArea" contentEditable="true"
data-placeholder="Write your comment here" ref="comment" onSubmit={this.handleSubmit.bind(this)}></div>
<input type="submit" hidden />
</form>
</div>
)
}
}
export default CommentList; |
docs/src/app/components/pages/discover-more/RelatedProjects.js | kittyjumbalaya/material-components-web | import React from 'react';
import Title from 'react-title-component';
import MarkdownElement from '../../MarkdownElement';
import relatedProjectsText from './related-projects.md';
const RelatedProjects = () => (
<div>
<Title render={(previousTitle) => `Related Projects - ${previousTitle}`} />
<MarkdownElement text={relatedProjectsText} />
</div>
);
export default RelatedProjects;
|
src/DropdownMenu.js | pandoraui/react-bootstrap | import React from 'react';
import keycode from 'keycode';
import classNames from 'classnames';
import RootCloseWrapper from 'react-overlays/lib/RootCloseWrapper';
import ValidComponentChildren from './utils/ValidComponentChildren';
import createChainedFunction from './utils/createChainedFunction';
class DropdownMenu extends React.Component {
constructor(props) {
super(props);
this.focusNext = this.focusNext.bind(this);
this.focusPrevious = this.focusPrevious.bind(this);
this.getFocusableMenuItems = this.getFocusableMenuItems.bind(this);
this.getItemsAndActiveIndex = this.getItemsAndActiveIndex.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
handleKeyDown(event) {
switch (event.keyCode) {
case keycode.codes.down:
this.focusNext();
event.preventDefault();
break;
case keycode.codes.up:
this.focusPrevious();
event.preventDefault();
break;
case keycode.codes.esc:
case keycode.codes.tab:
this.props.onClose(event);
break;
default:
}
}
focusNext() {
let { items, activeItemIndex } = this.getItemsAndActiveIndex();
if (items.length === 0) {
return;
}
if (activeItemIndex === items.length - 1) {
items[0].focus();
return;
}
items[activeItemIndex + 1].focus();
}
focusPrevious() {
let { items, activeItemIndex } = this.getItemsAndActiveIndex();
if (activeItemIndex === 0) {
items[items.length - 1].focus();
return;
}
items[activeItemIndex - 1].focus();
}
getItemsAndActiveIndex() {
let items = this.getFocusableMenuItems();
let activeElement = document.activeElement;
let activeItemIndex = items.indexOf(activeElement);
return {items, activeItemIndex};
}
getFocusableMenuItems() {
let menuNode = React.findDOMNode(this);
if (menuNode === undefined) {
return [];
}
return [].slice.call(menuNode.querySelectorAll('[tabIndex="-1"]'), 0);
}
render() {
const items = ValidComponentChildren.map(this.props.children, child => {
let {
children,
onKeyDown,
onSelect
} = child.props || {};
return React.cloneElement(child, {
onKeyDown: createChainedFunction(onKeyDown, this.handleKeyDown),
onSelect: createChainedFunction(onSelect, this.props.onSelect)
}, children);
});
const classes = {
'dropdown-menu': true,
'dropdown-menu-right': this.props.pullRight
};
let list = (
<ul
className={classNames(this.props.className, classes)}
role="menu"
aria-labelledby={this.props.labelledBy}
>
{items}
</ul>
);
if (this.props.open) {
list = (
<RootCloseWrapper noWrap onRootClose={this.props.onClose}>
{list}
</RootCloseWrapper>
);
}
return list;
}
}
DropdownMenu.defaultProps = {
bsRole: 'menu',
pullRight: false
};
DropdownMenu.propTypes = {
open: React.PropTypes.bool,
pullRight: React.PropTypes.bool,
onClose: React.PropTypes.func,
labelledBy: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]),
onSelect: React.PropTypes.func
};
export default DropdownMenu;
|
src/components/Header.js | tborisova/fridment-react | import React, { Component } from 'react';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
NavButton
} from 'reactstrap';
import Milestones from './Milestones';
import Issues from './Issues';
import Milestone from './Milestone';
import GenerateIssues from './GenerateIssues'
import FinishMilestone from './FinishMilestone'
import OpenMilestone from './OpenMilestone'
import NewMilestone from './NewMilestone'
import EditMilestone from './EditMilestone'
import Callback from './Callback'
import AuthService from './AuthService'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
import CommentsView from './CommentsView'
import AddTesters from './AddTesters'
import AddComments from './AddComments'
import TestersView from './TestersView'
import ViewIssue from './ViewIssue'
import { login, logout, isLoggedIn } from './AuthService';
const auth = new AuthService();
const handleAuthentication = (nextState, replace) => {
if (/access_token|id_token|error/.test(nextState.location.hash)) {
auth.handleAuthentication();
}
}
class Header extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
return (
<Router>
<div>
<Navbar color="faded" light toggleable>
<NavbarToggler right onClick={this.toggle} />
<NavbarBrand><Link to="/milestones">Milestones</Link></NavbarBrand>
{
( auth.isAuthenticated() ) ? <NavbarBrand><Link to="/new_milestone">New milestone</Link></NavbarBrand> : ''
}
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
<NavItem>
{
(auth.isAuthenticated()) ? ( <button className="btn btn-danger log" onClick={() => auth.logout()}>Log out </button> ) : ( <button className="btn btn-info log" onClick={() => auth.login()}>Log In</button> )
}
</NavItem>
</Nav>
</Collapse>
</Navbar>
<Route exact path="/milestones" component={Milestones}/>
<Route exact path="/new_milestone" component={NewMilestone}/>
<Route exact path="/milestones/:milestone_id/edit" component={EditMilestone}/>
<Route exact path="/issues/:milestone_id" component={Issues}/>
<Route exact path="/milestones/generate_issues/:milestone_id" component={GenerateIssues}/>
<Route exact path="/milestones/:milestone_id" component={Milestone}/>
<Route exact path="/finish_milestone/:milestone_id" component={FinishMilestone}/>
<Route exact path="/open_milestone/:milestone_id" component={OpenMilestone}/>
<Route exact path="/milestones/:id/open" component={OpenMilestone}/>
<Route exact path="/comments/:issue_id" component={CommentsView}/>
<Route exact path="/add_testers/:milestone_id/:issue_id" component={AddTesters}/>
<Route exact path="/add_comments/:milestone_id/:issue_id" component={AddComments}/>
<Route exact path="/get_testers/:issue_id" component={TestersView}/>
<Route exact path="/issues/show/:id" component={ViewIssue}/>
<Route path="/callback" component={Callback} />
<Route path="/callback" render={(props) => {
handleAuthentication(props);
return <Callback {...props} />
}}/>
</div>
</Router>
);
}
}
export default Header;
|
fluxArchitecture/src/js/components/cart/app-cart.js | wandarkaf/React-Bible | import React from 'react';
import AppStore from '../../stores/app-store';
import AppCartItem from './app-cart-item';
import StoreWatchMixin from '../../mixins/StoreWatchMixin'
import { Link } from 'react-router';
const cartItems = () => {
return { items: AppStore.getCart() }
}
const Cart = ( props ) => {
var total = 0;
var items = props.items.map( ( item, i ) => {
let subtotal = item.cost * item.qty;
total += subtotal;
return (
<AppCartItem
subtotal={subtotal}
key={i}
item={item}/>
)
} );
return (
<div>
<h1>Cart</h1>
<table className="table table-hover">
<thead>
<tr>
<th></th>
<th>Item</th>
<th>Qty</th>
<th></th>
<th>Subtotal</th>
</tr>
</thead>
<tbody>
{items}
</tbody>
<tfoot>
<tr>
<td colSpan="4" className="text-right">Total</td>
<td>${total}</td>
</tr>
</tfoot>
</table>
<Link to="/">Continue Shopping</Link>
</div>
);
}
export default StoreWatchMixin(Cart,cartItems) ;
|
src/js/components/ui/Toolbar/ToolbarFiltersForm.js | knowncitizen/tripleo-ui | /**
* Copyright 2017 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import { FormGroup, InputGroup, MenuItem } from 'react-bootstrap';
import PropTypes from 'prop-types';
import React from 'react';
import { Field, reduxForm } from 'redux-form';
import { required } from 'redux-form-validators';
import DropdownSelect from '../reduxForm/DropdownSelect';
class ToolbarFiltersForm extends React.Component {
submit(data) {
this.props.onSubmit(data);
this.props.initialize({ filterBy: data.filterBy });
}
renderFilterByOptions() {
const { options } = this.props;
return Object.keys(options).map(k => (
<MenuItem key={k} eventKey={k}>
{options[k]}
</MenuItem>
));
}
renderFilterStringField() {
return (
<Field
validate={required()}
autoComplete="off"
name="filterString"
component="input"
placeholder={this.props.placeholder}
className="form-control"
/>
);
}
render() {
const { formatSelectValue, handleSubmit, options, id } = this.props;
return (
<form id={id} onSubmit={handleSubmit(this.submit.bind(this))}>
<FormGroup className="toolbar-pf-filter">
{options ? (
<InputGroup>
<InputGroup.Button>
<Field
name="filterBy"
component={DropdownSelect}
format={formatSelectValue}
>
{this.renderFilterByOptions()}
</Field>
</InputGroup.Button>
{this.renderFilterStringField()}
</InputGroup>
) : (
this.renderFilterStringField()
)}
</FormGroup>
</form>
);
}
}
ToolbarFiltersForm.propTypes = {
form: PropTypes.string.isRequired,
formatSelectValue: PropTypes.func,
handleSubmit: PropTypes.func.isRequired,
id: PropTypes.string,
initialValues: PropTypes.object,
initialize: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
options: PropTypes.object,
placeholder: PropTypes.string
};
ToolbarFiltersForm.defaultProps = {
placeholder: 'Add filter'
};
export default reduxForm()(ToolbarFiltersForm);
|
src/index.js | lotas/message-flow | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import 'semantic-ui-css/semantic.min.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
node_modules/react-bootstrap/es/SafeAnchor.js | mohammed52/something.pk | 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 React from 'react';
import PropTypes from 'prop-types';
import elementType from 'prop-types-extra/lib/elementType';
var propTypes = {
href: PropTypes.string,
onClick: PropTypes.func,
disabled: PropTypes.bool,
role: PropTypes.string,
tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* this is sort of silly but needed for Button
*/
componentClass: elementType
};
var defaultProps = {
componentClass: 'a'
};
function isTrivialHref(href) {
return !href || href.trim() === '#';
}
/**
* There are situations due to browser quirks or Bootstrap CSS where
* an anchor tag is needed, when semantically a button tag is the
* better choice. SafeAnchor ensures that when an anchor is used like a
* button its accessible. It also emulates input `disabled` behavior for
* links, which is usually desirable for Buttons, NavItems, MenuItems, etc.
*/
var SafeAnchor = function (_React$Component) {
_inherits(SafeAnchor, _React$Component);
function SafeAnchor(props, context) {
_classCallCheck(this, SafeAnchor);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleClick = _this.handleClick.bind(_this);
return _this;
}
SafeAnchor.prototype.handleClick = function handleClick(event) {
var _props = this.props,
disabled = _props.disabled,
href = _props.href,
onClick = _props.onClick;
if (disabled || isTrivialHref(href)) {
event.preventDefault();
}
if (disabled) {
event.stopPropagation();
return;
}
if (onClick) {
onClick(event);
}
};
SafeAnchor.prototype.render = function render() {
var _props2 = this.props,
Component = _props2.componentClass,
disabled = _props2.disabled,
props = _objectWithoutProperties(_props2, ['componentClass', 'disabled']);
if (isTrivialHref(props.href)) {
props.role = props.role || 'button';
// we want to make sure there is a href attribute on the node
// otherwise, the cursor incorrectly styled (except with role='button')
props.href = props.href || '#';
}
if (disabled) {
props.tabIndex = -1;
props.style = _extends({ pointerEvents: 'none' }, props.style);
}
return React.createElement(Component, _extends({}, props, {
onClick: this.handleClick
}));
};
return SafeAnchor;
}(React.Component);
SafeAnchor.propTypes = propTypes;
SafeAnchor.defaultProps = defaultProps;
export default SafeAnchor; |
src/components/ReportIndex.js | blaqbern/report-generator | import React from 'react'
function ReportIndex() {
return (
<h1>{'Generate Reportzzzzz!'}</h1>
)
}
export default ReportIndex
|
docs/src/app/components/pages/components/TextField/ExampleError.js | nathanmarks/material-ui | import React from 'react';
import TextField from 'material-ui/TextField';
const TextFieldExampleError = () => (
<div>
<TextField
hintText="Hint Text"
errorText="This field is required"
/><br />
<TextField
hintText="Hint Text"
errorText="The error text can be as long as you want, it will wrap."
/><br />
<TextField
hintText="Hint Text"
errorText="This field is required"
floatingLabelText="Floating Label Text"
/><br />
<TextField
hintText="Message Field"
errorText="This field is required."
floatingLabelText="MultiLine and FloatingLabel"
multiLine={true}
rows={2}
/><br />
</div>
);
export default TextFieldExampleError;
|
modules/gui/src/app/home/map/imageLayerSource/assetImageLayer.js | openforis/sepal | import {CursorValue} from '../cursorValue'
import {MapAreaLayout} from '../mapAreaLayout'
import {Subject} from 'rxjs'
import {VisualizationSelector} from './visualizationSelector'
import {compose} from 'compose'
import {msg} from 'translate'
import {selectFrom} from 'stateUtils'
import {withMapAreaContext} from '../mapAreaContext'
import {withRecipe} from 'app/home/body/process/recipeContext'
import {withTabContext} from 'widget/tabs/tabContext'
import EarthEngineImageLayer from '../layer/earthEngineImageLayer'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import withSubscriptions from 'subscription'
const mapRecipeToProps = (recipe, ownProps) => {
const {source} = ownProps
return {
userDefinedVisualizations: selectFrom(recipe, ['layers.userDefinedVisualizations', source.id]) || []
}
}
class _AssetImageLayer extends React.Component {
cursorValue$ = new Subject()
render() {
const {map} = this.props
return (
<CursorValue value$={this.cursorValue$}>
<MapAreaLayout
layer={this.maybeCreateLayer()}
form={this.renderImageLayerForm()}
map={map}
/>
</CursorValue>
)
}
renderImageLayerForm() {
const {source, layerConfig = {}} = this.props
const recipe = {
type: 'ASSET',
id: source.sourceConfig.asset
}
const visParamsToOption = visParams => ({
value: visParams.id,
label: visParams.bands.join(', '),
visParams
})
const visualizations = source.sourceConfig.visualizations || []
const options = [{
label: msg('map.layout.addImageLayerSource.types.Asset.presets'),
options: visualizations.map(visParamsToOption)
}]
return (
<VisualizationSelector
source={source}
recipe={recipe}
presetOptions={options}
selectedVisParams={layerConfig.visParams}
/>
)
}
componentDidMount() {
this.selectFirstVisualization()
}
selectFirstVisualization() {
const {source, userDefinedVisualizations, layerConfig: {visParams} = {}, mapAreaContext: {updateLayerConfig}} = this.props
const allVisualizations = [...userDefinedVisualizations, ...(selectFrom(source, 'sourceConfig.visualizations') || [])]
if (allVisualizations.length && (!visParams || !allVisualizations.find(({id}) => id === visParams.id))) {
const firstVisParams = allVisualizations[0]
updateLayerConfig({visParams: firstVisParams})
return firstVisParams
} else {
return visParams
}
}
setBusy(name, busy) {
const {tabContext: {setBusy}, componentId} = this.props
setBusy(`${name}-${componentId}`, busy)
}
maybeCreateLayer() {
const {layerConfig, map} = this.props
return map && layerConfig && layerConfig.visParams
? this.createLayer()
: null
}
createLayer() {
const {layerConfig, map, source, boundsChanged$, dragging$, cursor$, busy$} = this.props
const asset = selectFrom(source, 'sourceConfig.asset')
const dataTypes = selectFrom(source, 'sourceConfig.metadata.dataTypes') || {}
const {watchedProps: prevPreviewRequest} = this.layer || {}
const previewRequest = {
recipe: {
type: 'ASSET',
id: asset
},
...layerConfig
}
if (!_.isEqual(previewRequest, prevPreviewRequest)) {
this.layer && this.layer.removeFromMap()
this.layer = new EarthEngineImageLayer({
previewRequest,
visParams: layerConfig.visParams,
dataTypes,
map,
cursorValue$: this.cursorValue$,
busy$,
boundsChanged$,
dragging$,
cursor$
})
}
return this.layer
}
}
export const AssetImageLayer = compose(
_AssetImageLayer,
withSubscriptions(),
withRecipe(mapRecipeToProps),
withMapAreaContext(),
withTabContext()
)
AssetImageLayer.propTypes = {
source: PropTypes.any.isRequired,
boundsChanged$: PropTypes.any,
cursor$: PropTypes.any,
dragging$: PropTypes.any,
layerConfig: PropTypes.object,
map: PropTypes.object
}
|
src/js/components/MaskedInput/stories/Date.js | HewlettPackard/grommet | import React from 'react';
import { Box, Grommet, MaskedInput } from 'grommet';
import { grommet } from 'grommet/themes';
const daysInMonth = month => new Date(2019, month, 0).getDate();
export const DateMaskedInput = () => {
const [value, setValue] = React.useState('');
return (
<Grommet full theme={grommet}>
<Box fill align="center" justify="start" pad="large">
<Box width="medium">
<MaskedInput
mask={[
{
length: [1, 2],
options: Array.from({ length: 12 }, (v, k) => k + 1),
regexp: /^1[0,1-2]$|^0?[1-9]$|^0$/,
placeholder: 'mm',
},
{ fixed: '/' },
{
length: [1, 2],
options: Array.from(
{
length: daysInMonth(parseInt(value.split('/')[0], 10)),
},
(v, k) => k + 1,
),
regexp: /^[1-2][0-9]$|^3[0-1]$|^0?[1-9]$|^0$/,
placeholder: 'dd',
},
{ fixed: '/' },
{
length: 4,
options: Array.from({ length: 100 }, (v, k) => 2019 - k),
regexp: /^[1-2]$|^19$|^20$|^19[0-9]$|^20[0-9]$|^19[0-9][0-9]$|^20[0-9][0-9]$/,
placeholder: 'yyyy',
},
]}
value={value}
onChange={event => setValue(event.target.value)}
/>
</Box>
</Box>
</Grommet>
);
};
DateMaskedInput.storyName = 'Date';
DateMaskedInput.parameters = {
chromatic: { disable: true },
};
export default {
title: 'Input/MaskedInput/Date',
};
|
src/svg-icons/action/turned-in.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionTurnedIn = (props) => (
<SvgIcon {...props}>
<path d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
ActionTurnedIn = pure(ActionTurnedIn);
ActionTurnedIn.displayName = 'ActionTurnedIn';
ActionTurnedIn.muiName = 'SvgIcon';
export default ActionTurnedIn;
|
src/routes/home/index.js | veskoy/ridiko | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Home from './Home';
import Layout from '../../components/Layout';
function action() {
return {
chunks: ['home'],
title: 'Ridiko',
component: <Layout><Home /></Layout>,
};
}
export default action;
|
src/svg-icons/maps/my-location.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsMyLocation = (props) => (
<SvgIcon {...props}>
<path d="M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/>
</SvgIcon>
);
MapsMyLocation = pure(MapsMyLocation);
MapsMyLocation.displayName = 'MapsMyLocation';
MapsMyLocation.muiName = 'SvgIcon';
export default MapsMyLocation;
|
src/App.js | SomeHats/somehats.github.io | import React from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { ThemeNames } from './lib/Themes';
import Layout from './components/Layout';
import ScrollToTop from './components/ScrollToTop';
import HomePage from './pages/HomePage';
import CVPage from './pages/CVPage';
import ContactPage from './pages/ContactPage';
import Error404Page from './pages/Error404Page';
const doesPathUseDarkTheme = path => path === '/';
const App = () => (
<Router>
<Route
render={({ location }) => (
<Layout
theme={
doesPathUseDarkTheme(location.pathname)
? ThemeNames.DARK
: ThemeNames.LIGHT
}
>
<ScrollToTop />
<CSSTransitionGroup
className="page-transition"
transitionName="page"
transitionEnterTimeout={400}
transitionLeaveTimeout={300}
>
<Switch key={location.pathname} location={location}>
<Route exact path="/" component={HomePage} />
{/* <Route path="/projects" component={ProjectsPage} /> */}
<Route path="/cv" component={CVPage} />
<Route path="/contact" component={ContactPage} />
<Route path="*" component={Error404Page} />
</Switch>
</CSSTransitionGroup>
</Layout>
)}
/>
</Router>
);
export default App;
|
templates/rubix/relay/relay-example/src/routes.js | jeffthemaximum/jeffline | import React from 'react';
import Relay from 'react-relay';
import classNames from 'classnames';
import { IndexRoute, Route } from 'react-router';
import { Grid, Row, Col, MainContainer } from '@sketchpixy/rubix';
import Footer from './common/footer';
import Header from './common/header';
import Sidebar from './common/sidebar';
import UserQuery from './common/UserQuery';
import AllTodos from './routes/AllTodos';
import EditTodo from './routes/EditTodo';
class App extends React.Component {
render() {
return (
<MainContainer {...this.props}>
<Sidebar />
<Header />
<div id='body'>
<Grid>
<Row>
<Col xs={12}>
{this.props.children}
</Col>
</Row>
</Grid>
</div>
<Footer />
</MainContainer>
);
}
}
export default (
<Route path='/' component={App}>
<IndexRoute component={AllTodos} queries={UserQuery} />
<Route path='todo/edit/:id' component={EditTodo} queries={UserQuery} />
</Route>
);
|
src/svg-icons/av/hd.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvHd = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-8 12H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm2-6h4c.55 0 1 .45 1 1v4c0 .55-.45 1-1 1h-4V9zm1.5 4.5h2v-3h-2v3z"/>
</SvgIcon>
);
AvHd = pure(AvHd);
AvHd.displayName = 'AvHd';
AvHd.muiName = 'SvgIcon';
export default AvHd;
|
src/components/Dock/SoundCloudPlayer.js | bibleexchange/be-front-new | import React from 'react'
class SoundCloudPlayer extends React.Component {
render() {
let srcString = null
let player = <p>(no audio was selected)</p>
if (this.props.status === true){
srcString = srcString = 'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/' + this.props.id + '&auto_play=true&hide_related=true&show_comments=false&show_user=false&show_reposts=false&visual=false';
player = <div><iframe key={this.props.id} width='100%' height='130px' scrolling='no' frameBorder='no' src={srcString}></iframe>
<button onClick={this.props.handleCloseAudio}>close</button></div>
}
return (player)
}
}
export default SoundCloudPlayer
|
common/components/ide/tabs/ProcessTab.js | ebertmi/webbox | import React from 'react';
import Tab from './Tab';
import Icon from '../../Icon';
export default class ProcessTab extends React.Component {
constructor(props) {
super(props);
this.onBell = this.onBell.bind(this);
this.onTitle = this.onTitle.bind(this);
this.state = {
bell: false,
title: 'Terminal'
};
}
componentDidMount() {
this.props.item.on('bell', this.onBell);
this.props.item.on('title', this.onTitle);
}
componentWillUnmount() {
this.props.item.removeListener('bell', this.onBell);
this.props.item.removeListener('title', this.onTitle);
}
componentWillReceiveProps({active}) {
if (active) {
this.setState({
bell: false
});
}
}
onBell() {
this.setState({
bell: !this.props.active
});
}
onTitle(title) {
this.setState({ title });
}
renderBell() {
if (this.state.bell) {
return <Icon title="Bell-Signal in diesem Terminal" name="bell" className="warning"/>;
}
}
render() {
return (
<Tab {...this.props} title={this.state.title} icon="terminal">
{this.state.title}
{' '}
{this.renderBell()}
</Tab>
);
}
}
|
src/docs/examples/EyeIcon/Example.js | StudentOfJS/ps-react-rod | import React from 'react';
import EyeIcon from 'ps-react-rod/EyeIcon';
export default function EyeIconExample() {
return <EyeIcon />;
} |
src/main.js | bingomanatee/ridecell | import React from 'react';
import ReactDOM from 'react-dom';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { useRouterHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import makeRoutes from './routes';
import Root from './containers/Root';
import configureStore from './redux/configureStore';
// Configure history for react-router
const browserHistory = useRouterHistory(createBrowserHistory)({
basename: __BASENAME__
});
// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the key "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState, browserHistory);
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: (state) => state.router
});
// Now that we have the Redux store, we can create our routes. We provide
// the store to the route definitions so that routes have access to it for
// hooks such as `onEnter`.
const routes = makeRoutes(store);
// Now that redux and react-router have been configured, we can render the
// React application to the DOM!
ReactDOM.render(
<Root history={history} routes={routes} store={store} />,
document.getElementById('root')
);
|
src/routes/zookeeper.js | Capgemini/mesos-ui | import _ from 'lodash';
import fs from 'fs';
import path from 'path';
import React from 'react';
import Router from 'react-router';
import routes from './react-routes';
import proxy from 'express-http-proxy';
import express from 'express';
module.exports = function(app) {
var zookeeper = require('node-zookeeper-client');
var config = require('../config/config');
var client = zookeeper.createClient(config.zookeeperAddress);
var router = express.Router();
client.once('connected', function () {
console.log('Connected to the Zookeeper.');
listChildren(client, config.zookeeperPath).then(function(childrenList) {
// The smallest one is the leader.
childrenList.sort();
return getData(client, config.zookeeperPath + '/' + childrenList[0]);
}).then(function(jsonData) {
// The top-level React component + HTML template for it
let leader = 'http://' + jsonData.address.ip + ':' + jsonData.address.port;
setRoutes(app, leader);
});
});
client.connect();
function setRoutes(app, leader) {
const templateFile = path.join(__dirname, 'master/static/index.html');
const template = _.template(fs.readFileSync(templateFile, 'utf8'));
var config = require('../config/config');
app.get(config.proxyPath + '/*', proxy(leader, {
forwardPath: function(req, res) {
// Gets the path after 'proxy/'.
let path = require('url').parse(req.url).path;
return path.slice(config.mesosEndpoint.length);
}
}));
app.get('*', function(req, res, next) {
try {
let data = { title: '', description: '', css: '', body: '' };
let css = [];
Router.run(routes, req.url, function(Handler) {
let application = (<Handler
context={{
onInsertCss: value => css.push(value),
onSetTitle: value => data.title = value,
onSetMeta: (key, value) => data[key] = value
}} />
);
data.body = React.renderToString(application);
data.css = css.join('');
let html = template(data);
res.send(html);
});
} catch (err) {
next(err);
}
});
}
function listChildren(client, path) {
return new Promise(function(resolve, reject) {
client.getChildren(
path,
function (event) {
console.log('Got watcher event: %s', event);
listChildren(client, path).then(function(childrenList) {
// The smallest one is the leader.
childrenList.sort();
return getData(client, path + '/' + childrenList[0]);
}).then(function(jsonData) {
var config = require('../config/config');
// The top-level React component + HTML template for it
let leader = 'http://' + jsonData.address.ip + ':' + jsonData.address.port;
// Remove and recreate routes for new leader.
app._router.stack.pop();
app._router.stack.pop();
setRoutes(app, leader);
});
},
function (error, children, stat) {
if (error) {
console.log(
'Failed to list children of %s due to: %s.',
path,
error
);
reject(Error('It broke'));
}
console.log('Children of %s are: %j.', path, children);
resolve(children);
}
);
});
}
function getData(client, path) {
return new Promise(function(resolve, reject) {
client.getData(
path,
function (event) {
console.log('Got event: %s.', event);
getData(client, path);
},
function (error, data, stat) {
if (error) {
console.log(error.stack);
reject(Error('It broke'));
return;
}
console.log('Got data: %s', data.toString('utf8'));
let string = data.toString('utf8');
let hash = JSON.parse(string);
resolve(hash);
}
);
});
}
};
|
client/components/calendar.js | vijayneophyte/react_redux_node_express | import React from "react";
import EventCalendar from 'react-event-calendar'
import 'style-loader!react-event-calendar/style.css';
// import BigCalendar from 'react-big-calendar';
// import 'style-loader!react-big-calendar/lib/css/react-big-calendar.css';
// import moment from 'moment';
// BigCalendar.momentLocalizer(moment); // or globalizeLocalizer
//import React from 'react';
import ReactDOM from 'react-dom';
//import EventCalendar from '../src/index.js';
import moment from 'moment';
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import Button from 'react-bootstrap/lib/Button';
import ButtonToolbar from 'react-bootstrap/lib/ButtonToolbar';
import Popover from 'react-bootstrap/lib/PopOver';
import Overlay from 'react-bootstrap/lib/Overlay';
import Modal from 'react-bootstrap/lib/Modal';
//import TestData from './TestData.js';
const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ];
class Calendar extends React.Component {
constructor(props) {
super(props);
this.state = {
moment: moment(),
showPopover: false,
showModal: false,
overlayTitle: null,
overlayContent: null,
popoverTarget: null,
getEvents:[
{
start: '2017-07-20',
end: '2017-07-20',
eventClasses: 'optionalEvent',
title: '8hr',
description: 'This is a test description of an event',
}
]
};
this.handleNextMonth = this.handleNextMonth.bind(this);
this.handlePreviousMonth = this.handlePreviousMonth.bind(this);
this.handleToday = this.handleToday.bind(this);
this.handleEventClick = this.handleEventClick.bind(this);
this.handleEventMouseOver = this.handleEventMouseOver.bind(this);
this.handleEventMouseOut = this.handleEventMouseOut.bind(this);
this.handleDayClick = this.handleDayClick.bind(this);
this.handleModalClose = this.handleModalClose.bind(this);
}
handleNextMonth() {
this.setState({
moment: this.state.moment.add(1, 'M'),
});
}
handlePreviousMonth() {
this.setState({
moment: this.state.moment.subtract(1, 'M'),
});
}
handleToday() {
this.setState({
moment: moment(),
});
}
handleEventMouseOver(target, eventData, day) {
console.log(target);
console.log(eventData)
this.setState({
showPopover: true,
popoverTarget: () => ReactDOM.findDOMNode(target),
overlayTitle: eventData.title,
overlayContent: eventData.description,
});
}
handleEventMouseOut(target, eventData, day) {
console.log(day);
this.setState({
showPopover: false,
});
}
handleEventClick(target, eventData, day) {
this.setState({
showPopover: false,
showModal: true,
overlayTitle: eventData.title,
overlayContent: eventData.description,
});
}
handleDayClick(target, day) {
this.setState({
showPopover: false,
showModal: true,
overlayTitle: this.getMomentFromDay(day).format('Do of MMMM YYYY'),
overlayContent: 'User clicked day (but not event node).',
});
}
getMomentFromDay(day) {
return moment().set({
'year': day.year,
'month': (day.month + 0) % 12,
'date': day.day
});
}
handleModalClose() {
this.setState({
showModal: false,
})
}
getHumanDate() {
return [moment.months('MM', this.state.moment.month()), this.state.moment.year(), ].join(' ');
}
render() {
const styles = {
position: 'relative',
};
return (
<div style={styles}>
<Overlay
show={this.state.showPopover}
rootClose
onHide = {()=>this.setState({showPopover: false, })}
placement="top"
container={this}
target={this.state.popoverTarget}>
<Popover id="event">{this.state.overlayTitle}</Popover>
</Overlay>
<Modal show={this.state.showModal} onHide={this.handleModalClose}>
<Modal.Header closeButton>
<Modal.Title>{this.state.overlayTitle}</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.state.overlayContent}
</Modal.Body>
<Modal.Footer>
<Button onClick={this.handleModalClose}>Close</Button>
</Modal.Footer>
</Modal>
<Grid>
<Row>
<Col xs={6}>
<ButtonToolbar>
<Button onClick={this.handlePreviousMonth}><</Button>
<Button onClick={this.handleNextMonth}>></Button>
<Button onClick={this.handleToday}>Today</Button>
<span className="pull-right h2">{this.getHumanDate()}</span>
</ButtonToolbar>
</Col>
{/*<Col xs={3}>*/}
{/*<div className="pull-right h2">{this.getHumanDate()}</div>*/}
{/*</Col>*/}
</Row>
<br />
<Row>
<Col xs={12}>
<EventCalendar
month={this.state.moment.month()}
year={this.state.moment.year()}
events={this.state.getEvents}
onEventClick={this.handleEventClick}
onEventMouseOver={this.handleEventMouseOver}
onEventMouseOut={this.handleEventMouseOut}
onDayClick={this.handleDayClick}
maxEventSlots={1}
/>
</Col>
</Row>
</Grid>
</div>
);
}
}
export default Calendar;
|
src/server.js | Maryanushka/masterskaya | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt, { UnauthorizedError as Jwt401Error } from 'express-jwt';
//import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import React from 'react';
import ReactDOM from 'react-dom/server';
import PrettyError from 'pretty-error';
import App from './components/App';
import Html from './components/Html';
import { ErrorPageWithoutStyle } from './routes/error/ErrorPage';
import errorPageStyle from './routes/error/ErrorPage.css';
import createFetch from './createFetch';
import passport from './passport';
import router from './router';
import models from './data/models';
import schema from './data/schema';
import assets from './assets.json'; // eslint-disable-line import/no-unresolved
import config from './config';
const app = express();
//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//
// Authentication
// -----------------------------------------------------------------------------
app.use(expressJwt({
secret: config.auth.jwt.secret,
credentialsRequired: false,
getToken: req => req.cookies.id_token,
}));
// Error handler for express-jwt
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
if (err instanceof Jwt401Error) {
console.error('[express-jwt-error]', req.cookies.id_token);
// `clearCookie`, otherwise user can't use web-app until cookie expires
res.clearCookie('id_token');
}
next(err);
});
app.use(passport.initialize());
if (__DEV__) {
app.enable('trust proxy');
}
app.get('/login/facebook',
passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false }),
);
app.get('/login/facebook/return',
passport.authenticate('facebook', { failureRedirect: '/login', session: false }),
(req, res) => {
const expiresIn = 60 * 60 * 24 * 180; // 180 days
const token = jwt.sign(req.user, config.auth.jwt.secret, { expiresIn });
res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true });
res.redirect('/');
},
);
//
// Register API middleware
// -----------------------------------------------------------------------------
// app.use('/graphql', expressGraphQL(req => ({
// schema,
// graphiql: __DEV__,
// rootValue: { request: req },
// pretty: __DEV__,
// })));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
app.get('*', async (req, res, next) => {
try {
const css = new Set();
// Global (context) variables that can be easily accessed from any React component
// https://facebook.github.io/react/docs/context.html
const context = {
// Enables critical path CSS rendering
// https://github.com/kriasoft/isomorphic-style-loader
insertCss: (...styles) => {
// eslint-disable-next-line no-underscore-dangle
styles.forEach(style => css.add(style._getCss()));
},
// Universal HTTP client
fetch: createFetch({
baseUrl: config.api.serverUrl,
cookie: req.headers.cookie,
}),
};
const route = await router.resolve({
...context,
path: req.path,
query: req.query,
});
if (route.redirect) {
res.redirect(route.status || 302, route.redirect);
return;
}
const data = { ...route };
data.children = ReactDOM.renderToString(<App context={context}>{route.component}</App>);
data.styles = [
{ id: 'css', cssText: [...css].join('') },
];
data.scripts = [
assets.vendor.js,
assets.client.js,
];
if (assets[route.chunk]) {
data.scripts.push(assets[route.chunk].js);
}
data.app = {
apiUrl: config.api.clientUrl,
};
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(route.status || 200);
res.send(`<!doctype html>${html}`);
} catch (err) {
next(err);
}
});
//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
console.error(pe.render(err));
const html = ReactDOM.renderToStaticMarkup(
<Html
title="Internal Server Error"
description={err.message}
styles={[{ id: 'css', cssText: errorPageStyle._getCss() }]} // eslint-disable-line no-underscore-dangle
>
{ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)}
</Html>,
);
res.status(err.status || 500);
res.send(`<!doctype html>${html}`);
});
//
// Launch the server
// -----------------------------------------------------------------------------
models.sync().catch(err => console.error(err.stack)).then(() => {
app.listen(config.port, () => {
console.info(`The server is running at http://localhost:${config.port}/`);
});
});
|
docs/src/app/components/pages/components/List/ExampleFolders.js | ichiohta/material-ui | import React from 'react';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem} from 'material-ui/List';
import ActionInfo from 'material-ui/svg-icons/action/info';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import Avatar from 'material-ui/Avatar';
import FileFolder from 'material-ui/svg-icons/file/folder';
import ActionAssignment from 'material-ui/svg-icons/action/assignment';
import {blue500, yellow600} from 'material-ui/styles/colors';
import EditorInsertChart from 'material-ui/svg-icons/editor/insert-chart';
const ListExampleFolder = () => (
<MobileTearSheet>
<List>
<Subheader inset={true}>Folders</Subheader>
<ListItem
leftAvatar={<Avatar icon={<FileFolder />} />}
rightIcon={<ActionInfo />}
primaryText="Photos"
secondaryText="Jan 9, 2014"
/>
<ListItem
leftAvatar={<Avatar icon={<FileFolder />} />}
rightIcon={<ActionInfo />}
primaryText="Recipes"
secondaryText="Jan 17, 2014"
/>
<ListItem
leftAvatar={<Avatar icon={<FileFolder />} />}
rightIcon={<ActionInfo />}
primaryText="Work"
secondaryText="Jan 28, 2014"
/>
</List>
<Divider inset={true} />
<List>
<Subheader inset={true}>Files</Subheader>
<ListItem
leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={blue500} />}
rightIcon={<ActionInfo />}
primaryText="Vacation itinerary"
secondaryText="Jan 20, 2014"
/>
<ListItem
leftAvatar={<Avatar icon={<EditorInsertChart />} backgroundColor={yellow600} />}
rightIcon={<ActionInfo />}
primaryText="Kitchen remodel"
secondaryText="Jan 10, 2014"
/>
</List>
</MobileTearSheet>
);
export default ListExampleFolder;
|
src/icons/SuccessIcon.js | resmio/mantecao | import React from 'react'
import Icon from '../Icon'
const SuccessIcon = props =>
<Icon {...props}>
<g strokeWidth="1.3" transform="translate(0, -0.5)">
<path d="M16.5 29C23.4 29 29 23.4 29 16.5 29 9.6 23.4 4 16.5 4 9.6 4 4 9.6 4 16.5 4 23.4 9.6 29 16.5 29ZM10 16.6L13.8 20.4C14.2 20.8 14.8 20.8 15.2 20.4L23.5 12" />
</g>
</Icon>
export default SuccessIcon
|
src/client.js | trungtin/mP | /**
* THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER.
*/
import 'babel/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import createHistory from 'history/lib/createBrowserHistory';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import io from 'socket.io-client';
import {Provider} from 'react-redux';
import {reduxReactRouter, ReduxRouter} from 'redux-router';
import getRoutes from './routes';
const client = new ApiClient();
const dest = document.getElementById('content');
const store = createStore(reduxReactRouter, getRoutes, createHistory, client, window.__data);
function initSocket() {
const socket = io('', {path: '/api/ws', transports: ['polling']});
socket.on('news', (data) => {
console.log(data);
socket.emit('my other event', { my: 'data from client' });
});
socket.on('msg', (data) => {
console.log(data);
});
return socket;
}
global.socket = initSocket();
const component = (
<Provider store={store} key="provider">
<ReduxRouter routes={getRoutes(store)} />
</Provider>
);
ReactDOM.render(component, dest);
if (process.env.NODE_ENV !== 'production') {
window.React = React; // enable debugger
if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) {
console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
}
}
if (__DEVTOOLS__) {
const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react');
ReactDOM.render(<div>
{component}
<DebugPanel top right bottom key="debugPanel">
<DevTools store={store} monitor={LogMonitor}/>
</DebugPanel>
</div>, dest);
}
|
src/svg-icons/editor/format-underlined.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatUnderlined = (props) => (
<SvgIcon {...props}>
<path d="M12 17c3.31 0 6-2.69 6-6V3h-2.5v8c0 1.93-1.57 3.5-3.5 3.5S8.5 12.93 8.5 11V3H6v8c0 3.31 2.69 6 6 6zm-7 2v2h14v-2H5z"/>
</SvgIcon>
);
EditorFormatUnderlined = pure(EditorFormatUnderlined);
EditorFormatUnderlined.displayName = 'EditorFormatUnderlined';
EditorFormatUnderlined.muiName = 'SvgIcon';
export default EditorFormatUnderlined;
|
src/components/button/index.js | enapupe/know-your-bundle | import PropTypes from 'prop-types'
import React from 'react'
const Button = ({ btnType, btnClicked, children }) => (
<button type={btnType} onClick={btnClicked}>
{children}
</button>
)
Button.propTypes = {
btnType: PropTypes.string,
btnClicked: PropTypes.func.isRequired,
children: PropTypes.node.isRequired,
}
Button.defaultProps = {
btnType: 'button',
}
export default Button
|
src/static/containers/Protected/index.js | spiskommg/mm-v2 | import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import * as actionCreators from '../../actions/data';
class ProtectedView extends React.Component {
static propTypes = {
isFetching: PropTypes.bool.isRequired,
data: PropTypes.string,
token: PropTypes.string.isRequired,
actions: PropTypes.shape({
dataFetchProtectedData: PropTypes.func.isRequired
}).isRequired
};
static defaultProps = {
data: ''
};
// Note: have to use componentWillMount, if I add this in constructor will get error:
// Warning: setState(...): Cannot update during an existing state transition (such as within `render`).
// Render methods should be a pure function of props and state.
componentWillMount() {
const token = this.props.token;
this.props.actions.dataFetchProtectedData(token);
}
render() {
return (
<div className="protected">
<div className="container">
<h1 className="text-center margin-bottom-medium">Protected</h1>
{this.props.isFetching === true ?
<p className="text-center">Loading data...</p>
:
<div>
<p>Data received from the server:</p>
<div className="margin-top-small">
<div className="alert alert-info">
<b>{this.props.data}</b>
</div>
</div>
<div className="margin-top-medium">
<h5 className="margin-bottom-small"><b>How does this work?</b></h5>
<p className="margin-bottom-small">
On the <code>componentWillMount</code> method of the
<code>ProtectedView</code> component, the action
<code>dataFetchProtectedData</code> is called. This action will first
dispatch a <code>DATA_FETCH_PROTECTED_DATA_REQUEST</code> action to the Redux
store. When an action is dispatched to the store, an appropriate reducer for
that specific action will change the state of the store. After that it will then
make an asynchronous request to the server using
the <code>isomorphic-fetch</code> library. On its
response, it will dispatch the <code>DATA_RECEIVE_PROTECTED_DATA</code> action
to the Redux store. In case of wrong credentials in the request, the
<code>AUTH_LOGIN_USER_FAILURE</code> action will be dispatched.
</p>
<p>
Because the <code>ProtectedView</code> is connected to the Redux store, when the
value of a property connected to the view is changed, the view is re-rendered
with the new data.
</p>
</div>
</div>
}
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
data: state.data.data,
isFetching: state.data.isFetching
};
};
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(actionCreators, dispatch)
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ProtectedView);
export { ProtectedView as ProtectedViewNotConnected };
|
client/src/Dashboard.js | chi-bumblebees-2017/gnomad | import React, { Component } from 'react';
import Interests from './components/Interests';
import RecentChats from './RecentChats';
import NewProfile from './NewProfile';
import { Button, Loader } from 'semantic-ui-react'
import { Link, Redirect } from 'react-router-dom';
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
userData: [],
conversations: [],
userLoaded: false,
chatsLoaded: false,
editing: false,
};
this.toggleEdit = this.toggleEdit.bind(this);
}
toggleEdit() {
this.setState({editing: true});
}
componentDidMount() {
fetch('/users/a', {
method: 'GET',
accept: 'application/json',
headers: {
'Authorization': localStorage.getItem('gnomad-auth-token')
},
}).then(data => data.json())
.then(dataJson => {
this.setState({
userData: dataJson,
userLoaded: true,
});
});
fetch('/conversations', {
accept: 'application/json',
headers: {
'Authorization': localStorage.getItem('gnomad-auth-token'),
'Limit': '3',
},
})
.then(data => data.json())
.then(dataJson => {
this.setState({
conversations: dataJson,
chatsLoaded: true,
editing: false,
});
});
}
render() {
// if (!this.props.loggedIn) {
// return (<Redirect to="/" />);
// }
if (this.state.userLoaded === true && this.state.chatsLoaded === true && this.state.editing === false) {
return(
<div className="profile-container ui centered container">
<div className="max-width">
<h1>{this.state.userData.user.first_name}</h1>
<div className="profile-picture-container">
<img src={this.state.userData.user.image_url} alt="profile-picture" className="border-radius-10"/>
</div>
<div>
<br/>
<Button compact content='Edit' icon='edit' labelPosition='left' basic color='red' size='small' onClick={this.toggleEdit}/>
<br/>
<br/>
<div>
<Link to={`/users/${this.state.userData.user.first_name}/${this.state.userData.user.id}`}>
<Button compact content="View My Public Profile" icon='user outline' labelPosition='left' basic color='blue' size='small' className="top-margin-10"/>
</Link>
</div>
</div>
<RecentChats conversations={this.state.conversations}/>
</div>
</div>
);
}
else if (this.state.userLoaded === true && this.state.chatsLoaded === true && this.state.editing === true) {
return ( <NewProfile userData={this.userData} /> );
}
else {
return ( <Loader /> );
}
}
}
export default Dashboard;
|
src/js/components/author-item.js | noknot/bnf-hackathon | import React from 'react'
import { sparqlConnect } from '../sparql/configure-sparql'
import {
List, ListItem, ListSubHeader, ListDivider, ListCheckbox
} from 'react-toolbox/lib/list'
function AuthorItem({
author, name,
dateOfBirth, dateOfDeath,
placeOfBirth, placeOfDeath,
thumbnail, count }) {
const yearOfBirth = dateOfBirth.match(/(\d{4})\/$/).pop()
const yearOfDeath = dateOfDeath.match(/(\d{4})\/$/).pop()
const legend = `${yearOfBirth} (${placeOfBirth}) - ${yearOfDeath} (${placeOfDeath})`
return (
<ListItem
avatar={thumbnail}
caption={`${name} (${count})`}
legend={legend} />
)
}
export default sparqlConnect.authorDetails(AuthorItem) |
app/javascript/mastodon/features/lists/index.js | lindwurm/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import { fetchLists } from '../../actions/lists';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ColumnLink from '../ui/components/column_link';
import ColumnSubheading from '../ui/components/column_subheading';
import NewListForm from './components/new_list_form';
import { createSelector } from 'reselect';
import ScrollableList from '../../components/scrollable_list';
const messages = defineMessages({
heading: { id: 'column.lists', defaultMessage: 'Lists' },
subheading: { id: 'lists.subheading', defaultMessage: 'Your lists' },
});
const getOrderedLists = createSelector([state => state.get('lists')], lists => {
if (!lists) {
return lists;
}
return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title')));
});
const mapStateToProps = state => ({
lists: getOrderedLists(state),
});
export default @connect(mapStateToProps)
@injectIntl
class Lists extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
lists: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchLists());
}
render () {
const { intl, lists, multiColumn } = this.props;
if (!lists) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.lists' defaultMessage="You don't have any lists yet. When you create one, it will show up here." />;
return (
<Column bindToDocument={!multiColumn} icon='list-ul' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<NewListForm />
<ScrollableList
scrollKey='lists'
emptyMessage={emptyMessage}
prepend={<ColumnSubheading text={intl.formatMessage(messages.subheading)} />}
bindToDocument={!multiColumn}
>
{lists.map(list =>
<ColumnLink key={list.get('id')} to={`/lists/${list.get('id')}`} icon='list-ul' text={list.get('title')} />,
)}
</ScrollableList>
</Column>
);
}
}
|
integration/examples/TableExamples.js | wundery/wundery-ui-react | import React from 'react';
import { Example, ExampleSet } from 'components';
import { tableData } from 'utils';
import { Table, TableColumn } from 'wundery-ui-react/components/Table';
import { FormValidation } from 'wundery-ui-react/components/Form';
class TableExamples extends React.Component {
constructor(props) {
super(props);
/**
* Validator for editable table
*
* @type {FormValidation}
*/
this.validation = new FormValidation().validate('price', 'required');
/**
* Initial container state
*
* @type {Object}
*/
this.state = {
expandableTableData: tableData(3),
expandableTablePage: 1,
expandableTablePageSize: 3,
editableTableData: tableData(3),
orderableTableData: tableData(3),
};
}
onUpdate = (prevDatum, nextDatum) => {
console.log('received update', prevDatum, nextDatum);
const { editableTableData } = this.state;
const newData = [...editableTableData];
newData[editableTableData.indexOf(prevDatum)] = nextDatum;
this.setState({
editableTableData: newData,
});
}
onValidate = (data) => {
return this.validation.run(data);
}
renderEditableExample() {
return (
<Example title="Table with inline edit support">
<Table
data={this.state.editableTableData}
onUpdate={this.onUpdate}
onValidate={this.onValidate}
>
<TableColumn
title="ID"
attribute="id"
width={60}
copyable
center
/>
<TableColumn
title="Product title"
attribute="title"
/>
<TableColumn
width={200}
title="Price"
editable="price"
onEdit={datum => {
console.log('Updating datum...', datum);
return new Promise(resolve => setTimeout(() => resolve(datum), 500));
}}
builder={datum => {
return (
<div>
<div><strong>{datum.price_formatted}</strong></div>
<div>floatVal = {datum.price}</div>
</div>
);
}}
/>
</Table>
</Example>
);
}
renderDefaultExample() {
return (
<Example title="Default table">
<Table title="This is the table title"data={tableData(3)}>
<TableColumn
title="ID"
attribute="id"
width={60}
copyable
center
/>
<TableColumn
title="Product title"
attribute="title"
/>
</Table>
</Example>
);
}
// If provided, this is called and renderd when the user expands a row
onExpandClick = (datum) => {
const content = (
<span>
Expanded content for {datum.id}
</span>
);
return new Promise((resolve) => {
setTimeout(() => resolve(content), 500);
})
};
onPaginate = (page) => this.setState({
expandableTableData: tableData(this.state.expandableTablePageSize, page),
expandableTablePage: page,
});
onPageSizeChange = (pageSize) => this.setState({
expandableTablePageSize: pageSize,
expandableTableData: tableData(pageSize),
});
onOrder = (objects) => {
this.setState({
orderableTableData: objects,
});
}
renderExpandableExample() {
return (
<Example title="Expandable table with pagination">
<Table
data={this.state.expandableTableData}
onExpand={this.onExpandClick}
pages={2}
pageSizes={[3, 6]}
pageSize={this.state.expandableTablePageSize}
page={this.state.expandableTablePage}
onPaginate={this.onPaginate}
onPageSizeChange={this.onPageSizeChange}
>
<TableColumn
title="ID"
attribute="id"
width={60}
copyable
center
/>
<TableColumn
title="Product title"
attribute="title"
/>
</Table>
</Example>
);
}
renderOrderableExample() {
return (
<Example title="Orderable table">
<Table
data={this.state.orderableTableData}
onExpand={this.onExpandClick}
onOrder={this.onOrder}
>
<TableColumn
title="ID"
attribute="id"
width={60}
copyable
center
/>
<TableColumn
title="Product title"
attribute="title"
/>
</Table>
</Example>
);
}
render() {
return (
<ExampleSet title="Tables">
{this.renderDefaultExample()}
{this.renderExpandableExample()}
{this.renderEditableExample()}
{this.renderOrderableExample()}
</ExampleSet>
);
}
}
export default TableExamples;
|
clients/packages/admin-client/src/pages/admin/mobilizations/widgets/donation/settings/autofire/page.js | nossas/bonde-client | import PropTypes from 'prop-types';
import React from 'react';
import { Loading } from '../../../../../../../components/await';
import { FormAutofire } from '../../../../../../../mobilizations/widgets/components';
const DonationSettingsAutofirePage = (props) =>
!props.widget ? <Loading /> : <FormAutofire {...props} />;
DonationSettingsAutofirePage.propTypes = {
// Injected by redux-form
fields: PropTypes.object.isRequired,
// Injected by container
mobilization: PropTypes.object.isRequired,
widget: PropTypes.object.isRequired,
asyncWidgetUpdate: PropTypes.func.isRequired,
};
export default DonationSettingsAutofirePage;
|
analysis/warlockdemonology/src/modules/talents/DemonicStrength.js | yajinni/WoWAnalyzer | import React from 'react';
import Analyzer, { SELECTED_PLAYER, SELECTED_PLAYER_PET } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import Pets from 'parser/shared/modules/Pets';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import ItemDamageDone from 'parser/ui/ItemDamageDone';
import PETS from '../pets/PETS';
const BUFFER = 200;
class DemonicStrength extends Analyzer {
static dependencies = {
pets: Pets,
};
_removedAt = null;
damage = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.DEMONIC_STRENGTH_TALENT.id);
this.addEventListener(Events.damage.by(SELECTED_PLAYER_PET).spell(SPELLS.FELSTORM_DAMAGE), this.handleFelstormDamage);
this.addEventListener(Events.removebuff.by(SELECTED_PLAYER).spell(SPELLS.DEMONIC_STRENGTH_TALENT), this.handleRemoveDemonicStrength);
}
handleFelstormDamage(event) {
// pet ability Felstorm and this "empowered" Felstorm can't be active at the same time, they're exclusive (the game doesn't let you cast it)
const petInfo = this.owner.playerPets.find(pet => pet.id === event.sourceID);
if (petInfo.guid === PETS.GRIMOIRE_FELGUARD.guid) {
// Grimoire: Felguard uses same spell IDs
return;
}
const pet = this.pets.getSourceEntity(event);
if (pet.hasBuff(SPELLS.DEMONIC_STRENGTH_TALENT.id) || event.timestamp <= this._removedAt + BUFFER) {
// the last empowered Felstorm usually happens in this order:
// Felstorm cast -> Demonic Strength removebuff -> Felstorm damages
// So in order to also count the last empowered damage events, we also count damage events within 200ms of the removebuff
this.damage += event.amount + (event.absorbed || 0);
}
}
handleRemoveDemonicStrength(event) {
this._removedAt = event.timestamp;
}
statistic() {
return (
<Statistic
category={STATISTIC_CATEGORY.TALENTS}
size="flexible"
tooltip={`${formatThousands(this.damage)} damage`}
>
<BoringSpellValueText spell={SPELLS.DEMONIC_STRENGTH_TALENT}>
<ItemDamageDone amount={this.damage} />
</BoringSpellValueText>
</Statistic>
);
}
}
export default DemonicStrength;
|
contrib/hello-world-react/src/www/js/components/login.js | intuit/wasabi | /*global WASABI*/
import React from 'react';
export class LoginComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
errorMessage: ''
};
this.onChange = this.onChange.bind(this);
this.validate = this.validate.bind(this);
this.submit = this.submit.bind(this);
}
validate() {
if (typeof WASABI === 'undefined') {
console.log('The wasabi.js library was not loaded.');
this.setState({
errorMessage: 'The required version of the Wasabi server is missing!'
});
return false;
}
if (this.state.username === '' || !this.state.username) {
this.setState({
errorMessage: 'Error: name must be present'
});
return false;
}
if (this.state.password === '' || !this.state.password) {
this.setState({
errorMessage: 'Error: password must be present'
});
return false;
}
this.setState({
errorMessage: ''
});
return true;
}
submit() {
if (this.validate()) {
console.log('Login submitted');
// TODO: We would usually actually do a login, but for this test app, we let them in.
// var data = JSON.stringify({name: login.name, cost: login.cost});
// $http.post('http://localhost:3000/login', data).success(function(data) {
// console.log(data);
// });
let sessionObj = {
'login': {
'name': this.state.username,
'loggedIn': true
}
};
sessionStorage.setItem('session', JSON.stringify(sessionObj));
// Set up properties that will be the same on all Wasabi calls.
WASABI.setOptions({
'applicationName': 'MyStore',
'experimentName': 'TestBuyButtonColor',
'protocol': 'http',
'host': 'localhost:8080'
});
// Check Wasabi to see if this user should be in the test and which bucket.
WASABI.getAssignment({
'userID': this.state.username
}).then(
(response) => {
console.log('getAssignment: success');
console.log(JSON.stringify(response));
// This object will include the assignment made and the status, which might tell you the experiment
// has not been started, etc.
// Note that if the experiment doesn't exist or hasn't been started, response.assignment is undefined, which is OK.
sessionObj.switches = {};
if (response.assignment === 'BlueButton') {
sessionObj.switches = {
'buyButtonColor': '#7474EA'
};
}
else if (response.assignment === 'GreenButton') {
sessionObj.switches = {
'buyButtonColor': 'green'
};
}
// else the user got the Control bucket, and we don't do anything.
sessionStorage.setItem('session', JSON.stringify(sessionObj));
this.props.setLoggedInFunc();
},
(error) => {
console.log('getAssignment: error');
console.dir(error);
sessionStorage.setItem('session', JSON.stringify(sessionObj));
this.props.setLoggedInFunc();
}
);
}
else {
console.log('invalid');
}
}
onChange(e) {
this.setState({
errorMessage: '',
[e.target.name]: e.target.value
});
}
render() {
return <section>
<section className="loginBox">
<div className="loginTitle">Welcome to our Store </div>
<div className="loginPrompt">Please Login</div>
<form>
<div className="loginDiv">
<label>User Name: </label> <input type="text" name="username" value={this.state.username} onChange={this.onChange} />
</div>
<div>
<label>Password: </label> <input type="password" name="password" value={this.state.password} onChange={this.onChange} />
</div>
</form>
<div><button className="loginBtn" onClick={this.submit}>Submit</button></div>
<div className="loginError">{this.state.errorMessage}</div>
</section>
</section>;
}
}
|
docs/general/flex/index.js | valzav/react-foundation-components | import React from 'react';
import { FlexParent, FlexChild } from '../../../src/flex';
const rowStyle = { border: 'solid 1px #c6c6c6', marginTop: '0.5rem', marginBottom: '0.5rem' };
const styleOdd = { background: '#eee', minWidth: '250px' };
const styleEven = { background: '#e1e1e1', minWidth: '250px' };
const FlexPage = () => (
<div>
<h1>Flexbox</h1>
<p>
Simple layout with flexbox properties.
</p>
<h2>Basics</h2>
<p>Importing the Flex components:</p>
<pre>
<code>
{
`// Import with local scoped class names (via CSS Modules)
import { FlexParent, FlexChild } from 'react-foundation-components/lib/flex';
or
// Import with global scoped class names
import { FlexParent, FlexChild } from 'react-foundation-components/lib/global/flex';`
}
</code>
</pre>
<p>
The FlexParent component can horizontally or vertically align its children. All immediate
children of FlexParent should be FlexChild components. A FlexChild component can
vertically align itself.
</p>
<h2>Horizontal Alignment</h2>
<p>
By default, all flex children align to the left but this can be overridden by setting the
<code>horizontalAlignment</code> prop to left, right, center, justify or spaced.
</p>
<pre>
<code>
{
`<FlexParent horizontalAlignment="left">
<FlexChild>Aligned to</FlexChild>
<FlexChild>the left</FlexChild>
</FlexParent>
<FlexParent horizontalAlignment="right">
<FlexChild>Aligned to</FlexChild>
<FlexChild>the right</FlexChild>
</FlexParent>
<FlexParent horizontalAlignment="center">
<FlexChild>Aligned to</FlexChild>
<FlexChild>the middle</FlexChild>
</FlexParent>
<FlexParent horizontalAlignment="justify">
<FlexChild>Aligned to</FlexChild>
<FlexChild>the edges</FlexChild>
</FlexParent>
<FlexParent horizontalAlignment="spaced">
<FlexChild>Aligned to</FlexChild>
<FlexChild>the space around</FlexChild>
</FlexParent>`
}
</code>
</pre>
<FlexParent horizontalAlignment="left" style={rowStyle}>
<FlexChild style={styleOdd}>Aligned to</FlexChild>
<FlexChild style={styleEven}>the left</FlexChild>
</FlexParent>
<FlexParent horizontalAlignment="right" style={rowStyle}>
<FlexChild style={styleOdd}>Aligned to</FlexChild>
<FlexChild style={styleEven}>the right</FlexChild>
</FlexParent>
<FlexParent horizontalAlignment="center" style={rowStyle}>
<FlexChild style={styleOdd}>Aligned to</FlexChild>
<FlexChild style={styleEven}>the middle</FlexChild>
</FlexParent>
<FlexParent horizontalAlignment="justify" style={rowStyle}>
<FlexChild style={styleOdd}>Aligned to</FlexChild>
<FlexChild style={styleEven}>the edges</FlexChild>
</FlexParent>
<FlexParent horizontalAlignment="spaced" style={rowStyle}>
<FlexChild style={styleOdd}>Aligned to</FlexChild>
<FlexChild style={styleEven}>the space around</FlexChild>
</FlexParent>
<hr />
<h2>Vertical Alignment</h2>
<p>
By default, all flex children stretch to be equal height but this can be overridden by
setting the <code>verticalAlignment</code> prop to top, middle, bottom or stretch.
</p>
<pre>
<code>
{
`<FlexParent verticalAlignment="top">
<FlexChild>I'm at the top!</FlexChild>
<FlexChild>
I am as well, but I have so much text I take up more space! Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Quis facere ducimus earum minus, inventore, ratione
doloremque deserunt neque perspiciatis accusamus explicabo soluta, quod provident
distinctio aliquam omnis? Labore, ullam possimus.
</FlexChild>
</FlexParent>
<FlexParent verticalAlignment="middle">
<FlexChild>I'm in the middle!</FlexChild>
<FlexChild>
I am as well, but I have so much text I take up more space! Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Quis facere ducimus earum minus, inventore, ratione
doloremque deserunt neque perspiciatis accusamus explicabo soluta, quod provident
distinctio aliquam omnis? Labore, ullam possimus.
</FlexChild>
</FlexParent>
<FlexParent verticalAlignment="bottom">
<FlexChild>I'm at the bottom!</FlexChild>
<FlexChild>
I am as well, but I have so much text I take up more space! Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Quis facere ducimus earum minus, inventore, ratione
doloremque deserunt neque perspiciatis accusamus explicabo soluta, quod provident
distinctio aliquam omnis? Labore, ullam possimus.
</FlexChild>
</FlexParent>
<FlexParent verticalAlignment="stretch">
<FlexChild>These colums have the same height.</FlexChild>
<FlexChild>
That's right, equal-height columns are possible with Flexbox too! Lorem ipsum dolor sit
amet, consectetur adipisicing elit. Voluptatum, tempora. Impedit eius officia possimus
laudantium? Molestiae eaque, sapiente atque doloremque placeat! In sint, fugiat saepe
sunt dolore tempore amet cupiditate.
</FlexChild>
</FlexParent>`
}
</code>
</pre>
<FlexParent verticalAlignment="top" style={rowStyle}>
<FlexChild style={styleOdd}>I'm at the top!</FlexChild>
<FlexChild style={styleEven}>
I am as well, but I have so much text I take up more space! Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Quis facere ducimus earum minus, inventore, ratione
doloremque deserunt neque perspiciatis accusamus explicabo soluta, quod provident
distinctio aliquam omnis? Labore, ullam possimus.
</FlexChild>
</FlexParent>
<FlexParent verticalAlignment="middle" style={rowStyle}>
<FlexChild style={styleOdd}>I'm in the middle!</FlexChild>
<FlexChild style={styleEven}>
I am as well, but I have so much text I take up more space! Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Quis facere ducimus earum minus, inventore, ratione
doloremque deserunt neque perspiciatis accusamus explicabo soluta, quod provident
distinctio aliquam omnis? Labore, ullam possimus.
</FlexChild>
</FlexParent>
<FlexParent verticalAlignment="bottom" style={rowStyle}>
<FlexChild style={styleOdd}>I'm at the bottom!</FlexChild>
<FlexChild style={styleEven}>
I am as well, but I have so much text I take up more space! Lorem ipsum dolor sit amet,
consectetur adipisicing elit. Quis facere ducimus earum minus, inventore, ratione
doloremque deserunt neque perspiciatis accusamus explicabo soluta, quod provident
distinctio aliquam omnis? Labore, ullam possimus.
</FlexChild>
</FlexParent>
<FlexParent verticalAlignment="stretch" style={rowStyle}>
<FlexChild style={styleOdd}>These colums have the same height.</FlexChild>
<FlexChild style={styleEven}>
That's right, equal-height columns are possible with Flexbox too! Lorem ipsum dolor sit
amet, consectetur adipisicing elit. Voluptatum, tempora. Impedit eius officia possimus
laudantium? Molestiae eaque, sapiente atque doloremque placeat! In sint, fugiat saepe
sunt dolore tempore amet cupiditate.
</FlexChild>
</FlexParent>
<p>
<code>verticalAlignment</code> prop can also be set on a FlexChild to vary vertical
alignment within a FlexParent.
</p>
<pre>
<code>
{
`<FlexParent>
<FlexChild verticalAlignment="bottom">Align bottom.</FlexChild>
<FlexChild verticalAlignment="middle">Align middle.</FlexChild>
<FlexChild verticalAlignment="top">Align top.</FlexChild>
<FlexChild verticalAlignment="stretch">Align stretch.</FlexChild>
<FlexChild>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non harum laborum
cum voluptate vel, eius adipisci similique dignissimos nobis at excepturi incidunt fugit
molestiae quaerat, consequuntur porro temporibus. Nisi, ex?
</FlexChild>
</FlexParent>`
}
</code>
</pre>
<FlexParent style={rowStyle}>
<FlexChild style={styleOdd} verticalAlignment="bottom">Align bottom.</FlexChild>
<FlexChild style={styleEven} verticalAlignment="middle">Align middle.</FlexChild>
<FlexChild style={styleOdd} verticalAlignment="top">Align top.</FlexChild>
<FlexChild style={styleEven} verticalAlignment="stretch">Align stretch.</FlexChild>
<FlexChild style={styleOdd}>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Non harum laborum
cum voluptate vel, eius adipisci similique dignissimos nobis at excepturi incidunt fugit
molestiae quaerat, consequuntur porro temporibus. Nisi, ex?
</FlexChild>
</FlexParent>
<hr />
<h2>Source Ordering</h2>
<p>
Set the
<code>smallOrder</code>, <code>mediumOrder</code>, <code>largeOrder</code>
, <code>xlargeOrder</code> and/or <code>xxlargeOrder</code> to shift children around
between breakpoints. These props accept a number between 1 and 6. Lower numbers are
placed first. If multiple children have the same number, they are sorted in the order
they appear
</p>
<pre>
<code>
{
`<FlexParent>
<FlexChild mediumOrder={1} smallOrder={2}>
This column will come second on small, and first on medium and larger.
</FlexChild>
<FlexChild mediumOrder={2} smallOrder={1}>
This column will come first on small, and second on medium and larger.
</FlexChild>
</FlexParent>`
}
</code>
</pre>
<FlexParent style={rowStyle}>
<FlexChild mediumOrder={1} smallOrder={2} style={styleOdd}>
This column will come second on small, and first on medium and larger.
</FlexChild>
<FlexChild mediumOrder={2} smallOrder={1} style={styleEven}>
This column will come first on small, and second on medium and larger.
</FlexChild>
</FlexParent>
</div>
);
export default FlexPage;
|
app/javascript/mastodon/features/list_adder/index.js | Ryanaka/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { injectIntl } from 'react-intl';
import { setupListAdder, resetListAdder } from '../../actions/lists';
import { createSelector } from 'reselect';
import List from './components/list';
import Account from './components/account';
import NewListForm from '../lists/components/new_list_form';
// hack
const getOrderedLists = createSelector([state => state.get('lists')], lists => {
if (!lists) {
return lists;
}
return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title')));
});
const mapStateToProps = state => ({
listIds: getOrderedLists(state).map(list=>list.get('id')),
});
const mapDispatchToProps = dispatch => ({
onInitialize: accountId => dispatch(setupListAdder(accountId)),
onReset: () => dispatch(resetListAdder()),
});
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class ListAdder extends ImmutablePureComponent {
static propTypes = {
accountId: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
onInitialize: PropTypes.func.isRequired,
onReset: PropTypes.func.isRequired,
listIds: ImmutablePropTypes.list.isRequired,
};
componentDidMount () {
const { onInitialize, accountId } = this.props;
onInitialize(accountId);
}
componentWillUnmount () {
const { onReset } = this.props;
onReset();
}
render () {
const { accountId, listIds } = this.props;
return (
<div className='modal-root__modal list-adder'>
<div className='list-adder__account'>
<Account accountId={accountId} />
</div>
<NewListForm />
<div className='list-adder__lists'>
{listIds.map(ListId => <List key={ListId} listId={ListId} />)}
</div>
</div>
);
}
}
|
src/parser/paladin/holy/modules/beacons/BeaconHealingDone.js | fyruna/WoWAnalyzer | import React from 'react';
import { Trans } from '@lingui/macro';
import Panel from 'interface/statistics/Panel';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import HealingValue from 'parser/shared/modules/HealingValue';
import HealingDone from 'parser/shared/modules/throughput/HealingDone';
import BeaconHealSource from './BeaconHealSource';
import BeaconHealingBreakdown from './BeaconHealingBreakdown';
class BeaconHealingDone extends Analyzer {
static dependencies = {
beaconHealSource: BeaconHealSource,
healingDone: HealingDone,
};
_totalBeaconHealing = new HealingValue();
_beaconHealingBySource = {};
constructor(options) {
super(options);
this.addEventListener(this.beaconHealSource.beacontransfer.by(SELECTED_PLAYER), this._onBeaconTransfer);
}
_onBeaconTransfer(event) {
this._totalBeaconHealing = this._totalBeaconHealing.add(event.amount, event.absorbed, event.overheal);
const source = event.originalHeal;
const spellId = source.ability.guid;
let sourceHealing = this._beaconHealingBySource[spellId];
if (!sourceHealing) {
sourceHealing = this._beaconHealingBySource[spellId] = {
ability: source.ability,
healing: new HealingValue(),
};
}
sourceHealing.healing = sourceHealing.healing.add(event.amount, event.absorbed, event.overheal);
}
statistic() {
return (
<Panel
title={<Trans>Beacon healing sources</Trans>}
explanation={(
<Trans>
Beacon healing is triggered by the <b>raw</b> healing done of your primary spells. This breakdown shows the amount of effective beacon healing replicated by each beacon transfering heal.
</Trans>
)}
position={120}
pad={false}
>
<BeaconHealingBreakdown
totalHealingDone={this.healingDone.total}
totalBeaconHealing={this._totalBeaconHealing}
beaconHealingBySource={this._beaconHealingBySource}
fightDuration={this.owner.fightDuration}
/>
</Panel>
);
}
}
export default BeaconHealingDone;
|
webpack/scenes/Subscriptions/components/SubscriptionsTable/components/Dialogs/UpdateDialog.js | ares/katello | import React from 'react';
import PropTypes from 'prop-types';
import { sprintf } from 'foremanReact/common/I18n';
import { MessageDialog } from 'patternfly-react';
import { buildPools } from '../../SubscriptionsTableHelpers';
import { renderTaskStartedToast } from '../../../../../Tasks/helpers';
import { BLOCKING_FOREMAN_TASK_TYPES } from '../../../../SubscriptionConstants';
const UpdateDialog = ({
show,
updatedQuantity,
updateQuantity,
showUpdateConfirm,
bulkSearch,
organization,
task,
enableEditing,
}) => {
const quantityLength = Object.keys(updatedQuantity).length;
const confirmEdit = () => {
showUpdateConfirm(false);
if (quantityLength > 0) {
updateQuantity(buildPools(updatedQuantity))
.then(() =>
bulkSearch({
action: `organization '${organization.owner_details.displayName}'`,
result: 'pending',
label: BLOCKING_FOREMAN_TASK_TYPES.join(' or '),
}))
.then(() => renderTaskStartedToast(task));
}
enableEditing(false);
};
return (
<MessageDialog
show={show}
title={__('Editing Entitlements')}
secondaryContent={
// eslint-disable-next-line react/no-danger
<p dangerouslySetInnerHTML={{
__html: sprintf(
__("You're making changes to %(entitlementCount)s entitlement(s)"),
{
entitlementCount: `<b>${quantityLength}</b>`,
},
),
}}
/>
}
primaryActionButtonContent={__('Save')}
primaryAction={confirmEdit}
secondaryActionButtonContent={__('Cancel')}
secondaryAction={() => showUpdateConfirm(false)}
onHide={() => showUpdateConfirm(false)}
/>);
};
UpdateDialog.propTypes = {
show: PropTypes.bool.isRequired,
updateQuantity: PropTypes.func.isRequired,
updatedQuantity: PropTypes.shape(PropTypes.Object).isRequired,
showUpdateConfirm: PropTypes.func.isRequired,
bulkSearch: PropTypes.func,
organization: PropTypes.shape({
owner_details: PropTypes.shape({
displayName: PropTypes.string,
}),
}),
task: PropTypes.shape({}),
enableEditing: PropTypes.func.isRequired,
};
UpdateDialog.defaultProps = {
task: { humanized: {} },
bulkSearch: undefined,
organization: undefined,
};
export default UpdateDialog;
|
imports/ui/components/personalInfo/components/StudentLocation.js | AdmitHub/ScholarFisher | import React, { Component } from 'react';
import Collapse from 'react-collapse';
export default class StudentLocation extends Component {
constructor(props) {
super(props);
this.state = { studentlocationopened: false };
this.drawCircle = this.drawCircle.bind(this);
this.handleStudentLocationOpened = this.handleStudentLocationOpened.bind(this);
this.handleOnChange = this.handleOnChange.bind(this);
}
handleStudentLocationOpened() {
this.setState({ studentlocationopened: !this.state.studentlocationopened });
}
handleOnChange(state) {
const {dispatchFromStudentLocation} = this.props;
dispatchFromStudentLocation(state.value)
}
handleClassName(value) {
if (this.props.selectedFromState === value) {
return 'pill selected';
}
return 'pill'
}
renderStudentLocation(states) {
const {selectedFromState}=this.props;
return states.map((currentEl, index) => (
<div
className={this.handleClassName(currentEl.value)}
onClick={() => {
this.handleOnChange(currentEl);
}}
key={index}
>
{currentEl.label}
</div>
));
}
drawCircle() {
const { selectedFromState } = this.props;
if (selectedFromState) {
return (
<span className="flex pull-right">
<i className="fa fa-check-circle fa-lg"></i>
</span>
);
} else {
return (
<span className="flex pull-right">
<i className="fa fa-circle-o fa-lg"></i>
</span>
)
};
}
render() {
const { dispatchFromStudentLocation, states } = this.props;
return (
<div>
<div className="row">
<div className="col-xs-12">
<h4
onClick={this.handleStudentLocationOpened}
>
YOUR LOCATION
{this.drawCircle()}
</h4>
<Collapse isOpened={this.state.studentlocationopened}>
<p className="caption">
<span className="caption-paragraph">
Where do you currently reside? Some scholarships are only for residents of certain states/territories
</span>
</p>
</Collapse>
</div>
</div>
<div className="row">
<div className="col-xs-12 flex-wrapper">
{this.renderStudentLocation(states)}
</div>
</div>
</div>
);
}
}
|
src/svg-icons/editor/drag-handle.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorDragHandle = (props) => (
<SvgIcon {...props}>
<path d="M20 9H4v2h16V9zM4 15h16v-2H4v2z"/>
</SvgIcon>
);
EditorDragHandle = pure(EditorDragHandle);
EditorDragHandle.displayName = 'EditorDragHandle';
EditorDragHandle.muiName = 'SvgIcon';
export default EditorDragHandle;
|
src/svg-icons/social/public.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPublic = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/>
</SvgIcon>
);
SocialPublic = pure(SocialPublic);
SocialPublic.displayName = 'SocialPublic';
SocialPublic.muiName = 'SvgIcon';
export default SocialPublic;
|
stories/Configure.stories.js | algolia/react-instantsearch | import React from 'react';
import { storiesOf } from '@storybook/react';
import { Configure } from 'react-instantsearch-dom';
import { WrapWithHits } from './util';
const stories = storiesOf('Configure', module);
stories.add('default', () => <ConfigureExample />);
class ConfigureExample extends React.Component {
constructor() {
super();
this.state = { hitsPerPage: 3 };
}
onClick = () => {
const hitsPerPage = this.state.hitsPerPage === 3 ? 1 : 3;
this.setState({ hitsPerPage });
};
render() {
return (
<WrapWithHits linkedStoryGroup="Configure.stories.js">
<Configure hitsPerPage={this.state.hitsPerPage} />
<button onClick={this.onClick}>Toggle HitsPerPage</button>
</WrapWithHits>
);
}
}
|
packages/react/components/messages-title.js | AdrianV/Framework7 | import React from 'react';
import Utils from '../utils/utils';
import Mixins from '../utils/mixins';
import __reactComponentSlots from '../runtime-helpers/react-component-slots.js';
import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js';
class F7MessagesTitle extends React.Component {
constructor(props, context) {
super(props, context);
}
render() {
const props = this.props;
const {
className,
id,
style
} = props;
const classes = Utils.classNames(className, 'messages-title', Mixins.colorClasses(props));
return React.createElement('div', {
id: id,
style: style,
className: classes
}, this.slots['default']);
}
get slots() {
return __reactComponentSlots(this.props);
}
}
__reactComponentSetProps(F7MessagesTitle, Object.assign({
id: [String, Number]
}, Mixins.colorProps));
F7MessagesTitle.displayName = 'f7-messages-title';
export default F7MessagesTitle; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.