path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ArraySpread.js | ontruck/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load(users) {
return [
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
...users,
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load([{ id: 42, name: '42' }]);
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-array-spread">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
src/components/start-screen/locale-select/LocaleSelect.js | marc-ed-raffalli/geo-game | import React from 'react';
import {Link} from 'react-router-dom';
import './_localeSelect.css';
function getLabel(name) {
return <span className="mb-4 text-capitalize text-nowrap">{name}</span>;
}
export default props => (
<div className="gg-localeSelect
d-flex flex-row flex-wrap justify-content-between
mt-2 mt-md-4">
{props.locales.map(locale => (
props.selectedLocale === locale.code
? (<div
key={locale.code}
className="col
bg-primary text-white rounded
p-2 m-2">
{getLabel(locale.name)}
</div>)
: (
<Link
to={`/${locale.code}`}
key={locale.code}
className="col
bg-light rounded
p-2 m-2">
{getLabel(locale.name)}
</Link>)
))}
</div>
);
|
src/js/modules/products/ProductTable.js | djordjes/webpack-boilerplate | import React from 'react';
import PropTypes from 'prop-types';
import ProductRow from './ProductRow';
import ProductCategoryRow from './ProductCategoryRow';
function ProductTable(props) {
console.log(props);
const rows = [];
let lastCategory = null;
props.products.forEach((product) => {
if (product.name.indexOf(props.filterText) === -1 || (!product.stocked && props.inStockOnly)) {
return;
}
if (product.category !== lastCategory) {
rows.push(<ProductCategoryRow category={product.category} key={product.category}/>);
}
rows.push(<ProductRow product={product} key={product.name}/>);
lastCategory = product.category;
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
ProductTable.propTypes = {
products: PropTypes.array,
filterText: PropTypes.string,
inStockOnly: PropTypes.bool
};
export default ProductTable;
|
src/core/containers/FleetSetup.js | getfilament/Distil | import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as hqActionCreators from '../actions/hqActionCreators';
import Section from '../components/Section';
import FleetInfoForm from '../components/forms/FleetInfoForm';
let FleetSetup = React.createClass({
handleSubmit(data) {
this.props.hqActions.hqUpdateFleet(data);
},
render() {
return (
<div>
<h1>Fleet Setup</h1>
<Section>
<FleetInfoForm onSubmit={this.handleSubmit}/>
</Section>
</div>
);
}
});
function mapStateToProps(state) {
return {};
}
function mapDispatchToProps(dispatch) {
return {
hqActions: bindActionCreators(hqActionCreators, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(FleetSetup);
|
src/utils/children.js | felipethome/material-ui | import React from 'react';
import createFragment from 'react-addons-create-fragment';
export default {
create(fragments) {
const newFragments = {};
let validChildrenCount = 0;
let firstKey;
//Only create non-empty key fragments
for (const key in fragments) {
const currentChild = fragments[key];
if (currentChild) {
if (validChildrenCount === 0) firstKey = key;
newFragments[key] = currentChild;
validChildrenCount++;
}
}
if (validChildrenCount === 0) return undefined;
if (validChildrenCount === 1) return newFragments[firstKey];
return createFragment(newFragments);
},
extend(children, extendedProps, extendedChildren) {
return React.isValidElement(children) ?
React.Children.map(children, (child) => {
const newProps = typeof (extendedProps) === 'function' ?
extendedProps(child) : extendedProps;
const newChildren = typeof (extendedChildren) === 'function' ?
extendedChildren(child) : extendedChildren ?
extendedChildren : child.props.children;
return React.cloneElement(child, newProps, newChildren);
}) : children;
},
};
|
src/routes.js | jch254/audio-insights | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import AboutPage from './shared-components/AboutPage';
import GlossaryPage from './shared-components/GlossaryPage';
import HomePage from './shared-components/HomePage';
import NotFoundPage from './shared-components/NotFoundPage';
import App from './app/App';
import ArtistsPage from './artists/ArtistsPage';
import SpotifyLoginCallbackHandler from './auth/SpotifyLoginCallbackHandler';
import RestrictedPage from './auth/RestrictedPage';
import MosaicPage from './mosaic/MosaicPage';
import RecommendedPage from './recommended/RecommendedPage';
export default (
<Route
path="/"
component={App}
onChange={(prevState, nextState) => {
if (nextState.location.action !== 'POP') {
window.scrollTo(0, 0);
}
}}
>
<IndexRoute component={HomePage} />
<Route path="/about" component={AboutPage} />
<Route path="/glossary" component={GlossaryPage} />
<Route path="/spotifylogincallback" component={SpotifyLoginCallbackHandler} />
<Route component={RestrictedPage}>
<Route path="/mosaic" component={MosaicPage} />
<Route path="/recommended" component={RecommendedPage} />
<Route path="/artists" component={ArtistsPage} />
</Route>
<Route path="*" component={NotFoundPage} />
</Route>
);
|
src/svg-icons/image/photo-camera.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImagePhotoCamera = pure(ImagePhotoCamera);
ImagePhotoCamera.displayName = 'ImagePhotoCamera';
ImagePhotoCamera.muiName = 'SvgIcon';
export default ImagePhotoCamera;
|
app/App.js | basask/react-router-material-ui-seed | import React from 'react';
import ReactDom from 'react-dom';
import Routes from './components/Routes';
import './stylesheet/index.scss';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
ReactDom.render(
<Routes />,
document.getElementById('app')
);
|
src/containers/MyAccount/MyAccount.js | petorious/dmprov-app | import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { injectIntl, intlShape } from 'react-intl';
import { Activity } from '../../containers/Activity'
import { setSimpleValue } from '../../store/simpleValues/actions';
import MyAccountForm from '../../components/Forms/MyAccountForm';
import { withRouter } from 'react-router-dom';
import FontIcon from 'material-ui/FontIcon';
import FlatButton from 'material-ui/FlatButton';
import Dialog from 'material-ui/Dialog';
import firebase from 'firebase';
import { withFirebase, FireForm } from 'firekit';
import { GoogleIcon, FacebookIcon, GitHubIcon, TwitterIcon } from '../../components/Icons';
import muiThemeable from 'material-ui/styles/muiThemeable';
import { change, submit, formValueSelector } from 'redux-form';
import { ResponsiveMenu } from 'material-ui-responsive-menu'
const path='/users/'
const form_name='my_account'
class MyAccount extends Component {
getProviderIcon = (provider) => {
const { muiTheme } = this.props
const color = muiTheme.palette.primary2Color
switch (provider.PROVIDER_ID) {
case 'google.com':
return <GoogleIcon color={color}/>
case 'facebook.com':
return <FacebookIcon color={color}/>
case 'twitter.com':
return <TwitterIcon color={color}/>
case 'github.com':
return <GitHubIcon color={color}/>
default:
return undefined
}
}
handleEmailVerificationsSend = () => {
const { firebaseApp } = this.props;
firebaseApp.auth().currentUser.sendEmailVerification().then(() => {
alert('Verification E-Mail send');
})
}
handlePhotoUploadSuccess = (snapshot) => {
const { setSimpleValue, change}=this.props;
change(form_name, 'photoURL', snapshot.downloadURL);
setSimpleValue('new_company_photo', undefined);
}
handleUserDeletion = () => {
const { change, submit } = this.props;
change(form_name, 'delete_user', true);
submit(form_name)
}
getProvider = (provider) => {
if(provider.indexOf('facebook')>-1){
return new firebase.auth.FacebookAuthProvider();
}
if(provider.indexOf('github')>-1){
return new firebase.auth.GithubAuthProvider();
}
if(provider.indexOf('google')>-1){
return new firebase.auth.GoogleAuthProvider();
}
if(provider.indexOf('twitter')>-1){
return new firebase.auth.TwitterAuthProvider();
}
if(provider.indexOf('phone')>-1){
return new firebase.auth.PhoneAuthProvider();
}
throw new Error('Provider is not supported!');
};
reauthenticateUser = (values, onSuccess) => {
const { auth, firebaseApp, authError} = this.props;
if (this.isLinkedWithProvider('password') && !values) {
if(onSuccess && onSuccess instanceof Function){
onSuccess();
}
} else if (this.isLinkedWithProvider('password') && values) {
const credential = firebase.auth.EmailAuthProvider.credential(
auth.email,
values.old_password
)
firebaseApp.auth().currentUser.reauthenticateWithCredential(credential)
.then(() => {
if(onSuccess && onSuccess instanceof Function){
onSuccess();
}
}, e=>{authError(e)})
} else {
firebaseApp.auth().currentUser.reauthenticateWithPopup(this.getProvider(auth.providerData[0].providerId)).then(()=>{
if(onSuccess && onSuccess instanceof Function){
onSuccess()
}
}, e=>{authError(e)})
}
}
isLinkedWithProvider = (provider) => {
const { auth } = this.props;
let providerId = ''
if (typeof provider === 'string' || provider instanceof String) {
providerId = provider
} else {
providerId = provider.PROVIDER_ID
}
try {
return auth && auth.providerData && auth.providerData.find((p)=>{return p.providerId===providerId})!==undefined;
} catch(e) {
return false;
}
}
linkUserWithPopup = (provider) => {
const { firebaseApp, authError, authStateChanged } =this.props;
firebaseApp.auth().currentUser.linkWithPopup(this.getProvider(provider.PROVIDER_ID))
.then((payload) => {
authStateChanged(firebaseApp.auth().currentUser);
}, e=>{authError(e)})
}
handleCreateValues = (values) => {
return false;
}
clean = (obj) => {
Object.keys(obj).forEach((key) => (obj[key] === undefined) && delete obj[key]);
return obj
}
handleUpdateValues = (values, dispatch, props) => {
const { auth, firebaseApp, authStateChanged, authError }=this.props;
const simpleChange=(values.displayName && values.displayName.localeCompare(auth.displayNam)) ||
(values.photoURL && values.photoURL.localeCompare(auth.photoURL));
let simpleValues={
displayName: values.displayName,
photoURL: values.photoURL
}
//Change simple data
if(simpleChange){
firebaseApp.auth().currentUser.updateProfile(simpleValues).then(() => {
firebaseApp.database().ref(`users/${auth.uid}`).update(this.clean(simpleValues)).then(()=>{
authStateChanged(values);
}, e =>{authError(e)});
}, e => {authError(e)});
}
//Change email
if(values.email && values.email.localeCompare(auth.email)){
this.reauthenticateUser(values, ()=>{
firebaseApp.auth().currentUser.updateEmail(values.email).then(() => {
firebaseApp.database().ref(`users/${auth.uid}`).update({email: values.email}).then(()=>{
authStateChanged({email: values.email});
}, e =>{authError(e)});
}, e => {
authError(e)
// eslint-disable-next-line
if (e.code == 'auth/requires-recent-login') {
firebaseApp.auth().signOut().then(function() {
setTimeout(() => {
alert('Please sign in again to change your email.');
}, 1);
});
}
});
})
}
//Change password
if(values.new_password){
this.reauthenticateUser( values, ()=>{
firebaseApp.auth().currentUser.updatePassword(values.new_password).then(() => {
firebaseApp.auth().signOut();
}, e => {
authError(e)
// eslint-disable-next-line
if (e.code == 'auth/requires-recent-login') {
firebaseApp.auth().signOut().then(() => {
setTimeout(() => {
alert('Please sign in again to change your password.');
}, 1);
});
}
});
})
}
//We manage the data saving above
return false;
}
handleClose = () => {
const { setSimpleValue }=this.props;
setSimpleValue('delete_user', false);
setSimpleValue('auth_menu', false);
}
handleDelete = () => {
const { firebaseApp, authError }=this.props;
this.reauthenticateUser( false , ()=>{
firebaseApp.auth().currentUser.delete()
.then(() => {
this.handleClose();
}, e => {
authError(e)
// eslint-disable-next-line
if (e.code == 'auth/requires-recent-login') {
firebaseApp.auth().signOut().then(() => {
setTimeout(() => {
alert('Please sign in again to delete your account.');
}, 1);
});
}
});
});
}
validate = (values) => {
const { auth } =this.props;
const providerId=auth.providerData[0].providerId;
const errors = {}
if (!values.displayName) {
errors.displayName = 'Required'
}
if (!values.email) {
errors.email = 'Required'
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address'
} else if (!values.old_password && providerId==='password' && auth.email.localeCompare(values.email)){
errors.old_password = 'For email change enter your pasword'
}
if(values.new_password){
if(values.new_password.length <6){
errors.new_password = 'Password should be at least 6 characters'
}else if (values.new_password.localeCompare(values.new_password_confirmation)) {
errors.new_password = 'Must be equal'
errors.new_password_confirmation = 'Must be equal'
}
}
return errors
}
render() {
const {
history,
intl,
setSimpleValue,
delete_user,
auth,
muiTheme,
submit
} = this.props;
const actions = [
<FlatButton
label={intl.formatMessage({id: 'cancel'})}
primary={true}
onClick={this.handleClose}
/>,
<FlatButton
label={intl.formatMessage({id: 'delete'})}
secondary={true}
onClick={this.handleDelete}
/>,
]
const menuList = [
{
hidden: auth.uid === undefined,
text: intl.formatMessage({id: 'save'}),
icon: <FontIcon className="material-icons" color={muiTheme.palette.canvasColor}>save</FontIcon>,
tooltip:intl.formatMessage({id: 'save'}),
onClick: () => submit('my_account')
},
{
hidden: auth.uid === undefined,
text: intl.formatMessage({id: 'delete'}),
icon: <FontIcon className="material-icons" color={muiTheme.palette.canvasColor}>delete</FontIcon>,
tooltip: intl.formatMessage({id: 'delete'}),
onClick: () => setSimpleValue('delete_user', true)
}
]
return (
<Activity
iconStyleRight={{width:'50%'}}
iconElementRight={
<ResponsiveMenu
iconMenuColor={muiTheme.palette.canvasColor}
menuList={menuList}
/>
}
title={intl.formatMessage({id: 'my_account'})}>
{
auth.uid &&
<div style={{margin: 15, display: 'flex'}}>
<FireForm
validate={this.validate}
name={form_name}
path={path}
handleUpdateValues={this.handleUpdateValues}
onSubmitSuccess={(values)=>{history.push('/dashboard'); setSimpleValue('auth_menu', false)}}
onDelete={(values)=>{history.push('/signin');}}
handleCreateValues={this.handleCreateValues}
uid={auth.uid}>
<MyAccountForm
linkUserWithPopup={this.linkUserWithPopup}
isLinkedWithProvider={this.isLinkedWithProvider}
getProviderIcon={this.getProviderIcon}
handleEmailVerificationsSend={this.handleEmailVerificationsSend}
handlePhotoUploadSuccess={this.handlePhotoUploadSuccess}
handleUserDeletion={this.handleUserDeletion}
{...this.props}
/>
</FireForm>
</div>
}
<Dialog
title={intl.formatMessage({id: 'delete_account_dialog_title'})}
actions={actions}
modal={false}
open={delete_user===true}
onRequestClose={this.handleClose}>
{intl.formatMessage({id: 'delete_account_dialog_message'})}
</Dialog>
</Activity>
);
}
}
MyAccount.propTypes = {
history: PropTypes.object,
setSimpleValue: PropTypes.func.isRequired,
intl: intlShape.isRequired,
isGranted: PropTypes.func,
auth: PropTypes.object.isRequired,
vehicle_types: PropTypes.array,
};
const selector = formValueSelector(form_name)
const mapStateToProps = (state) => {
const { intl, simpleValues, auth } = state
const delete_user = simpleValues.delete_user
const new_user_photo = simpleValues.new_user_photo
return {
new_user_photo,
intl,
delete_user,
auth,
photoURL: selector(state, 'photoURL'),
old_password: selector(state, 'old_password')
};
};
export default connect(
mapStateToProps, { setSimpleValue, change, submit }
)(injectIntl(withRouter(muiThemeable()(withFirebase(MyAccount)))))
|
test/mochaTestHelper.js | glaserp/Maturita-Project | import Bluebird from 'bluebird';
import chai, {assert, expect} from 'chai';
import React from 'react';
import sinon from 'sinon';
import sinonAsPromised from 'sinon-as-promised';
import sinonChai from 'sinon-chai';
import TestUtils from 'react-addons-test-utils';
chai.should();
chai.use(sinonChai);
// Use Bluebird Promises inside of sinon stubs.
// Bluebird has better error reporting for unhandled Promises.
sinonAsPromised(Bluebird);
export {
assert,
chai,
expect,
React,
sinon,
sinonChai,
TestUtils
};
|
src/routes/app/routes/pages/routes/faqs/components/FAQs.js | ahthamrin/kbri-admin2 | import React from 'react';
import QueueAnim from 'rc-queue-anim';
const Hero = () => (
<section className="hero">
<div className="hero-content">
<h1 className="hero-title">FAQs</h1>
</div>
<p className="hero-tagline">Frequently Asked Questions</p>
</section>
);
const FAQs = () => (
<article className="article padding-lg-v article-dark article-bordered">
<div className="container-fluid with-maxwidth">
<div className="row">
<div className="col-xl-6">
<h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit?</h4>
<p>BEligendi amet quam inventore nam nostrum quaerat aliquam enim dicta illo laboriosam, quia odio voluptas animi consequatur non nemo deleniti, illum tempore assumenda reprehenderit corporis vel impedit nihil earum. Voluptas explicabo voluptatem iste libero officia cum voluptate, qui laboriosam atque.</p>
<div className="divider divider-xl divider-dashed" />
<h4>Doloribus dolores, officia voluptatibus deserunt ratione debitis laboriosam?</h4>
<p>Ut tempora, ad eos. Eveniet asperiores quaerat cupiditate quo, possimus officiis deserunt porro dolor mollitia iure minima id incidunt facilis accusamus ea quod perferendis veniam quas, et distinctio dolores corporis magni sapiente hic. Non saepe, veritatis, molestias debitis illum, quasi optio modi numquam harum repellat dolorem, velit blanditiis aliquid eveniet iusto! Sed reiciendis, tempora ex dolor fugiat temporibus, iste!</p>
<div className="divider divider-xl divider-dashed" />
<h4>Illo recusandae beatae facilis?</h4>
<p>Facere quo corporis distinctio recusandae pariatur possimus veniam ipsa assumenda autem, qui laborum molestias, magnam sed, voluptas optio illo. Illo, minima officia, labore ipsa fugiat, cum magnam ad error, nobis placeat suscipit? Enim magni delectus, sit, deserunt, repudiandae ratione hic et, libero nemo doloremque numquam quibusdam obcaecati pariatur dolorem.</p>
<div className="divider divider-xl divider-dashed" />
<h4>Quidem doloribus, repudiandae?</h4>
<p>Veniam optio iste aliquid dicta labore perspiciatis pariatur modi. Explicabo quisquam tenetur consectetur at possimus laborum aliquam a magni nulla veritatis accusamus consequuntur dolorem doloremque fugiat earum vero quos sit cumque saepe maiores sint, beatae ab..</p>
<p>Nemo sed ipsa consequatur facere saepe dolore velit magni autem laborum exercitationem sequi animi vel necessitatibus veritatis, a aliquam voluptas voluptatum vitae qui harum, repellendus. Ut pariatur dignissimos dolore in repudiandae porro quos a delectus doloribus odit, maxime magnam eius soluta dolorum! Recusandae illum perferendis, expedita voluptates</p>
</div>
<div className="col-xl-6">
<h4>Assumenda accusamus reiciendis obcaecati iusto?</h4>
<p>Delectus provident dolorum quam quae, facere dolore sint modi eius ut enim distinctio. Ratione adipisci fugiat deserunt provident tempora? Reprehenderit, perspiciatis excepturi fugiat neque atque tenetur nesciunt cum perferendis dolor ullam similique iure nulla amet, delectus consequuntur qui quaerat unde quidem assumenda!</p>
<p>At quis accusamus distinctio enim quaerat laudantium veniam laborum impedit cumque, minima porro. Aliquam laborum, tempore totam temporibus ea obcaecati at aut omnis fugit natus, doloribus, labore pariatur molestias velit veritatis?</p>
<div className="divider divider-xl divider-dashed" />
<h4>Alias harum culpa earum cum id aspernatur repellendus aliquam?</h4>
<p>Officia placeat vero ut quis perspiciatis ad doloribus. Voluptatum unde eaque magni ullam, veniam non illo doloremque ducimus voluptatibus quisquam, labore aspernatur ipsam optio sed necessitatibus culpa numquam vel, earum, autem porro laborum reprehenderit nulla. Nam quo, sunt, nesciunt ipsum architecto ipsa cumque minima reprehenderit dignissimos quod rem, amet deserunt, cupiditate dicta!</p>
<p>Natus omnis quam ad, repellat similique nesciunt, quia molestias obcaecati itaque odio animi eaque distinctio error ipsa. Dolore quod vel possimus minima, maxime aperiam magni omnis nemo ex ipsa doloribus quidem adipisci eius fugit dignissimos praesentium velit quis, et totam, tempore necessitatibus doloremque!</p>
<div className="divider divider-xl divider-dashed" />
<h4>Optio doloremque suscipit aut accusantium maxime provident cumque?</h4>
<p>Unde repudiandae repellat in eos, ullam, hic eveniet dolorum dignissimos illum voluptates adipisci animi vel, aspernatur quaerat quos. Accusamus nihil odit quia, eligendi molestiae necessitatibus blanditiis beatae delectus nulla quidem. Blanditiis molestias harum iste ad iure corporis culpa ratione nulla est similique incidunt nisi tempore ea dignissimos, laudantium, sequi deleniti porro veritatis. Maiores nihil, dignissimos magnam beatae quae quia natus eligendi et, quos quas. Mollitia laboriosam, magni at minus veniam voluptates ad dolor aliquid quisquam nobis maiores dolorum repudiandae, iste ea alias pariatur consectetur voluptatibus ullam repellat autem tempore necessitatibus explicabo nisi.</p>
</div>
</div>
</div>
</article>
);
const Page = () => (
<section className="page-faq chapter">
<QueueAnim type="bottom" className="ui-animate">
<div key="1"><Hero /></div>
<div key="2"><FAQs /></div>
</QueueAnim>
</section>
);
module.exports = Page;
|
src/Textfield.js | react-mdl/react-mdl | import React from 'react';
import PropTypes from 'prop-types';
import { findDOMNode } from 'react-dom';
import classNames from 'classnames';
import mdlUpgrade from './utils/mdlUpgrade';
const propTypes = {
className: PropTypes.string,
disabled: PropTypes.bool,
error: PropTypes.node,
expandable: PropTypes.bool,
expandableIcon: PropTypes.string,
floatingLabel: PropTypes.bool,
id: (props, propName, componentName) => {
const { id } = props;
if (id && typeof id !== 'string') {
return new Error(`Invalid prop \`${propName}\` supplied to \`${componentName}\`. \`${propName}\` should be a string. Validation failed.`);
}
if (!id && typeof props.label !== 'string') {
return new Error(`Invalid prop \`${propName}\` supplied to \`${componentName}\`. \`${propName}\` is required when label is an element. Validation failed.`);
}
return null;
},
inputClassName: PropTypes.string,
label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]).isRequired,
maxRows: PropTypes.number,
onChange: PropTypes.func,
pattern: PropTypes.string,
required: PropTypes.bool,
rows: PropTypes.number,
style: PropTypes.object,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
])
};
class Textfield extends React.Component {
componentDidMount() {
if (this.props.error && !this.props.pattern) {
this.setAsInvalid();
}
}
componentDidUpdate(prevProps) {
if (
this.props.required !== prevProps.required ||
this.props.pattern !== prevProps.pattern ||
this.props.error !== prevProps.error
) {
findDOMNode(this).MaterialTextfield.checkValidity();
}
if (this.props.disabled !== prevProps.disabled) {
findDOMNode(this).MaterialTextfield.checkDisabled();
}
if (this.props.value !== prevProps.value && this.inputRef !== document.activeElement) {
findDOMNode(this).MaterialTextfield.change(this.props.value);
}
if (this.props.error && !this.props.pattern) {
// Every time the input gets updated by MDL (checkValidity() or change())
// its invalid class gets reset. We have to put it again if the input is specifically set as "invalid"
this.setAsInvalid();
}
}
setAsInvalid() {
const elt = findDOMNode(this);
if (elt.className.indexOf('is-invalid') < 0) {
elt.className = classNames(elt.className, 'is-invalid');
}
}
render() {
const { className, inputClassName, id,
error, expandable, expandableIcon,
floatingLabel, label, maxRows,
rows, style, children, ...otherProps } = this.props;
const hasRows = !!rows;
const customId = id || `textfield-${label.replace(/[^a-z0-9]/gi, '')}`;
const inputTag = hasRows || maxRows > 1 ? 'textarea' : 'input';
const inputProps = {
className: classNames('mdl-textfield__input', inputClassName),
id: customId,
rows,
ref: (c) => (this.inputRef = c),
...otherProps
};
const input = React.createElement(inputTag, inputProps);
const labelContainer = <label className="mdl-textfield__label" htmlFor={customId}>{label}</label>;
const errorContainer = !!error && <span className="mdl-textfield__error">{error}</span>;
const containerClasses = classNames('mdl-textfield mdl-js-textfield', {
'mdl-textfield--floating-label': floatingLabel,
'mdl-textfield--expandable': expandable
}, className);
return expandable ? (
<div className={containerClasses} style={style}>
<label className="mdl-button mdl-js-button mdl-button--icon" htmlFor={customId}>
<i className="material-icons">{expandableIcon}</i>
</label>
<div className="mdl-textfield__expandable-holder">
{input}
{labelContainer}
{errorContainer}
</div>
{children}
</div>
) : (
<div className={containerClasses} style={style}>
{input}
{labelContainer}
{errorContainer}
{children}
</div>
);
}
}
Textfield.propTypes = propTypes;
export default mdlUpgrade(Textfield);
|
src/components/app/form/Submit.js | teamNOne/showdown | import React from 'react';
export default class Submit extends React.Component {
render() {
return <input type="submit" className={ `btn ${ this.props.type }` } value={ this.props.value } />;
}
} |
packages/demo/src/index.js | marnusw/react-css-transition-replace | import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import './transitions.css'
import Demo from './Demo'
ReactDOM.render(<Demo />, document.getElementById('root'))
|
fields/types/password/PasswordColumn.js | helloworld3q3q/keystone | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var PasswordColumn = React.createClass({
displayName: 'PasswordColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
return value ? '********' : '';
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = PasswordColumn;
|
app/components/papers/album/component.js | DenQ/electron-react-lex | import React, { Component } from 'react';
import { Paper, RaisedButton, Popover, Menu, MenuItem } from 'material-ui';
import PlayIcon from 'material-ui/svg-icons/av/play-circle-filled';
import BaseComponent from 'lex/libs/base/component';
import { I18n } from 'react-redux-i18n';
import Badge from 'material-ui/Badge';
const styles = {
paper: {
width: 167 ,
height: 167,
margin: 10,
textAlign: 'center',
display: 'inline-block',
backgroundColor: 'white',
},
menu: {
position: 'relative',
top: 20,
},
text: {
color: 'black',
},
icon: {
play: {
cursor: 'pointer',
position: 'relative',
top: 5,
width: 60,
height: 60,
}
}
};
function calculateLearning(album) {
const { size, learned } = album;
return Math.floor(learned * 100 / size);
}
export default class AlbumPaper extends BaseComponent {
constructor(props) {
super(props);
this.state = {
open: false,
};
this.handlerOnClick = this.handlerOnClick.bind(this);
this.handleTouchTap = this.handleTouchTap.bind(this);
this.handleRequestClose = this.handleRequestClose.bind(this);
}
handleTouchTap = (event) => {
event.stopPropagation();
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget,
});
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
handlerOnClick() {
const { record, urlManagerActions } = this.props;
urlManagerActions.transitionTo(`/run-album/${record.id}`);
}
render() {
this.decorateStyle();
const { record, handleToRun, handleToEdit, handleRemove } = this.props;
return (
<Paper style={styles.paper} zDepth={2} onClick={this.handlerOnClick}>
<div style={styles.text}>
{record.name}
</div>
<Badge
badgeContent={calculateLearning(record)}
secondary={true}
badgeStyle={{top: 27, right: 20}}
title="Persent learning"
>
<PlayIcon
style={styles.icon.play}
color={this.styles.palette.primary3Color}
/>
</Badge>
<div style={styles.menu}>
<RaisedButton
onClick={this.handleTouchTap}
label={I18n.t('components.papers.album.options')}
primary={true}
fullWidth={true}
/>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
onRequestClose={this.handleRequestClose}
>
<Menu>
<MenuItem
primaryText={I18n.t('components.papers.album.run')}
onClick={handleToRun}
/>
<MenuItem
primaryText={I18n.t('components.papers.album.edit')}
onClick={handleToEdit}
/>
<MenuItem
primaryText={I18n.t('components.papers.album.remove')}
onClick={handleRemove}
/>
</Menu>
</Popover>
</div>
</Paper>
);
}
}
|
frontend/src/components/Footer.js | dimkarakostas/rupture | import React from 'react';
export default class Footer extends React.Component {
render() {
return(
<footer>
<a href='https://ruptureit.com/'>RuptureIt</a>
</footer>
);
}
}
|
react-ui/src/components/NavTransition.react.js | simonlimon/varsncrafts | import React from 'react';
import { RouteTransition } from 'react-router-transition';
class NavTransition extends React.PureComponent {
render() {
return (
<div>
<RouteTransition
pathname={this.props.location.pathname}
atEnter={{ opacity: 0 }}
atLeave={{ opacity: 0 }}
atActive={{ opacity: 1 }}
runOnMount={false}
>
{this.props.children}
</RouteTransition>
</div>
);
}
}
export default NavTransition;
|
src/utils/devTools.js | BenGoldstein88/redux-chartmaker | import React from 'react';
import { createStore as initialCreateStore, compose } from 'redux';
export let createStore = initialCreateStore;
if (__DEV__) {
createStore = compose(
require('redux-devtools').devTools(),
require('redux-devtools').persistState(
window.location.href.match(/[?&]debug_session=([^&]+)\b/)
),
createStore
);
}
export function renderDevTools(store) {
if (__DEV__) {
let {DevTools, DebugPanel, LogMonitor} = require('redux-devtools/lib/react');
return (
<DebugPanel top right bottom>
<DevTools store={store} monitor={LogMonitor} />
</DebugPanel>
);
}
return null;
} |
src/svg-icons/device/battery-charging-80.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBatteryCharging80 = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h4.93L13 7v2h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9h-4v3.5z"/>
</SvgIcon>
);
DeviceBatteryCharging80 = pure(DeviceBatteryCharging80);
DeviceBatteryCharging80.displayName = 'DeviceBatteryCharging80';
DeviceBatteryCharging80.muiName = 'SvgIcon';
export default DeviceBatteryCharging80;
|
packages/canvas-media/src/shared/CanvasSelect.js | djbender/canvas-lms | /*
* Copyright (C) 2020 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
---
CanvasSelect is a wrapper on the new (as of instui 5 or 6 or so) controlled-only Select
While CanvasSelect is also controlled-only, it has a simpler api and is almost a drop-in
replacement for the old instui Select used throughout canvas at this time. One big difference
is the need to pass in an options property rather than rendering <Options> children
It does not currently support old-Select's allowCustom property
(see https://instructure.design/#DeprecatedSelect)
It only handles single-select. Multi-select will likely have to be in a separate component
<CanvasSelect
id="your-id"
label="select's label"
value={value} // should match the ID of the selected option
onChange={handleChange} // function(event, selectedOption)
{...otherPropsPassedToTheUnderlyingSelect} // if you need to (width="100%" is a popular one)
>
<CanvasSelect.Option key="1" id="1" value="1">one</CanvasSelect.Option>
<CanvasSelect.Option key="2" id="2" value="2">two</CanvasSelect.Option>
<CanvasSelect.Option key="3" id="3" value="3">three</CanvasSelect.Option>
</CanvasSelect>
---
*/
/*
* this file is a copy of canvas-lms/packages/canvas-planner/src/CanvasSelect.js
* but with strings passed in, rather then formatMessage'd here.
*/
import React from 'react'
import {func, node, string, shape, oneOfType} from 'prop-types'
import {compact, castArray, isEqual} from 'lodash'
import formatMessage from 'format-message'
import {Select} from '@instructure/ui-select'
import {Alert} from '@instructure/ui-alerts'
import {matchComponentTypes} from '@instructure/ui-react-utils'
const noOptionsOptionId = '_noOptionsOption'
// CanvasSelectOption and CanvasSelectGroup are components our client can create thru CanvasSelect
// to pass us our options. They are never rendered themselves, but get transformed into INSTUI's
// Select.Option and Select.Group on rendering CanvasSelect. See renderChildren below.
function CanvasSelectOption() {
return <div />
}
CanvasSelectOption.propTypes = {
id: string.isRequired, // eslint-disable-line react/no-unused-prop-types
value: string.isRequired // eslint-disable-line react/no-unused-prop-types
}
function CanvasSelectGroup() {
return <div />
}
CanvasSelectGroup.propTypes = {
label: string.isRequired // eslint-disable-line react/no-unused-prop-types
}
export default class CanvasSelect extends React.Component {
static Option = CanvasSelectOption
static Group = CanvasSelectGroup
static propTypes = {
id: string,
label: oneOfType([node, func]).isRequired,
liveRegion: func,
value: string,
onChange: func.isRequired,
children: node,
noOptionsLabel: string, // unselectable option to display when there are no options
translatedStrings: shape({
USE_ARROWS: string.isRequired,
LIST_COLLAPSED: string.isRequired,
LIST_EXPANDED: string.isRequired,
OPTION_SELECTED: string.isRequired
}),
onBlur: func
}
static defaultProps = {
noOptionsLabel: '---'
}
constructor(props) {
super(props)
const option = this.getOptionByFieldValue('value', props.value)
this.state = {
inputValue: option ? option.props.children : '',
isShowingOptions: false,
highlightedOptionId: null,
selectedOptionId: option ? option.props.id : null,
announcement: null
}
}
componentDidUpdate(prevProps) {
if (this.props.value !== prevProps.value || !isEqual(this.props.children, prevProps.children)) {
const option = this.getOptionByFieldValue('value', this.props.value)
// eslint-disable-next-line react/no-did-update-set-state
this.setState({
inputValue: option ? option.props.children : '',
selectedOptionId: option ? option.props.id : ''
})
}
}
render() {
const {id, label, value, onChange, children, noOptionsLabel, ...otherProps} = this.props
return (
<>
<Select
id={id}
renderLabel={() => label}
assistiveText={this.props.translatedStrings.USE_ARROWS}
inputValue={this.state.inputValue}
isShowingOptions={this.state.isShowingOptions}
onBlur={this.handleBlur}
onRequestShowOptions={this.handleShowOptions}
onRequestHideOptions={this.handleHideOptions}
onRequestHighlightOption={this.handleHighlightOption}
onRequestSelectOption={this.handleSelectOption}
{...otherProps}
>
{this.renderChildren(children)}
</Select>
<Alert liveRegion={this.props.liveRegion} liveRegionPoliteness="assertive" screenReaderOnly>
{this.state.announcement}
</Alert>
</>
)
}
renderChildren(children) {
if (!Array.isArray(children)) {
// children is 1 child
if (matchComponentTypes(children, [CanvasSelectOption])) {
return this.renderOption(children)
} else if (matchComponentTypes(children, [CanvasSelectGroup])) {
return this.renderGroup(children)
} else {
return this.renderNoOptionsOption()
}
}
const opts = children
.map(child => {
if (Array.isArray(child)) {
return this.renderChildren(child)
} else if (matchComponentTypes(child, [CanvasSelectOption])) {
return this.renderOption(child)
} else if (matchComponentTypes(child, [CanvasSelectGroup])) {
return this.renderGroup(child)
}
return null
})
.filter(child => !!child) // instui Select blows up on undefined options
if (opts.length === 0) {
return this.renderNoOptionsOption()
}
return opts
}
backupKey = 0
renderOption(option) {
const {id, children, ...optionProps} = option.props
return (
<Select.Option
id={id}
key={option.key || id || ++this.backupKey}
isHighlighted={id === this.state.highlightedOptionId}
isSelected={id === this.state.selectedOptionId}
{...optionProps}
>
{children}
</Select.Option>
)
}
renderGroup(group) {
const {id, label, ...otherProps} = group.props
const children = compact(castArray(group.props.children))
return (
<Select.Group
data-testid={`Group:${label}`}
renderLabel={() => label}
key={group.key || id || ++this.backupKey}
{...otherProps}
>
{children.map(c => this.renderOption(c))}
</Select.Group>
)
}
renderNoOptionsOption() {
return (
<Select.Option id={noOptionsOptionId} isHighlighted={false} isSelected={false}>
{this.props.noOptionsLabel}
</Select.Option>
)
}
handleBlur = event => {
this.setState({highlightedOptionId: null, announcement: null})
if (this.props.onBlur) {
this.props.onBlur(event)
}
}
handleShowOptions = () => {
this.setState({
isShowingOptions: true
})
}
handleHideOptions = _event => {
this.setState(state => {
const text = this.getOptionLabelById(state.selectedOptionId)
return {
isShowingOptions: false,
highlightedOptionId: null,
inputValue: text
}
})
}
/* eslint-disable react/no-access-state-in-setstate */
// Because handleShowOptions sets state.isShowingOptions:true
// it's already in the value of state passed to the setState(updater)
// by the time handleHighlightOption is called we miss the transition,
// this.state still has the previous value as of the last render
// which is what we need. This is why we use this version of setState.
handleHighlightOption = (event, {id}) => {
if (id === noOptionsOptionId) return
const text = this.getOptionLabelById(id)
const nowOpen = this.state.isShowingOptions ? '' : this.props.translatedStrings.LIST_EXPANDED
const inputValue = event.type === 'keydown' ? text : this.state.inputValue
this.setState({
highlightedOptionId: id,
inputValue,
announcement: `${text} ${nowOpen}`
})
}
/* eslint-enable react/no-access-state-in-setstate */
handleSelectOption = (event, {id}) => {
if (id === noOptionsOptionId) {
this.setState({
isShowingOptions: false,
announcement: this.props.translatedStrings.LIST_COLLAPSED
})
} else {
const text = this.getOptionLabelById(id)
const prevSelection = this.state.selectedOptionId
this.setState({
selectedOptionId: id,
inputValue: text,
isShowingOptions: false,
announcement: formatMessage(this.props.translatedStrings.OPTION_SELECTED, {option: text})
})
const option = this.getOptionByFieldValue('id', id)
if (prevSelection !== id) {
this.props.onChange(event, option.props.value)
}
}
}
getOptionLabelById(oid) {
const option = this.getOptionByFieldValue('id', oid)
return option ? option.props.children : ''
}
getOptionByFieldValue(field, value, options = castArray(this.props.children)) {
if (!this.props.children) return null
let foundOpt = null
for (let i = 0; i < options.length; ++i) {
const o = options[i]
if (Array.isArray(o)) {
foundOpt = this.getOptionByFieldValue(field, value, o)
} else if (matchComponentTypes(o, [CanvasSelectOption])) {
if (o.props[field] === value) {
foundOpt = o
}
} else if (matchComponentTypes(o, [CanvasSelectGroup])) {
const groupOptions = castArray(o.props.children)
for (let j = 0; j < groupOptions.length; ++j) {
const o2 = groupOptions[j]
if (o2.props[field] === value) {
foundOpt = o2
break
}
}
}
if (foundOpt) {
break
}
}
return foundOpt
}
}
|
examples/dynamic-segments/app.js | whouses/react-router | import React from 'react';
import { Router, Route, Link, Redirect } from 'react-router';
var App = React.createClass({
render() {
return (
<div>
<ul>
<li><Link to="/user/123">Bob</Link></li>
<li><Link to="/user/abc">Sally</Link></li>
</ul>
{this.props.children}
</div>
);
}
});
var User = React.createClass({
render() {
var { userID } = this.props.params;
return (
<div className="User">
<h1>User id: {userID}</h1>
<ul>
<li><Link to={`/user/${userID}/tasks/foo`}>foo task</Link></li>
<li><Link to={`/user/${userID}/tasks/bar`}>bar task</Link></li>
</ul>
{this.props.children}
</div>
);
}
});
var Task = React.createClass({
render() {
var { userID, taskID } = this.props.params;
return (
<div className="Task">
<h2>User ID: {userID}</h2>
<h3>Task ID: {taskID}</h3>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="user/:userID" component={User}>
<Route path="tasks/:taskID" component={Task} />
<Redirect from="todos/:taskID" to="/user/:userID/tasks/:taskID" />
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
src/ui-kit/Grid/index.js | Menternship/client-web | // @flow
import React from 'react';
import { Grid as GridFB } from 'react-flexbox-grid';
type $props = {
children?: any,
};
export default ({ children, ...props }: $props) => (
<GridFB {...props} fluid>
{children}
</GridFB>
);
|
src/components/joystick/JoystickMotorSelect.js | TheGigabots/gigabots-dashboard | import React from 'react';
import PropTypes from 'prop-types'
import Typography from 'material-ui/Typography';
import Paper from 'material-ui/Paper';
import Select from 'material-ui/Select';
import {MenuItem} from 'material-ui/Menu';
const style = {
height: 75,
width: 200,
margin: 20,
textAlign: 'center',
display: 'inline-block',
};
export default class JoystickMotorSelect extends React.Component {
handleMotorChange = event => {
const {button, config} = this.props;
const speed = config.speedForButton(button);
const direction = config.directionForButton(button);
this.updateParent(event.target.value, speed, direction);
};
handleSpeedChange(event) {
const {button, config} = this.props;
const direction = config.directionForButton(button);
const motor = config.motorForButton(button);
this.updateParent(motor, event.target.value, direction);
}
handleDirectionChange(event) {
const {button, config} = this.props;
const speed = config.speedForButton(button);
const motor = config.motorForButton(button);
this.updateParent(motor, speed, event.target.value);
}
updateParent(motor, speed, direction) {
this.props.callback(this.props.button, motor, speed, direction)
}
render() {
const {button, config} = this.props;
const speed = config.speedForButton(button);
const direction = config.directionForButton(button);
const motor = config.motorForButton(button);
return (
<Paper style={style}>
<Typography type="subheading" color="secondary">
{button}
</Typography>
<Select
value={motor}
onChange={this.handleMotorChange}
>
<MenuItem value={""}>None</MenuItem>
<MenuItem value={"A"}>A</MenuItem>
<MenuItem value={"B"}>B</MenuItem>
<MenuItem value={"C"}>C</MenuItem>
<MenuItem value={"D"}>D</MenuItem>
<MenuItem value={"S"}>STOP</MenuItem>
</Select>
<Select
value={speed}
onChange={(e) => this.handleSpeedChange(e)}
>
<MenuItem value={0}>0</MenuItem>
<MenuItem value={10}>10</MenuItem>
<MenuItem value={20}>20</MenuItem>
<MenuItem value={30}>30</MenuItem>
<MenuItem value={40}>40</MenuItem>
<MenuItem value={50}>50</MenuItem>
<MenuItem value={60}>60</MenuItem>
<MenuItem value={70}>70</MenuItem>
<MenuItem value={80}>80</MenuItem>
<MenuItem value={90}>90</MenuItem>
<MenuItem value={100}>100</MenuItem>
</Select>
<Select
value={direction}
onChange={(e) => this.handleDirectionChange(e)}
>
<MenuItem value={"f"}>fwd</MenuItem>
<MenuItem value={"r"}>rvs</MenuItem>
</Select>
</Paper>
)
}
}
JoystickMotorSelect.propTypes = {
button: PropTypes.string.isRequired,
config: PropTypes.object.isRequired,
callback: PropTypes.func.isRequired
}
|
src/index.js | undefinedist/sicario | import React from 'react'
import ReactDOM from 'react-dom'
import Docs from './docs/Docs'
import '../node_modules/highlight.js/styles/ocean.css'
import './index.css'
import registerServiceWorker from './registerServiceWorker'
ReactDOM.render(<Docs />, document.getElementById('root'))
registerServiceWorker()
|
app/components/RentalsPage.js | stratigos/stormsreach | /******************************************************************************
* Component for composing the Rentals page of the Housing section.
******************************************************************************/
import React from 'react';
import RentalsContainer from '../containers/RentalsContainer';
import HomepageLink from './HomepageLink';
const RentalsPage = () => {
return(
<div className="rentals-container">
<div className='rentals-header'>
<h2>Rentals</h2>
<p className='subheader'>Rooms, basements, homes, and farm beds for rent.</p>
</div>
<div className='rentals-list-container'>
<RentalsContainer />
</div>
<HomepageLink />
</div>
);
};
export default RentalsPage;
|
src/static/containers/Home/index.js | 24HeuresINSA/pass-checker | import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import './style.scss';
import reactLogo from './images/react-logo.png';
import reduxLogo from './images/redux-logo.png';
class HomeView extends React.Component {
static propTypes = {
statusText: React.PropTypes.string,
userName: React.PropTypes.string
};
static defaultProps = {
statusText: '',
userName: ''
};
render() {
return (
<div className="container">
<div className="margin-top-medium text-center">
<img className="page-logo margin-bottom-medium"
src={reactLogo}
alt="ReactJs"
/>
<img className="page-logo margin-bottom-medium"
src={reduxLogo}
alt="Redux"
/>
</div>
<div className="text-center">
<h1>Pass Checker</h1>
<h4>Bienvenue, {this.props.userName || 'invité'}.</h4>
</div>
<div className="margin-top-medium text-center">
<p>Accéder à la recherche de <Link to="/pass"><b>laissez-passer</b></Link>.</p>
</div>
<div className="margin-top-medium">
{this.props.statusText ?
<div className="alert alert-info">
{this.props.statusText}
</div>
:
null
}
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
userName: state.auth.userName,
statusText: state.auth.statusText
};
};
export default connect(mapStateToProps)(HomeView);
export { HomeView as HomeViewNotConnected };
|
src/molecules/archive/pagination/component-test.js | dsmjs/components | import React from 'react';
import {shallow} from 'enzyme';
import any from '@travi/any';
import {assert} from 'chai';
import Pagination from '.';
suite('archive pagination', () => {
test('that links are rendered for each page', () => {
const totalPages = any.integer({min: 2, max: 10});
const currentPage = any.integer({max: totalPages}) + 1;
const wrapper = shallow(<Pagination totalPages={totalPages} currentPage={currentPage} />);
const pages = wrapper.find('ol > li');
assert.equal(pages.length, totalPages);
pages.forEach((page, index) => {
const link = page.find('InternalLink');
const pageNumber = index + 1;
assert.equal(link.prop('to'), 0 === index ? '/archive' : `/archive/page-${pageNumber}`);
assert.equal(link.children().text(), `${pageNumber}`);
});
});
});
|
src/client/components/hoc/Order/withOrders.hoc.js | DBCDK/content-first | import React from 'react';
import {connect} from 'react-redux';
export const withOrders = WrappedComponent => {
const Wrapper = class extends React.Component {
render() {
return <WrappedComponent {...this.props} />;
}
};
const mapStateToProps = state => {
return {
orders: state.orderReducer.orders
};
};
return connect(mapStateToProps)(Wrapper);
};
|
scripts/utils/connectToStores.js | machnicki/healthunlocked | import React, { Component } from 'react';
import shallowEqual from 'react-pure-render/shallowEqual';
/**
* Exports a higher-order component that connects the component to stores.
* This higher-order component is most easily used as an ES7 decorator.
* Decorators are just a syntax sugar over wrapping class in a function call.
*
* Read more about higher-order components: https://goo.gl/qKYcHa
* Read more about decorators: https://github.com/wycats/javascript-decorators
*/
export default function connectToStores(stores, getState) {
return function (DecoratedComponent) {
const displayName =
DecoratedComponent.displayName ||
DecoratedComponent.name ||
'Component';
return class StoreConnector extends Component {
static displayName = `connectToStores(${displayName})`;
constructor(props) {
super(props);
this.handleStoresChanged = this.handleStoresChanged.bind(this);
this.state = getState(props);
}
componentWillMount() {
stores.forEach(store =>
store.addChangeListener(this.handleStoresChanged)
);
}
componentWillReceiveProps(nextProps) {
if (!shallowEqual(nextProps, this.props)) {
this.setState(getState(nextProps));
}
}
componentWillUnmount() {
stores.forEach(store =>
store.removeChangeListener(this.handleStoresChanged)
);
}
handleStoresChanged() {
this.setState(getState(this.props));
}
render() {
return <DecoratedComponent {...this.props} {...this.state} />;
}
};
};
}
|
packages/generator-emakinacee-react/generators/app/templates/static/src/index.js | emakina-cee-oss/generator-emakinacee-react | import React from 'react';
import ReactDOM from 'react-dom';
import { Container } from '@cerebral/react';
import App from './containers/App/App';
import controller from './controller';
import registerServiceWorker from './registerServiceWorker';
import './styles/global.scss';
ReactDOM.render(
<Container controller={controller} >
<App />
</Container>,
document.getElementById('root')
);
registerServiceWorker();
|
src/svg-icons/notification/drive-eta.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationDriveEta = (props) => (
<SvgIcon {...props}>
<path d="M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01L3 11v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.5-4.5h11L19 10H5z"/>
</SvgIcon>
);
NotificationDriveEta = pure(NotificationDriveEta);
NotificationDriveEta.displayName = 'NotificationDriveEta';
NotificationDriveEta.muiName = 'SvgIcon';
export default NotificationDriveEta;
|
src/index.js | papernotes/actemotion | import React from 'react';
import {render} from 'react-dom';
import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk'
import {Provider} from 'react-redux';
import {Router, Route, IndexRoute, browserHistory} from 'react-router';
import {syncHistoryWithStore, routerReducer} from 'react-router-redux';
import App from './containers/App';
import Home from './containers/Home';
import CreateAccount from './components/CreateAccount';
import CalendarPage from './containers/CalendarPage';
import Analytics from './containers/Analytics';
import NotFound from './components/NotFound';
import Login from './components/Login';
import AddEvent from './components/AddEvent';
// unused
import Home2 from './containers/Home2';
import Settings from './containers/Settings';
import Analytics2 from './containers/Analytics2';
import * as reducers from './reducers';
const reducer = combineReducers({
...reducers,
routing: routerReducer
});
const store = createStore(
reducer,
applyMiddleware(
thunkMiddleware
)
)
const history = syncHistoryWithStore(browserHistory, store);
render(
<Provider store={store}>
<Router history={history}>
<Route path='/' component={App}>
<IndexRoute component={Login}/>
<Route path='home' component={Home}/>
<Route path='calendar' component={CalendarPage}/>
<Route path='home2' component={Home2}/>
<Route path='create' component={CreateAccount}/>
<Route path='settings' component={Settings}/>
<Route path='analytics' component={Analytics}/>
<Route path='analytics2' component={Analytics2}/>
<Route path='editevent' component={AddEvent}/>
<Route path='*' component={NotFound}/>
</Route>
</Router>
</Provider>,
document.getElementById('root')
);
|
src/svg-icons/maps/person-pin.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsPersonPin = (props) => (
<SvgIcon {...props}>
<path d="M19 2H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 3.3c1.49 0 2.7 1.21 2.7 2.7 0 1.49-1.21 2.7-2.7 2.7-1.49 0-2.7-1.21-2.7-2.7 0-1.49 1.21-2.7 2.7-2.7zM18 16H6v-.9c0-2 4-3.1 6-3.1s6 1.1 6 3.1v.9z"/>
</SvgIcon>
);
MapsPersonPin = pure(MapsPersonPin);
MapsPersonPin.displayName = 'MapsPersonPin';
MapsPersonPin.muiName = 'SvgIcon';
export default MapsPersonPin;
|
app-client/src/index.js | vikoperdomo/serverql | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
docs/app/Examples/collections/Form/FieldVariations/index.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
const FormFieldVariationsExamples = () => (
<ExampleSection title='Field Variations'>
<ComponentExample
title='Inline'
description='A field can have its label next to instead of above it.'
examplePath='collections/Form/FieldVariations/FormExampleInlineField'
/>
</ExampleSection>
)
export default FormFieldVariationsExamples
|
examples/complete/react-native/screens/LinksScreen.js | prescottprue/react-redux-firebase | import React from 'react';
import { ScrollView, StyleSheet } from 'react-native';
import { ExpoLinksView } from '@expo/samples';
export default class LinksScreen extends React.Component {
static navigationOptions = {
title: 'Links',
};
render() {
return (
<ScrollView style={styles.container}>
{/* Go ahead and delete ExpoLinksView and replace it with your
* content, we just wanted to provide you with some helpful links */}
<ExpoLinksView />
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 15,
backgroundColor: '#fff',
},
});
|
src/Parser/Druid/Restoration/CombatLogParser.js | enragednuke/WoWAnalyzer | import React from 'react';
import Tab from 'Main/Tab';
import Mana from 'Main/Mana';
import CoreCombatLogParser from 'Parser/Core/CombatLogParser';
import LowHealthHealing from 'Parser/Core/Modules/LowHealthHealing';
import HealingDone from 'Parser/Core/Modules/HealingDone';
import WildGrowthNormalizer from './Normalizers/WildGrowth';
import ClearcastingNormalizer from './Normalizers/ClearcastingNormalizer';
import Mastery from './Modules/Core/Mastery';
import Rejuvenation from './Modules/Core/Rejuvenation';
import Ekowraith from './Modules/Items/Ekowraith';
import XonisCaress from './Modules/Items/XonisCaress';
import DarkTitanAdvice from './Modules/Items/DarkTitanAdvice';
import EssenceOfInfusion from './Modules/Items/EssenceOfInfusion';
import SoulOfTheArchdruid from './Modules/Items/SoulOfTheArchdruid';
import Tearstone from './Modules/Items/Tearstone';
import DarkmoonDeckPromises from './Modules/Items/DarkmoonDeckPromises';
import GarothiFeedbackConduit from './Modules/Items/GarothiFeedbackConduit';
import CarafeOfSearingLight from './Modules/Items/CarafeOfSearingLight';
import T19_2Set from './Modules/Items/T19_2Set';
import T20_2Set from './Modules/Items/T20_2Set';
import T20_4Set from './Modules/Items/T20_4Set';
import T21_2Set from './Modules/Items/T21_2Set';
import T21_4Set from './Modules/Items/T21_4Set';
import HealingTouch from './Modules/Features/HealingTouch';
import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting';
import AverageHots from './Modules/Features/AverageHots';
import Abilities from './Modules/Features/Abilities';
import CooldownThroughputTracker from './Modules/Features/CooldownThroughputTracker';
import WildGrowth from './Modules/Features/WildGrowth';
import Lifebloom from './Modules/Features/Lifebloom';
import Efflorescence from './Modules/Features/Efflorescence';
import Clearcasting from './Modules/Features/Clearcasting';
import Innervate from './Modules/Features/Innervate';
import PowerOfTheArchdruid from './Modules/Features/PowerOfTheArchdruid';
import Dreamwalker from './Modules/Features/Dreamwalker';
import EssenceOfGhanir from './Modules/Features/EssenceOfGhanir';
import NaturesEssence from './Modules/Features/NaturesEssence';
import Ironbark from './Modules/Features/Ironbark';
import CenarionWard from './Modules/Talents/CenarionWard';
import Cultivation from './Modules/Talents/Cultivation';
import Flourish from './Modules/Talents/Flourish';
import SpringBlossoms from './Modules/Talents/SpringBlossoms';
import SoulOfTheForest from './Modules/Talents/SoulOfTheForest';
import TreeOfLife from './Modules/Talents/TreeOfLife';
import RelicTraits from './Modules/Traits/RelicTraits';
import ArmorOfTheAncients from './Modules/Traits/ArmorOfTheAncients';
import BlessingOfTheWorldTree from './Modules/Traits/BlessingOfTheWorldTree';
import EssenceOfNordrassil from './Modules/Traits/EssenceOfNordrassil';
import Grovewalker from './Modules/Traits/Grovewalker';
import InfusionOfNature from './Modules/Traits/InfusionOfNature';
import KnowledgeOfTheAncients from './Modules/Traits/KnowledgeOfTheAncients';
import NaturalMending from './Modules/Traits/NaturalMending';
import Persistence from './Modules/Traits/Persistence';
import SeedsOfTheWorldTree from './Modules/Traits/SeedsOfTheWorldTree';
import EternalRestoration from './Modules/Traits/EternalRestoration';
import StatWeights from './Modules/Features/StatWeights';
import { ABILITIES_AFFECTED_BY_HEALING_INCREASES } from './Constants';
import MurderousIntent from "./Modules/NetherlightCrucibleTraits/MurderousIntent";
import Shocklight from "./Modules/NetherlightCrucibleTraits/Shocklight";
import LightSpeed from "./Modules/NetherlightCrucibleTraits/LightSpeed";
import NLCTraits from "./Modules/NetherlightCrucibleTraits/NLCTraits";
import MasterOfShadows from "./Modules/NetherlightCrucibleTraits/MasterOfShadows";
class CombatLogParser extends CoreCombatLogParser {
static abilitiesAffectedByHealingIncreases = ABILITIES_AFFECTED_BY_HEALING_INCREASES;
static specModules = {
// Normalizers
wildGrowthNormalizer: WildGrowthNormalizer,
clearcastingNormalizer: ClearcastingNormalizer,
// Core
healingDone: [HealingDone, { showStatistic: true }],
// Features
healingTouch : HealingTouch,
lowHealthHealing: LowHealthHealing,
alwaysBeCasting: AlwaysBeCasting,
averageHots: AverageHots,
cooldownThroughputTracker: CooldownThroughputTracker,
abilities: Abilities,
rejuvenation: Rejuvenation,
wildGrowth: WildGrowth,
lifebloom: Lifebloom,
efflorescence: Efflorescence,
clearcasting: Clearcasting,
treeOfLife: TreeOfLife,
flourish: Flourish,
innervate: Innervate,
powerOfTheArchdruid: PowerOfTheArchdruid,
dreamwalker: Dreamwalker,
soulOfTheForest: SoulOfTheForest,
essenceOfGhanir: EssenceOfGhanir,
mastery: Mastery,
springBlossoms: SpringBlossoms,
cultivation: Cultivation,
cenarionWard: CenarionWard,
naturesEssence: NaturesEssence,
ironbark: Ironbark,
// Items:
ekowraith: Ekowraith,
xonisCaress: XonisCaress,
darkTitanAdvice: DarkTitanAdvice,
essenceOfInfusion: EssenceOfInfusion,
soulOfTheArchdruid: SoulOfTheArchdruid,
tearstone: Tearstone,
t19_2set: T19_2Set,
t20_2set: T20_2Set,
t20_4set: T20_4Set,
t21_2set: T21_2Set,
t21_4set: T21_4Set,
// TODO:
// Edraith
// Aman'Thul's Wisdom
// NLC
murderousIntent: MurderousIntent,
shocklight: Shocklight,
lightSpeed: LightSpeed,
masterOfShadows: MasterOfShadows,
nlcTraits: NLCTraits,
// Shared:
darkmoonDeckPromises: DarkmoonDeckPromises,
garothiFeedbackConduit: GarothiFeedbackConduit,
carafeOfSearingLight: CarafeOfSearingLight,
// Traits
RelicTraits: RelicTraits,
ArmorOfTheAncients: ArmorOfTheAncients,
BlessingOfTheWorldTree: BlessingOfTheWorldTree,
EssenceOfNordrassil: EssenceOfNordrassil,
Grovewalker: Grovewalker,
InfusionOfNature: InfusionOfNature,
KnowledgeOfTheAncients: KnowledgeOfTheAncients,
NaturalMending: NaturalMending,
Persistence: Persistence,
SeedsOfTheWorldTree: SeedsOfTheWorldTree,
EternalRestoration: EternalRestoration,
statWeights: StatWeights,
};
generateResults() {
const results = super.generateResults();
results.tabs = [
...results.tabs,
{
title: 'Mana',
url: 'mana',
render: () => (
<Tab title="Mana" style={{ padding: '15px 22px' }}>
<Mana parser={this} />
</Tab>
),
},
];
return results;
}
}
export default CombatLogParser;
|
learning/index.js | YashdalfTheGray/talks | import React from 'react';
import { render } from 'react-dom';
import Presentation from './presentation';
render(<Presentation/>, document.querySelector('#root'));
|
frontend/src/components/on_boarding/ContributorPicker.js | OpenCollective/opencollective-website | import React from 'react';
import ContributorPickerItem from './ContributorPickerItem'
export default class ContributorPicker extends React.Component {
constructor(props) {
super(props);
}
renderChosenContributors() {
const { chosen, onRemove } = this.props;
return chosen.map((contributor, index) => {
return (
<ContributorPickerItem
key={index}
name={contributor.name}
avatar={contributor.avatar}
onRemove={() => onRemove(contributor)}
/>
)
});
}
render() {
const { available, onChoose } = this.props;
return (
<div className="ContributorPicker">
{this.renderChosenContributors()}
{available.length ? <ContributorPickerItem available={available} onChoose={onChoose} /> : null}
</div>
)
}
}
|
src/app/components/team/SmoochBot/SmoochBotMainMenu.js | meedan/check-web | import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl, intlShape, defineMessages, FormattedMessage } from 'react-intl';
import Typography from '@material-ui/core/Typography';
import { languageLabel } from '../../../LanguageRegistry';
import SmoochBotMainMenuSection from './SmoochBotMainMenuSection';
const messages = defineMessages({
privacyStatement: {
id: 'smoochBotMainMenu.privacyStatement',
defaultMessage: 'Privacy statement',
description: 'Menu label used in the tipline bot',
},
});
const SmoochBotMainMenu = ({
value,
languages,
enabledIntegrations,
intl,
onChange,
}) => {
const resources = value.smooch_custom_resources || [];
const handleChangeTitle = (newValue, menu) => {
onChange({ smooch_menu_title: newValue }, menu);
};
const handleChangeMenuOptions = (newOptions, menu) => {
onChange({ smooch_menu_options: newOptions }, menu);
};
const whatsAppEnabled = (enabledIntegrations.whatsapp && enabledIntegrations.whatsapp.status === 'active');
return (
<React.Fragment>
<Typography variant="subtitle2" component="div">
<FormattedMessage id="smoochBotMainMenu.mainMenu" defaultMessage="Main menu" description="Title of the tipline bot main menu settings page." />
</Typography>
<Typography component="div" variant="body2" paragraph>
<FormattedMessage
id="smoochBotMainMenu.subtitle"
defaultMessage="The menu of your bot, asking the user to choose between a set of options."
description="Subtitle displayed in tipline settings page for the main menu."
/>
</Typography>
{ Object.keys(enabledIntegrations).filter(platformName => platformName !== 'whatsapp').length > 0 ? // Any platform other than WhatsApp
<Typography component="div" variant="body2" paragraph>
<FormattedMessage
id="smoochBotMainMenu.subtitle2"
defaultMessage="Please note that some messaging services may have different menu display options than others. {linkToLearnMore}."
description="Subtitle displayed in tipline settings page for the main menu if the tipline is enabled for WhatsApp and at least one more platform."
values={{
linkToLearnMore: (
<a href="http://help.checkmedia.org/en/articles/4838307-creating-your-tipline-bot" target="_blank" rel="noopener noreferrer">
<FormattedMessage
id="smoochBotMainMenu.learnMore"
defaultMessage="Learn more"
description="Link with help article about which menu features are supported by each platform in tipline settings page for the main menu."
/>
</a>
),
}}
/>
</Typography> : null }
<SmoochBotMainMenuSection
number={1}
value={value.smooch_state_main}
resources={resources}
noTitleNoDescription={!whatsAppEnabled}
onChangeTitle={(newValue) => { handleChangeTitle(newValue, 'smooch_state_main'); }}
onChangeMenuOptions={(newOptions) => { handleChangeMenuOptions(newOptions, 'smooch_state_main'); }}
/>
{ whatsAppEnabled ?
<SmoochBotMainMenuSection
number={2}
value={value.smooch_state_secondary}
resources={resources}
onChangeTitle={(newValue) => { handleChangeTitle(newValue, 'smooch_state_secondary'); }}
onChangeMenuOptions={(newOptions) => { handleChangeMenuOptions(newOptions, 'smooch_state_secondary'); }}
optional
/> : null }
<SmoochBotMainMenuSection
number={3}
value={
languages.length > 1 ?
{
smooch_menu_title: <FormattedMessage id="smoochBotMainMenu.languagesAndPrivacy" defaultMessage="Languages and Privacy" description="Title of the main menu third section of the tipline where there is more than one supported language" />,
smooch_menu_options: languages.map(l => ({ smooch_menu_option_label: languageLabel(l) })).concat({ smooch_menu_option_label: intl.formatMessage(messages.privacyStatement) }),
} :
{
smooch_menu_title: <FormattedMessage id="smoochBotMainMenu.privacy" defaultMessage="Privacy" description="Title of the main menu third section of the tipline when there is only one supported language" />,
smooch_menu_options: [{ smooch_menu_option_label: intl.formatMessage(messages.privacyStatement) }],
}
}
onChangeTitle={() => {}}
onChangeMenuOptions={() => {}}
readOnly
/>
</React.Fragment>
);
};
SmoochBotMainMenu.defaultProps = {
value: {},
languages: [],
};
SmoochBotMainMenu.propTypes = {
value: PropTypes.object,
languages: PropTypes.arrayOf(PropTypes.string),
intl: intlShape.isRequired,
enabledIntegrations: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
};
export default injectIntl(SmoochBotMainMenu);
|
src/icons/IosCog.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosCog extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M293.25,150.32L265.2,254.9l74.954,75C358.159,309.457,368,283.486,368,256c0-29.916-11.65-58.042-32.805-79.196
C323.154,164.763,308.854,155.807,293.25,150.32z"></path>
<path d="M278.068,146.161C270.88,144.732,263.496,144,256,144c-29.916,0-58.042,11.65-79.196,32.805
C155.65,197.958,144,226.084,144,256c0,7.468,0.727,14.824,2.145,21.988L250.3,250.1L278.068,146.161z"></path>
<path d="M150.473,293.697c5.5,15.43,14.404,29.572,26.331,41.498C197.958,356.35,226.083,368,256,368
c27.009,0,52.558-9.499,72.835-26.911L253.9,266.2L150.473,293.697z"></path>
<path d="M448,272.754v-32.008l-33.291-8.703l-2.601-13.204l27.594-20.905l-12.197-29.608l-34.392,4.802l-7.498-10.603
l17.695-29.708l-22.594-22.605l-30.191,17.404l-10.697-7.302l5.298-35.009l-29.492-12.303L294.04,101.31l-12.297-2.601L273.045,64
h-31.991l-9.197,34.909l-12.098,2.4l-21.494-29.008l-29.592,12.304l4.799,35.709l-11.697,7.202l-31.292-18.705l-22.594,22.606
l18.795,31.508l-6.698,10.502l-35.49-5.001l-12.197,29.608l28.893,21.706l-2.399,12.203L64,240.846v32.007l34.69,8.903l2.4,12.503
l-28.394,21.307l12.297,29.508l34.991-5.002l7.099,11.303l-17.896,30.607l22.595,22.605l30.192-18.204l11.196,7.302l-4.498,34.311
l29.592,12.202l20.595-27.808l13.396,2.5L241.054,448h31.991l8.298-33.109l13.597-2.601l20.694,27.106l29.593-12.203l-4.998-33.709
l10.196-7.4l28.992,16.904l22.595-22.606l-16.795-28.907l7.896-11.402l33.791,4.802l12.298-29.508l-27.193-20.507l2.7-13.502
L448,272.754z M256,384c-70.692,0-128-57.307-128-128c0-70.692,57.308-128,128-128c70.692,0,128,57.308,128,128
C384,326.693,326.692,384,256,384z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M293.25,150.32L265.2,254.9l74.954,75C358.159,309.457,368,283.486,368,256c0-29.916-11.65-58.042-32.805-79.196
C323.154,164.763,308.854,155.807,293.25,150.32z"></path>
<path d="M278.068,146.161C270.88,144.732,263.496,144,256,144c-29.916,0-58.042,11.65-79.196,32.805
C155.65,197.958,144,226.084,144,256c0,7.468,0.727,14.824,2.145,21.988L250.3,250.1L278.068,146.161z"></path>
<path d="M150.473,293.697c5.5,15.43,14.404,29.572,26.331,41.498C197.958,356.35,226.083,368,256,368
c27.009,0,52.558-9.499,72.835-26.911L253.9,266.2L150.473,293.697z"></path>
<path d="M448,272.754v-32.008l-33.291-8.703l-2.601-13.204l27.594-20.905l-12.197-29.608l-34.392,4.802l-7.498-10.603
l17.695-29.708l-22.594-22.605l-30.191,17.404l-10.697-7.302l5.298-35.009l-29.492-12.303L294.04,101.31l-12.297-2.601L273.045,64
h-31.991l-9.197,34.909l-12.098,2.4l-21.494-29.008l-29.592,12.304l4.799,35.709l-11.697,7.202l-31.292-18.705l-22.594,22.606
l18.795,31.508l-6.698,10.502l-35.49-5.001l-12.197,29.608l28.893,21.706l-2.399,12.203L64,240.846v32.007l34.69,8.903l2.4,12.503
l-28.394,21.307l12.297,29.508l34.991-5.002l7.099,11.303l-17.896,30.607l22.595,22.605l30.192-18.204l11.196,7.302l-4.498,34.311
l29.592,12.202l20.595-27.808l13.396,2.5L241.054,448h31.991l8.298-33.109l13.597-2.601l20.694,27.106l29.593-12.203l-4.998-33.709
l10.196-7.4l28.992,16.904l22.595-22.606l-16.795-28.907l7.896-11.402l33.791,4.802l12.298-29.508l-27.193-20.507l2.7-13.502
L448,272.754z M256,384c-70.692,0-128-57.307-128-128c0-70.692,57.308-128,128-128c70.692,0,128,57.308,128,128
C384,326.693,326.692,384,256,384z"></path>
</g>
</IconBase>;
}
};IosCog.defaultProps = {bare: false} |
src/ui/containers/account.js | redcom/aperitive | // @flow
import React from 'react';
import { withRouter } from 'react-router';
import { Row, Button } from 'react-bootstrap';
import { isNil } from 'ramda';
import LoginAuth0 from './LoginAuth0';
import { auth0Config } from '../../config';
type Props = {
loading: boolean,
};
class Account extends React.Component {
props: Props;
static contextTypes = {
router: React.PropTypes.object.isRequired,
};
isLoggedIn() {
return (__CLIENT__ && !isNil(global.localStorage.getItem('account.auth0IdAuthorization')));
}
logout = () => {
if (__CLIENT__) {
global.localStorage.removeItem('account.auth0IdAuthorization');
global.location.reload();
}
}
renderLoggedIn() {
return (
<div>
<Button onClick={this.logout}>Logout</Button>
</div>
);
}
renderLoggedOut() {
if (!__CLIENT__) return null;
return (
<Row>
<LoginAuth0
clientId={auth0Config.clientId}
domain={auth0Config.domain}
/>
</Row>
);
}
render() {
if (this.props.loading) {
return (
<Row className="text-center">
Loading...
</Row>
);
}
if (this.isLoggedIn()) {
return this.renderLoggedIn();
} else {
return this.renderLoggedOut();
}
}
}
export default withRouter(Account);
|
node_modules/react-select/examples/src/components/Creatable.js | rblin081/drafting-client | import React from 'react';
import createClass from 'create-react-class';
import PropTypes from 'prop-types';
import Select from 'react-select';
var CreatableDemo = createClass({
displayName: 'CreatableDemo',
propTypes: {
hint: PropTypes.string,
label: PropTypes.string
},
getInitialState () {
return {
multi: true,
multiValue: [],
options: [
{ value: 'R', label: 'Red' },
{ value: 'G', label: 'Green' },
{ value: 'B', label: 'Blue' }
],
value: undefined
};
},
handleOnChange (value) {
const { multi } = this.state;
if (multi) {
this.setState({ multiValue: value });
} else {
this.setState({ value });
}
},
render () {
const { multi, multiValue, options, value } = this.state;
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select.Creatable
multi={multi}
options={options}
onChange={this.handleOnChange}
value={multi ? multiValue : value}
/>
<div className="hint">{this.props.hint}</div>
<div className="checkbox-list">
<label className="checkbox">
<input
type="radio"
className="checkbox-control"
checked={multi}
onChange={() => this.setState({ multi: true })}
/>
<span className="checkbox-label">Multiselect</span>
</label>
<label className="checkbox">
<input
type="radio"
className="checkbox-control"
checked={!multi}
onChange={() => this.setState({ multi: false })}
/>
<span className="checkbox-label">Single Value</span>
</label>
</div>
</div>
);
}
});
module.exports = CreatableDemo;
|
src/svg-icons/image/add-to-photos.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageAddToPhotos = (props) => (
<SvgIcon {...props}>
<path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z"/>
</SvgIcon>
);
ImageAddToPhotos = pure(ImageAddToPhotos);
ImageAddToPhotos.displayName = 'ImageAddToPhotos';
ImageAddToPhotos.muiName = 'SvgIcon';
export default ImageAddToPhotos;
|
client/extensions/woocommerce/app/reviews/review-reply-create.js | Automattic/woocommerce-connect-client | /**
* External depedencies
*
* @format
*/
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { localize } from 'i18n-calypso';
import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import { createReviewReply } from 'woocommerce/state/sites/review-replies/actions';
import { getCurrentUser } from 'state/current-user/selectors';
import Gravatar from 'components/gravatar';
import { successNotice } from 'state/notices/actions';
// Matches comments reply box heights
const TEXTAREA_HEIGHT_COLLAPSED = 47; // 1 line
const TEXTAREA_HEIGHT_FOCUSED = 68; // 2 lines
const TEXTAREA_MAX_HEIGHT = 236; // 10 lines
const TEXTAREA_VERTICAL_BORDER = 2;
class ReviewReplyCreate extends Component {
static propTypes = {
siteId: PropTypes.number.isRequired,
review: PropTypes.shape( {
status: PropTypes.string,
} ).isRequired,
};
// TODO Update this to use Redux edits state for creates at some point. Unfortunately it only supports holding one at a time,
// so we will use internal component state to hold the text for now.
state = {
commentText: '',
hasFocus: false,
textareaHeight: TEXTAREA_HEIGHT_COLLAPSED,
};
bindTextareaRef = textarea => {
this.textarea = textarea;
};
calculateTextareaHeight = () => {
const textareaScrollHeight = this.textarea.scrollHeight;
const textareaHeight = Math.min(
TEXTAREA_MAX_HEIGHT,
textareaScrollHeight + TEXTAREA_VERTICAL_BORDER
);
return Math.max( TEXTAREA_HEIGHT_FOCUSED, textareaHeight );
};
getTextareaPlaceholder = () => {
const { review, translate } = this.props;
if ( 'approved' === review.status ) {
return translate( 'Reply to %(reviewAuthor)s…', { args: { reviewAuthor: review.name } } );
}
return translate( 'Approve and reply to %(reviewAuthor)s…', {
args: { reviewAuthor: review.name },
} );
};
onTextChange = event => {
const { value } = event.target;
const textareaHeight = this.calculateTextareaHeight();
this.setState( {
commentText: value,
textareaHeight,
} );
};
setFocus = () =>
this.setState( {
hasFocus: true,
textareaHeight: this.calculateTextareaHeight(),
} );
unsetFocus = () =>
this.setState( {
hasFocus: false,
textareaHeight: TEXTAREA_HEIGHT_COLLAPSED,
} );
onSubmit = event => {
event.preventDefault();
const { siteId, review, translate } = this.props;
const { commentText } = this.state;
const { product } = review;
const shouldApprove = 'pending' === review.status ? true : false;
this.props.createReviewReply( siteId, product.id, review.id, commentText, shouldApprove );
this.setState( {
commentText: '',
} );
this.props.successNotice( translate( 'Reply submitted.' ), { duration: 5000 } );
};
render() {
const { translate, currentUser } = this.props;
const { hasFocus, textareaHeight, commentText } = this.state;
const hasCommentText = commentText.trim().length > 0;
// Only show the scrollbar if the textarea content exceeds the max height
const hasScrollbar = textareaHeight >= TEXTAREA_MAX_HEIGHT;
const buttonClasses = classNames( 'reviews__reply-submit', {
'has-scrollbar': hasScrollbar,
'is-active': hasCommentText,
'is-visible': hasFocus || hasCommentText,
} );
const gravatarClasses = classNames( { 'is-visible': ! hasFocus } );
const textareaClasses = classNames( {
'has-content': hasCommentText,
'has-focus': hasFocus,
'has-scrollbar': hasScrollbar,
} );
// Without focus, force the textarea to collapse even if it was manually resized
const textareaStyle = {
height: hasFocus ? textareaHeight : TEXTAREA_HEIGHT_COLLAPSED,
};
return (
<form className="reviews__reply-textarea">
<textarea
className={ textareaClasses }
onBlur={ this.unsetFocus }
onChange={ this.onTextChange }
onFocus={ this.setFocus }
placeholder={ this.getTextareaPlaceholder() }
ref={ this.bindTextareaRef }
style={ textareaStyle }
value={ commentText }
/>
<Gravatar className={ gravatarClasses } size={ 24 } user={ currentUser } />
<button className={ buttonClasses } disabled={ ! hasCommentText } onClick={ this.onSubmit }>
{ translate( 'Send' ) }
</button>
</form>
);
}
}
function mapStateToProps( state ) {
return {
currentUser: getCurrentUser( state ),
};
}
function mapDispatchToProps( dispatch ) {
return bindActionCreators(
{
createReviewReply,
successNotice,
},
dispatch
);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)( localize( ReviewReplyCreate ) );
|
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch03/03_04/finish/src/index.js | yevheniyc/Autodidact | import React from 'react'
import { render } from 'react-dom'
import { SkiDayCount } from './components/SkiDayCount'
window.React = React
render(
<SkiDayCount total={50}
powder={20}
backcountry={10}
goal={100}/>,
document.getElementById('react-container')
) |
react-router-tutorial/lessons/08-index-routes/index.js | zerotung/practices-and-notes | import React from 'react'
import { render } from 'react-dom'
import { Router, Route, hashHistory } from 'react-router'
import App from './modules/App'
import About from './modules/About'
import Repos from './modules/Repos'
import Repo from './modules/Repo'
render((
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="/repos" component={Repos}>
<Route path="/repos/:userName/:repoName" component={Repo}/>
</Route>
<Route path="/about" component={About}/>
</Route>
</Router>
), document.getElementById('app'))
|
public/js/sequenceserver.js | elsiklab/sequenceserver | import 'jquery';
import 'jquery-ui';
import 'bootstrap';
import 'webshim';
import React from 'react';
import Router from 'react-router';
import {Page as Search} from './search';
import {Page as Report} from './report';
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
/**
* Simple, small jQuery extensions for convenience.
*/
(function ($) {
/**
* Disable an element.
*
* Sets `disabled` property to `true` and adds `disabled` class.
*/
$.fn.disable = function () {
return this.prop('disabled', true).addClass('disabled');
};
/**
* Enable an element.
*
* Sets `disabled` property to `false` and removes `disabled` class
* if present.
*/
$.fn.enable = function () {
return this.prop('disabled', false).removeClass('disabled');
};
/**
* Check an element.
*
* Sets `checked` property to `true`.
*/
$.fn.check = function () {
return this.prop('checked', true);
};
/**
* Un-check an element.
*
* Sets `checked` property to `false`.
*/
$.fn.uncheck = function () {
return this.prop('checked', false);
};
/**
* Initialise Bootstrap tooltip on an element with presets. Takes title.
*/
$.fn._tooltip = $.fn.tooltip;
$.fn.tooltip = function (options) {
return this
._tooltip('destroy')
._tooltip($.extend({
container: 'body',
placement: 'left',
delay: {
show: 1000
}
}, options));
};
/**
* Returns true / false if any modal is active.
*/
$.modalActive = function () {
var active = false;
$('.modal').each(function () {
var modal = $(this).data('bs.modal');
if (modal) {
active = modal.isShown;
return !active;
}
});
return active;
};
/**
* Wiggle an element.
*
* Used for wiggling BLAST button.
*/
$.fn.wiggle = function () {
this.finish().effect("bounce", {
direction: 'left',
distance: 24,
times: 4,
}, 250);
};
}(jQuery));
SequenceServer = React.createClass({
// Class methods. //
statics: {
FASTA_FORMAT: /^>/,
setupTooltips: function () {
$('.pos-label').each(function () {
$(this).tooltip({
placement: 'right'
});
});
$('.downloads a').each(function () {
$(this).tooltip();
});
},
showErrorModal: function (jqXHR, beforeShow) {
setTimeout(function () {
beforeShow();
if (jqXHR.responseText) {
$("#error").html(jqXHR.responseText).modal();
}
else {
$("#error-no-response").modal();
}
}, 500);
},
routes: function () {
return (
<Route handler={SequenceServer}>
<Route path="/" handler={Search}/>
<Route path="/:jid" handler={Report}/>
</Route>
);
},
run: function () {
Router.run(this.routes(), Router.HistoryLocation, function (Root) {
React.render(<Root/>, document.getElementById("view"));
});
}
},
// Lifecycle methods. //
render: function () {
return (<RouteHandler/>);
}
});
SequenceServer.run();
|
app/javascript/mastodon/features/list_timeline/index.js | mstdn-jp/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { FormattedMessage, defineMessages, injectIntl } from 'react-intl';
import { connectListStream } from '../../actions/streaming';
import { expandListTimeline } from '../../actions/timelines';
import { fetchList, deleteList } from '../../actions/lists';
import { openModal } from '../../actions/modal';
import MissingIndicator from '../../components/missing_indicator';
import LoadingIndicator from '../../components/loading_indicator';
const messages = defineMessages({
deleteMessage: { id: 'confirmations.delete_list.message', defaultMessage: 'Are you sure you want to permanently delete this list?' },
deleteConfirm: { id: 'confirmations.delete_list.confirm', defaultMessage: 'Delete' },
});
const mapStateToProps = (state, props) => ({
list: state.getIn(['lists', props.params.id]),
hasUnread: state.getIn(['timelines', `list:${props.params.id}`, 'unread']) > 0,
});
@connect(mapStateToProps)
@injectIntl
export default class ListTimeline extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
columnId: PropTypes.string,
hasUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
list: PropTypes.oneOfType([ImmutablePropTypes.map, PropTypes.bool]),
intl: PropTypes.object.isRequired,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('LIST', { id: this.props.params.id }));
this.context.router.history.push('/');
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch } = this.props;
const { id } = this.props.params;
dispatch(fetchList(id));
dispatch(expandListTimeline(id));
this.disconnect = dispatch(connectListStream(id));
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { id } = this.props.params;
this.props.dispatch(expandListTimeline(id, { maxId }));
}
handleEditClick = () => {
this.props.dispatch(openModal('LIST_EDITOR', { listId: this.props.params.id }));
}
handleDeleteClick = () => {
const { dispatch, columnId, intl } = this.props;
const { id } = this.props.params;
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.deleteMessage),
confirm: intl.formatMessage(messages.deleteConfirm),
onConfirm: () => {
dispatch(deleteList(id));
if (!!columnId) {
dispatch(removeColumn(columnId));
} else {
this.context.router.history.push('/lists');
}
},
}));
}
render () {
const { hasUnread, columnId, multiColumn, list } = this.props;
const { id } = this.props.params;
const pinned = !!columnId;
const title = list ? list.get('title') : id;
if (typeof list === 'undefined') {
return (
<Column>
<div className='scrollable'>
<LoadingIndicator />
</div>
</Column>
);
} else if (list === false) {
return (
<Column>
<div className='scrollable'>
<MissingIndicator />
</div>
</Column>
);
}
return (
<Column ref={this.setRef}>
<ColumnHeader
icon='list-ul'
active={hasUnread}
title={title}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<div className='column-header__links'>
<button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.handleEditClick}>
<i className='fa fa-pencil' /> <FormattedMessage id='lists.edit' defaultMessage='Edit list' />
</button>
<button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.handleDeleteClick}>
<i className='fa fa-trash' /> <FormattedMessage id='lists.delete' defaultMessage='Delete list' />
</button>
</div>
<hr />
</ColumnHeader>
<StatusListContainer
trackScroll={!pinned}
scrollKey={`list_timeline-${columnId}`}
timelineId={`list:${id}`}
onLoadMore={this.handleLoadMore}
emptyMessage={<FormattedMessage id='empty_column.list' defaultMessage='There is nothing in this list yet. When members of this list post new statuses, they will appear here.' />}
/>
</Column>
);
}
}
|
admin/client/App/elemental/DropdownButton/index.js | snowkeeper/keystone | /* eslint quote-props: ["error", "as-needed"] */
import React from 'react';
import { css, StyleSheet } from 'aphrodite/no-important';
import Button from '../Button';
function DropdownButton ({ children, ...props }) {
return (
<Button {...props}>
{children}
<span className={css(classes.arrow)} />
</Button>
);
};
// NOTE
// 1: take advantage of `currentColor` by leaving border top color undefined
// 2: even though the arrow is vertically centered, visually it appears too low
// because of lowercase characters beside it
const classes = StyleSheet.create({
arrow: {
borderLeft: '0.3em solid transparent',
borderRight: '0.3em solid transparent',
borderTop: '0.3em solid', // 1
display: 'inline-block',
height: 0,
marginTop: '-0.125em', // 2
verticalAlign: 'middle',
width: 0,
// add spacing
':first-child': {
marginRight: '0.5em',
},
':last-child': {
marginLeft: '0.5em',
},
},
});
module.exports = DropdownButton;
|
app/javascript/mastodon/components/dropdown_menu.js | dunn/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import IconButton from './icon_button';
import Overlay from 'react-overlays/lib/Overlay';
import Motion from '../features/ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import detectPassiveEvents from 'detect-passive-events';
const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false;
let id = 0;
class DropdownMenu extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
items: PropTypes.array.isRequired,
onClose: PropTypes.func.isRequired,
style: PropTypes.object,
placement: PropTypes.string,
arrowOffsetLeft: PropTypes.string,
arrowOffsetTop: PropTypes.string,
openedViaKeyboard: PropTypes.bool,
};
static defaultProps = {
style: {},
placement: 'bottom',
};
state = {
mounted: false,
};
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
componentDidMount () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('keydown', this.handleKeyDown, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
if (this.focusedItem && this.props.openedViaKeyboard) {
this.focusedItem.focus();
}
this.setState({ mounted: true });
}
componentWillUnmount () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('keydown', this.handleKeyDown, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
setFocusRef = c => {
this.focusedItem = c;
}
handleKeyDown = e => {
const items = Array.from(this.node.getElementsByTagName('a'));
const index = items.indexOf(document.activeElement);
let element;
switch(e.key) {
case 'ArrowDown':
element = items[index+1];
if (element) {
element.focus();
}
break;
case 'ArrowUp':
element = items[index-1];
if (element) {
element.focus();
}
break;
case 'Tab':
if (e.shiftKey) {
element = items[index-1] || items[items.length-1];
} else {
element = items[index+1] || items[0];
}
if (element) {
element.focus();
e.preventDefault();
e.stopPropagation();
}
break;
case 'Home':
element = items[0];
if (element) {
element.focus();
}
break;
case 'End':
element = items[items.length-1];
if (element) {
element.focus();
}
break;
case 'Escape':
this.props.onClose();
break;
}
}
handleItemKeyPress = e => {
if (e.key === 'Enter' || e.key === ' ') {
this.handleClick(e);
}
}
handleClick = e => {
const i = Number(e.currentTarget.getAttribute('data-index'));
const { action, to } = this.props.items[i];
this.props.onClose();
if (typeof action === 'function') {
e.preventDefault();
action(e);
} else if (to) {
e.preventDefault();
this.context.router.history.push(to);
}
}
renderItem (option, i) {
if (option === null) {
return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
}
const { text, href = '#', target = '_blank', method } = option;
return (
<li className='dropdown-menu__item' key={`${text}-${i}`}>
<a href={href} target={target} data-method={method} rel='noopener noreferrer' role='button' tabIndex='0' ref={i === 0 ? this.setFocusRef : null} onClick={this.handleClick} onKeyPress={this.handleItemKeyPress} data-index={i}>
{text}
</a>
</li>
);
}
render () {
const { items, style, placement, arrowOffsetLeft, arrowOffsetTop } = this.props;
const { mounted } = this.state;
return (
<Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}>
{({ opacity, scaleX, scaleY }) => (
// It should not be transformed when mounting because the resulting
// size will be used to determine the coordinate of the menu by
// react-overlays
<div className={`dropdown-menu ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}>
<div className={`dropdown-menu__arrow ${placement}`} style={{ left: arrowOffsetLeft, top: arrowOffsetTop }} />
<ul>
{items.map((option, i) => this.renderItem(option, i))}
</ul>
</div>
)}
</Motion>
);
}
}
export default class Dropdown extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
icon: PropTypes.string.isRequired,
items: PropTypes.array.isRequired,
size: PropTypes.number.isRequired,
title: PropTypes.string,
disabled: PropTypes.bool,
status: ImmutablePropTypes.map,
isUserTouching: PropTypes.func,
isModalOpen: PropTypes.bool.isRequired,
onOpen: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
dropdownPlacement: PropTypes.string,
openDropdownId: PropTypes.number,
openedViaKeyboard: PropTypes.bool,
};
static defaultProps = {
title: 'Menu',
};
state = {
id: id++,
};
handleClick = ({ target, type }) => {
if (this.state.id === this.props.openDropdownId) {
this.handleClose();
} else {
const { top } = target.getBoundingClientRect();
const placement = top * 2 < innerHeight ? 'bottom' : 'top';
this.props.onOpen(this.state.id, this.handleItemClick, placement, type !== 'click');
}
}
handleClose = () => {
if (this.activeElement) {
this.activeElement.focus();
this.activeElement = null;
}
this.props.onClose(this.state.id);
}
handleMouseDown = () => {
if (!this.state.open) {
this.activeElement = document.activeElement;
}
}
handleButtonKeyDown = (e) => {
switch(e.key) {
case ' ':
case 'Enter':
this.handleMouseDown();
break;
}
}
handleKeyPress = (e) => {
switch(e.key) {
case ' ':
case 'Enter':
this.handleClick(e);
e.stopPropagation();
e.preventDefault();
break;
}
}
handleItemClick = e => {
const i = Number(e.currentTarget.getAttribute('data-index'));
const { action, to } = this.props.items[i];
this.handleClose();
if (typeof action === 'function') {
e.preventDefault();
action();
} else if (to) {
e.preventDefault();
this.context.router.history.push(to);
}
}
setTargetRef = c => {
this.target = c;
}
findTarget = () => {
return this.target;
}
componentWillUnmount = () => {
if (this.state.id === this.props.openDropdownId) {
this.handleClose();
}
}
render () {
const { icon, items, size, title, disabled, dropdownPlacement, openDropdownId, openedViaKeyboard } = this.props;
const open = this.state.id === openDropdownId;
return (
<div>
<IconButton
icon={icon}
title={title}
active={open}
disabled={disabled}
size={size}
ref={this.setTargetRef}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
onKeyDown={this.handleButtonKeyDown}
onKeyPress={this.handleKeyPress}
/>
<Overlay show={open} placement={dropdownPlacement} target={this.findTarget}>
<DropdownMenu items={items} onClose={this.handleClose} openedViaKeyboard={openedViaKeyboard} />
</Overlay>
</div>
);
}
}
|
app/desktop/LiveUser/index.js | christianalfoni/webpack-bin | import React from 'react';
import {Decorator as Cerebral} from 'cerebral-view-react';
import styles from './styles.css';
@Cerebral({
userName: 'live.userName',
controllingUser: 'live.controllingUser'
})
class LiveUser extends React.Component {
render() {
return (
<div className={styles.wrapper}>
<div
className={this.props.controllingUser === this.props.userName ? styles.activeUser : styles.user}>
{this.props.userName}
</div>
</div>
);
}
}
export default LiveUser;
|
src/components/Portfolio.js | jerednel/jerednel.github.io | import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Card, CardContent, CardActionArea, CardMedia, Typography, Grid, Container } from '@material-ui/core/';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
backgroundColor: theme.palette.primary.light,
},
card: {
maxWidth: 250,
margin: 0,
},
media: {
height: 160,
},
}));
export default function Portfolio(props) {
const classes = useStyles();
if (props.data) {
var projects = props.data.projects.map(function (projects) {
var projectImage = 'images/portfolio/' + projects.image;
return (
<div key={projects.title} className="columns portfolio-item">
<Card className={classes.card}>
<CardActionArea href={projects.url}>
<CardMedia className={classes.media} image={projectImage} title={projects.title} />
<CardContent>
<Typography gutterBottom variant="h5" component="h2">{projects.title}</Typography>
<Typography variant="body2" gutterBottom>{projects.category}</Typography>
</CardContent>
</CardActionArea>
</Card>
</div>
)
})
}
return (
<section className={classes.root} id="portfolio">
<Container className="row">
<h1>Check Out Some of My Works.</h1>
<div id="portfolio-wrapper" className="bgrid-quarters s-bgrid-thirds cf">
{projects}
</div>
</Container>
</section>
);
}
|
node_modules/react-bootstrap/es/DropdownMenu.js | Crisa221/Lista-Giocatori | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _Array$from from 'babel-runtime/core-js/array/from';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import keycode from 'keycode';
import React from 'react';
import ReactDOM from 'react-dom';
import RootCloseWrapper from 'react-overlays/lib/RootCloseWrapper';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
import createChainedFunction from './utils/createChainedFunction';
import ValidComponentChildren from './utils/ValidComponentChildren';
var 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
};
var defaultProps = {
bsRole: 'menu',
pullRight: false
};
var DropdownMenu = function (_React$Component) {
_inherits(DropdownMenu, _React$Component);
function DropdownMenu(props) {
_classCallCheck(this, DropdownMenu);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.handleKeyDown = _this.handleKeyDown.bind(_this);
return _this;
}
DropdownMenu.prototype.handleKeyDown = function 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:
}
};
DropdownMenu.prototype.getItemsAndActiveIndex = function getItemsAndActiveIndex() {
var items = this.getFocusableMenuItems();
var activeIndex = items.indexOf(document.activeElement);
return { items: items, activeIndex: activeIndex };
};
DropdownMenu.prototype.getFocusableMenuItems = function getFocusableMenuItems() {
var node = ReactDOM.findDOMNode(this);
if (!node) {
return [];
}
return _Array$from(node.querySelectorAll('[tabIndex="-1"]'));
};
DropdownMenu.prototype.focusNext = function focusNext() {
var _getItemsAndActiveInd = this.getItemsAndActiveIndex();
var items = _getItemsAndActiveInd.items;
var activeIndex = _getItemsAndActiveInd.activeIndex;
if (items.length === 0) {
return;
}
var nextIndex = activeIndex === items.length - 1 ? 0 : activeIndex + 1;
items[nextIndex].focus();
};
DropdownMenu.prototype.focusPrevious = function focusPrevious() {
var _getItemsAndActiveInd2 = this.getItemsAndActiveIndex();
var items = _getItemsAndActiveInd2.items;
var activeIndex = _getItemsAndActiveInd2.activeIndex;
if (items.length === 0) {
return;
}
var prevIndex = activeIndex === 0 ? items.length - 1 : activeIndex - 1;
items[prevIndex].focus();
};
DropdownMenu.prototype.render = function render() {
var _extends2,
_this2 = this;
var _props = this.props;
var open = _props.open;
var pullRight = _props.pullRight;
var onClose = _props.onClose;
var labelledBy = _props.labelledBy;
var onSelect = _props.onSelect;
var className = _props.className;
var children = _props.children;
var props = _objectWithoutProperties(_props, ['open', 'pullRight', 'onClose', 'labelledBy', 'onSelect', 'className', 'children']);
var _splitBsProps = splitBsProps(props);
var bsProps = _splitBsProps[0];
var elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'right')] = pullRight, _extends2));
var list = React.createElement(
'ul',
_extends({}, elementProps, {
role: 'menu',
className: classNames(className, classes),
'aria-labelledby': labelledBy
}),
ValidComponentChildren.map(children, function (child) {
return React.cloneElement(child, {
onKeyDown: createChainedFunction(child.props.onKeyDown, _this2.handleKeyDown),
onSelect: createChainedFunction(child.props.onSelect, onSelect)
});
})
);
if (open) {
return React.createElement(
RootCloseWrapper,
{ noWrap: true, onRootClose: onClose },
list
);
}
return list;
};
return DropdownMenu;
}(React.Component);
DropdownMenu.propTypes = propTypes;
DropdownMenu.defaultProps = defaultProps;
export default bsClass('dropdown-menu', DropdownMenu); |
src/app.js | fkoester/tachograph-app | import React from 'react';
import { UIManager } from 'react-native';
import { Provider } from 'react-redux';
import store from './store';
import scenes from './scenes';
import './i18n';
UIManager.setLayoutAnimationEnabledExperimental(true);
export default class App extends React.Component {
componentDidMount() {
}
render() {
return (
<Provider store={store}>
{scenes}
</Provider>
);
}
}
|
src/pages/SignoutPage.js | ihenvyr/react-parse | import React from 'react';
import Helmet from 'react-helmet';
import { withRouter } from 'react-router';
import Parse from 'parse';
class SignoutPage extends React.Component {
static propTypes = {};
static defaultProps = {};
componentDidMount() {
Parse.User.logOut().then(() => {
this.props.router.push('/');
});
}
render() {
return (
<div>
<Helmet
title="Logging out.."
meta={[
{ name: "description", content: "Logging out.." }
]}
/>
<p>Logging out..</p>
</div>
);
}
}
export default withRouter(SignoutPage);
|
src/routes.js | taoveweb/reactTemplate | //import React from 'react';
//import { Route, IndexRoute } from 'react-router';
import App from './components/App';
/*import Home from './containers/Home';
import About from './containers/About';
import New from './containers/New';
import New1 from './containers/New1';
import NotFound from './containers/NotFound';*/
function errorLoading(err) {
console.error('Dynamic page loading failed', err);
}
function loadRoute(cb) {
return (module) => cb(null, module.default);
}
/*export default (
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="about" component={About}/>
<Route path="new" component={New}/>
<Route path="new1" component={New1}/>
<Route path="*" component={NotFound}/>
</Route>
);*/
export default {
component: App,
childRoutes: [
{
path: '/',
getComponent(location, cb) {
System.import('./containers/Home').then(loadRoute(cb)).catch(errorLoading);
}
},
{
path: 'about',
getComponent(location, cb) {
require("./static/css/about.scss");
System.import('./containers/About').then(loadRoute(cb)).catch(errorLoading);
}
},
]
};
|
packages/node_modules/@webex/react-component-adaptive-card/src/index.js | ciscospark/react-ciscospark | import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import {getAdaptiveCard, CARD_CONTAINS_IMAGE, replaceIndexWithBlobURL, API_ACTIVITY_VERB} from '@webex/react-component-utils';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {handleAdaptiveCardSubmitAction} from '@webex/redux-module-conversation';
import './adaptiveCard.scss';
import styles from './styles.css';
import messages from './messages';
class AdaptiveCard extends React.Component {
constructor(props) {
super(props);
this.nodeElement = React.createRef();
this.addChildNode = this.addChildNode.bind(this);
this.handleSubmitAction = this.handleSubmitAction.bind(this);
this.dismissStatusMessage = this.dismissStatusMessage.bind(this);
this.setupState = this.setupState.bind(this);
this.setStateForCardActionStatus = this.setStateForCardActionStatus.bind(this);
this.setStateForCardActionSubmissionFailed = this.setStateForCardActionSubmissionFailed.bind(this);
this.lastAcknowledgedCardActionActivityId = null;
this.cards = this.props.cards;
this.hasReplacedCard = false;
this.parentActivityId = null;
this.state = {
childNodes: [],
hasReplacedImagesInJSON: false,
actionStatusMessage: '',
isCardActionClicked: false,
isCardActionSubmissionFailed: false
};
}
componentDidMount() {
if (Object.prototype.hasOwnProperty.call(this, 'nodeElement') && Object.prototype.hasOwnProperty.call(this.nodeElement, 'current')) {
this.nodeElement.current.appendChild(
getAdaptiveCard(
this.cards,
this.props.displayName,
this.props.sdkInstance,
this.addChildNode,
this.props.activityId,
this.props.conversation,
this.handleSubmitAction
)
);
}
}
componentDidUpdate(prevProps) {
if (prevProps !== this.props) {
if (this.props.verb === API_ACTIVITY_VERB.SHARE) {
try {
const decryptedURLs = this.props.items.filter((file) => file.type === CARD_CONTAINS_IMAGE)
.map((file) => {
const thumbnail = file.mimeType === 'image/gif' ? this.props.share.getIn(['files', file.url]) : this.props.share.getIn(['files', file.image.url]);
if (thumbnail) {
const objectUrl = thumbnail.get('objectUrl');
return objectUrl;
}
return undefined;
});
const cardsObject = JSON.parse(this.props.cards[0]);
const undefinedUrls = decryptedURLs.filter((file) => file === undefined);
if (undefinedUrls.length === 0) {
this.cards[0] = JSON.stringify(replaceIndexWithBlobURL(cardsObject, decryptedURLs));
if (this.cards[0]) {
this.setupState();
}
}
}
catch (error) {
this.props.sdkInstance.logger.error('Unable render Adaptive Card', error.message);
}
}
if (this.props.conversation.get('lastAcknowledgedCardActionActivity')) {
const {formatMessage} = this.props.intl;
this.lastAcknowledgedCardActionActivityId = this.props.conversation.get('lastAcknowledgedCardActionActivity').cardActionAcknowledgmentId;
this.parentActivityId = this.props.conversation.get('lastAcknowledgedCardActionActivity').parentId;
if ((this.props.activityId === this.parentActivityId) &&
(!!this.lastAcknowledgedCardActionActivityId) && this.state.isCardActionClicked) {
setTimeout(() => {
this.setStateForCardActionStatus(formatMessage(messages.sent));
}, 500);
}
else if (this.parentActivityId === null && this.lastAcknowledgedCardActionActivityId === null) {
this.setStateForCardActionSubmissionFailed(true);
}
}
}
return null;
}
componentWillUnmount() {
this.state.childNodes.forEach((childNode) => {
ReactDOM.unmountComponentAtNode(childNode);
});
}
/**
* set state to actionStatusMessage
* @param {string} status
* @returns {void}
*/
setStateForCardActionStatus(status) {
this.setState({actionStatusMessage: status});
}
/**
* set state to isCardActionSubmissionFailed
* @param {boolean} isSubmissionFailed
* @returns {void}
*/
setStateForCardActionSubmissionFailed(isSubmissionFailed) {
const {formatMessage} = this.props.intl;
this.setState({isCardActionSubmissionFailed: isSubmissionFailed});
if (this.state.isCardActionSubmissionFailed) {
this.setStateForCardActionStatus(formatMessage(messages.unableToSendYourRequest));
}
}
/**
* set state to tohasReplacedImagesInJSON
* @returns {void}
*/
setupState() {
this.setState({hasReplacedImagesInJSON: true});
}
/**
* set state to maintain a list of all the DOM nodes
* @param {object} childNode
* @returns {void}
*/
addChildNode(childNode) {
this.setState((prevState) => ({childNodes: [...prevState.childNodes, childNode]}));
}
/**
* calls handleAdaptiveCardSubmitAction action when card action is performed
* @param {string} url
* @param {object} actionInput
* @param {string} parentId
* @returns {void}
*/
handleSubmitAction(url, actionInput, parentId) {
const {formatMessage} = this.props.intl;
this.props.handleAdaptiveCardSubmitAction(url, actionInput, parentId, this.props.sdkInstance);
this.setStateForCardActionStatus(formatMessage(messages.sending));
this.setState({isCardActionClicked: true});
}
/**
* method used to set the state variables to default state
* @returns {void}
*/
dismissStatusMessage() {
setTimeout(() => {
this.setStateForCardActionStatus('');
this.setState({isCardActionClicked: false});
this.lastAcknowledgedCardActionActivityId = null;
this.setStateForCardActionSubmissionFailed(false);
}, 2000);
}
render() {
const activityItemMsgClass = classnames('activity-item--adaptive-card');
const {formatMessage} = this.props.intl;
if (this.state.hasReplacedImagesInJSON && !this.hasReplacedCard) {
if (Object.prototype.hasOwnProperty.call(this, 'nodeElement') && Object.prototype.hasOwnProperty.call(this.nodeElement, 'current')) {
this.nodeElement.current.replaceChild(
getAdaptiveCard(
this.cards,
this.props.displayName,
this.props.sdkInstance,
this.addChildNode,
this.props.activityId,
this.props.conversation,
this.handleSubmitAction
),
this.nodeElement.current.firstChild
);
this.hasReplacedCard = true;
}
}
if (this.state.actionStatusMessage === formatMessage(messages.sending)
|| this.state.actionStatusMessage === formatMessage(messages.unableToSendYourRequest)) {
this.dismissStatusMessage();
}
return (
<div>
<div
ref={this.nodeElement}
className={activityItemMsgClass}
/>
{
this.state.isCardActionClicked && (this.state.isCardActionSubmissionFailed
? (
<div className={classnames('failed-status-box', styles.failedStatusBox)}>
<span className={classnames('failed-error-text', styles.failedErrorText)}>{this.state.actionStatusMessage}</span>
</div>
)
: (
<p className={classnames('pending-status-box', styles.pendingStatusBox)}>
<span className={classnames('pending-status-text', styles.pendingStatusText)}>{this.state.actionStatusMessage}</span>
</p>
)
)
}
</div>
);
}
}
const injectedPropTypes = {
handleAdaptiveCardSubmitAction: PropTypes.func.isRequired
};
AdaptiveCard.propTypes = {
cards: PropTypes.array,
displayName: PropTypes.string,
sdkInstance: PropTypes.object,
verb: PropTypes.string,
items: PropTypes.array,
share: PropTypes.object,
conversation: PropTypes.object,
activityId: PropTypes.string,
intl: PropTypes.object.isRequired,
...injectedPropTypes
};
AdaptiveCard.defaultProps = {
cards: [],
displayName: '',
sdkInstance: {},
verb: '',
items: [],
share: {},
conversation: {},
activityId: ''
};
export default connect(
(state) => ({
conversation: state.conversation
}),
(dispatch) => bindActionCreators({
handleAdaptiveCardSubmitAction
}, dispatch)
)(AdaptiveCard);
|
src/forms/rentFields.js | codeforboston/cliff-effects | import React, { Component } from 'react';
import { MonthlyCashFlowRow } from './cashflow';
import {
isNonNegNumber,
hasOnlyNonNegNumberChars,
} from '../utils/validators';
const BLANK_FUNCTION = function () {};
class RentShareField extends Component {
state = { valid: true, message: null };
storeValidator = (ownValue) => {
let message = null,
valid = true;
let isPosNum = isNonNegNumber(ownValue);
if (!isPosNum) {
valid = false;
} else {
valid = (Number(ownValue) <= this.props.timeState[ `contractRent` ]);
if (!valid) {
message = `Rent share must be less than contract rent`;
}
}
this.setState({ valid: valid, message: message });
return valid;
};
onBlur = (evnt) => {
this.setState({ valid: true, message: null });
};
render() {
const {
timeState,
updateClientValue,
} = this.props,
{
valid,
message,
} = this.state;
const inputProps = {
name: `rentShare`,
displayValidator: hasOnlyNonNegNumberChars,
storeValidator: this.storeValidator,
onBlur: this.onBlur,
},
rowProps = {
label: `Your Monthly Rent Share (how much of the total rent you have to pay)`,
name: `rentShare`,
validRow: valid,
message: message,
};
return (
<MonthlyCashFlowRow
inputProps = { inputProps }
baseValue = { timeState[ `rentShare` ] }
includes = { [ `monthly` ] }
updateClientValue = { updateClientValue }
rowProps = { rowProps } />
);
};
}; // Ends <RentShareField>
class ContractRentField extends Component {
state = { valid: true, message: null };
storeValidator = (ownValue) => {
let message = null,
valid = true;
let isPosNum = isNonNegNumber(ownValue);
if (!isPosNum) {
valid = false;
} else {
valid = (ownValue >= this.props.timeState[ `rentShare` ]);
if (!valid) {
message = `Contract rent must be more than rent share`;
}
}
this.setState({ valid: valid, message: message });
return valid;
};
onBlur = (evnt) => {
this.setState({ valid: true, message: null });
};
render() {
const {
timeState,
updateClientValue,
} = this.props,
{
valid,
message,
} = this.state;
const inputProps = {
name: `contractRent`,
displayValidator: hasOnlyNonNegNumberChars,
storeValidator: this.storeValidator,
onBlur: this.onBlur,
},
rowProps = {
label: `Monthly Contract Rent (the total rent for your apartment)`,
name: `contractRent`,
validRow: valid,
message: message,
};
return (
<MonthlyCashFlowRow
inputProps = { inputProps }
baseValue = { timeState[ `contractRent` ] }
includes = { [ `monthly` ] }
updateClientValue = { updateClientValue }
rowProps = { rowProps } />
);
};
}; // Ends <ContractRentField>
const PlainRentRow = function ({ timeState, updateClientValue }) {
const inputProps = {
name: `rent`,
displayValidator: hasOnlyNonNegNumberChars,
storeValidator: isNonNegNumber,
onBlur: BLANK_FUNCTION,
},
rowProps = {
label: `Monthly Rent`,
validRow: true,
message: null,
};
return (
<MonthlyCashFlowRow
inputProps = { inputProps }
baseValue = { timeState[ `rent` ] }
includes = { [ `monthly` ] }
updateClientValue = { updateClientValue }
rowProps = { rowProps } />
);
};
export {
ContractRentField,
RentShareField,
PlainRentRow,
};
|
src/Button.js | mattBlackDesign/react-materialize | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import constants from './constants';
import cx from 'classnames';
import Icon from './Icon';
import idgen from './idgen';
class Button extends Component {
constructor (props) {
super(props);
this.renderIcon = this.renderIcon.bind(this);
this.renderFab = this.renderFab.bind(this);
}
render () {
const {
className,
node,
fab,
fabClickOnly,
modal,
flat,
floating,
large,
disabled,
waves,
...other
} = this.props;
const toggle = fabClickOnly ? 'click-to-toggle' : '';
let C = node;
let classes = {
btn: true,
disabled,
'waves-effect': waves
};
if (constants.WAVES.indexOf(waves) > -1) {
classes['waves-' + waves] = true;
}
let styles = { flat, floating, large };
constants.STYLES.forEach(style => {
classes['btn-' + style] = styles[style];
});
if (modal) {
classes['modal-action'] = true;
classes['modal-' + modal] = true;
}
if (fab) {
return this.renderFab(cx(classes, className), fab, toggle);
} else {
return (
<C
{...other}
disabled={!!disabled}
onClick={this.props.onClick}
className={cx(classes, className)}
>
{ this.renderIcon() }
{ this.props.children }
</C>
);
}
}
renderFab (className, orientation, clickOnly) {
const classes = cx(orientation, clickOnly);
return (
<div className={cx('fixed-action-btn', classes)}>
<a className={className}>{ this.renderIcon() }</a>
<ul>
{
React.Children.map(this.props.children, child => {
return <li key={idgen()}>{child}</li>;
})
}
</ul>
</div>
);
}
renderIcon () {
const { icon } = this.props;
if (!icon) return;
return <Icon>{icon}</Icon>;
}
}
Button.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
disabled: PropTypes.bool,
/**
* Enable other styles
*/
flat: PropTypes.bool,
large: PropTypes.bool,
floating: PropTypes.bool,
/**
* Fixed action button
* If enabled, any children button will be rendered as actions, remember to provide an icon.
* @default vertical
*/
fab: PropTypes.oneOf(['vertical', 'horizontal']),
/**
* The icon to display, if specified it will create a button with the material icon
*/
icon: PropTypes.string,
modal: PropTypes.oneOf(['close', 'confirm']),
node: PropTypes.node,
onClick: PropTypes.func,
/**
* Tooltip to show when mouse hovered
*/
tooltip: PropTypes.string,
waves: PropTypes.oneOf(['light', 'red', 'yellow', 'orange', 'purple', 'green', 'teal']),
/**
* FAB Click-Only
* Turns a FAB from a hover-toggle to a click-toggle
*/
fabClickOnly: PropTypes.bool
};
Button.defaultProps = {
node: 'button'
};
export default Button;
|
src/app/containers/index.js | blowsys/reservo | import React from 'react';
import thunk from 'redux-thunk';
import { createStore, applyMiddleware, compose } from 'redux';
import type { Store } from 'redux';
import { Provider } from 'react-redux';
import Router from 'react-router/HashRouter';
import { connect } from 'react-redux';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import reducers from 'reducers/index';
import './styles.scss';
import { generateRouteMatches } from 'core/routes/helper';
import BaseRoutes, { indexPathname } from './routes';
import { getAppUser } from 'selectors/index';
const composeEnhancers =
process.env.NODE_ENV !== 'production' &&
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? // eslint-disable-line no-underscore-dangle
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ // eslint-disable-line no-underscore-dangle
}) : compose;
const enhancer = composeEnhancers(
applyMiddleware(thunk),
);
const store: Store<*, *> = createStore(reducers, enhancer);
const mapStateToProps = (state) => ({
auth: getAppUser(state)
});
const RoutesHandler = connect(mapStateToProps)((props) => {
const { auth = {} } = props;
return (
<Router>
<fb className="grow" style={{ height: '100%' }}>
{ generateRouteMatches(BaseRoutes, indexPathname, auth.isLoading || false, auth.isLoggedIn || false) }
</fb>
</Router>
);
});
export default class App extends React.Component {
render() {
return (
<MuiThemeProvider>
<Provider store={store}>
<RoutesHandler />
</Provider>
</MuiThemeProvider>
);
}
}
|
src/components/body/menu/options/AddModal.js | TechyFatih/Nuzlog | import React from 'react';
import { Modal, Media, Panel, Button, Row, Col, ControlLabel } from 'react-bootstrap';
import { actions } from 'react-redux-form';
import { connect } from 'react-redux';
import natures from 'data/natures.json';
import abilities from 'data/abilities.json';
import male from 'img/male.png';
import female from 'img/female.png';
import PokeSlot from 'components/pokemon/slot/PokeSlot';
import PokeSprite from 'components/pokemon/sprite/PokeSprite';
import { RRForm, RRFControl } from 'components/form/RRF';
import { addPokemon } from 'actions';
class AddModal extends React.Component {
constructor(props) {
super(props);
this.state = {
pokemon: null,
locations: {},
validLocation: false,
open: false
};
this.handleEnter = this.handleEnter.bind(this);
this.updatePokemon = this.updatePokemon.bind(this);
this.checkLocation = this.checkLocation.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleHide = this.handleHide.bind(this);
}
componentWillReceiveProps(nextProps) {
const {pokemon} = nextProps;
if (this.props.pokemon != pokemon) {
const locations = {};
for (let i in pokemon)
locations[pokemon[i].location] = true;
this.setState({locations});
}
}
handleEnter() {
const {location} = this.props;
this.setState({
pokemon: null,
open: false
});
this.dispatch(actions.change('local.location', location));
this.checkLocation(location);
this.dispatch(actions.setPristine('local'));
this.dispatch(actions.focus('local.species'));
}
updatePokemon(pokemon) {
this.setState(prevState => {
return {
pokemon: {...prevState.pokemon, ...pokemon}
};
});
}
checkLocation(location) {
this.setState(({locations}) => ({
validLocation: !locations[location]}
));
}
handleSubmit(values) {
let moves;
if (Array.isArray(values.moves))
moves = values.moves.filter(move => move);
this.props.onAddPokemon({
species: values.species,
nickname: values.nickname,
location: values.location,
level: values.level,
gender: values.gender,
shiny: values.shiny,
form: values.form,
nature: values.nature,
ability: values.ability,
moves,
item: values.item,
method: values.method
});
this.handleHide();
}
handleHide() {
this.setState({
open: false
});
this.props.onHide();
}
render() {
const {pokemon, validLocation} = this.state;
return (
<Modal show={this.props.show} onEnter={this.handleEnter}
onHide={this.handleHide}>
<RRForm getDispatch={dispatch => this.dispatch = dispatch}
onSubmit={this.handleSubmit}>
<Modal.Header closeButton><h2>Add Pokémon</h2></Modal.Header>
<Modal.Body>
<PokeSlot pokemon={pokemon} />
<PokeSprite pokemon={pokemon} />
<Row className='row-no-padding'>
<Col xs={6}>
<RRFControl model='.species' component='pokemon'
label='Pokemon*' placeholder='Bulbasaur' required
onChange={species => this.updatePokemon({species})} />
</Col>
<Col xs={6}>
<RRFControl model='.nickname' label='Nickname'
placeholder='Bulby' />
</Col>
</Row>
<ControlLabel>Location*</ControlLabel>
{validLocation ? (
<em> (No catches here yet)</em>
) : (
<em className='text-danger'> (You already reported this location!)</em>
)}
<Row className='row-no-padding'>
<Col xs={6}>
<RRFControl model='.method' componentClass='select'>
<option value='Received at:'>Received at:</option>
<option value='Caught at:'>Caught at:</option>
</RRFControl>
</Col>
<Col xs={6}>
<RRFControl model='.location' placeholder='Pallet Town'
onChange={this.checkLocation} required />
</Col>
</Row>
<Button onClick={() => this.setState(({open}) => ({open: !open}))}
block>
More Details
</Button>
<Panel collapsible expanded={this.state.open} className='no-margin'>
<Row>
<Col sm={6} xs={12}>
<RRFControl model='.level' type='number' label='Level'
placeholder='1-100'
onChange={level => this.updatePokemon({level})} />
</Col>
<Col sm={4} xs={7}>
<RRFControl model='.gender' component='toggle' type='radio'
label='Gender'
onChange={gender => this.updatePokemon({gender})}>
<img src={male} value='M' />
<img src={female} value='F' />
<span value='N'>N/A</span>
</RRFControl>
</Col>
<Col xs={2}>
<RRFControl model='.shiny' component='check'
onChange={shiny => this.updatePokemon({shiny})}>
Shiny
</RRFControl>
</Col>
</Row>
<Row>
<Col xs={6}>
<RRFControl model='.form' component='forms' label='Form'
placeholder='Normal' pokemon={this.state.pokemon}
onChange={form => this.updatePokemon({form})} />
<RRFControl model='.nature' component='combobox'
label='Nature' placeholder='Adamant'>
{natures}
</RRFControl>
<RRFControl model='.ability' component='combobox'
label='Ability' placeholder='Overgrow'>
{abilities}
</RRFControl>
</Col>
<Col xs={6}>
<RRFControl model='.moves' component='moves' label='Moves' />
</Col>
</Row>
<RRFControl model='.item' label='Item' placeholder='Oran Berry' />
</Panel>
</Modal.Body>
<Modal.Footer>
<Button type='submit' bsStyle='success' bsSize='large' block>
Add Pokémon
</Button>
</Modal.Footer>
</RRForm>
</Modal>
);
}
}
const mapStateToProps = state => {
return {
location: state.location,
pokemon: state.pokemon
}
};
const mapDispatchToProps = dispatch => {
return {
onAddPokemon: (pokemon) => {
dispatch(addPokemon(pokemon))
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(AddModal); |
Native/Learn_NavigationBox/index.android.js | renxlWin/React-Native_Demo | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button
} from 'react-native';
import { StackNavigator } from 'react-navigation'
class HomeScreen extends React.Component {
static navigationOptions = {
title : '附近',
};
render() {
const { navigate } = this.props.navigation;
var testPra = {'testKey' : '我是谁','user' : 'React'}
return (
<View>
<Text>Hello,React</Text>
<Button
onPress={() =>
navigate('Detail',testPra)
}
title = '详情'
/>
</View>
);
}
}
class DetailSereen extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: `${navigation.state.params.user}`,
});
render() {
const { params } = this.props.navigation.state;
return (
<Text>Hello {params.testKey}</Text>
);
}
}
const Learn_NavigationBox = StackNavigator({
Home : { screen : HomeScreen },
Detail : { screen : DetailSereen},
});
AppRegistry.registerComponent('Learn_NavigationBox', () => Learn_NavigationBox);
|
examples/tutorials/react-integration/front/src/index.js | softindex/datakernel | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
react_state/index.android.js | devSC/react-native | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
} from 'react-native';
import setup from './setup'
AppRegistry.registerComponent('react_state', () => setup);
|
src/containers/Launch/LaunchView.js | yursky/recommend | /**
* Launch Screen
* - Shows a nice loading screen whilst:
* - Preloading any specified app content
* - Checking if user is logged in, and redirects from there
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
View,
Image,
Alert,
StatusBar,
StyleSheet,
ActivityIndicator,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
// Consts and Libs
import { AppStyles, AppSizes } from '@theme/';
/* Styles ==================================================================== */
const styles = StyleSheet.create({
launchImage: {
width: AppSizes.screen.width,
height: AppSizes.screen.height,
},
});
/* Component ==================================================================== */
class AppLaunch extends Component {
static componentName = 'AppLaunch';
static propTypes = {
login: PropTypes.func.isRequired,
getYelpUsers: PropTypes.func.isRequired
}
constructor() {
super();
console.ignoredYellowBox = ['Setting a timer'];
}
componentDidMount = () => {
// Show status bar on app launch
StatusBar.setHidden(false, true);
// Preload content here
Promise.all([
this.props.getYelpUsers(),
]).then(() => {
// Once we've preloaded basic content,
// - Try to authenticate based on existing token
this.props.login()
// Logged in, show index screen
.then(() => Actions.app({ type: 'reset' }))
// Not Logged in, show Login screen
.catch(() => Actions.authenticate({ type: 'reset' }));
}).catch(err => Alert.alert(err.message));
}
render = () => (
<View style={[AppStyles.container]}>
<Image
source={require('../../images/launch.jpg')}
style={[styles.launchImage, AppStyles.containerCentered]}
>
<ActivityIndicator
animating
size={'large'}
color={'#C1C5C8'}
/>
</Image>
</View>
);
}
/* Export Component ==================================================================== */
export default AppLaunch;
|
game-new/src/utils/Icon.js | d07RiV/d3planner | import React from 'react';
import classNames from 'classnames';
class Icon extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {visible: false};
}
onLoad = () => {
this.setState({visible: true});
}
componentWillReceiveProps(newProps) {
if (newProps.src !== this.props.src) {
this.setState({visible: false});
}
}
render() {
const { className, ...props } = this.props;
return <img {...props} className={classNames(className, {"image-loading": !this.state.visible})} onLoad={this.onLoad}/>;
}
}
export { Icon };
export default Icon;
|
app/routes.js | alexdibattista/no-noise | /* eslint flowtype-errors/show-errors: 0 */
import React from 'react';
import { HashRouter as Router } from 'react-router-dom';
import { Switch, Route } from 'react-router';
import App from './containers/App';
import HomePage from './containers/HomePage';
import CounterPage from './containers/CounterPage';
export default () => (
<Router>
<App>
<Switch>
<Route path="/counter" component={CounterPage} />
<Route path="/" component={HomePage} />
</Switch>
</App>
</Router>
);
|
src/sidebar/app/router.js | cedricium/notes | import React from 'react';
import { HashRouter, Route } from 'react-router-dom';
import ListPanel from './components/ListPanel';
import EditorPanel from './components/EditorPanel';
const styles = {
container: {
flex: '100%',
display: 'flex',
flexDirection: 'column'
}
};
class Router extends React.Component {
render() {
return (
<HashRouter>
<div style={styles.container}>
<Route exact path="/" component={ListPanel} />
<Route exact path="/note" component={EditorPanel} />
<Route exact path="/note/:id" component={EditorPanel} />
</div>
</HashRouter>
);
}
}
export default Router;
|
src/sources/youtube/ImportPanel.js | welovekpop/uwave-web-welovekpop.club | import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { IDLE, LOADING, LOADED } from '../../constants/LoadingStates';
import { addMediaMenu as openAddMediaMenu } from '../../actions/PlaylistActionCreators';
import { PLAYLIST, CHANNEL } from './constants';
import { importPlaylist } from './actions';
import LoadingPanel from './LoadingPanel';
import ChannelPanel from './ChannelPanel';
import PlaylistPanel from './PlaylistPanel';
const mapStateToProps = () => ({});
const mapDispatchToProps = dispatch => bindActionCreators({
onImportPlaylist: importPlaylist,
onOpenAddMediaMenu: openAddMediaMenu,
}, dispatch);
const YouTubeImportPanel = ({ type, importingState, ...props }) => {
if (importingState === LOADED) {
if (type === PLAYLIST) {
return <PlaylistPanel {...props} />;
}
return <ChannelPanel {...props} />;
}
return <LoadingPanel {...props} />;
};
YouTubeImportPanel.propTypes = {
type: PropTypes.oneOf([PLAYLIST, CHANNEL]).isRequired,
importingState: PropTypes.oneOf([IDLE, LOADING, LOADED]),
};
export default connect(mapStateToProps, mapDispatchToProps)(YouTubeImportPanel);
|
src/components/common/svg-icons/image/crop-din.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCropDin = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z"/>
</SvgIcon>
);
ImageCropDin = pure(ImageCropDin);
ImageCropDin.displayName = 'ImageCropDin';
ImageCropDin.muiName = 'SvgIcon';
export default ImageCropDin;
|
geonode/contrib/monitoring/frontend/src/components/organisms/ws-analytics/index.js | kartoza/geonode | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import HoverPaper from '../../atoms/hover-paper';
import HR from '../../atoms/hr';
import WSServiceSelect from '../../molecules/ws-service-select';
import ResponseTime from '../../cels/response-time';
import Throughput from '../../cels/throughput';
import ErrorsRate from '../../cels/errors-rate';
import { getCount, getTime } from '../../../utils';
import styles from './styles';
import actions from './actions';
const mapStateToProps = (state) => ({
errors: state.wsErrorSequence.response,
interval: state.interval.interval,
responseTimes: state.wsServiceData.response,
responses: state.wsResponseSequence.response,
selected: state.wsService.service,
throughputs: state.wsThroughputSequence.throughput,
timestamp: state.interval.timestamp,
});
@connect(mapStateToProps, actions)
class WSAnalytics extends React.Component {
static propTypes = {
errors: PropTypes.object,
getErrors: PropTypes.func.isRequired,
getResponseTimes: PropTypes.func.isRequired,
getResponses: PropTypes.func.isRequired,
getThroughputs: PropTypes.func.isRequired,
interval: PropTypes.number,
resetErrors: PropTypes.func.isRequired,
resetResponseTimes: PropTypes.func.isRequired,
resetResponses: PropTypes.func.isRequired,
resetThroughputs: PropTypes.func.isRequired,
responseTimes: PropTypes.object,
responses: PropTypes.object,
selected: PropTypes.string,
throughputs: PropTypes.object,
timestamp: PropTypes.instanceOf(Date),
}
constructor(props) {
super(props);
this.get = (
service = this.props.selected,
interval = this.props.interval,
) => {
this.props.getResponses(service, interval);
this.props.getResponseTimes(service, interval);
this.props.getThroughputs(service, interval);
this.props.getErrors(service, interval);
};
this.reset = () => {
this.props.resetResponses();
this.props.resetResponseTimes();
this.props.resetThroughputs();
this.props.resetErrors();
};
}
componentWillMount() {
if (this.props.timestamp && this.props.selected) {
this.get();
}
}
componentWillReceiveProps(nextProps) {
if (nextProps && nextProps.selected && nextProps.timestamp) {
if ((nextProps.timestamp !== this.props.timestamp) ||
(nextProps.selected !== this.props.selected)) {
this.get(nextProps.selected, nextProps.interval);
}
}
}
componentWillUnmount() {
this.reset();
}
render() {
let responseData = [];
let throughputData = [];
let errorRateData = [];
let averageResponseTime = 0;
let maxResponseTime = 0;
if (this.props.responseTimes) {
const data = this.props.responseTimes.data.data;
if (data.length > 0) {
if (data[0].data.length > 0) {
const metric = data[0].data[0];
maxResponseTime = Math.floor(metric.max);
averageResponseTime = Math.floor(metric.val);
}
}
}
responseData = getTime(this.props.responses);
throughputData = getCount(this.props.throughputs);
errorRateData = getCount(this.props.errors);
return (
<HoverPaper style={styles.content}>
<h3>W*S Analytics</h3>
<WSServiceSelect />
<ResponseTime
average={averageResponseTime}
max={maxResponseTime}
data={responseData}
/>
<HR />
<Throughput data={throughputData} />
<HR />
<ErrorsRate data={errorRateData} />
</HoverPaper>
);
}
}
export default WSAnalytics;
|
src/components/App.js | dzwiedziu-nkg/books-collection-frontend | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import 'bootstrap';
import './basic/EditButton';
import '../styles/App.css';
import EditButton from "./basic/EditButton";
class AppComponent extends React.Component {
static propTypes = {
brand_name: PropTypes.string,
children: PropTypes.node,
edit: PropTypes.bool,
onEditChange: PropTypes.func
};
static defaultProps = {
edit: false,
onEditChange: (edit) => {}
};
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.props.onEditChange(!this.props.edit);
}
render() {
const { edit } = this.props;
return (
<div className="container">
<div className="jumbotron">
<EditButton active={edit} onEditClick={this.handleClick}/>
<h1><Link to="/">{this.props.brand_name}</Link></h1>
</div>
{this.props.children}
</div>
);
}
}
export default AppComponent;
|
src/components/Header.js | codevinsky/deep-ellum-jukebox-ui | import React from 'react';
import { Grid, Row, Col, Button, Glyphicon, Input } from 'react-bootstrap';
import FitterHappierText from 'react-fitter-happier-text';
import ReactFitText from 'react-fittext';
import { Hatchshow, FullScreenSearch, BigText } from './index';
class Header extends React.Component {
constructor(...args) {
super(...args);
this.state = {searchQuery: ''};
this.handleInput = _.bind(this.handleInput, this);
this.searchLink = {
value: this.state.searchQuery,
requestChange: this.handleInput
};
}
handleInput(event) {
let query = event.target.value;
this.setState({searchQuery: query});
if ( query.length >= 4 ) {
_.delay(() => this.setState({searchQuery: ''}), 1000);
}
}
render() {
return (
<header>
<Row className="intro-text">
<Col xs={8}
sm={6}
md={5}
lg={4}
className="intro-heading">
<Hatchshow>
DEEP
</Hatchshow>
<Hatchshow>
ELLUM
</Hatchshow>
<Hatchshow>
JUKEBOX
</Hatchshow>
<Hatchshow>
.COM
</Hatchshow>
</Col>
</Row>
</header>
);
}
}
export default Header;
|
javascript/src/containers/ViewToggleContainer.js | unclecheese/silverstripe-kickassets | import React from 'react';
import Reflux from 'reflux';
import Navigation from '../actions/Navigation';
import ViewToggle from '../views/ViewToggle';
const ViewToggleContainer = React.createClass({
mixins: [
React.addons.PureRenderMixin,
Reflux.ListenerMixin
],
propTypes: {
routerParams: React.PropTypes.object.isRequired
},
handleToggle (view) {
Navigation.updateView(view);
},
render () {
return <ViewToggle onToggle={this.handleToggle} view={this.props.routerParams.get('view')} />
}
});
export default ViewToggleContainer; |
components/CheckboxGroup/index.js | azl397985856/ltcrm-components | import React from 'react';
import {Col} from 'antd';
import Checkbox from 'rc-checkbox';
const CheckboxGroup = React.createClass({
getDefaultProps() {
return {
prefixCls: 'ant-checkbox',
options: [],
defaultValue: [],
onChange() {},
span: 4,
};
},
propTypes: {
defaultValue: React.PropTypes.array,
value: React.PropTypes.array,
options: React.PropTypes.array.isRequired,
onChange: React.PropTypes.func,
span: React.PropTypes.string,
},
getInitialState() {
const props = this.props;
let value;
if ('value' in props) {
value = props.value;
} else if ('defaultValue' in props) {
value = props.defaultValue;
}
return { value };
},
componentWillReceiveProps(nextProps) {
if ('value' in nextProps) {
this.setState({
value: nextProps.value || [],
});
}
},
toggleOption(option) {
const optionIndex = this.state.value.indexOf(option);
const value = [...this.state.value];
if (optionIndex === - 1) {
value.push(option);
} else {
value.splice(optionIndex, 1);
}
if (!('value' in this.props)) {
this.setState({ value });
}
this.props.onChange(value);
},
render() {
const options = this.props.options;
const span = this.props.span;
return (
<div className="ant-checkbox-group col-24">
{
options.map(option =>
<Col span= {span}>
<label className="ant-checkbox-group-item" key={option}>
<Checkbox disabled={this.props.disabled} {...this.props}
checked={this.state.value.indexOf(option) !== -1}
onChange={this.toggleOption.bind(this, option)} />
{option}
</label>
</Col>
)
}
</div>
);
},
});
export default CheckboxGroup;
module.exports = exports['default'];
|
pilgrim3/components/serviceBrowser.js | opendoor-labs/pilgrim3 | import React from 'react';
import state from './state';
import { Link } from 'react-router';
import { map } from 'lodash';
import { relativeName } from './utils';
import ProtoInfo from './protoInfo';
import DocBlock from './docBlock';
import OptionsPopover from './optionsPopover';
export default class ServiceBrowser extends React.Component {
renderService(service) {
// TODO(daicoden) replace test-done with template mechanism, tests will use it to inject this data, others can use it to styleize page
return (
<div>
<h1>{service.name}<OptionsPopover placement='right' obj={service} /></h1>
<DocBlock docs={service.documentation} />
<ProtoInfo infoObject={service}/>
{this.renderMethods(service)}
<div id="test-done"></div>
</div>
);
}
renderMethods(service) {
let methodRows = this.renderMethodRows(service.method, service);
return (
<div className='panel panel-default'>
<div className='panel-heading'>Methods</div>
<table className='table table-hover'>
<thead>
<tr>
<th/>
<th>Name</th>
<th>Input</th>
<th>Output</th>
<th/>
</tr>
</thead>
<tbody>
{methodRows}
</tbody>
</table>
</div>
);
}
renderMethodRows(methods, service) {
return map(methods, (meth) => {
let deprecated = (meth.options && meth.options.deprecated) ? 'deprecated' : '';
return (
<tr key={`rpc-method-${service.fullName}-${meth.name}`} className={deprecated}>
<td><OptionsPopover obj={meth}/></td>
<td>{meth.name}</td>
<td><Link to={`/messages/${meth.inputType}`}>{relativeName(meth.inputType, service.fileDescriptor)}</Link></td>
<td><Link to={`/messages/${meth.outputType}`}>{relativeName(meth.outputType, service.fileDescriptor)}</Link></td>
<td>{meth.documentation}</td>
</tr>
);
});
}
render() {
if (!state.byService) {
return (<div className='alert alert-info'>Loading</div>);
}
let service = state.byService[this.props.params.service_name];
if (!service) {
return (<div className='alert alert-danger'>Service Not Found</div>);
} else {
return this.renderService(service);
}
}
}
|
webapp/src/containers/search/logList.js | nathandunn/agr | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Tooltip, OverlayTrigger } from 'react-bootstrap';
import style from './style.css';
const DEFAULT_LABEL = 'Homologs';
const HIGHLIGHT_EL = 'em';
import { selectQueryParams } from '../../selectors/searchSelectors';
class LogListComponent extends Component {
renderLabel(raw) {
if (this.props.rawHighlight) {
let q = this.props.query;
let re = new RegExp(q, 'gi');
let htmlStr = raw.replace(re, `<${HIGHLIGHT_EL}>${q}</${HIGHLIGHT_EL}>`);
return <span dangerouslySetInnerHTML={{ __html: htmlStr }} />;
}
return raw;
}
render() {
let logs = this.props.logs;
let label = this.props.label;
if (!logs) return null;
label = label || DEFAULT_LABEL;
if (logs.length === 0) return null;
let nodes = logs.map( (d, i) => {
let commaNode = (i === logs.length - 1) ? null : ', ';
let tooltipNode = <Tooltip className='in' id='tooltip-top' placement='top'><i>{d.species}</i> type: {d.relationship_type}</Tooltip>;
return (
<span key={'h.' + i}>
<OverlayTrigger overlay={tooltipNode} placement='top'>
<a href={d.href} target='_new'>
{this.renderLabel(d.symbol)}
</a>
</OverlayTrigger>
<a className={style.evidenceFootnote} href={d.evidence_href} target='_new'>
{this.renderLabel(d.evidence_name)}
</a>
{commaNode}
</span>
);
});
return (
<div className={style.detailContainer}>
<span className={style.detailLabel}><strong>{label}:</strong> {nodes}</span>
</div>
);
}
}
LogListComponent.propTypes = {
label: React.PropTypes.string,
logs: React.PropTypes.array,
query: React.PropTypes.string,
rawHighlight: React.PropTypes.string
};
function mapStateToProps(state) {
let qp = selectQueryParams(state);
return {
query: qp.q || ''
};
}
export default connect(mapStateToProps)(LogListComponent);
|
sourcestats/webpack/main.js | Fizzadar/SourceServerStats | // Source Server Stats
// File: sourcestats/webpack/main.jsx
// Desc: frontend entry-point
import React from 'react';
import ReactDOM from 'react-dom';
// Not included by default
import 'react-select/less/default.less';
import 'metrics-graphics/dist/metricsgraphics.css';
import './main.less';
import { App } from './App';
ReactDOM.render(
<App />,
document.getElementById('app')
);
|
client/src/js/components/Nav/Footer.js | yassinej/oerk_v4 | import React, { Component } from 'react';
class Footer extends Component {
render() {
return (
<div className="container-fluid p-1 p-md-3 text-center bg-warning">
Footer
</div>
);
}
}
export default Footer;
|
src/scripts/modules/guest/forgot/UserForgotComponent.js | arikanmstf/userauth | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import InputText from '../../../common/input/InputText';
class UserForgotComponent extends Component {
constructor (props) {
super(props);
this.state = props;
this.submitForgotForm = this.submitForgotForm.bind(this);
}
submitForgotForm () {
const form = {
email: this.state.email
};
this.props.submitForgotForm(form);
}
render () {
return (
<div className="user-forgot-component">
<p>Enter your email address to recover your password</p>
<InputText
onChange={e => this.setState({ email: e })}
placeholder="Example email: [email protected]"
/>
<button className="btn btn-primary" onClick={() => this.submitForgotForm()}>Submit</button>
</div>
);
}
}
UserForgotComponent.propTypes = {
submitForgotForm: PropTypes.func.isRequired
};
export default UserForgotComponent;
|
ui/lib/search.js | Bit-Nation/BITNATION-Pangea | 'use babel'
import React from 'react'
import ssbref from 'ssb-ref'
import app from './app'
import u from 'patchkit-util'
import social from 'patchkit-util/social'
import t from 'patchwork-translations'
const MAX_CHANNEL_RESULTS = 3
const MAX_USER_RESULTS = 3
export function getResults (query) {
var results = []
// ssb references
if (ssbref.isLink(query)) {
var shortened = u.shortString(query)
if (ssbref.isFeedId(query)) results = [{ icon: 'user', label: t('search.OpenUser', {id: shortened}), fn: openObject }]
else if (ssbref.isMsgId(query)) results = [{ icon: 'envelope', label: t('search.OpenMessage', {id: shortened}), fn: openObject }]
else if (ssbref.isBlobId(query)) results = [{ icon: 'file', label: t('search.OpenFile', {id: shortened}), fn: openObject }]
results.push({ icon: 'search', label: t('search.SearchForReferences', {id: shortened}), fn: doSearch({ type: 'mentions' }) })
return results
}
// general results
results = results.concat([
{ icon: 'envelope', label: t('search.SearchMessages', {query}), fn: doSearch({ type: 'posts' }) }
])
// builtin pages
// TODO
// known users
results = results.concat(getUserResults(query))
// channels
results = results.concat(getChannelResults(query))
return results
}
function getUserResults (query) {
if (query.charAt(0) == '#') // strip off the pound
query = query.slice(1)
query = query.toLowerCase()
var results = []
for (let id in app.users.names) {
var name = app.users.names[id]
if (typeof name == 'string' && name.toLowerCase().indexOf(query) !== -1)
results.push(id)
}
// sort by popularity (isnt that just the way of things?)
results.sort(social.sortByPopularity.bind(social, app.users))
results = results
.slice(0, MAX_USER_RESULTS)
.map(id => { return { icon: 'user', label: t('search.OpenUser', {id: app.users.names[id]}), fn: () => openObject(id) } })
return results
}
function getChannelResults (query) {
if (query.charAt(0) == '#') // strip off the pound
query = query.slice(1)
query = query.toLowerCase()
var hasExact = false
var results = []
for (var i=0; i < app.channels.length && results.length < MAX_CHANNEL_RESULTS; i++) {
var ch = app.channels[i]
if (ch.name.toLowerCase().indexOf(query) !== -1) {
if (!hasExact)
hasExact = (ch.name == query)
results.push({
icon: 'hashtag',
label: <span>{t('search.OpenChannel', {name: ch.name})}</span>,
fn: openChannel(ch.name)
})
}
}
if (!hasExact)
results.push({ icon: 'hashtag', label: t('search.OpenChannel', {name: query}), fn: openChannel(query) })
return results
}
function openObject (ref) {
if (ssbref.isFeedId(ref)) {
app.history.pushState(null, '/profile/'+encodeURIComponent(ref))
} else if (ssbref.isMsgId(ref)) {
app.history.pushState(null, '/msg/'+encodeURIComponent(ref))
} else if (ssbref.isBlobId(ref)) {
window.location = '/'+encodeURIComponent(ref)
}
}
const openChannel = channel => () => {
if (channel.charAt(0) == '#') // strip off the pound
channel = channel.slice(1)
app.history.pushState(null, '/channel/'+encodeURIComponent(channel))
}
export const doSearch = opts => query => {
// TODO incorporate `opts`
app.history.pushState(null, '/search/'+encodeURIComponent(query))
} |
src/svg-icons/av/forward-10.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvForward10 = (props) => (
<SvgIcon {...props}>
<path d="M4 13c0 4.4 3.6 8 8 8s8-3.6 8-8h-2c0 3.3-2.7 6-6 6s-6-2.7-6-6 2.7-6 6-6v4l5-5-5-5v4c-4.4 0-8 3.6-8 8zm6.8 3H10v-3.3L9 13v-.7l1.8-.6h.1V16zm4.3-1.8c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.8-.8v-.5s-.1-.2-.1-.3-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z"/>
</SvgIcon>
);
AvForward10 = pure(AvForward10);
AvForward10.displayName = 'AvForward10';
AvForward10.muiName = 'SvgIcon';
export default AvForward10;
|
stories/list/index.js | JerryBerton/dh-component | import React from 'react';
import { storiesOf, action, linkTo } from '@kadira/storybook';
import withReadme from 'storybook-readme/with-readme';
import { List, Menu, Dropdown, Icon, Avatar} from '../../src';
import listReadme from './list.md';
const addWithInfoOptions = { inline: true, propTables: false };
const menu = (
<Menu>
<Menu.Item>
<span>菜单1</span>
</Menu.Item>
<Menu.Item>
<span>菜单2</span>
</Menu.Item>
</Menu>
);
const suffix = (
<Dropdown overlay={menu} trigger="click">
<Icon type="list-circle"/>
</Dropdown>
);
storiesOf('列表组件', module)
.addDecorator(withReadme(listReadme))
.addWithInfo('默认列表', () => (
<List mode="only" itemClassName="wjb-" itemStyles={{color: 'red'}}>
<List.Item key="1" onClick={action('onClick')}> 我是默认列表 </List.Item>
<List.Item key="2" onClick={action('onClick')}> 我是默认列表 </List.Item>
<List.Item key="3" onClick={action('onClick')}> 我是默认列表 </List.Item>
</List>
), addWithInfoOptions)
.addWithInfo('单行选择', () => (
<List
mode="only"
selectedKeys={['1']}
onChange={action('onChange')}>
<List.Item key="1"> 我可以被操作选择</List.Item>
<List.Item key="2"> 我可以被操作选择</List.Item>
<List.Item key="3"> 我可以被操作选择</List.Item>
</List>
), addWithInfoOptions)
.addWithInfo('单行选择不可变', () => (
<List
mode="only"
immutable
icon
onChange={action('onChange')}>
<List.Item key="1"> 我可以被操作选择, 但是不可变</List.Item>
<List.Item key="2"> 我可以被操作选择, 但是不可变</List.Item>
<List.Item key="3"> 我可以被操作选择, 但是不可变</List.Item>
</List>
), addWithInfoOptions)
.addWithInfo('多行选择', () => (
<List mode="multiple" icon onChange={action('onChange')}>
<List.Item key="1"> 来点我一下</List.Item>
<List.Item key="2"> 来点我一下</List.Item>
<List.Item key="3"> 来点我一下</List.Item>
</List>
), addWithInfoOptions)
.addWithInfo('前缀图标', () => (
<List>
<List.Item key="1" prefix={<Avatar />}>Avatar的前置图标</List.Item>
<List.Item
key="2"
prefix={<Avatar src="http://7xr8fr.com1.z0.glb.clouddn.com/IMG_2197.JPG"/>}
>
Avatar用户传入图片
</List.Item>
<List.Item
key="3"
prefix={<Avatar>OK</Avatar>}
>
Avatar自定义中间元素
</List.Item>
<List.Item
key="4"
prefix={<Avatar radius={false}>中国</Avatar>}
>
我是方形的前置元素
</List.Item>
</List>
), addWithInfoOptions)
.addWithInfo('后缀图标', () => (
<List>
<List.Item key="1" suffix={suffix}> Avatar用户传入图片</List.Item>
<List.Item key="2" suffix={suffix}> Avatar用户传入图片</List.Item>
<List.Item key="3" suffix={suffix}> Avatar用户传入图片</List.Item>
<List.Item key="4" suffix={suffix}> Avatar用户传入图片</List.Item>
<List.Item key="5" suffix={suffix}> Avatar用户传入图片</List.Item>
</List>
), addWithInfoOptions)
|
src/routes/appointment/EditAppointment.js | chunkiat82/rarebeauty-ui | import React from 'react';
import moment from 'moment';
import Appointment from './components/Individual';
import Layout from '../../components/Layout';
import {
listContacts,
getAppointment,
queryPastAppointments,
getServices,
cancelAppointment,
updateAppointment,
} from './common/functions';
import CancelSection from './components/CancelSection';
function show(store) {
return () => {
store.dispatch({ type: 'SHOW_LOADER' });
};
}
function hide(store) {
return () => {
store.dispatch({ type: 'HIDE_LOADER' });
};
}
async function action({ fetch, params, store }) {
const apptId = params.id;
const appointment = await getAppointment(fetch)(apptId);
if (appointment.error) {
return {
chunks: ['appointment-edit'],
title: 'Rare Beauty Professional',
component: (
<Layout>
<center>
<h1>Appointment Does Not Exist</h1>
</center>
</Layout>
),
};
}
show(store)();
const contacts = await listContacts(fetch)();
const { event, transaction } = appointment;
const name = event.name;
const mobile = event.mobile;
const startDate = moment(event.start);
const endDate = moment(event.end);
const duration = Number(moment.duration(endDate - startDate) / 60000);
const serviceIds = event.serviceIds;
const resourceName = event.resourceName;
let discount = 0;
let additional = 0;
let totalAmount = 0;
let deposit = 0;
if (transaction) {
discount = transaction.discount;
additional = transaction.additional;
totalAmount = transaction.totalAmount;
deposit = transaction.deposit;
}
// const pastAppointments = await queryPastAppointments(fetch)(resourceName);
const {
appointments: pastAppointments,
cancelCount: cancelAppointmentsCount,
} = await queryPastAppointments(fetch)(resourceName);
const services = await getServices(fetch)();
// console.log(`resourceName=${resourceName}`);
// console.log(`Edit pastAppointments=${JSON.stringify(pastAppointments)}`);
hide(store)();
if (!contacts) throw new Error('Failed to load the contact feed.');
return {
chunks: ['appointment-edit'],
title: 'Rare Beauty Professional',
component: (
<Layout>
<Appointment
post={async input => {
// console.log(input);
await updateAppointment(fetch)(
Object.assign({ id: apptId, resourceName }, input),
);
return { updatedAppointment: true };
}}
queryPastAppointments={queryPastAppointments(fetch)}
pastAppointments={pastAppointments}
cancelAppointmentsCount={cancelAppointmentsCount}
services={services}
contacts={contacts}
name={name}
mobile={mobile}
apptId={apptId}
startDate={startDate.toDate()}
startTime={startDate.toDate()}
serviceIds={serviceIds}
discount={discount}
additional={additional}
totalAmount={totalAmount}
duration={duration}
resourceName={resourceName}
postText={'Update Appointment'}
successMessage={'Appointment Updated'}
errorMessage={'Appointment Creation Failed'}
showLoading={show(store)}
hideLoading={hide(store)}
deposit={deposit}
toBeInformed={false}
cancelButton={
<CancelSection
label="Customer Cancel"
showLoading={show(store)}
hideLoading={hide(store)}
post={async () => {
// console.log(input);
await cancelAppointment(fetch)({ apptId });
return { canceledAppointment: true };
}}
/>
}
{...this.props}
/>
</Layout>
),
};
}
export default action;
|
public/components/tehtPage/tabsComponents/templates/KuvatVideotTemplate.js | City-of-Vantaa-SmartLab/kupela | import React from 'react';
import MainContent from './MainContent';
const KuvatVideotTemplate = (props) => (
<div className="kuvatvideot-grid">
<MainContent component={props.component} className="kuvatvideotcontent" {...props} />
</div>
);
export default KuvatVideotTemplate; |
src/components/frankulator/Conductors.js | SashaKoro/reactulator | import React from 'react';
import styled from 'styled-components';
const LeftConductor = styled.span`
background-color: gray;
float: left;
color: red;
float: left;
height: 40px;
width: 40px;
margin-left: -47px;
margin-top: -55px;
-webkit-border-radius: 5px 0 0 5px;
`;
const RightConductor = styled(LeftConductor)`
margin-left: 393px;
-webkit-border-radius: 0 5px 5px 0;
boxShadow: 5px 8px 3px black;
`;
const Conductors = () => {
return (
<div>
<LeftConductor />
<RightConductor />
</div>
);
};
export default Conductors;
|
src/hello.js | GRT/react-example | import React from 'react';
export default React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
}); |
pollard/components/Setlist.js | spencerliechty/pollard | import React, { Component } from 'react';
import SearchSong from './SearchSong';
import AddedSongs from './AddedSongs';
import NewPlaylistInstructions from './NewPlaylistInstructions.js';
export default class Setlist extends Component {
render() {
const {
songs,
} = this.props;
return (
<div className="row">
<ul className="list-group">
<SearchSong/>
{
(songs.size === 0) ?
<NewPlaylistInstructions /> :
''
}
<AddedSongs />
</ul>
</div>
);
}
}
|
static/src/components/RegisterView.js | PMA-2020/pma-translation-hub | /* eslint camelcase: 0, no-underscore-dangle: 0 */
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import Paper from 'material-ui/Paper';
import * as actionCreators from '../actions/auth';
import { validateEmail } from '../utils/misc';
function mapStateToProps(state) {
return {
isRegistering: state.auth.isRegistering,
registerStatusText: state.auth.registerStatusText,
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(actionCreators, dispatch);
}
const style = {
marginTop: 50,
paddingBottom: 50,
paddingTop: 25,
width: '100%',
textAlign: 'center',
display: 'inline-block',
};
@connect(mapStateToProps, mapDispatchToProps)
export default class RegisterView extends React.Component {
constructor(props) {
super(props);
const redirectRoute = '/login';
this.state = {
email: '',
password: '',
email_error_text: null,
password_error_text: null,
redirectTo: redirectRoute,
disabled: true,
};
}
isDisabled() {
let email_is_valid = false;
let password_is_valid = false;
if (this.state.email === '') {
this.setState({
email_error_text: null,
});
} else if (validateEmail(this.state.email)) {
email_is_valid = true;
this.setState({
email_error_text: null,
});
} else {
this.setState({
email_error_text: 'Sorry, this is not a valid email',
});
}
if (this.state.password === '' || !this.state.password) {
this.setState({
password_error_text: null,
});
} else if (this.state.password.length >= 6) {
password_is_valid = true;
this.setState({
password_error_text: null,
});
} else {
this.setState({
password_error_text: 'Your password must be at least 6 characters',
});
}
if (email_is_valid && password_is_valid) {
this.setState({
disabled: false,
});
}
}
changeValue(e, type) {
const value = e.target.value;
const next_state = {};
next_state[type] = value;
this.setState(next_state, () => {
this.isDisabled();
});
}
_handleKeyPress(e) {
if (e.key === 'Enter') {
if (!this.state.disabled) {
this.login(e);
}
}
}
login(e) {
e.preventDefault();
this.props.registerUser(this.state.email, this.state.password, this.state.redirectTo);
}
render() {
return (
<div className="col-md-6 col-md-offset-3" onKeyPress={(e) => this._handleKeyPress(e)}>
<Paper style={style}>
<div className="text-center">
<h2>Register to view protected content!</h2>
{
this.props.registerStatusText &&
<div className="alert alert-info">
{this.props.registerStatusText}
</div>
}
<div className="col-md-12">
<TextField
hintText="Email"
floatingLabelText="Email"
type="email"
errorText={this.state.email_error_text}
onChange={(e) => this.changeValue(e, 'email')}
/>
</div>
<div className="col-md-12">
<TextField
hintText="Password"
floatingLabelText="Password"
type="password"
errorText={this.state.password_error_text}
onChange={(e) => this.changeValue(e, 'password')}
/>
</div>
<RaisedButton
disabled={this.state.disabled}
style={{ marginTop: 50 }}
label="Submit"
onClick={(e) => this.login(e)}
/>
</div>
</Paper>
</div>
);
}
}
RegisterView.propTypes = {
registerUser: React.PropTypes.func,
registerStatusText: React.PropTypes.string,
};
|
src/svg-icons/content/add-circle.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentAddCircle = (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 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/>
</SvgIcon>
);
ContentAddCircle = pure(ContentAddCircle);
ContentAddCircle.displayName = 'ContentAddCircle';
export default ContentAddCircle;
|
src/layouts/index.js | jameslutley/jameslutley.com | import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import Img from 'gatsby-image'
import Helmet from 'react-helmet'
import { injectGlobal } from 'emotion'
import { ThemeProvider } from 'emotion-theming'
import { normalize } from 'polished'
import t from 'tachyons-js'
import { theme } from '../utils/theme'
import Container from '../components/atoms/container'
import Header from '../components/organisms/header'
import Footer from '../components/organisms/footer'
injectGlobal`
${normalize()}
html {
${t.overflow_y_scroll};
}
html,
body,
div,
article,
section,
main,
footer,
header,
form,
fieldset,
legend,
pre,
code,
a,
h1,h2,h3,h4,h5,h6,
p,
ul,
ol,
li,
dl,
dt,
dd,
textarea,
table,
td,
th,
tr,
input[type="email"],
input[type="number"],
input[type="password"],
input[type="tel"],
input[type="text"],
input[type="url"] {
box-sizing: border-box;
}
*,
*::before,
*::after {
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font-family: ${theme.serif};
font-size: ${theme.fontSize6}
line-height: ${theme.lineHeightCopy};
font-kerning: normal;
font-feature-settings: 'kern', 'liga', 'clig', 'calt';
color: ${theme.darkGray};
}
img {
${t.mw_100};
${t.v_mid};
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin-top: ${theme.spacingMediumLarge};
margin-bottom: ${theme.spacingMediumLarge};
font-family: ${theme.sansSerifDisplay};
text-rendering: optimizeLegibility;
letter-spacing: -0.02rem;
color: ${theme.nearBlack};
${theme.Desktop} {
margin-top: ${theme.spacingExtraLarge};
margin-bottom: ${theme.spacingMediumLarge};
}
}
h1 {
font-size: ${theme.fontSize2};
line-height: calc(64 / 48);
${theme.Desktop} {
font-size: ${theme.fontSize1};
line-height: calc(80 / 64);
}
}
h2 {
font-size: ${theme.fontSize3};
line-height: calc(48 / 30);
}
h3 {
font-size: ${theme.fontSize4};
line-height: calc(32 / 24);
}
h4 {
font-size: ${theme.fontSize5};
line-height: calc(24 / 20);
}
h5 {
font-size: ${theme.fontSize6};
line-height: calc(24 / 18);
}
h6 {
font-size: ${theme.fontSize7};
line-height: calc(24 / 16);
}
a {
color: inherit;
text-decoration: underline;
text-decoration-color: ${theme.lightBlue};
text-decoration-skip: ink;
transition: color 0.15s ease-in, text-decoration-color 0.15s ease-in;
&:hover,
&:focus {
color: ${theme.nearBlack};
text-decoration-color: ${theme.blue};
}
}
`
const DefaultLayout = ({ children, data }) =>
<div>
<Helmet
title="James Lutley — Designer, Developer, Maker"
meta={[
{ name: 'description', content: 'Sample' },
{ name: 'keywords', content: 'sample, something' },
]}
link={[
{ rel: 'stylesheet', href: 'https://use.typekit.net/uon4clj.css' }
]}
/>
<ThemeProvider theme={theme}>
<div>
<Header siteTitle={data.site.siteMetadata.title} />
{children()}
<Footer avatar={data.file.childImageSharp.resolutions} siteTitle={data.site.siteMetadata.title} />
</div>
</ThemeProvider>
</div>
export const query = graphql`
query LayoutQuery {
site {
siteMetadata {
title
}
}
file(relativePath: { eq: "images/jameslutley.jpg"}) {
childImageSharp {
resolutions(width: 72, height: 72) {
...GatsbyImageSharpResolutions
}
}
}
},
`
DefaultLayout.propTypes = {
children: PropTypes.oneOfType([
PropTypes.func,
PropTypes.object,
]).isRequired,
data: PropTypes.object.isRequired,
}
export default DefaultLayout
|
src/app/components/loadingSpinner.js | nazar/sound-charts-react-spa | import React from 'react';
export default React.createClass({
render() {
return (
<div className="loading-spinner">
<i className="fa fa-cog fa-spin"></i>
</div>
);
}
}); |
packages/react-error-overlay/src/components/Collapsible.js | viankakrisna/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* @flow */
import React, { Component } from 'react';
import { black } from '../styles';
import type { Element as ReactElement } from 'react';
const _collapsibleStyle = {
color: black,
cursor: 'pointer',
border: 'none',
display: 'block',
width: '100%',
textAlign: 'left',
background: '#fff',
fontFamily: 'Consolas, Menlo, monospace',
fontSize: '1em',
padding: '0px',
lineHeight: '1.5',
};
const collapsibleCollapsedStyle = {
..._collapsibleStyle,
marginBottom: '1.5em',
};
const collapsibleExpandedStyle = {
..._collapsibleStyle,
marginBottom: '0.6em',
};
type Props = {|
children: ReactElement<any>[],
|};
type State = {|
collapsed: boolean,
|};
class Collapsible extends Component<Props, State> {
state = {
collapsed: true,
};
toggleCollapsed = () => {
this.setState(state => ({
collapsed: !state.collapsed,
}));
};
render() {
const count = this.props.children.length;
const collapsed = this.state.collapsed;
return (
<div>
<button
onClick={this.toggleCollapsed}
style={
collapsed ? collapsibleCollapsedStyle : collapsibleExpandedStyle
}
>
{(collapsed ? '▶' : '▼') +
` ${count} stack frames were ` +
(collapsed ? 'collapsed.' : 'expanded.')}
</button>
<div style={{ display: collapsed ? 'none' : 'block' }}>
{this.props.children}
<button
onClick={this.toggleCollapsed}
style={collapsibleExpandedStyle}
>
{`▲ ${count} stack frames were expanded.`}
</button>
</div>
</div>
);
}
}
export default Collapsible;
|
src/components/BreadcrumbItem/BreadcrumbItem.js | wfp/ui | import PropTypes from 'prop-types';
import React from 'react';
import classnames from 'classnames';
import Link from '../Link';
import settings from '../../globals/js/settings';
const { prefix } = settings;
const newChild = (children, disableLink, href) => {
if (disableLink === true) {
return <span>{children}</span>;
} else if (typeof children === 'string' && !(href === undefined)) {
return <Link href={href}>{children}</Link>;
} else {
return React.cloneElement(React.Children.only(children), {
className: `${prefix}--link`,
});
}
};
const BreadcrumbItem = ({
children,
className,
disableLink,
href,
...other
}) => {
const classNames = classnames(`${prefix}--breadcrumb-item`, className);
return (
<div className={classNames} {...other}>
{newChild(children, disableLink, href)}
</div>
);
};
BreadcrumbItem.propTypes = {
/**
* The children elements, usually a link
*/
children: PropTypes.node,
/**
* Specify an optional className to be added to the `BreadcrumbItem` Icon
*/
className: PropTypes.string,
/**
* Specify an link for the `BreadcrumbItem`
*/
href: PropTypes.string,
/**
* Specify `BreadcrumbItem` to be interactive/enabled or non-interactive/disabled
*/
disableLink: PropTypes.bool,
};
export default BreadcrumbItem;
|
MadWare.Hathor.FrontEnd/src/js/components/server/PlayerControls.js | zvizdo/MadWare.Hathor | import React from 'react'
class PlayerControls extends React.Component {
onNewPlaylist(e) {
this.props.onNewPlaylistClick();
}
onCleanPlayed(e) {
this.props.onCleanPlayedClick();
}
onRepeatSettingChange (e) {
this.props.onRepeatChange(e.target.checked);
}
onShuffleSettingChange (e) {
this.props.onShuffleChange(e.target.checked);
}
render() {
return (
<div class="row">
<div class="col-md-12">
<div class="bs-component">
<div class="jumbotron">
<a class="btn btn-primary btn-lg" onClick={this.onNewPlaylist.bind(this)} >
NEW PLAYLIST
<div class="ripple-container"></div></a>
<a class="btn btn-primary btn-lg" onClick={this.onCleanPlayed.bind(this)} >
CLEAN PLAYED
<div class="ripple-container"></div></a>
<div class="checkbox">
<label>
<input type="checkbox"
checked={this.props.repeat}
onChange={this.onRepeatSettingChange.bind(this)} />
<span style={{paddingLeft: "10px"}}>repeat</span>
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox"
checked={this.props.shuffle}
onChange={this.onShuffleSettingChange.bind(this)} />
<span style={{paddingLeft: "10px"}}>shuffle</span>
</label>
</div>
</div>
</div>
</div>
</div>
);
}
}
PlayerControls.propTypes = {
repeat: React.PropTypes.bool.isRequired,
repeat: React.PropTypes.bool.isRequired,
onNewPlaylistClick: React.PropTypes.func,
onCleanPlayedClick: React.PropTypes.func,
onRepeatChange: React.PropTypes.func,
onShuffleChange: React.PropTypes.func
}
PlayerControls.defaultProps = {
onNewPlaylistClick: () => {},
onCleanPlayedClick: () => {},
onRepeatChange: () => {},
onShuffleChange: () => {}
}
export default PlayerControls;
|
app/admin/dashboard/HomeNavigate.js | ecellju/internship-portal | import React from 'react';
import PropTypes from 'prop-types';
import { Route } from 'react-router-dom';
import HomeTab from './HomeTab';
import PostView from '../post/PostView';
const HomeNavigate = ({ match }) => (
<div>
<Route exact path={match.url} component={HomeTab} />
<Route path={`${match.url}/:id`} component={PostView} />
</div>
);
HomeNavigate.propTypes = {
match: PropTypes.shape({
url: PropTypes.string.isRequired,
}).isRequired,
};
export default HomeNavigate;
|
admin/client/App/screens/Item/components/EditForm.js | w01fgang/keystone | import React from 'react';
import moment from 'moment';
import assign from 'object-assign';
import {
Form,
FormField,
FormInput,
Grid,
ResponsiveText,
} from '../../../elemental';
// import { css, StyleSheet } from 'aphrodite/no-important';
import { Fields } from 'FieldTypes';
import { fade } from '../../../../utils/color';
import theme from '../../../../theme';
import { Button, LoadingButton } from '../../../elemental';
import AlertMessages from '../../../shared/AlertMessages';
import ConfirmationDialog from './../../../shared/ConfirmationDialog';
import FormHeading from './FormHeading';
import AltText from './AltText';
import FooterBar from './FooterBar';
import InvalidFieldType from '../../../shared/InvalidFieldType';
import { deleteItem } from '../actions';
import { upcase } from '../../../../utils/string';
function getNameFromData (data) {
if (typeof data === 'object') {
if (typeof data.first === 'string' && typeof data.last === 'string') {
return data.first + ' ' + data.last;
} else if (data.id) {
return data.id;
}
}
return data;
}
function smoothScrollTop () {
if (document.body.scrollTop || document.documentElement.scrollTop) {
window.scrollBy(0, -50);
var timeOut = setTimeout(smoothScrollTop, 20);
} else {
clearTimeout(timeOut);
}
}
var EditForm = React.createClass({
displayName: 'EditForm',
propTypes: {
data: React.PropTypes.object,
list: React.PropTypes.object,
},
getInitialState () {
return {
values: assign({}, this.props.data.fields),
confirmationDialog: null,
loading: false,
lastValues: null, // used for resetting
focusFirstField: !this.props.list.nameField && !this.props.list.nameFieldIsFormHeader,
};
},
componentDidMount () {
this.__isMounted = true;
},
componentWillUnmount () {
this.__isMounted = false;
},
getFieldProps (field) {
const props = assign({}, field);
const alerts = this.state.alerts;
// Display validation errors inline
if (alerts && alerts.error && alerts.error.error === 'validation errors') {
if (alerts.error.detail[field.path]) {
// NOTE: This won't work yet, as ElementalUI doesn't allow
// passed in isValid, only invalidates via internal state.
// PR to fix that: https://github.com/elementalui/elemental/pull/149
props.isValid = false;
}
}
props.value = this.state.values[field.path];
props.values = this.state.values;
props.onChange = this.handleChange;
props.mode = 'edit';
return props;
},
handleChange (event) {
const values = assign({}, this.state.values);
values[event.path] = event.value;
this.setState({ values });
},
toggleDeleteDialog () {
this.setState({
deleteDialogIsOpen: !this.state.deleteDialogIsOpen,
});
},
toggleResetDialog () {
this.setState({
resetDialogIsOpen: !this.state.resetDialogIsOpen,
});
},
handleReset () {
this.setState({
values: assign({}, this.state.lastValues || this.props.data.fields),
resetDialogIsOpen: false,
});
},
handleDelete () {
const { data } = this.props;
this.props.dispatch(deleteItem(data.id, this.props.router));
},
handleKeyFocus () {
const input = this.refs.keyOrIdInput;
input.select();
},
removeConfirmationDialog () {
this.setState({
confirmationDialog: null,
});
},
updateItem () {
const { data, list } = this.props;
const editForm = this.refs.editForm;
const formData = new FormData(editForm);
// Show loading indicator
this.setState({
loading: true,
});
list.updateItem(data.id, formData, (err, data) => {
smoothScrollTop();
if (err) {
this.setState({
alerts: {
error: err,
},
loading: false,
});
} else {
// Success, display success flash messages, replace values
// TODO: Update key value
this.setState({
alerts: {
success: {
success: 'Your changes have been saved successfully',
},
},
lastValues: this.state.values,
values: data.fields,
loading: false,
});
}
});
},
renderKeyOrId () {
var className = 'EditForm__key-or-id';
var list = this.props.list;
if (list.nameField && list.autokey && this.props.data[list.autokey.path]) {
return (
<div className={className}>
<AltText
modified="ID:"
normal={`${upcase(list.autokey.path)}: `}
title="Press <alt> to reveal the ID"
className="EditForm__key-or-id__label" />
<AltText
modified={<input ref="keyOrIdInput" onFocus={this.handleKeyFocus} value={this.props.data.id} className="EditForm__key-or-id__input" readOnly />}
normal={<input ref="keyOrIdInput" onFocus={this.handleKeyFocus} value={this.props.data[list.autokey.path]} className="EditForm__key-or-id__input" readOnly />}
title="Press <alt> to reveal the ID"
className="EditForm__key-or-id__field" />
</div>
);
} else if (list.autokey && this.props.data[list.autokey.path]) {
return (
<div className={className}>
<span className="EditForm__key-or-id__label">{list.autokey.path}: </span>
<div className="EditForm__key-or-id__field">
<input ref="keyOrIdInput" onFocus={this.handleKeyFocus} value={this.props.data[list.autokey.path]} className="EditForm__key-or-id__input" readOnly />
</div>
</div>
);
} else if (list.nameField) {
return (
<div className={className}>
<span className="EditForm__key-or-id__label">ID: </span>
<div className="EditForm__key-or-id__field">
<input ref="keyOrIdInput" onFocus={this.handleKeyFocus} value={this.props.data.id} className="EditForm__key-or-id__input" readOnly />
</div>
</div>
);
}
},
renderNameField () {
var nameField = this.props.list.nameField;
var nameFieldIsFormHeader = this.props.list.nameFieldIsFormHeader;
var wrapNameField = field => (
<div className="EditForm__name-field">
{field}
</div>
);
if (nameFieldIsFormHeader) {
var nameFieldProps = this.getFieldProps(nameField);
nameFieldProps.label = null;
nameFieldProps.size = 'full';
nameFieldProps.autoFocus = true;
nameFieldProps.inputProps = {
className: 'item-name-field',
placeholder: nameField.label,
size: 'large',
};
return wrapNameField(
React.createElement(Fields[nameField.type], nameFieldProps)
);
} else {
return wrapNameField(
<h2>{this.props.data.name || '(no name)'}</h2>
);
}
},
renderFormElements () {
var headings = 0;
return this.props.list.uiElements.map((el, index) => {
// Don't render the name field if it is the header since it'll be rendered in BIG above
// the list. (see renderNameField method, this is the reverse check of the one it does)
if (
this.props.list.nameField
&& el.field === this.props.list.nameField.path
&& this.props.list.nameFieldIsFormHeader
) return;
if (el.type === 'heading') {
headings++;
el.options.values = this.state.values;
el.key = 'h-' + headings;
return React.createElement(FormHeading, el);
}
if (el.type === 'field') {
var field = this.props.list.fields[el.field];
var props = this.getFieldProps(field);
if (typeof Fields[field.type] !== 'function') {
return React.createElement(InvalidFieldType, { type: field.type, path: field.path, key: field.path });
}
props.key = field.path;
if (index === 0 && this.state.focusFirstField) {
props.autoFocus = true;
}
return React.createElement(Fields[field.type], props);
}
}, this);
},
renderFooterBar () {
const { loading } = this.state;
const loadingButtonText = loading ? 'Saving' : 'Save';
// Padding must be applied inline so the FooterBar can determine its
// innerHeight at runtime. Aphrodite's styling comes later...
return (
<FooterBar style={styles.footerbar}>
<div style={styles.footerbarInner}>
<LoadingButton
color="primary"
disabled={loading}
loading={loading}
onClick={this.updateItem}
data-button="update"
>
{loadingButtonText}
</LoadingButton>
<Button disabled={loading} onClick={this.toggleResetDialog} variant="link" color="cancel" data-button="reset">
<ResponsiveText
hiddenXS="reset changes"
visibleXS="reset"
/>
</Button>
{!this.props.list.nodelete && (
<Button disabled={loading} onClick={this.toggleDeleteDialog} variant="link" color="delete" style={styles.deleteButton} data-button="delete">
<ResponsiveText
hiddenXS={`delete ${this.props.list.singular.toLowerCase()}`}
visibleXS="delete"
/>
</Button>
)}
</div>
</FooterBar>
);
},
renderTrackingMeta () {
// TODO: These fields are visible now, so we don't want this. We may revisit
// it when we have more granular control over hiding fields in certain
// contexts, so I'm leaving this code here as a reference for now - JW
if (true) return null; // if (true) prevents unreachable code linter errpr
if (!this.props.list.tracking) return null;
var elements = [];
var data = {};
if (this.props.list.tracking.createdAt) {
data.createdAt = this.props.data.fields[this.props.list.tracking.createdAt];
if (data.createdAt) {
elements.push(
<FormField key="createdAt" label="Created on">
<FormInput noedit title={moment(data.createdAt).format('DD/MM/YYYY h:mm:ssa')}>{moment(data.createdAt).format('Do MMM YYYY')}</FormInput>
</FormField>
);
}
}
if (this.props.list.tracking.createdBy) {
data.createdBy = this.props.data.fields[this.props.list.tracking.createdBy];
if (data.createdBy && data.createdBy.name) {
let createdByName = getNameFromData(data.createdBy.name);
if (createdByName) {
elements.push(
<FormField key="createdBy" label="Created by">
<FormInput noedit>{data.createdBy.name.first} {data.createdBy.name.last}</FormInput>
</FormField>
);
}
}
}
if (this.props.list.tracking.updatedAt) {
data.updatedAt = this.props.data.fields[this.props.list.tracking.updatedAt];
if (data.updatedAt && (!data.createdAt || data.createdAt !== data.updatedAt)) {
elements.push(
<FormField key="updatedAt" label="Updated on">
<FormInput noedit title={moment(data.updatedAt).format('DD/MM/YYYY h:mm:ssa')}>{moment(data.updatedAt).format('Do MMM YYYY')}</FormInput>
</FormField>
);
}
}
if (this.props.list.tracking.updatedBy) {
data.updatedBy = this.props.data.fields[this.props.list.tracking.updatedBy];
if (data.updatedBy && data.updatedBy.name) {
let updatedByName = getNameFromData(data.updatedBy.name);
if (updatedByName) {
elements.push(
<FormField key="updatedBy" label="Updated by">
<FormInput noedit>{data.updatedBy.name.first} {data.updatedBy.name.last}</FormInput>
</FormField>
);
}
}
}
return Object.keys(elements).length ? (
<div className="EditForm__meta">
<h3 className="form-heading">Meta</h3>
{elements}
</div>
) : null;
},
render () {
return (
<form ref="editForm" className="EditForm-container">
{(this.state.alerts) ? <AlertMessages alerts={this.state.alerts} /> : null}
<Grid.Row>
<Grid.Col large="three-quarters">
<Form layout="horizontal" component="div">
{this.renderNameField()}
{this.renderKeyOrId()}
{this.renderFormElements()}
{this.renderTrackingMeta()}
</Form>
</Grid.Col>
<Grid.Col large="one-quarter"><span /></Grid.Col>
</Grid.Row>
{this.renderFooterBar()}
<ConfirmationDialog
confirmationLabel="Reset"
isOpen={this.state.resetDialogIsOpen}
onCancel={this.toggleResetDialog}
onConfirmation={this.handleReset}
>
<p>Reset your changes to <strong>{this.props.data.name}</strong>?</p>
</ConfirmationDialog>
<ConfirmationDialog
confirmationLabel="Delete"
isOpen={this.state.deleteDialogIsOpen}
onCancel={this.toggleDeleteDialog}
onConfirmation={this.handleDelete}
>
Are you sure you want to delete <strong>{this.props.data.name}?</strong>
<br />
<br />
This cannot be undone.
</ConfirmationDialog>
</form>
);
},
});
const styles = {
footerbar: {
backgroundColor: fade(theme.color.body, 93),
boxShadow: '0 -2px 0 rgba(0, 0, 0, 0.1)',
paddingBottom: 20,
paddingTop: 20,
zIndex: 99,
},
footerbarInner: {
height: theme.component.height, // FIXME aphrodite bug
},
deleteButton: {
float: 'right',
},
};
module.exports = EditForm;
|
node_modules/antd/es/breadcrumb/BreadcrumbItem.js | prodigalyijun/demo-by-antd | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
var __rest = this && this.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]];
}return t;
};
import React from 'react';
import PropTypes from 'prop-types';
var BreadcrumbItem = function (_React$Component) {
_inherits(BreadcrumbItem, _React$Component);
function BreadcrumbItem() {
_classCallCheck(this, BreadcrumbItem);
return _possibleConstructorReturn(this, (BreadcrumbItem.__proto__ || Object.getPrototypeOf(BreadcrumbItem)).apply(this, arguments));
}
_createClass(BreadcrumbItem, [{
key: 'render',
value: function render() {
var _a = this.props,
prefixCls = _a.prefixCls,
separator = _a.separator,
children = _a.children,
restProps = __rest(_a, ["prefixCls", "separator", "children"]);
var link = void 0;
if ('href' in this.props) {
link = React.createElement(
'a',
_extends({ className: prefixCls + '-link' }, restProps),
children
);
} else {
link = React.createElement(
'span',
_extends({ className: prefixCls + '-link' }, restProps),
children
);
}
if (children) {
return React.createElement(
'span',
null,
link,
React.createElement(
'span',
{ className: prefixCls + '-separator' },
separator
)
);
}
return null;
}
}]);
return BreadcrumbItem;
}(React.Component);
export default BreadcrumbItem;
BreadcrumbItem.__ANT_BREADCRUMB_ITEM = true;
BreadcrumbItem.defaultProps = {
prefixCls: 'ant-breadcrumb',
separator: '/'
};
BreadcrumbItem.propTypes = {
prefixCls: PropTypes.string,
separator: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
href: PropTypes.string
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.