path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
examples/components/Markdown.react.js | ericgio/r-d3 | import cx from 'classnames';
import marked from 'marked';
import React from 'react';
class Markdown extends React.Component {
componentWillMount() {
marked.setOptions({
gfm: true,
tables: true,
breaks: true,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: false,
highlight(code) {
/* eslint-disable max-len */
const hljs = require('highlight.js/lib/highlight.js');
hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript'));
hljs.registerLanguage('xml', require('highlight.js/lib/languages/xml'));
return hljs.highlightAuto(code).value;
/* eslint-enable max-len */
},
});
}
render() {
const html = marked.parse(this.props.children);
return (
<div
className={cx('markdown-body', this.props.className)}
dangerouslySetInnerHTML={{__html: html}}
/>
);
}
}
export default Markdown;
|
src/svg-icons/editor/format-list-numbered.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatListNumbered = (props) => (
<SvgIcon {...props}>
<path d="M2 17h2v.5H3v1h1v.5H2v1h3v-4H2v1zm1-9h1V4H2v1h1v3zm-1 3h1.8L2 13.1v.9h3v-1H3.2L5 10.9V10H2v1zm5-6v2h14V5H7zm0 14h14v-2H7v2zm0-6h14v-2H7v2z"/>
</SvgIcon>
);
EditorFormatListNumbered = pure(EditorFormatListNumbered);
EditorFormatListNumbered.displayName = 'EditorFormatListNumbered';
EditorFormatListNumbered.muiName = 'SvgIcon';
export default EditorFormatListNumbered;
|
src/components/Modules/withModules.js | folio-org/stripes-core | import React from 'react';
import hoistNonReactStatics from 'hoist-non-react-statics';
import { ModulesContext } from '../../ModulesContext';
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
export default function withModules(WrappedComponent) {
class WithModules extends React.Component {
render() {
return (
<ModulesContext.Consumer>
{modules => <WrappedComponent {...this.props} modules={modules} /> }
</ModulesContext.Consumer>
);
}
}
WithModules.displayName = `WithModules(${getDisplayName(WrappedComponent)})`;
return hoistNonReactStatics(WithModules, WrappedComponent);
}
|
docs/src/app/components/pages/components/IconButton/ExampleSize.js | rhaedes/material-ui | import React from 'react';
import IconButton from 'material-ui/IconButton';
import ActionHome from 'material-ui/svg-icons/action/home';
const styles = {
smallIcon: {
width: 36,
height: 36,
},
mediumIcon: {
width: 48,
height: 48,
},
largeIcon: {
width: 60,
height: 60,
},
small: {
width: 72,
height: 72,
padding: 16,
},
medium: {
width: 96,
height: 96,
padding: 24,
},
large: {
width: 120,
height: 120,
padding: 30,
},
};
const IconButtonExampleSize = () => (
<div>
<IconButton>
<ActionHome />
</IconButton>
<IconButton
iconStyle={styles.smallIcon}
style={styles.small}
>
<ActionHome />
</IconButton>
<IconButton
iconStyle={styles.mediumIcon}
style={styles.medium}
>
<ActionHome />
</IconButton>
<IconButton
iconStyle={styles.largeIcon}
style={styles.large}
>
<ActionHome />
</IconButton>
</div>
);
export default IconButtonExampleSize;
|
src/main/app/scripts/views/Note.js | ondrejhudek/hudy-app | import React from 'react'
import { connect } from 'react-redux'
import { Card, CardText } from 'material-ui'
import AddNote from '../containers/note/AddNote'
import Notes from '../components/note/Notes'
import { fetchNotes } from '../actions/notes'
let fetched = false
const style = {
headerCard: {
margin: '0 20% 1em'
},
headerCardText: {
padding: '3px 17px'
}
}
class NoteView extends React.Component {
constructor(props) {
super(props)
this.state = {
dispatch: props.dispatch
}
}
componentWillMount() {
if (!fetched) {
this.state.dispatch(fetchNotes())
fetched = true
}
}
render() {
return (
<div className="view-note">
<h2>Notes</h2>
<Card style={style.headerCard}>
<CardText children={<AddNote />} style={style.headerCardText}/>
</Card>
<Notes/>
</div>
)
}
}
NoteView = connect()(NoteView)
export default NoteView
|
src/components/common/card/Card.js | seyade/loggent | import React from 'react';
import moment from 'moment';
import { truncate } from '../../../helpers/stringy';
import './Card.scss';
import '../../../assets/svg/table-lamp-simple.svg';
const Card = ({ title, agent, agency, phone, email, description, createdAt, index, id, deleteCard }) => {
let momentCreatedAt = moment(createdAt),
formattedTime = momentCreatedAt.format('LT').toLowerCase(),
formattedDate = momentCreatedAt.format('DD.MM.YY');
return (
<article className="card role">
<span className="role__index">{index + 1}</span>
<h2 className="role__title">
<span className="role__term-label">Role</span>
<span className="role__title-main">{truncate(title, 20)}</span>
</h2>
<section className="role__section role__agent-info">
<span className="role__term-label">AGENT</span>
<span className="role__agent">{agent} </span> | <span className="role__agency"> {truncate(agency, 12)}</span>
</section>
<section className="role__section role__call-info">
{/* <span className="fa fa-phone card__icon"></span> */}
<span className="role__term-label">CALL DETAILS</span>
<p className="role__call-phone"><a href={'tel:' + phone.replace(/\s+/gi, '')}>{phone}</a></p>
<p className="role__call-time">
<strong>Date</strong> {formattedDate} @ {formattedTime}
</p>
</section>
<section className="role__section role__email">
{/* <span className="fa fa-at card__icon"></span> */}
<span className="role__term-label">EMAIL</span>
<p className="role__email-text">{truncate(email, 25)}</p>
</section>
<section className="buttons clearfix">
<div className="hero-gradient">
<div id="wave">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1170 193">
<path d="M1175 131.2c0 0-81-89.4-224.3-103.4S713 72 665 97c-86 46-148 63-271 7C221.7 25.5 56 104.5-4 197.4 -4 58.7-3.3 0.3-3.3 0.3L1175 0V131.2z"></path>
</svg>
</div>
</div>
<button className="buttons__btn buttons--save">view more</button>
<button className="buttons__btn buttons--close" onClick={deleteCard(id)}> delete</button>
</section>
</article>
);
};
export default Card;
|
components/Notification.js | CoffeeApp/clientSide | import React from 'react'
import Confirm from './Confirm'
import ShowOrderStatus from './ShowOrderStatus'
const Notification = ({ order, confirmOrder, cancelOrder }) => (
<div className="notification">
<div className="module">
{ order.status === 'In process' ?
<ShowOrderStatus order={order} /> :
<Confirm order={order} confirmOrder={confirmOrder} cancelOrder={cancelOrder} />
}
</div>
</div>
)
export default Notification
|
app/App.js | halversondm/react-tutorial | import React from 'react';
import styles from './App.css';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {test: 'foo'};
}
render() {
return (
<div className={styles.app}>
bar
</div>
);
}
}
|
imports/client/components/Project/ProjectInfoList.js | evancorl/portfolio | import React from 'react';
class ProjectInfoList extends React.Component {
shouldComponentUpdate() {
return false;
}
render() {
const { subtitle, list } = this.props;
return (
<div className="project-info-list-container">
<h3 className="project-subtitle">{subtitle}:</h3>
<ul className="project-info-list">
{list.map((item, i) => (
<li key={i} className="project-info-list-item">{item}</li>
))}
</ul>
</div>
);
}
}
ProjectInfoList.propTypes = {
subtitle: React.PropTypes.string.isRequired,
list: React.PropTypes.array.isRequired,
};
export default ProjectInfoList;
|
project-templates/reactfiber/externals/react-fiber/fixtures/ssr/src/components/App.js | ItsAsbreuk/itsa-cli | import React, { Component } from 'react';
import Chrome from './Chrome';
import Page from './Page';
export default class App extends Component {
render() {
return (
<Chrome title="Hello World" assets={this.props.assets}>
<div>
<h1>Hello World</h1>
<Page />
</div>
</Chrome>
);
}
}
|
public/src/js/main.js | Robertmw/imagistral | import React from 'react';
import { render } from 'react-dom';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { Router, Route, IndexRoute } from 'react-router';
import Editor from './pages/editor';
import Wall from './pages/wall';
import style from '../css/style.less';
render(
<Router history={createBrowserHistory()}>
<Route
component={Editor}
path="/"
/>
<Route
component={Wall}
path="wall"
/>
</Router>,
document.getElementById('app')
); |
src/svg-icons/av/volume-mute.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvVolumeMute = (props) => (
<SvgIcon {...props}>
<path d="M7 9v6h4l5 5V4l-5 5H7z"/>
</SvgIcon>
);
AvVolumeMute = pure(AvVolumeMute);
AvVolumeMute.displayName = 'AvVolumeMute';
AvVolumeMute.muiName = 'SvgIcon';
export default AvVolumeMute;
|
app/components/Filter/SubDropdowns/SubNight.js | Bullseyed/Bullseye | import React from 'react'
import { Input } from 'react-materialize'
import { connect } from 'react-redux'
import { addBType } from '../../../reducers/b-type-reducer'
const SubNight = (props) => {
const changeHandler = (event) => {
let value = event.target.value
let str = ''
let restStr = ''
if (value == 0) str = 'nightlife'
if (value == 1) str = 'beergardens'
if (value == 2) str = 'sportsbars'
if (value == 3) str = 'speakeasies'
if (value == 4) str = 'irish_pubs'
if (value == 5) str = 'hookah_bars'
if (value == 6) str = 'lounges'
if (value == 7) str = 'wine_bars'
if (value == 8) str = 'cocktailbars'
if (value == 9) str = 'champagne_bars'
if (value == 10) str = 'divebars'
props.addBType(str)
}
return (
<Input s={12} type='select' label="Nightlife Type" defaultValue='0' onChange={changeHandler}>
<option value='0' disabled='disabled'> Select Nightlife Type </option>
<option value='1'>Beer Garden</option>
<option value='2'>Sports Bar</option>
<option value='3'>Speakeasy</option>
<option value='4'>Irish Pub</option>
<option value='5'>Hookah</option>
<option value='6'>Lounge</option>
<option value='7'>Wine Bar</option>
<option value='8'>Cocktail Bar</option>
<option value='9'>Champagne Bar</option>
<option value='10'>Dive Bar</option>
</Input>
)
}
const mapStateToProps = storeState => ({ bType: storeState.bType })
const mapDispatchToProps = dispatch => ({ addBType: typeStr => dispatch(addBType(typeStr)) })
export default connect(mapStateToProps, mapDispatchToProps)(SubNight)
|
login/src/components/MainList.js | bobmacneal/react-native-firebase-auth | import React, { Component } from 'react';
import { Text } from 'react-native';
import { Card, CardSection } from './common';
class MainList extends Component {
render() {
return (
<Card>
<CardSection>
<Text>Item 1</Text>
</CardSection>
<CardSection>
<Text>Item 2</Text>
</CardSection>
<CardSection>
<Text>Item 2</Text>
</CardSection>
</Card>
);
}
}
export default MainList;
|
src/components/map/buildPolygons.js | kobotoolbox/kobomaps-orig | import React from 'react';
import calculateMinSpread from '../../util/calculateMinSpread';
import Area from './Area';
import {getStore} from '../../redux/redux-store';
export function buildPolygons(data) {
const areaValues = data.data ?? {};
const {min, spread} = calculateMinSpread(Object.keys(areaValues).map(key=> areaValues[key]));
const areas = getStore().getState().areas;
return Object.keys(areas).map(function (areaName, idx) {
const points = areas[areaName].points;
const value = areaValues[areaName];
return <Area
key={idx}
index={idx}
name={areaName}
points={points}
value={value}
min={min}
spread={spread}
/>;
//creates a list of the place names we've encountered
});
}
|
information/blendle-frontend-react-source/app/modules/stories/higher-order-components/includeStoryDetails.js | BramscoChill/BlendleParser | import React from 'react';
import { setStatic, wrapDisplayName } from 'recompose';
export default function includeStoryDetails(ComposedComponent) {
const enhance = setStatic(
'displayName',
wrapDisplayName(ComposedComponent, 'includeStoryDetails'),
);
return enhance(({ storyDetails, ...props }) => (
<div>
{storyDetails}
<ComposedComponent {...props} />
</div>
));
}
// WEBPACK FOOTER //
// ./src/js/app/modules/stories/higher-order-components/includeStoryDetails.js |
node_modules/react-bootstrap/es/TabPane.js | mohammed52/door-quote-automator | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import elementType from 'prop-types-extra/lib/elementType';
import warning from 'warning';
import { bsClass, getClassSet, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils';
import createChainedFunction from './utils/createChainedFunction';
import Fade from './Fade';
var propTypes = {
/**
* Uniquely identify the `<TabPane>` among its siblings.
*/
eventKey: PropTypes.any,
/**
* Use animation when showing or hiding `<TabPane>`s. Use `false` to disable,
* `true` to enable the default `<Fade>` animation or any `<Transition>`
* component.
*/
animation: PropTypes.oneOfType([PropTypes.bool, elementType]),
/** @private **/
id: PropTypes.string,
/** @private **/
'aria-labelledby': PropTypes.string,
/**
* If not explicitly specified and rendered in the context of a
* `<TabContent>`, the `bsClass` of the `<TabContent>` suffixed by `-pane`.
* If otherwise not explicitly specified, `tab-pane`.
*/
bsClass: PropTypes.string,
/**
* Transition onEnter callback when animation is not `false`
*/
onEnter: PropTypes.func,
/**
* Transition onEntering callback when animation is not `false`
*/
onEntering: PropTypes.func,
/**
* Transition onEntered callback when animation is not `false`
*/
onEntered: PropTypes.func,
/**
* Transition onExit callback when animation is not `false`
*/
onExit: PropTypes.func,
/**
* Transition onExiting callback when animation is not `false`
*/
onExiting: PropTypes.func,
/**
* Transition onExited callback when animation is not `false`
*/
onExited: PropTypes.func,
/**
* Wait until the first "enter" transition to mount the tab (add it to the DOM)
*/
mountOnEnter: PropTypes.bool,
/**
* Unmount the tab (remove it from the DOM) when it is no longer visible
*/
unmountOnExit: PropTypes.bool
};
var contextTypes = {
$bs_tabContainer: PropTypes.shape({
getTabId: PropTypes.func,
getPaneId: PropTypes.func
}),
$bs_tabContent: PropTypes.shape({
bsClass: PropTypes.string,
animation: PropTypes.oneOfType([PropTypes.bool, elementType]),
activeKey: PropTypes.any,
mountOnEnter: PropTypes.bool,
unmountOnExit: PropTypes.bool,
onPaneEnter: PropTypes.func.isRequired,
onPaneExited: PropTypes.func.isRequired,
exiting: PropTypes.bool.isRequired
})
};
/**
* We override the `<TabContainer>` context so `<Nav>`s in `<TabPane>`s don't
* conflict with the top level one.
*/
var childContextTypes = {
$bs_tabContainer: PropTypes.oneOf([null])
};
var TabPane = function (_React$Component) {
_inherits(TabPane, _React$Component);
function TabPane(props, context) {
_classCallCheck(this, TabPane);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleEnter = _this.handleEnter.bind(_this);
_this.handleExited = _this.handleExited.bind(_this);
_this['in'] = false;
return _this;
}
TabPane.prototype.getChildContext = function getChildContext() {
return {
$bs_tabContainer: null
};
};
TabPane.prototype.componentDidMount = function componentDidMount() {
if (this.shouldBeIn()) {
// In lieu of the action event firing.
this.handleEnter();
}
};
TabPane.prototype.componentDidUpdate = function componentDidUpdate() {
if (this['in']) {
if (!this.shouldBeIn()) {
// We shouldn't be active any more. Notify the parent.
this.handleExited();
}
} else if (this.shouldBeIn()) {
// We are the active child. Notify the parent.
this.handleEnter();
}
};
TabPane.prototype.componentWillUnmount = function componentWillUnmount() {
if (this['in']) {
// In lieu of the action event firing.
this.handleExited();
}
};
TabPane.prototype.handleEnter = function handleEnter() {
var tabContent = this.context.$bs_tabContent;
if (!tabContent) {
return;
}
this['in'] = tabContent.onPaneEnter(this, this.props.eventKey);
};
TabPane.prototype.handleExited = function handleExited() {
var tabContent = this.context.$bs_tabContent;
if (!tabContent) {
return;
}
tabContent.onPaneExited(this);
this['in'] = false;
};
TabPane.prototype.getAnimation = function getAnimation() {
if (this.props.animation != null) {
return this.props.animation;
}
var tabContent = this.context.$bs_tabContent;
return tabContent && tabContent.animation;
};
TabPane.prototype.isActive = function isActive() {
var tabContent = this.context.$bs_tabContent;
var activeKey = tabContent && tabContent.activeKey;
return this.props.eventKey === activeKey;
};
TabPane.prototype.shouldBeIn = function shouldBeIn() {
return this.getAnimation() && this.isActive();
};
TabPane.prototype.render = function render() {
var _props = this.props,
eventKey = _props.eventKey,
className = _props.className,
onEnter = _props.onEnter,
onEntering = _props.onEntering,
onEntered = _props.onEntered,
onExit = _props.onExit,
onExiting = _props.onExiting,
onExited = _props.onExited,
propsMountOnEnter = _props.mountOnEnter,
propsUnmountOnExit = _props.unmountOnExit,
props = _objectWithoutProperties(_props, ['eventKey', 'className', 'onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'onExited', 'mountOnEnter', 'unmountOnExit']);
var _context = this.context,
tabContent = _context.$bs_tabContent,
tabContainer = _context.$bs_tabContainer;
var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['animation']),
bsProps = _splitBsPropsAndOmit[0],
elementProps = _splitBsPropsAndOmit[1];
var active = this.isActive();
var animation = this.getAnimation();
var mountOnEnter = propsMountOnEnter != null ? propsMountOnEnter : tabContent && tabContent.mountOnEnter;
var unmountOnExit = propsUnmountOnExit != null ? propsUnmountOnExit : tabContent && tabContent.unmountOnExit;
if (!active && !animation && unmountOnExit) {
return null;
}
var Transition = animation === true ? Fade : animation || null;
if (tabContent) {
bsProps.bsClass = prefix(tabContent, 'pane');
}
var classes = _extends({}, getClassSet(bsProps), {
active: active
});
if (tabContainer) {
process.env.NODE_ENV !== 'production' ? warning(!elementProps.id && !elementProps['aria-labelledby'], 'In the context of a `<TabContainer>`, `<TabPanes>` are given ' + 'generated `id` and `aria-labelledby` attributes for the sake of ' + 'proper component accessibility. Any provided ones will be ignored. ' + 'To control these attributes directly provide a `generateChildId` ' + 'prop to the parent `<TabContainer>`.') : void 0;
elementProps.id = tabContainer.getPaneId(eventKey);
elementProps['aria-labelledby'] = tabContainer.getTabId(eventKey);
}
var pane = React.createElement('div', _extends({}, elementProps, {
role: 'tabpanel',
'aria-hidden': !active,
className: classNames(className, classes)
}));
if (Transition) {
var exiting = tabContent && tabContent.exiting;
return React.createElement(
Transition,
{
'in': active && !exiting,
onEnter: createChainedFunction(this.handleEnter, onEnter),
onEntering: onEntering,
onEntered: onEntered,
onExit: onExit,
onExiting: onExiting,
onExited: createChainedFunction(this.handleExited, onExited),
mountOnEnter: mountOnEnter,
unmountOnExit: unmountOnExit
},
pane
);
}
return pane;
};
return TabPane;
}(React.Component);
TabPane.propTypes = propTypes;
TabPane.contextTypes = contextTypes;
TabPane.childContextTypes = childContextTypes;
export default bsClass('tab-pane', TabPane); |
client/index.js | WillHearn/apoc | import React from 'react';
import routes from '../shared/routes';
import DevTools from '../shared/container/DevTools/DevTools';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import { configureStore } from '../shared/redux/store/configureStore';
const store = configureStore(window.__INITIAL_STATE__);
const history = browserHistory;
const dest = document.getElementById('root');
render((
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>
), dest);
if (process.env.NODE_ENV !== 'production') {
window.React = React; // enable debugger
if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) {
console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); // eslint-disable-line
}
}
if (process.env.CLIENT) {
render(
<Provider store={store} key="provider">
<div>
<Router history={history} routes={routes} />
<DevTools />
</div>
</Provider>,
dest
);
}
|
src/client/pages/home-page.js | nefa/Leeact | import React from 'react';
import products from '../components/transaction/transaction-products';
import AdapterController from '../components/transaction/transaction-adapters';
import {ModalComponent} from '../components/modal/modal-component';
import {ModalActions} from '../stores/modal-store';
import ProductModal from '../components/modal/product-modal';
//TODO: should remove this or make it relevant
class Home extends React.Component {
selectItem(item) {
ModalActions.show(ProductModal, item);
}
renderProducts() {
return products.map( item => {
return (
<li key={item.id}>
<a onClick={ evt => this.selectItem(item)} >
{item.description} --+-- {item.price}
</a>
</li>
)
})
}
render() {
return (
<div>
<div id="home" className="mw8 center phm phl-ns">
<h1 className="ptxl tc ttu pbn normal mega-ns f1-ns">halcyon - calm, peaceful</h1>
{this.renderProducts()}
</div>
<ModalComponent />
</div>
);
}
}
export default Home;
|
js/components/auth/logIn/index.js | amandamfielding/Coffee-Shop-Mobile | import React, { Component } from 'react';
import { Image, Alert } from 'react-native';
import { Font } from 'exponent';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import { Container, Text, Content, InputGroup, Input, Button, Icon, View } from 'native-base';
import * as firebase from "firebase";
import { firebaseApp } from "../authentication";
import Exponent from 'exponent';
import { setUser } from '../../../actions/user';
import styles from './styles';
const {
replaceAt,
pushRoute
} = actions;
const background = require('../../../../images/beans2.jpg');
class Login extends Component {
static propTypes = {
popRoute: React.PropTypes.func,
setUser: React.PropTypes.func,
replaceAt: React.PropTypes.func,
pushRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
constructor(props) {
super(props);
this.state = ({
email: "",
password: "",
result: "",
FBloggedIn: false,
fontLoaded: false
});
}
async FBlogIn() {
const { type, token } = await Exponent.Facebook.logInWithReadPermissionsAsync(
'1831068953774364', {
permissions: ['public_profile', 'email', 'user_friends'],
});
if (type === 'success') {
const credential = firebase.auth.FacebookAuthProvider.credential(token);
firebase.auth().signInWithCredential(credential).then(() => {this.setState({FBloggedIn: true})})
.catch((error) => {
alert("error");
});
const response = await fetch(`https://graph.facebook.com/me?fields=gender,name,locale,age_range,first_name,picture.width(200).height(200),link,cover&access_token=${token}`);
const user = await response.json();
this.props.setUser(user)
Alert.alert(
'Logged in!',
`Hi ${user.name}!`,
);
}
}
pushToRoute(route) {
this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key);
}
replaceRoute(route) {
this.props.replaceAt('logIn', { key: route }, this.props.navigation.key);
}
componentDidUpdate() {
firebaseApp.auth().onAuthStateChanged(user => {
if (user) {
this.replaceRoute('home');
}
});
}
logIn() {
const { email, password } = this.state;
firebaseApp.auth().signInWithEmailAndPassword(email, password)
.catch(error => {
this.setState({ result: error.message });
});
}
async componentDidMount() {
await Font.loadAsync({
'veneer': require('../../../../assets/fonts/veneer.ttf'),
});
this.setState({ fontLoaded: true });
}
render() {
if (!this.state.fontLoaded) {return null;}
const fb = this.state.fontLoaded ? "Sign in with Facebook" : null;
const login = this.state.fontLoaded ? "Login" : null;
const signup = this.state.fontLoaded ? "Sign Up" : null;
const forgot = this.state.fontLoaded ? "Forgot Password?" : null;
return (
<Image source={require('../../../../images/beans2.jpg')} style={styles.container}>
<View style={styles.logoContainer}>
<Image
style={styles.logoImage}
source={{uri:'https://firebasestorage.googleapis.com/v0/b/coffee-shop-mobile.appspot.com/o/logofritzwhite.png?alt=media&token=1c9f80e9-53ca-42cd-82b9-e6ca72c25d6f'}} />
</View>
<View style={styles.buttonContainer}>
<Button onPress={() => {this.FBlogIn()}} style={styles.FBbutton}>
<View style={styles.FBflex}>
<Text style={styles.FBtext}>{fb}</Text>
<FontAwesome name="facebook-f" size={24} color="#ffffff" />
</View>
</Button>
<Text style={styles.feedback}>{this.state.result}</Text>
<InputGroup style={styles.input}>
<Icon name="ios-person" style={{ color:"white" }} />
<Input
style={styles.inputValue}
placeholder="EMAIL"
onChangeText={(text) => {this.setState({ email: text })}} />
</InputGroup>
<InputGroup style={styles.input}>
<Icon name="ios-unlock-outline" style={{ color:"white" }}/>
<Input
style={styles.inputValue}
placeholder="PASSWORD"
secureTextEntry
onChangeText={(text) => {this.setState({ password: text })}}
/>
</InputGroup>
<Button style={styles.loginBtn} onPress={() => {this.logIn()}}>
<Text style={styles.btnText}>{login}</Text>
</Button>
</View>
<View style={styles.linkContainer}>
<Button transparent
onPress={() => {this.pushToRoute('signUp');}}>
<Text style={styles.links}>{signup}</Text>
</Button>
<Button transparent
onPress={() => {this.pushToRoute('forgotPassword');}}>
<Text style={styles.links}>{forgot}</Text>
</Button>
</View>
</Image>
);
}
}
function bindActions(dispatch) {
return {
replaceAt: (routeKey, route, key) => dispatch(replaceAt(routeKey, route, key)),
pushRoute: (route, key) => dispatch(pushRoute(route, key)),
setUser: token => dispatch(setUser(token)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
});
export default connect(mapStateToProps, bindActions)(Login);
|
src/team/index.js | marchisbogdan/licenta-front | import React from 'react';
import s from './style.css';
import pageConfig from '../pageProps.json';
import SignUp from '../../components/SignUp';
import LobbyLayout from '../../components/LobbyLayout';
import history from "../../src/history";
import {ensureSessionExists,getSessionToken} from "../../core/sessionManager.js";
import TeamSegment from '../../components/TeamSegment';
import LobbyFooter from '../../components/LobbyLayout/LobbyFooter.js';
class Team extends React.Component{
constructor(props){
super(props);
this.state = {
title: pageConfig.title,
operator:pageConfig.operator,
operatorLogoUrl:pageConfig.operatorLogoURL,
isLoggedIn: false
};
}
componentWillMount() {
document.title = pageConfig.title;
if(getSessionToken()){
this.setState({isLoggedIn: true});
}else{
history.push("./sign-in");
}
// ensureSessionExists().then( () => {
// this.setState({isLoggedIn: true});
// console.log('Session exists!');
// }).catch( () => {
// console.log('Session doesn\'t exists!');
// history.push("./sign-in");
// })
}
render() {
if(this.state.isLoggedIn){
return (
<LobbyLayout className={s.content}>
<TeamSegment pageAttr={this.state}/>
<LobbyFooter/>
</LobbyLayout>
);
}else{
return null;
}
}
}
export default Team; |
src/components/theme-legacy/form/instructions/target-national.js | MoveOnOrg/mop-frontend | import React from 'react'
const TargetNational = () => (
<div>
<h4>Targeting the White House or Congress</h4>
<p>If you choose <strong>The entire U.S. House</strong>, then your petition signers will be asked to sign a petition addressed to their individual representative in the U.S. House of Representatives.</p>
<p>If you choose <strong>The entire U.S. Senate</strong>, then your petition signers will be asked to sign a petition addressed to their state’s U.S. Senators.</p><p>If you choose <strong>President Donald Trump</strong>, your petition signatures will be addressed to President Donald Trump.</p>
<p>If your petition should be addressed to <strong>a specific legislator</strong>, type his or her name in the text area. Be sure to check the spelling and use the individual’s proper title.</p>
</div>
)
export default TargetNational
|
src/mongostick/frontend/src/screens/ReplicaMembers.js | RockingRolli/mongostick | import React from 'react'
import { Card, Col, Row } from 'antd'
import ReplicaMember from '../components/ReplicaMember'
import { connect } from 'react-redux'
import DataRow from '../components/DataRow'
class ReplicaMembers extends React.Component {
render() {
const { replica_set } = this.props
const { members, conf } = replica_set
return (
<div>
<Row gutter={16}>
<Col span={6}>
<Card title={<strong>{conf.set}</strong>} className='text-center' bordered={false} style={{ border: '1px rgba(0, 0, 0, 0.65) solid' }}>
<Row>
<DataRow title='Replica Set' text={conf.set} />
<DataRow title='Last Update' text={conf.date} />
<DataRow title='Members' text={members.length} />
<DataRow title='Heartbeat Interval' text={members.length} />
<DataRow title='Heartbeat Timeout' text={`${conf.heartbeatTimeoutSecs}s`} />
<DataRow title='Chaining Allowed' text={conf.chainingAllowed.toString()} />
<DataRow title='Election Timeout' text={`${conf.electionTimeoutMillis}ms`} />
<DataRow title='CatchUp Timeout' text={`${conf.catchUpTimeoutMillis}ms`} />
</Row>
</Card>
</Col>
<Col span={18}>
<Row gutter={16}>
{members.map((member, index) => (
<Col span={8} key={index}>
<ReplicaMember member={member} />
</Col>
))}
</Row>
</Col>
</Row>
</div>
)
}
}
const mapStateToProps = store => {
return {
replica_set: store.replica_set
}
}
export default connect(mapStateToProps)(ReplicaMembers)
|
apps/marketplace/components/BuyerATM/BuyerATMAboutStage.js | AusDTO/dto-digitalmarketplace-frontend | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Form } from 'react-redux-form'
import Textfield from 'shared/form/Textfield'
import Textarea from 'shared/form/Textarea'
import CheckboxDetailsField from 'shared/form/CheckboxDetailsField'
import formProps from 'shared/form/formPropsSelector'
import { required } from 'marketplace/components/validators'
import AUheadings from '@gov.au/headings/lib/js/react.js'
import ErrorAlert from 'marketplace/components/Alerts/ErrorAlert'
import locations from 'marketplace/components/BuyerBriefFlow/Locations'
import styles from './BuyerATMAboutStage.scss'
const BuyerATMAboutStage = props => (
<Form
model={props.model}
validators={{
'': {
requiredTitle: formValues => required(formValues.title),
requiredOrg: formValues => required(formValues.organisation),
requiredSummary: formValues => required(formValues.summary),
atLeastOneLocation: formValues => formValues.location && formValues.location.length > 0
}
}}
onSubmit={props.onSubmit}
onSubmitFailed={props.onSubmitFailed}
validateOn="submit"
>
<AUheadings level="1" size="xl">
About
</AUheadings>
<ErrorAlert
model={props.model}
messages={{
requiredTitle: 'Enter the title for your opportunity',
requiredOrg: 'Enter the name of your organisation',
requiredSummary: 'Enter a summary of your opportunity',
requiredWorkingArrangements: 'Enter the working arrangements for your opportunity',
atLeastOneLocation: 'You must select at least one location'
}}
/>
<Textfield
model={`${props.model}.title`}
label="Title"
description="Describe the outcome you need."
placeholder="For example, 'Website redesign and development'."
name="title"
id="title"
htmlFor="title"
defaultValue={props[props.model].title}
maxLength={100}
validators={{
required
}}
/>
<Textfield
model={`${props.model}.organisation`}
label="Department, agency or organisation"
description="Who is the work for? Please write in full, including the state if necessary."
placeholder="For example, Digital Transformation Agency instead of DTA."
name="organisation"
id="organisation"
htmlFor="organisation"
defaultValue={props[props.model].organisation}
maxLength={150}
validators={{
required
}}
/>
<Textarea
model={`${props.model}.summary`}
label="Summary of work to be done"
name="summary"
id="summary"
htmlFor="summary"
defaultValue={props[props.model].summary}
controlProps={{ limit: 200 }}
validators={{
required
}}
messages={{
limitWords: 'Your summary has exceeded the 200 word limit'
}}
/>
<AUheadings level="2" size="sm">
Where can the work be done?
</AUheadings>
<div className={styles.locations}>
{Object.keys(locations).map(key => (
<CheckboxDetailsField
key={key}
model={`${props.model}.location[]`}
id={`location_${key}`}
name={`location_${key}`}
label={locations[key]}
value={locations[key]}
detailsModel={props.model}
validators={{}}
messages={{}}
/>
))}
</div>
{props.formButtons}
</Form>
)
BuyerATMAboutStage.defaultProps = {
onSubmit: () => {},
onSubmitFailed: () => {}
}
BuyerATMAboutStage.propTypes = {
model: PropTypes.string.isRequired,
formButtons: PropTypes.node.isRequired,
onSubmit: PropTypes.func,
onSubmitFailed: PropTypes.func
}
const mapStateToProps = (state, props) => ({
...formProps(state, props.model)
})
export default connect(mapStateToProps)(BuyerATMAboutStage)
|
src/components/ContextEditor.js | jimf/intl-live | import React from 'react';
import PropTypes from 'prop-types';
const handleContextChange = (f, x) => e => f({ [x]: e.target.value });
const inputTypeMap = {
numberFormat: 'number',
pluralFormat: 'number',
dateFormat: 'date',
timeFormat: 'time',
};
const ContextEditor = ({
context,
setContextValue,
variables
}) => (
<div>
{variables.map(([name, type]) => (
<label key={name}>
<span className="variable-label">
{name} <span className="variable-label__type">{inputTypeMap[type] || 'text'}</span>
</span>
<input
type={inputTypeMap[type] || 'text'}
value={context[name] || ''}
onChange={handleContextChange(setContextValue, name)}
/>
</label>
))}
</div>
);
ContextEditor.propTypes = {
context: PropTypes.object.isRequired,
setContextValue: PropTypes.func.isRequired,
variables: PropTypes.array.isRequired
};
export default ContextEditor;
|
src/pages/404.js | BeardedYeti/react-blog | import React from 'react'
const NotFoundPage = () => (
<div>
<h1>NOT FOUND</h1>
<p>You just hit a route that doesn't exist... the sadness.</p>
</div>
)
export default NotFoundPage
|
docs/src/app/components/pages/components/Snackbar/ExampleAction.js | xmityaz/material-ui | import React from 'react';
import Snackbar from 'material-ui/Snackbar';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
export default class SnackbarExampleSimple extends React.Component {
constructor(props) {
super(props);
this.state = {
autoHideDuration: 4000,
message: 'Event added to your calendar',
open: false,
};
}
handleTouchTap = () => {
this.setState({
open: true,
});
};
handleActionTouchTap = () => {
this.setState({
open: false,
});
alert('Event removed from your calendar.');
};
handleChangeDuration = (event) => {
const value = event.target.value;
this.setState({
autoHideDuration: value.length > 0 ? parseInt(value) : 0,
});
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
render() {
return (
<div>
<RaisedButton
onTouchTap={this.handleTouchTap}
label="Add to my calendar"
/>
<br />
<TextField
floatingLabelText="Auto Hide Duration in ms"
value={this.state.autoHideDuration}
onChange={this.handleChangeDuration}
/>
<Snackbar
open={this.state.open}
message={this.state.message}
action="undo"
autoHideDuration={this.state.autoHideDuration}
onActionTouchTap={this.handleActionTouchTap}
onRequestClose={this.handleRequestClose}
/>
</div>
);
}
}
|
frontend/src/Settings/Indexers/Indexers/EditIndexerModal.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React from 'react';
import Modal from 'Components/Modal/Modal';
import { sizes } from 'Helpers/Props';
import EditIndexerModalContentConnector from './EditIndexerModalContentConnector';
function EditIndexerModal({ isOpen, onModalClose, ...otherProps }) {
return (
<Modal
size={sizes.MEDIUM}
isOpen={isOpen}
onModalClose={onModalClose}
>
<EditIndexerModalContentConnector
{...otherProps}
onModalClose={onModalClose}
/>
</Modal>
);
}
EditIndexerModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
onModalClose: PropTypes.func.isRequired
};
export default EditIndexerModal;
|
src/shared/LinkButton.js | cityofasheville/simplicity2 | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router';
import Button from './Button';
const LinkButton = props => (
<Link to={{ pathname: props.pathname, query: props.query }}>
<Button {...props} />
</Link>
);
LinkButton.propTypes = {
pathname: PropTypes.string,
query: PropTypes.object, // eslint-disable-line
};
export default LinkButton;
|
index.android.js | uuom/aitribe | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import App from './app/app';
AppRegistry.registerComponent('aitribe', () => App);
|
docs/src/app/components/pages/components/Popover/Page.js | ichiohta/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import popoverReadmeText from './README';
import PopoverExampleSimple from './ExampleSimple';
import popoverExampleSimpleCode from '!raw!./ExampleSimple';
import PopoverExampleAnimation from './ExampleAnimation';
import popoverExampleAnimationCode from '!raw!./ExampleAnimation';
import PopoverExampleConfigurable from './ExampleConfigurable';
import popoverExampleConfigurableCode from '!raw!./ExampleConfigurable';
import popoverNoteText from './NOTE';
import popoverCode from '!raw!material-ui/Popover/Popover';
const descriptions = {
simple: 'A simple example showing a Popover containing a [Menu](/#/components/menu). ' +
'It can be also closed by clicking away from the Popover.',
animation: 'The default animation style is to animate around the origin. ' +
'An alternative animation can be applied using the `animation` property. ' +
'Currently one alternative animation is available, `popover-animation-from-top`, which animates vertically.',
configurable: 'Use the radio buttons to adjust the `anchorOrigin` and `targetOrigin` positions.',
};
const PopoverPage = () => (
<div>
<Title render={(previousTitle) => `Popover - ${previousTitle}`} />
<MarkdownElement text={popoverReadmeText} />
<CodeExample
title="Simple example"
description={descriptions.simple}
code={popoverExampleSimpleCode}
>
<PopoverExampleSimple />
</CodeExample>
<CodeExample
title="Animation"
description={descriptions.animation}
code={popoverExampleAnimationCode}
>
<PopoverExampleAnimation />
</CodeExample>
<CodeExample
title="Anchor playground"
description={descriptions.configurable}
code={popoverExampleConfigurableCode}
>
<PopoverExampleConfigurable />
</CodeExample>
<MarkdownElement text={popoverNoteText} />
<PropTypeDescription code={popoverCode} />
</div>
);
export default PopoverPage;
|
src/encoded/static/components/item-pages/SchemaView.js | hms-dbmi/fourfront | 'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import { ItemDetailList } from '@hms-dbmi-bgm/shared-portal-components/es/components/ui/ItemDetailList';
export default class SchemaView extends React.PureComponent {
static keyTitleDescriptionMap = {
'$schema' : {
title : "Schema Used",
description : "Type & draft of schema used."
},
'additionalProperties' : {
title : "Additional Properties"
},
'facets' : {
title : "Available Facets",
description : "Facets by which items of this type may be sorted by."
},
'id' : {
title : "ID"
},
'identifyingProperties' : {
title : "Identifying Properties",
description : "These must be unique."
},
'properties' : {
title : "Properties",
description : "Properties of this Item type."
},
'required' : {
title : "Required Properties",
description : "These may not be blank for an Item of this type."
}
};
static propTypes = {
'href' : PropTypes.string.isRequired,
'schemas' : PropTypes.any.isRequired
};
render() {
const { context, schemas } = this.props;
return (
<div className="view-item type-JSONSchema container" id="content">
{typeof context.description == "string" ? <p className="description">{context.description}</p> : null}
<ItemDetailList
context={context}
schemas={schemas}
keyTitleDescriptionMap={SchemaView.keyTitleDescriptionMap}
excludedKeys={['mixinProperties', 'title', 'type', 'description']}
stickyKeys={['properties', 'required', 'identifyingProperties', 'facets']}
/>
</div>
);
}
}
|
src/index.js | react-store/react-store.ml | require("babel-core/register");
require("babel-polyfill");
import 'rc-slider/assets/index.css';
import React from 'react'
import ReactDOM from 'react-dom'
import Routes from './routes'
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension'
import reducers from 'struct/reducers';
import { BrowserRouter } from 'react-router-dom'
let store = null
let initData = window.__PRELOADED_STATE__
if (initData)
store = createStore(reducers, initData, composeWithDevTools(applyMiddleware(thunk)))
else
store = createStore(reducers, composeWithDevTools(applyMiddleware(thunk)))
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<Routes />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
window.__PRELOADED_STATE__ = null
// |
src/ModalTitle.js | wjb12/react-bootstrap | import React from 'react';
import classNames from 'classnames';
class ModalTitle extends React.Component {
render() {
return (
<h4
{...this.props}
className={classNames(this.props.className, this.props.modalClassName)}>
{ this.props.children }
</h4>
);
}
}
ModalTitle.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: React.PropTypes.string
};
ModalTitle.defaultProps = {
modalClassName: 'modal-title'
};
export default ModalTitle;
|
client/index.js | mrblueblue/moodmusic | import React from 'react';
import { MoodMusic } from './components/App';
// window.addEventListener('touchstart', function() {
// var buffer = myContext.createBuffer(1, 1, 22050);
// var source = myContext.createBufferSource();
// source.buffer = buffer;
// source.connect(myContext.destination);
// source.noteOn(0);
// }, false);
// console.log(App)/
console.log(document.getElementById('content'))
React.render(
<MoodMusic />,
document.getElementById('content')
);
|
code/workspaces/web-app/src/components/common/typography/ResourceInfoSpan.js | NERC-CEH/datalab | import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles(theme => ({
root: {
fontWeight: 200,
letterSpacing: '0.05em',
color: theme.typography.body2.color,
textTransform: 'uppercase',
},
}));
const ResourceInfoSpan = ({ className = '', children }) => {
const classes = useStyles();
const totalClassName = `${className} ${classes.root}`;
return (
<span className={totalClassName}>{children}</span>
);
};
export default ResourceInfoSpan;
|
app/components/SortMenu.js | billyvg/pokemon-journal | import React, { Component } from 'react';
import {
inject,
observer,
} from 'mobx-react';
import autobind from 'autobind-decorator';
import IconButton from 'material-ui/IconButton';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import SortIcon from 'material-ui/svg-icons/content/sort';
import ScheduleIcon from 'material-ui/svg-icons/action/schedule';
import AlphaIcon from 'material-ui/svg-icons/av/sort-by-alpha';
import TextIcon from './TextIcon';
export type Props = {
authStore: Object;
iconColor: string;
};
@inject('authStore')
@autobind
@observer
export default class SortMenu extends Component {
props: Props;
handleChangeSort(e, child) {
const {
authStore,
} = this.props;
authStore.sort = child.props.value;
}
render() {
const {
authStore,
iconColor,
} = this.props;
const sortOptions = {
recent: {
icon: <ScheduleIcon />,
label: 'Recent',
},
id: {
icon: <TextIcon title="#" />,
label: 'Number',
},
name: {
icon: <AlphaIcon />,
label: 'Name',
},
cp: {
icon: <TextIcon title="CP" />,
label: 'Combat Power',
},
iv: {
icon: <TextIcon title="IV" />,
label: 'IV',
},
};
if (authStore.journalVisible) {
return (
<IconMenu
iconButtonElement={
<IconButton
iconStyle={{ color: iconColor }}
>
{sortOptions[authStore.sort].icon || <SortIcon />}
</IconButton>
}
onItemTouchTap={this.handleChangeSort}
targetOrigin={{ horizontal: 'right', vertical: 'top' }}
anchorOrigin={{ horizontal: 'right', vertical: 'top' }}
autoWidth
>
{Object.keys(sortOptions).map((key) => {
const {
label,
icon,
} = sortOptions[key];
return (
<MenuItem
key={key}
value={key}
primaryText={label}
rightIcon={icon}
/>
);
})}
</IconMenu>
);
}
return null;
}
}
|
src/components/Schedule.js | w1nston/re-conf | import React, { Component } from 'react';
import SwipeableView from 'react-swipeable-views';
import styled from 'styled-components';
import Day from './Day';
export const Title = styled.h1`
font-family: 'Love Ya Like A Sister', 'Arial', 'sans-serif';
font-size: 34px;
`;
export default class Schedule extends Component {
constructor(props) {
super(props);
this.days = props.schedule ? Object.keys(props.schedule) : [];
this.state = {
title: this.days[0],
};
}
changeTitle = newIndex =>
this.setState(() => ({ title: this.days[newIndex] }));
render() {
return (
<section>
<Title>May {this.state.title}</Title>
<SwipeableView onChangeIndex={this.changeTitle}>
{this.days.map(day => (
<Day key={day} items={this.props.schedule[day]} />
))}
</SwipeableView>
</section>
);
}
}
|
pootle/static/js/admin/app.js | JohnnyKing94/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import 'imports?Backbone=>require("backbone")!backbone-move';
import $ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import { q } from 'utils/dom';
import AdminController from './components/AdminController';
import User from './components/User';
import Language from './components/Language';
import Project from './components/Project';
import AdminRouter from './AdminRouter';
window.PTL = window.PTL || {};
const itemTypes = {
user: User,
language: Language,
project: Project,
};
PTL.userAdmin = {
init() {
$(document).ready(() => {
const processResults = (data) => {
const results = {
results: $.map(data.items.results, (result) => {
const item = {
id: result.id,
text: result.text,
};
return item;
}),
};
results.pagination = { more: data.items.more_results };
return results;
};
$('.js-s2-new-members').on(
's2-process-data', (evt, data) => PTL.s2.processData(data));
$('.js-s2-new-members').on(
's2-process-results', (evt, results) => processResults(results));
$('.js-s2-new-members').on(
's2-template-result', (evt, result) => PTL.s2.templateResult(result));
});
},
};
PTL.admin = {
init(opts) {
if (!itemTypes.hasOwnProperty(opts.itemType)) {
throw new Error('Invalid `itemType`.');
}
ReactDOM.render(
<AdminController
adminModule={itemTypes[opts.itemType]}
appRoot={opts.appRoot}
formChoices={opts.formChoices || {}}
router={new AdminRouter()}
/>,
q('.js-admin-app')
);
},
};
|
index.ios.js | jindallae/ReactNativeInit | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class jindallae extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!!!!!!!!!!!!!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js. This app is version 0.0.3.
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('jindallae', () => jindallae);
|
src/main.js | foglerek/yn-mafia | import React from 'react'
import ReactDOM from 'react-dom'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { useRouterHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import createStore from './store/createStore';
import AppContainer from './containers/AppContainer'
import io from 'socket.io-client';
import { injectReducer } from './store/reducers'
import AppReducer from './AppReducer';
let host = process.env.HOST || 'localhost',
port = process.env.PORT || 3000
//TODO See how to change the server regarding the Heroku ENV
const socket = io(`http://${host}:${port}`);
// ========================================================
// Browser History Setup
// ========================================================
const browserHistory = useRouterHistory(createBrowserHistory)({
basename: __BASENAME__
})
// ========================================================
// Store and History Instantiation
// ========================================================
// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the routerKey "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
const initialState = {};
const store = createStore(initialState, browserHistory, socket);
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: (state) => state.router
})
history.listen(location => console.log(location.pathname) );
injectReducer(store, {key: 'AppReducer', reducer: AppReducer });
socket.on('state', (state) => {
console.log('Got a state');
store.dispatch({type: 'SET_STATE', state});
});
// ========================================================
// Developer Tools Setup
// ========================================================
if (__DEBUG__) {
if (window.devToolsExtension) {
window.devToolsExtension.open()
}
}
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const routes = require('./routes/index').default(store)
ReactDOM.render(
<AppContainer
store={store}
history={history}
routes={routes}
/>,
MOUNT_NODE
)
}
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
// Wrap render in try/catch
render = () => {
try {
renderApp()
} catch (error) {
renderError(error)
}
}
// Setup hot module replacement
module.hot.accept('./routes/index', () => {
setTimeout(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
})
}
}
// ========================================================
// Go!
// ========================================================
render()
|
examples/ui-web-samples/react/src/ChatView.js | layerhq/layer-js-sampleapps | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { LayerProvider } from 'layer-react';
import Messenger from './containers/Messenger';
import ActiveConversation from './containers/ActiveConversation';
import DefaultPanel from './components/DefaultPanel';
import { IndexRoute, Route } from 'react-router';
import { ReduxRouter } from 'redux-router';
export default class ChatView extends Component {
constructor(props) {
super(props);
}
render() {
return (
<LayerProvider client={this.props.client}>
<Provider store={this.props.store}>
<ReduxRouter>
<Route path='/' component={Messenger}>
<IndexRoute component={DefaultPanel}/>
<Route path='/conversations/:conversationId' component={ActiveConversation}/>
</Route>
</ReduxRouter>
</Provider>
</LayerProvider>
)
}
}
|
app/containers/root.dev.js | fc-io/react-tape-redux | import React from 'react'
import {Router} from 'react-router/es6'
import {Provider} from 'react-redux'
import routes from '../routes'
import DevTools from '../dev_tools'
export default ({store, history}) =>
<Provider store={store}>
<div>
<Router history={history} routes={routes} />
<DevTools />
</div>
</Provider>
|
src/components/common/NoResults.js | TalentedEurope/te-app | import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import COMMON_STYLES from '../../styles/common';
export const NoResults = (props) => {
const { text } = props;
return (
<View style={styles.container}>
<Icon name="frown-o" style={styles.icon} />
<Text style={styles.text}>{text}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
icon: {
fontSize: 60,
color: COMMON_STYLES.SEMI_DARK_GRAY,
marginBottom: 20,
},
text: {
fontSize: 14,
color: COMMON_STYLES.DARK_GRAY,
paddingHorizontal: 40,
textAlign: 'center',
fontWeight: '500',
},
});
|
docs/app/Examples/collections/Table/Variations/TableExampleStackable.js | koenvg/Semantic-UI-React | import React from 'react'
import { Table } from 'semantic-ui-react'
const TableExampleStackable = () => {
return (
<Table stackable>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Status</Table.HeaderCell>
<Table.HeaderCell textAlign='right'>Notes</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>John</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell textAlign='right'>None</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jamie</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell textAlign='right'>Requires call</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jill</Table.Cell>
<Table.Cell>Denied</Table.Cell>
<Table.Cell textAlign='right'>None</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
)
}
export default TableExampleStackable
|
src/components/SearchBar.js | mangal49/HORECA | import React from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';
import IconButton from 'material-ui/IconButton';
import TextField from 'material-ui/TextField';
import Star from 'material-ui/svg-icons/toggle/star';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
import Search from 'material-ui/svg-icons/action/search';
const styles = {
container: {
paddingTop: 0,
width: '100%',
textAlign: 'center',
zIndex: 300,
//marginTop: '-14px',
//backgroundColor: 'white',
},
TextField: {
width: '90%',
padding: 0,
margin: 0,
//backgroundColor: '#FFF'
},
textPadding: {
paddingLeft: '35px',
// marginTop: 0,
},
IconButtonLeft: {
marginLeft: '-35px'
},
StarBorder: {
cursor: 'pointer',
color: 'gold',
},
Star: {
cursor: 'pointer',
color: 'gold',
},
Search: {
marginRight: '-30px',
marginTop: '20px',
}
};
class SearchBar extends React.Component {
constructor(props) {
super(props);
}
changeFavorite = () => {
this.props.updateSearchFavorite(!this.props.searchFavorite);
}
updateSearchText = (e) => {
this.props.updateSearchText(e.target.value);
}
render() {
let icon = null;
if (this.props.searchFavorite) {
icon = <Star
style={styles.Star}
color={"gold"}
/>
} else {
icon = <StarBorder
style={styles.StarBorder}
//hoverColor={"gold"}
/>
}
let displayFavorite = '';
if (!this.props.searchShowFavorite) displayFavorite = 'none';
return (
<div style={styles.container}>
<Search style={styles.Search} />
<TextField
hintText="สินค้า"
floatingLabelText="ค้นหา"
style={styles.TextField}
hintStyle={styles.textPadding}
floatingLabelStyle={styles.textPadding}
inputStyle={{
...styles.textPadding,
}}
defaultValue={this.props.searchText}
onKeyUp={(e) => { this.updateSearchText(e) }}
/>
<IconButton
style={{ ...styles.IconButtonLeft, display: displayFavorite }}
onTouchTap={() => { this.changeFavorite() }}
>
{icon}
</IconButton>
</div>
);
}
}
function mapStateToProps(state) {
return {
width: state.navLeftMenu.width,
height: state.navLeftMenu.height,
searchText: state.search.text,
searchFavorite: state.search.favorite,
}
}
SearchBar.defaultProps = {
searchShowFavorite: false,
};
export default connect(mapStateToProps, actions)(SearchBar); |
ee/client/omnichannel/monitors/MonitorsTable.js | VoiSmart/Rocket.Chat | import React from 'react';
import FilterByText from '../../../../client/components/FilterByText';
import GenericTable from '../../../../client/components/GenericTable';
import { useTranslation } from '../../../../client/contexts/TranslationContext';
import { useResizeInlineBreakpoint } from '../../../../client/hooks/useResizeInlineBreakpoint';
import MonitorsRow from './MonitorsRow';
function MonitorsTable({
monitors,
totalMonitors,
params,
sort,
onHeaderClick,
onChangeParams,
onDelete,
}) {
const t = useTranslation();
const [ref, onMediumBreakpoint] = useResizeInlineBreakpoint([600], 200);
return (
<GenericTable
ref={ref}
header={
<>
<GenericTable.HeaderCell
key={'name'}
sort='name'
active={sort[0] === 'name'}
direction={sort[1]}
onClick={onHeaderClick}
>
{t('Name')}
</GenericTable.HeaderCell>
<GenericTable.HeaderCell>{t('Username')}</GenericTable.HeaderCell>
<GenericTable.HeaderCell>{t('Email')}</GenericTable.HeaderCell>
<GenericTable.HeaderCell width='x60'>{t('Remove')}</GenericTable.HeaderCell>
</>
}
results={monitors}
total={totalMonitors}
params={params}
setParams={onChangeParams}
renderFilter={({ onChange, ...props }) => <FilterByText onChange={onChange} {...props} />}
>
{(props) => (
<MonitorsRow key={props._id} medium={onMediumBreakpoint} onDelete={onDelete} {...props} />
)}
</GenericTable>
);
}
export default MonitorsTable;
|
React_Redux/blog/src/components/posts_index.js | awg3/LearnCodeImprove | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions/index';
// Link: A React component, which is an anchor tag.
import { Link } from 'react-router';
class PostsIndex extends Component {
// A Lifecycle method: automatically called by React when the component is going to be rendered by the DOM for the first time.
componentWillMount(){
// Fetching data from API
this.props.fetchPosts();
}
renderPosts(){
return this.props.posts.map((post) => {
return (
<Link to={`posts/${post.id}`} className="list-group-link">
<li className="list-group-item" key={post.id}>
<span>{post.title}</span>
<span className="pull-xs-right">{post.categories}</span>
</li>
</Link>
);
});
}
render() {
return (
<div>
<div className="row margin__top-bottom-30px">
<div className="col-xs-6">
<h3>Post List</h3>
</div>
<div className="col-xs-6">
<Link to="/posts/new" className="btn btn-primary pull-xs-right">
Add a Post
</Link>
</div>
</div>
<div>
<ul className="list-group">
<li className="list-group-item list-title">
<span className="pull-xs-left">Title</span>
<span className="pull-xs-right">Category</span>
</li>
{this.renderPosts()}
</ul>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts.all };
}
export default connect(mapStateToProps, {fetchPosts})(PostsIndex);
|
src/routes.js | edabot/ReduxFour | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/app';
import PostsIndex from './components/posts_index';
import PostsNew from './components/posts_new';
import PostShow from './components/post_show';
export default (
<Route path="/" component={App}>
<IndexRoute component={PostsIndex} />
<Route path="/posts/new" component={PostsNew} />
<Route path='/posts/:id' component={PostShow} />
</Route>
);
|
src/Tabs/test.js | kareem3d/react-swipeable-tabs | import Tabs from './index';
import React from 'react';
import { Slider, RaisedButton } from 'material-ui';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
const CubesIcon = props => (
<svg viewBox="0 0 40 40" {...props}>
<g><path d="m11.7 33.4l7-3.5v-5.7l-7 3v6.2z m-1.2-8.3l7.4-3.1-7.4-3.2-7.4 3.2z m19.8 8.3l7-3.5v-5.7l-7 3v6.2z m-1.1-8.3l7.3-3.1-7.3-3.2-7.4 3.2z m-8.2-5.3l7-3v-4.9l-7 3v4.9z m-1.2-6.9l8.1-3.5-8.1-3.4-8 3.5z m19.8 9.4v7.6q0 0.7-0.3 1.2t-0.9 0.9l-8.2 4.1q-0.5 0.2-1 0.2t-1.1-0.2l-8.1-4.1q-0.1 0-0.2-0.1 0 0.1-0.1 0.1l-8.2 4.1q-0.4 0.2-1 0.2t-1-0.2l-8.2-4.1q-0.6-0.3-1-0.9t-0.3-1.2v-7.6q0-0.7 0.4-1.2t1-0.9l7.9-3.4v-7.3q0-0.7 0.4-1.3t1.1-0.8l8.1-3.5q0.4-0.2 0.9-0.2t0.9 0.2l8.2 3.5q0.6 0.2 1 0.8t0.4 1.3v7.3l7.9 3.4q0.7 0.3 1.1 0.9t0.4 1.2z"/></g>
</svg>
);
const GithubIcon = props => (
<svg viewBox="0 0 40 40" {...props}>
<g><path d="m20.1 2.9q4.7 0 8.6 2.3t6.3 6.2 2.3 8.6q0 5.6-3.3 10.1t-8.4 6.2q-0.6 0.1-0.9-0.2t-0.3-0.7q0 0 0-1.7t0-3q0-2.1-1.2-3.1 1.3-0.2 2.3-0.4t2.1-0.9 1.8-1.5 1.2-2.3 0.5-3.4q0-2.7-1.8-4.6 0.8-2-0.2-4.5-0.6-0.2-1.8 0.2t-2 1l-0.9 0.5q-2-0.6-4.3-0.6t-4.2 0.6q-0.4-0.2-1-0.6t-1.9-0.8-1.9-0.3q-1 2.5-0.1 4.5-1.8 1.9-1.8 4.6 0 1.9 0.5 3.4t1.1 2.3 1.8 1.5 2.1 0.9 2.3 0.4q-0.9 0.8-1.1 2.3-0.4 0.2-1 0.3t-1.3 0.1-1.4-0.5-1.3-1.4q-0.4-0.7-1-1.1t-1.1-0.6l-0.5 0q-0.5 0-0.6 0.1t-0.1 0.2 0.2 0.3 0.2 0.3l0.2 0.1q0.5 0.2 1 0.9t0.7 1.1l0.2 0.5q0.3 0.9 1 1.4t1.5 0.7 1.5 0.1 1.3-0.1l0.5 0q0 0.8 0 1.9t0 1.2q0 0.5-0.3 0.7t-0.9 0.2q-5.2-1.7-8.4-6.2t-3.3-10.1q0-4.7 2.3-8.6t6.2-6.2 8.6-2.3z m-10.6 24.6q0.1-0.2-0.2-0.3-0.2-0.1-0.2 0.1-0.1 0.1 0.1 0.2 0.2 0.2 0.3 0z m0.7 0.7q0.1-0.1-0.1-0.3-0.2-0.2-0.3-0.1-0.2 0.1 0 0.4 0.3 0.2 0.4 0z m0.7 1q0.2-0.1 0-0.4-0.2-0.3-0.4-0.1-0.2 0.1 0 0.4t0.4 0.1z m0.9 1q0.2-0.2-0.1-0.4-0.3-0.3-0.4-0.1-0.2 0.2 0 0.4 0.3 0.3 0.5 0.1z m1.3 0.5q0-0.2-0.3-0.3-0.4-0.1-0.4 0.1t0.2 0.4q0.4 0.1 0.5-0.2z m1.4 0.1q0-0.2-0.4-0.2-0.4 0-0.4 0.2 0 0.3 0.4 0.3 0.4 0 0.4-0.3z m1.3-0.2q-0.1-0.2-0.4-0.2-0.4 0.1-0.3 0.4t0.4 0.1 0.3-0.3z"/></g>
</svg>
);
const maxStiffness = 300;
const maxResistanceCoefficenet = 1;
const maxDamping = 50;
const maxSafeMargin = 200;
const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const createRandomItems = (no) => {
const items = [];
for (var i = 1; i <= no; i++) {
items.push(<span>{Math.round(Math.random()) === 0 ? <GithubIcon /> : <CubesIcon />}Item {i}</span>)
}
return items;
}
export default class TabsTest extends React.Component {
componentWillMount() {
this.setState({
activeItemIndex: 2,
stiffness: 170,
resistanceCoeffiecent: 0.5,
damping: 26,
safeMargin: 60,
items: createRandomItems(14)
})
}
renderTabs() {
return (
<div style={{ maxWidth: '600px', margin: '0 auto' }}>
<Tabs
noFirstLeftPadding={false}
noLastRightPadding={false}
fitItems={false}
resistanceCoeffiecent={this.state.resistanceCoeffiecent}
stiffness={this.state.stiffness}
damping={this.state.damping}
safeMargin={this.state.safeMargin}
borderWidthRatio={1}
activeItemIndex={this.state.activeItemIndex}
onItemClick={(item, index) => this.setState({ activeItemIndex: index })}
items={this.state.items}
borderPosition="top"
borderThickness={2}
borderColor="#4dc4c0"
activeStyle={{
color: '#4dc4c0'
}}
/>
</div>
);
}
getToolsContainerStyle() {
return { justifyContent: 'space-around', display: 'flex' };
}
getToolStyle() {
return { background: '#EEE', padding: '20px 5px' };
}
renderGlobalTools() {
return (
<div style={this.getToolsContainerStyle()}>
<div style={this.getToolStyle()}>
<b style={{ fontSize: '0.8rem' }}>Stiffness</b><br />
<Slider
style={{height: 100}}
axis="y"
onChange={(e, value) => this.setState({ stiffness: value*maxStiffness })}
value={this.state.stiffness/maxStiffness} />
<br />
{this.state.stiffness.toFixed(1)}
</div>
<div style={this.getToolStyle()}>
<b style={{ fontSize: '0.8rem' }}>Damping</b><br />
<Slider
style={{height: 100}}
axis="y"
onChange={(e, value) => this.setState({ damping: value*maxDamping })}
value={this.state.damping/maxDamping} />
<br />
{this.state.damping.toFixed(1)}
</div>
</div>
);
}
renderSwipeTools() {
return (
<div style={this.getToolsContainerStyle()}>
<div style={this.getToolStyle()}>
<b style={{ fontSize: '0.8rem' }}>Resistance</b><br />
<Slider
style={{height: 100}}
axis="y"
onChange={(e, value) => this.setState({ resistanceCoeffiecent: value*maxResistanceCoefficenet })}
value={this.state.resistanceCoeffiecent/maxResistanceCoefficenet} />
<br />
{this.state.resistanceCoeffiecent.toFixed(3)}
</div>
<div style={this.getToolStyle()}>
<b style={{ fontSize: '0.8rem' }}>SafeMargin</b><br />
<Slider
style={{height: 100}}
axis="y"
onChange={(e, value) => this.setState({ safeMargin: value*maxSafeMargin })}
value={this.state.safeMargin/maxSafeMargin} />
<br />
{this.state.safeMargin.toFixed(1)}
</div>
</div>
);
}
changeItems = () => {
this.setState({
items: createRandomItems(10),
})
}
changeActiveItem3 = () => {
this.setState({
activeItemIndex: 3
})
}
renderDynamicTools() {
const style = { margin: 12 };
return (
<div>
<RaisedButton onClick={this.changeItems} label="Change items" style={style} />
<RaisedButton onClick={this.changeActiveItem3} label="Change active to the fourth item" style={style} />
</div>
);
}
renderTools() {
const titleStyle = { textAlign: 'center', backgroundColor: '#EEE', padding: 20 };
return (
<div>
<h1 style={titleStyle}>Dynamic?</h1>
{this.renderDynamicTools()}
<h1 style={titleStyle}>Animation values</h1>
{this.renderGlobalTools()}
<h1 style={titleStyle}>Swipe values</h1>
{this.renderSwipeTools()}
</div>
);
}
render() {
return (
<MuiThemeProvider>
<div>
{this.renderTabs()}
<br />
<br />
<br />
{this.renderTools()}
</div>
</MuiThemeProvider>
);
}
} |
src/components/Search/Search.js | caijinchun/hsweb-antd | import React from 'react'
import PropTypes from 'prop-types'
import ReactDOM from 'react-dom'
import styles from './Search.less'
import { Input, Select, Button, Icon } from 'antd'
class Search extends React.Component {
state = {
clearVisible: false,
selectValue: (this.props.select && this.props.selectProps) ? this.props.selectProps.defaultValue : '',
}
handleSearch = () => {
const data = {
keyword: ReactDOM.findDOMNode(this.refs.searchInput).value,
}
if (this.props.select) {
data.field = this.state.selectValue
}
if (this.props.onSearch) this.props.onSearch(data)
}
handleInputChange = e => {
this.setState({
...this.state,
clearVisible: e.target.value !== '',
})
}
handleSelectChange = value => {
this.setState({
...this.state,
selectValue: value,
})
}
handleClearInput = () => {
ReactDOM.findDOMNode(this.refs.searchInput).value = ''
this.setState({
clearVisible: false,
})
this.handleSearch()
}
render () {
const { size, select, selectOptions, selectProps, style, keyword } = this.props
const { clearVisible } = this.state
return (
<Input.Group compact size={size} className={styles.search} style={style}>
{select && <Select ref="searchSelect" onChange={this.handleSelectChange} size={size} {...selectProps}>
{selectOptions && selectOptions.map((item, key) => <Select.Option value={item.value} key={key}>{item.name || item.value}</Select.Option>)}
</Select>}
<Input ref="searchInput" size={size} onChange={this.handleInputChange} onPressEnter={this.handleSearch} defaultValue={keyword} />
<Button size={size} type="primary" onClick={this.handleSearch}>搜索</Button>
{clearVisible && <Icon type="cross" onClick={this.handleClearInput} />}
</Input.Group>
)
}
}
Search.propTypes = {
size: PropTypes.string,
select: PropTypes.bool,
selectProps: PropTypes.object,
onSearch: PropTypes.func,
selectOptions: PropTypes.array,
style: PropTypes.object,
keyword: PropTypes.string,
}
export default Search
|
blueprints/form/files/__root__/forms/__name__Form/__name__Form.js | cargo-transport/web-frontend | import React from 'react'
import { reduxForm } from 'redux-form'
export const fields = []
const validate = (values) => {
const errors = {}
return errors
}
type Props = {
handleSubmit: Function,
fields: Object,
}
export class <%= pascalEntityName %> extends React.Component {
props: Props;
defaultProps = {
fields: {},
}
render() {
const { fields, handleSubmit } = this.props
return (
<form onSubmit={handleSubmit}>
</form>
)
}
}
<%= pascalEntityName %> = reduxForm({
form: '<%= pascalEntityName %>',
fields,
validate
})(<%= pascalEntityName %>)
export default <%= pascalEntityName %>
|
packages/wix-style-react/src/MessageBox/docs/AlertExamples/Standard.js | wix/wix-style-react | /* eslint-disable react/prop-types */
import React from 'react';
import { MessageBoxFunctionalLayout } from 'wix-style-react';
export default () => (
<MessageBoxFunctionalLayout
title="Interruption Message"
confirmText="Action"
theme="blue"
dataHook="alert-standard"
>
This is a generic message. No harm done, but really needed to interrupt you.
</MessageBoxFunctionalLayout>
);
|
ui/src/views/nodes/UpdateNode.js | jcampanell-cablelabs/lora-app-server | import React, { Component } from 'react';
import NodeStore from "../../stores/NodeStore";
import SessionStore from "../../stores/SessionStore";
import NodeForm from "../../components/NodeForm";
import ApplicationStore from "../../stores/ApplicationStore";
class UpdateNode extends Component {
static contextTypes = {
router: React.PropTypes.object.isRequired
};
constructor() {
super();
this.state = {
application: {},
node: {},
isAdmin: false,
};
this.onSubmit = this.onSubmit.bind(this);
}
componentWillMount() {
NodeStore.getNode(this.props.params.applicationID, this.props.params.devEUI, (node) => {
this.setState({node: node});
});
ApplicationStore.getApplication(this.props.params.applicationID, (application) => {
this.setState({application: application});
});
this.setState({
isAdmin: (SessionStore.isAdmin() || SessionStore.isOrganizationAdmin(this.props.params.organizationID)),
});
SessionStore.on("change", () => {
this.setState({
isAdmin: (SessionStore.isAdmin() || SessionStore.isOrganizationAdmin(this.props.params.organizationID)),
});
});
}
onSubmit(node) {
node.applicationID = this.props.params.applicationID;
NodeStore.updateNode(this.props.params.applicationID, this.props.params.devEUI, node, (responseData) => {
this.context.router.push('/organizations/'+this.props.params.organizationID+'/applications/'+this.props.params.applicationID);
});
}
render() {
return(
<div>
<div className="panel panel-default">
<div className="panel-body">
<NodeForm applicationID={this.props.params.applicationID} node={this.state.node} onSubmit={this.onSubmit} disabled={!this.state.isAdmin} application={this.state.application} />
</div>
</div>
</div>
);
}
}
export default UpdateNode;
|
api/responses/renderRoute.js | joshgagnon/sailjs-webpack-base | "use strict"
import React from 'react'
import createLocation from 'history/lib/createLocation'
import {renderToString } from 'react-dom/server'
import routes from '../../assets/js/routes';
import configureStore from '../../assets/js/serverStore';
import { match } from 'redux-router/server';
import { Provider } from 'react-redux';
export default function(renderProps) {
let req = this.req;
let res = this.res;
//let location = createLocation(req.url)
const state = {login: {loggedIn: req.isAuthenticated()}};
const store = configureStore(state);
store.dispatch(match(req.url, (error, redirectLocation, routerState) => {
if (error) {
res.send(500, error.message)
}
if (redirectLocation) {
res.redirect(301, redirectLocation.pathname + redirectLocation.search)
}
if (!routerState) {
//res.send(404, 'Not found')
}
class Root extends React.Component {
render() {
return (
<Provider store={store}>
{ routes }
</Provider>
);
}
}
const output = renderToString(<Root/>);
res.render('content.ejs', { reactOutput: output, data: JSON.stringify(state), _layoutFile: 'layout.ejs'});
}));
} |
src/js/ui/components/progressButton.js | heartnotes/heartnotes | import _ from 'lodash';
import React from 'react';
import ActionProgress from './actionProgress';
import Button from './button';
module.exports = React.createClass({
propTypes: {
checkVar: React.PropTypes.object.isRequired,
defaultProgressMsg: React.PropTypes.string,
progressProps: React.PropTypes.object,
},
getDefaultProps: function() {
return {
defaultProgressMsg: 'Processing...',
progressProps: {},
};
},
render: function() {
let msg = null;
let buttonAttrs = _.extend({}, this.props);
if (_.get(this.props.checkVar, 'inProgress')) {
let _msg = _.get(this.props.checkVar, 'progressMsg');
if (!_.get((_msg || '').trim(), 'length')) {
_msg = this.props.defaultProgressMsg;
}
msg = (
<div>{_msg}</div>
);
buttonAttrs.animActive = true;
buttonAttrs.disabled = true;
} else {
buttonAttrs.animActive = false;
}
let err = _.get(this.props.checkVar, 'error');
if (err) {
msg = (
<div className="error">{err + ''}</div>
);
}
let progressProps = _.omit(this.props.progressProps, 'msg');
return (
<ActionProgress msg={msg} {...progressProps}>
<Button {...buttonAttrs}>{this.props.children}</Button>
</ActionProgress>
);
},
});
|
src/components/EditorWidgets/Markdown/MarkdownControl/index.js | Aloomaio/netlify-cms | import PropTypes from 'prop-types';
import React from 'react';
import c from 'classnames';
import { markdownToRemark, remarkToMarkdown } from 'EditorWidgets/Markdown/serializers'
import RawEditor from './RawEditor';
import VisualEditor from './VisualEditor';
const MODE_STORAGE_KEY = 'cms.md-mode';
let editorControl;
export const getEditorControl = () => editorControl;
export default class MarkdownControl extends React.Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
onAddAsset: PropTypes.func.isRequired,
getAsset: PropTypes.func.isRequired,
classNameWrapper: PropTypes.string.isRequired,
editorControl: PropTypes.func.isRequired,
value: PropTypes.string,
};
constructor(props) {
super(props);
editorControl = props.editorControl;
this.state = { mode: localStorage.getItem(MODE_STORAGE_KEY) || 'visual' };
}
handleMode = (mode) => {
this.setState({ mode });
localStorage.setItem(MODE_STORAGE_KEY, mode);
};
processRef = ref => this.ref = ref;
render() {
const {
onChange,
onAddAsset,
getAsset,
value,
classNameWrapper,
} = this.props;
const { mode } = this.state;
const visualEditor = (
<div className="cms-editor-visual" ref={this.processRef}>
<VisualEditor
onChange={onChange}
onAddAsset={onAddAsset}
onMode={this.handleMode}
getAsset={getAsset}
className={classNameWrapper}
value={value}
/>
</div>
);
const rawEditor = (
<div className="cms-editor-raw" ref={this.processRef}>
<RawEditor
onChange={onChange}
onAddAsset={onAddAsset}
onMode={this.handleMode}
getAsset={getAsset}
className={classNameWrapper}
value={value}
/>
</div>
);
return mode === 'visual' ? visualEditor : rawEditor;
}
}
|
src/pages/Signup.js | GamerZUnited/GamerZUninted-FrontEnd | import React from 'react'
import {connect} from 'react-redux'
import {pushState } from 'redux-router'
import * as Actions from '../actions/AppActions'
@connect(
state => ({
login: state.login
})
)
class Signup extends React.Component {
render() {
const {login, dispatch} = this.props
const handleSignup = (event) => {
const { password, first_name, email, last_name, age} = this.refs
dispatch(Actions.signup(first_name.value, last_name.value, email.value, password.value, age.value))
dispatch(pushState(null,'/'))
}
return (
<div className="signUp">
<form>
<label>Sign Up Here!</label>
<input type="text" placeholder="First Name" ref="first_name"/>
<input type="text" placeholder="last Name" ref="last_name"/>
<input type="text" placeholder="Email" ref="email"/>
<input type="password" placeholder="Password" ref="password"/>
<input type="text" placeholder="Age" ref="age"/>
<input type="button" value="Sign Up" onClick={handleSignup}/>
</form>
</div>
)
}
}
export default Signup
|
js/Landing.js | PaquitoSoft/complete-intro-to-react | import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import { setSearchTerm } from './actionCreators';
const { string, func, object } = React.PropTypes;
const Landing = React.createClass({
/* WTF!!! */
contextTypes: {
router: object
},
propTypes: {
searchTerm: string,
dispatch: func
},
handleSearchSubmit (event) {
event.preventDefault();
this.context.router.transitionTo('/search');
},
handleSearchTermChange (event) {
this.props.dispatch(setSearchTerm(event.target.value));
},
render () {
return (
<div className='landing'>
<h1>svideo</h1>
<form onSubmit={this.handleSearchSubmit}>
<input
type='text'
value={this.props.searchTerm}
onChange={this.handleSearchTermChange}
placeholder='Search'
/>
</form>
<Link to='/search'>or Browse all</Link>
</div>
);
}
});
function mapStateToProps (state) {
return {
searchTerm: state.searchTerm
};
}
export default connect(mapStateToProps)(Landing);
|
stories/form/input.js | lanyuechen/dh-component | import React from 'react';
import { Input } from '../../src';
export default class InputDemo extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="test-input">
<div className="test-input-eq ">
<Input value="1223" onChange={(e) => {console.log('wjb', e.target.value)}}/>
</div>
<div className="test-input-eq ">
<Input placeholder="默认提示信息" />
</div>
<div className="test-input-eq ">
<Input defaultValue="我是系统的默认值"/>
</div>
<div className="test-input-eq ">
<Input placeholder="请输入内容" addonBefore="前置"/>
</div>
<div className="test-input-eq ">
<Input placeholder="请输入内容" addonAfter="后置"/>
</div>
<div className="test-input-eq ">
<Input placeholder="请输入内容" searched />
</div>
<div className="test-input-eq ">
<Input.Number placeholder="数字输入框" />
</div>
</div>
)
}
} |
ElementContent.js | asconwe/formulate | import React, { Component } from 'react';
import CustomElementInput from './CustomElementInput'
class ElementContent extends Component {
render() {
return (
<div>
<h3>
<CustomElementInput
value={this.props.elementTitle}
index={this.props.index}
contentKey="elementTitle"
editElement={this.props.editElement}
/>
</h3>
<p>
<CustomElementInput
value={this.props.elementPrompt}
index={this.props.index}
contentKey="elementPrompt"
editElement={this.props.editElement}
/>
</p>
</div>
);
}
}
export default ElementContent;
|
src/components/Footer/Footer.js | yvanwangl/UniversalBlog | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
import Link from '../Link';
class Footer extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Your Company</span>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/">Home</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/admin">Admin</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/privacy">Privacy</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/not-found">Not Found</Link>
</div>
</div>
);
}
}
export default withStyles(s)(Footer);
|
src/encoded/static/components/navigation/components/BigDropdown/BigDropdownPageTreeMenu.js | 4dn-dcic/fourfront | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import url from 'url';
import _ from 'underscore';
import { console, memoizedUrlParse } from '@hms-dbmi-bgm/shared-portal-components/es/components/util';
import { BigDropdownIntroductionWrapper } from './BigDropdownIntroductionWrapper';
export function BigDropdownPageTreeMenuIntroduction(props) {
const { menuTree, windowHeight, windowWidth, titleIcon = null, isActive = false } = props;
const { display_title, name: pathName, description } = menuTree || {};
if (!menuTree || !menuTree.display_title || windowHeight < 600) {
// Hide this link to top-level page on smaller heights.
// TODO: Reconsider and maybe remove this; works currently for /help and /resources since they serve
// as "directory" pages without much useful content themselves.
return null;
}
return (
<BigDropdownIntroductionWrapper {...{ windowHeight, windowWidth, titleIcon, isActive }}>
<h4 className="mt-0 mb-0">
<a href={'/' + pathName} data-handle-click={true}>{ display_title }</a>
</h4>
{ description ? <div className="description">{ description }</div> : null }
</BigDropdownIntroductionWrapper>
);
}
export function BigDropdownPageTreeMenu(props) {
const { menuTree, href } = props;
const { display_title, name: pathName, children = [] } = menuTree || {};
if (!pathName || !display_title) return null;
/*
var mostChildrenHaveChildren = _.filter(helpMenuTree.children, function(c){
return (c.children || []).length > 0;
}).length >= parseInt(helpMenuTree.children.length / 2);
*/
const urlParts = memoizedUrlParse(href);
function filterOutChildren(child){ // Ensure Item has view permission, title, and name (route/URL).
return !child.error && child.display_title && child.name;
}
const level1ChildrenWithoutSubChildren = [];
const level1ChildrenWithSubChildren = _.filter(children, function(child){
const childValid = filterOutChildren(child);
if (!childValid) return false;
const filteredChildren = _.filter(child.children || [], filterOutChildren);
if (filteredChildren.length > 0){
return true;
} else {
if ((child.content || []).length > 0) {
level1ChildrenWithoutSubChildren.push(child);
}
return false;
}
});
const hasLevel2Children = level1ChildrenWithSubChildren.length > 0;
let topLeftMenuCol = null;
if (level1ChildrenWithoutSubChildren.length > 0){
topLeftMenuCol = (
<div key="reserved"
className={"help-menu-tree level-1-no-child-links level-1 col-12" + (!hasLevel2Children? " col-lg-8" : " col-lg-4")}>
{ level1ChildrenWithoutSubChildren.map(function(child){
const active = (urlParts.pathname.indexOf(child.name) > -1 ? ' active' : '');
return (
<div className={"level-1-title-container" + (active? " active" : "")} key={child.name}>
<a className="level-1-title text-medium" href={'/' + child.name} data-tip={child.description}
data-delay-show={500} id={"menutree-linkto-" + child.name.replace(/\//g, '_')} >
<span>{ child.display_title }</span>
</a>
</div>
);
}) }
</div>
);
}
const childItems = level1ChildrenWithSubChildren.map(function(childLevel1){
const level1Children = _.filter(childLevel1.children || [], filterOutChildren);
const hasChildren = level1Children.length > 0;
const active = urlParts.pathname.indexOf(childLevel1.name) > -1;
const outerCls = (
"help-menu-tree level-1 col-12 col-md-6 col-lg-4" +
(hasChildren ? ' has-children' : '')
);
return (
<div className={outerCls} key={childLevel1.name}>
<div className={"level-1-title-container" + (active ? " active" : "")}>
<a className="level-1-title text-medium" href={'/' + childLevel1.name} data-tip={childLevel1.description}
data-delay-show={500} id={"menutree-linkto-" + childLevel1.name.replace(/\//g, '_')} >
<span>{ childLevel1.display_title }</span>
</a>
</div>
{ hasChildren ?
level1Children.map(function(childLevel2){
return (
<a className={"level-2-title text-small" + (urlParts.pathname.indexOf(childLevel2.name) > -1 ? ' active' : '')}
href={'/' + childLevel2.name} data-tip={childLevel2.description} data-delay-show={500}
key={childLevel2.name} id={"menutree-linkto-" + childLevel2.name.replace(/\//g, '_')}>
{ childLevel2.display_title }
</a>
);
})
: null }
</div>
);
});
const childItemsLen = childItems.length;
const cls = (
"tree-menu-container row" +
(!hasLevel2Children ? " no-level-2-children" : "") +
(!topLeftMenuCol ? "" : (childItemsLen < 3 ? "" : ((childItemsLen + 1) % 3 === 1 ? " justify-content-lg-center" : " justify-content-lg-end")))
);
return (
<div className={cls}>
{ topLeftMenuCol }
{ childItems }
</div>
);
}
|
src/src/Components/RulesEditor/components/CustomDate/index.js | ioBroker/ioBroker.javascript | import { FormControl, MenuItem, Select } from '@material-ui/core';
import React from 'react';
import cls from './style.module.scss';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import I18n from '@iobroker/adapter-react/i18n';
const DAYS = [
31, // 1
29, // 2
31, // 3
30, // 4
31, // 5
30, // 6
31, // 7
31, // 8
30, // 9
31, // 10
30, // 11
31 // 12
];
const CustomDate = ({ value, onChange, className, title, style }) => {
let [month, date] = (value || '01.01').toString().split('.');
date = parseInt(date, 10) || 0;
month = parseInt(month, 10) || 0;
if (month > 12) {
month = 12;
} else if (month < 0) {
month = 0;
}
if (date > DAYS[month]) {
date = DAYS[month];
} else if (date < 0) {
date = 0;
}
let days = [];
for (let i = 0; i < DAYS[month]; i++) {
days.push(i + 1);
}
return <div>
<FormControl
className={clsx(cls.root, className)}
style={style}
>
<Select
className={clsx(cls.root, className)}
margin="dense"
label={I18n.t('Month')}
onChange={e =>
onChange(e.target.value.toString().padStart(2, '0') + '.' + date.toString().padStart(2, '0'))}
value={month}
>
<MenuItem style={{ placeContent: 'space-between' }} key={0} value={0}>{I18n.t('Any month')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={1} value={1}>{I18n.t('January')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={2} value={2}>{I18n.t('February')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={3} value={3}>{I18n.t('March')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={4} value={4}>{I18n.t('April')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={5} value={5}>{I18n.t('May')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={6} value={6}>{I18n.t('June')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={7} value={7}>{I18n.t('July')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={8} value={8}>{I18n.t('August')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={9} value={9}>{I18n.t('September')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={10} value={10}>{I18n.t('October')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={11} value={11}>{I18n.t('November')}</MenuItem>
<MenuItem style={{ placeContent: 'space-between' }} key={12} value={12}>{I18n.t('December')}</MenuItem>
</Select>
</FormControl>
<FormControl
className={clsx(cls.root, className)}
style={style}
>
<Select
className={clsx(cls.root, className)}
margin="dense"
label={I18n.t('Date')}
onChange={e =>
onChange(month.toString().padStart(2, '0') + '.' + e.target.value.toString().padStart(2, '0'))}
value={date}
>
<MenuItem style={{ placeContent: 'space-between' }} key={'A'} value={0}>{I18n.t('Any')}</MenuItem>
{days.map(i => <MenuItem style={{ placeContent: 'space-between' }} key={i} value={i}>{i}</MenuItem>)}
</Select>
</FormControl>
</div>;
}
CustomDate.defaultProps = {
value: '',
className: null,
};
CustomDate.propTypes = {
title: PropTypes.string,
attr: PropTypes.string,
style: PropTypes.object,
onChange: PropTypes.func
};
export default CustomDate; |
client2/src/components/react-burger-menu/src/BurgerIcon.js | ibulmer/Board | 'use strict';
import React from 'react';
import Radium from 'radium';
let BurgerIcon = Radium(React.createClass({
propTypes: {
image: React.PropTypes.string,
styles: React.PropTypes.object
},
getLineStyle(index) {
return {
position: 'absolute',
height: '20%',
left: 0,
right: 0,
top: 20 * (index * 2) + '%',
opacity: this.state.hover ? 0.6 : 1
};
},
handleHover() {
this.setState({ hover: !this.state.hover });
},
getInitialState() {
return { hover: false };
},
getDefaultProps() {
return {
image: '',
styles: {}
};
},
render() {
let icon;
let buttonStyle = {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
margin: 0,
padding: 0,
border: 'none',
fontSize: 14,
color: 'transparent',
background: 'transparent',
outline: 'none'
};
if (this.props.image) {
icon = <img src={ this.props.image } alt="Menu icon" className="bm-icon" style={ [{width: '100%', height: '100%'}, this.props.styles.bmIcon] }/>;
} else {
icon = (
<span>
<span className="bm-burger-bars" style={ [this.getLineStyle(0), this.props.styles.bmBurgerBars] }></span>
<span className="bm-burger-bars" style={ [this.getLineStyle(1), this.props.styles.bmBurgerBars] }></span>
<span className="bm-burger-bars" style={ [this.getLineStyle(2), this.props.styles.bmBurgerBars] }></span>
</span>
);
}
return (
<div className="bm-burger-button" style={ [{ zIndex: 1 }, this.props.styles.bmBurgerButton] }>
{ icon }
<button onClick={ this.props.onClick }
onMouseEnter={ this.handleHover }
onMouseLeave={ this.handleHover }
style={ buttonStyle }>
Open Menu
</button>
</div>
);
}
}));
export default BurgerIcon;
|
src/index.js | mende/deckard | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './stores';
import App from './containers/App';
const store = configureStore();
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
|
components/animals/agamaKocincinska.adult.js | marxsk/zobro | import React, { Component } from 'react';
import { Text } from 'react-native';
import styles from '../../styles/styles';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';
const IMAGES = [
require('../../images/animals/agamaKocincinska/01.jpg'),
require('../../images/animals/agamaKocincinska/02.jpg'),
];
const THUMBNAILS = [
require('../../images/animals/agamaKocincinska/01-thumb.jpg'),
require('../../images/animals/agamaKocincinska/02-thumb.jpg'),
];
var AnimalDetail = React.createClass({
render() {
return (
<AnimalTemplate firstIndex={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
<AnimalText>
Agama kočinčinská neboli <Text style={styles.italic}>Physignathus cocincinus</Text>, pro Angličany <Text style={styles.italic}>chinese water dragon</Text>, tedy čínský vodní drak, je plaz dlouhý kolem tří čtvrtin metru, přičemž přibližně dvě třetiny délky agamy tvoří ocas. (Je proto s podivem, že agam nejsou plné učebnice matematiky; byly by z nich krásné příklady.)
</AnimalText>
<AnimalText>
Agamy kočinčinské obývají jihovýchod Asie, oblast takzvané Kočinčíny, tedy jih Vietnamu. Kromě toho je možné je potkat v Číně, Thajsku a Laosu. Žijí na místech, kde je vlhko a teplo – pro milovníky čísel to znamená až 80% vlhkost a teploty 29 ± 3 °C. V takovýchto oblastech pobývají u vody na keřích nebo malých stromech. K nebezpečí se agamy otáčejí zády – vrhají se do vody, ve které jsou jako doma, a dovedou se potápět na desítky minut.
</AnimalText>
<InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
<AnimalText>
Co se potravy týče, nejčastěji si agamy pochutnávají na hmyzu. Čas od času si smlsnou i na drobných obratlovcích včetně ryb. Jen výjimečně okoštují i něco zeleného, většině agam totiž vegetariánství dvakrát nevoní. A proč by také mělo, když mají předpoklady k tomu být vynikajícími lovci – kromě plavání dokážou agamy také utíkat pouze po zadních nohou.
</AnimalText>
<AnimalText>
V naší zoo žije jeden sameček a dvě samičky. Samečka lze poznat podle toho, že je barevnější, má na hřbetě větší hřeben a má žlutooranžově zbarvený spodek krku. Jinak jsou všechny agamy svrchu zelené, trochu do hněda a mají světlá bříška. (Mimochodem, hřeben mají i samičky; samečci je do něj kousají během kopulace.)
</AnimalText>
<AnimalText>
Agamy jsou vejcorodé. Snůšku kladou samičky do jamky v zemi, mláďata se líhnou po dvou až dvou a půl měsících, záleží na okolní teplotě. Délka života agam je 10–15 let.
</AnimalText>
<AnimalText>
A zajímavost na závěr: Agamy mají tři oči. Na temeni hlavy, mezi „normálníma“ očima, mají skvrnu, tzv. pineální oko, kterým vnímají změny intenzity světla. To jim jednak pravděpodobně pomáhá s termoregulací (slouží pro nalezení místa k vyhřívání) a jednak je chrání před nebezpečím. Spící agamy totiž tímto okem pravděpodobně dokážou poznat rozdíl v intenzitě světla, když nad nimi například letí dravec.
</AnimalText>
</AnimalTemplate>
);
}
});
module.exports = AnimalDetail;
|
django/webcode/webcode/frontend/node_modules/react-bootstrap/es/NavItem.js | OpenKGB/webcode | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import SafeAnchor from './SafeAnchor';
import createChainedFunction from './utils/createChainedFunction';
var propTypes = {
active: PropTypes.bool,
disabled: PropTypes.bool,
role: PropTypes.string,
href: PropTypes.string,
onClick: PropTypes.func,
onSelect: PropTypes.func,
eventKey: PropTypes.any
};
var defaultProps = {
active: false,
disabled: false
};
var NavItem = function (_React$Component) {
_inherits(NavItem, _React$Component);
function NavItem(props, context) {
_classCallCheck(this, NavItem);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleClick = _this.handleClick.bind(_this);
return _this;
}
NavItem.prototype.handleClick = function handleClick(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, e);
}
}
};
NavItem.prototype.render = function render() {
var _props = this.props,
active = _props.active,
disabled = _props.disabled,
onClick = _props.onClick,
className = _props.className,
style = _props.style,
props = _objectWithoutProperties(_props, ['active', 'disabled', 'onClick', 'className', 'style']);
delete props.onSelect;
delete props.eventKey;
// These are injected down by `<Nav>` for building `<SubNav>`s.
delete props.activeKey;
delete props.activeHref;
if (!props.role) {
if (props.href === '#') {
props.role = 'button';
}
} else if (props.role === 'tab') {
props['aria-selected'] = active;
}
return React.createElement(
'li',
{
role: 'presentation',
className: classNames(className, { active: active, disabled: disabled }),
style: style
},
React.createElement(SafeAnchor, _extends({}, props, {
disabled: disabled,
onClick: createChainedFunction(onClick, this.handleClick)
}))
);
};
return NavItem;
}(React.Component);
NavItem.propTypes = propTypes;
NavItem.defaultProps = defaultProps;
export default NavItem; |
client/src/components/trucks/Truck.js | PCGeekBrain/TruckTrack | import React from 'react';
import { Button, ButtonGroup } from 'react-bootstrap';
const Truck = ({truck, onEdit, onDelete}) => {
const edit = (event) => {
onEdit(event, truck);
}
const deleteItem = (event) => {
onDelete(truck.id)
}
return (
<div className="truck-card card">
<h2 className="truck_name">{truck.name}</h2>
<h3 className="truck_licence">Licence Plate: {truck.licence ? truck.licence : "N/A"}</h3>
<ButtonGroup>
<Button bsStyle="primary" onClick={edit}>Edit</Button>
<Button bsStyle="danger" onClick={deleteItem}>Delete</Button>
</ButtonGroup>
</div>
)
}
// default blank functions to avoid fatal errors
Truck.defaultProps = {
onEdit: () => {},
onDelete: () => {}
}
export default Truck;
|
src/clincoded/static/components/variant_central/interpretation/population.js | ClinGen/clincoded | 'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import _ from 'underscore';
import moment from 'moment';
import { RestMixin } from '../../rest';
import { parseClinvar } from '../../../libs/parse-resources';
import { queryKeyValue, dbxref_prefix_map, external_url_map } from '../../globals';
import { renderDataCredit } from './shared/credit';
import { showActivityIndicator } from '../../activity_indicator';
import { parseKeyValue } from '../helpers/parse_key_value';
import { Form, FormMixin, Input } from '../../../libs/bootstrap/form';
import { PanelGroup, Panel } from '../../../libs/bootstrap/panel';
import { findDiffKeyValuesMixin } from './shared/find_diff';
import { CompleteSection } from './shared/complete_section';
import { parseAndLogError } from '../../mixins';
import { scrollElementIntoView } from '../../../libs/helpers/scroll_into_view';
const vciFormHelper = require('./shared/form');
const CurationInterpretationForm = vciFormHelper.CurationInterpretationForm;
const genomic_chr_mapping = require('./mapping/NC_genomic_chr_format.json');
const evaluation_section_mapping = require('./mapping/evaluation_section.json');
const extraEvidence = require('./shared/extra_evidence');
const populationStatic = {
page: {
_labels: {
AfricanAmerican: 'African American', Asian: 'Asian', CentralAmerican: 'Central American', Cuban: 'Cuban', Dominican: 'Dominican', Mexican: 'Mexican',
NativeAmerican: 'Native American', NativeHawaiian: 'Native Hawaiian', PuertoRican: 'Puerto Rican', SouthAmerican: 'South American', SouthAsian: 'South Asian'
}
},
exac: {
_order: ['afr', 'amr', 'sas', 'nfe', 'eas', 'fin', 'oth'],
_labels: {afr: 'African', amr: 'Latino', eas: 'East Asian', fin: 'European (Finnish)', nfe: 'European (Non-Finnish)', oth: 'Other', sas: 'South Asian'}
},
gnomAD: {
_order: ['afr', 'amr', 'asj', 'sas', 'nfe', 'eas', 'fin', 'oth'],
_labels: {afr: 'African', amr: 'Latino', asj: 'Ashkenazi Jewish', eas: 'East Asian', fin: 'European (Finnish)', nfe: 'European (Non-Finnish)', oth: 'Other', sas: 'South Asian'}
},
tGenomes: {
_order: ['afr', 'amr', 'eas', 'eur', 'sas', 'espaa', 'espea'],
_labels: {afr: 'AFR', amr: 'AMR', eas: 'EAS', eur: 'EUR', sas: 'SAS', espaa: 'ESP6500: African American', espea: 'ESP6500: European American'}
},
esp: {
_order: ['ea', 'aa'],
_labels: {ea: 'EA Allele', aa: 'AA Allele'}
}
};
const CI_DEFAULT = 95;
// Display the population data of external sources
var CurationInterpretationPopulation = module.exports.CurationInterpretationPopulation = createReactClass({
mixins: [RestMixin, findDiffKeyValuesMixin],
propTypes: {
data: PropTypes.object, // ClinVar data payload
interpretation: PropTypes.object,
updateInterpretationObj: PropTypes.func,
ext_pageData: PropTypes.object,
ext_myVariantInfo: PropTypes.object,
ext_myVariantInfo_metadata: PropTypes.object,
ext_ensemblHgvsVEP: PropTypes.array,
ext_ensemblVariation: PropTypes.object,
ext_singleNucleotide: PropTypes.bool,
ext_gnomadExac: PropTypes.bool,
loading_pageData: PropTypes.bool,
loading_myVariantInfo: PropTypes.bool,
loading_ensemblVariation: PropTypes.bool,
href_url: PropTypes.object,
affiliation: PropTypes.object,
session: PropTypes.object,
selectedCriteria: PropTypes.string
},
getInitialState: function() {
return {
data: this.props.data,
clinvar_id: null, // ClinVar ID
car_id: null, // ClinGen Allele Registry ID
interpretation: this.props.interpretation,
ensembl_exac_allele: {},
hasExacData: false, // flag to display ExAC table
hasGnomadData: false, // flag to display gnomAD table
hasTGenomesData: false,
hasEspData: false, // flag to display ESP table
hasPageData: false,
CILow: null,
CIhigh: null,
populationObj: {
highestMAF: null,
desiredCI: 95,
mafCutoff: 5,
exac: {
_version: '', afr: {}, amr: {}, eas: {}, fin: {}, nfe: {}, oth: {}, sas: {}, _tot: {}, _extra: {}
},
gnomAD: {
_version: '', afr: {}, amr: {}, asj: {}, eas: {}, fin: {}, nfe: {}, oth: {}, sas: {}, _tot: {}, _extra: {}
},
tGenomes: {
afr: {ac: {}, af: {}, gc: {}, gf: {}},
amr: {ac: {}, af: {}, gc: {}, gf: {}},
eas: {ac: {}, af: {}, gc: {}, gf: {}},
eur: {ac: {}, af: {}, gc: {}, gf: {}},
sas: {ac: {}, af: {}, gc: {}, gf: {}},
espaa: {ac: {}, af: {}, gc: {}, gf: {}},
espea: {ac: {}, af: {}, gc: {}, gf: {}},
_tot: {ac: {}, af: {}, gc: {}, gf: {}},
_extra: {}
},
esp: {
aa: {ac: {}, gc: {}},
ea: {ac: {}, gc: {}},
_tot: {ac: {}, gc: {}},
_extra: {}
}
},
populationObjDiff: null,
populationObjDiffFlag: false,
ext_singleNucleotide: this.props.ext_singleNucleotide,
ext_gnomadExac: this.props.ext_gnomadExac,
loading_pageData: this.props.loading_pageData,
loading_myVariantInfo: this.props.loading_myVariantInfo,
loading_ensemblVariation: this.props.loading_ensemblVariation,
selectedCriteria: this.props.selectedCriteria
};
},
componentDidMount: function() {
if (this.props.data) {
this.setState({data: this.props.data});
}
if (this.props.interpretation) {
this.setState({interpretation: this.props.interpretation});
// set desired CI if previous data for it exists
this.getPrevSetDesiredCI(this.props.interpretation);
}
if (this.props.ext_pageData) {
this.setState({hasPageData: true});
}
if (this.props.ext_myVariantInfo) {
this.parseExacData(this.props.ext_myVariantInfo, this.props.ext_myVariantInfo_metadata);
this.parseGnomadData(this.props.ext_myVariantInfo, this.props.ext_myVariantInfo_metadata);
this.parseEspData(this.props.ext_myVariantInfo);
this.calculateHighestMAF();
}
if (this.props.ext_ensemblHgvsVEP) {
this.parseAlleleFrequencyData(this.props.ext_ensemblHgvsVEP);
this.calculateHighestMAF();
}
if (this.props.ext_ensemblVariation) {
this.parseTGenomesData(this.props.ext_ensemblVariation);
this.calculateHighestMAF();
}
if (this.state.interpretation && this.state.interpretation.evaluations) {
this.compareExternalDatas(this.state.populationObj, this.state.interpretation.evaluations);
}
if (this.state.selectedCriteria) {
setTimeout(scrollElementIntoView(evaluation_section_mapping[this.state.selectedCriteria], 'class'), 200);
}
},
componentWillReceiveProps: function(nextProps) {
this.setState({data: nextProps.data, interpretation: nextProps.interpretation});
// set desired CI if previous data for it exists
this.getPrevSetDesiredCI(nextProps.interpretation);
// update data based on api call results
if (nextProps.ext_pageData) {
this.setState({hasPageData: true});
}
if (nextProps.ext_myVariantInfo) {
this.parseExacData(nextProps.ext_myVariantInfo, nextProps.ext_myVariantInfo_metadata);
this.parseGnomadData(nextProps.ext_myVariantInfo, nextProps.ext_myVariantInfo_metadata);
this.parseEspData(nextProps.ext_myVariantInfo);
this.calculateHighestMAF();
}
if (nextProps.ext_ensemblHgvsVEP) {
this.parseAlleleFrequencyData(nextProps.ext_ensemblHgvsVEP);
this.calculateHighestMAF();
}
if (nextProps.ext_ensemblVariation) {
this.parseTGenomesData(nextProps.ext_ensemblVariation);
this.calculateHighestMAF();
}
if (nextProps.interpretation && nextProps.interpretation.evaluations) {
this.compareExternalDatas(this.state.populationObj, nextProps.interpretation.evaluations);
}
if (nextProps.selectedCriteria) {
this.setState({selectedCriteria: nextProps.selectedCriteria}, () => {
setTimeout(scrollElementIntoView(evaluation_section_mapping[this.state.selectedCriteria], 'class'), 200);
});
}
this.setState({
ext_singleNucleotide: nextProps.ext_singleNucleotide,
ext_gnomadExac: nextProps.ext_gnomadExac,
loading_ensemblVariation: nextProps.loading_ensemblVariation,
loading_myVariantInfo: nextProps.loading_myVariantInfo,
loading_pageData: nextProps.loading_pageData
});
},
componentWillUnmount: function() {
this.setState({
hasExacData: false,
hasGnomadData: false,
hasTGenomesData: false,
hasEspData: false,
hasPageData: false
});
},
// helper function to shorten display of imported float values to 5 decimal places;
// if float being displayed has less than 5 decimal places, just show the value with no changes
// Returns a string for display purposes.
parseFloatShort: function(float) {
let splitFloat = (float + "").split('.');
if (splitFloat.length > 1 && splitFloat[1].length > 5) {
return float.toFixed(5) + '';
} else {
return float.toString();
}
},
// function to compare current external data with external data saved with a previous interpretation
compareExternalDatas: function(newData, savedEvals) {
for (var i in savedEvals) {
if (['BA1', 'PM2', 'BS1'].indexOf(savedEvals[i].criteria) > -1) {
var tempCompare = this.findDiffKeyValues(newData, savedEvals[i].population.populationData);
this.setState({populationObjDiff: tempCompare[0], populationObjDiffFlag: tempCompare[1]});
break;
}
}
},
// Get ExAC allele frequency from Ensembl (VEP) directly
// Because myvariant.info doesn't always return ExAC allele frequency data
parseAlleleFrequencyData: function(response) {
let populationObj = this.state.populationObj;
const colocatedVariants = response && response[0] && response[0].colocated_variants && response[0].colocated_variants[0] ?
response[0].colocated_variants[0] : null;
populationStatic.exac._order.map(key => {
populationObj.exac[key].af = typeof populationObj.exac[key].af !== 'undefined' ?
(isNaN(populationObj.exac[key].af) ? null : populationObj.exac[key].af) :
(colocatedVariants ? parseFloat(colocatedVariants['exac_' + key + '_maf']) : NaN);
});
populationObj.exac._tot.af = typeof populationObj.exac._tot.af !== 'undefined' ?
(isNaN(populationObj.exac._tot.af) ? null : populationObj.exac._tot.af) :
(colocatedVariants ? parseFloat(colocatedVariants.exac_adj_maf) : NaN);
this.setState({populationObj: populationObj});
},
// Method to assign ExAC population data to global population object
parseExacData: function(response, metadata) {
// Not all variants can be found in ExAC
// Do nothing if the exac{...} object is not returned from myvariant.info
if (response.exac) {
let populationObj = this.state.populationObj;
// get the allele count, allele number, and homozygote count for desired populations
populationStatic.exac._order.map(key => {
populationObj.exac[key].ac = parseInt(response.exac.ac['ac_' + key]);
populationObj.exac[key].an = parseInt(response.exac.an['an_' + key]);
populationObj.exac[key].hom = parseInt(response.exac.hom['hom_' + key]);
populationObj.exac[key].af = populationObj.exac[key].ac / populationObj.exac[key].an;
});
// get the allele count, allele number, and homozygote count totals
populationObj.exac._tot.ac = parseInt(response.exac.ac.ac_adj);
populationObj.exac._tot.an = parseInt(response.exac.an.an_adj);
populationObj.exac._tot.hom = response.exac.ac.ac_hom ? parseInt(response.exac.ac.ac_hom) : parseInt(response.exac.hom.ac_hom);
populationObj.exac._tot.af = populationObj.exac._tot.ac / populationObj.exac._tot.an;
// get extra ExAC information
populationObj.exac._extra.chrom = response.exac.chrom + ''; // ensure that the chromosome is stored as a String
populationObj.exac._extra.pos = parseInt(response.exac.pos);
populationObj.exac._extra.ref = response.exac.ref;
populationObj.exac._extra.alt = response.exac.alt;
// get filter information
if (response.exac.filter) {
if (Array.isArray(response.exac.filter)) {
populationObj.exac._extra.filter = response.exac.filter;
} else {
populationObj.exac._extra.filter = [response.exac.filter];
}
}
// get the source version
if (metadata && metadata.src && metadata.src.exac && metadata.src.exac.version) {
populationObj.exac._version = metadata.src.exac.version;
}
// update populationObj, and set flag indicating that we have ExAC data
this.setState({hasExacData: true, populationObj: populationObj});
}
},
// Method to assign gnomAD population data to global population object
parseGnomadData: function(response, metadata) {
let populationObj = this.state.populationObj;
// Parse gnomAD exome data in myvariant.info response
if (response.gnomad_exome && (response.gnomad_exome.ac || response.gnomad_exome.an || response.gnomad_exome.hom)) {
let indexHOM = -2;
let gnomADExomeAC, gnomADExomeAN, gnomADExomeHOM, gnomADExomeAF;
populationObj.gnomAD._extra.hasExomeData = true;
// Possible resulting values for indexHOM (and what each indicates):
// -2 - default set above, response data either doesn't exist or isn't in tested format (variant likely isn't multi-allelic),
// so any homozygote numbers would be in response.gnomad_*.hom['hom_' + key] ("default" location)
// -1 - response data exists, but current minor allele (response.gnomad_*.alt) not found within it,
// so homozygote numbers are not available
// >=0 - response data exists and current minor allele (response.gnomad_*.alt) found within it,
// so homozygote numbers should be in response.gnomad_*.hom['hom_' + key][indexHOM]
if (Array.isArray(response.gnomad_exome.alleles) && response.gnomad_exome.hom && Array.isArray(response.gnomad_exome.hom.hom)) {
indexHOM = response.gnomad_exome.alleles.indexOf(response.gnomad_exome.alt);
}
// Retrieve allele and homozygote exome data for each population
populationStatic.gnomAD._order.map(key => {
gnomADExomeAC = response.gnomad_exome.ac ? parseInt(response.gnomad_exome.ac['ac_' + key]) : null;
populationObj.gnomAD[key].ac = isNaN(gnomADExomeAC) ? null : gnomADExomeAC;
gnomADExomeAN = response.gnomad_exome.an ? parseInt(response.gnomad_exome.an['an_' + key]) : null;
populationObj.gnomAD[key].an = isNaN(gnomADExomeAN) ? null : gnomADExomeAN;
if (indexHOM < -1) {
gnomADExomeHOM = response.gnomad_exome.hom ? parseInt(response.gnomad_exome.hom['hom_' + key]) : null;
populationObj.gnomAD[key].hom = isNaN(gnomADExomeHOM) ? null : gnomADExomeHOM;
} else if (indexHOM > -1) {
gnomADExomeHOM = parseInt(response.gnomad_exome.hom['hom_' + key][indexHOM]);
populationObj.gnomAD[key].hom = isNaN(gnomADExomeHOM) ? null : gnomADExomeHOM;
}
gnomADExomeAF = populationObj.gnomAD[key].ac / populationObj.gnomAD[key].an;
populationObj.gnomAD[key].af = isFinite(gnomADExomeAF) ? gnomADExomeAF : null;
});
// Retrieve allele and homozygote exome totals
gnomADExomeAC = response.gnomad_exome.ac ? parseInt(response.gnomad_exome.ac.ac) : null;
populationObj.gnomAD._tot.ac = isNaN(gnomADExomeAC) ? null : gnomADExomeAC;
gnomADExomeAN = response.gnomad_exome.an ? parseInt(response.gnomad_exome.an.an) : null;
populationObj.gnomAD._tot.an = isNaN(gnomADExomeAN) ? null : gnomADExomeAN;
if (indexHOM < -1) {
gnomADExomeHOM = response.gnomad_exome.hom ? parseInt(response.gnomad_exome.hom.hom) : null;
populationObj.gnomAD._tot.hom = isNaN(gnomADExomeHOM) ? null : gnomADExomeHOM;
} else if (indexHOM > -1) {
gnomADExomeHOM = parseInt(response.gnomad_exome.hom.hom[indexHOM]);
populationObj.gnomAD._tot.hom = isNaN(gnomADExomeHOM) ? null : gnomADExomeHOM;
}
gnomADExomeAF = populationObj.gnomAD._tot.ac / populationObj.gnomAD._tot.an;
populationObj.gnomAD._tot.af = isFinite(gnomADExomeAF) ? gnomADExomeAF : null;
// Retrieve variant information
populationObj.gnomAD._extra.chrom = response.gnomad_exome.chrom;
populationObj.gnomAD._extra.pos = response.gnomad_exome.pos;
populationObj.gnomAD._extra.ref = response.gnomad_exome.ref;
populationObj.gnomAD._extra.alt = response.gnomad_exome.alt;
// Retrieve any available filter information
if (response.gnomad_exome.filter) {
if (Array.isArray(response.gnomad_exome.filter)) {
populationObj.gnomAD._extra.exome_filter = response.gnomad_exome.filter;
} else {
populationObj.gnomAD._extra.exome_filter = [response.gnomad_exome.filter];
}
}
}
// Parse gnomAD genome data in myvariant.info response
if (response.gnomad_genome && (response.gnomad_genome.ac || response.gnomad_genome.an || response.gnomad_genome.hom)) {
let indexHOM = -2;
let gnomADGenomeAC, gnomADGenomeAN, gnomADGenomeHOM, gnomADGenomeAF;
let hasExomeData = populationObj.gnomAD._extra.hasExomeData;
populationObj.gnomAD._extra.hasGenomeData = true;
if (Array.isArray(response.gnomad_genome.alleles) && response.gnomad_genome.hom && Array.isArray(response.gnomad_genome.hom.hom)) {
indexHOM = response.gnomad_genome.alleles.indexOf(response.gnomad_genome.alt);
}
// Retrieve allele and homozygote genome data for each population and add it to any corresponding exome data
populationStatic.gnomAD._order.map(key => {
gnomADGenomeAC = response.gnomad_genome.ac ? parseInt(response.gnomad_genome.ac['ac_' + key]) : null;
if (!(isNaN(gnomADGenomeAC) || gnomADGenomeAC == null)) {
if (hasExomeData) {
populationObj.gnomAD[key].ac += gnomADGenomeAC;
} else {
populationObj.gnomAD[key].ac = gnomADGenomeAC;
}
}
gnomADGenomeAN = response.gnomad_genome.an ? parseInt(response.gnomad_genome.an['an_' + key]) : null;
if (!(isNaN(gnomADGenomeAN) || gnomADGenomeAN == null)) {
if (hasExomeData) {
populationObj.gnomAD[key].an += gnomADGenomeAN;
} else {
populationObj.gnomAD[key].an = gnomADGenomeAN;
}
}
if (indexHOM < -1) {
gnomADGenomeHOM = response.gnomad_genome.hom ? parseInt(response.gnomad_genome.hom['hom_' + key]) : null;
} else if (indexHOM > -1) {
gnomADGenomeHOM = parseInt(response.gnomad_genome.hom['hom_' + key][indexHOM]);
}
if (!(isNaN(gnomADGenomeHOM) || gnomADGenomeHOM == null)) {
if (hasExomeData) {
populationObj.gnomAD[key].hom += gnomADGenomeHOM;
} else {
populationObj.gnomAD[key].hom = gnomADGenomeHOM;
}
}
gnomADGenomeAF = populationObj.gnomAD[key].ac / populationObj.gnomAD[key].an;
populationObj.gnomAD[key].af = isFinite(gnomADGenomeAF) ? gnomADGenomeAF : null;
});
// Retrieve allele and homozygote genome totals and add them to any corresponding exome totals
gnomADGenomeAC = response.gnomad_genome.ac ? parseInt(response.gnomad_genome.ac.ac) : null;
if (!(isNaN(gnomADGenomeAC) || gnomADGenomeAC == null)) {
if (hasExomeData) {
populationObj.gnomAD._tot.ac += gnomADGenomeAC;
} else {
populationObj.gnomAD._tot.ac = gnomADGenomeAC;
}
}
gnomADGenomeAN = response.gnomad_genome.an ? parseInt(response.gnomad_genome.an.an) : null;
if (!(isNaN(gnomADGenomeAN) || gnomADGenomeAN == null)) {
if (hasExomeData) {
populationObj.gnomAD._tot.an += gnomADGenomeAN;
} else {
populationObj.gnomAD._tot.an = gnomADGenomeAN;
}
}
if (indexHOM < -1) {
gnomADGenomeHOM = response.gnomad_genome.hom ? parseInt(response.gnomad_genome.hom.hom) : null;
} else if (indexHOM > -1) {
gnomADGenomeHOM = parseInt(response.gnomad_genome.hom.hom[indexHOM]);
}
if (!(isNaN(gnomADGenomeHOM) || gnomADGenomeHOM == null)) {
if (hasExomeData) {
populationObj.gnomAD._tot.hom += gnomADGenomeHOM;
} else {
populationObj.gnomAD._tot.hom = gnomADGenomeHOM;
}
}
gnomADGenomeAF = populationObj.gnomAD._tot.ac / populationObj.gnomAD._tot.an;
populationObj.gnomAD._tot.af = isFinite(gnomADGenomeAF) ? gnomADGenomeAF : null;
// Retrieve variant information (if not already collected)
if (!populationObj.gnomAD._extra.chrom) {
populationObj.gnomAD._extra.chrom = response.gnomad_genome.chrom;
}
if (!populationObj.gnomAD._extra.pos) {
populationObj.gnomAD._extra.pos = response.gnomad_genome.pos;
}
if (!populationObj.gnomAD._extra.ref) {
populationObj.gnomAD._extra.ref = response.gnomad_genome.ref;
}
if (!populationObj.gnomAD._extra.alt) {
populationObj.gnomAD._extra.alt = response.gnomad_genome.alt;
}
// Retrieve any available filter information
if (response.gnomad_genome.filter) {
if (Array.isArray(response.gnomad_genome.filter)) {
populationObj.gnomAD._extra.genome_filter = response.gnomad_genome.filter;
} else {
populationObj.gnomAD._extra.genome_filter = [response.gnomad_genome.filter];
}
}
// Get the source version
if (metadata && metadata.src && metadata.src.gnomad && metadata.src.gnomad.version) {
populationObj.gnomAD._version = metadata.src.gnomad.version;
}
}
if (populationObj.gnomAD._extra.hasExomeData || populationObj.gnomAD._extra.hasGenomeData) {
this.setState({hasGnomadData: true, populationObj: populationObj});
}
},
// parse 1000Genome data
parseTGenomesData: function(response) {
// not all variants are SNPs. Do nothing if variant is not a SNP
if (response.var_class && response.var_class == 'SNP') {
let hgvs_GRCh37 = '';
let hgvs_GRCh38 = '';
let populationObj = this.state.populationObj;
let updated1000GData = false;
// FIXME: this GRCh vs gRCh needs to be reconciled in the data model and data import
// update off of this.props.data as it is more stable, and this.state.data does not contain relevant updates
if (this.props.data && this.props.data.hgvsNames) {
hgvs_GRCh37 = this.props.data.hgvsNames.GRCh37 ? this.props.data.hgvsNames.GRCh37 :
(this.props.data.hgvsNames.gRCh37 ? this.props.data.hgvsNames.gRCh37 : '');
hgvs_GRCh38 = this.props.data.hgvsNames.GRCh38 ? this.props.data.hgvsNames.GRCh38 :
(this.props.data.hgvsNames.gRCh38 ? this.props.data.hgvsNames.gRCh38 : '');
}
// get extra 1000Genome information
populationObj.tGenomes._extra.name = response.name;
populationObj.tGenomes._extra.var_class = response.var_class;
if (hgvs_GRCh37.indexOf('>') > -1 || hgvs_GRCh38.indexOf('>') > -1) {
// if SNP variant, extract allele information from hgvs names, preferring grch38
populationObj.tGenomes._extra.ref = hgvs_GRCh38 ? hgvs_GRCh38.charAt(hgvs_GRCh38.length - 3) : hgvs_GRCh37.charAt(hgvs_GRCh37.length - 3);
populationObj.tGenomes._extra.alt = hgvs_GRCh38 ? hgvs_GRCh38.charAt(hgvs_GRCh38.length - 1) : hgvs_GRCh37.charAt(hgvs_GRCh37.length - 1);
} else {
// fallback for non-SNP variants
populationObj.tGenomes._extra.ref = response.ancestral_allele;
populationObj.tGenomes._extra.alt = response.minor_allele;
}
// get the allele count and frequencies...
if (response.populations) {
response.populations.map(population => {
// extract 20 characters and forward to get population code (not always relevant)
let populationCode = population.population.substring(20).toLowerCase();
if (population.population.indexOf('1000GENOMES:phase_3') == 0 &&
populationStatic.tGenomes._order.indexOf(populationCode) > -1) {
// ... for specific populations =
populationObj.tGenomes[populationCode].ac[population.allele] = parseInt(population.allele_count);
populationObj.tGenomes[populationCode].af[population.allele] = parseFloat(population.frequency);
updated1000GData = true;
} else if (population.population == '1000GENOMES:phase_3:ALL') {
// ... and totals
populationObj.tGenomes._tot.ac[population.allele] = parseInt(population.allele_count);
populationObj.tGenomes._tot.af[population.allele] = parseFloat(population.frequency);
updated1000GData = true;
} else if (population.population == 'ESP6500:African_American') {
// ... and ESP AA
populationObj.tGenomes.espaa.ac[population.allele] = parseInt(population.allele_count);
populationObj.tGenomes.espaa.af[population.allele] = parseFloat(population.frequency);
updated1000GData = true;
} else if (population.population == 'ESP6500:European_American') {
// ... and ESP EA
populationObj.tGenomes.espea.ac[population.allele] = parseInt(population.allele_count);
populationObj.tGenomes.espea.af[population.allele] = parseFloat(population.frequency);
updated1000GData = true;
}
});
}
// get the genotype counts and frequencies...
if (response.population_genotypes) {
response.population_genotypes.map(population_genotype => {
// extract 20 characters and forward to get population code (not always relevant)
let populationCode = population_genotype.population.substring(20).toLowerCase();
if (population_genotype.population.indexOf('1000GENOMES:phase_3:') == 0 &&
populationStatic.tGenomes._order.indexOf(populationCode) > -1) {
// ... for specific populations
populationObj.tGenomes[populationCode].gc[population_genotype.genotype] = parseInt(population_genotype.count);
populationObj.tGenomes[populationCode].gf[population_genotype.genotype] = parseFloat(population_genotype.frequency);
updated1000GData = true;
} else if (population_genotype.population == '1000GENOMES:phase_3:ALL') {
// ... and totals
populationObj.tGenomes._tot.gc[population_genotype.genotype] = parseInt(population_genotype.count);
populationObj.tGenomes._tot.gf[population_genotype.genotype] = parseFloat(population_genotype.frequency);
updated1000GData = true;
} else if (population_genotype.population == 'ESP6500:African_American') {
// ... and ESP AA
populationObj.tGenomes.espaa.gc[population_genotype.genotype] = parseInt(population_genotype.count);
populationObj.tGenomes.espaa.gf[population_genotype.genotype] = parseFloat(population_genotype.frequency);
updated1000GData = true;
} else if (population_genotype.population == 'ESP6500:European_American') {
// ... and ESP EA
populationObj.tGenomes.espea.gc[population_genotype.genotype] = parseInt(population_genotype.count);
populationObj.tGenomes.espea.gf[population_genotype.genotype] = parseFloat(population_genotype.frequency);
updated1000GData = true;
}
});
}
if (updated1000GData) {
// update populationObj, and set flag indicating that we have 1000Genomes data
this.setState({hasTGenomesData: true, populationObj: populationObj});
}
}
},
// Method to assign ESP population data to global population object
parseEspData: function(response) {
// Not all variants return the evs{...} object from myvariant.info
if (response.evs) {
let populationObj = this.state.populationObj;
// get relevant numbers and extra information from ESP
populationObj.esp.aa.ac = this.dictValuesToInt(response.evs.allele_count.african_american);
populationObj.esp.aa.gc = this.dictValuesToInt(response.evs.genotype_count.african_american);
populationObj.esp.ea.ac = this.dictValuesToInt(response.evs.allele_count.european_american);
populationObj.esp.ea.gc = this.dictValuesToInt(response.evs.genotype_count.european_american);
populationObj.esp._tot.ac = this.dictValuesToInt(response.evs.allele_count.all);
populationObj.esp._tot.gc = this.dictValuesToInt(response.evs.genotype_count.all_genotype);
populationObj.esp._extra.avg_sample_read = response.evs.avg_sample_read;
populationObj.esp._extra.rsid = response.evs.rsid;
populationObj.esp._extra.chrom = response.evs.chrom + ''; // ensure that the chromosome is stored as a String
populationObj.esp._extra.hg19_start = parseInt(response.evs.hg19.start);
populationObj.esp._extra.ref = response.evs.ref;
populationObj.esp._extra.alt = response.evs.alt;
// update populationObj, and set flag indicating that we have ESP data
this.setState({hasEspData: true, populationObj: populationObj});
}
},
// method to run through dictionary/Object's values and convert them to Int
dictValuesToInt: function(dict) {
for (var key in dict) {
dict[key] = parseInt(dict[key]);
}
return dict;
},
// calculate highest MAF value and related info from external data
calculateHighestMAF: function() {
let populationObj = this.state.populationObj;
let highestMAFObj = {af: 0};
// check gnomAD data
populationStatic.gnomAD._order.map(pop => {
if (populationObj.gnomAD[pop].af > highestMAFObj.af) {
highestMAFObj.pop = pop;
highestMAFObj.popLabel = populationStatic.gnomAD._labels[pop];
highestMAFObj.ac = populationObj.gnomAD[pop].ac;
highestMAFObj.ac_tot = populationObj.gnomAD[pop].an;
highestMAFObj.source = 'gnomAD';
highestMAFObj.af = populationObj.gnomAD[pop].af;
}
});
// check against exac data
populationStatic.exac._order.map(pop => {
if (populationObj.exac[pop].af && populationObj.exac[pop].af) {
if (populationObj.exac[pop].af > highestMAFObj.af) {
highestMAFObj.pop = pop;
highestMAFObj.popLabel = populationStatic.exac._labels[pop];
highestMAFObj.ac = populationObj.exac[pop].ac;
highestMAFObj.ac_tot = populationObj.exac[pop].an;
highestMAFObj.source = 'ExAC';
highestMAFObj.af = populationObj.exac[pop].af;
}
}
});
// check against esp data - done before 1000g's so that it takes precedence in case of tie
// due to 1000g also carrying esp data
populationStatic.esp._order.map(pop => {
let alt = populationObj.esp._extra.alt;
if (populationObj.esp[pop].ac) {
let ref = populationObj.esp._extra.ref,
alt = populationObj.esp._extra.alt;
// esp does not report back frequencies, so we have to calculate it off counts
let tempMAF = parseFloat(populationObj.esp[pop].ac[alt] / (populationObj.esp[pop].ac[ref] + populationObj.esp[pop].ac[alt]));
if (tempMAF > highestMAFObj.af) {
highestMAFObj.pop = pop;
highestMAFObj.popLabel = populationStatic.esp._labels[pop];
highestMAFObj.ac = populationObj.esp[pop].ac[alt];
highestMAFObj.ac_tot = populationObj.esp[pop].ac[ref] + populationObj.esp[pop].ac[alt];
highestMAFObj.source = 'ESP';
highestMAFObj.af = tempMAF;
}
}
});
// check against 1000g data
populationStatic.tGenomes._order.map(pop => {
let ref = populationObj.tGenomes._extra.ref,
alt = populationObj.tGenomes._extra.alt;
if (populationObj.tGenomes[pop].af && populationObj.tGenomes[pop].af[alt]) {
if (populationObj.tGenomes[pop].af[alt] > highestMAFObj.af) {
highestMAFObj.pop = pop;
highestMAFObj.popLabel = populationStatic.tGenomes._labels[pop];
highestMAFObj.ac = populationObj.tGenomes[pop].ac[alt];
highestMAFObj.ac_tot = populationObj.tGenomes[pop].ac[ref] + populationObj.tGenomes[pop].ac[alt];
highestMAFObj.source = (pop == 'espaa' || pop == 'espea') ? 'ESP (provided by 1000 Genomes)' : '1000 Genomes';
highestMAFObj.af = populationObj.tGenomes[pop].af[alt];
}
}
});
// embed highest MAF and related data into population obj, and update to state
populationObj.highestMAF = highestMAFObj;
this.setState({populationObj: populationObj}, () => {
this.changeDesiredCI(); // we have highest MAF data, so calculate the CI ranges
});
},
// Method to render external ExAC/gnomAD linkout when no relevant population data is found
renderExacGnomadLinkout: function(response, datasetName) {
let datasetCheck, datasetLink, datasetRegionURLKey;
let linkText = 'Search ' + datasetName;
// If no ExAC/gnomAD population data, construct external linkout for one of the following:
// 1) clinvar/cadd data found & the variant type is substitution
// 2) clinvar/cadd data found & the variant type is NOT substitution
// 3) no data returned by myvariant.info
switch (datasetName) {
case 'ExAC':
datasetCheck = this.state.hasExacData;
datasetLink = external_url_map['EXACHome'];
datasetRegionURLKey = 'ExACRegion';
break;
case 'gnomAD':
datasetCheck = this.state.hasGnomadData;
datasetLink = external_url_map['gnomADHome'];
datasetRegionURLKey = 'gnomADRegion';
break;
}
if (response) {
let chrom = response.chrom;
const regionStart = response.hg19 ? parseInt(response.hg19.start) - 30 :
(response.clinvar && response.clinvar.hg19 ? parseInt(response.clinvar.hg19.start) - 30 :
(response.cadd && response.cadd.hg19 ? parseInt(response.cadd.hg19.start) - 30 : ''));
const regionEnd = response.hg19 ? parseInt(response.hg19.end) + 30 :
(response.clinvar && response.clinvar.hg19 ? parseInt(response.clinvar.hg19.end) + 30 :
(response.cadd && response.cadd.hg19 ? parseInt(response.cadd.hg19.end) + 30 : ''));
// Applies to 'Duplication', 'Deletion', 'Insertion', 'Indel' (deletion + insertion)
// Or there is no ExAC/gnomAD data object in the returned myvariant.info JSON response
if ((!this.state.ext_gnomadExac || !datasetCheck) && chrom && regionStart && regionEnd) {
datasetLink = external_url_map[datasetRegionURLKey] + chrom + '-' + regionStart + '-' + regionEnd;
linkText = 'View the coverage of this region (+/- 30 bp) in ' + datasetName;
}
}
return (
<span>
<a href={datasetLink} target="_blank">{linkText}</a> for this variant.
</span>
);
},
/* The following methods are related to the rendering of population data tables */
/**
* Method to render a row of data for the PAGE table
* @param {object} pageObj - Individual PAGE population data object (e.g. African American)
* @param {number} key - Unique number
*/
renderPageRow(pageObj, key) {
let popKey = pageObj['pop'];
return (
<tr key={key} className="page-data-item">
<td>{populationStatic.page._labels[popKey]}</td>
<td>{pageObj['nobs']}</td>
<td>{pageObj['alleles'][1] + ': ' + this.parseFloatShort(1 - parseFloat(pageObj['rawfreq']))}</td>
<td>{pageObj['alleles'][0] + ': ' + this.parseFloatShort(pageObj['rawfreq'])}</td>
</tr>
);
},
// method to render a row of data for the ExAC/gnomAD table
renderExacGnomadRow: function(key, dataset, datasetStatic, rowNameCustom, className) {
let rowName = datasetStatic._labels[key];
if (key == '_tot') {
rowName = rowNameCustom;
}
return (
<tr key={key} className={className ? className : ''}>
<td>{rowName}</td>
<td>{dataset[key].ac || dataset[key].ac === 0 ? dataset[key].ac : '--'}</td>
<td>{dataset[key].an || dataset[key].an === 0 ? dataset[key].an : '--'}</td>
<td>{dataset[key].hom || dataset[key].hom === 0 ? dataset[key].hom : '--'}</td>
<td>{dataset[key].af || dataset[key].af === 0 ? this.parseFloatShort(dataset[key].af) : '--'}</td>
</tr>
);
},
// method to render a row of data for the 1000Genomes table
renderTGenomesRow: function(key, tGenomes, tGenomesStatic, rowNameCustom, className) {
let rowName = tGenomesStatic._labels[key];
// for when generating difference object:
//let tGenomesDiff = this.state.populationObjDiff && this.state.populationObjDiff.tGenomes ? this.state.populationObjDiff.tGenomes : null; // this null creates issues when populationObjDiff is not set because it compraes on null later
// generate genotype strings from reference and alt allele information
let g_ref = tGenomes._extra.ref + '|' + tGenomes._extra.ref,
g_alt = tGenomes._extra.alt + '|' + tGenomes._extra.alt,
g_mixed = tGenomes._extra.ref + '|' + tGenomes._extra.alt;
if (key == '_tot') {
rowName = rowNameCustom;
}
return (
<tr key={key} className={className ? className : ''}>
<td>{rowName}</td>
<td>{tGenomes[key].af[tGenomes._extra.ref] || tGenomes[key].af[tGenomes._extra.ref] === 0 ? tGenomes._extra.ref + ': ' + this.parseFloatShort(tGenomes[key].af[tGenomes._extra.ref]) : '--'}{tGenomes[key].ac[tGenomes._extra.ref] ? ' (' + tGenomes[key].ac[tGenomes._extra.ref] + ')' : ''}</td>
<td>{tGenomes[key].af[tGenomes._extra.alt] || tGenomes[key].af[tGenomes._extra.alt] === 0 ? tGenomes._extra.alt + ': ' + this.parseFloatShort(tGenomes[key].af[tGenomes._extra.alt]) : '--'}{tGenomes[key].ac[tGenomes._extra.alt] ? ' (' + tGenomes[key].ac[tGenomes._extra.alt] + ')' : ''}</td>
<td>{tGenomes[key].gf[g_ref] || tGenomes[key].gf[g_ref] === 0 ? g_ref + ': ' + this.parseFloatShort(tGenomes[key].gf[g_ref]) : '--'}{tGenomes[key].gc[g_ref] ? ' (' + tGenomes[key].gc[g_ref] + ')' : ''}</td>
<td>{tGenomes[key].gf[g_alt] || tGenomes[key].gf[g_alt] === 0 ? g_alt + ': ' + this.parseFloatShort(tGenomes[key].gf[g_alt]) : '--'}{tGenomes[key].gc[g_alt] ? ' (' + tGenomes[key].gc[g_alt] + ')' : ''}</td>
<td>{tGenomes[key].gf[g_mixed] || tGenomes[key].gf[g_mixed] === 0 ? g_mixed + ': ' + this.parseFloatShort(tGenomes[key].gf[g_mixed]) : '--'}{tGenomes[key].gc[g_mixed] ? ' (' + tGenomes[key].gc[g_mixed] + ')' : ''}</td>
</tr>
);
},
// method to render a row of data for the ESP table
renderEspRow: function(key, esp, espStatic, rowNameCustom, className) {
let rowName = espStatic._labels[key];
// generate genotype strings from reference and alt allele information
let g_ref = esp._extra.ref + esp._extra.ref,
g_alt = esp._extra.alt + esp._extra.alt,
g_mixed = esp._extra.alt + esp._extra.ref;
if (key == '_tot') {
rowName = rowNameCustom;
}
return (
<tr key={key} className={className ? className : ''}>
<td>{rowName}</td>
<td>{esp[key].ac[esp._extra.ref] || esp[key].ac[esp._extra.ref] === 0 ? esp._extra.ref + ': ' + esp[key].ac[esp._extra.ref] : '--'}</td>
<td>{esp[key].ac[esp._extra.alt] || esp[key].ac[esp._extra.alt] === 0 ? esp._extra.alt + ': ' + esp[key].ac[esp._extra.alt] : '--'}</td>
<td>{esp[key].gc[g_ref] || esp[key].gc[g_ref] ? g_ref + ': ' + esp[key].gc[g_ref] : '--'}</td>
<td>{esp[key].gc[g_alt] || esp[key].gc[g_alt] ? g_alt + ': ' + esp[key].gc[g_alt] : '--'}</td>
<td>{esp[key].gc[g_mixed] || esp[key].gc[g_mixed] ? g_mixed + ': ' + esp[key].gc[g_mixed] : '--'}</td>
</tr>
);
},
/* the following methods are related to the desired CI field and its related calculated values */
// method to determine desired CI value from previously saved interpretation
getPrevSetDesiredCI: function(interpretation) {
if (interpretation && interpretation.evaluations && interpretation.evaluations.length > 0) {
for (var i = 0; i < interpretation.evaluations.length; i++) {
if (interpretation.evaluations[i].criteria == 'BA1') {
let tempPopulationObj = this.state.populationObj;
tempPopulationObj.desiredCI = interpretation.evaluations[i].population.populationData.desiredCI;
this.setState({populationObj: tempPopulationObj});
break;
}
}
}
if (!this.state.populationObj.desiredCI) {
// previously saved value does not exist for some reason... set it to default value
let tempPopulationObj = this.state.populationObj;
tempPopulationObj.desiredCI = CI_DEFAULT;
this.setState({populationObj: tempPopulationObj});
}
// update CI low and high values
this.changeDesiredCI();
},
// wrapper function to calculateCI on value change
changeDesiredCI: function() {
if (this.refs && this.refs.desiredCI) {
this.calculateCI(parseInt(this.refs.desiredCI.getValue()), this.state.populationObj && this.state.populationObj.highestMAF ? this.state.populationObj.highestMAF : null);
}
},
// checking for empty text when clicking away from desired CI field
onBlurDesiredCI: function(event) {
let desiredCI = parseInt(this.refs.desiredCI.getValue());
if (desiredCI == '' || isNaN(desiredCI)) {
// if the user clicks away from the desired CI field, but it is blank/filled with
// bad input, re-set it to the default value
let tempPopulationObj = this.state.populationObj;
this.refs.desiredCI.setValue(CI_DEFAULT);
tempPopulationObj.desiredCI = CI_DEFAULT;
this.setState({populationObj: tempPopulationObj});
this.changeDesiredCI();
}
},
// function to calculate confidence intervals (CI). Formula taken from Steven's excel spreadsheet
calculateCI: function(CIp, highestMAF) {
// store user-input desired CI value into population object
let populationObj = this.state.populationObj;
populationObj.desiredCI = CIp;
if (highestMAF) {
if (isNaN(CIp) || CIp < 0 || CIp > 100) {
// the field is blank... clear CI low and high values
// note that the user did not necessary navigate away from field just yet, so do not
// automatically set value to default here
this.setState({populationObj: populationObj, CILow: null, CIHigh: null});
} else if (highestMAF.ac && highestMAF.ac_tot) {
// calculate CI
let xp = highestMAF.ac,
np = highestMAF.ac_tot;
let zp = -this.normSInv((1 - CIp / 100) / 2),
pp = xp / np,
qp = 1 - pp;
let CILow = ((2 * np * pp) + (zp * zp) - zp * Math.sqrt((zp * zp) + (4 * np * pp * qp))) / (2 * (np + (zp * zp))),
CIHigh = ((2 * np * pp) + (zp * zp) + zp * Math.sqrt((zp * zp) + (4 * np * pp * qp))) / (2 * (np + (zp * zp)));
this.setState({populationObj: populationObj, CILow: CILow, CIHigh: CIHigh});
} else {
this.setState({populationObj: populationObj, CILow: 'N/A', CIHigh: 'N/A'});
}
} else {
this.setState({populationObj: populationObj, CILow: 'N/A', CIHigh: 'N/A'});
}
},
// NORMSINV implementation taken from http://stackoverflow.com/a/8843728
// used for CI calculation
normSInv: function (p) {
let a1 = -39.6968302866538, a2 = 220.946098424521, a3 = -275.928510446969;
let a4 = 138.357751867269, a5 = -30.6647980661472, a6 = 2.50662827745924;
let b1 = -54.4760987982241, b2 = 161.585836858041, b3 = -155.698979859887;
let b4 = 66.8013118877197, b5 = -13.2806815528857, c1 = -7.78489400243029E-03;
let c2 = -0.322396458041136, c3 = -2.40075827716184, c4 = -2.54973253934373;
let c5 = 4.37466414146497, c6 = 2.93816398269878, d1 = 7.78469570904146E-03;
let d2 = 0.32246712907004, d3 = 2.445134137143, d4 = 3.75440866190742;
let p_low = 0.02425, p_high = 1 - p_low;
let q, r;
let retVal;
if ((p < 0) || (p > 1)) {
alert("NormSInv: Argument out of range.");
retVal = 0;
} else if (p < p_low) {
q = Math.sqrt(-2 * Math.log(p));
retVal = (((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1);
} else if (p <= p_high) {
q = p - 0.5;
r = q * q;
retVal = (((((a1 * r + a2) * r + a3) * r + a4) * r + a5) * r + a6) * q / (((((b1 * r + b2) * r + b3) * r + b4) * r + b5) * r + 1);
} else {
q = Math.sqrt(-2 * Math.log(1 - p));
retVal = -(((((c1 * q + c2) * q + c3) * q + c4) * q + c5) * q + c6) / ((((d1 * q + d2) * q + d3) * q + d4) * q + 1);
}
return retVal;
},
parseAlleleMyVariant(response) {
let alleleData = {};
let chrom = parseKeyValue(response, 'chrom'),
hg19 = parseKeyValue(response, 'hg19'),
ref = parseKeyValue(response, 'ref'),
alt = parseKeyValue(response, 'alt');
if (response) {
alleleData = {
chrom: (chrom && typeof chrom === 'string') ? chrom : null,
pos: (hg19 && typeof hg19 === 'object' && hg19.start) ? hg19.start : null,
ref: (ref && typeof ref === 'string') ? ref : null,
alt: (alt && typeof alt === 'string') ? alt : null
};
}
return alleleData;
},
/**
* Method to render PAGE population table header content
* @param {boolean} hasPageData - Flag for response from querying PAGE Rest api
* @param {boolean} loading_pageData - Flag for status on receiving/loading data
* @param {object} pageVariant - Data object abstracted from PAGE response
* @param (boolean) singleNucleotide - Flag for single nucleotide variant
*/
renderPageHeader: function(hasPageData, loading_pageData, pageVariant, singleNucleotide) {
const variantData = this.state.data;
const nc_genomic = variantData && variantData.hgvsNames && variantData.hgvsNames.GRCh37 ? variantData.hgvsNames.GRCh37 : null;
if (hasPageData && !loading_pageData && singleNucleotide) {
// const variantPage = pageVariant.chrom + ':' + pageVariant.pos + ' ' + pageVariant['alleles'][0] + '/' + pageVariant['alleles'][1];
return (
<h3 className="panel-title">PAGE: {nc_genomic} (GRCh37)
<a href="#credit-pagestudy" className="credit-pagestudy" title="pagestudy.org"><i className="icon icon-info-circle"></i> <span>PAGE Study</span></a>
<a className="panel-subtitle pull-right" href="http://popgen.uchicago.edu/ggv/" target="_blank" rel="noopener noreferrer">GGV Browser</a>
</h3>
);
} else {
return (
<h3 className="panel-title">PAGE: {nc_genomic} (GRCh37)
<a href="#credit-pagestudy" className="credit-pagestudy" title="pagestudy.org"><i className="icon icon-info-circle"></i> <span>PAGE Study</span></a>
</h3>
);
}
},
// Method to render ExAC/gnomAD population table header content
renderExacGnomadHeader: function(datasetCheck, loading_myVariantInfo, dataset, gnomadExac, response, metadata, datasetName) {
let datasetVariant = '';
let datasetLink;
let version;
if (datasetCheck) {
datasetVariant = ' ' + dataset._extra.chrom + ':' + dataset._extra.pos + ' ' + dataset._extra.ref + '/' + dataset._extra.alt + ' (GRCh37)';
} else if (response) {
let alleleData = this.parseAlleleMyVariant(response);
if (Object.keys(alleleData).length) {
datasetVariant = ' ' + alleleData.chrom + ':' + alleleData.pos + ' ' + alleleData.ref + '/' + alleleData.alt + ' (GRCh37)';
}
}
if (datasetCheck && !loading_myVariantInfo && gnomadExac) {
const datasetVariantURLKey = (datasetName === 'ExAC') ? 'EXAC' : (datasetName === 'gnomAD') ? 'gnomAD' : null;
const datasetURL = 'http:' + external_url_map[datasetVariantURLKey] + dataset._extra.chrom + '-' + dataset._extra.pos + '-' + dataset._extra.ref + '-' + dataset._extra.alt;
datasetLink = <a className="panel-subtitle pull-right" href={datasetURL} target="_blank">See data in {datasetName}</a>
}
// Set the source version
if (metadata && metadata.src) {
version = (datasetName === 'ExAC' && metadata.src.exac && metadata.src.exac.version) ? metadata.src.exac.version :
(datasetName === 'gnomAD' && metadata.src.gnomad && metadata.src.gnomad.version) ? metadata.src.gnomad.version : '';
}
return (
<h3 className="panel-title">{datasetName}{datasetVariant} {version ? <span>Version: {version}</span> : null}
<a href="#credit-myvariant" className="credit-myvariant" title="MyVariant.info"><span>MyVariant</span></a>
{datasetLink}
</h3>
);
},
// Method to render a single filter status in ExAC/gnomAD population table
renderExacGnomadFilter: function(filter, filterKey, filterClass) {
return (<li key={filterKey} className={'label label-' + filterClass}>{filter}</li>);
},
// Method to render additional information (data sources, filter status) in ExAC/gnomAD population table
// If filter(s) not provided by myvariant.info, assume there was a "Pass"; if no data is provided, assume there was a "No variant"
renderExacGnomadAddlInfo: function(dataset, datasetName) {
if (datasetName === 'ExAC') {
return (
<table className="table additional-info">
<tbody>
<tr>
<td className="filter">
<span>Filter:</span>
<ul>
{dataset._extra.filter ?
dataset._extra.filter.map((filter, index) => {
return (this.renderExacGnomadFilter(filter, (filter + '-' + index), 'danger'));
})
:
this.renderExacGnomadFilter('Pass', 'Pass', 'success')}
</ul>
</td>
</tr>
</tbody>
</table>
);
} else if (datasetName === 'gnomAD') {
return (
<table className="table additional-info">
<tbody>
{dataset._extra.hasExomeData ?
<tr>
<td className="included-data"><i className="icon icon-check-circle" /><span>Exomes</span></td>
<td className="filter">
<span>Filter:</span>
<ul>
{dataset._extra.exome_filter ?
dataset._extra.exome_filter.map((filter, index) => {
return (this.renderExacGnomadFilter(filter, (filter + '-' + index), 'warning'));
})
:
this.renderExacGnomadFilter('Pass', 'Pass', 'success')}
</ul>
</td>
</tr>
:
<tr>
<td className="included-data"><i className="icon icon-times-circle" /><span>Exomes</span></td>
<td className="filter">
<span>Filter:</span>
<ul>{this.renderExacGnomadFilter('No variant', 'No variant', 'danger')}</ul>
</td>
</tr>
}{dataset._extra.hasGenomeData ?
<tr>
<td className="included-data"><i className="icon icon-check-circle" /><span>Genomes</span></td>
<td className="filter">
<span>Filter:</span>
<ul>
{dataset._extra.genome_filter ?
dataset._extra.genome_filter.map((filter, index) => {
return (this.renderExacGnomadFilter(filter, (filter + '-' + index), 'warning'));
})
:
this.renderExacGnomadFilter('Pass', 'Pass', 'success')}
</ul>
</td>
</tr>
:
<tr>
<td className="included-data"><i className="icon icon-times-circle" /><span>Genomes</span></td>
<td className="filter">
<span>Filter:</span>
<ul>{this.renderExacGnomadFilter('No variant', 'No variant', 'danger')}</ul>
</td>
</tr>
}
</tbody>
</table>
);
} else {
return;
}
},
// Method to render 1000 Genomes population table header content
renderTGenomesHeader: function(hasTGenomesData, loading_ensemblVariation, tGenomes, singleNucleotide) {
if (hasTGenomesData && !loading_ensemblVariation && singleNucleotide) {
const variantTGenomes = tGenomes._extra.name + ' ' + tGenomes._extra.var_class;
const linkoutEnsembl = external_url_map['EnsemblPopulationPage'] + tGenomes._extra.name;
return (
<h3 className="panel-title">1000 Genomes: {variantTGenomes} (GRCh38)
<a href="#credit-vep" className="credit-vep" title="VEP"><span>VEP</span></a>
<a className="panel-subtitle pull-right" href={linkoutEnsembl} target="_blank">See data in Ensembl</a>
</h3>
);
} else {
return (
<h3 className="panel-title">1000 Genomes
<a href="#credit-vep" className="credit-vep" title="VEP"><span>VEP</span></a>
</h3>
);
}
},
// Method to render ESP population table header content
renderEspHeader: function(hasEspData, loading_myVariantInfo, esp, singleNucleotide) {
if (hasEspData && !loading_myVariantInfo && singleNucleotide) {
const variantEsp = esp._extra.rsid + '; ' + esp._extra.chrom + '.' + esp._extra.hg19_start + '; Alleles ' + esp._extra.ref + '>' + esp._extra.alt;
const linkoutEsp = dbxref_prefix_map['ESP_EVS'] + 'searchBy=rsID&target=' + esp._extra.rsid + '&x=0&y=0';
return (
<h3 className="panel-title">Exome Sequencing Project (ESP): {variantEsp} (GRCh37)
<a href="#credit-myvariant" className="credit-myvariant" title="MyVariant.info"><span>MyVariant</span></a>
<a className="panel-subtitle pull-right" href={linkoutEsp} target="_blank">See data in ESP</a>
</h3>
);
} else {
return (
<h3 className="panel-title">Exome Sequencing Project (ESP)
<a href="#credit-myvariant" className="credit-myvariant" title="MyVariant.info"><span>MyVariant</span></a>
</h3>
);
}
},
/**
* Sort population data table by allele frequency from highest to lowest
*/
sortObjKeys(obj) {
let arr = []; // Array converted from object
let filteredArray = []; // filtered array without the '_tot' and '_extra' key/value pairs
let sortedArray = []; // Sorting the filtered array from highest to lowest allele frequency
let sortedKeys = []; // Sorted order for the rendering of populations
if (Object.keys(obj).length) {
arr = Object.entries(obj);
filteredArray = arr.filter(item => {
return item[0].indexOf('_') < 0;
});
sortedArray = filteredArray.sort((x, y) => y[1]['af'] - x[1]['af']);
sortedArray.forEach(item => {
sortedKeys.push(item[0]);
});
}
return sortedKeys;
},
render() {
var exacStatic = populationStatic.exac,
gnomADStatic = populationStatic.gnomAD,
tGenomesStatic = populationStatic.tGenomes,
espStatic = populationStatic.esp;
var highestMAF = this.state.populationObj && this.state.populationObj.highestMAF ? this.state.populationObj.highestMAF : null,
pageData = this.props.ext_pageData && this.props.ext_pageData.data ? this.props.ext_pageData.data : [], // Get PAGE data from response
pageVariant = this.props.ext_pageData && this.props.ext_pageData.variant ? this.props.ext_pageData.variant : null, // Get PAGE data from response
exac = this.state.populationObj && this.state.populationObj.exac ? this.state.populationObj.exac : null, // Get ExAC data from global population object
gnomAD = this.state.populationObj && this.state.populationObj.gnomAD ? this.state.populationObj.gnomAD : null, // Get gnomAD data from global population object
tGenomes = this.state.populationObj && this.state.populationObj.tGenomes ? this.state.populationObj.tGenomes : null,
esp = this.state.populationObj && this.state.populationObj.esp ? this.state.populationObj.esp : null; // Get ESP data from global population object
var desiredCI = this.state.populationObj && this.state.populationObj.desiredCI ? this.state.populationObj.desiredCI : CI_DEFAULT;
var populationObjDiffFlag = this.state.populationObjDiffFlag;
var singleNucleotide = this.state.ext_singleNucleotide;
var gnomadExac = this.state.ext_gnomadExac;
let exacSortedAlleleFrequency = this.sortObjKeys(exac);
let gnomADSortedAlleleFrequency = this.sortObjKeys(gnomAD);
const affiliation = this.props.affiliation, session = this.props.session;
return (
<div className="variant-interpretation population">
<PanelGroup accordion><Panel title="Population Criteria Evaluation" panelBodyClassName="panel-wide-content"
panelClassName="tab-population-panel-population" open>
{(this.state.data && this.state.interpretation) ?
<div className="row">
<div className="col-sm-12">
<CurationInterpretationForm renderedFormContent={criteriaGroup1}
evidenceData={this.state.populationObj} evidenceDataUpdated={populationObjDiffFlag} formChangeHandler={criteriaGroup1Change}
formDataUpdater={criteriaGroup1Update} variantUuid={this.state.data['@id']}
criteria={['BA1', 'PM2', 'BS1']} criteriaCrossCheck={[['BA1', 'PM2', 'BS1']]}
interpretation={this.state.interpretation} updateInterpretationObj={this.props.updateInterpretationObj}
affiliation={affiliation} session={session} />
</div>
</div>
: null}
{populationObjDiffFlag ?
<div className="row">
<p className="alert alert-warning">
<strong>Notice:</strong> Some of the data retrieved below has changed since the last time you evaluated these criteria. Please update your evaluation as needed.
</p>
</div>
: null}
<div className="bs-callout bs-callout-info clearfix">
<h4>Subpopulation with Highest Minor Allele Frequency</h4>
<p className="header-note">Note: this calculation does not currently include PAGE study minor allele data</p>
<p>This reflects the highest MAF observed, as calculated by the interface, across all subpopulations in the versions of gnomAD, ExAC, 1000 Genomes, and ESP shown below.</p>
<div className="clearfix">
<div className="bs-callout-content-container">
<dl className="inline-dl clearfix">
<dt>Subpopulation: </dt><dd>{highestMAF && highestMAF.popLabel ? highestMAF.popLabel : 'N/A'}</dd>
<dt># Variant Alleles: </dt><dd>{highestMAF && highestMAF.ac ? highestMAF.ac : 'N/A'}</dd>
<dt>Total # Alleles Tested: </dt><dd>{highestMAF && highestMAF.ac_tot ? highestMAF.ac_tot : 'N/A'}</dd>
</dl>
</div>
<div className="bs-callout-content-container">
<dl className="inline-dl clearfix">
<dt>Source: </dt><dd>{highestMAF && highestMAF.source ? highestMAF.source : 'N/A'}</dd>
<dt>Allele Frequency: </dt><dd>{highestMAF && (highestMAF.af || highestMAF.af === 0) ? this.parseFloatShort(highestMAF.af) : 'N/A'}</dd>
{(this.state.interpretation && highestMAF) ?
<span>
<dt className="dtFormLabel">Desired CI:</dt>
<dd className="ddFormInput">
<Input type="number" inputClassName="desired-ci-input" ref="desiredCI" value={desiredCI} handleChange={this.changeDesiredCI} inputDisabled={true}
onBlur={this.onBlurDesiredCI} minVal={0} maxVal={100} maxLength="2" placeholder={CI_DEFAULT.toString()} />
</dd>
<dt>CI - lower: </dt><dd>{this.state.CILow || this.state.CILow === 0 ? this.parseFloatShort(this.state.CILow) : ''}</dd>
<dt>CI - upper: </dt><dd>{this.state.CIHigh || this.state.CIHigh === 0 ? this.parseFloatShort(this.state.CIHigh) : ''}</dd>
</span>
: null}
</dl>
</div>
</div>
<br/>
<p className="exac-pop-note">Note: ExAC Constraint Scores displayed on the Gene-centric tab</p>
</div>
<div className="panel panel-info datasource-gnomAD">
<div className="panel-heading">
{this.renderExacGnomadHeader(this.state.hasGnomadData, this.state.loading_myVariantInfo, gnomAD, gnomadExac, this.props.ext_myVariantInfo, this.props.ext_myVariantInfo_metadata, 'gnomAD')}
</div>
<div className="panel-content-wrapper">
{this.state.loading_myVariantInfo ? showActivityIndicator('Retrieving data... ') : null}
{!gnomadExac ?
<div className="panel-body">
<span>Data is currently only returned for single nucleotide variants and for some small duplications, insertions, and deletions. {this.renderExacGnomadLinkout(this.props.ext_myVariantInfo, 'gnomAD')}</span>
</div>
:
<div>
{this.state.hasGnomadData ?
<div>
{this.renderExacGnomadAddlInfo(gnomAD, 'gnomAD')}
<table className="table">
<thead>
<tr>
<th>Population</th>
<th>Allele Count</th>
<th>Allele Number</th>
<th>Number of Homozygotes</th>
<th>Allele Frequency</th>
</tr>
</thead>
<tbody>
{gnomADSortedAlleleFrequency.map(key => {
return (this.renderExacGnomadRow(key, gnomAD, gnomADStatic));
})}
</tbody>
<tfoot>
{this.renderExacGnomadRow('_tot', gnomAD, gnomADStatic, 'Total', 'count')}
</tfoot>
</table>
</div>
:
<div className="panel-body">
<span>No population data was found for this allele in gnomAD. {this.renderExacGnomadLinkout(this.props.ext_myVariantInfo, 'gnomAD')}</span>
</div>
}
</div>
}
</div>
</div>
<div className="panel panel-info datasource-ExAC">
<div className="panel-heading">
{this.renderExacGnomadHeader(this.state.hasExacData, this.state.loading_myVariantInfo, exac, gnomadExac, this.props.ext_myVariantInfo, this.props.ext_myVariantInfo_metadata, 'ExAC')}
</div>
<div className="panel-content-wrapper">
{this.state.loading_myVariantInfo ? showActivityIndicator('Retrieving data... ') : null}
{!gnomadExac ?
<div className="panel-body">
<span>Data is currently only returned for single nucleotide variants and for some small duplications, insertions, and deletions. {this.renderExacGnomadLinkout(this.props.ext_myVariantInfo, 'ExAC')}</span>
</div>
:
<div>
{this.state.hasExacData ?
<div>
{this.renderExacGnomadAddlInfo(exac, 'ExAC')}
<table className="table">
<thead>
<tr>
<th>Population</th>
<th>Allele Count</th>
<th>Allele Number</th>
<th>Number of Homozygotes</th>
<th>Allele Frequency</th>
</tr>
</thead>
<tbody>
{exacSortedAlleleFrequency.map(key => {
return (this.renderExacGnomadRow(key, exac, exacStatic));
})}
</tbody>
<tfoot>
{this.renderExacGnomadRow('_tot', exac, exacStatic, 'Total', 'count')}
</tfoot>
</table>
</div>
:
<div className="panel-body">
<span>No population data was found for this allele in ExAC. {this.renderExacGnomadLinkout(this.props.ext_myVariantInfo, 'ExAC')}</span>
</div>
}
</div>
}
</div>
</div>
<div className="panel panel-info datasource-PAGE">
<div className="panel-heading">
{this.renderPageHeader(this.state.hasPageData, this.state.loading_pageData, pageVariant, singleNucleotide)}
</div>
<div className="panel-content-wrapper">
{this.state.loading_pageData ? showActivityIndicator('Retrieving data... ') : null}
{!singleNucleotide ?
<div className="panel-body">
<span>Data is currently only returned for single nucleotide variants. <a href="http://popgen.uchicago.edu/ggv/" target="_blank" rel="noopener noreferrer">Search GGV</a> for this variant.</span>
</div>
:
<div>
{this.state.hasPageData ?
<div>
<table className="table">
<thead>
<tr>
<th>Population</th>
<th>Allele Number</th>
<th colSpan="2">Allele Frequency</th>
</tr>
</thead>
<tbody>
{pageData.length ?
pageData.map((item, i) => {
return (this.renderPageRow(item, i));
})
: null}
</tbody>
</table>
</div>
:
<div className="panel-body">
{session && session.user_properties && session.user_properties.email === '[email protected]' ?
<span>PAGE population data is not available to demo users. Please login or request an account for the ClinGen interfaces by emailing the <a href='mailto:[email protected]'>[email protected] <i className="icon icon-envelope"></i></a>.</span>
:
<span>No population data was found for this allele in PAGE. <a href="http://popgen.uchicago.edu/ggv/" target="_blank" rel="noopener noreferrer">Search GGV</a> for this variant.</span>
}
</div>
}
</div>
}
</div>
</div>
<div className="panel panel-info datasource-1000G">
<div className="panel-heading">
{this.renderTGenomesHeader(this.state.hasTGenomesData, this.state.loading_ensemblVariation, tGenomes, singleNucleotide)}
</div>
<div className="panel-content-wrapper">
{this.state.loading_ensemblVariation ? showActivityIndicator('Retrieving data... ') : null}
{!singleNucleotide ?
<div className="panel-body">
<span>Data is currently only returned for single nucleotide variants. <a href={external_url_map['1000GenomesHome']} target="_blank">Search 1000 Genomes</a> for this variant.</span>
</div>
:
<div>
{this.state.hasTGenomesData ?
<table className="table">
<thead>
<tr>
<th>Population</th>
<th colSpan="2">Allele Frequency (count)</th>
<th colSpan="3">Genotype Frequency (count)</th>
</tr>
</thead>
<tbody>
{this.renderTGenomesRow('_tot', tGenomes, tGenomesStatic, 'ALL')}
{tGenomesStatic._order.map(key => {
return (this.renderTGenomesRow(key, tGenomes, tGenomesStatic));
})}
</tbody>
</table>
:
<div className="panel-body">
<span>No population data was found for this allele in 1000 Genomes. <a href={external_url_map['1000GenomesHome']} target="_blank">Search 1000 Genomes</a> for this variant.</span>
</div>
}
</div>
}
</div>
</div>
<div className="panel panel-info datasource-ESP">
<div className="panel-heading">
{this.renderEspHeader(this.state.hasEspData, this.state.loading_myVariantInfo, esp, singleNucleotide)}
</div>
<div className="panel-content-wrapper">
{this.state.loading_myVariantInfo ? showActivityIndicator('Retrieving data... ') : null}
{!singleNucleotide ?
<div className="panel-body">
<span>Data is currently only returned for single nucleotide variants. <a href={external_url_map['ESPHome']} target="_blank">Search ESP</a> for this variant.</span>
</div>
:
<div>
{this.state.hasEspData ?
<table className="table">
<thead>
<tr>
<th>Population</th>
<th colSpan="2">Allele Count</th>
<th colSpan="3">Genotype Count</th>
</tr>
</thead>
<tbody>
{espStatic._order.map(key => {
return (this.renderEspRow(key, esp, espStatic));
})}
{this.renderEspRow('_tot', esp, espStatic, 'All Allele', 'count')}
</tbody>
<tfoot>
<tr className="count">
<td colSpan="6">Average Sample Read Depth: {esp._extra.avg_sample_read}</td>
</tr>
</tfoot>
</table>
:
<div className="panel-body">
<span>No population data was found for this allele in ESP. <a href={external_url_map['ESPHome']} target="_blank">Search ESP</a> for this variant.</span>
</div>
}
</div>
}
</div>
</div>
<extraEvidence.ExtraEvidenceTable category="population" subcategory="population" session={session}
href_url={this.props.href_url} tableName={<span>Curated Literature Evidence (Population)</span>}
variant={this.state.data} interpretation={this.state.interpretation} updateInterpretationObj={this.props.updateInterpretationObj}
viewOnly={this.state.data && !this.state.interpretation} affiliation={affiliation} criteriaList={['BA1', 'BS1', 'PM2']} />
</Panel></PanelGroup>
{this.state.interpretation ?
<CompleteSection interpretation={this.state.interpretation} tabName="population" updateInterpretationObj={this.props.updateInterpretationObj} />
: null}
{renderDataCredit('pagestudy')}
{renderDataCredit('myvariant')}
{renderDataCredit('vep')}
</div>
);
}
});
// code for rendering of this group of interpretation forms
var criteriaGroup1 = function() {
let criteriaList1 = ['BA1', 'BS1', 'PM2']; // array of criteria code handled subgroup of this section
let mafCutoffInput = (
<span>
<Input type="number" ref="maf-cutoff" label="MAF cutoff:" minVal={0} maxVal={100} maxLength="2" handleChange={this.handleFormChange}
value={this.state.evidenceData && this.state.evidenceData.mafCutoff ? this.state.evidenceData.mafCutoff : "5"} inputDisabled={true}
labelClassName="col-xs-1 control-label maf-cutoff-input-label" wrapperClassName="col-xs-1 input-right maf-cutoff-input"
groupClassName="form-group" onBlur={mafCutoffBlur.bind(this)} />
<span className="col-xs-1 after-input">%</span>
<div className="clear"></div>
</span>
);
return (
<div>
{vciFormHelper.renderEvalFormSection.call(this, criteriaList1, false)}
{mafCutoffInput}
</div>
);
};
// code for updating the form values of interpretation forms upon receiving
// existing interpretations and evaluations
var criteriaGroup1Update = function(nextProps) {
// define custom form update function for MAF Cutoff field in BA1
let mafCutoffUpdate = function(evaluation) {
this.refs['maf-cutoff'].setValue(evaluation.population.populationData.mafCutoff);
};
// add custom form update functions into customActions dictionary
let customActions = {
'BA1': mafCutoffUpdate
};
vciFormHelper.updateEvalForm.call(this, nextProps, ['BA1', 'PM2', 'BS1'], customActions);
};
// code for handling logic within the form
var criteriaGroup1Change = function(ref, e) {
// if the MAF cutoff field is changed, update the populationObj payload with the updated value
if (ref === 'maf-cutoff') {
let tempEvidenceData = this.state.evidenceData;
tempEvidenceData.mafCutoff = parseInt(this.refs[ref].getValue());
this.setState({evidenceData: tempEvidenceData});
}
};
// special function to handle the MAF cutoff % field
var mafCutoffBlur = function(event) {
let mafCutoff = parseInt(this.refs['maf-cutoff'].getValue());
if (mafCutoff == '' || isNaN(mafCutoff)) {
let tempEvidenceData = this.state.evidenceData;
// if the user clicks away from the MAF cutoff field, but it is blank/filled with
// bad input, re-set it to the default value of 5
this.refs['maf-cutoff'].setValue(5);
tempEvidenceData.mafCutoff = 5;
this.setState({evidenceData: tempEvidenceData});
}
};
|
src/index.js | christiannaths/supergroups | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './reset.css';
import './index.css';
ReactDOM.render(<App />, document.getElementById('root'));
|
ui/app/components/wizard/provider_select_stage.js | leapcode/bitmask-dev | import React from 'react'
import {Button, ButtonGroup, ButtonToolbar, Glyphicon} from 'react-bootstrap'
import App from 'app'
import Provider from 'models/provider'
import Language from 'lib/language'
import ListEditor from 'components/list_editor'
import {HorizontalLayout, Column} from 'components/layout'
import StageLayout from './stage_layout'
import AddProviderModal from './add_provider_modal'
const SERVICE_MAP = {
mx: "Mail",
openvpn: "VPN",
chat: "Chat"
}
export default class ProviderSelectStage extends React.Component {
static get defaultProps() {return{
title: "Choose a provider",
initialProvider: null
}}
constructor(props) {
super(props)
this.state = {
domains: [], // array of domains, as strings
showModal: false,
selected: null, // domain of selected item
provider: null, // Provider object, if selected
error: null // error message
}
this.add = this.add.bind(this)
this.remove = this.remove.bind(this)
this.select = this.select.bind(this)
this.close = this.close.bind(this)
this.cancel = this.cancel.bind(this)
this.next = this.next.bind(this)
this.onKeyDown = this.onKeyDown.bind(this)
}
componentWillMount() {
this.refreshList({
provider: this.props.initialProvider,
selected: (this.props.initialProvider ? this.props.initialProvider.domain : null)
})
}
//
// newState is the state to apply after
// domains are refreshed
//
refreshList(newState=null) {
Provider.list(true).then(domains => {
this.setState(Object.assign({domains: domains}, newState))
if (domains.length > 0) {
let domain = this.state.selected
if (domains.includes(domain)) {
this.select(domain)
} else {
this.select(domains[0])
}
} else {
this.select(null)
}
})
}
add() {
this.setState({showModal: true})
}
remove(domain, newactive) {
Provider.delete(domain).then(
response => {
this.refreshList({selected: newactive})
},
error => {
console.log(error)
}
)
}
select(domain) {
this.setState({
selected: domain
})
if (domain) {
Provider.get(domain).then(
provider => {
this.setState({
provider: provider
})
},
error => {
this.setState({
provider: null,
error: error
})
}
)
} else {
this.setState({
provider: null,
error: null
})
}
}
close(provider=null) {
if (provider) {
this.refreshList({
showModal: false,
provider: provider,
selected: provider.domain
})
} else {
this.setState({
showModal: false
})
}
}
cancel() {
App.start()
}
next() {
App.show('wizard', {
stage: 'register',
provider: this.state.provider
})
}
onKeyDown(e) {
// Check for enter key
if (e.keyCode === 13) {
this.next();
}
}
render() {
let modal = null
let info = null
if (this.state.provider) {
let languages = this.state.provider.languages.map(code => Language.find(code).name)
let services = this.state.provider.services.map(code => SERVICE_MAP[code] || '????')
info = (
<div>
<h1 className="first">{this.state.provider.name}</h1>
<h3>{this.state.provider.domain}</h3>
<p>{this.state.provider.description}</p>
<p><b>Enrollment Policy:</b> {this.state.provider.enrollment_policy}</p>
<p><b>Services</b>: {services.join(', ')}</p>
<p><b>Languages</b>: {languages.join(', ')}</p>
</div>
)
} else if (this.state.error) {
info = <div>{this.state.error}</div>
}
if (this.state.showModal) {
modal = <AddProviderModal onClose={this.close} />
}
let buttons = (
<div>
<ButtonToolbar className="pull-left">
<Button onClick={this.cancel}>
Cancel
</Button>
</ButtonToolbar>
<ButtonToolbar className="pull-right">
<Button onClick={this.next}>
Next
<Glyphicon glyph="chevron-right" />
</Button>
</ButtonToolbar>
</div>
)
let editlist = <ListEditor
ref="list"
items={this.state.domains}
selected={this.state.selected}
onRemove={this.remove}
onAdd={this.add}
onSelect={this.select}
onKeyDown={this.onKeyDown}
/>
return(
<StageLayout title={this.props.title} subtitle={this.props.subtitle} buttons={buttons}>
<HorizontalLayout equalWidths={true}>
<Column>{editlist}</Column>
<Column>{info}</Column>
</HorizontalLayout>
{modal}
</StageLayout>
)
}
}
|
app/containers/App/index.js | Quinn-Donnelly/poller | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
classic/src/scenes/mailboxes/src/Scenes/AccountWizardScene/ServiceAttachWizardScene/WizardPersonalise.js | wavebox/waveboxapp | import PropTypes from 'prop-types'
import React from 'react'
import shallowCompare from 'react-addons-shallow-compare'
import { Button } from '@material-ui/core'
import { withStyles } from '@material-ui/core/styles'
import classNames from 'classnames'
import lightBlue from '@material-ui/core/colors/lightBlue'
import StyleMixins from 'wbui/Styles/StyleMixins'
import WizardPersonaliseGeneric from '../Common/WizardPersonalise/WizardPersonaliseGeneric'
import WizardPersonaliseContainer from '../Common/WizardPersonalise/WizardPersonaliseContainer'
import SERVICE_TYPES from 'shared/Models/ACAccounts/ServiceTypes'
const styles = {
// Layout
container: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0
},
body: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 68,
padding: 16,
...StyleMixins.scrolling.alwaysShowVerticalScrollbars
},
footer: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
height: 68,
padding: 16,
textAlign: 'right'
},
// Typography
heading: {
fontWeight: 300,
marginTop: 40
},
subHeading: {
fontWeight: 300,
marginTop: -10,
fontSize: 16
},
// Elements
colorPicker: {
display: 'inline-block',
maxWidth: '100%'
},
servicesPurchaseContainer: {
border: `2px solid ${lightBlue[500]}`,
borderRadius: 4,
padding: 16,
display: 'block'
},
// Footer
footerCancelButton: {
marginRight: 8
}
}
@withStyles(styles)
class WizardPersonalise extends React.Component {
/* **************************************************************************/
// Class
/* **************************************************************************/
static propTypes = {
serviceType: PropTypes.string.isRequired,
accessMode: PropTypes.string.isRequired,
onRequestNext: PropTypes.func.isRequired,
onRequestCancel: PropTypes.func.isRequired
}
/* **************************************************************************/
// Lifecycle
/* **************************************************************************/
constructor (props) {
super(props)
this.customPersonalizeRef = null
}
/* **************************************************************************/
// UI Events
/* **************************************************************************/
/**
* Handles the user pressing next
*/
handleNext = () => {
if (this.customPersonalizeRef) {
const { ok, serviceJS } = this.customPersonalizeRef.updateAttachingService({})
if (ok) {
this.props.onRequestNext(serviceJS)
}
} else {
this.props.onRequestNext({})
}
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
render () {
const {
serviceType,
accessMode,
onRequestCancel,
onRequestNext,
classes,
className,
...passProps
} = this.props
return (
<div {...passProps} className={classNames(classes.container, className)}>
<div className={classes.body}>
{serviceType === SERVICE_TYPES.GENERIC ? (
<WizardPersonaliseGeneric
innerRef={(n) => { this.customPersonalizeRef = n }}
onRequestNext={this.handleNext}
accessMode={accessMode} />
) : undefined}
{serviceType === SERVICE_TYPES.CONTAINER ? (
<WizardPersonaliseContainer
innerRef={(n) => { this.customPersonalizeRef = n }}
onRequestNext={this.handleNext}
accessMode={accessMode} />
) : undefined}
</div>
<div className={classes.footer}>
<Button className={classes.footerCancelButton} onClick={onRequestCancel}>
Cancel
</Button>
<Button color='primary' variant='contained' onClick={this.handleNext}>
Next
</Button>
</div>
</div>
)
}
}
export default WizardPersonalise
|
src/js/containers/DevTools.js | petemill/bernie-activism-priorities | import React from 'react';
import { createDevTools } from 'redux-devtools';
// Monitors are separate packages, and you can make a custom one
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
// createDevTools takes a monitor and produces a DevTools component
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-q">
<LogMonitor theme="nicinabox" />
</DockMonitor>
);
|
app/javascript/mastodon/features/trends/index.js | MastodonCloud/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { connect } from 'react-redux';
import { injectIntl, defineMessages } from 'react-intl';
import Column from '../ui/components/column';
import ColumnHeader from '../../components/column_header';
import Hashtag from '../../components/hashtag';
import classNames from 'classnames';
import { fetchTrends } from '../../actions/trends';
const messages = defineMessages({
title: { id: 'trends.header', defaultMessage: 'Trending now' },
refreshTrends: { id: 'trends.refresh', defaultMessage: 'Refresh trends' },
});
const mapStateToProps = state => ({
trends: state.getIn(['trends', 'items']),
loading: state.getIn(['trends', 'isLoading']),
});
const mapDispatchToProps = dispatch => ({
fetchTrends: () => dispatch(fetchTrends()),
});
@connect(mapStateToProps, mapDispatchToProps)
@injectIntl
export default class Trends extends ImmutablePureComponent {
static propTypes = {
intl: PropTypes.object.isRequired,
trends: ImmutablePropTypes.list,
fetchTrends: PropTypes.func.isRequired,
loading: PropTypes.bool,
};
componentDidMount () {
this.props.fetchTrends();
}
handleRefresh = () => {
this.props.fetchTrends();
}
render () {
const { trends, loading, intl } = this.props;
return (
<Column>
<ColumnHeader
icon='fire'
title={intl.formatMessage(messages.title)}
extraButton={(
<button className='column-header__button' title={intl.formatMessage(messages.refreshTrends)} aria-label={intl.formatMessage(messages.refreshTrends)} onClick={this.handleRefresh}><i className={classNames('fa', 'fa-refresh', { 'fa-spin': loading })} /></button>
)}
/>
<div className='scrollable'>
{trends && trends.map(hashtag => <Hashtag key={hashtag.get('name')} hashtag={hashtag} />)}
</div>
</Column>
);
}
}
|
src/svg-icons/image/filter-tilt-shift.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilterTiltShift = (props) => (
<SvgIcon {...props}>
<path d="M11 4.07V2.05c-2.01.2-3.84 1-5.32 2.21L7.1 5.69c1.11-.86 2.44-1.44 3.9-1.62zm7.32.19C16.84 3.05 15.01 2.25 13 2.05v2.02c1.46.18 2.79.76 3.9 1.62l1.42-1.43zM19.93 11h2.02c-.2-2.01-1-3.84-2.21-5.32L18.31 7.1c.86 1.11 1.44 2.44 1.62 3.9zM5.69 7.1L4.26 5.68C3.05 7.16 2.25 8.99 2.05 11h2.02c.18-1.46.76-2.79 1.62-3.9zM4.07 13H2.05c.2 2.01 1 3.84 2.21 5.32l1.43-1.43c-.86-1.1-1.44-2.43-1.62-3.89zM15 12c0-1.66-1.34-3-3-3s-3 1.34-3 3 1.34 3 3 3 3-1.34 3-3zm3.31 4.9l1.43 1.43c1.21-1.48 2.01-3.32 2.21-5.32h-2.02c-.18 1.45-.76 2.78-1.62 3.89zM13 19.93v2.02c2.01-.2 3.84-1 5.32-2.21l-1.43-1.43c-1.1.86-2.43 1.44-3.89 1.62zm-7.32-.19C7.16 20.95 9 21.75 11 21.95v-2.02c-1.46-.18-2.79-.76-3.9-1.62l-1.42 1.43z"/>
</SvgIcon>
);
ImageFilterTiltShift = pure(ImageFilterTiltShift);
ImageFilterTiltShift.displayName = 'ImageFilterTiltShift';
ImageFilterTiltShift.muiName = 'SvgIcon';
export default ImageFilterTiltShift;
|
frontend/components/player/Duration.js | BootstrapBETA/GAAMER | import React from 'react'
export default function Duration ({ className, seconds }) {
return (
<time dateTime={`P${Math.round(seconds)}S`} className={className}>
{format(seconds)}
</time>
)
}
function format (seconds) {
const date = new Date(seconds * 1000)
const hh = date.getHours()
const mm = date.getMinutes()
const ss = pad(date.getSeconds())
if (hh) {
return `${pad(mm)}:${ss}`
}
return `${mm}:${ss}`
}
function pad (string) {
return ('0' + string).slice(-2)
}
|
react/src/containers/FileMassActions/index.js | sinfin/folio | import React from 'react'
import { connect } from 'react-redux'
import {
massDelete,
massCancel,
makeMassSelectedIdsSelector
} from 'ducks/files'
import FileMassActionsWrap from './styled/FileMassActionsWrap'
function downloadHref (filesUrl, massSelectedIds) {
return `${filesUrl}/mass_download?ids=${massSelectedIds.join(',')}`
}
function FileMassActions ({ massSelectedIds, massSelectedIndestructibleIds, fileType, dispatchMassCancel, dispatchMassDelete, filesUrl }) {
if (massSelectedIds.length === 0) return null
const indestructible = massSelectedIndestructibleIds.length > 0
let notAllowedCursor = ''
if (indestructible) {
notAllowedCursor = 'cursor-not-allowed'
}
return (
<FileMassActionsWrap className='mb-3 px-h py-2 bg-info d-flex align-items-center'>
<div className='mr-g d-flex'>
<strong className='d-block mr-2'>{massSelectedIds.length}</strong>
<span className='mi mi--20'>content_copy</span>
</div>
<div className='d-flex flex-wrap my-n2'>
<button
className={`btn btn-danger d-block mr-2 mr-sm-g my-2 font-weight-bold ${notAllowedCursor}`}
type='button'
title={indestructible ? window.FolioConsole.translations.indestructibleFiles : window.FolioConsole.translations.destroy}
onClick={indestructible ? undefined : () => dispatchMassDelete(fileType)}
disabled={indestructible}
>
<span className='fa fa-trash' />
{window.FolioConsole.translations.destroy}
</button>
<a
className='btn btn-secondary d-block mr-2 mr-sm-g my-2 font-weight-bold'
href={downloadHref(filesUrl, massSelectedIds)}
onClick={() => dispatchMassCancel(fileType)}
target='_blank'
rel='noopener noreferrer'
>
<span className='mi'>file_download</span>
{window.FolioConsole.translations.download}
</a>
</div>
<div className='ml-auto'>
<button
className='btn-unbutton px-2 py-1'
type='button'
onClick={() => dispatchMassCancel(fileType)}
>
<span className='fa fa-times' />
</button>
</div>
</FileMassActionsWrap>
)
}
const mapStateToProps = (state, props) => makeMassSelectedIdsSelector(props.fileType)(state)
function mapDispatchToProps (dispatch) {
return {
dispatchMassCancel: (fileType) => dispatch(massCancel(fileType)),
dispatchMassDelete: (fileType) => {
if (window.confirm(window.FolioConsole.translations.removePrompt)) {
dispatch(massDelete(fileType))
}
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(FileMassActions)
|
src/js/components/acl/modals/permission_manager_modal.js | rafaelfbs/realizejs | import React, { Component } from 'react';
import PropTypes from '../../../prop_types';
import $ from 'jquery';
import { autobind, mixin } from '../../../utils/decorators';
import { difference } from 'lodash';
import { Modal, ModalHeader, ModalContent, ModalFooter } from '../../../components/modal';
import CloseModalButton from './close_modal_button';
import PermissionManager from '../permission_manager';
import UpdatePermissionsButton from '../update_permission_button';
import { RequestHandlerMixin } from '../../../mixins';
@mixin(RequestHandlerMixin)
export default class PermissionManagerModal extends Component {
static propTypes = {
permissionManagerInModal: PropTypes.bool,
principal: PropTypes.object,
principalType: PropTypes.string,
resource: PropTypes.object,
resourceType: PropTypes.string,
className: PropTypes.string,
modalId: PropTypes.string,
updatePermissionsBaseUrl: PropTypes.string,
principalsBaseUrl: PropTypes.string,
principalsPermissionsBaseUrl: PropTypes.string,
title: PropTypes.string,
reloadPageAfterSubmit: PropTypes.bool,
headerSize: PropTypes.string,
handleRemovePrincipal: PropTypes.func,
};
static defaultProps = {
permissionManagerInModal: true,
principal: null,
principalType: '',
resource: null,
resourceType: '',
title: null,
className: 'permission-manager-modal',
modalId: 'permission-manager-modal',
updatePermissionsBaseUrl: '/wkm_acl_ui/bulk_permissions',
principalsBaseUrl: '/wkm_acl_ui/principals',
principalsPermissionsBaseUrl: '/wkm_acl_ui/principals/principals_permissions',
reloadPageAfterSubmit: false,
};
@autobind
onSuccess() {
$(`#${this.props.modalId}`).closeModal();
if (this.props.reloadPageAfterSubmit) {
window.location.reload();
}
}
getPostData() {
const principalPermissions = this.refs.permissionManager.state.principalsPermissions;
const postData = [];
for (let i = 0; i < principalPermissions.length; i++) {
if (!!principalPermissions[i].changed) {
const permissionsByPrincipal = principalPermissions[i].permissions;
let permissions = permissionsByPrincipal.map((a) => a.permission);
let implies = permissionsByPrincipal.map((a) => a.implies);
implies = [].concat.apply([], implies);
permissions = difference(permissions, implies);
postData.push({
principal_id: principalPermissions[i].principal_id,
principal_type: principalPermissions[i].principal_type,
permissions,
});
}
}
return {
resource_id: this.props.resource.id,
resource_type: this.props.resourceType,
permissions_by_principal: postData,
};
}
loadPrincipalsPermissions(selectedDatas) {
this.refs.permissionManager.createPrincipalsPermissions(selectedDatas);
}
@autobind
handleUpdatePermissions() {
const url = this.props.updatePermissionsBaseUrl;
const postData = this.getPostData();
const method = 'PUT';
this.performRequest(url, postData, method);
}
renderTitle() {
const component = [];
const title = !!this.props.title ?
this.props.title :
this.props.resource.name;
component.push(
<h5>Gerenciar Permissões - {title}</h5>
);
return component;
}
render() {
return (
<Modal
id={this.props.modalId}
className={this.props.className}
headerSize={this.props.headerSize}
opened
ref="modal"
>
<ModalHeader>
<h5>Gerenciar Permissões - {this.props.resource.name}</h5>
</ModalHeader>
<ModalContent>
<div className="permissions-modal-content">
<PermissionManager
ref="permissionManager"
handleRemovePrincipal={this.props.handleRemovePrincipal}
permissionManagerInModal={this.props.permissionManagerInModal}
principal={this.props.principal}
principalType={this.props.principalType}
resource={this.props.resource}
resourceType={this.props.resourceType}
principalsBaseUrl={this.props.principalsBaseUrl}
principalsPermissionsBaseUrl={this.props.principalsPermissionsBaseUrl}
/>
</div>
</ModalContent>
<ModalFooter>
<div className="modal-footer" style={{ float: 'right' }}>
<CloseModalButton modalId={this.props.modalId} />
<UpdatePermissionsButton handleUpdatePermissions={this.handleUpdatePermissions} />
</div>
</ModalFooter>
</Modal>
);
}
}
|
ReactNative/messagelist.ios.js | jpush/aurora-imui | 'use strict';
import React from 'react';
import ReactNative from 'react-native';
import PropTypes from 'prop-types';
import {ViewPropTypes} from 'react-native';
var {
Component,
} = React;
var {
StyleSheet,
requireNativeComponent,
} = ReactNative;
export default class MessageList extends Component {
constructor(props) {
super(props);
this._onMsgClick = this._onMsgClick.bind(this);
this._onMsgLongClick = this._onMsgLongClick.bind(this);
this._onAvatarClick = this._onAvatarClick.bind(this);
this._onStatusViewClick = this._onStatusViewClick.bind(this);
this._onPullToRefresh = this._onPullToRefresh.bind(this);
}
_onMsgClick(event: Event) {
if (!this.props.onMsgClick) {
return;
}
this.props.onMsgClick(event.nativeEvent.message);
}
_onMsgLongClick(event: Event) {
if (!this.props.onMsgLongClick) {
return;
}
this.props.onMsgLongClick(event.nativeEvent.message);
}
_onAvatarClick(event: Event) {
if (!this.props.onAvatarClick) {
return;
}
this.props.onAvatarClick(event.nativeEvent.message);
}
_onStatusViewClick(event: Event) {
if (!this.props.onStatusViewClick) {
return;
}
this.props.onStatusViewClick(event.nativeEvent.message);
}
_onBeginDragMessageList(event: Event) {
if (!this.props.onStatusViewClick) {
return;
}
this.props.onBeginDragMessageList();
}
_onPullToRefresh(event: Event) {
if (!this.props.onPullToRefresh) {
return;
}
this.props.onPullToRefresh();
}
render() {
return (
<RCTMessageList
{...this.props}
onMsgClick={this._onMsgClick}
onAvatarClick={this._onAvatarClick}
onMsgLongClick={this._onMsgLongClick}
onStatusViewClick={this._onStatusViewClick}
/>
);
}
}
MessageList.propTypes = {
onMsgClick: PropTypes.func,
onMsgLongClick: PropTypes.func,
onAvatarClick: PropTypes.func,
onStatusViewClick: PropTypes.func,
onBeginDragMessageList: PropTypes.func,
onTouchMsgList: PropTypes.func,
onPullToRefresh: PropTypes.func,
messageListBackgroundColor: PropTypes.string,
sendBubble: PropTypes.object,
receiveBubble: PropTypes.object,
sendBubbleTextColor: PropTypes.string,
receiveBubbleTextColor: PropTypes.string,
sendBubbleTextSize: PropTypes.number,
receiveBubbleTextSize: PropTypes.number,
sendBubblePadding: PropTypes.object,
receiveBubblePadding: PropTypes.object,
avatarSize: PropTypes.object,
avatarCornerRadius: PropTypes.number,
isShowDisplayName: PropTypes.bool,
isShowIncomingDisplayName: PropTypes.bool,
isShowOutgoingDisplayName: PropTypes.bool,
isAllowPullToRefresh: PropTypes.bool,
dateTextSize: PropTypes.number,
dateTextColor: PropTypes.string,
datePadding: PropTypes.object,
dateBackgroundColor: PropTypes.string,
dateCornerRadius: PropTypes.number,
eventTextPadding: PropTypes.object,
eventBackgroundColor: PropTypes.string,
eventTextColor: PropTypes.string,
eventTextSize: PropTypes.number,
eventCornerRadius: PropTypes.number,
displayNameTextSize: PropTypes.number,
displayNameTextColor: PropTypes.string,
displayNamePadding: PropTypes.object,
maxBubbleWidth: PropTypes.number,
eventTextLineHeight: PropTypes.number, //TODO:
messageTextLineHeight: PropTypes.number, //TODO:
...ViewPropTypes
};
var RCTMessageList = requireNativeComponent('RCTMessageListView', MessageList);
var styles = StyleSheet.create({
}); |
EEG101/src/components/DecisionButton.js | NeuroTechX/eeg-101 | // DecisionButton.js
// Round, bordered buttons for choosing BCI action type
import React, { Component } from 'react';
import {
Text,
View,
TouchableOpacity,
StyleSheet,
} from 'react-native';
import { MediaQueryStyleSheet } from 'react-native-responsive';
import * as colors from "../styles/colors";
export default class SandboxButton extends Component{
constructor(props){
super(props);
}
render() {
const dynamicButtonStyle = (this.props.active) ? styles.activeButton: styles.inactiveButton;
const dynamicTextStyle = (this.props.active) ? styles.activeText: styles.inactiveText;
return(
<TouchableOpacity onPress={this.props.onPress}>
<View style={[dynamicButtonStyle, {height: this.props.size, width: this.props.size}]}>
{this.props.children}
</View>
</TouchableOpacity>
)
}
};
const styles = MediaQueryStyleSheet.create(
{
// Base styles
activeButton: {
justifyContent: 'center',
backgroundColor: colors.malibu,
borderWidth: 2,
borderColor: colors.black,
elevation: 5,
alignItems: 'center',
borderRadius: 50,
},
inactiveButton: {
justifyContent: 'center',
backgroundColor: colors.white,
borderWidth: 2,
borderColor: colors.black,
elevation: 5,
alignItems: 'center',
borderRadius: 50,
},
},
// Responsive styles
{
"@media (min-device-height: 700)": {
activeButton: {
height: 50,
},
inactiveButton: {
height: 50,
},
activeText:{
fontSize: 25
},
inactiveText:{
fontSize: 25
},
}
});
|
src/components/ItemList.js | berrydanielt/redux_thunk_tutorial | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { itemsFetchData } from '../actions/items'
class ItemList extends Component {
componentDidMount(){
this.fetchData('http://5826ed963900d612000138bd.mockapi.io/items');
}
render() {
if (this.state.hasErrored) {
return <p>Sorry! There was an error loading the items</p>;
}
if (this.state.isLoading) {
return <p>Loading…</p>;
}
return (
<ul>
{this.state.items.map((item) => (
<li key={item.id}>
{item.label}
</li>
))}
</ul>
);
}
}
const mapStateToProps = (state) => {
return {
items: state.items,
hasErrored: state.itemsHasErrored,
isLoading: state.itemsIsLoading
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchData: (url) => dispatch(itemsFetchData(url))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ItemList);
|
packages/arwes/src/Appear/sandbox.js | romelperez/prhone-ui | import React from 'react';
import Appear from './index';
import Arwes from '../Arwes';
export default () => (
<Arwes>
<Appear animate>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
</Appear>
</Arwes>
);
|
node_modules/react-bootstrap/es/Collapse.js | darklilium/Factigis_2 | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import css from 'dom-helpers/style';
import React from 'react';
import Transition from 'react-overlays/lib/Transition';
import capitalize from './utils/capitalize';
import createChainedFunction from './utils/createChainedFunction';
var MARGINS = {
height: ['marginTop', 'marginBottom'],
width: ['marginLeft', 'marginRight']
};
// reading a dimension prop will cause the browser to recalculate,
// which will let our animations work
function triggerBrowserReflow(node) {
node.offsetHeight; // eslint-disable-line no-unused-expressions
}
function getDimensionValue(dimension, elem) {
var value = elem['offset' + capitalize(dimension)];
var margins = MARGINS[dimension];
return value + parseInt(css(elem, margins[0]), 10) + parseInt(css(elem, margins[1]), 10);
}
var propTypes = {
/**
* Show the component; triggers the expand or collapse animation
*/
'in': React.PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is collapsed
*/
unmountOnExit: React.PropTypes.bool,
/**
* Run the expand animation when the component mounts, if it is initially
* shown
*/
transitionAppear: React.PropTypes.bool,
/**
* Duration of the collapse animation in milliseconds, to ensure that
* finishing callbacks are fired even if the original browser transition end
* events are canceled
*/
timeout: React.PropTypes.number,
/**
* Callback fired before the component expands
*/
onEnter: React.PropTypes.func,
/**
* Callback fired after the component starts to expand
*/
onEntering: React.PropTypes.func,
/**
* Callback fired after the component has expanded
*/
onEntered: React.PropTypes.func,
/**
* Callback fired before the component collapses
*/
onExit: React.PropTypes.func,
/**
* Callback fired after the component starts to collapse
*/
onExiting: React.PropTypes.func,
/**
* Callback fired after the component has collapsed
*/
onExited: React.PropTypes.func,
/**
* The dimension used when collapsing, or a function that returns the
* dimension
*
* _Note: Bootstrap only partially supports 'width'!
* You will need to supply your own CSS animation for the `.width` CSS class._
*/
dimension: React.PropTypes.oneOfType([React.PropTypes.oneOf(['height', 'width']), React.PropTypes.func]),
/**
* Function that returns the height or width of the animating DOM node
*
* Allows for providing some custom logic for how much the Collapse component
* should animate in its specified dimension. Called with the current
* dimension prop value and the DOM node.
*/
getDimensionValue: React.PropTypes.func,
/**
* ARIA role of collapsible element
*/
role: React.PropTypes.string
};
var defaultProps = {
'in': false,
timeout: 300,
unmountOnExit: false,
transitionAppear: false,
dimension: 'height',
getDimensionValue: getDimensionValue
};
var Collapse = function (_React$Component) {
_inherits(Collapse, _React$Component);
function Collapse(props, context) {
_classCallCheck(this, Collapse);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleEnter = _this.handleEnter.bind(_this);
_this.handleEntering = _this.handleEntering.bind(_this);
_this.handleEntered = _this.handleEntered.bind(_this);
_this.handleExit = _this.handleExit.bind(_this);
_this.handleExiting = _this.handleExiting.bind(_this);
return _this;
}
/* -- Expanding -- */
Collapse.prototype.handleEnter = function handleEnter(elem) {
var dimension = this._dimension();
elem.style[dimension] = '0';
};
Collapse.prototype.handleEntering = function handleEntering(elem) {
var dimension = this._dimension();
elem.style[dimension] = this._getScrollDimensionValue(elem, dimension);
};
Collapse.prototype.handleEntered = function handleEntered(elem) {
var dimension = this._dimension();
elem.style[dimension] = null;
};
/* -- Collapsing -- */
Collapse.prototype.handleExit = function handleExit(elem) {
var dimension = this._dimension();
elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px';
triggerBrowserReflow(elem);
};
Collapse.prototype.handleExiting = function handleExiting(elem) {
var dimension = this._dimension();
elem.style[dimension] = '0';
};
Collapse.prototype._dimension = function _dimension() {
return typeof this.props.dimension === 'function' ? this.props.dimension() : this.props.dimension;
};
// for testing
Collapse.prototype._getScrollDimensionValue = function _getScrollDimensionValue(elem, dimension) {
return elem['scroll' + capitalize(dimension)] + 'px';
};
Collapse.prototype.render = function render() {
var _props = this.props,
onEnter = _props.onEnter,
onEntering = _props.onEntering,
onEntered = _props.onEntered,
onExit = _props.onExit,
onExiting = _props.onExiting,
className = _props.className,
props = _objectWithoutProperties(_props, ['onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'className']);
delete props.dimension;
delete props.getDimensionValue;
var handleEnter = createChainedFunction(this.handleEnter, onEnter);
var handleEntering = createChainedFunction(this.handleEntering, onEntering);
var handleEntered = createChainedFunction(this.handleEntered, onEntered);
var handleExit = createChainedFunction(this.handleExit, onExit);
var handleExiting = createChainedFunction(this.handleExiting, onExiting);
var classes = {
width: this._dimension() === 'width'
};
return React.createElement(Transition, _extends({}, props, {
'aria-expanded': props.role ? props['in'] : null,
className: classNames(className, classes),
exitedClassName: 'collapse',
exitingClassName: 'collapsing',
enteredClassName: 'collapse in',
enteringClassName: 'collapsing',
onEnter: handleEnter,
onEntering: handleEntering,
onEntered: handleEntered,
onExit: handleExit,
onExiting: handleExiting
}));
};
return Collapse;
}(React.Component);
Collapse.propTypes = propTypes;
Collapse.defaultProps = defaultProps;
export default Collapse; |
src/routes/PersonalInformation/components/PersonalInformation.js | dannyrdalton/example_signup_flow | import React from 'react'
import { Field } from 'redux-form'
import { Link } from 'react-router'
import { FORM_FIELDS } from '../config/personal_information_config'
export const PersonalInformation = (props) => (
<div>
<h2>Personal Information</h2>
<form>
{FORM_FIELDS.map(field =>
<Field
{...field} /
>
)}
</form>
<div>
<button className="btn btn-default" onClick={props.next} disabled={!props.valid}>Next</button>
</div>
</div>
)
export default PersonalInformation
|
src/containers/Home/Home.js | jahrlin/isomorphic-flux-react-react-router | import React from 'react';
import { Link } from 'react-router';
class Home extends React.Component {
render() {
return (
<div className="home">
<h2>This is the <Home> component</h2>
<ul className="links">
<li className="links__item">
<i className="fa fa-check" aria-hidden="true"></i>
<Link to="subroute/">A subroute</Link>
</li>
<li className="links__item">
<i className="fa fa-check" aria-hidden="true"></i>
<Link to="parameters/value/">Parameters</Link>
</li>
<li className="links__item">
<i className="fa fa-check" aria-hidden="true"></i>
<Link to="asyncdata/">A route that fetches data asynchronuously</Link>
</li>
</ul>
</div>
);
}
}
export default Home;
|
services/ui/src/components/errors/ProblemNotFound.js | amazeeio/lagoon | import React from 'react';
import ErrorPage from 'pages/_error';
export default ({ variables }) => (
<ErrorPage
statusCode={404}
errorMessage={`Problem "${variables.id}" not found`}
/>
); |
client/src/components/About.js | Velocies/raptor-ads | import React from 'react';
import { Link } from 'react-router';
import { Item, Statistic, Container, Grid, Divider, Image, Card } from 'semantic-ui-react';
const About = () =>
<Container textAlign="center" className="about" fluid>
<Grid columns={1}>
<Grid.Column>
<Grid.Row>
<Item.Image
as={Link}
to="landing"
size="small"
src="/client/src/assets/full-raptor.png"
/>
<Item.Content verticalAlign="center">
<Statistic
size="large"
color="black"
value="MEET THE TEAM"
/>
</Item.Content>
</Grid.Row>
<Divider hidden />
<Divider section hidden />
<Grid.Row className="ui center aligned grid">
<Card.Group stackable>
<Card>
<Card.Content>
<Image centered size="medium" shape="rounded" src="http://bit.ly/2pRshhC" />
<Divider />
<Card.Header>Jimmie Gisclair</Card.Header>
<Card.Meta>
<p>
<a href="https://www.linkedin.com/in/jimmie-gisclair/">LinkedIn</a>
</p>
<p>
<a href="https://github.com/Darkrender">GitHub</a>
</p>
<p>
<a href="https://jimmiegisclair.wordpress.com/">Blog</a>
</p>
</Card.Meta>
</Card.Content>
</Card>
<Card>
<Card.Content>
<Image centered size="medium" shape="rounded" src="https://media.licdn.com/mpr/mpr/shrinknp_400_400/AAEAAQAAAAAAAAnIAAAAJDQ5ZGQ2MmQyLThjYWItNDYyYi1iNzQ5LWQzYTc0ZGM1OGFiYQ.jpg" />
<Divider />
<Card.Header>Cory Wolnewitz</Card.Header>
<Card.Meta>
<Card.Meta>
<p>
<a href="https://www.linkedin.com/in/cory-wolnewitz/">LinkedIn</a>
</p>
<p>
<a href="https://github.com/wolnewitz">GitHub</a>
</p>
<p>
<a href="https://codecor.wordpress.com/">Blog</a>
</p>
</Card.Meta>
</Card.Meta>
</Card.Content>
</Card>
<Card>
<Card.Content>
<Image centered size="medium" shape="rounded" src="https://media.licdn.com/mpr/mpr/shrinknp_400_400/AAEAAQAAAAAAAAtOAAAAJDU5MTQ2MjFkLTU2NGYtNDg0Yi1iYjA1LWUyNjcxZWQyOThhYw.jpg" />
<Divider />
<Card.Header>Bobby Phan</Card.Header>
<Card.Meta>
<p>
<a href="https://www.linkedin.com/in/bobby-phan-393b53135/">LinkedIn</a>
</p>
<p>
<a href="https://github.com/bwuphan">GitHub</a>
</p>
</Card.Meta>
</Card.Content>
</Card>
<Card>
<Card.Content>
<Image centered size="medium" shape="rounded" src="https://i.gyazo.com/e6894fc283b7d1f8dda70737ccde1203.png" />
<Divider />
<Card.Header>Tyler Mackay</Card.Header>
<Card.Meta>
<p>
<a href="https://github.com/tylermackay587">GitHub</a>
</p>
</Card.Meta>
</Card.Content>
</Card>
</Card.Group>
</Grid.Row>
<Divider section hidden />
<Divider section hidden />
<Divider section hidden />
<Divider section hidden />
<Grid.Row>
<Container textAlign="center">
<Item.Content>
<Statistic
size="large"
color="black"
value="TECH STACK"
/>
</Item.Content>
<Divider hidden />
<Image.Group size="medium">
<Image src="http://blog-assets.risingstack.com/2016/Jan/react_best_practices-1453211146748.png" />
<Image src="https://raw.githubusercontent.com/reactjs/redux/master/logo/logo-title-dark.png" />
<Image src="https://www.computersnyou.com/wp-content/uploads/2014/12/postgresql-logo.png" />
<Image src="http://techforgeek.com/wp-content/uploads/2015/01/nodejs-logo.png" />
<Image src="http://www.userlogos.org/files/logos/3_gumanov/google_maps1.png?1445141432" />
<Image src="https://s-media-cache-ak0.pinimg.com/originals/27/e2/f8/27e2f81f0b20c79a2b6dd093f06062d1.png" />
<Image shape="rounded" src="http://i.imgur.com/twi3WOn.png" />
</Image.Group>
</Container>
</Grid.Row>
</Grid.Column>
</Grid>
</Container>;
export default About;
|
index.ios.js | feirari/ITS484Project | /**
* Load the App component.
* (All the fun stuff happens in "/ReactApp/containers/index.js")
*
* React Native Starter App
* //
*/
'use strict';
import React from 'react'
import { AppRegistry } from 'react-native'
import AppContainer from './ReactApp/containers/'
AppRegistry.registerComponent('StarterKit', () => AppContainer)
|
node_modules/react-router-dom/es/HashRouter.js | bburnett-cpf/react-intro | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React from 'react';
import PropTypes from 'prop-types';
import createHistory from 'history/createHashHistory';
import { Router } from 'react-router';
/**
* The public API for a <Router> that uses window.location.hash.
*/
var HashRouter = function (_React$Component) {
_inherits(HashRouter, _React$Component);
function HashRouter() {
var _temp, _this, _ret;
_classCallCheck(this, HashRouter);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret);
}
HashRouter.prototype.render = function render() {
return React.createElement(Router, { history: this.history, children: this.props.children });
};
return HashRouter;
}(React.Component);
HashRouter.propTypes = {
basename: PropTypes.string,
getUserConfirmation: PropTypes.func,
hashType: PropTypes.oneOf(['hashbang', 'noslash', 'slash']),
children: PropTypes.node
};
export default HashRouter; |
admin/client/App/shared/Popout/PopoutListHeading.js | helloworld3q3q/keystone | /**
* Render a popout list heading
*/
import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';
var PopoutListHeading = React.createClass({
displayName: 'PopoutListHeading',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
},
render () {
const className = classnames('PopoutList__heading', this.props.className);
const props = blacklist(this.props, 'className');
return (
<div className={className} {...props} />
);
},
});
module.exports = PopoutListHeading;
|
docs/client/components/pages/Video/CustomAddVideoVideoEditor/VideoAdd/index.js | koaninc/draft-js-plugins | import React, { Component } from 'react';
import styles from './styles.css';
export default class VideoAdd extends Component {
// Start the popover closed
state = {
url: '',
open: false,
};
// When the popover is open and users click anywhere on the page,
// the popover should close
componentDidMount() {
document.addEventListener('click', this.closePopover);
}
componentWillUnmount() {
document.removeEventListener('click', this.closePopover);
}
// Note: make sure whenever a click happens within the popover it is not closed
onPopoverClick = () => {
this.preventNextClose = true;
};
openPopover = () => {
if (!this.state.open) {
this.preventNextClose = true;
this.setState({
open: true,
});
}
};
closePopover = () => {
if (!this.preventNextClose && this.state.open) {
this.setState({
open: false,
});
}
this.preventNextClose = false;
};
addVideo = () => {
const { editorState, onChange } = this.props;
onChange(this.props.modifier(editorState, { src: this.state.url }));
};
changeUrl = (evt) => {
this.setState({ url: evt.target.value });
};
render() {
const popoverClassName = this.state.open ?
styles.addVideoPopover :
styles.addVideoClosedPopover;
const buttonClassName = this.state.open ?
styles.addVideoPressedButton :
styles.addVideoButton;
return (
<div className={styles.addVideo} >
<button
className={buttonClassName}
onMouseUp={this.openPopover}
type="button"
>
+
</button>
<div
className={popoverClassName}
onClick={this.onPopoverClick}
>
<input
type="text"
placeholder="Paste the video url …"
className={styles.addVideoInput}
onChange={this.changeUrl}
value={this.state.url}
/>
<button
className={styles.addVideoConfirmButton}
type="button"
onClick={this.addVideo}
>
Add
</button>
</div>
</div>
);
}
}
|
src/components/Weui/button/button_area.js | ynu/res-track-wxe | /*
eslint-disable
*/
import React from 'react';
import classNames from 'classnames';
export default class ButtonArea extends React.Component {
static propTypes = {
direction: React.PropTypes.string
};
static defaultProps = {
direction: 'vertical'
};
render() {
const {direction, children} = this.props;
const className = classNames({
'weui-btn-area': true,
'weui-btn-area_inline': direction === 'horizontal'
});
return (
<div className={className}>
{children}
</div>
);
}
};
|
src/svg-icons/image/panorama-wide-angle.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePanoramaWideAngle = (props) => (
<SvgIcon {...props}>
<path d="M12 6c2.45 0 4.71.2 7.29.64.47 1.78.71 3.58.71 5.36 0 1.78-.24 3.58-.71 5.36-2.58.44-4.84.64-7.29.64s-4.71-.2-7.29-.64C4.24 15.58 4 13.78 4 12c0-1.78.24-3.58.71-5.36C7.29 6.2 9.55 6 12 6m0-2c-2.73 0-5.22.24-7.95.72l-.93.16-.25.9C2.29 7.85 2 9.93 2 12s.29 4.15.87 6.22l.25.89.93.16c2.73.49 5.22.73 7.95.73s5.22-.24 7.95-.72l.93-.16.25-.89c.58-2.08.87-4.16.87-6.23s-.29-4.15-.87-6.22l-.25-.89-.93-.16C17.22 4.24 14.73 4 12 4z"/>
</SvgIcon>
);
ImagePanoramaWideAngle = pure(ImagePanoramaWideAngle);
ImagePanoramaWideAngle.displayName = 'ImagePanoramaWideAngle';
ImagePanoramaWideAngle.muiName = 'SvgIcon';
export default ImagePanoramaWideAngle;
|
src/hoc/withTick.js | xavi160/react-video | import React from 'react';
export default function withTick(milliseconds, condition, Component) {
return class Tick extends React.Component {
constructor() {
super();
this.state = { now: new Date() };
}
componentDidMount() {
this.tickInterval = setInterval(
() => condition(this.props) && this.tick(),
milliseconds
);
}
componentWillUnmount() {
clearInterval(this.tickInterval);
}
tick() {
this.setState({ now: new Date() });
}
render() {
return <Component {...this.props} now={this.state.now}/>;
}
};
}
|
packages/react-error-overlay/src/components/Footer.js | mangomint/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 from 'react';
import { darkGray } from '../styles';
const footerStyle = {
fontFamily: 'sans-serif',
color: darkGray,
marginTop: '0.5rem',
flex: '0 0 auto',
};
type FooterPropsType = {|
line1: string,
line2?: string,
|};
function Footer(props: FooterPropsType) {
return (
<div style={footerStyle}>
{props.line1}
<br />
{props.line2}
</div>
);
}
export default Footer;
|
src/PopoverMenuItem3/index.js | DuckyTeam/ducky-components | import Icon from '../Icon';
import React from 'react';
import PropTypes from 'prop-types';
import Typography from '../Typography';
import Wrapper from '../Wrapper';
import classNames from 'classnames';
import styles from './styles.css';
function PopoverMenuItem3(props) {
return (
<Wrapper
className={classNames(styles.wrapper, {
[styles.selected]: props.selected}, {
[props.className]: props.className}
)}
onClick={props.onClick}
size={'short'}
>
<Typography
className={styles.text}
type="bodyTextNormal"
>
{props.label}
</Typography>
<Icon
className={styles.icon}
icon={props.selected ? 'icon-check' : ''}
size={'small'}
/>
</Wrapper>
);
}
PopoverMenuItem3.propTypes = {
className: PropTypes.string,
label: PropTypes.string,
onClick: PropTypes.func,
selected: PropTypes.selected
};
export default PopoverMenuItem3;
|
src/svg-icons/action/alarm-on.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAlarmOn = (props) => (
<SvgIcon {...props}>
<path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-1.46-5.47L8.41 12.4l-1.06 1.06 3.18 3.18 6-6-1.06-1.06-4.93 4.95z"/>
</SvgIcon>
);
ActionAlarmOn = pure(ActionAlarmOn);
ActionAlarmOn.displayName = 'ActionAlarmOn';
ActionAlarmOn.muiName = 'SvgIcon';
export default ActionAlarmOn;
|
docs/app/Examples/elements/Header/States/HeaderExampleDisabled.js | ben174/Semantic-UI-React | import React from 'react'
import { Header } from 'semantic-ui-react'
const HeaderExampleDisabled = () => (
<Header as='h2' disabled>
Disabled Header
</Header>
)
export default HeaderExampleDisabled
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.