path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
frontend/src/components/eois/modals/addClarificationAnswer/addClarificationAnswerForm.js
unicef/un-partner-portal
import React from 'react'; import { connect } from 'react-redux'; import { reduxForm, clearSubmitErrors } from 'redux-form'; import PropTypes from 'prop-types'; import Snackbar from 'material-ui/Snackbar'; import GridColumn from '../../../common/grid/gridColumn'; import TextFieldForm from '../../../forms/textFieldForm'; import FileForm from '../../../forms/fileForm'; const messages = { labels: { comment: 'Title', commentPlaceholder: 'Enter title of file', document: 'Document', }, }; const AddClarificationAnswerForm = (props) => { const { handleSubmit, error, clearError, form } = props; return ( <form onSubmit={handleSubmit}> <GridColumn > <TextFieldForm fieldName="title" textFieldProps={{ multiline: true, InputProps: { inputProps: { maxLength: '5000', }, }, }} label={messages.labels.comment} placeholder={messages.labels.commentPlaceholder} /> <FileForm fieldName="file" label={messages.labels.document} formName={form} /> <Snackbar anchorOrigin={{ vertical: 'bottom', horizontal: 'left', }} open={error} message={error} autoHideDuration={6e3} onClose={clearError} /> </GridColumn> </form > ); }; AddClarificationAnswerForm.propTypes = { /** * callback for form submit */ handleSubmit: PropTypes.func.isRequired, clearError: PropTypes.func, error: PropTypes.string, form: PropTypes.string, }; const formAddClarificationAnswerForm = reduxForm({ enableReinitialize: true, })(AddClarificationAnswerForm); const mapDispatchToProps = dispatch => ({ clearError: () => dispatch(clearSubmitErrors('addClarificationAnswerForm')), }); export default connect( null, mapDispatchToProps, )(formAddClarificationAnswerForm);
src/components/Sections/SectionTable.js
demisto/sane-reports
import './SectionTable.less'; import React from 'react'; import PropTypes from 'prop-types'; import { getDefaultMaxLength, TABLE_CELL_TYPE } from '../../constants/Constants'; import { isEmpty, isString, isArray, truncate, isObjectLike, map } from 'lodash'; import WidgetEmptyState from './WidgetEmptyState'; import SectionTitle from './SectionTitle'; function getExtraPropsForColumn(key, columnsMetaDataMap, headerStyle) { const extraProps = {}; const metaData = columnsMetaDataMap.get(key); if (metaData) { extraProps.width = metaData.width; } if (headerStyle) { extraProps.style = headerStyle; } return extraProps; } const SectionTable = ({ columns, readableHeaders, data, classes, style, title, titleStyle, emptyString, maxColumns, forceRangeMessage, headerStyle }) => { let tableData = data || []; if (isString(data)) { try { tableData = JSON.parse(data); } catch (ignored) { return <div>Error parsing table</div>; } } if (!isArray(tableData) && isObjectLike(tableData)) { tableData = tableData.data || tableData.iocs || tableData.messages || []; } let readyColumns = columns; if (isEmpty(columns) && isArray(tableData)) { const headerKeys = {}; tableData.forEach((val, i) => { for (const key in tableData[i]) { // eslint-disable-line no-restricted-syntax if (headerKeys[key] !== key) { headerKeys[key] = key; } } }); readyColumns = Object.keys(headerKeys); } const columnsMetaDataMap = new Map(); if (columns && isArray(columns)) { columns.forEach(mData => columnsMetaDataMap.set(mData.key, mData)); } let tableBody; const defaultMaxLength = getDefaultMaxLength(); if (isArray(readyColumns)) { readyColumns = maxColumns > 0 ? readyColumns.slice(0, maxColumns) : readyColumns; tableBody = tableData.length > 0 ? ( <table className={'ui compact table unstackable section-table ' + classes} style={{ tableLayout: 'fixed' }}> <thead> <tr> {readyColumns.map((col) => { const key = col.key || col; const extraProps = getExtraPropsForColumn(key, columnsMetaDataMap, headerStyle); return ( <th key={key} {...extraProps}> {!col.hidden && ((readableHeaders && readableHeaders[key]) || key)} </th> ); })} </tr> </thead> <tbody> {tableData.map((row, i) => <tr key={i}> {readyColumns.map((col, j) => (() => { const key = col.key || col; let cell = row[key]; if (cell === undefined || cell === null) { cell = readableHeaders && row[readableHeaders[key]]; } let cellToRender = ''; if (cell || cell === 0) { switch (cell.type) { case TABLE_CELL_TYPE.image: cellToRender = ( <img src={cell.data} alt={cell.alt} className={'ui image ' + cell.classes} style={cell.style} /> ); break; default: cellToRender = truncate(cell, { length: defaultMaxLength }); } } return ( <td key={j} style={{ wordBreak: 'break-word', whiteSpace: 'pre-line' }}> {cellToRender} </td> ); })() )} </tr>) } </tbody> </table> ) : ( <div> <table className={'ui compact table unstackable ' + classes} style={{ tableLayout: 'fixed' }}> <thead> <tr> {readyColumns.map((col) => { const key = col.key || col; const extraProps = getExtraPropsForColumn(key, columnsMetaDataMap, headerStyle); return ( <th {...extraProps} key={key} {...(headerStyle ? { style: headerStyle } : {})} > {!col.hidden && ((readableHeaders && readableHeaders[key]) || key)} </th> ); })} </tr> </thead> </table> <WidgetEmptyState emptyString={emptyString} /> </div>); } else { tableBody = ( <table className={'ui compact table unstackable ' + classes}> <tbody> {map(tableData, (val, key) => ( <tr key={key}> <td style={{ background: 'rgb(249, 250, 251)', width: '20%', whiteSpace: 'nowrap' }}> {key} </td> <td>{truncate(val, { length: defaultMaxLength })}</td> </tr> ))} </tbody> </table> ); } return ( <div className="section-table" style={style}> <SectionTitle title={title} titleStyle={titleStyle} subTitle={forceRangeMessage} /> {tableBody} </div> ); }; SectionTable.propTypes = { columns: PropTypes.array, readableHeaders: PropTypes.object, data: PropTypes.oneOfType([ PropTypes.array, PropTypes.object, PropTypes.string ]), classes: PropTypes.string, style: PropTypes.object, title: PropTypes.string, maxColumns: PropTypes.number, titleStyle: PropTypes.object, emptyString: PropTypes.string, forceRangeMessage: PropTypes.string, headerStyle: PropTypes.object }; export default SectionTable;
src/index.js
budiantotan/book-store
import 'babel-polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import { render } from 'react-dom'; import { Router, browserHistory } from 'react-router'; import routes from './routes'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import configureStore from './store/configureStore'; import * as bookActions from './actions/bookActions'; const store = configureStore(); store.dispatch(bookActions.fetchBooks()); render( <Provider store={store}> <Router routes={routes} history={browserHistory} /> </Provider>, document.getElementById('app') );
src/js/components/icons/base/VmMaintenance.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-vm-maintenance`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'vm-maintenance'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M19,9.9999 L19,1.9999 L7,1.9999 L7,13.9999 L14,13.9999 L14,6.9999 L2,6.9999 L2,18.9999 L10,18.9999 M14,23 L20,17 M21,14 C19.8954305,14 19,14.8954305 19,16 C19,17.1045695 19.8954305,18 21,18 C22.1045695,18 23,17.1045695 23,16"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'VmMaintenance'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
imports/old/signup/confirm.js
jiyuu-llc/jiyuu
import React from 'react'; const Confirm = () => ({ confirmNext(){ const firstName = Session.get("fname"); const lastName = Session.get("lname"); const username = Session.get('username'); const email = Session.get('contact'); const dob =Session.get('dob'); const password = Session.get('password'); const accountType = Session.get('aType'); const theme = "jiyuu"; const interests = Session.get("interests") || []; var user = {email:email,password:password,username:username,theme:theme,type:accountType,firstName:firstName,lastName:lastName,avatar:'/images/users.png',cover:'/images/cover.png',dob:dob, interests: interests}; Accounts.createUser(user,function(error){ if(error){ alert("Sorry something went wrong.") } else{ Meteor.call('addConnectionGroup', 'Friends', (err, res)=>{ if (!err){ Meteor.call('addConnectionGroup', 'Following', (err, res)=>{ if (!err){ Meteor.call('addConnectionGroup', 'Blocked'); if (interests.indexOf('news') != -1){ // adds the anti media Meteor.call('addConnectionToGroup', 'Following', 'TheAntiMedia'); } if (interests.indexOf('technology') != -1){ // adds futurism Meteor.call('addConnectionToGroup', 'Following', 'Futurism'); } if (interests.indexOf('hippie') != -1){ // adds the mind unleashed Meteor.call('addConnectionToGroup', 'Following', 'TheMindUnleashed'); } } }); } }); FlowRouter.go('/register/10'); } }); }, render() { return ( <div id="jiyuu"> <h2 className="question">We have sent you a confirmation code.</h2> <div id="question-card" className="form-group"> <div id="questionInputContain"> <input id="questionInput" type="text" tabindex="1" placeholder="Confirmation Code" className="form-control"/> </div> <div className="qnext" onClick={this.confirmNext.bind(this)}> <i className="fa fa-caret-right" aria-hidden="true"/> </div> </div> </div> ); } }); export default Confirm;
examples/js/app.js
prajapati-parth/react-bootstrap-table
import React from 'react'; import ReactDOM from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import { IndexRoute, Router, Route, hashHistory } from 'react-router'; import App from './components/App'; import Home from './components/Home'; import GettingStarted from './components/GettingStarted'; import PageNotFound from './components/PageNotFound'; import Basic from './basic/demo'; import Column from './column/demo'; import Sort from './sort/demo'; import ColumnFormat from './column-format/demo'; import ColumnFilter from './column-filter/demo'; import Selection from './selection/demo'; import Pagination from './pagination/demo'; import Manipulation from './manipulation/demo'; import CellEdit from './cell-edit/demo'; import Style from './style/demo'; import Advance from './advance/demo'; import Other from './others/demo'; import Complex from './complex/demo'; import Remote from './remote/demo'; import Expand from './expandRow/demo'; import Custom from './custom/demo'; import Span from './column-header-span/demo'; import KeyBoardNav from './keyboard-nav/demo'; import FooterTable from './footer/demo'; const renderApp = () => { ReactDOM.render( <AppContainer> <Router history={ hashHistory }> <Route path='/' component={ App }> <IndexRoute component={ Home } /> <Route path='getting-started' component={ GettingStarted }/> <Route path='examples'> <Route path='basic' component={ Basic } /> <Route path='column' component={ Column } /> <Route path='sort' component={ Sort } /> <Route path='column-format' component={ ColumnFormat } /> <Route path='column-filter' component={ ColumnFilter } /> <Route path='column-header-span' component={ Span } /> <Route path='selection' component={ Selection } /> <Route path='pagination' component={ Pagination } /> <Route path='manipulation' component={ Manipulation } /> <Route path='cell-edit' component={ CellEdit } /> <Route path='style' component={ Style } /> <Route path='advance' component={ Advance } /> <Route path='others' component={ Other } /> <Route path='complex' component={ Complex } /> <Route path='remote' component={ Remote } /> <Route path='custom' component={ Custom } /> <Route path='expandRow' component={ Expand } /> <Route path='keyboard-nav' component={ KeyBoardNav } /> <Route path='footer' component={ FooterTable } /> </Route> <Route path='*' component={ PageNotFound }/> </Route> </Router> </AppContainer>, document.querySelector('#root')); }; if (module.hot) { module.hot.accept('./app', renderApp); } renderApp();
frontend/components/TwoColumn.js
datoszs/czech-lawyers
import React from 'react'; import PropTypes from 'prop-types'; import styles from './TwoColumn.less'; const TwoColumn = ({children}) => <div className={styles.main}>{children}</div>; TwoColumn.propTypes = { children: PropTypes.node, }; TwoColumn.defaultProps = { children: null, }; export default TwoColumn;
docs/app/Examples/elements/Reveal/Types/RevealExampleMoveDown.js
aabustamante/Semantic-UI-React
import React from 'react' import { Image, Reveal } from 'semantic-ui-react' const RevealExampleMoveDown = () => ( <Reveal animated='move down'> <Reveal.Content visible> <Image src='/assets/images/wireframe/square-image.png' size='small' /> </Reveal.Content> <Reveal.Content hidden> <Image src='/assets/images/avatar/large/nan.jpg' size='small' /> </Reveal.Content> </Reveal> ) export default RevealExampleMoveDown
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
nicksiyer/nicksiyer.github.io
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
index.android.js
quickresolve/CycleTheBay
/** * Sample React Native App * https://github.com/facebook/react-native */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; class CycleTheBay extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('CycleTheBay', () => CycleTheBay);
src/icons/ArrowForwardIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class ArrowForwardIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M24 8l-2.83 2.83L32.34 22H8v4h24.34L21.17 37.17 24 40l16-16z"/></svg>;} };
fixtures/nesting/src/modern/index.js
billfeller/react
import React from 'react'; import {StrictMode} from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import App from './App'; import {store} from '../store'; ReactDOM.render( <StrictMode> <Provider store={store}> <App /> </Provider> </StrictMode>, document.getElementById('root') );
webpack/scenes/Subscriptions/components/SubscriptionsTable/SubscriptionsTable.js
snagoor/katello
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { cloneDeep, findIndex, isEqual } from 'lodash'; import { translate as __ } from 'foremanReact/common/I18n'; import { LoadingState } from '../../../../components/LoadingState'; import { recordsValid } from '../../SubscriptionValidations'; import { buildTableRows, groupSubscriptionsByProductId } from './SubscriptionsTableHelpers'; import Table from './components/Table'; import Dialogs from './components/Dialogs'; class SubscriptionsTable extends Component { constructor(props) { super(props); this.state = { rows: undefined, subscriptions: undefined, groupedSubscriptions: undefined, updatedQuantity: {}, editing: false, showUpdateConfirmDialog: false, showCancelConfirmDialog: false, showErrorDialog: false, }; } static getDerivedStateFromProps(nextProps, prevState) { if ( nextProps.subscriptions !== undefined && !isEqual(nextProps.subscriptions, prevState.subscriptions) ) { const groupedSubscriptions = groupSubscriptionsByProductId( nextProps.subscriptions, prevState.groupedSubscriptions, ); const rows = buildTableRows( groupedSubscriptions, nextProps.subscriptions.availableQuantities, prevState.updatedQuantity, ); return { rows, groupedSubscriptions, subscriptions: nextProps.subscriptions }; } return null; } getInlineEditController = () => ({ isEditing: ({ rowData }) => (this.state.editing && rowData.available >= 0 && rowData.upstream_pool_id), hasChanged: ({ rowData }) => { const editedValue = this.state.updatedQuantity[rowData.id]; return this.hasQuantityChanged(rowData, editedValue); }, onActivate: () => this.enableEditing(true), onConfirm: () => { if (recordsValid(this.state.rows)) { this.showUpdateConfirm(true); } else { this.showErrorDialog(true); } }, onCancel: () => { this.showCancelConfirm(true); }, onChange: (value, { rowData }) => { const updatedQuantity = cloneDeep(this.state.updatedQuantity); if (this.hasQuantityChanged(rowData, value)) { updatedQuantity[rowData.id] = value; } else { delete updatedQuantity[rowData.id]; } this.updateRows(updatedQuantity); }, }); getSelectionController = () => { const allSubscriptionResults = this.props.subscriptions.results; const checkAllRowsSelected = () => allSubscriptionResults.length === this.props.selectedRows.length; return ({ allRowsSelected: () => checkAllRowsSelected(), selectAllRows: () => { if (checkAllRowsSelected()) { this.props.onSelectedRowsChange([]); this.props.toggleDeleteButton(false); } else { this.props.onSelectedRowsChange(allSubscriptionResults.map(row => row.id)); this.props.toggleDeleteButton(true); } }, selectRow: ({ rowData }) => { let { selectedRows } = this.props; if (selectedRows.includes(rowData.id)) { selectedRows = selectedRows.filter(e => e !== rowData.id); } else { selectedRows = selectedRows.concat(rowData.id); } this.props.onSelectedRowsChange(selectedRows); this.props.toggleDeleteButton(selectedRows.length > 0); }, isSelected: ({ rowData }) => this.props.selectedRows.includes(rowData.id), }); }; getTableProps = () => { const { subscriptions, emptyState, tableColumns, loadSubscriptions, selectionEnabled, } = this.props; const { groupedSubscriptions, rows, editing } = this.state; return { emptyState, editing, groupedSubscriptions, loadSubscriptions, rows, subscriptions, selectionEnabled, tableColumns, toggleSubscriptionGroup: this.toggleSubscriptionGroup, inlineEditController: this.getInlineEditController(), selectionController: this.getSelectionController(), }; }; getUpdateDialogProps = () => { const { showUpdateConfirmDialog: show, updatedQuantity } = this.state; const { updateQuantity, } = this.props; return { show, updatedQuantity, updateQuantity, enableEditing: this.enableEditing, showUpdateConfirm: this.showUpdateConfirm, }; }; getUnsavedChangesDialogProps = () => { const { showCancelConfirmDialog: show } = this.state; return { show, cancelEdit: this.cancelEdit, showCancelConfirm: this.showCancelConfirm, }; }; getInputsErrorsDialogProps = () => { const { showErrorDialog: show } = this.state; return { show, showErrorDialog: this.showErrorDialog, }; }; getDeleteDialogProps = () => { const { subscriptionDeleteModalOpen: show, onDeleteSubscriptions, onSubscriptionDeleteModalClose, } = this.props; const { selectedRows } = this.props; return { show, selectedRows, onSubscriptionDeleteModalClose, onDeleteSubscriptions, }; }; getLoadingStateProps = () => { const { subscriptions: { loading } } = this.props; return { loading, loadingText: __('Loading'), }; }; getDialogsProps = () => ({ updateDialog: this.getUpdateDialogProps(), unsavedChangesDialog: this.getUnsavedChangesDialogProps(), inputsErrorsDialog: this.getInputsErrorsDialogProps(), deleteDialog: this.getDeleteDialogProps(), }); toggleSubscriptionGroup = (groupId) => { this.setState((prevState) => { const { subscriptions } = this.props; const { groupedSubscriptions, updatedQuantity } = prevState; const { open } = groupedSubscriptions[groupId]; groupedSubscriptions[groupId].open = !open; const rows = buildTableRows( groupedSubscriptions, subscriptions.availableQuantities, updatedQuantity, ); return { rows, groupedSubscriptions }; }); }; enableEditing = (editingState) => { this.setState({ updatedQuantity: {}, editing: editingState, }); }; updateRows = (updatedQuantity) => { this.setState((prevState) => { const { groupedSubscriptions } = prevState; const { subscriptions } = this.props; const rows = buildTableRows( groupedSubscriptions, subscriptions.availableQuantities, updatedQuantity, ); return { rows, updatedQuantity }; }); }; showUpdateConfirm = (show) => { this.setState({ showUpdateConfirmDialog: show, }); }; showCancelConfirm = (show) => { this.setState({ showCancelConfirmDialog: show, }); }; showErrorDialog = (show) => { this.setState({ showErrorDialog: show, }); }; cancelEdit = () => { this.showCancelConfirm(false); this.enableEditing(false); this.updateRows({}); }; hasQuantityChanged = (rowData, editedValue) => { if (editedValue !== undefined) { const originalRows = this.props.subscriptions.results; const index = findIndex(originalRows, row => (row.id === rowData.id)); const currentValue = originalRows[index].quantity; return (`${editedValue}` !== `${currentValue}`); } return false; }; render() { return ( <LoadingState {...this.getLoadingStateProps()}> <Table {...this.getTableProps()} /> <Dialogs {...this.getDialogsProps()} /> </LoadingState> ); } } SubscriptionsTable.propTypes = { tableColumns: PropTypes.arrayOf(PropTypes.string).isRequired, loadSubscriptions: PropTypes.func.isRequired, updateQuantity: PropTypes.func.isRequired, emptyState: PropTypes.shape({}).isRequired, subscriptions: PropTypes.shape({ loading: PropTypes.bool, availableQuantities: PropTypes.shape({}), // Disabling rule as existing code failed due to an eslint-plugin-react update // eslint-disable-next-line react/forbid-prop-types results: PropTypes.array, }).isRequired, subscriptionDeleteModalOpen: PropTypes.bool.isRequired, onDeleteSubscriptions: PropTypes.func.isRequired, onSubscriptionDeleteModalClose: PropTypes.func.isRequired, toggleDeleteButton: PropTypes.func.isRequired, selectedRows: PropTypes.instanceOf(Array).isRequired, onSelectedRowsChange: PropTypes.func.isRequired, selectionEnabled: PropTypes.bool, }; SubscriptionsTable.defaultProps = { selectionEnabled: false, }; export default SubscriptionsTable;
node_modules/react-bootstrap/es/PaginationButton.js
ivanhristov92/bookingCalendar
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 elementType from 'react-prop-types/lib/elementType'; import SafeAnchor from './SafeAnchor'; import createChainedFunction from './utils/createChainedFunction'; // TODO: This should be `<Pagination.Item>`. // TODO: This should use `componentClass` like other components. var propTypes = { componentClass: elementType, className: React.PropTypes.string, eventKey: React.PropTypes.any, onSelect: React.PropTypes.func, disabled: React.PropTypes.bool, active: React.PropTypes.bool, onClick: React.PropTypes.func }; var defaultProps = { componentClass: SafeAnchor, active: false, disabled: false }; var PaginationButton = function (_React$Component) { _inherits(PaginationButton, _React$Component); function PaginationButton(props, context) { _classCallCheck(this, PaginationButton); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } PaginationButton.prototype.handleClick = function handleClick(event) { var _props = this.props, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; PaginationButton.prototype.render = function render() { var _props2 = this.props, Component = _props2.componentClass, active = _props2.active, disabled = _props2.disabled, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = _objectWithoutProperties(_props2, ['componentClass', 'active', 'disabled', 'onClick', 'className', 'style']); if (Component === SafeAnchor) { // Assume that custom components want `eventKey`. delete props.eventKey; } delete props.onSelect; return React.createElement( 'li', { className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(Component, _extends({}, props, { disabled: disabled, onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return PaginationButton; }(React.Component); PaginationButton.propTypes = propTypes; PaginationButton.defaultProps = defaultProps; export default PaginationButton;
src/icons/ArrowUpC.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class ArrowUpC extends React.Component { render() { if(this.props.bare) { return <g> <path d="M128.4,189.3L233.4,89c5.8-6,13.7-9,22.4-9c8.7,0,16.5,3,22.4,9l105.4,100.3c12.5,11.9,12.5,31.3,0,43.2 c-12.5,11.9-32.7,11.9-45.2,0L288,184.4v217c0,16.9-14.3,30.6-32,30.6c-17.7,0-32-13.7-32-30.6v-217l-50.4,48.2 c-12.5,11.9-32.7,11.9-45.2,0C115.9,220.6,115.9,201.3,128.4,189.3z"></path> </g>; } return <IconBase> <path d="M128.4,189.3L233.4,89c5.8-6,13.7-9,22.4-9c8.7,0,16.5,3,22.4,9l105.4,100.3c12.5,11.9,12.5,31.3,0,43.2 c-12.5,11.9-32.7,11.9-45.2,0L288,184.4v217c0,16.9-14.3,30.6-32,30.6c-17.7,0-32-13.7-32-30.6v-217l-50.4,48.2 c-12.5,11.9-32.7,11.9-45.2,0C115.9,220.6,115.9,201.3,128.4,189.3z"></path> </IconBase>; } };ArrowUpC.defaultProps = {bare: false}
src/components/Card.js
ciaoben/ListView
import React from 'react'; var Card = React.createClass({ getDefaultProps: function() { return { onPaginate: function() {}, status: 'loading', per: 25, page: 1, filter: null }; }, render: function() { return (<div className='card'> <div className='header'> <span className='status'>Status: Active</span> {this.props.title} </div> <div className='body'> <span className='info'>45 email accounts</span> <span className='separator'></span> <span className='info'>3.5GB spazio occupato</span> <span className='separator'></span> <span className='info'>attivo dal 13 agosto 2015</span> </div> </div>); } }); module.exports = Card;
src/containers/Simple/Simple.js
hungtruongquoc/shipper_front
import React, { Component } from 'react'; class Simple extends Component { render() { return ( <div className="app flex-row align-items-center"> {this.props.children} </div> ); } } export default Simple;
demo/universal-routed-flux-demo/components/AppContainer.react.js
waterbolik/prestudy
import React from 'react'; import {Link} from 'react-router'; export default class AppContainer extends React.Component{ constructor(props) { super(props); } render(){ var nav = <div> <p> <Link to="/todo">Todo list without logs</Link><br/> <Link to="/todo/logs">Todo list with logs</Link> </p> </div>; return ( <div> {this.props.children || nav} </div> ); } }
src/TabPane.js
IveWong/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import TransitionEvents from './utils/TransitionEvents'; const TabPane = React.createClass({ propTypes: { active: React.PropTypes.bool, animation: React.PropTypes.bool, onAnimateOutEnd: React.PropTypes.func, disabled: React.PropTypes.bool }, getDefaultProps() { return { animation: true }; }, getInitialState() { return { animateIn: false, animateOut: false }; }, componentWillReceiveProps(nextProps) { if (this.props.animation) { if (!this.state.animateIn && nextProps.active && !this.props.active) { this.setState({ animateIn: true }); } else if (!this.state.animateOut && !nextProps.active && this.props.active) { this.setState({ animateOut: true }); } } }, componentDidUpdate() { if (this.state.animateIn) { setTimeout(this.startAnimateIn, 0); } if (this.state.animateOut) { TransitionEvents.addEndEventListener( React.findDOMNode(this), this.stopAnimateOut ); } }, startAnimateIn() { if (this.isMounted()) { this.setState({ animateIn: false }); } }, stopAnimateOut() { if (this.isMounted()) { this.setState({ animateOut: false }); if (this.props.onAnimateOutEnd) { this.props.onAnimateOutEnd(); } } }, render() { let classes = { 'tab-pane': true, 'fade': true, 'active': this.props.active || this.state.animateOut, 'in': this.props.active && !this.state.animateIn }; return ( <div {...this.props} role='tabpanel' aria-hidden={!this.props.active} className={classNames(this.props.className, classes)} > {this.props.children} </div> ); } }); export default TabPane;
src/svg-icons/content/filter-list.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentFilterList = (props) => ( <SvgIcon {...props}> <path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/> </SvgIcon> ); ContentFilterList = pure(ContentFilterList); ContentFilterList.displayName = 'ContentFilterList'; ContentFilterList.muiName = 'SvgIcon'; export default ContentFilterList;
app/javascript/mastodon/features/notifications/components/notification.js
hyuki0000/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import StatusContainer from '../../../containers/status_container'; import AccountContainer from '../../../containers/account_container'; import { FormattedMessage } from 'react-intl'; import Permalink from '../../../components/permalink'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class Notification extends ImmutablePureComponent { static propTypes = { notification: ImmutablePropTypes.map.isRequired, hidden: PropTypes.bool, }; renderFollow (account, link) { return ( <div className='notification notification-follow'> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-user-plus' /> </div> <FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} /> </div> <AccountContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} /> </div> ); } renderMention (notification) { return <StatusContainer id={notification.get('status')} withDismiss hidden={this.props.hidden} />; } renderFavourite (notification, link) { return ( <div className='notification notification-favourite'> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-star star-icon' /> </div> <FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} /> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={!!this.props.hidden} /> </div> ); } renderReblog (notification, link) { return ( <div className='notification notification-reblog'> <div className='notification__message'> <div className='notification__favourite-icon-wrapper'> <i className='fa fa-fw fa-retweet' /> </div> <FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} /> </div> <StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} /> </div> ); } render () { const { notification } = this.props; const account = notification.get('account'); const displayNameHtml = { __html: account.get('display_name_html') }; const link = <Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} />; switch(notification.get('type')) { case 'follow': return this.renderFollow(account, link); case 'mention': return this.renderMention(notification); case 'favourite': return this.renderFavourite(notification, link); case 'reblog': return this.renderReblog(notification, link); } return null; } }
App/src/features/projects/ProjectsList.js
DupK/dashboard-epitech
import React, { Component } from 'react'; import moment from 'moment'; import { observer } from 'mobx-react/native'; import { Text, View, TouchableOpacity, Platform, ScrollView, ListView, } from 'react-native'; import ProgressBar from './ProgressBar'; import { Actions } from 'react-native-router-flux'; import _ from 'lodash'; import IconFA from 'react-native-vector-icons/FontAwesome'; import IconIO from 'react-native-vector-icons/Ionicons'; import styles from './styles.js'; @observer export default class ProjectsList extends Component { constructor(props) { super(props); this.renderProject = this.renderProject.bind(this); this.renderHeader = this.renderHeader.bind(this); this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); } renderProject(project) { const { uiStore } = this.props; const parsedStart = moment(project.begin_acti, 'YYYY-MM-DD, HH:mm:ss'); const parsedEnd = moment(project.end_acti, 'YYYY-MM-DD, HH:mm:ss'); const projectDuration = parsedEnd.diff(parsedStart, 'days'); const durationSoFar = moment().diff(parsedStart, 'days'); const progress = Math.max(1, Math.min((durationSoFar / projectDuration) * 100, 100)); return ( <View style={{ padding: 15, borderBottomWidth: 1, borderBottomColor: 'rgba(0, 0, 0, 0.2)'}}> <TouchableOpacity onPress={() => uiStore.isConnected && Actions.projectDetails({ progress: progress, project: project, title: project.acti_title }) }> <View style={{ flex: 1, flexDirection: 'row', backgroundColor: '#fafafa',}}> <View style={{ flex: 100,}}> <View style={{flex: 1, flexDirection: 'column',}}> <View style={{ flexDirection: 'row' }}> <Text style={{ fontSize: 12, fontWeight: 'bold', color: '#233445',}}>{ project.acti_title }</Text> <Text style={{fontSize: 12, color: '#233445',}}> / { project.title_module }</Text> </View> <View style={{ marginTop: 2 }}> <View style={{flexDirection: 'row', justifyContent: 'space-between',}}> <Text style={{color: '#233445', fontSize: 10, marginTop: 5,}}>{ parsedStart.fromNow() }</Text> <Text style={{color: '#233445', fontSize: 10, margin: 5,}}>{ parsedEnd.fromNow() }</Text> </View> <ProgressBar completePercentage={progress}/> </View> </View> </View> <View style={{flex: 15, justifyContent: 'center', alignItems: 'flex-end',}}> <IconIO name="ios-arrow-forward-outline" style={{fontSize: 14, color: '#233445',}}/> </View> </View> </TouchableOpacity> </View> ); } renderHeader(title, icon) { return ( <View key={title} style={Platform.OS === 'ios' ? styles.headerContainerIOS : styles.headerContainerAndroid}> <IconFA style={styles.headerIcon} name={ icon } /> <Text style={styles.headerText}>{ title }</Text> </View> ) } renderAerProjects(projects) { return [ this.renderHeader('AER projects', 'life-bouy'), <ListView key="aer" dataSource={this.ds.cloneWithRows(projects)} renderRow={this.renderProject}> </ListView> ]; } renderCurrentProjects(projects) { return [ this.renderHeader('Currents projects', 'hourglass-half'), <ListView key="current" dataSource={this.ds.cloneWithRows(projects)} renderRow={this.renderProject}> </ListView> ]; } renderCommingProjects(projects) { return [ this.renderHeader('Incoming projects', 'hourglass-start'), <ListView key="comming" dataSource={this.ds.cloneWithRows(projects)} renderRow={this.renderProject}> </ListView> ]; } render() { const { projectsStore } = this.props; const projects = projectsStore.projects.slice(); const currentProjects = _.filter(projects, (project) => ( moment(project.begin_acti, 'YYYY-MM-DD, HH:mm:ss').isBefore(moment()) && project.rights.includes('student') )); const comingsProjects = _.filter(projects, (project) => ( moment(project.begin_acti, 'YYYY-MM-DD, HH:mm:ss').isAfter(moment()) && project.rights.includes('student') )); const aerProjects = _.filter(projects, (project) => ( project.rights.includes('assistant') )); return ( <View style={{ flex: 1 }}> {projects.length > 0 ? <ScrollView style={{ flex: 1, backgroundColor: '#FAFAFA' }}> { currentProjects.length !== 0 && this.renderCurrentProjects(currentProjects)} { comingsProjects.length !== 0 && this.renderCommingProjects(comingsProjects)} { aerProjects.length !== 0 && this.renderAerProjects(aerProjects) } </ScrollView> : <View style={{ flex: 1, backgroundColor: '#2c3e50', flexDirection: 'column', justifyContent: 'center' }}> <IconIO name="ios-cafe-outline" size={100} style={{ color: '#203040', alignSelf: 'center' }} /> <Text style={{ marginTop: 10, color:'#203040', alignSelf: 'center', fontSize: 15 }}> You're not registered to any future project </Text> </View> } </View> ); } } ProjectsList.propTypes = { projectsStore: React.PropTypes.object.isRequired, uiStore: React.PropTypes.object.isRequired, };
src/components/GithubButton/GithubButton.js
paschcua/erikras
import React from 'react'; const GithubButton = (props) => { const {user, repo, type, width, height, count, large} = props; let src = `https://ghbtns.com/github-btn.html?user=${user}&repo=${repo}&type=${type}`; if (count) src += '&count=true'; if (large) src += '&size=large'; return ( <iframe src={src} frameBorder="0" allowTransparency="true" scrolling="0" width={width} height={height} style={{border: 'none', width: width, height: height}}></iframe> ); }; GithubButton.propTypes = { user: React.PropTypes.string.isRequired, repo: React.PropTypes.string.isRequired, type: React.PropTypes.oneOf(['star', 'watch', 'fork', 'follow']).isRequired, width: React.PropTypes.number.isRequired, height: React.PropTypes.number.isRequired, count: React.PropTypes.bool, large: React.PropTypes.bool }; export default GithubButton;
src/svg-icons/maps/layers-clear.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLayersClear = (props) => ( <SvgIcon {...props}> <path d="M19.81 14.99l1.19-.92-1.43-1.43-1.19.92 1.43 1.43zm-.45-4.72L21 9l-9-7-2.91 2.27 7.87 7.88 2.4-1.88zM3.27 1L2 2.27l4.22 4.22L3 9l1.63 1.27L12 16l2.1-1.63 1.43 1.43L12 18.54l-7.37-5.73L3 14.07l9 7 4.95-3.85L20.73 21 22 19.73 3.27 1z"/> </SvgIcon> ); MapsLayersClear = pure(MapsLayersClear); MapsLayersClear.displayName = 'MapsLayersClear'; MapsLayersClear.muiName = 'SvgIcon'; export default MapsLayersClear;
src/rows-toolbar.js
Uber5/u5-datatable
import React from 'react' import IconMenu from 'material-ui/IconMenu' import IconButton from 'material-ui/IconButton' import NavigationExpandMoreIcon from 'material-ui/svg-icons/navigation/expand-more' import MenuItem from 'material-ui/MenuItem' import DropDownMenu from 'material-ui/DropDownMenu' import FlatButton from 'material-ui/FlatButton' import RaisedButton from 'material-ui/RaisedButton' import { Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle } from 'material-ui/Toolbar'; import BackIcon from 'material-ui/svg-icons/navigation/arrow-back' import * as R from 'ramda' import { saveAs } from 'file-saver' export default class ToolbarExamplesSimple extends React.Component { constructor(props) { super(props); this.state = { value: 3, }; } handleChange = (event, index, value) => this.setState({value}); downloadRows = () => { const { selected, config } = this.props const escape = s => s.replace(/["]/g, "\\$&") // escape '"' only const headers = R.keys(config.columns) .filter(colName => config.columns[colName].skipExport !== true) .map(colName => config.columns[colName].label || colName) .map(label => `"${ escape(label) }"`).join(',') const lines = selected.map(row => { const line = R.keys(config.columns) .filter(colName => config.columns[colName].skipExport !== true) .map(colName => { const value = R.path(colName.split('.'), row) const spec = config.columns[colName] const formatted = spec.format ? spec.format(row) : value const escaped = formatted ? escape(formatted.toString()) : '' return `"${ escaped }"` }).join(',') return line }) const asCsv = R.concat([ headers ], lines ).join('\n') const blob = new Blob([ asCsv ], { type: "text/csv;charset=utf-8" }) saveAs(blob, "data.csv") } render() { const { selected, clearSelected } = this.props return ( <Toolbar> <ToolbarGroup firstChild={true}> <FlatButton label="Back" icon={<BackIcon />} onClick={clearSelected} /> </ToolbarGroup> <ToolbarGroup> <ToolbarTitle text={`${ selected.length } selected`} /> <ToolbarSeparator /> <RaisedButton label="Download" primary={true} onClick={this.downloadRows} /> </ToolbarGroup> </Toolbar> ); } }
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Apis/Create/Swagger/ApiCreateSwagger.js
lakmali/carbon-apimgt
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import SingleInput from '../FormComponents/SingleInput'; import CheckboxOrRadioGroup from '../FormComponents/CheckboxOrRadioGroup'; import API from '../../../../data/api.js' import { toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.min.css'; import './ApiCreateSwagger.css' import Dropzone from 'react-dropzone' import {ScopeValidation, resourceMethod, resourcePath} from '../../../../data/ScopeValidation' import { Form, Icon, Input, Button, message, Upload, Radio } from 'antd'; const FormItem = Form.Item; const RadioButton = Radio.Button; const RadioGroup = Radio.Group; class SwaggerForm extends React.Component { constructor(props) { super(props); this.state = {uploadMethod:'file',file:{}} } createAPICallback = (response) => { let uuid = JSON.parse(response.data).id; let redirect_url = "/apis/" + uuid + "/overview"; this.props.history.push(redirect_url); }; /** * Do create API from either swagger URL or swagger file upload.In case of URL pre fetch the swagger file and make a blob * and the send it over REST API. * @param e {Event} */ handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { console.log('Received values of form: ', values); let input_type = this.state.uploadMethod; if (input_type === "url") { let url = values.url; let data = {}; data.url = url; data.type = 'swagger-url'; let new_api = new API(''); new_api.create(data) .then(this.createAPICallback) .catch( function (error_response) { let error_data = JSON.parse(error_response.data); let messageTxt = "Error[" + error_data.code + "]: " + error_data.description + " | " + error_data.message + "."; message.error(messageTxt); console.debug(error_response); }); } else if (input_type === "file") { let swagger = this.state.file.originFileObj; let new_api = new API(''); new_api.create(swagger) .then(this.createAPICallback) .catch( function (error_response) { let error_data; let messageTxt; if (error_response.obj) { error_data = error_response.obj; messageTxt = "Error[" + error_data.code + "]: " + error_data.description + " | " + error_data.message + "."; } else { error_data = error_response.data; messageTxt = "Error: " + error_data + "."; } message.error(messageTxt); console.debug(error_response); }); } } else { } }); }; normFile = (e) => { console.log('Upload event:', e); if (Array.isArray(e)) { return e; } return e && e.fileList; }; handleUploadMethodChange = (e) => { this.setState({uploadMethod:e.target.value}); }; toggleSwaggerType = (containerType) => { return this.state.uploadMethod === containerType ? '' : 'hidden'; }; handleUploadFile = (info) => { const status = info.file.status; if (status !== 'uploading') { console.log(info.file, info.fileList); } if (status === 'done') { message.success(`${info.file.name} file uploaded successfully.`); this.setState({file:info.file}) } else if (status === 'error') { message.error(`${info.file.name} file upload failed.`); } } render(){ const { getFieldDecorator } = this.props.form; const props = { name: 'file', multiple: false, showUploadList: true, action: '//jsonplaceholder.typicode.com/posts/' }; return( <Form onSubmit={this.handleSubmit} className="login-form"> <FormItem> {getFieldDecorator('radio-button')( <RadioGroup initialValue="file" onChange={this.handleUploadMethodChange}> <RadioButton value="file">Swagger File</RadioButton> <RadioButton value="url">Swagger URL</RadioButton> </RadioGroup> )} </FormItem> <FormItem className={this.toggleSwaggerType("file")}> <div className="dropbox"> {getFieldDecorator('dragger', { valuePropName: 'fileList', getValueFromEvent: this.normFile, })( <Upload.Dragger {...props} onChange={this.handleUploadFile}> <p className="ant-upload-drag-icon"> <Icon type="inbox" /> </p> <p className="ant-upload-text">Click or drag file to this area to upload</p> <p className="ant-upload-hint">Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files</p> </Upload.Dragger> )} </div> </FormItem> <FormItem className={this.toggleSwaggerType("url")}> {getFieldDecorator('userName', { rules: [{ required: false, message: 'Please input your username!' }], })( <Input name="url" prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="Username" /> )} </FormItem> <FormItem > <ScopeValidation resourceMethod={resourceMethod.POST} resourcePath={resourcePath.APIS}> <Button type="primary" htmlType="submit"> Create </Button> </ScopeValidation> <Button type="default" htmlType="button" onClick={() => this.props.history.push("/api/create/home")}> Cancel </Button> </FormItem> </Form> ); } } const SwaggerFormGenerated = Form.create()(SwaggerForm); class ApiCreateSwagger extends React.Component { constructor(props) { super(props); } render = () => {return <SwaggerFormGenerated history={this.props.history} /> } } export default ApiCreateSwagger;
app/javascript/mastodon/features/standalone/hashtag_timeline/index.js
cobodo/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { expandHashtagTimeline } from 'mastodon/actions/timelines'; import Masonry from 'react-masonry-infinite'; import { List as ImmutableList } from 'immutable'; import DetailedStatusContainer from 'mastodon/features/status/containers/detailed_status_container'; import { debounce } from 'lodash'; import LoadingIndicator from 'mastodon/components/loading_indicator'; const mapStateToProps = (state, { hashtag }) => ({ statusIds: state.getIn(['timelines', `hashtag:${hashtag}`, 'items'], ImmutableList()), isLoading: state.getIn(['timelines', `hashtag:${hashtag}`, 'isLoading'], false), hasMore: state.getIn(['timelines', `hashtag:${hashtag}`, 'hasMore'], false), }); export default @connect(mapStateToProps) class HashtagTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, statusIds: ImmutablePropTypes.list.isRequired, isLoading: PropTypes.bool.isRequired, hasMore: PropTypes.bool.isRequired, hashtag: PropTypes.string.isRequired, local: PropTypes.bool.isRequired, }; static defaultProps = { local: false, }; componentDidMount () { const { dispatch, hashtag, local } = this.props; dispatch(expandHashtagTimeline(hashtag, { local })); } handleLoadMore = () => { const { dispatch, hashtag, local, statusIds } = this.props; const maxId = statusIds.last(); if (maxId) { dispatch(expandHashtagTimeline(hashtag, { maxId, local })); } } setRef = c => { this.masonry = c; } handleHeightChange = debounce(() => { if (!this.masonry) { return; } this.masonry.forcePack(); }, 50) render () { const { statusIds, hasMore, isLoading } = this.props; const sizes = [ { columns: 1, gutter: 0 }, { mq: '415px', columns: 1, gutter: 10 }, { mq: '640px', columns: 2, gutter: 10 }, { mq: '960px', columns: 3, gutter: 10 }, { mq: '1255px', columns: 3, gutter: 10 }, ]; const loader = (isLoading && statusIds.isEmpty()) ? <LoadingIndicator key={0} /> : undefined; return ( <Masonry ref={this.setRef} className='statuses-grid' hasMore={hasMore} loadMore={this.handleLoadMore} sizes={sizes} loader={loader}> {statusIds.map(statusId => ( <div className='statuses-grid__item' key={statusId}> <DetailedStatusContainer id={statusId} compact measureHeight onHeightChange={this.handleHeightChange} /> </div> )).toArray()} </Masonry> ); } }
src/shared/components/imageListItem/imageListItem.js
tal87/operationcode_frontend
import React from 'react'; import PropTypes from 'prop-types'; import styles from './imageListItem.css'; const ImageListItem = props => ( <div className={styles.imageListItem}> <img className={styles.cardImage} src={props.image} alt={props.title} /> <div className={styles.cardText}> <h3 className={styles.cardTitle}>{props.title}</h3> <p>{props.cardText}</p> </div> </div> ); ImageListItem.propTypes = { image: PropTypes.string.isRequired, title: PropTypes.string.isRequired, cardText: PropTypes.string.isRequired }; export default ImageListItem;
app/components/results-Child/Player.js
mohamekasem/reactstart
import React from 'react'; import PropTypes from 'prop-types'; import PlayerPreview from '../Battle-Child/Player-Preview'; const Profile = (props)=>{ let info = props.info; return ( <PlayerPreview username={info.login} avatar={info.avatar_url}> <ul className='space-list-items'> {info.name && <li>{info.name}</li>} {info.location && <li>{info.location}</li>} {info.company && <li>{info.company}</li>} <li>Followers: {info.followers}</li> <li>Following: {info.following}</li> <li>Public Repos: {info.public_repos}</li> {info.blog && <li><a href={info.blog}>{info.blog}</a></li>} </ul> </PlayerPreview> ) } Profile.PropTypes = { info: PropTypes.object.isRquired } const Player = (props)=> { return ( <div> <h1>{props.label}</h1> <h3 style={{textAlign: 'centr'}}>Score: {props.score}</h3> <Profile info={props.profile} /> </div> ) } Player.propTypes = { label: PropTypes.string.isRequired, score: PropTypes.number.isRequired, profile: PropTypes.object.isRequired, } export default Player;
src/components/dashboard/feed/item.js
cosminseceleanu/react-sb-admin-bootstrap4
import React from 'react'; import Comment from "./comment"; import ItemActions from "./item-actions"; import { Card, CardImg, CardBody, CardFooter, CardTitle, CardText } from 'reactstrap'; const Item = ({item}) => { return ( <Card className="mb-3"> <CardImg top width="100%" src={item.photo}/> <CardBody> <CardTitle><a href="/">{item.user}</a></CardTitle> <CardText className="small"> {item.description} {renderHashTags(item.tags)} </CardText> </CardBody> <hr className="my-0"/> <ItemActions/> <hr className="my-0"/> <CardBody className="small bg-faded"> {renderComments(item.comments)} </CardBody> <CardFooter className="small text-muted">{item.date}</CardFooter> </Card> ) }; const renderHashTags = tags => { return tags.map((tag, index) => { return ( <a key={index} href="/"> {tag}</a> ) }) }; const renderComments = comments => { return comments.map((comment, index) => { const reply = comment.reply ? renderComment(comment.reply, null) : null; return renderComment(comment, reply, index); }) }; const renderComment = (comment, reply = null, index) => { return ( <Comment key={reply !== null ? `reply-${index}` : index} {...comment}>{reply}</Comment> ) }; export default Item;
src/Nav/Nav.js
brz0/folio-v11
import React from 'react'; import Modal from 'react-modal'; import {Link} from 'react-router'; import LogoLight from '../img/logo-light.svg'; import LogoDark from '../img/logo-dark.svg'; import MenuBtn from '../img/menu-btn.svg'; import MenuBtnDark from '../img/menu-btn-dark.svg'; import MenuClose from '../img/menuClose.svg'; const customStyles = { content: { top: 'auto', left: 'auto', right: '0px', bottom: 'auto', transform: 'none', width: '300px', height: '100%', position: 'fixed', marginRight: '0px', backgroundColor: '#F21F40', border: 'none', borderRadius: '0px', zIndex: 4, padding: '0px', }, overlay: { backgroundColor: 'transparent', zIndex: 4, } }; function setStyle( objId, propertyObject ) { var elem = document.getElementById(objId); for (var property in propertyObject) elem.style[property] = propertyObject[property]; } var scrollObject = {}; function getScrollPosition(){ scrollObject = { x: window.pageXOffset, y: window.pageYOffset } if(scrollObject.y > window.innerHeight - 50) { setStyle('nav', {'background': '#F8F5F9', 'transition': '1s'}); setStyle('logoLight', {'display': 'none', 'transition': '1s'}); setStyle('logoDark', {'display': 'inline-block', 'transition': '1s'}); setStyle('menuLight', {'display': 'none', 'transition': '1s'}); setStyle('menuDark', {'display': 'block', 'transition': '1s'}); document.activeElement.blur(); } else { setStyle('nav', {'background': 'transparent', 'transition': '1s'}); setStyle('logoLight', {'display': 'inline-block', 'transition': '1s'}); setStyle('logoDark', {'display': 'none', 'transition': '1s'}); setStyle('menuLight', {'display': 'block', 'transition': '1s'}); setStyle('menuDark', {'display': 'none', 'transition': '1s'}); } } window.onscroll = getScrollPosition; export default class Nav extends React.Component { constructor() { super(); this.state = { modalIsOpen: false }; this.openModal = this.openModal.bind(this); this.afterOpenModal = this.afterOpenModal.bind(this); this.closeModal = this.closeModal.bind(this); } openModal() { this.setState({modalIsOpen: true}); } afterOpenModal() {} closeModal() { this.setState({modalIsOpen: false}); } render() { return ( <div> <div className="navWrap" id="nav"> <Link to="/"><img src={LogoLight} className="logoNav" id="logoLight" alt="Justin Brazeau" /></Link> <Link to="/"><img src={LogoDark} className="logoNav" id="logoDark" alt="Justin Brazeau" /></Link> <img src={MenuBtn} className="menuBtn" id="menuLight" alt="Menu" onClick={this.openModal} /> <img src={MenuBtnDark} className="menuBtn" id="menuDark" alt="Menu" onClick={this.openModal} /> </div> <Modal isOpen={this.state.modalIsOpen} onAfterOpen={this.afterOpenModal} onRequestClose={this.closeModal} style={customStyles} contentLabel="Example Modal" > <button onClick={this.closeModal} className="modalBtnClose"> <img src={MenuClose} className="modalBtnCloseImg" /> </button> <div className="menuList"> <h2>Projects</h2> <ul> <Link to="chart-suite"><li><span>Chart Suite</span></li></Link> <Link to="terminal-ui"><li><span>Terminal UI</span></li></Link> <Link to="homes-from-the-future"><li><span>Future Homes</span></li></Link> <Link to="odd-scenes"><li><span>Odd Scenes</span></li></Link> <Link to="walltagged"><li><span>WallTagged</span></li></Link> <Link to="gold-tooth"><li><span>Gold Tooth</span></li></Link> </ul> </div> <div className="bottonMenuWrap"> <div className="buttonMenu"> <a href="http://be.net/justinbrazeau"> <div className="buttonMenuInner btnMenuLeft"> <i className="fa fa-behance" aria-hidden="true"></i> <span>behance</span> </div> </a> </div> <div className="buttonMenu"> <a href="http://codepen.io/brz0"> <div className="buttonMenuInner btnMenuRight"> <i className="fa fa-codepen" aria-hidden="true"></i> <span>codepen</span> </div> </a> </div> <div className="buttonMenu"> <a href="http://twitter.com/justinbrazeau"> <div className="buttonMenuInner btnMenuLeft buttonMenuInnerBottom"> <i className="fa fa-twitter" aria-hidden="true"></i> <span>twitter</span> </div> </a> </div> <div className="buttonMenu"> <a href="http://github.com/brz0"> <div className="buttonMenuInner btnMenuRight buttonMenuInnerBottom"> <i className="fa fa-github" aria-hidden="true"></i> <span>github</span> </div> </a> </div> </div> </Modal> </div> ) } }
app/react-icons/fa/hand-peace-o.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaHandPeaceO extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m31.8 14.4q1.3 0 2.3 0.6 3.2 1.4 3.2 5v3.9q0 2.2-0.5 4.2l-1.9 7.6q-0.5 1.9-2 3.1t-3.6 1.2h-14.9q-2.3 0-4-1.7t-1.7-4v-9l-5.3-14q-0.4-1-0.4-2 0-2.4 1.7-4.1t4-1.6q1.8 0 3.3 1t2 2.7l0.4 0.9v-2.5q0-2.4 1.7-4t4-1.7 4.1 1.7 1.7 4v5.8q0.6-0.1 1-0.1 1.6 0 2.9 0.8t1.9 2.2z m-4.9-0.1q-0.7 0-1.3 0.4t-0.9 1.1l-1.7 3.6-1.6 3.5h1.2q1.2 0 2.1 0.7t1.1 1.8l3.4-7.6q0.2-0.4 0.2-1 0-1-0.7-1.8t-1.8-0.7z m5 3q-0.5 0-0.9 0.2t-0.7 0.3-0.5 0.7-0.4 0.7-0.4 0.8l-2.9 6.5q-0.2 0.4-0.2 1 0 1 0.7 1.8t1.8 0.7q0.7 0 1.3-0.4t0.9-1.1l3.6-7.8q0.2-0.4 0.2-0.9 0-1.1-0.7-1.8t-1.8-0.7z m-26-8q0 0.5 0.1 1l5.6 14.5v1.6l2.2-2.5q1-1 2.4-1h4.4l2.4-5.2v-12q0-1.2-0.8-2t-2.1-0.8-2 0.8-0.8 2v14.3h-1.4l-4.5-11.7q-0.3-0.9-1.1-1.4t-1.6-0.5q-1.2 0-2 0.9t-0.8 2z m23.4 27.8q1 0 1.8-0.6t1-1.5l1.9-7.6q0.4-1.6 0.4-3.5v-2l-3.1 6.9q-0.4 0.9-1.2 1.4t-1.7 0.5q-1.2 0-2.1-0.8t-1.1-1.9q-1 1.3-2.6 1.3h-4.6v-0.7h4.6q1.1 0 1.8-0.8t0.8-1.7-0.7-1.8-1.7-0.7h-6.6q-1.1 0-1.8 0.8l-2.8 3v6.9q0 1.2 0.8 2t2 0.8h14.9z"/></g> </IconBase> ); } }
src/scripts/components/app.js
k-takam/simple-text-translator
import React, { Component } from 'react'; import Header from './header'; import Footer from './footer'; import MenuContainer from '../containers/menu-container'; import InputTextContainer from '../containers/input-text-container'; import OutputTextContainer from '../containers/output-text-container'; import ModalContainer from '../containers/modal-container'; export default class App extends Component { render() { return ( <div className="wrapper"> <Header /> <section className="section"> <div className="container"> <div className="columns is-multiline"> <div className="column is-half"> <p>テキストを日本語から英語へ翻訳します。</p> </div> <MenuContainer /> <InputTextContainer /> <OutputTextContainer /> </div> </div> <ModalContainer /> </section> <Footer /> </div> ); } }
app/components/Vesting/CancelPowerDownPrompt.js
aaroncox/vessel
// @flow import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Message, Modal, Segment } from 'semantic-ui-react'; import { Form } from 'formsy-semantic-ui-react' import * as KeysActions from '../../actions/keys'; class CancelPowerDownPrompt extends Component { handleConfirm = (e: SyntheticEvent) => { const account = this.props.targetAccount; const permissions = this.props.keys.permissions; // console.log('cancelWithdrawVesting', { account }, permissions[account]); this.props.actions.useKey('cancelWithdrawVesting', { account }, permissions[account]); e.preventDefault(); } handleOnChange = (value) => { const vests = parseFloat(value).toFixed(6); const props = this.props.hive.props; const totalVestsHive = parseFloat(props.total_vesting_fund_steem.split(" ")[0]) const totalVests = parseFloat(props.total_vesting_shares.split(" ")[0]) const sp = totalVestsHive * vests / totalVests; const perWeek = Math.round(sp / 13 * 1000) / 1000; this.setState({ vests, sp, perWeek }); } handleOnChangeComplete = (value) => { const vests = parseFloat(value).toFixed(6); const props = this.props.hive.props; const totalVestsHive = parseFloat(props.total_vesting_fund_steem.split(" ")[0]) const totalVests = parseFloat(props.total_vesting_shares.split(" ")[0]) const sp = totalVestsHive * vests / totalVests; const perWeek = Math.round(sp / 13 * 1000) / 1000; this.setState({ vests, sp, perWeek }); } render() { const { account_vesting_withdraw_error, account_vesting_withdraw_pending, account_vesting_withdraw_resolved } = this.props.processing; return ( <Modal size="small" open header="Cancel - Power Down" content={ <Form error={account_vesting_withdraw_error} loading={account_vesting_withdraw_pending} > <Segment padded basic > <p> Cancelling this power down cannot be reversed. Any progress on your current week's credit will be reset, and if you power down again, you'll have to wait another 7 days for it to begin. </p> <Message error header="Operation Error" content={account_vesting_withdraw_error} /> </Segment> </Form> } actions={[ { key: 'no', content: 'Cancel Operation', floated: 'left', color: 'red', onClick: this.props.handleCancel, disabled: account_vesting_withdraw_pending }, { key: 'yes', type: 'submit', content: 'Cancel Power Down', color: 'blue', onClick: this.handleConfirm, disabled: account_vesting_withdraw_pending } ]} /> ); } } function mapStateToProps(state) { return { account: state.account, keys: state.keys, hive: state.hive }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({ ...KeysActions }, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(CancelPowerDownPrompt);
src/prop-types.js
narendrashetty/react-geosuggest
import React from 'react'; /** * Default values */ export default { fixtures: React.PropTypes.array, initialValue: React.PropTypes.string, placeholder: React.PropTypes.string, disabled: React.PropTypes.bool, className: React.PropTypes.string, inputClassName: React.PropTypes.string, suggestsHiddenClassName: React.PropTypes.string, suggestItemActiveClassName: React.PropTypes.string, location: React.PropTypes.object, radius: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]), bounds: React.PropTypes.object, country: React.PropTypes.string, types: React.PropTypes.array, queryDelay: React.PropTypes.number, googleMaps: React.PropTypes.object, onSuggestSelect: React.PropTypes.func, onFocus: React.PropTypes.func, onBlur: React.PropTypes.func, onChange: React.PropTypes.func, onKeyPress: React.PropTypes.func, skipSuggest: React.PropTypes.func, getSuggestLabel: React.PropTypes.func, autoActivateFirstSuggest: React.PropTypes.bool, style: React.PropTypes.shape({ input: React.PropTypes.object, suggests: React.PropTypes.object, suggestItem: React.PropTypes.object }), ignoreTab: React.PropTypes.bool, label: React.PropTypes.string };
app/templates/src/createRoutes.js
chentsulin/generator-redux-app
import React from 'react'; import { Route } from 'react-router'; import App from './containers/App'; import * as containers from './containers'; const { CounterPage, AnotherPage, NotFoundPage, } = containers; /** * / * /another **/ const createRoutes = store => ( // eslint-disable-line no-unused-vars <Route component={App}> <Route path="/" component={CounterPage} /> <Route path="/another" component={AnotherPage} /> <Route path="*" component={NotFoundPage} /> </Route> ); export default createRoutes;
src/Popover.js
JimiHFord/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import CustomPropTypes from './utils/CustomPropTypes'; const Popover = React.createClass({ mixins: [ BootstrapMixin ], propTypes: { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: CustomPropTypes.isRequiredForA11y( React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) ), /** * Sets the direction the Popover is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "left" position value for the Popover. */ positionLeft: React.PropTypes.number, /** * The "top" position value for the Popover. */ positionTop: React.PropTypes.number, /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * Title text */ title: React.PropTypes.node }, getDefaultProps() { return { placement: 'right' }; }, render() { const classes = { 'popover': true, [this.props.placement]: true }; const style = { 'left': this.props.positionLeft, 'top': this.props.positionTop, 'display': 'block', // we don't want to expose the `style` property ...this.props.style // eslint-disable-line react/prop-types }; const arrowStyle = { 'left': this.props.arrowOffsetLeft, 'top': this.props.arrowOffsetTop }; return ( <div role="tooltip" {...this.props} className={classNames(this.props.className, classes)} style={style} title={null}> <div className="arrow" style={arrowStyle} /> {this.props.title ? this.renderTitle() : null} <div className="popover-content"> {this.props.children} </div> </div> ); }, renderTitle() { return ( <h3 className="popover-title">{this.props.title}</h3> ); } }); export default Popover;
src/routes.js
kunwardeep/react-redux-store
import React from 'react'; import {Route,IndexRoute} from 'react-router'; import HomePage from './components/home/HomePage'; import App from './components/App'; import AboutPage from './components/about/AboutPage'; import CoursesPage from './components/course/CoursesPage'; import PracticePage from './components/practice/PracticePage'; import ManageCoursePage from './components/course/ManageCoursePage'; export default( <Route path="/" component={App}> <IndexRoute component={HomePage}/> <Route path="about" component={AboutPage}/> <Route path="courses" component={CoursesPage}/> <Route path="course/:id" component={ManageCoursePage}/> <Route path="course" component={ManageCoursePage}/> <Route path="practice" component={PracticePage}/> </Route> );
docs/build.js
leozdgao/react-bootstrap
import React from 'react'; import path from 'path'; import Router from 'react-router'; import routes from './src/Routes'; import Root from './src/Root'; import fsp from 'fs-promise'; import { copy } from '../tools/fs-utils'; import { exec } from '../tools/exec'; import metadata from './generate-metadata'; const repoRoot = path.resolve(__dirname, '../'); const docsBuilt = path.join(repoRoot, 'docs-built'); const license = path.join(repoRoot, 'LICENSE'); const readmeSrc = path.join(__dirname, 'README.docs.md'); const readmeDest = path.join(docsBuilt, 'README.md'); /** * Generates HTML code for `fileName` page. * * @param {string} fileName Path for Router.Route * @return {Promise} promise * @internal */ function generateHTML(fileName, propData) { return new Promise((resolve, reject) => { const urlSlug = fileName === 'index.html' ? '/' : `/${fileName}`; Router.run(routes, urlSlug, Handler => { let html = React.renderToString(React.createElement(Handler, { propData })); html = '<!doctype html>' + html; let write = fsp.writeFile(path.join(docsBuilt, fileName), html); resolve(write); }); }); } export default function BuildDocs({ dev }) { console.log('Building: '.cyan + 'docs'.green + (dev ? ' [DEV]'.grey : '')); return exec(`rimraf ${docsBuilt}`) .then(() => fsp.mkdir(docsBuilt)) .then(metadata) .then(propData => { let pagesGenerators = Root.getPages().map( page => generateHTML(page, propData)); return Promise.all(pagesGenerators.concat([ exec(`webpack --config webpack.docs.js ${dev ? '' : '-p '}--bail`), copy(license, docsBuilt), copy(readmeSrc, readmeDest) ])); }) .then(() => console.log('Built: '.cyan + 'docs'.green + (dev ? ' [DEV]'.grey : ''))); }
actor-apps/app-web/src/app/components/ActivitySection.react.js
shaunstanislaus/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import ActivityActionCreators from 'actions/ActivityActionCreators'; import ActorAppConstants from 'constants/ActorAppConstants'; import ActivityStore from 'stores/ActivityStore'; import UserProfile from 'components/activity/UserProfile.react'; import GroupProfile from 'components/activity/GroupProfile.react'; import classNames from 'classnames'; const ActivityTypes = ActorAppConstants.ActivityTypes; var getStateFromStores = function() { return { activity: ActivityStore.getActivity() }; }; class ActivitySection extends React.Component { constructor() { super(); this.setActivityClosed = this.setActivityClosed.bind(this); this.onChange = this.onChange.bind(this); this.state = getStateFromStores(); } componentDidMount() { ActivityStore.addChangeListener(this.onChange); } componentWillUnmount() { ActivityStore.removeChangeListener(this.onChange); } render() { let activity = this.state.activity; if (activity !== null) { let activityTitle; let activityBody; let activityClassName = classNames('activity', { 'activity--shown': true }); switch (activity.type) { case ActivityTypes.USER_PROFILE: activityTitle = 'User information'; activityBody = <UserProfile user={activity.user}/>; break; case ActivityTypes.GROUP_PROFILE: activityTitle = 'Group information'; activityBody = <GroupProfile group={activity.group}/>; break; default: } return ( <section className={activityClassName}> <ActivitySection.Header close={this.setActivityClosed} title={activityTitle}/> {activityBody} </section> ); } else { return (null); } } setActivityClosed() { ActivityActionCreators.hide(); } onChange() { this.setState(getStateFromStores()); } } ActivitySection.Header = React.createClass({ propTypes: { close: React.PropTypes.func, title: React.PropTypes.string }, mixins: [PureRenderMixin], render() { let title = this.props.title; let close = this.props.close; var headerTitle; if (typeof title !== 'undefined') { headerTitle = <span className="activity__header__title">{title}</span>; } return ( <header className="activity__header toolbar"> <a className="activity__header__close material-icons" onClick={close}>clear</a> {headerTitle} </header> ); } }); export default ActivitySection;
src/components/gradients/h-gradient.js
mapbox/react-colorpickr
import React from 'react'; import PropTypes from 'prop-types'; import themeable from 'react-themeable'; import { autokey } from '../../autokey'; function HGradient({ theme, active, hueBackground }) { const themer = autokey(themeable(theme)); if (!active) return <noscript />; return ( <> <div {...themer('gradient')} style={{ backgroundColor: hueBackground }} /> <div {...themer('gradient', 'gradientHue')} /> </> ); } HGradient.propTypes = { theme: PropTypes.object.isRequired, active: PropTypes.bool.isRequired, hueBackground: PropTypes.string.isRequired }; export { HGradient };
packages/react/components/fab-buttons.js
AdrianV/Framework7
import React from 'react'; import Utils from '../utils/utils'; import Mixins from '../utils/mixins'; import __reactComponentSlots from '../runtime-helpers/react-component-slots.js'; import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js'; class F7FabButtons extends React.Component { constructor(props, context) { super(props, context); } render() { const props = this.props; const { className, id, style, position } = props; const classes = Utils.classNames(className, 'fab-buttons', `fab-buttons-${position}`, Mixins.colorClasses(props)); return React.createElement('div', { id: id, style: style, className: classes }, this.slots['default']); } get slots() { return __reactComponentSlots(this.props); } } __reactComponentSetProps(F7FabButtons, Object.assign({ id: [String, Number], position: { type: String, default: 'top' } }, Mixins.colorProps)); F7FabButtons.displayName = 'f7-fab-buttons'; export default F7FabButtons;
src/react/connect.js
krasimir/stent
import React from 'react'; import connect from '../helpers/connect'; export default function(Component) { const withFunc = (...names) => { const mapFunc = (done, once, silent) => { const mapping = once ? "mapOnce" : silent ? "mapSilent" : "map"; return class StentConnect extends React.Component { constructor(props) { super(props); this.initialStateHasBeenSet = false; this.state = {}; this.disconnect = connect({ meta: { component: Component.name } }) .with(...names) [mapping]((...deps) => { const nextState = done ? done(...deps) : {}; if ( this.initialStateHasBeenSet === false && mapping !== 'mapSilent' ) { this.state = nextState; this.initialStateHasBeenSet = true; return; } this.setState(function () { return nextState; }); }); } componentWillUnmount() { if (this.disconnect) { this.disconnect(); } } render() { return <Component {...this.state} {...this.props} />; } } } return { 'map': mapFunc, 'mapOnce': done => mapFunc(done, true), 'mapSilent': done => mapFunc(done, false, true), } } return { 'with': withFunc }; }
site/demos/ecommerce/src/index.js
appbaseio/reactivesearch
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('app'));
assets/js/components/SignInModal.js
basarevych/webfm
import React from 'react'; import PropTypes from 'prop-types'; import { Map } from 'immutable'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import { Form, FormGroup, Label, Col, Input } from 'reactstrap'; import RequiredFieldLabel from './RequiredFieldLabel'; import FormMessages from './FormMessages'; import FieldErrors from './FieldErrors'; class SignInModal extends React.Component { static propTypes = { isOpen: PropTypes.bool.isRequired, isLocked: PropTypes.bool.isRequired, values: PropTypes.instanceOf(Map).isRequired, messages: PropTypes.instanceOf(Map).isRequired, errors: PropTypes.instanceOf(Map).isRequired, onToggle: PropTypes.func.isRequired, onInput: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { isOpen: props.isOpen, isLocked: props.isLocked, ignoreBlur: true, nextFocus: null, }; this.loginInput = React.createRef(); this.passwordInput = React.createRef(); this.handleInput = this.handleInput.bind(this); this.handleKeyPress = this.handleKeyPress.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } static getDerivedStateFromProps(nextProps, prevState) { let state = {}; if (nextProps.isOpen !== prevState.isOpen) state.isOpen = nextProps.isOpen; if (nextProps.isLocked !== prevState.isLocked) state.isLocked = nextProps.isLocked; if (state.isOpen === true) { state.nextFocus = 'login'; } else if (state.isLocked === false) { if (nextProps.errors.has('login')) state.nextFocus = 'login'; else if (nextProps.errors.has('password')) state.nextFocus = 'password'; } return _.keys(state).length ? state : null; } handleInput(event) { if (this.props.isLocked) return; this.props.onInput({ [event.target.name]: event.target.value }); } handleKeyPress(event) { if (this.props.isLocked || event.charCode !== 13) // enter return; switch (event.target.name) { case 'login': if (this.passwordInput.current) setTimeout(() => this.passwordInput.current.focus(), 0); break; case 'password': this.handleSubmit(); break; } } handleFocus() { if (this.props.isLocked) return; this.setState({ ignoreBlur: false }); } handleBlur(event) { if (this.props.isLocked || this.state.ignoreBlur) return; let submittedAt = Date.now(); let field = event.target.name; setTimeout( () => { if (this.props.isLocked || this.state.ignoreBlur) return; this.props.onSubmit(submittedAt, field); }, 250 ); } handleSubmit() { if (this.props.isLocked) return; this.setState({ ignoreBlur: true }); this.props.onSubmit(Date.now()); } componentDidUpdate() { if (this.state.nextFocus) { let field = this.state.nextFocus; this.setState({ nextFocus: null }, () => { switch (field) { case 'login': if (this.loginInput.current) setTimeout(() => this.loginInput.current.focus(), 0); break; case 'password': if (this.passwordInput.current) setTimeout(() => this.passwordInput.current.focus(), 0); break; } }); } } render() { return ( <Modal isOpen={this.props.isOpen} toggle={this.props.onToggle} backdrop="static" fade centered > <ModalHeader toggle={this.props.onToggle}>{__('sign_in_title')}</ModalHeader> <ModalBody> <Form> <FormMessages messages={this.props.messages} /> <FormGroup row> <Label for="signInLogin" sm={4} className="text-sm-right"> {__('login_label')} <RequiredFieldLabel /> </Label> <Col sm={8}> <Input type="text" name="login" id="signInLogin" disabled={this.props.isLocked} invalid={this.props.errors.has('login')} value={this.props.values.get('login')} onChange={this.handleInput} onKeyPress={this.handleKeyPress} onFocus={this.handleFocus} onBlur={this.handleBlur} innerRef={this.loginInput} /> <FieldErrors errors={this.props.errors.get('login')} /> </Col> </FormGroup> <FormGroup row> <Label for="signInPassword" sm={4} className="text-sm-right"> {__('password_label')} <RequiredFieldLabel /> </Label> <Col sm={8}> <Input type="password" name="password" id="signInPassword" disabled={this.props.isLocked} invalid={this.props.errors.has('password')} value={this.props.values.get('password')} onChange={this.handleInput} onKeyPress={this.handleKeyPress} onFocus={this.handleFocus} onBlur={this.handleBlur} innerRef={this.passwordInput} /> <FieldErrors errors={this.props.errors.get('password')} /> </Col> </FormGroup> </Form> </ModalBody> <ModalFooter> <Button color="secondary" disabled={this.props.isLocked} onClick={this.props.onToggle}> {__('cancel_button')} </Button> &nbsp; <Button color="primary" disabled={this.props.isLocked} onClick={this.handleSubmit}> {__('submit_button')} </Button> </ModalFooter> </Modal> ); } } export default SignInModal;
src/core/UserProfileStructure/ProfileImage/component.js
dlennox24/ricro-app-template
import { Collapse } from '@material-ui/core'; import Button from '@material-ui/core/Button'; import withStyles from '@material-ui/core/styles/withStyles'; import Typography from '@material-ui/core/Typography'; import classNames from 'classnames'; import _ from 'lodash'; import IconPencil from 'mdi-material-ui/Pencil'; import PropTypes from 'prop-types'; import React from 'react'; import userDefaultProfileImg from '../../../assets/img/default-profile.svg'; import { userShape } from '../../../assets/propTypes'; import FileDropzone from '../../../component/FileDropzone'; import FileDropzoneList from '../../../component/FileDropzoneList'; import styles from './styles'; class ProfileImage extends React.Component { state = { dropzoneFunc: {}, files: [], }; handleUpdateFiles = files => { this.setState({ files }); }; handleLoadDropzoneFunc = funcs => { this.setState({ dropzoneFunc: funcs }); }; handleUploadSuccess = apiResp => { this.props.handleReduxUpdateProfileImage(apiResp.data.result.newPath); }; createHelpText = () => { const { classes } = this.props; const { dropzoneFunc, files } = this.state; return ( <React.Fragment> {!_.isEmpty(dropzoneFunc) && ( <Collapse className={classes.fileListContainer} in={files.length > 0}> <FileDropzoneList files={files} onRemoveFile={dropzoneFunc.handleRemove} /> <Button variant="contained" color="primary" fullWidth onClick={dropzoneFunc.handleUpload} > Update Profile Image </Button> </Collapse> )} <Collapse in={files.length < 1}> <Typography className={classes.uploadInstructions} variant="caption"> Click the image above or drag and drop an image file to change the profile image. Images must be square and of the type <code>.jpg</code>. </Typography> </Collapse> </React.Fragment> ); }; render() { const { api, classes, loggedInUserId, user } = this.props; const { files } = this.state; const image = ( <img className={classes.profileImage} src={user.profileImage ? api.host + user.profileImage : userDefaultProfileImg} alt={user.displayName} /> ); return user.csuId !== loggedInUserId ? ( image ) : ( <React.Fragment> <FileDropzone axiosData={{ csuId: user.csuId }} axiosPath={api.editProfileImagePath} dragRootClassName={classes.dragRoot} dropzoneProps={{ accept: 'image/jpeg', multiple: false, onClick: null, }} maxFiles={1} onFilesChange={this.handleUpdateFiles} onLoadFunc={this.handleLoadDropzoneFunc} onUploadSuccessFunc={this.handleUploadSuccess} > {() => ( <div className={classNames(files.length < 1 && classes.editImageContainer)}> {files.length < 1 && ( <div className={classes.profileImageEdit}> <Typography color="inherit" component="div" className={classes.dragIconContainer}> <IconPencil /> </Typography> <Typography color="inherit" component="div" variant="h6"> Edit Image </Typography> </div> )} <div className={classes.profileImageCover}>{image}</div> </div> )} </FileDropzone> {this.createHelpText()} </React.Fragment> ); } } ProfileImage.propTypes = { api: PropTypes.object.isRequired, // redux state classes: PropTypes.object.isRequired, // MUI withStyles() handleReduxUpdateProfileImage: PropTypes.func.isRequired, // redux dispatch loggedInUserId: PropTypes.number.isRequired, // redux state user: userShape.isRequired, }; export default withStyles(styles)(ProfileImage);
src/svg-icons/image/crop-3-2.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCrop32 = (props) => ( <SvgIcon {...props}> <path d="M19 4H5c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H5V6h14v12z"/> </SvgIcon> ); ImageCrop32 = pure(ImageCrop32); ImageCrop32.displayName = 'ImageCrop32'; ImageCrop32.muiName = 'SvgIcon'; export default ImageCrop32;
client/src/components/Draftail/Tooltip/Tooltip.js
jnns/wagtail
import PropTypes from 'prop-types'; import React from 'react'; const TOP = 'top'; const LEFT = 'left'; const TOP_LEFT = 'top-left'; const getTooltipStyles = (target, direction) => { const top = window.pageYOffset + target.top; const left = window.pageXOffset + target.left; switch (direction) { case TOP: return { top: top + target.height, left: left + target.width / 2, }; case LEFT: return { top: top + target.height / 2, left: left + target.width, }; case TOP_LEFT: default: return { top: top + target.height, left: left, }; } }; /** * A tooltip, with arbitrary content. */ const Tooltip = ({ target, children, direction }) => ( <div style={getTooltipStyles(target, direction)} className={`Tooltip Tooltip--${direction}`} role="tooltip" > {children} </div> ); Tooltip.propTypes = { target: PropTypes.shape({ top: PropTypes.number.isRequired, left: PropTypes.number.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, }).isRequired, direction: PropTypes.oneOf([TOP, LEFT, TOP_LEFT]).isRequired, children: PropTypes.node.isRequired, }; export default Tooltip;
src/js/components/icons/base/Detach.js
odedre/grommet-final
/** * @description Detach SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M4,4 L20,20 M22,12 C22,12 16.7200572,17.2799437 16.7200572,17.2799437 M15,19 C15,19 13.7932491,20.2067517 13.0000004,21.0000004 C6.99999996,27.0000004 -2.00000007,18.0000004 3.99999994,12.0000004 C4.88551518,11.1144851 6,10 6,10 M8,8 C8,8 10.1615592,5.83844087 13,3.00000008 C17,-0.999999955 23,4.99999994 19,9.00000005 C16.9873313,11.0126688 14,14 14,14 M12,16 C12,16 10.6478339,17.3521667 9.99999995,18.0000004 C7.99999952,20 5,17 6.99999995,15.0000004 C7.50049504,14.4995054 9,13 9,13 M11,11 C10.7388543,11.261146 16,6 16,6"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-detach`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'detach'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M4,4 L20,20 M22,12 C22,12 16.7200572,17.2799437 16.7200572,17.2799437 M15,19 C15,19 13.7932491,20.2067517 13.0000004,21.0000004 C6.99999996,27.0000004 -2.00000007,18.0000004 3.99999994,12.0000004 C4.88551518,11.1144851 6,10 6,10 M8,8 C8,8 10.1615592,5.83844087 13,3.00000008 C17,-0.999999955 23,4.99999994 19,9.00000005 C16.9873313,11.0126688 14,14 14,14 M12,16 C12,16 10.6478339,17.3521667 9.99999995,18.0000004 C7.99999952,20 5,17 6.99999995,15.0000004 C7.50049504,14.4995054 9,13 9,13 M11,11 C10.7388543,11.261146 16,6 16,6"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Detach'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
app/containers/Root.js
pamler/electron-mario
// @flow import React from 'react'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'react-router-redux'; import Routes from '../routes'; type RootType = { store: {}, history: {} }; export default function Root({ store, history }: RootType) { return ( <Provider store={store}> <ConnectedRouter history={history}> <Routes /> </ConnectedRouter> </Provider> ); }
src/components/repository-section-title.component.js
Antoine38660/git-point
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { StateBadge } from 'components'; import { colors, fonts } from 'config'; type Props = { text: string, openCount: number, closedCount: number, loading: boolean, }; const styles = StyleSheet.create({ title: { flexDirection: 'row', }, titleText: { color: colors.black, ...fonts.fontPrimaryBold, }, badgeContainer: { flexDirection: 'row', marginTop: -7, }, badge: { marginLeft: 10, }, }); export const RepositorySectionTitle = ({ text, loading, openCount, closedCount, }: Props) => { return ( <View style={styles.title}> <Text style={styles.titleText}>{text}</Text> {!loading && ( <View style={styles.badgeContainer}> <StateBadge type="open" text={openCount} style={styles.badge} /> <StateBadge type="closed" text={closedCount} style={styles.badge} /> </View> )} </View> ); };
app/containers/CodingPage/index.js
andresol/homepage
import React from 'react'; import Nav from 'components/Nav'; import StravaSection from 'components/Strava/Section'; const Coding = () => ( <div className="page-wrap"> <Nav index={3} /> <section id="main"> <StravaSection note={'Coding'} action={false} /> <section id="athlets"> <div> <p>Vær info</p> </div> </section> </section> </div> ); export default Coding;
modules/RouteContext.js
brownbathrobe/react-router
import React from 'react' const { object } = React.PropTypes /** * The RouteContext mixin provides a convenient way for route * components to set the route in context. This is needed for * routes that render elements that want to use the Lifecycle * mixin to prevent transitions. */ const RouteContext = { propTypes: { route: object.isRequired }, childContextTypes: { route: object.isRequired }, getChildContext() { return { route: this.props.route } } } export default RouteContext
src/components/EditPaymentMethods.js
OpenCollective/frontend
import React from 'react'; import PropTypes from 'prop-types'; import { Button } from 'react-bootstrap'; import { defineMessages } from 'react-intl'; import withIntl from '../lib/withIntl'; import EditPaymentMethod from './EditPaymentMethod'; class EditPaymentMethods extends React.Component { static propTypes = { paymentMethods: PropTypes.arrayOf(PropTypes.object).isRequired, collective: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; constructor(props) { super(props); this.renderPaymentMethod = this.renderPaymentMethod.bind(this); this.addPaymentMethod = this.addPaymentMethod.bind(this); this.removePaymentMethod = this.removePaymentMethod.bind(this); this.editPaymentMethod = this.editPaymentMethod.bind(this); this.onChange = props.onChange.bind(this); this.defaultType = this.props.defaultType || 'TICKET'; this.messages = defineMessages({ 'paymentMethods.add': { id: 'paymentMethods.add', defaultMessage: 'add another payment method', }, 'paymentMethods.remove': { id: 'paymentMethods.remove', defaultMessage: 'remove payment method', }, }); } /** Returns payment methods from props or a list with an empty entry if empty */ loadPaymentMethodsFromProps(props) { return props.paymentMethods.length === 0 ? [{}] : props.paymentMethods; } editPaymentMethod(paymentMethodId, paymentMethod) { const paymentMethods = [...this.props.paymentMethods]; const index = !paymentMethodId ? paymentMethods.findIndex(pm => !pm.id) : paymentMethods.findIndex(pm => pm.id === paymentMethodId); if (paymentMethod === null) { return this.removePaymentMethod(index); } paymentMethods[index] = { ...paymentMethods[index], ...paymentMethod }; this.onChange({ paymentMethods }); } addPaymentMethod(paymentMethod) { const newPm = paymentMethod || {}; this.onChange({ paymentMethods: [...this.props.paymentMethods, newPm] }); } removePaymentMethod(index) { let paymentMethods = this.props.paymentMethods; if (index < 0 || index > paymentMethods.length) return; paymentMethods = [...paymentMethods.slice(0, index), ...paymentMethods.slice(index + 1)]; this.onChange({ paymentMethods }); } renderPaymentMethod(paymentMethod) { const { collective } = this.props; const keyId = paymentMethod.id || 'new'; const hasMonthlyLimitPerMember = collective.type === 'ORGANIZATION' && paymentMethod.type !== 'prepaid'; return ( <div className="paymentMethod" key={`paymentMethod-${keyId}`}> <EditPaymentMethod paymentMethod={paymentMethod} onChange={pm => this.editPaymentMethod(paymentMethod.id, pm)} editMode={paymentMethod.id ? false : true} monthlyLimitPerMember={hasMonthlyLimitPerMember} currency={collective.currency} slug={collective.slug} /> </div> ); } render() { const { intl, paymentMethods = [] } = this.props; const hasNewPaymentMethod = Boolean(this.props.paymentMethods.find(pm => !pm.id)); return ( <div className="EditPaymentMethods"> <style jsx> {` :global(.paymentMethodActions) { text-align: right; font-size: 1.3rem; } :global(.field) { margin: 1rem; } .editPaymentMethodsActions { text-align: right; } :global(.paymentMethod) { margin: 3rem 0; } `} </style> <div className="paymentMethods">{paymentMethods.map(this.renderPaymentMethod)}</div> {!hasNewPaymentMethod && ( <div className="editPaymentMethodsActions"> <Button bsStyle="primary" onClick={() => this.addPaymentMethod()}> {intl.formatMessage(this.messages['paymentMethods.add'])} </Button> </div> )} </div> ); } } export default withIntl(EditPaymentMethods);
packages/react-scripts/fixtures/kitchensink/src/features/syntax/TemplateInterpolation.js
johnslay/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load(name) { return [ { id: 1, name: `${name}1` }, { id: 2, name: `${name}2` }, { id: 3, name: `${name}3` }, { id: 4, name: `${name}4` }, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load('user_'); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-template-interpolation"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
Libraries/Image/Image.ios.js
cdlewis/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Image * @flow */ 'use strict'; const EdgeInsetsPropType = require('EdgeInsetsPropType'); const ImageResizeMode = require('ImageResizeMode'); const ImageSourcePropType = require('ImageSourcePropType'); const ImageStylePropTypes = require('ImageStylePropTypes'); const NativeMethodsMixin = require('NativeMethodsMixin'); const NativeModules = require('NativeModules'); const React = require('React'); const PropTypes = require('prop-types'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheet = require('StyleSheet'); const StyleSheetPropType = require('StyleSheetPropType'); const createReactClass = require('create-react-class'); const flattenStyle = require('flattenStyle'); const requireNativeComponent = require('requireNativeComponent'); const resolveAssetSource = require('resolveAssetSource'); const ImageViewManager = NativeModules.ImageViewManager; /** * A React component for displaying different types of images, * including network images, static resources, temporary local images, and * images from local disk, such as the camera roll. * * This example shows fetching and displaying an image from local storage * as well as one from network and even from data provided in the `'data:'` uri scheme. * * > Note that for network and data images, you will need to manually specify the dimensions of your image! * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, Image } from 'react-native'; * * export default class DisplayAnImage extends Component { * render() { * return ( * <View> * <Image * source={require('./img/favicon.png')} * /> * <Image * style={{width: 50, height: 50}} * source={{uri: 'https://facebook.github.io/react-native/img/favicon.png'}} * /> * <Image * style={{width: 66, height: 58}} * source={{uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg=='}} * /> * </View> * ); * } * } * * // skip this line if using Create React Native App * AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage); * ``` * * You can also add `style` to an image: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, Image, StyleSheet } from 'react-native'; * * const styles = StyleSheet.create({ * stretch: { * width: 50, * height: 200 * } * }); * * export default class DisplayAnImageWithStyle extends Component { * render() { * return ( * <View> * <Image * style={styles.stretch} * source={require('./img/favicon.png')} * /> * </View> * ); * } * } * * // skip these lines if using Create React Native App * AppRegistry.registerComponent( * 'DisplayAnImageWithStyle', * () => DisplayAnImageWithStyle * ); * ``` * * ### GIF and WebP support on Android * * When building your own native code, GIF and WebP are not supported by default on Android. * * You will need to add some optional modules in `android/app/build.gradle`, depending on the needs of your app. * * ``` * dependencies { * // If your app supports Android versions before Ice Cream Sandwich (API level 14) * compile 'com.facebook.fresco:animated-base-support:1.3.0' * * // For animated GIF support * compile 'com.facebook.fresco:animated-gif:1.3.0' * * // For WebP support, including animated WebP * compile 'com.facebook.fresco:animated-webp:1.3.0' * compile 'com.facebook.fresco:webpsupport:1.3.0' * * // For WebP support, without animations * compile 'com.facebook.fresco:webpsupport:1.3.0' * } * ``` * * Also, if you use GIF with ProGuard, you will need to add this rule in `proguard-rules.pro` : * ``` * -keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl { * public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier); * } * ``` * */ const Image = createReactClass({ displayName: 'Image', propTypes: { /** * > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the * > `resizeMode` style property on `Image` components. The values are `contain`, `cover`, * > `stretch`, `center`, `repeat`. */ style: StyleSheetPropType(ImageStylePropTypes), /** * The image source (either a remote URL or a local file resource). * * This prop can also contain several remote URLs, specified together with * their width and height and potentially with scale/other URI arguments. * The native side will then choose the best `uri` to display based on the * measured size of the image container. A `cache` property can be added to * control how networked request interacts with the local cache. * * The currently supported formats are `png`, `jpg`, `jpeg`, `bmp`, `gif`, * `webp` (Android only), `psd` (iOS only). */ source: ImageSourcePropType, /** * A static image to display while loading the image source. * * - `uri` - a string representing the resource identifier for the image, which * should be either a local file path or the name of a static image resource * (which should be wrapped in the `require('./path/to/image.png')` function). * - `width`, `height` - can be specified if known at build time, in which case * these will be used to set the default `<Image/>` component dimensions. * - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if * unspecified, meaning that one image pixel equates to one display point / DIP. * - `number` - Opaque type returned by something like `require('./image.jpg')`. * * @platform ios */ defaultSource: PropTypes.oneOfType([ // TODO: Tooling to support documenting these directly and having them display in the docs. PropTypes.shape({ uri: PropTypes.string, width: PropTypes.number, height: PropTypes.number, scale: PropTypes.number, }), PropTypes.number, ]), /** * When true, indicates the image is an accessibility element. * @platform ios */ accessible: PropTypes.bool, /** * The text that's read by the screen reader when the user interacts with * the image. * @platform ios */ accessibilityLabel: PropTypes.node, /** * blurRadius: the blur radius of the blur filter added to the image */ blurRadius: PropTypes.number, /** * When the image is resized, the corners of the size specified * by `capInsets` will stay a fixed size, but the center content and borders * of the image will be stretched. This is useful for creating resizable * rounded buttons, shadows, and other resizable assets. More info in the * [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets). * * @platform ios */ capInsets: EdgeInsetsPropType, /** * The mechanism that should be used to resize the image when the image's dimensions * differ from the image view's dimensions. Defaults to `auto`. * * - `auto`: Use heuristics to pick between `resize` and `scale`. * * - `resize`: A software operation which changes the encoded image in memory before it * gets decoded. This should be used instead of `scale` when the image is much larger * than the view. * * - `scale`: The image gets drawn downscaled or upscaled. Compared to `resize`, `scale` is * faster (usually hardware accelerated) and produces higher quality images. This * should be used if the image is smaller than the view. It should also be used if the * image is slightly bigger than the view. * * More details about `resize` and `scale` can be found at http://frescolib.org/docs/resizing-rotating.html. * * @platform android */ resizeMethod: PropTypes.oneOf(['auto', 'resize', 'scale']), /** * Determines how to resize the image when the frame doesn't match the raw * image dimensions. * * - `cover`: Scale the image uniformly (maintain the image's aspect ratio) * so that both dimensions (width and height) of the image will be equal * to or larger than the corresponding dimension of the view (minus padding). * * - `contain`: Scale the image uniformly (maintain the image's aspect ratio) * so that both dimensions (width and height) of the image will be equal to * or less than the corresponding dimension of the view (minus padding). * * - `stretch`: Scale width and height independently, This may change the * aspect ratio of the src. * * - `repeat`: Repeat the image to cover the frame of the view. The * image will keep it's size and aspect ratio. (iOS only) */ resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']), /** * A unique identifier for this element to be used in UI Automation * testing scripts. */ testID: PropTypes.string, /** * Invoked on mount and layout changes with * `{nativeEvent: {layout: {x, y, width, height}}}`. */ onLayout: PropTypes.func, /** * Invoked on load start. * * e.g., `onLoadStart={(e) => this.setState({loading: true})}` */ onLoadStart: PropTypes.func, /** * Invoked on download progress with `{nativeEvent: {loaded, total}}`. * @platform ios */ onProgress: PropTypes.func, /** * Invoked on load error with `{nativeEvent: {error}}`. */ onError: PropTypes.func, /** * Invoked when a partial load of the image is complete. The definition of * what constitutes a "partial load" is loader specific though this is meant * for progressive JPEG loads. * @platform ios */ onPartialLoad: PropTypes.func, /** * Invoked when load completes successfully. */ onLoad: PropTypes.func, /** * Invoked when load either succeeds or fails. */ onLoadEnd: PropTypes.func, }, statics: { resizeMode: ImageResizeMode, /** * Retrieve the width and height (in pixels) of an image prior to displaying it. * This method can fail if the image cannot be found, or fails to download. * * In order to retrieve the image dimensions, the image may first need to be * loaded or downloaded, after which it will be cached. This means that in * principle you could use this method to preload images, however it is not * optimized for that purpose, and may in future be implemented in a way that * does not fully load/download the image data. A proper, supported way to * preload images will be provided as a separate API. * * Does not work for static image resources. * * @param uri The location of the image. * @param success The function that will be called if the image was successfully found and width * and height retrieved. * @param failure The function that will be called if there was an error, such as failing to * to retrieve the image. * * @returns void * * @platform ios */ getSize: function( uri: string, success: (width: number, height: number) => void, failure?: (error: any) => void, ) { ImageViewManager.getSize(uri, success, failure || function() { console.warn('Failed to get size for image: ' + uri); }); }, /** * Prefetches a remote image for later use by downloading it to the disk * cache * * @param url The remote location of the image. * * @return The prefetched image. */ prefetch(url: string) { return ImageViewManager.prefetchImage(url); }, /** * Resolves an asset reference into an object which has the properties `uri`, `width`, * and `height`. The input may either be a number (opaque type returned by * require('./foo.png')) or an `ImageSource` like { uri: '<http location || file path>' } */ resolveAssetSource: resolveAssetSource, }, mixins: [NativeMethodsMixin], /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ viewConfig: { uiViewClassName: 'UIView', validAttributes: ReactNativeViewAttributes.UIView }, render: function() { const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined }; let sources; let style; if (Array.isArray(source)) { style = flattenStyle([styles.base, this.props.style]) || {}; sources = source; } else { const {width, height, uri} = source; style = flattenStyle([{width, height}, styles.base, this.props.style]) || {}; sources = [source]; if (uri === '') { console.warn('source.uri should not be an empty string'); } } const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108 const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108 if (this.props.src) { console.warn('The <Image> component requires a `source` property rather than `src`.'); } if (this.props.children) { throw new Error('The <Image> component cannot contain children. If you want to render content on top of the image, consider using aboslute positioning.'); } return ( <RCTImageView {...this.props} style={style} resizeMode={resizeMode} tintColor={tintColor} source={sources} /> ); }, }); const styles = StyleSheet.create({ base: { overflow: 'hidden', }, }); const RCTImageView = requireNativeComponent('RCTImageView', Image); module.exports = Image;
client/src/components/instructor/InstructorCourseRow.js
yegor-sytnyk/contoso-express
import React from 'react'; const InstructorCourseRow = (props) => { let course = props.course; let activeClass = props.selectedCourseId === course.id ? 'success' : ''; return ( <tr className={activeClass}> <td className="tools"> <a href="#" onClick={props.onSelectClick}><i className="fa fa-hand-o-up fa-lg"></i></a> </td> <td>{course.number}</td> <td>{course.title}</td> <td>{course.department.name}</td> </tr> ); }; InstructorCourseRow.propTypes = { course: React.PropTypes.object.isRequired, selectedCourseId: React.PropTypes.number.isRequired, onSelectClick: React.PropTypes.func.isRequired }; export default InstructorCourseRow;
fields/types/number/NumberColumn.js
ONode/keystone
import React from 'react'; import numeral from 'numeral'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var NumberColumn = React.createClass({ displayName: 'NumberColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || isNaN(value)) return null; const formattedValue = (this.props.col.path === 'money') ? numeral(value).format('$0,0.00') : value; return formattedValue; }, render () { return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = NumberColumn;
src/routes/not-found/NotFound.js
murthymuddu/murthy-umg
/** * 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 PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './NotFound.css'; class NotFound extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1> {this.props.title} </h1> <p>Sorry, the page you were trying to view does not exist.</p> </div> </div> ); } } export default withStyles(s)(NotFound);
ButtonExample/src/containers/DisabledButtons.js
jacklam718/react-native-button-component
import React, { Component } from 'react'; import { View, ScrollView, StyleSheet } from 'react-native'; import ButtonComponent from 'react-native-button-component'; import GroupContainer from '../components/GroupContainer'; export default class DisabledButtons extends Component { render() { return ( <ScrollView style={styles.scrollView}> <View style={styles.container}> <GroupContainer groupTitle="Button" > <ButtonComponent disabled backgroundColors={['#212122', '#414141']} text={'Button'.toUpperCase()} onPress={() => { }} /> </GroupContainer> <GroupContainer groupTitle="Icon Button" > <ButtonComponent disabled image={require('../img/settings.png')} text={'Icon Buttons'.toUpperCase()} onPress={() => { }} /> </GroupContainer> </View> </ScrollView> ); } } const styles = StyleSheet.create({ scrollView: { flex: 1, backgroundColor: '#ffffff', }, container: { marginTop: 64, alignItems: 'center', marginLeft: 10, marginRight: 10, }, });
examples/todomvc/index.js
cyongen/redux
import React from 'react'; import App from './containers/App'; import 'todomvc-app-css/index.css'; React.render( <App />, document.getElementById('root') );
inventapp/src/App/App.js
ladanv/learn-react-js
import React, { Component } from 'react'; import Header from './Header'; import SideNav from './SideNav'; import styles from './App.scss'; const App = ({ children }) => ( <div className="App"> <Header /> <SideNav /> <div className={styles.main}> {children} </div> </div> ); export default App;
client/src/components/thankyou.js
JoeDou/wesayidou
import React from 'react' export default () => { return ( <div className="thankyou"> <div className="thankyou-msg black">We got your</div> <img src="/assets/images/rsvp.jpg" width="600" height="350"/> <div className="thankyou-msg black">Thank You!</div> </div> ) }
main.js
BigAB/can-react-performance-test
import React from 'react'; import ReactDOM from 'react-dom'; import App from "./containers/app"; ReactDOM.render( <App />, document.querySelector( '#app' ) );
app/components/LoadingOverlay.js
LouWii/syno-music-app
import React from 'react'; import '../styles/LoadingOverlay.global.css' class LoadingOverlay extends React.Component { render() { const visibilityClass = this.props.ui.loadingOverlay ? 'running' : 'done' return ( <div className={'loading-overlay '+visibilityClass}> <div className="loading-background"> </div> <div className="loading-wrapper"> <div className="loading-container"> <h3>Loading</h3> <div className="progress"> <div className="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style={{width: '100%'}}> <span className="sr-only">100% Complete</span> </div> </div> </div> </div> </div> ) } } export default LoadingOverlay
src/docs/examples/ProgressBar/ExampleProgressBar.js
choudlet/ps-react-choudlet
import React from 'react'; import ProgressBar from 'ps-react/ProgressBar'; /** 80% Example */ export default function ExampleProgressBar() { return <ProgressBar width={200} percent={80} /> }
src/clincoded/static/components/experimental_curation.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 url from 'url'; import { curator_page, content_views, history_views, queryKeyValue, dbxref_prefix_map, external_url_map, country_codes } from './globals'; import { RestMixin } from './rest'; import { Form, FormMixin, Input } from '../libs/bootstrap/form'; import { PanelGroup, Panel } from '../libs/bootstrap/panel'; import { AddResourceId } from './add_external_resource'; import * as CuratorHistory from './curator_history'; import * as methods from './methods'; import { ScoreExperimental } from './score/experimental_score'; import { ScoreViewer } from './score/viewer'; import { renderVariantLabelAndTitle } from '../libs/render_variant_label_title'; import * as curator from './curator'; const CurationMixin = curator.CurationMixin; const RecordHeader = curator.RecordHeader; const ViewRecordHeader = curator.ViewRecordHeader; const CurationPalette = curator.CurationPalette; const PmidSummary = curator.PmidSummary; const PmidDoiButtons = curator.PmidDoiButtons; const DeleteButton = curator.DeleteButton; import * as Assessments from './assessment'; const AssessmentTracker = Assessments.AssessmentTracker; const AssessmentPanel = Assessments.AssessmentPanel; const AssessmentMixin = Assessments.AssessmentMixin; const MAX_VARIANTS = 5; var initialCv = { assessmentTracker: null, // Tracking object for a single assessment experimentalDataAssessed: false, // TRUE if experimental data has been assessed by self or others othersAssessed: false // TRUE if other curators have assessed the experimental data }; var ExperimentalCuration = createReactClass({ mixins: [FormMixin, RestMixin, CurationMixin, AssessmentMixin, CuratorHistory], contextTypes: { navigate: PropTypes.func }, cv: initialCv, /** * Keeps track of values from the query string */ queryValues: {}, getInitialState: function() { this.cv.assessmentTracker = initialCv; return { gdm: null, // GDM object given in UUID annotation: null, // Annotation object given in UUID experimental: null, // If we're editing an Experimental Data entry, this gets the fleshed-out group Experimental Data entry we're editing experimentalNameVisible: false, // Is the Experimental Data Name field visible? experimentalName: '', // Currently entered name of the Experimental Data entry experimentalType: '', // Currently entered type of the Experimental Data entry experimentalTypeDescription: [], // Description of the selected Experimental Data type experimentalSubtype: 'none', // Currently entered subtype of the Experimental Data entry (if applicable) othersAssessed: false, // TRUE if other curators have assessed the experimental data entry geneImplicatedWithDisease: false, // checkbox state values geneImplicatedInDisease: false, expressedInTissue: false, expressedInPatients: false, patientVariantRescue: false, showPatientVariantRescue: true, // Flag for showing 'pateintVariantRescue' wildTypeRescuePhenotype: false, biochemicalFunctionHPO: false, // form enabled/disabled checks biochemicalFunctionFT: false, bioChemicalFunctionIF_GoId: false, // True if GO ID is provided bioChemicalFunctionIF_FreeText: false, // True if free text is provided expressionOT_UberonId: false, // True if Uberon ID is provided expressionOT_FreeText: false, // True if free text is provided functionalAlterationNFG_GoId: false, // True if GO ID is provided functionalAlterationNFG_FreeText: false, // True if free text is provided functionalAlterationPCells_ClId: false, // True if CL Ontology ID is provided functionalAlterationPCells_FreeText: false, // True if free text is provided functionalAlterationNPCells_EfoId: false, // True if EFO ID is provided functionalAlterationNPCells_FreeText: false, // True if free text is provided functionalAlterationType: '', modelSystemsType: '', modelSystemsPOMSHPO: false, modelSystemsPOMSFT: false, modelSystemsPPHPO: false, modelSystemsPPFT: false, modelSystemsCC_EfoId: false, // True if EFO ID is provided modelSystemsCC_FreeText: false, // True if free text is provided rescueType: '', rescuePRHPO: false, rescuePRFT: false, rescuePCells_ClId: false, // True if CL Ontology ID is provided rescuePCells_FreeText: false, // True if free text is provided rescueCC_EfoId: false, // True if EFO ID is provided rescueCC_FreeText: false, // True if free text is provided variantCount: 0, // Number of variants to display variantInfo: {}, // Extra holding info for variant display addVariantDisabled: false, // True if Add Another Variant button enabled submitBusy: false, // True while form is submitting userScoreObj: {}, // Logged-in user's score object uniprotId: '', formError: false }; }, /** * Called by child function props to update user score obj */ handleUserScoreObj: function(newUserScoreObj) { this.setState({userScoreObj: newUserScoreObj}, () => { if (!newUserScoreObj.hasOwnProperty('score') || (newUserScoreObj.hasOwnProperty('score') && newUserScoreObj.score !== false && newUserScoreObj.scoreExplanation)) { this.setState({formError: false}); } }); }, /** * sets the description text below the experimental data type dropdown */ getExperimentalTypeDescription: function(item, subitem) { subitem = typeof subitem !== 'undefined' ? subitem : ''; var experimentalTypeDescriptionList = { 'Biochemical Function': [ 'A. The gene product performs a biochemical function shared with other known genes in the disease of interest', 'B. The gene product is consistent with the observed phenotype(s)' ], 'Protein Interactions': ['The gene product interacts with proteins previously implicated (genetically or biochemically) in the disease of interest'], 'Expression': [ 'A. The gene is expressed in tissues relevant to the disease of interest', 'B. The gene is altered in expression in patients who have the disease' ], 'Functional Alteration': ['The gene and/or gene product function is demonstrably altered in cultured patient or non-patient cells carrying candidate variant(s)'], 'Model Systems': ['Non-human model organism OR cell culture model with a similarly disrupted copy of the affected gene shows a phenotype consistent with human disease state'], 'Rescue': ['The phenotype in humans, non-human model organisms, cell culture models, or patient cells can be rescued by exogenous wild-type gene or gene product'] }; if (subitem == 'A') { return [experimentalTypeDescriptionList[item][0]]; } else if (subitem == 'B') { return [experimentalTypeDescriptionList[item][1]]; } else { return experimentalTypeDescriptionList[item]; } }, /** * Handle value changes in forms */ handleChange: function(ref, e) { var clinvarid, othervariant, user; if (ref === 'experimentalName' && this.refs[ref].getValue()) { this.setState({experimentalName: this.refs[ref].getValue()}); } else if (ref === 'experimentalType') { var tempExperimentalType = this.refs[ref].getValue(); // if assessmentTracker was set previously, reset its value if (this.cv.assessmentTracker) { // set values for assessmentTracker user = this.props.session && this.props.session.user_properties; this.cv.assessmentTracker.setCurrentVal(Assessments.DEFAULT_VALUE); this.setAssessmentValue(this.cv.assessmentTracker, Assessments.DEFAULT_VALUE); } this.setState({ experimentalName: '', experimentalType: tempExperimentalType, experimentalTypeDescription: this.getExperimentalTypeDescription(tempExperimentalType), functionalAlterationType: '', modelSystemsType: '', rescueType: '', geneImplicatedWithDisease: false, geneImplicatedInDisease: false, expressedInTissue: false, expressedInPatients: false, patientVariantRescue: false, wildTypeRescuePhenotype: false }); if (this.state.experimentalNameVisible) { this.refs['experimentalName'].setValue(''); } if (tempExperimentalType == 'none') { // reset form this.setState({ experimentalNameVisible: false, experimentalTypeDescription: [] }); } else if (tempExperimentalType == 'Biochemical Function' || tempExperimentalType == 'Expression') { // display only subtype field if type is Biochemical Function or Expression this.setState({ experimentalSubtype: 'none', experimentalTypeDescription: this.getExperimentalTypeDescription(tempExperimentalType), experimentalNameVisible: false }); } else { this.setState({experimentalNameVisible: true}); } } else if (ref === 'experimentalSubtype') { var tempExperimentalSubtype = this.refs[ref].getValue(); this.setState({experimentalSubtype: tempExperimentalSubtype}); // if assessmentTracker was set previously, reset its value if (this.cv.assessmentTracker) { // set values for assessmentTracker user = this.props.session && this.props.session.user_properties; this.cv.assessmentTracker.setCurrentVal(Assessments.DEFAULT_VALUE); this.setAssessmentValue(this.cv.assessmentTracker, Assessments.DEFAULT_VALUE); } /** * Reset values when changing between Subtypes */ if (this.refs['experimentalName']) { this.refs['experimentalName'].setValue(''); this.setState({experimentalName: ''}); } if (this.refs['identifiedFunction']) { this.refs['identifiedFunction'].setValue(''); } if (this.refs['identifiedFunctionFreeText']) { this.refs['identifiedFunctionFreeText'].setValue(''); } if (this.refs['evidenceForFunction']) { this.refs['evidenceForFunction'].resetValue(); } if (this.refs['evidenceForFunctionInPaper']) { this.refs['evidenceForFunctionInPaper'].resetValue(); } if (this.refs['geneWithSameFunctionSameDisease.geneImplicatedWithDisease']) { this.refs['geneWithSameFunctionSameDisease.geneImplicatedWithDisease'].resetValue(); this.setState({geneImplicatedWithDisease: false}); } if (this.refs['organOfTissue']) { this.refs['organOfTissue'].setValue(''); } if (this.refs['organOfTissueFreeText']) { this.refs['organOfTissueFreeText'].setValue(''); } if (this.refs['normalExpression.expressedInTissue']) { this.refs['normalExpression.expressedInTissue'].resetValue(); this.setState({expressedInTissue: false}); } if (this.refs['alteredExpression.expressedInPatients']) { this.refs['alteredExpression.expressedInPatients'].resetValue(); this.setState({expressedInPatients: false}); } // If a subtype is not selected, do not let the user specify the experimental name if (tempExperimentalSubtype == 'none' || tempExperimentalSubtype === '') { this.setState({ experimentalTypeDescription: this.getExperimentalTypeDescription(this.state.experimentalType), experimentalNameVisible: false }); } else { this.setState({ experimentalTypeDescription: this.getExperimentalTypeDescription(this.state.experimentalType, tempExperimentalSubtype.charAt(0)), experimentalNameVisible: true }); } } else if (ref === 'geneWithSameFunctionSameDisease.geneImplicatedWithDisease') { this.setState({geneImplicatedWithDisease: this.refs[ref].toggleValue()}, () => { this.clrFormErrors('geneWithSameFunctionSameDisease.explanationOfOtherGenes'); }); } else if (ref === 'geneImplicatedInDisease') { this.setState({geneImplicatedInDisease: this.refs[ref].toggleValue()}, () => { this.clrFormErrors('relationshipOfOtherGenesToDisese'); }); } else if (ref === 'normalExpression.expressedInTissue') { this.setState({expressedInTissue: this.refs[ref].toggleValue()}, () => { this.clrFormErrors('normalExpression.evidence'); }); } else if (ref === 'alteredExpression.expressedInPatients') { this.setState({expressedInPatients: this.refs[ref].toggleValue()}, () => { this.clrFormErrors('alteredExpression.evidence'); }); } else if (ref === 'wildTypeRescuePhenotype') { this.setState({wildTypeRescuePhenotype: this.refs[ref].toggleValue()}, () => { this.clrFormErrors('explanation'); }); } else if (ref === 'patientVariantRescue') { this.setState({patientVariantRescue: this.refs[ref].toggleValue()}); } else if (ref === 'geneFunctionConsistentWithPhenotype.phenotypeHPO') { if (this.refs['geneFunctionConsistentWithPhenotype.phenotypeHPO'].getValue() === '') { this.setState({biochemicalFunctionHPO: false}); } else { this.setState({biochemicalFunctionHPO: true}); } } else if (ref === 'geneFunctionConsistentWithPhenotype.phenotypeFreeText') { if (this.refs['geneFunctionConsistentWithPhenotype.phenotypeFreeText'].getValue() === '') { this.setState({biochemicalFunctionFT: false}); } else { this.setState({biochemicalFunctionFT: true}); } } else if (ref === 'functionalAlterationType') { this.setState({functionalAlterationType: this.refs['functionalAlterationType'].getValue()}); } else if (ref === 'modelSystemsType') { this.setState({modelSystemsType: this.refs['modelSystemsType'].getValue()}); } else if (ref === 'identifiedFunction') { // Biochemical Function 'Identified Function' GO ID if (this.refs['identifiedFunction'].getValue() === '') { this.setState({bioChemicalFunctionIF_GoId: false}); } else { this.setState({bioChemicalFunctionIF_GoId: true}, () => {this.clrFormErrors('identifiedFunctionFreeText');}); } } else if (ref === 'identifiedFunctionFreeText') { // Biochemical Function 'Identified Function' free text if (this.refs['identifiedFunctionFreeText'].getValue() === '') { this.setState({bioChemicalFunctionIF_FreeText: false}); } else { this.setState({bioChemicalFunctionIF_FreeText: true}, () => {this.clrFormErrors('identifiedFunction');}); } } else if (ref === 'organOfTissue') { // Expression 'Organ of Tissue' Uberon ID if (this.refs['organOfTissue'].getValue() === '') { this.setState({expressionOT_UberonId: false}); } else { this.setState({expressionOT_UberonId: true}, () => {this.clrFormErrors('organOfTissueFreeText');}); } } else if (ref === 'organOfTissueFreeText') { // Expression 'Organ of Tissue' free text if (this.refs['organOfTissueFreeText'].getValue() === '') { this.setState({expressionOT_FreeText: false}); } else { this.setState({expressionOT_FreeText: true}, () => {this.clrFormErrors('organOfTissue');}); } } else if (ref === 'funcalt.patientCells') { // Functional Alteration 'Patient Cell Type' CL Ontology if (this.refs['funcalt.patientCells'].getValue() === '') { this.setState({functionalAlterationPCells_ClId: false}); } else { this.setState({functionalAlterationPCells_ClId: true}, () => {this.clrFormErrors('funcalt.patientCellsFreeText');}); } } else if (ref === 'funcalt.patientCellsFreeText') { // Functional Alteration 'Patient Cell Type' free text if (this.refs['funcalt.patientCellsFreeText'].getValue() === '') { this.setState({functionalAlterationPCells_FreeText: false}); } else { this.setState({functionalAlterationPCells_FreeText: true}, () => {this.clrFormErrors('funcalt.patientCells');}); } } else if (ref === 'funcalt.nonPatientCells') { // Functional Alteration 'Engineered Equivalent Cell Type' EFO ID if (this.refs['funcalt.nonPatientCells'].getValue() === '') { this.setState({functionalAlterationNPCells_EfoId: false}); } else { this.setState({functionalAlterationNPCells_EfoId: true}, () => {this.clrFormErrors('funcalt.nonPatientCellsFreeText');}); } } else if (ref === 'funcalt.nonPatientCellsFreeText') { // Functional Alteration 'Engineered Equivalent Cell Type' free text if (this.refs['funcalt.nonPatientCellsFreeText'].getValue() === '') { this.setState({functionalAlterationNPCells_FreeText: false}); } else { this.setState({functionalAlterationNPCells_FreeText: true}, () => {this.clrFormErrors('funcalt.nonPatientCells');}); } } else if (ref === 'normalFunctionOfGene') { // Functional Alteration 'Normal Function of Gene/Gene Product' GO ID if (this.refs['normalFunctionOfGene'].getValue() === '') { this.setState({functionalAlterationNFG_GoId: false}); } else { this.setState({functionalAlterationNFG_GoId: true}, () => {this.clrFormErrors('normalFunctionOfGeneFreeText');}); } } else if (ref === 'normalFunctionOfGeneFreeText') { // Functional Alteration 'Normal Function of Gene/Gene Product' free text if (this.refs['normalFunctionOfGeneFreeText'].getValue() === '') { this.setState({functionalAlterationNFG_FreeText: false}); } else { this.setState({functionalAlterationNFG_FreeText: true}, () => {this.clrFormErrors('normalFunctionOfGene');}); } } else if (ref === 'model.phenotypeHPOObserved') { if (this.refs['model.phenotypeHPOObserved'].getValue() === '') { this.setState({modelSystemsPOMSHPO: false}); } else { this.setState({modelSystemsPOMSHPO: true}); } } else if (ref === 'phenotypeFreetextObserved') { if (this.refs['phenotypeFreetextObserved'].getValue() === '') { this.setState({modelSystemsPOMSFT: false}); } else { this.setState({modelSystemsPOMSFT: true}); } } else if (ref === 'cellCulture') { // Model Systems 'Cell Culture' EFO ID if (this.refs['cellCulture'].getValue() === '') { this.setState({modelSystemsCC_EfoId: false}); } else { this.setState({modelSystemsCC_EfoId: true}, () => {this.clrFormErrors('cellCultureFreeText');}); } } else if (ref === 'cellCultureFreeText') { // Model Systems 'Cell Culture' free text if (this.refs['cellCultureFreeText'].getValue() === '') { this.setState({modelSystemsCC_FreeText: false}); } else { this.setState({modelSystemsCC_FreeText: true}, () => {this.clrFormErrors('cellCulture');}); } } else if (ref === 'model.phenotypeHPO') { if (this.refs['model.phenotypeHPO'].getValue() === '') { this.setState({modelSystemsPPHPO: false}); } else { this.setState({modelSystemsPPHPO: true}); } } else if (ref === 'model.phenotypeFreeText') { if (this.refs['model.phenotypeFreeText'].getValue() === '') { this.setState({modelSystemsPPFT: false}); } else { this.setState({modelSystemsPPFT: true}); } } else if (ref === 'rescue.patientCells') { // Rescue 'Patient Cell Type' CL Ontology if (this.refs['rescue.patientCells'].getValue() === '') { this.setState({rescuePCells_ClId: false}); } else { this.setState({rescuePCells_ClId: true}, () => {this.clrFormErrors('rescue.patientCellsFreeText');}); } } else if (ref === 'rescue.patientCellsFreeText') { // Rescue 'Patient Cell Type' free text if (this.refs['rescue.patientCellsFreeText'].getValue() === '') { this.setState({rescuePCells_FreeText: false}); } else { this.setState({rescuePCells_FreeText: true}, () => {this.clrFormErrors('rescue.patientCells');}); } } else if (ref === 'rescue.cellCulture') { // Rescue 'Cell-culture model' EFO ID if (this.refs['rescue.cellCulture'].getValue() === '') { this.setState({rescueCC_EfoId: false}); } else { this.setState({rescueCC_EfoId: true}, () => {this.clrFormErrors('rescue.cellCultureFreeText');}); } } else if (ref === 'rescue.cellCultureFreeText') { // Rescue 'Cell-culture model' free text if (this.refs['rescue.cellCultureFreeText'].getValue() === '') { this.setState({rescueCC_FreeText: false}); } else { this.setState({rescueCC_FreeText: true}, () => {this.clrFormErrors('rescue.cellCulture');}); } } else if (ref === 'rescue.phenotypeHPO') { if (this.refs['rescue.phenotypeHPO'].getValue() === '') { this.setState({rescuePRHPO: false}); } else { this.setState({rescuePRHPO: true}); } } else if (ref === 'rescue.phenotypeFreeText') { if (this.refs['rescue.phenotypeFreeText'].getValue() === '') { this.setState({rescuePRFT: false}); } else { this.setState({rescuePRFT: true}); } } else if (ref === 'rescueType') { this.setState({rescueType: this.refs['rescueType'].getValue()}, () => { if (this.state.rescueType === 'Human') { this.setState({showPatientVariantRescue: false}); } else { this.setState({showPatientVariantRescue: true}); } }); } }, /** * Load objects from query string into the state variables. Must have already parsed the query string * and set the queryValues property of this React class. */ loadData: function() { var gdmUuid = this.queryValues.gdmUuid; var experimentalUuid = this.queryValues.experimentalUuid; var annotationUuid = this.queryValues.annotationUuid; /** * Make an array of URIs to query the database. Don't include any that didn't include a query string. */ var uris = _.compact([ gdmUuid ? '/gdm/' + gdmUuid : '', experimentalUuid ? '/experimental/' + experimentalUuid : '', annotationUuid ? '/evidence/' + annotationUuid : '' ]); /** * With all given query string variables, get the corresponding objects from the DB. */ this.getRestDatas( uris ).then(datas => { var user = this.props.session && this.props.session.user_properties; var userAssessment; // See what we got back so we can build an object to copy in this React object's state to rerender the page. var stateObj = {}; datas.forEach(function(data) { switch(data['@type'][0]) { case 'gdm': stateObj.gdm = data; break; case 'experimental': stateObj.experimental = data; break; case 'annotation': stateObj.annotation = data; break; default: break; } }); /** * Update the Curator Mixin OMIM state with the current GDM's OMIM ID. */ if (stateObj.gdm) { this.getUniprotId(stateObj.gdm); if (stateObj.gdm.omimId) { this.setOmimIdState(stateObj.gdm.omimId); } } // Load data and set states as needed if (stateObj.experimental) { this.setState({ experimentalName: stateObj.experimental.label, experimentalType: stateObj.experimental.evidenceType, experimentalTypeDescription: this.getExperimentalTypeDescription(stateObj.experimental.evidenceType), experimentalNameVisible: true }); if (stateObj.experimental.evidenceType === 'Biochemical Function') { let bioFunc = stateObj.experimental.biochemicalFunction; if (!_.isEmpty(bioFunc.geneWithSameFunctionSameDisease)) { this.setState({ experimentalSubtype: "A. Gene(s) with same function implicated in same disease", experimentalTypeDescription: this.getExperimentalTypeDescription(stateObj.experimental.evidenceType, 'A') }); if (bioFunc.geneWithSameFunctionSameDisease.geneImplicatedWithDisease) { this.setState({geneImplicatedWithDisease: bioFunc.geneWithSameFunctionSameDisease.geneImplicatedWithDisease}); } } else if (!_.isEmpty(bioFunc.geneFunctionConsistentWithPhenotype)) { this.setState({ experimentalSubtype: "B. Gene function consistent with phenotype(s)", experimentalTypeDescription: this.getExperimentalTypeDescription(stateObj.experimental.evidenceType, 'B') }); if (bioFunc.geneFunctionConsistentWithPhenotype.phenotypeHPO && bioFunc.geneFunctionConsistentWithPhenotype.phenotypeHPO.length > 0) { this.setState({'biochemicalFunctionHPO': true}); } if (bioFunc.geneFunctionConsistentWithPhenotype.phenotypeFreeText && bioFunc.geneFunctionConsistentWithPhenotype.phenotypeFreeText !== '') { this.setState({'biochemicalFunctionFT': true}); } } // Set boolean state on 'required' prop for Biochemical Function 'Identified Function' GO ID bioFunc.identifiedFunction && bioFunc.identifiedFunction.length ? this.setState({bioChemicalFunctionIF_GoId: true}) : this.setState({bioChemicalFunctionIF_GoId: false}); // Set boolean state on 'required' prop for Biochemical Function 'Identified Function' free text bioFunc.identifiedFunctionFreeText && bioFunc.identifiedFunctionFreeText.length ? this.setState({bioChemicalFunctionIF_FreeText: true}) : this.setState({bioChemicalFunctionIF_FreeText: false}); } else if (stateObj.experimental.evidenceType === 'Protein Interactions') { if (stateObj.experimental.proteinInteractions.geneImplicatedInDisease) { this.setState({geneImplicatedInDisease: stateObj.experimental.proteinInteractions.geneImplicatedInDisease}); } } else if (stateObj.experimental.evidenceType === 'Expression') { let expression = stateObj.experimental.expression; if (!_.isEmpty(expression.normalExpression)) { this.setState({ experimentalSubtype: "A. Gene normally expressed in tissue relevant to the disease", experimentalTypeDescription: this.getExperimentalTypeDescription(stateObj.experimental.evidenceType, 'A') }); if (expression.normalExpression.expressedInTissue) { this.setState({expressedInTissue: expression.normalExpression.expressedInTissue}); } } else if (!_.isEmpty(expression.alteredExpression)) { this.setState({ experimentalSubtype: "B. Altered expression in Patients", experimentalTypeDescription: this.getExperimentalTypeDescription(stateObj.experimental.evidenceType, 'B') }); if (expression.alteredExpression.expressedInPatients) { this.setState({expressedInPatients: expression.alteredExpression.expressedInPatients}); } } // Set boolean state on 'required' prop for Expression 'Organ of Tissue' Uberon ID expression.organOfTissue && expression.organOfTissue.length ? this.setState({expressionOT_UberonId: true}) : this.setState({expressionOT_UberonId: false}); // Set boolean state on 'required' prop for Expression 'Organ of Tissue' free text expression.organOfTissueFreeText && expression.organOfTissueFreeText.length ? this.setState({expressionOT_FreeText: true}) : this.setState({expressionOT_FreeText: false}); } else if (stateObj.experimental.evidenceType === 'Functional Alteration') { let funcAlt = stateObj.experimental.functionalAlteration; this.setState({functionalAlterationType: funcAlt.functionalAlterationType}); // Set boolean state on 'required' prop for Functional Alteration 'Patient Cell Type' CL Ontology funcAlt.patientCells && funcAlt.patientCells.length ? this.setState({functionalAlterationPCells_ClId: true}): this.setState({functionalAlterationPCells_ClId: false}); // Set boolean state on 'required' prop for Functional Alteration 'Patient Cell Type' free text funcAlt.patientCellsFreeText && funcAlt.patientCellsFreeText.length ? this.setState({functionalAlterationPCells_FreeText: true}) : this.setState({functionalAlterationPCells_FreeText: false}); // Set boolean state on 'required' prop for Functional Alteration 'Engineered Equivalent Cell Type' EFO ID funcAlt.nonPatientCells && funcAlt.nonPatientCells.length ? this.setState({functionalAlterationNPCells_EfoId: true}) : this.setState({functionalAlterationNPCells_EfoId: false}); // Set boolean state on 'required' prop for Functional Alteration 'Engineered Equivalent Cell Type' free text funcAlt.nonPatientCellsFreeText && funcAlt.nonPatientCellsFreeText.length ? this.setState({functionalAlterationNPCells_FreeText: true}) : this.setState({functionalAlterationNPCells_FreeText: false}); // Set boolean state on 'required' prop for Functional Alteration 'Normal Function of Gene/Gene Function' GO ID funcAlt.normalFunctionOfGene && funcAlt.normalFunctionOfGene.length ? this.setState({functionalAlterationNFG_GoId: true}) : this.setState({functionalAlterationNFG_GoId: false}); // Set boolean state on 'required' prop for Functional Alteration 'Normal Function of Gene/Gene Function' free text funcAlt.normalFunctionOfGeneFreeText && funcAlt.normalFunctionOfGeneFreeText.length ? this.setState({functionalAlterationNFG_FreeText: true}) : this.setState({functionalAlterationNFG_FreeText: false}); } else if (stateObj.experimental.evidenceType === 'Model Systems') { let modelSystems = stateObj.experimental.modelSystems; this.setState({modelSystemsType: modelSystems.modelSystemsType}); modelSystems.phenotypeHPOObserved && modelSystems.phenotypeHPOObserved.length ? this.setState({modelSystemsPOMSHPO: true}) : this.setState({modelSystemsPOMSHPO: false}); modelSystems.phenotypeFreetextObserved && modelSystems.phenotypeFreetextObserved.length ? this.setState({modelSystemsPOMSFT: true}) : this.setState({modelSystemsPOMSFT: false}); modelSystems.phenotypeHPO && modelSystems.phenotypeHPO.length ? this.setState({modelSystemsPPHPO: true}) : this.setState({modelSystemsPPHPO: false}); modelSystems.phenotypeFreeText && modelSystems.phenotypeFreeText.length ? this.setState({modelSystemsPPFT: true}) : this.setState({modelSystemsPPFT: false}); // Set boolean state on 'required' prop for Model Systems 'Cell Culture' EFO ID modelSystems.cellCulture && modelSystems.cellCulture.length ? this.setState({modelSystemsCC_EfoId: true}) : this.setState({modelSystemsCC_EfoId: false}); // Set boolean state on 'required' prop for Model Systems 'Cell Culture' free text modelSystems.cellCultureFreeText && modelSystems.cellCultureFreeText.length ? this.setState({modelSystemsCC_FreeText: true}) : this.setState({modelSystemsCC_FreeText: false}); } else if (stateObj.experimental.evidenceType === 'Rescue') { let rescue = stateObj.experimental.rescue; this.setState({rescueType: rescue.rescueType}, () => { if (this.state.rescueType === 'Human') { this.setState({showPatientVariantRescue: false}); } else { this.setState({showPatientVariantRescue: true}); } }); if (rescue.wildTypeRescuePhenotype) { this.setState({wildTypeRescuePhenotype: rescue.wildTypeRescuePhenotype}); } if (rescue.hasOwnProperty('patientVariantRescue')) { this.setState({patientVariantRescue: rescue.patientVariantRescue}); } rescue.phenotypeHPO && rescue.phenotypeHPO.length ? this.setState({rescuePRHPO: true}) : this.setState({rescuePRHPO: false}); rescue.phenotypeFreeText && rescue.phenotypeFreeText.length ? this.setState({rescuePRFT: true}) : this.setState({rescuePRFT: false}); // Set boolean state on 'required' prop for Rescue 'Patient Cell Type' CL Ontology rescue.patientCells && rescue.patientCells.length ? this.setState({rescuePCells_ClId: true}) : this.setState({rescuePCells_ClId: false}); // Set boolean state on 'required' prop for Rescue 'Patient Cell Type' free text rescue.patientCellsFreeText && rescue.patientCellsFreeText.length ? this.setState({rescuePCells_FreeText: true}) : this.setState({rescuePCells_FreeText: false}); // Set boolean state on 'required' prop for Rescue 'Engineered Equivalent Cell Type' EFO ID rescue.cellCulture && rescue.cellCulture.length ? this.setState({rescueCC_EfoId: true}) : this.setState({rescueCC_EfoId: false}); // Set boolean state on 'required' prop for Rescue 'Engineered Equivalent Cell Type' free text rescue.cellCultureFreeText && rescue.cellCultureFreeText.length ? this.setState({rescueCC_FreeText: true}) : this.setState({rescueCC_FreeText: false}); } // See if we need to disable the Add Variant button based on the number of variants configured if (stateObj.experimental.variants) { var variants = stateObj.experimental.variants; if (variants && variants.length > 0) { // We have variants stateObj.variantCount = variants.length; stateObj.addVariantDisabled = false; stateObj.variantInfo = {}; for (var i = 0; i < variants.length; i++) { if (variants[i].clinvarVariantId || variants[i].carId) { stateObj.variantInfo[i] = { 'clinvarVariantId': variants[i].clinvarVariantId ? variants[i].clinvarVariantId : null, 'clinvarVariantTitle': variants[i].clinvarVariantTitle ? variants[i].clinvarVariantTitle : null, 'carId': variants[i].carId ? variants[i].carId : null, 'canonicalTranscriptTitle': variants[i].canonicalTranscriptTitle ? variants[i].canonicalTranscriptTitle : null, 'maneTranscriptTitle': variants[i].maneTranscriptTitle ? variants[i].maneTranscriptTitle : null, 'hgvsNames': variants[i].hgvsNames ? variants[i].hgvsNames : null, 'uuid': variants[i].uuid }; } } } } // Find the current user's assessment from the assessment list if (stateObj.experimental.assessments && stateObj.experimental.assessments.length) { // Find the assessment belonging to the logged-in curator, if any. userAssessment = Assessments.userAssessment(stateObj.experimental.assessments, user && user.uuid); // See if any assessments are non-default this.cv.experimentalDataAssessed = _(stateObj.experimental.assessments).find(function(assessment) { return assessment.value !== Assessments.DEFAULT_VALUE; }); // See if others have assessed if (user && user.uuid) { this.cv.othersAssessed = Assessments.othersAssessed(stateObj.experimental.assessments, user.uuid); } } } // Make a new tracking object for the current assessment. Either or both of the original assessment or user can be blank // and assigned later. Then set the component state's assessment value to the assessment's value -- default if there was no // assessment. var tempEvidenceType = ''; if (stateObj.experimental) { tempEvidenceType = stateObj.experimental.evidenceType; } var assessmentTracker = this.cv.assessmentTracker = new AssessmentTracker(userAssessment, user, tempEvidenceType); this.setAssessmentValue(assessmentTracker); // Set all the state variables we've collected this.setState(stateObj); // No one’s waiting but the user; just resolve with an empty promise. return Promise.resolve(); }).catch(function(e) { console.log('OBJECT LOAD ERROR: %s', e); }); }, // After the Experimental Data Curation page component mounts, grab the GDM and annotation UUIDs from the query // string and retrieve the corresponding annotation from the DB, if they exist. // Note, we have to do this after the component mounts because AJAX DB queries can't be // done from unmounted components. componentDidMount: function() { this.loadData(); }, componentWillUnmount: function() { this.cv.othersAssessed = false; }, // Clear error state when either experimentalType or experimentalSubtype selection is changed componentDidUpdate: function(prevProps, prevState) { if (typeof prevState.experimentalType !== undefined && prevState.experimentalType !== this.state.experimentalType) { this.setState({formErrors: []}); } else if (typeof prevState.experimentalSubtype !== undefined && prevState.experimentalSubtype !== this.state.experimentalSubtype) { this.setState({formErrors: []}); } }, // validate values and return error messages as needed validateFormTerms: function(formError, type, terms, formField, limit) { limit = typeof limit !== 'undefined' ? limit : 0; var errorMsgs = { 'clIDs': { 'invalid1': "Use CL Ontology ID (e.g. CL_0000057)", 'invalid': "Use CL Ontologys (e.g. CL_0000057) separated by commas", 'limit1': "Enter only one CL Ontology ID", 'limit': "Enter only " + limit + " CL Ontology IDs" }, 'efoIDs': { 'invalid1': "Use EFO ID (e.g. EFO_0001187)", 'invalid': "Use EFO IDs (e.g. EFO_0001187) separated by commas", 'limit1': "Enter only one EFO ID", 'limit': "Enter only " + limit + " EFO IDs" }, 'efoClIDs': { 'invalid1': "Use EFO ID (e.g. EFO_0001187) or CL Ontology ID (e.g. CL_0000057)", 'invalid': "Use EFO IDs (e.g. EFO_0001187) or CL Ontology IDs (e.g. CL_0000057) separated by commas", 'limit1': "Enter only one EFO or CL Ontology ID", 'limit': "Enter only " + limit + " EFO or CL Ontology IDs" }, 'geneSymbols': { 'invalid1': "Use gene symbol (e.g. SMAD3)", 'invalid': "Use gene symbols (e.g. SMAD3) separated by commas", 'limit1': "Enter only one gene symbol", 'limit': "Enter only " + limit + " gene symbols" }, 'goSlimIds': { 'invalid1': "Use GO ID (e.g. GO:0006259)", 'invalid': "Use GO IDs (e.g. GO:0006259) separated by commas", 'limit1': "Enter only one GO ID", 'limit': "Enter only " + limit + " GO IDs" }, 'hpoIDs': { 'invalid1': "Use HPO ID (e.g. HP:0000001)", 'invalid': "Use HPO IDs (e.g. HP:0000001) separated by commas", 'limit1': "Enter only one HPO ID", 'limit': "Enter only " + limit + " HPO IDs" }, 'hpoMpIDs': { 'invalid1': "Use HPO ID (e.g. HP:0000001) or MP ID (e.g. MP:0000001)", 'invalid': "Use HPO IDs (e.g. HP:0000001) or MP IDs (e.g. MP:0000001) separated by commas", 'limit1': "Enter only one HPO ID or MP ID", 'limit': "Enter only " + limit + " HPO or MP IDs" }, 'uberonIDs': { 'invalid1': "Use Uberon ID (e.g. UBERON:0015228)", 'invalid': "Use Uberon IDs (e.g. UBERON:0015228) separated by commas", 'limit1': "Enter only one Uberon ID", 'limit': "Enter only " + limit + " Uberon IDs" } }; if (terms && terms.length && _(terms).any(function(id) { return id === null; })) { // term is bad formError = true; if (limit == 1) { this.setFormErrors(formField, errorMsgs[type]['invalid1']); } else { this.setFormErrors(formField, errorMsgs[type]['invalid']); } } if (limit !== 0 && terms.length > limit) { // number of terms more than specified limit formError = true; if (limit == 1) { this.setFormErrors(formField, errorMsgs[type]['limit1']); } else { this.setFormErrors(formField, errorMsgs[type]['limit']); } } return formError; }, submitForm: function(e) { e.preventDefault(); e.stopPropagation(); // Don't run through HTML submit handler // Save all form values from the DOM. this.saveAllFormValues(); // Make sure there is an explanation for the score selected differently from the default score let newUserScoreObj = Object.keys(this.state.userScoreObj).length ? this.state.userScoreObj : {}; if (Object.keys(newUserScoreObj).length) { if (newUserScoreObj.hasOwnProperty('score') && newUserScoreObj.score !== false && !newUserScoreObj.scoreExplanation) { this.setState({formError: true}); return false; } } // Start with default validation; indicate errors on form if not, then bail if (this.validateDefault()) { var groupGenes; var goSlimIDs, geneSymbols, hpoIDs, hpoMpIDs, uberonIDs, clIDs, efoClIDs; var formError = false; if (this.state.experimentalType == 'Biochemical Function') { // Validate GO ID(s) if value is not empty. Don't validate if free text is provided. if (this.getFormValue('identifiedFunction')) { goSlimIDs = curator.capture.goslims(this.getFormValue('identifiedFunction')); formError = this.validateFormTerms(formError, 'goSlimIds', goSlimIDs, 'identifiedFunction', 1); } // check geneSymbols geneSymbols = curator.capture.genes(this.getFormValue('geneWithSameFunctionSameDisease.genes')); formError = this.validateFormTerms(formError, 'geneSymbols', geneSymbols, 'geneWithSameFunctionSameDisease.genes'); // check hpoIDs hpoIDs = curator.capture.hpoids(this.getFormValue('geneFunctionConsistentWithPhenotype.phenotypeHPO')); formError = this.validateFormTerms(formError, 'hpoIDs', hpoIDs, 'geneFunctionConsistentWithPhenotype.phenotypeHPO'); } else if (this.state.experimentalType == 'Protein Interactions') { // check geneSymbols geneSymbols = curator.capture.genes(this.getFormValue('interactingGenes')); formError = this.validateFormTerms(formError, 'geneSymbols', geneSymbols, 'interactingGenes'); } else if (this.state.experimentalType == 'Expression') { // Validate Uberon ID(s) if value is not empty. Don't validate if free text is provided. if (this.getFormValue('organOfTissue')) { uberonIDs = curator.capture.uberonids(this.getFormValue('organOfTissue')); formError = this.validateFormTerms(formError, 'uberonIDs', uberonIDs, 'organOfTissue'); } } else if (this.state.experimentalType === 'Functional Alteration') { // Check form for Functional Alterations panel // Validate clIDs/efoIDs depending on form selection. Don't validate if free text is provided. if (this.getFormValue('functionalAlterationType') === 'Patient cells' && this.getFormValue('funcalt.patientCells')) { clIDs = curator.capture.clids(this.getFormValue('funcalt.patientCells')); formError = this.validateFormTerms(formError, 'clIDs', clIDs, 'funcalt.patientCells', 1); } else if (this.getFormValue('functionalAlterationType') === 'Non-patient cells' && this.getFormValue('funcalt.nonPatientCells')) { // This input field accepts both EFO and CLO IDs efoClIDs = curator.capture.efoclids(this.getFormValue('funcalt.nonPatientCells')); formError = this.validateFormTerms(formError, 'efoClIDs', efoClIDs, 'funcalt.nonPatientCells', 1); } // Validate GO ID(s) if value is not empty. Don't validate if free text is provided. if (this.getFormValue('normalFunctionOfGene')) { goSlimIDs = curator.capture.goslims(this.getFormValue('normalFunctionOfGene')); formError = this.validateFormTerms(formError, 'goSlimIds', goSlimIDs, 'normalFunctionOfGene', 1); } } else if (this.state.experimentalType == 'Model Systems') { // Check form for Model Systems panel // Validate efoIDs depending on form selection. Don't validate if free text is provided. if (this.getFormValue('modelSystemsType') === 'Cell culture model' && this.getFormValue('cellCulture')) { // This input field accepts both EFO and CLO IDs efoClIDs = curator.capture.efoclids(this.getFormValue('cellCulture')); formError = this.validateFormTerms(formError, 'efoClIDs', efoClIDs, 'cellCulture', 1); } // check hpoIDs if (this.getFormValue('model.phenotypeHPO') !== '') { hpoIDs = curator.capture.hpoids(this.getFormValue('model.phenotypeHPO')); formError = this.validateFormTerms(formError, 'hpoIDs', hpoIDs, 'model.phenotypeHPO'); } // check hpoMpIDs part 2 if (this.getFormValue('model.phenotypeHPOObserved') !== '') { hpoMpIDs = curator.capture.hpoMpids(this.getFormValue('model.phenotypeHPOObserved')); formError = this.validateFormTerms(formError, 'hpoMpIDs', hpoMpIDs, 'model.phenotypeHPOObserved'); } } else if (this.state.experimentalType == 'Rescue') { // Validate clIDs/efoIDs depending on form selection. Don't validate if free text is provided. if (this.getFormValue('rescueType') === 'Patient cells' && this.getFormValue('rescue.patientCells')) { clIDs = curator.capture.clids(this.getFormValue('rescue.patientCells')); formError = this.validateFormTerms(formError, 'clIDs', clIDs, 'rescue.patientCells', 1); } else if (this.getFormValue('rescueType') === 'Cell culture model' && this.getFormValue('rescue.cellCulture')) { // This input field accepts both EFO and CLO IDs efoClIDs = curator.capture.efoclids(this.getFormValue('rescue.cellCulture')); formError = this.validateFormTerms(formError, 'efoClIDs', efoClIDs, 'rescue.cellCulture', 1); } // check hpoIDs if (this.getFormValue('rescue.phenotypeHPO') !== '') { hpoIDs = curator.capture.hpoids(this.getFormValue('rescue.phenotypeHPO')); formError = this.validateFormTerms(formError, 'hpoIDs', hpoIDs, 'rescue.phenotypeHPO'); } } if (!formError) { // form passed error checking var newExperimental = this.state.experimental ? curator.flatten(this.state.experimental) : {}; var experimentalDataVariants = []; var savedExperimental; newExperimental.label = this.getFormValue('experimentalName'); newExperimental.evidenceType = this.getFormValue('experimentalType'); // prepare experimental object for post/putting to db // copy assessments over if (this.state.experimental) { if (this.state.experimental.assessments && this.state.experimental.assessments.length) { newExperimental.assessments = []; for (var i = 0; i < this.state.experimental.assessments.length; i++) { newExperimental.assessments.push(this.state.experimental.assessments[i]['@id']); } } } if (newExperimental.evidenceType == 'Biochemical Function') { // newExperimental object for type Biochemical Function newExperimental.biochemicalFunction = {}; var BFidentifiedFunction = this.getFormValue('identifiedFunction'); if (BFidentifiedFunction) { newExperimental.biochemicalFunction.identifiedFunction = BFidentifiedFunction; } var BFidentifiedFunctionFreeText = this.getFormValue('identifiedFunctionFreeText'); if (BFidentifiedFunctionFreeText) { newExperimental.biochemicalFunction.identifiedFunctionFreeText = BFidentifiedFunctionFreeText; } var BFevidenceForFunction = this.getFormValue('evidenceForFunction'); if (BFevidenceForFunction) { newExperimental.biochemicalFunction.evidenceForFunction = BFevidenceForFunction; } var BFevidenceForFunctionInPaper = this.getFormValue('evidenceForFunctionInPaper'); if (BFevidenceForFunctionInPaper) { newExperimental.biochemicalFunction.evidenceForFunctionInPaper = BFevidenceForFunctionInPaper; } if (this.state.experimentalSubtype.charAt(0) == 'A') { newExperimental.biochemicalFunction['geneWithSameFunctionSameDisease'] = {}; var BFgenes = geneSymbols; if (BFgenes) { newExperimental.biochemicalFunction.geneWithSameFunctionSameDisease.genes = BFgenes; } var BFevidenceForOtherGenesWithSameFunction = this.getFormValue('geneWithSameFunctionSameDisease.evidenceForOtherGenesWithSameFunction'); if (BFevidenceForOtherGenesWithSameFunction) { newExperimental.biochemicalFunction.geneWithSameFunctionSameDisease.evidenceForOtherGenesWithSameFunction = BFevidenceForOtherGenesWithSameFunction; } var BFgeneImplicatedWithDisease = this.getFormValue('geneWithSameFunctionSameDisease.geneImplicatedWithDisease'); newExperimental.biochemicalFunction.geneWithSameFunctionSameDisease.geneImplicatedWithDisease = BFgeneImplicatedWithDisease; var BFexplanationOfOtherGenes = this.getFormValue('geneWithSameFunctionSameDisease.explanationOfOtherGenes'); if (BFexplanationOfOtherGenes) { newExperimental.biochemicalFunction.geneWithSameFunctionSameDisease.explanationOfOtherGenes = BFexplanationOfOtherGenes; } var BFGWSFSDevidenceInPaper = this.getFormValue('geneWithSameFunctionSameDisease.evidenceInPaper'); if (BFGWSFSDevidenceInPaper) { newExperimental.biochemicalFunction.geneWithSameFunctionSameDisease.evidenceInPaper = BFGWSFSDevidenceInPaper; } } else if (this.state.experimentalSubtype.charAt(0) == 'B') { newExperimental.biochemicalFunction['geneFunctionConsistentWithPhenotype'] = {}; var BFphenotypeHPO = hpoIDs; if (BFphenotypeHPO) { newExperimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeHPO = BFphenotypeHPO; } var BFphenotypeFreeText = this.getFormValue('geneFunctionConsistentWithPhenotype.phenotypeFreeText'); if (BFphenotypeFreeText) { newExperimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeFreeText = BFphenotypeFreeText; } var BFexplanation = this.getFormValue('geneFunctionConsistentWithPhenotype.explanation'); if (BFexplanation) { newExperimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.explanation = BFexplanation; } var BFGFCWPevidenceInPaper = this.getFormValue('geneFunctionConsistentWithPhenotype.evidenceInPaper'); if (BFGFCWPevidenceInPaper) { newExperimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.evidenceInPaper = BFGFCWPevidenceInPaper; } } } else if (newExperimental.evidenceType == 'Protein Interactions') { // newExperimental object for type Protein Interactions newExperimental.proteinInteractions = {}; var PIinteractingGenes = geneSymbols; if (PIinteractingGenes) { newExperimental.proteinInteractions.interactingGenes = PIinteractingGenes; } var PIinteractionType = this.getFormValue('interactionType'); if (PIinteractionType) { newExperimental.proteinInteractions.interactionType = PIinteractionType; } var PIexperimentalInteractionDetection = this.getFormValue('experimentalInteractionDetection'); if (PIexperimentalInteractionDetection) { newExperimental.proteinInteractions.experimentalInteractionDetection = PIexperimentalInteractionDetection; } var PIgeneImplicatedInDisease = this.getFormValue('geneImplicatedInDisease'); newExperimental.proteinInteractions.geneImplicatedInDisease = PIgeneImplicatedInDisease; var PIrelationshipOfOtherGenesToDisese = this.getFormValue('relationshipOfOtherGenesToDisese'); if (PIrelationshipOfOtherGenesToDisese) { newExperimental.proteinInteractions.relationshipOfOtherGenesToDisese = PIrelationshipOfOtherGenesToDisese; } var PIevidenceInPaper = this.getFormValue('evidenceInPaper'); if (PIevidenceInPaper) { newExperimental.proteinInteractions.evidenceInPaper = PIevidenceInPaper; } } else if (newExperimental.evidenceType == 'Expression') { // newExperimental object for type Expression newExperimental.expression = {}; if (uberonIDs) { newExperimental.expression.organOfTissue = uberonIDs; } var EorganOfTissueFreeText = this.getFormValue('organOfTissueFreeText'); if (EorganOfTissueFreeText) { newExperimental.expression.organOfTissueFreeText = EorganOfTissueFreeText; } if (this.state.experimentalSubtype.charAt(0) == 'A') { newExperimental.expression['normalExpression'] = {}; var EexpressedInTissue = this.getFormValue('normalExpression.expressedInTissue'); newExperimental.expression.normalExpression.expressedInTissue = EexpressedInTissue; var ENEevidence = this.getFormValue('normalExpression.evidence'); if (ENEevidence) { newExperimental.expression.normalExpression.evidence = ENEevidence; } var ENEevidenceInPaper = this.getFormValue('normalExpression.evidenceInPaper'); if (ENEevidenceInPaper) { newExperimental.expression.normalExpression.evidenceInPaper = ENEevidenceInPaper; } } else if (this.state.experimentalSubtype.charAt(0) == 'B') { newExperimental.expression['alteredExpression'] = {}; var EexpressedInPatients = this.getFormValue('alteredExpression.expressedInPatients'); newExperimental.expression.alteredExpression.expressedInPatients = EexpressedInPatients; var EAEevidence = this.getFormValue('alteredExpression.evidence'); if (EAEevidence) { newExperimental.expression.alteredExpression.evidence = EAEevidence; } var EAEevidenceInPaper = this.getFormValue('alteredExpression.evidenceInPaper'); if (EAEevidenceInPaper) { newExperimental.expression.alteredExpression.evidenceInPaper = EAEevidenceInPaper; } } } else if (newExperimental.evidenceType === 'Functional Alteration') { // newExperimental object for type Functional Alteration newExperimental.functionalAlteration = {}; const FA_functionalAlterationType = this.getFormValue('functionalAlterationType'); if (FA_functionalAlterationType) { newExperimental.functionalAlteration.functionalAlterationType = FA_functionalAlterationType; } const FA_patientCells = this.getFormValue('funcalt.patientCells'); if (FA_patientCells) { newExperimental.functionalAlteration.patientCells = FA_patientCells.indexOf('_') > -1 ? FA_patientCells.replace('_', ':') : FA_patientCells; } const FA_patientCellsFreeText = this.getFormValue('funcalt.patientCellsFreeText'); if (FA_patientCellsFreeText) { newExperimental.functionalAlteration.patientCellsFreeText = FA_patientCellsFreeText; } const FA_nonPatientCells = this.getFormValue('funcalt.nonPatientCells'); if (FA_nonPatientCells) { newExperimental.functionalAlteration.nonPatientCells = FA_nonPatientCells.indexOf('_') > -1 ? FA_nonPatientCells.replace('_', ':') : FA_nonPatientCells; } const FA_nonPatientCellsFreeText = this.getFormValue('funcalt.nonPatientCellsFreeText'); if (FA_nonPatientCellsFreeText) { newExperimental.functionalAlteration.nonPatientCellsFreeText = FA_nonPatientCellsFreeText; } const FA_descriptionOfGeneAlteration = this.getFormValue('descriptionOfGeneAlteration'); if (FA_descriptionOfGeneAlteration) { newExperimental.functionalAlteration.descriptionOfGeneAlteration = FA_descriptionOfGeneAlteration; } const FA_normalFunctionOfGene = this.getFormValue('normalFunctionOfGene'); if (FA_normalFunctionOfGene) { newExperimental.functionalAlteration.normalFunctionOfGene = FA_normalFunctionOfGene; } const FA_normalFunctionOfGeneFreeText = this.getFormValue('normalFunctionOfGeneFreeText'); if (FA_normalFunctionOfGeneFreeText) { newExperimental.functionalAlteration.normalFunctionOfGeneFreeText = FA_normalFunctionOfGeneFreeText; } const FA_evidenceForNormalFunction = this.getFormValue('evidenceForNormalFunction'); if (FA_evidenceForNormalFunction) { newExperimental.functionalAlteration.evidenceForNormalFunction = FA_evidenceForNormalFunction; } const FA_evidenceInPaper = this.getFormValue('evidenceInPaper'); if (FA_evidenceInPaper) { newExperimental.functionalAlteration.evidenceInPaper = FA_evidenceInPaper; } } else if (newExperimental.evidenceType == 'Model Systems') { // newExperimental object for type Model Systems newExperimental.modelSystems = {}; const MS_modelSystemsType = this.getFormValue('modelSystemsType'); if (MS_modelSystemsType) { newExperimental.modelSystems.modelSystemsType = MS_modelSystemsType; } if (MS_modelSystemsType == 'Non-human model organism') { const MS_nonHumanModel = this.getFormValue('nonHumanModel'); if (MS_nonHumanModel) { newExperimental.modelSystems.nonHumanModel = MS_nonHumanModel; } } else if (MS_modelSystemsType == 'Cell culture model') { const MS_cellCulture = this.getFormValue('cellCulture'); if (MS_cellCulture) { newExperimental.modelSystems.cellCulture = MS_cellCulture.indexOf('_') > -1 ? MS_cellCulture.replace('_', ':') : MS_cellCulture; } const MS_cellCultureFreeText = this.getFormValue('cellCultureFreeText'); if (MS_cellCultureFreeText) { newExperimental.modelSystems.cellCultureFreeText = MS_cellCultureFreeText; } } const MS_descriptionOfGeneAlteration = this.getFormValue('descriptionOfGeneAlteration'); if (MS_descriptionOfGeneAlteration) { newExperimental.modelSystems.descriptionOfGeneAlteration = MS_descriptionOfGeneAlteration; } const MS_phenotypeHPO = this.getFormValue('model.phenotypeHPO'); if (MS_phenotypeHPO) { newExperimental.modelSystems.phenotypeHPO = MS_phenotypeHPO; } const MS_phenotypeFreeText = this.getFormValue('model.phenotypeFreeText'); if (MS_phenotypeFreeText) { newExperimental.modelSystems.phenotypeFreeText = MS_phenotypeFreeText; } const MS_phenotypeHPOObserved = this.getFormValue('model.phenotypeHPOObserved'); if (MS_phenotypeHPOObserved) { newExperimental.modelSystems.phenotypeHPOObserved = MS_phenotypeHPOObserved; } const MS_phenotypeFreetextObserved = this.getFormValue('phenotypeFreetextObserved'); if (MS_phenotypeFreetextObserved) { newExperimental.modelSystems.phenotypeFreetextObserved = MS_phenotypeFreetextObserved; } const MS_explanation = this.getFormValue('explanation'); if (MS_explanation) { newExperimental.modelSystems.explanation = MS_explanation; } const MS_evidenceInPaper = this.getFormValue('evidenceInPaper'); if (MS_evidenceInPaper) { newExperimental.modelSystems.evidenceInPaper = MS_evidenceInPaper; } } else if (newExperimental.evidenceType == 'Rescue') { // newExperimental object for type Rescue newExperimental.rescue = {}; const RES_rescueType = this.getFormValue('rescueType'); if (RES_rescueType) { newExperimental.rescue.rescueType = RES_rescueType; } const RES_patientCells = this.getFormValue('rescue.patientCells'); if (RES_patientCells) { newExperimental.rescue.patientCells = RES_patientCells.indexOf('_') > -1 ? RES_patientCells.replace('_', ':') : RES_patientCells; } const RES_patientCellsFreeText = this.getFormValue('rescue.patientCellsFreeText'); if (RES_patientCellsFreeText) { newExperimental.rescue.patientCellsFreeText = RES_patientCellsFreeText; } const RES_cellCulture = this.getFormValue('rescue.cellCulture'); if (RES_cellCulture) { newExperimental.rescue.cellCulture = RES_cellCulture.indexOf('_') > -1 ? RES_cellCulture.replace('_', ':') : RES_cellCulture; } const RES_cellCultureFreeText = this.getFormValue('rescue.cellCultureFreeText'); if (RES_cellCultureFreeText) { newExperimental.rescue.cellCultureFreeText = RES_cellCultureFreeText; } const RES_nonHumanModel = this.getFormValue('rescue.nonHumanModel'); if (RES_nonHumanModel) { newExperimental.rescue.nonHumanModel = RES_nonHumanModel; } const RES_humanModel = this.getFormValue('rescue.humanModel'); if (RES_humanModel) { newExperimental.rescue.humanModel = RES_humanModel; } const RES_descriptionOfGeneAlteration = this.getFormValue('descriptionOfGeneAlteration'); if (RES_descriptionOfGeneAlteration) { newExperimental.rescue.descriptionOfGeneAlteration = RES_descriptionOfGeneAlteration; } const RES_phenotypeHPO = this.getFormValue('rescue.phenotypeHPO'); if (RES_phenotypeHPO) { newExperimental.rescue.phenotypeHPO = RES_phenotypeHPO; } const RES_phenotypeFreeText = this.getFormValue('rescue.phenotypeFreeText'); if (RES_phenotypeFreeText) { newExperimental.rescue.phenotypeFreeText = RES_phenotypeFreeText; } const RES_rescueMethod = this.getFormValue('rescueMethod'); if (RES_rescueMethod) { newExperimental.rescue.rescueMethod = RES_rescueMethod; } const RES_wildTypeRescuePhenotype = this.getFormValue('wildTypeRescuePhenotype'); newExperimental.rescue.wildTypeRescuePhenotype = RES_wildTypeRescuePhenotype; if (this.refs['patientVariantRescue']) { const RES_patientVariantRescue = this.getFormValue('patientVariantRescue'); newExperimental.rescue.patientVariantRescue = RES_patientVariantRescue; } const RES_explanation = this.getFormValue('explanation'); if (RES_explanation) { newExperimental.rescue.explanation = RES_explanation; } const RES_evidenceInPaper = this.getFormValue('evidenceInPaper'); if (RES_evidenceInPaper) { newExperimental.rescue.evidenceInPaper = RES_evidenceInPaper; } } // Add affiliation if the user is associated with an affiliation // and if the data object has no affiliation if (this.props.affiliation && Object.keys(this.props.affiliation).length) { if (!newExperimental.affiliation) { newExperimental.affiliation = this.props.affiliation.affiliation_id; } } // Get variant uuid's if they were added via the modals for (var j = 0; j < this.state.variantCount; j++) { // Grab the values from the variant form panel var variantId = this.getFormValue('variantUuid' + j); // Build the search string depending on what the user entered if (variantId) { // Make a search string for these terms experimentalDataVariants.push('/variants/' + variantId); } } var searchStr = ''; this.setState({submitBusy: true}); // Begin with empty promise new Promise(function(resolve, reject) { resolve(1); }).then(diseases => { if (geneSymbols && geneSymbols.length) { // At least one gene symbol entered; search the DB for them. searchStr = '/search/?type=gene&' + geneSymbols.map(function(symbol) { return 'symbol=' + symbol; }).join('&'); return this.getRestData(searchStr).then(genes => { if (genes['@graph'].length === geneSymbols.length) { // Successfully retrieved all genes return Promise.resolve(genes); } else { var missingGenes = _.difference(geneSymbols, genes['@graph'].map(function(gene) { return gene.symbol; })); if (newExperimental.evidenceType == 'Biochemical Function') { this.setState({submitBusy: false}); // submit error; re-enable submit button this.setFormErrors('geneWithSameFunctionSameDisease.genes', missingGenes.join(', ') + ' not found'); } else if (newExperimental.evidenceType == 'Protein Interactions') { this.setState({submitBusy: false}); // submit error; re-enable submit button this.setFormErrors('interactingGenes', missingGenes.join(', ') + ' not found'); } throw genes; } }); } else { // No genes entered; just pass null to the next then return Promise.resolve(null); } }).then(data => { let currExperimental = this.state.experimental; let currExperimentalUuid = currExperimental && currExperimental.uuid; let evidenceScores = []; // Holds new array of scores let experimentalScores = currExperimental && currExperimental.scores && currExperimental.scores.length ? currExperimental.scores : []; // Find any pre-existing score(s) and put their '@id' values into an array if (experimentalScores.length) { experimentalScores.forEach(score => { evidenceScores.push(score['@id']); }); } /*************************************************************/ /* Either update or create the score status object in the DB */ /*************************************************************/ if (Object.keys(newUserScoreObj).length && newUserScoreObj.scoreStatus) { // Update and create score object when the score object has the scoreStatus key/value pair if (this.state.userScoreObj.uuid) { return this.putRestData('/evidencescore/' + this.state.userScoreObj.uuid, newUserScoreObj).then(modifiedScoreObj => { // Only need to update the evidence score object return Promise.resolve(evidenceScores); }); } else { return this.postRestData('/evidencescore/', newUserScoreObj).then(newScoreObject => { if (newScoreObject) { // Add the new score to array evidenceScores.push(newScoreObject['@graph'][0]['@id']); } return Promise.resolve(evidenceScores); }); } } else if (Object.keys(newUserScoreObj).length && !newUserScoreObj.scoreStatus) { // If an existing score object has no scoreStatus key/value pair, the user likely removed score // Then delete the score entry from the score list associated with the evidence if (this.state.userScoreObj.uuid) { newUserScoreObj['status'] = 'deleted'; return this.putRestData('/evidencescore/' + this.state.userScoreObj.uuid, newUserScoreObj).then(modifiedScoreObj => { evidenceScores.forEach(score => { if (score === modifiedScoreObj['@graph'][0]['@id']) { let index = evidenceScores.indexOf(score); evidenceScores.splice(index, 1); } }); // Return the evidence score array without the deleted object return Promise.resolve(evidenceScores); }); } } else { return Promise.resolve(null); } }).then(scoreArray => { var promise; // Add variants if they've been found if (experimentalDataVariants.length > 0) { newExperimental.variants = experimentalDataVariants; } // The scoreArray may contain: // 1. One new score // 2. New score and other curators' scores // 3. No new score but an updated score // 4. No score after the curator deletes the only score in the array if (scoreArray && scoreArray.length) { newExperimental.scores = scoreArray; } if (this.state.experimental) { // We're editing a experimental. PUT the new group object to the DB to update the existing one. promise = this.putRestData('/experimental/' + this.state.experimental.uuid, newExperimental).then(data => { return Promise.resolve({data: data['@graph'][0], experimentalAdded: false}); }); } else { // We created an experimental data item; post it to the DB promise = this.postRestData('/experimental/', newExperimental).then(data => { return Promise.resolve({data: data['@graph'][0], experimentalAdded: true}); }).then(newExperimental => { savedExperimental = newExperimental.data; if (!this.state.experimental) { return this.getRestData('/evidence/' + this.state.annotation.uuid, null, true).then(freshAnnotation => { // Get a flattened copy of the fresh annotation object and put our new experimental data into it, // ready for writing. var annotation = curator.flatten(freshAnnotation); if (!annotation.experimentalData) { annotation.experimentalData = []; } annotation.experimentalData.push(newExperimental.data['@id']); // Post the modified annotation to the DB return this.putRestData('/evidence/' + this.state.annotation.uuid, annotation).then(data => { return Promise.resolve({data: newExperimental.data, experimentalAdded: newExperimental.experimentalAdded}); }); }); } else { return Promise.resolve({data: newExperimental.data, experimentalAdded: newExperimental.experimentalAdded}); } }); } return promise; }).then(data => { // Record history of the group creation var meta, historyPromise; if (data.experimentalAdded) { // Record the creation of new experimental data meta = { experimental: { gdm: this.state.gdm['@id'], article: this.state.annotation.article['@id'] } }; historyPromise = this.recordHistory('add', data.data, meta); } else { // Record the modification of an existing group historyPromise = this.recordHistory('modify', data.data); } this.resetAllFormValues(); if (this.queryValues.editShortcut) { this.context.navigate('/curation-central/?gdm=' + this.state.gdm.uuid + '&pmid=' + this.state.annotation.article.pmid); } else { var tempExperimentalUuid = savedExperimental ? savedExperimental.uuid : this.state.experimental.uuid; this.context.navigate('/experimental-submit/?gdm=' + this.state.gdm.uuid + '&experimental=' + tempExperimentalUuid + '&evidence=' + this.state.annotation.uuid); } }).catch(function(e) { console.log('EXPERIMENTAL DATA ERROR=: %o', e); }); } } }, // Add another variant section to the FamilyVariant panel handleAddVariant: function() { this.setState({variantCount: this.state.variantCount + 1, addVariantDisabled: true}); }, // Update the ClinVar Variant ID fields upon interaction with the Add Resource modal updateVariantId: function(data, fieldNum) { var newVariantInfo = _.clone(this.state.variantInfo); var addVariantDisabled; if (data) { // Enable/Disable Add Variant button as needed if (fieldNum < MAX_VARIANTS - 1) { addVariantDisabled = false; } else { addVariantDisabled = true; } // Update the form and display values with new data this.refs['variantUuid' + fieldNum].setValue(data['uuid']); newVariantInfo[fieldNum] = { 'clinvarVariantId': data.clinvarVariantId ? data.clinvarVariantId : null, 'clinvarVariantTitle': data.clinvarVariantTitle ? data.clinvarVariantTitle : null, 'carId': data.carId ? data.carId : null, 'canonicalTranscriptTitle': data.canonicalTranscriptTitle ? data.canonicalTranscriptTitle : null, 'maneTranscriptTitle': data.maneTranscriptTitle ? data.maneTranscriptTitle : null, 'hgvsNames': data.hgvsNames ? data.hgvsNames : null, 'uuid': data.uuid }; } else { // Reset the form and display values this.refs['variantUuid' + fieldNum].setValue(''); delete newVariantInfo[fieldNum]; } // Set state this.setState({variantInfo: newVariantInfo, addVariantDisabled: addVariantDisabled}); }, // Method to fetch uniprot data from mygene.info getUniprotId(gdm) { if (gdm && gdm.gene && gdm.gene.entrezId) { let geneId = gdm.gene.entrezId; let fields = 'fields=uniprot.Swiss-Prot'; this.getRestData(this.props.href_url.protocol + external_url_map['MyGeneInfo'] + geneId + '&species=human&' + fields).then(result => { let myGeneObj = result.hits[0]; if (myGeneObj.uniprot && myGeneObj.uniprot['Swiss-Prot']) { this.setState({uniprotId: myGeneObj.uniprot['Swiss-Prot']}); } }).catch(err => { console.log('Fetch Error for Uniprot ID from MyGeneInfo =: %o', err); }); } }, render: function() { var gdm = this.state.gdm; var annotation = this.state.annotation; var pmid = (annotation && annotation.article && annotation.article.pmid) ? annotation.article.pmid : null; var experimental = this.state.experimental; /****************************************/ /* Retain pre-existing assessments data */ /****************************************/ var assessments = experimental && experimental.assessments && experimental.assessments.length ? experimental.assessments : []; var validAssessments = []; _.map(assessments, assessment => { if (assessment.value !== 'Not Assessed') { validAssessments.push(assessment); } }); var submitErrClass = 'submit-err pull-right' + (this.anyFormErrors() ? '' : ' hidden'); var session = (this.props.session && Object.keys(this.props.session).length) ? this.props.session : null; // Get the 'evidence', 'gdm', and 'experimental' UUIDs from the query string and save them locally. this.queryValues.annotationUuid = queryKeyValue('evidence', this.props.href); this.queryValues.gdmUuid = queryKeyValue('gdm', this.props.href); this.queryValues.experimentalUuid = queryKeyValue('experimental', this.props.href); this.queryValues.editShortcut = queryKeyValue('editsc', this.props.href) === ""; // define where pressing the Cancel button should take you to var cancelUrl; if (gdm) { cancelUrl = (!this.queryValues.experimentalUuid || this.queryValues.editShortcut) ? '/curation-central/?gdm=' + gdm.uuid + (pmid ? '&pmid=' + pmid : '') : '/experimental-submit/?gdm=' + gdm.uuid + (experimental ? '&experimental=' + experimental.uuid : '') + (annotation ? '&evidence=' + annotation.uuid : ''); } let uniprotId = this.state.uniprotId; // Find any pre-existing scores associated with the evidence let evidenceScores = experimental && experimental.scores && experimental.scores.length ? experimental.scores : []; let experimentalEvidenceType; if (this.state.experimentalType === 'Protein Interactions') { experimentalEvidenceType = null; } else if (this.state.experimentalType === 'Biochemical Function' || this.state.experimentalType === 'Expression') { experimentalEvidenceType = this.state.experimentalSubtype; } else if (this.state.experimentalType === 'Functional Alteration') { experimentalEvidenceType = this.state.functionalAlterationType; } else if (this.state.experimentalType === 'Model Systems') { experimentalEvidenceType = this.state.modelSystemsType; } else if (this.state.experimentalType === 'Rescue') { experimentalEvidenceType = this.state.rescueType; } return ( <div> {(!this.queryValues.experimentalUuid || this.state.experimental) ? <div> <RecordHeader gdm={gdm} omimId={this.state.currOmimId} updateOmimId={this.updateOmimId} session={session} linkGdm={true} pmid={pmid} /> <div className="container"> {annotation && annotation.article ? <div className="curation-pmid-summary"> <PmidSummary article={this.state.annotation.article} displayJournal pmidLinkout /> </div> : null} <div className="viewer-titles"> <h1>{(experimental ? 'Edit' : 'Curate') + ' Experimental Data Information'}</h1> <h2> {gdm ? <a href={'/curation-central/?gdm=' + gdm.uuid + (pmid ? '&pmid=' + pmid : '')}><i className="icon icon-briefcase"></i></a> : null} <span> &#x2F;&#x2F; {this.state.experimentalName ? <span> Experiment {this.state.experimentalName}</span> : <span className="no-entry">No entry</span>} {this.state.experimentalType && this.state.experimentalType != 'none' ? <span>({this.state.experimentalType})</span> : null}</span> </h2> </div> <div className="row group-curation-content"> <div className="col-sm-12"> <Form submitHandler={this.submitForm} formClassName="form-horizontal form-std"> <Panel> {ExperimentalNameType.call(this)} </Panel> {this.state.experimentalType == 'Biochemical Function' && this.state.experimentalNameVisible ? <PanelGroup accordion><Panel title={this.state.experimentalSubtype.charAt(0) + ". Biochemical Function"} open> {TypeBiochemicalFunction.call(this, uniprotId)} </Panel></PanelGroup> : null} {this.state.experimentalType == 'Protein Interactions' ? <PanelGroup accordion><Panel title="Protein Interactions" open> {TypeProteinInteractions.call(this)} </Panel></PanelGroup> : null} {this.state.experimentalType == 'Expression' && this.state.experimentalNameVisible ? <PanelGroup accordion><Panel title={this.state.experimentalSubtype.charAt(0) + ". Expression"} open> {TypeExpression.call(this)} </Panel></PanelGroup> : null} {this.state.experimentalType == 'Functional Alteration' ? <PanelGroup accordion><Panel title="Functional Alteration" open> {TypeFunctionalAlteration.call(this, uniprotId)} </Panel></PanelGroup> : null} {this.state.experimentalType == 'Model Systems' ? <PanelGroup accordion><Panel title="Model Systems" open> {TypeModelSystems.call(this)} </Panel></PanelGroup> : null} {this.state.experimentalType == 'Rescue' ? <PanelGroup accordion><Panel title="Rescue" open> {TypeRescue.call(this)} </Panel></PanelGroup> : null} {((this.state.experimentalType == 'Expression' && this.state.experimentalSubtype.charAt(0) != 'A') || this.state.experimentalType == 'Functional Alteration' || this.state.experimentalType == 'Model Systems' || this.state.experimentalType == 'Rescue') && this.state.experimentalNameVisible ? <PanelGroup accordion><Panel title="Experimental Data - Associated Variant(s)" open> {ExperimentalDataVariant.call(this)} </Panel></PanelGroup> : null} {this.state.experimentalNameVisible ? <div> {validAssessments.length ? <Panel panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>Assessments</dt> <dd> <div> {validAssessments.map(function(assessment, i) { return ( <span key={assessment.uuid}> {i > 0 ? <br /> : null} {assessment.value+' ('+assessment.submitted_by.title+')'} </span> ); })} </div> </dd> </div> </dl> </Panel> : null} <PanelGroup accordion> <Panel title="Experimental Data Score" panelClassName="experimental-evidence-score" open> <ScoreExperimental evidence={experimental} experimentalType={this.state.experimentalType} experimentalEvidenceType={experimentalEvidenceType} evidenceType="Experimental" session={session} handleUserScoreObj={this.handleUserScoreObj} formError={this.state.formError} affiliation={this.props.affiliation} /> </Panel> </PanelGroup> </div> : null} <div className="curation-submit clearfix"> {this.state.experimentalType != '' && this.state.experimentalType != 'none' && this.state.experimentalNameVisible ? <Input type="submit" inputClassName="btn-primary pull-right btn-inline-spacer" id="submit" title="Save" submitBusy={this.state.submitBusy} /> : null} {gdm ? <a href={cancelUrl} className="btn btn-default btn-inline-spacer pull-right">Cancel</a> : null} {experimental ? <DeleteButton gdm={gdm} parent={annotation} item={experimental} pmid={pmid} disabled={this.cv.othersAssessed} /> : null} <div className={submitErrClass}>Please fix errors on the form and resubmit.</div> </div> </Form> </div> </div> </div> </div> : null} </div> ); } }); curator_page.register(ExperimentalCuration, 'curator_page', 'experimental-curation'); /** * Experimental Data Name and Type curation panel. Call with .call(this) to run in the same context * as the calling component. */ function ExperimentalNameType() { let experimental = this.state.experimental; return ( <div className="row form-row-helper"> {!this.state.experimentalType || this.state.experimentalType == 'none' ? <div className="col-sm-7 col-sm-offset-5"> <p>Select which experiment type you would like to curate:</p> </div> : null} <Input type="select" ref="experimentalType" label="Experiment type:" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" handleChange={this.handleChange} defaultValue="none" value={experimental && experimental.evidenceType ? experimental.evidenceType : 'none'} inputDisabled={this.state.experimental!=null || this.cv.othersAssessed} required> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="Biochemical Function">Biochemical Function</option> <option value="Protein Interactions">Protein Interactions</option> <option value="Expression">Expression</option> <option value="Functional Alteration">Functional Alteration</option> <option value="Model Systems">Model Systems</option> <option value="Rescue">Rescue</option> </Input> {!this.state.experimentalType || this.state.experimentalType == 'none' ? <div className="col-sm-7 col-sm-offset-5"> <p className="alert alert-info"> <strong>Biochemical Function</strong>: The gene product performs a biochemical function shared with other known genes in the disease of interest, OR the gene product is consistent with the observed phenotype(s)<br /><br /> <strong>Protein Interactions</strong>: The gene product interacts with proteins previously implicated (genetically or biochemically) in the disease of interest<br /><br /> <strong>Expression</strong>: The gene is expressed in tissues relevant to the disease of interest, OR the gene is altered in expression in patients who have the disease<br /><br /> <strong>Functional Alteration of gene/gene product</strong>: The gene and/or gene product function is demonstrably altered in cultured patient or non-patient cells carrying candidate variant(s)<br /><br /> <strong>Model Systems</strong>: Non-human model organism OR cell culture model with a similarly disrupted copy of the affected gene shows a phenotype consistent with human disease state<br /><br /> <strong>Rescue</strong>: The phenotype in humans, non-human model organisms, cell culture models, or patient cells can be rescued by exogenous wild-type gene or gene product </p> </div> : null} {this.state.experimentalTypeDescription.map(function(description, i) { return ( <div key={i} className="col-sm-7 col-sm-offset-5"> <p className="alert alert-info">{description}</p> </div> ); })} {this.state.experimentalType && this.state.experimentalType == 'Biochemical Function' ? <Input type="select" ref="experimentalSubtype" label="Please select which one (A or B) you would like to curate" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" defaultValue="none" value={this.state.experimentalSubtype} handleChange={this.handleChange} inputDisabled={this.state.experimental!=null || this.cv.othersAssessed} required> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="A. Gene(s) with same function implicated in same disease">A. Gene(s) with same function implicated in same disease</option> <option value="B. Gene function consistent with phenotype(s)">B. Gene function consistent with phenotype(s)</option> </Input> : null} {this.state.experimentalType && this.state.experimentalType == 'Expression' ? <Input type="select" ref="experimentalSubtype" label="Please select which one (A or B) you would like to curate" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" defaultValue="none" value={this.state.experimentalSubtype} handleChange={this.handleChange} inputDisabled={this.state.experimental!=null || this.cv.othersAssessed} required> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="A. Gene normally expressed in tissue relevant to the disease">A. Gene normally expressed in tissue relevant to the disease</option> <option value="B. Altered expression in Patients">B. Altered expression in Patients</option> </Input> : null} {this.state.experimentalNameVisible ? <Input type="text" ref="experimentalName" label="Experiment name:" error={this.getFormError('experimentalName')} clearError={this.clrFormErrors.bind(null, 'experimentalName')} maxLength="60" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" value={experimental && experimental.label ? experimental.label : ''} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required /> : null} </div> ); } /** * Biochemical Function type curation panel. Call with .call(this) to run in the same context * as the calling component. */ function TypeBiochemicalFunction(uniprotId) { let experimental = this.state.experimental ? this.state.experimental : {}; let biochemicalFunction = experimental.biochemicalFunction ? experimental.biochemicalFunction : {}; let BF_identifiedFunction, BF_identifiedFunctionFreeText, BF_evidenceForFunction, BF_evidenceForFunctionInPaper; if (biochemicalFunction) { BF_identifiedFunction = biochemicalFunction.identifiedFunction ? biochemicalFunction.identifiedFunction : ''; BF_identifiedFunctionFreeText = biochemicalFunction.identifiedFunctionFreeText ? biochemicalFunction.identifiedFunctionFreeText : ''; BF_evidenceForFunction = biochemicalFunction.evidenceForFunction ? biochemicalFunction.evidenceForFunction : ''; BF_evidenceForFunctionInPaper = biochemicalFunction.evidenceForFunctionInPaper ? biochemicalFunction.evidenceForFunctionInPaper : ''; } return ( <div className="row form-row-helper"> {curator.renderWarning('GO')} <div className="col-sm-7 col-sm-offset-5"> <ul className="gene-ontology help-text style-list"> <li>View <a href={dbxref_prefix_map['UniProtKB'] + uniprotId} target="_blank">existing GO annotations for this gene</a> in UniProt.</li> <li>Search <a href={external_url_map['GO']} target="_blank">GO</a> using the OLS.</li> <li>Search for existing or new terms using <a href="https://www.ebi.ac.uk/QuickGO/" target="_blank">QuickGO</a></li> </ul> </div> <Input type="text" ref="identifiedFunction" label={<span>Identified function of gene in this record <span className="normal">(GO ID)</span>:</span>} error={this.getFormError('identifiedFunction')} clearError={this.clrFormErrors.bind(null, 'identifiedFunction')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" value={BF_identifiedFunction} placeholder="e.g. GO:2001284" inputDisabled={this.cv.othersAssessed} handleChange={this.handleChange} required={!this.state.bioChemicalFunctionIF_FreeText} customErrorMsg="Enter GO ID and/or free text" /> <Input type="textarea" ref="identifiedFunctionFreeText" label={<span>Identified function of gene in this record <span className="normal">(free text)</span>:</span>} error={this.getFormError('identifiedFunctionFreeText')} clearError={this.clrFormErrors.bind(null, 'identifiedFunctionFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" value={BF_identifiedFunctionFreeText} inputDisabled={this.cv.othersAssessed} row="2" placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" handleChange={this.handleChange} required={!this.state.bioChemicalFunctionIF_GoId} customErrorMsg="Enter GO ID and/or free text" /> <Input type="textarea" ref="evidenceForFunction" label="Evidence for above function:" error={this.getFormError('evidenceForFunction')} clearError={this.clrFormErrors.bind(null, 'evidenceForFunction')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={BF_evidenceForFunction} inputDisabled={this.cv.othersAssessed} required /> <Input type="textarea" ref="evidenceForFunctionInPaper" label="Notes on where evidence found in paper:" error={this.getFormError('evidenceForFunctionInPaper')} clearError={this.clrFormErrors.bind(null, 'evidenceForFunctionInPaper')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={BF_evidenceForFunctionInPaper} inputDisabled={this.cv.othersAssessed} /> {this.state.experimentalSubtype == 'A. Gene(s) with same function implicated in same disease' ? TypeBiochemicalFunctionA.call(this) : null} {this.state.experimentalSubtype == 'B. Gene function consistent with phenotype(s)' ? TypeBiochemicalFunctionB.call(this) : null} </div> ); } function TypeBiochemicalFunctionA() { let experimental = this.state.experimental ? this.state.experimental : {}; let biochemicalFunction = experimental.biochemicalFunction ? experimental.biochemicalFunction : {}; let BF_genes, BF_evidenceForOtherGenesWithSameFunction, BF_explanationOfOtherGenes, BF_evidenceInPaper; if (biochemicalFunction) { biochemicalFunction.geneWithSameFunctionSameDisease = biochemicalFunction.geneWithSameFunctionSameDisease ? biochemicalFunction.geneWithSameFunctionSameDisease : {}; if (biochemicalFunction.geneWithSameFunctionSameDisease) { BF_genes = biochemicalFunction.geneWithSameFunctionSameDisease.genes ? biochemicalFunction.geneWithSameFunctionSameDisease.genes.map(gene => { return gene.symbol; }).join(', ') : ''; BF_evidenceForOtherGenesWithSameFunction = biochemicalFunction.geneWithSameFunctionSameDisease.evidenceForOtherGenesWithSameFunction ? biochemicalFunction.geneWithSameFunctionSameDisease.evidenceForOtherGenesWithSameFunction : ''; BF_explanationOfOtherGenes = biochemicalFunction.geneWithSameFunctionSameDisease.explanationOfOtherGenes ? biochemicalFunction.geneWithSameFunctionSameDisease.explanationOfOtherGenes : ''; BF_evidenceInPaper = biochemicalFunction.geneWithSameFunctionSameDisease.evidenceInPaper ? biochemicalFunction.geneWithSameFunctionSameDisease.evidenceInPaper : ''; } } return ( <div> <Input type="text" ref="geneWithSameFunctionSameDisease.genes" label={<LabelGenesWithSameFunction />} error={this.getFormError('geneWithSameFunctionSameDisease.genes')} clearError={this.clrFormErrors.bind(null, 'geneWithSameFunctionSameDisease.genes')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" placeholder="e.g. DICER1" value={BF_genes} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required /> <Input type="textarea" ref="geneWithSameFunctionSameDisease.evidenceForOtherGenesWithSameFunction" label="Evidence that above gene(s) share same function with gene in record:" error={this.getFormError('geneWithSameFunctionSameDisease.evidenceForOtherGenesWithSameFunction')} clearError={this.clrFormErrors.bind(null, 'geneWithSameFunctionSameDisease.evidenceForOtherGenesWithSameFunction')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={BF_evidenceForOtherGenesWithSameFunction} inputDisabled={this.cv.othersAssessed} required /> <Input type="textarea" ref="geneWithSameFunctionSameDisease.sharedDisease" label="Shared disease:" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputDisabled={true} rows="2" value={!this.state.gdm.disease.freetext ? this.state.gdm.disease.term + ' (' + this.state.gdm.disease.diseaseId.replace('_', ':') + ')' : this.state.gdm.disease.term + ' (' + this.props.session.user_properties.title + ')'} /> <Input type="checkbox" ref="geneWithSameFunctionSameDisease.geneImplicatedWithDisease" label="Has this gene(s) been implicated in the above disease?:" error={this.getFormError('geneWithSameFunctionSameDisease.geneImplicatedWithDisease')} clearError={this.clrFormErrors.bind(null, 'geneWithSameFunctionSameDisease.geneImplicatedWithDisease')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" checked={this.state.geneImplicatedWithDisease} defaultChecked="false" handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} /> <p className="col-sm-7 col-sm-offset-5 hug-top alert alert-warning"><strong>Warning:</strong> not checking the above box indicates this criteria has not been met for this evidence; this should be taken into account during its evaluation.</p> <Input type="textarea" ref="geneWithSameFunctionSameDisease.explanationOfOtherGenes" label="How has this other gene(s) been implicated in the above disease?:" error={this.getFormError('geneWithSameFunctionSameDisease.explanationOfOtherGenes')} clearError={this.clrFormErrors.bind(null, 'geneWithSameFunctionSameDisease.explanationOfOtherGenes')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={BF_explanationOfOtherGenes} inputDisabled={this.cv.othersAssessed} required={this.state.geneImplicatedWithDisease} /> <Input type="textarea" ref="geneWithSameFunctionSameDisease.evidenceInPaper" label="Additional comments:" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={BF_evidenceInPaper} inputDisabled={this.cv.othersAssessed} /> </div> ); } /** * HTML labels for Biochemical Functions panel A */ const LabelGenesWithSameFunction = () => { return ( <span>Other gene(s) with same function as gene in record <span className="normal">(<a href={external_url_map['HGNCHome']} target="_blank" title="HGNC homepage in a new tab">HGNC</a> symbol)</span>:</span> ); }; function TypeBiochemicalFunctionB() { let experimental = this.state.experimental ? this.state.experimental : {}; let biochemicalFunction = experimental.biochemicalFunction ? experimental.biochemicalFunction : {}; let BF_phenotypeHPO, BF_phenotypeFreeText, BF_explanation, BF_evidenceInPaper; if (biochemicalFunction) { biochemicalFunction.geneFunctionConsistentWithPhenotype = biochemicalFunction.geneFunctionConsistentWithPhenotype ? biochemicalFunction.geneFunctionConsistentWithPhenotype : {}; if (biochemicalFunction.geneFunctionConsistentWithPhenotype) { BF_phenotypeHPO = biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeHPO ? biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeHPO.join(', ') : ''; BF_phenotypeFreeText = biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeFreeText ? biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeFreeText : ''; BF_explanation = biochemicalFunction.geneFunctionConsistentWithPhenotype.explanation ? biochemicalFunction.geneFunctionConsistentWithPhenotype.explanation : ''; BF_evidenceInPaper = biochemicalFunction.geneFunctionConsistentWithPhenotype.evidenceInPaper ? biochemicalFunction.geneFunctionConsistentWithPhenotype.evidenceInPaper : ''; } } return ( <div> {curator.renderPhenotype(null, 'Experimental')} <Input type="textarea" ref="geneFunctionConsistentWithPhenotype.phenotypeHPO" label={<LabelHPOIDs />} rows="1" error={this.getFormError('geneFunctionConsistentWithPhenotype.phenotypeHPO')} clearError={this.clrFormErrors.bind(null, 'geneFunctionConsistentWithPhenotype.phenotypeHPO')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" placeholder="e.g. HP:0010704" value={BF_phenotypeHPO} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required={!this.state.biochemicalFunctionFT} customErrorMsg="Enter HPO ID(s) and/or free text" /> <Input type="textarea" ref="geneFunctionConsistentWithPhenotype.phenotypeFreeText" label={<span>Phenotype(s) consistent with function <span className="normal">(free text)</span>:</span>} error={this.getFormError('geneFunctionConsistentWithPhenotype.phenotypeFreeText')} clearError={this.clrFormErrors.bind(null, 'geneFunctionConsistentWithPhenotype.phenotypeFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="2" value={BF_phenotypeFreeText} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required={!this.state.biochemicalFunctionHPO} customErrorMsg="Enter HPO ID(s) and/or free text" /> <Input type="textarea" ref="geneFunctionConsistentWithPhenotype.explanation" label="Explanation of how phenotype is consistent with disease:" error={this.getFormError('geneFunctionConsistentWithPhenotype.explanation')} clearError={this.clrFormErrors.bind(null, 'geneFunctionConsistentWithPhenotype.explanation')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={BF_explanation} inputDisabled={!(this.state.biochemicalFunctionHPO || this.state.biochemicalFunctionFT) || this.cv.othersAssessed} required={this.state.biochemicalFunctionHPO || this.state.biochemicalFunctionFT} /> <Input type="textarea" ref="geneFunctionConsistentWithPhenotype.evidenceInPaper" label="Notes on where evidence found in paper:" error={this.getFormError('geneFunctionConsistentWithPhenotype.evidenceInPaper')} clearError={this.clrFormErrors.bind(null, 'geneFunctionConsistentWithPhenotype.evidenceInPaper')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={BF_evidenceInPaper} inputDisabled={!(this.state.biochemicalFunctionHPO || this.state.biochemicalFunctionFT) || this.cv.othersAssessed} /> </div> ); } /** * HTML labels for Biochemical Functions panel B */ const LabelHPOIDs = () => { return ( <span>Phenotype(s) consistent with function <span className="normal">(<a href={external_url_map['HPOBrowser']} target="_blank" title="Open HPO Browser in a new tab">HPO</a> ID)</span>:</span> ); }; /** * Protein Interaction type curation panel. Call with .call(this) to run in the same context * as the calling component. */ function TypeProteinInteractions() { let experimental = this.state.experimental ? this.state.experimental : {}; let proteinInteractions = experimental.proteinInteractions ? experimental.proteinInteractions : {}; let PI_interactingGenes, PI_interactionType, PI_experimentalInteractionDetection, PI_relationshipOfOtherGenesToDisese, PI_evidenceInPaper; if (proteinInteractions) { PI_interactingGenes = proteinInteractions.interactingGenes ? proteinInteractions.interactingGenes.map(gene => { return gene.symbol; }).join(', ') : ''; PI_interactionType = proteinInteractions.interactionType ? proteinInteractions.interactionType : 'none'; PI_experimentalInteractionDetection = proteinInteractions.experimentalInteractionDetection ? proteinInteractions.experimentalInteractionDetection : 'none'; PI_relationshipOfOtherGenesToDisese = proteinInteractions.relationshipOfOtherGenesToDisese ? proteinInteractions.relationshipOfOtherGenesToDisese : ''; PI_evidenceInPaper = proteinInteractions.evidenceInPaper ? proteinInteractions.evidenceInPaper : ''; } return ( <div className="row form-row-helper"> <Input type="text" ref="interactingGenes" label={<LabelInteractingGenes />} error={this.getFormError('interactingGenes')} clearError={this.clrFormErrors.bind(null, 'interactingGenes')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" value={PI_interactingGenes} placeholder="e.g. DICER1" inputDisabled={this.cv.othersAssessed} required /> <Input type="select" ref="interactionType" label="Interaction Type:" defaultValue="none" error={this.getFormError('interactionType')} clearError={this.clrFormErrors.bind(null, 'interactionType')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" value={PI_interactionType} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="physical association (MI:0915)">physical association (MI:0915)</option> <option value="genetic interaction (MI:0208)">genetic interaction (MI:0208)</option> <option value="negative genetic interaction (MI:0933)">negative genetic interaction (MI:0933)</option> <option value="positive genetic interaction (MI:0935)">positive genetic interaction (MI:0935)</option> </Input> <Input type="select" ref="experimentalInteractionDetection" label="Method by which interaction detected:" error={this.getFormError('experimentalInteractionDetection')} clearError={this.clrFormErrors.bind(null, 'experimentalInteractionDetection')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" defaultValue="none" value={PI_experimentalInteractionDetection} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="affinity chromatography technology (MI:0004)">affinity chromatography technology (MI:0004)</option> <option value="coimmunoprecipitation (MI:0019)">coimmunoprecipitation (MI:0019)</option> <option value="comigration in gel electrophoresis (MI:0807)">comigration in gel electrophoresis (MI:0807)</option> <option value="electron microscopy (MI:0040)">electron microscopy (MI:0040)</option> <option value="protein cross-linking with a bifunctional reagent (MI:0031)">protein cross-linking with a bifunctional reagent (MI:0031)</option> <option value="pull down (MI:0096)">pull down (MI:0096)</option> <option value="synthetic genetic analysis (MI:0441)">synthetic genetic analysis (MI:0441)</option> <option value="two hybrid (MI:0018)">two hybrid (MI:0018)</option> <option value="x-ray crystallography (MI:0114)">x-ray crystallography (MI:0114)</option> </Input> <Input type="checkbox" ref="geneImplicatedInDisease" label="Has this gene or genes been implicated in the above disease?:" error={this.getFormError('geneImplicatedInDisease')} clearError={this.clrFormErrors.bind(null, 'geneImplicatedInDisease')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" checked={this.state.geneImplicatedInDisease} defaultChecked="false" inputDisabled={this.cv.othersAssessed} handleChange={this.handleChange} /> <p className="col-sm-7 col-sm-offset-5 hug-top alert alert-warning"><strong>Warning:</strong> not checking the above box indicates this criteria has not been met for this evidence; this should be taken into account during its evaluation.</p> <Input type="textarea" ref="relationshipOfOtherGenesToDisese" label="Explanation of relationship of interacting gene(s):" error={this.getFormError('relationshipOfOtherGenesToDisese')} clearError={this.clrFormErrors.bind(null, 'relationshipOfOtherGenesToDisese')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={PI_relationshipOfOtherGenesToDisese} inputDisabled={this.cv.othersAssessed} required={this.state.geneImplicatedInDisease} /> <Input type="textarea" ref="evidenceInPaper" label="Information about where evidence can be found on paper" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={PI_evidenceInPaper}inputDisabled={this.cv.othersAssessed} /> </div> ); } /** * HTML labels for Protein Interactions panel */ const LabelInteractingGenes = () => { return ( <span>Interacting gene(s) <span className="normal">(<a href={external_url_map['HGNCHome']} target="_blank" title="HGNC homepage in a new tab">HGNC</a> symbol)</span>:</span> ); }; /** * Expression type curation panel. Call with .call(this) to run in the same context * as the calling component. */ function TypeExpression() { let experimental = this.state.experimental ? this.state.experimental : {}; let expression = experimental.expression ? experimental.expression : {}; let EXP_organOfTissue, EXP_organOfTissueFreeText; if (expression) { EXP_organOfTissue = expression.organOfTissue ? expression.organOfTissue : ''; EXP_organOfTissueFreeText = expression.organOfTissueFreeText ? expression.organOfTissueFreeText : ''; } return ( <div className="row form-row-helper"> {curator.renderWarning('UBERON')} <p className="col-sm-7 col-sm-offset-5"> Search the <a href={external_url_map['Uberon']} target="_blank">Uberon</a> using the OLS. </p> <Input type="text" ref="organOfTissue" label={<span>Organ or tissue relevant to disease <span className="normal">(Uberon ID)</span>:</span>} error={this.getFormError('organOfTissue')} clearError={this.clrFormErrors.bind(null, 'organOfTissue')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" value={EXP_organOfTissue} placeholder="e.g. UBERON:0015228 or UBERON_0015228 or UBERON:0015228, UBERON:0012345" inputDisabled={this.cv.othersAssessed} handleChange={this.handleChange} required={!this.state.expressionOT_FreeText} customErrorMsg="Enter Uberon ID and/or free text" /> <Input type="textarea" ref="organOfTissueFreeText" label={<span>Organ or tissue relevant to disease <span className="normal">(free text)</span>:</span>} error={this.getFormError('organOfTissueFreeText')} clearError={this.clrFormErrors.bind(null, 'organOfTissueFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" value={EXP_organOfTissueFreeText} inputDisabled={this.cv.othersAssessed} row="2" placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" handleChange={this.handleChange} required={!this.state.expressionOT_UberonId} customErrorMsg="Enter Uberon ID and/or free text" /> {this.state.experimentalSubtype == 'A. Gene normally expressed in tissue relevant to the disease' ? TypeExpressionA.call(this) : null} {this.state.experimentalSubtype == 'B. Altered expression in Patients' ? TypeExpressionB.call(this) : null} </div> ); } function TypeExpressionA() { let experimental = this.state.experimental ? this.state.experimental : {}; let expression = experimental.expression ? experimental.expression : {}; let EXP_normalExpression_evidence, EXP_normalExpression_evidenceInPaper; if (expression) { expression.normalExpression = expression.normalExpression ? expression.normalExpression : {}; if (expression.normalExpression) { EXP_normalExpression_evidence = expression.normalExpression.evidence ? expression.normalExpression.evidence : ''; EXP_normalExpression_evidenceInPaper = expression.normalExpression.evidenceInPaper ? expression.normalExpression.evidenceInPaper : ''; } } return ( <div> <Input type="checkbox" ref="normalExpression.expressedInTissue" label="Is the gene normally expressed in the above tissue?:" error={this.getFormError('normalExpression.expressedInTissue')} clearError={this.clrFormErrors.bind(null, 'normalExpression.expressedInTissue')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" checked={this.state.expressedInTissue} defaultChecked="false" handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} /> <p className="col-sm-7 col-sm-offset-5 hug-top alert alert-warning"><strong>Warning:</strong> not checking the above box indicates this criteria has not been met for this evidence; this should be taken into account during its evaluation.</p> <Input type="textarea" ref="normalExpression.evidence" label="Evidence for normal expression in disease tissue:" error={this.getFormError('normalExpression.evidence')} clearError={this.clrFormErrors.bind(null, 'normalExpression.evidence')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={EXP_normalExpression_evidence} inputDisabled={this.cv.othersAssessed} required={this.state.expressedInTissue} /> <Input type="textarea" ref="normalExpression.evidenceInPaper" label="Notes on where evidence found:" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={EXP_normalExpression_evidenceInPaper} inputDisabled={this.cv.othersAssessed} /> </div> ); } function TypeExpressionB() { let experimental = this.state.experimental ? this.state.experimental : {}; let expression = experimental.expression ? experimental.expression : {}; let EXP_alteredExpression_evidence, EXP_alteredExpression_evidenceInPaper; if (expression) { expression.alteredExpression = expression.alteredExpression ? expression.alteredExpression : {}; if (expression.alteredExpression) { EXP_alteredExpression_evidence = expression.alteredExpression.evidence ? expression.alteredExpression.evidence : ''; EXP_alteredExpression_evidenceInPaper = expression.alteredExpression.evidenceInPaper ? expression.alteredExpression.evidenceInPaper : ''; } } return ( <div> <Input type="checkbox" ref="alteredExpression.expressedInPatients" label="Is expression altered in patients who have the disease?:" error={this.getFormError('alteredExpression.expressedInPatients')} clearError={this.clrFormErrors.bind(null, 'alteredExpression.expressedInPatients')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" checked={this.state.expressedInPatients} defaultChecked="false" handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} /> <p className="col-sm-7 col-sm-offset-5 hug-top alert alert-warning"><strong>Warning:</strong> not checking the above box indicates this criteria has not been met for this evidence; this should be taken into account during its evaluation.</p> <Input type="textarea" ref="alteredExpression.evidence" label="Evidence for altered expression in patients:" error={this.getFormError('alteredExpression.evidence')} clearError={this.clrFormErrors.bind(null, 'alteredExpression.evidence')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={EXP_alteredExpression_evidence} inputDisabled={this.cv.othersAssessed} required={this.state.expressedInPatients} /> <Input type="textarea" ref="alteredExpression.evidenceInPaper" label="Notes on where evidence found in paper:" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={EXP_alteredExpression_evidenceInPaper} inputDisabled={this.cv.othersAssessed} /> </div> ); } /** * Functional Alteration type curation panel. Call with .call(this) to run in the same context * as the calling component. * @param {string} uniprotId */ function TypeFunctionalAlteration(uniprotId) { let experimental = this.state.experimental ? this.state.experimental : {}; let functionalAlteration = experimental.functionalAlteration ? experimental.functionalAlteration : {}; let FA_functionalAlterationType, FA_patientCells, FA_patientCellsFreeText, FA_nonPatientCells, FA_nonPatientCellsFreeText, FA_descriptionOfGeneAlteration, FA_normalFunctionOfGene, FA_normalFunctionOfGeneFreeText, FA_evidenceForNormalFunction, FA_evidenceInPaper; if (functionalAlteration) { FA_functionalAlterationType = functionalAlteration.functionalAlterationType ? functionalAlteration.functionalAlterationType : 'none'; FA_patientCells = functionalAlteration.patientCells ? functionalAlteration.patientCells : ''; FA_patientCellsFreeText = functionalAlteration.patientCellsFreeText ? functionalAlteration.patientCellsFreeText : ''; FA_nonPatientCells = functionalAlteration.nonPatientCells ? functionalAlteration.nonPatientCells : ''; FA_nonPatientCellsFreeText = functionalAlteration.nonPatientCellsFreeText ? functionalAlteration.nonPatientCellsFreeText : ''; FA_descriptionOfGeneAlteration = functionalAlteration.descriptionOfGeneAlteration ? functionalAlteration.descriptionOfGeneAlteration : ''; FA_normalFunctionOfGene = functionalAlteration.normalFunctionOfGene ? functionalAlteration.normalFunctionOfGene : ''; FA_normalFunctionOfGeneFreeText = functionalAlteration.normalFunctionOfGeneFreeText ? functionalAlteration.normalFunctionOfGeneFreeText : ''; FA_evidenceForNormalFunction = functionalAlteration.evidenceForNormalFunction ? functionalAlteration.evidenceForNormalFunction : ''; FA_evidenceInPaper = functionalAlteration.evidenceInPaper ? functionalAlteration.evidenceInPaper : ''; } return ( <div className="row form-row-helper"> <Input type="select" ref="functionalAlterationType" label="Cultured patient or non-patient cells carrying candidate variant(s)?:" error={this.getFormError('functionalAlterationType')} clearError={this.clrFormErrors.bind(null, 'functionalAlterationType')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" defaultValue="none" value={FA_functionalAlterationType} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="Patient cells">Patient cells</option> <option value="Non-patient cells">Non-patient cells</option> </Input> {this.state.functionalAlterationType === 'Patient cells' ? <div> {curator.renderWarning('CL')} <p className="col-sm-7 col-sm-offset-5"> Search the <a href={external_url_map['CL']} target="_blank">Cell Ontology (CL)</a> using the OLS. </p> <Input type="textarea" ref="funcalt.patientCells" label={<span>Patient cell type <span className="normal">(CL ID)</span>:</span>} error={this.getFormError('funcalt.patientCells')} clearError={this.clrFormErrors.bind(null, 'funcalt.patientCells')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input no-resize" rows="1" value={FA_patientCells} placeholder="e.g. CL:0000057 or CL_0000057" inputDisabled={this.cv.othersAssessed} handleChange={this.handleChange} required={!this.state.functionalAlterationPCells_FreeText} customErrorMsg="Enter CL ID and/or free text" /> <Input type="textarea" ref="funcalt.patientCellsFreeText" label={<span>Patient cell type <span className="normal">(free text)</span>:</span>} error={this.getFormError('funcalt.patientCellsFreeText')} clearError={this.clrFormErrors.bind(null, 'funcalt.patientCellsFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" value={FA_patientCellsFreeText} inputDisabled={this.cv.othersAssessed} row="2" placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" handleChange={this.handleChange} required={!this.state.functionalAlterationPCells_ClId} customErrorMsg="Enter CL ID and/or free text" /> </div> : null} {this.state.functionalAlterationType === 'Non-patient cells' ? <div> {curator.renderWarning('CL_EFO')} <p className="col-sm-7 col-sm-offset-5"> Search the <a href={external_url_map['EFO']} target="_blank">EFO</a> or <a href={external_url_map['CL']} target="_blank">Cell Ontology (CL)</a> using the OLS. </p> <Input type="textarea" ref="funcalt.nonPatientCells" label={<span>Non-patient cell type <span className="normal">(EFO or CL ID)</span>:</span>} error={this.getFormError('funcalt.nonPatientCells')} clearError={this.clrFormErrors.bind(null, 'funcalt.nonPatientCells')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input no-resize" rows="1" value={FA_nonPatientCells} placeholder="e.g. EFO:0001187 or EFO_0001187; CL:0000057 or CL_0000057" inputDisabled={this.cv.othersAssessed} handleChange={this.handleChange} required={!this.state.functionalAlterationNPCells_FreeText} customErrorMsg="Enter EFO or CL ID, and/or free text" /> <Input type="textarea" ref="funcalt.nonPatientCellsFreeText" label={<span>Non-patient cell type <span className="normal">(free text)</span>:</span>} error={this.getFormError('funcalt.nonPatientCellsFreeText')} clearError={this.clrFormErrors.bind(null, 'funcalt.nonPatientCellsFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" value={FA_nonPatientCellsFreeText} inputDisabled={this.cv.othersAssessed} row="2" placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" handleChange={this.handleChange} required={!this.state.functionalAlterationNPCells_EfoId} customErrorMsg="EEnter EFO or CL ID, and/or free text" /> </div> : null} {curator.renderWarning('GO')} <div className="col-sm-7 col-sm-offset-5"> <ul className="gene-ontology help-text style-list"> <li>View <a href={dbxref_prefix_map['UniProtKB'] + uniprotId} target="_blank">existing GO annotations for this gene</a> in UniProt.</li> <li>Search <a href={external_url_map['GO']} target="_blank">GO</a> using the OLS.</li> <li>Search for existing or new terms using <a href="https://www.ebi.ac.uk/QuickGO/" target="_blank" rel="noopener noreferrer">QuickGO</a></li> </ul> </div> <Input type="text" ref="normalFunctionOfGene" label={<span>Normal function of gene/gene product <span className="normal">(GO ID)</span>:</span>} error={this.getFormError('normalFunctionOfGene')} clearError={this.clrFormErrors.bind(null, 'normalFunctionOfGene')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" value={FA_normalFunctionOfGene} placeholder="e.g. GO:2001284" inputDisabled={this.cv.othersAssessed} handleChange={this.handleChange} required={!this.state.functionalAlterationNFG_FreeText} customErrorMsg="Enter GO ID and/or free text" /> <Input type="textarea" ref="normalFunctionOfGeneFreeText" label={<span>Normal function of gene/gene product <span className="normal">(free text)</span>:</span>} error={this.getFormError('normalFunctionOfGeneFreeText')} clearError={this.clrFormErrors.bind(null, 'normalFunctionOfGeneFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" row="2" value={FA_normalFunctionOfGeneFreeText} inputDisabled={this.cv.othersAssessed} placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" handleChange={this.handleChange} required={!this.state.functionalAlterationNFG_GoId} customErrorMsg="Enter GO ID and/or free text" /> <Input type="textarea" ref="descriptionOfGeneAlteration" label="Description of gene alteration:" error={this.getFormError('descriptionOfGeneAlteration')} clearError={this.clrFormErrors.bind(null, 'descriptionOfGeneAlteration')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={FA_descriptionOfGeneAlteration} inputDisabled={this.cv.othersAssessed} required /> <Input type="textarea" ref="evidenceForNormalFunction" label="Evidence for altered function:" error={this.getFormError('evidenceForNormalFunction')} clearError={this.clrFormErrors.bind(null, 'evidenceForNormalFunction')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={FA_evidenceForNormalFunction} inputDisabled={this.cv.othersAssessed} required /> <Input type="textarea" ref="evidenceInPaper" label="Notes on where evidence found in paper:" error={this.getFormError('evidenceInPaper')} clearError={this.clrFormErrors.bind(null, 'evidenceInPaper')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={FA_evidenceInPaper} inputDisabled={this.cv.othersAssessed} /> </div> ); } /** * Model Systems type curation panel. Call with .call(this) to run in the same context * as the calling component. */ function TypeModelSystems() { let experimental = this.state.experimental ? this.state.experimental : {}; let modelSystems = experimental.modelSystems ? experimental.modelSystems : {}; let MS_modelSystemsType, MS_nonHumanModel, MS_cellCulture, MS_cellCultureFreeText, MS_descriptionOfGeneAlteration, MS_phenotypeHPO, MS_phenotypeFreeText, MS_phenotypeHPOObserved, MS_phenotypeFreetextObserved, MS_explanation, MS_evidenceInPaper; if (modelSystems) { MS_modelSystemsType = modelSystems.modelSystemsType ? modelSystems.modelSystemsType : 'none'; MS_nonHumanModel = modelSystems.nonHumanModel ? modelSystems.nonHumanModel : 'none'; MS_cellCulture = modelSystems.cellCulture ? modelSystems.cellCulture : ''; MS_cellCultureFreeText = modelSystems.cellCultureFreeText ? modelSystems.cellCultureFreeText : ''; MS_descriptionOfGeneAlteration = modelSystems.descriptionOfGeneAlteration ? modelSystems.descriptionOfGeneAlteration : ''; MS_phenotypeHPO = modelSystems.phenotypeHPO ? modelSystems.phenotypeHPO : ''; MS_phenotypeFreeText = modelSystems.phenotypeFreeText ? modelSystems.phenotypeFreeText : ''; MS_phenotypeHPOObserved = modelSystems.phenotypeHPOObserved ? modelSystems.phenotypeHPOObserved : ''; MS_phenotypeFreetextObserved = modelSystems.phenotypeFreetextObserved ? modelSystems.phenotypeFreetextObserved : ''; MS_explanation = modelSystems.explanation ? modelSystems.explanation : ''; MS_evidenceInPaper = modelSystems.evidenceInPaper ? modelSystems.evidenceInPaper : ''; } return ( <div className="row form-row-helper"> <Input type="select" ref="modelSystemsType" label="Non-human model organism or cell culture model?:" error={this.getFormError('modelSystemsType')} clearError={this.clrFormErrors.bind(null, 'modelSystemsType')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" defaultValue="none" value={MS_modelSystemsType} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="Non-human model organism">Non-human model organism</option> <option value="Cell culture model">Cell culture model</option> </Input> {this.state.modelSystemsType === 'Non-human model organism' ? <div> <Input type="select" ref="nonHumanModel" label="Non-human model organism:" error={this.getFormError('nonHumanModel')} clearError={this.clrFormErrors.bind(null, 'nonHumanModel')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" defaultValue="none" value={MS_nonHumanModel} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="Budding yeast (Saccharomyces cerevisiae) 4932">Budding yeast (Saccharomyces cerevisiae) 4932</option> <option value="Cat (Felis catus) 9685">Cat (Felis catus) 9685</option> <option value="Chicken (Gallus gallus) 9031">Chicken (Gallus gallus) 9031</option> <option value="Chimpanzee (Pan troglodytes) 9598">Chimpanzee (Pan troglodytes) 9598</option> <option value="Chlamydomonas (Chlamydomonas reinhardtii) 3055">Chlamydomonas (Chlamydomonas reinhardtii) 3055</option> <option value="Cow (Bos taurus) 9913">Cow (Bos taurus) 9913</option> <option value="Dog (Canis lupus familiaris) 9615">Dog (Canis lupus familiaris) 9615</option> <option value="Fission yeast (Schizosaccharomyces pombe) 4896">Fission yeast (Schizosaccharomyces pombe) 4896</option> <option value="Frog (Xenopus) 262014">Frog (Xenopus) 262014</option> <option value="Fruit fly (Drosophila) 7215">Fruit fly (Drosophila) 7215</option> <option value="Gerbil (Gerbillinae) 10045">Gerbil (Gerbillinae) 10045</option> <option value="Guinea pig (Cavia porcellus) 10141">Guinea pig (Cavia porcellus) 10141</option> <option value="Hamster (Cricetinae) 10026">Hamster (Cricetinae) 10026</option> <option value="Macaque (Macaca) 9539">Macaque (Macaca) 9539</option> <option value="Mouse (Mus musculus) 10090">Mouse (Mus musculus) 10090</option> <option value="Pig (Sus scrofa) 9823">Pig (Sus scrofa) 9823</option> <option value="Rabbit (Oryctolagus cuniculus) 9986">Rabbit (Oryctolagus cuniculus) 9986</option> <option value="Rat (Rattus norvegicus) 10116">Rat (Rattus norvegicus) 10116</option> <option value="Round worm (Caenorhabditis elegans) 6239">Round worm (Caenorhabditis elegans) 6239</option> <option value="Sheep (Ovis aries) 9940">Sheep (Ovis aries) 9940</option> <option value="Zebra finch (Taeniopygia guttata) 59729">Zebra finch (Taeniopygia guttata) 59729</option> <option value="Zebrafish (Danio rerio) 7955">Zebrafish (Danio rerio) 7955</option> </Input> </div> : null} {this.state.modelSystemsType === 'Cell culture model' ? <div> {curator.renderWarning('CL_EFO')} <p className="col-sm-7 col-sm-offset-5"> Search the <a href={external_url_map['EFO']} target="_blank">EFO</a> or <a href={external_url_map['CL']} target="_blank">Cell Ontology (CL)</a> using the OLS. </p> <Input type="textarea" ref="cellCulture" label={<span>Cell culture model type/line <span className="normal">(EFO or CL ID)</span>:</span>} error={this.getFormError('cellCulture')} clearError={this.clrFormErrors.bind(null, 'cellCulture')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input no-resize" rows="1" value={MS_cellCulture} placeholder="e.g. EFO:0001187 or EFO_0001187; CL:0000057 or CL_0000057" inputDisabled={this.cv.othersAssessed} handleChange={this.handleChange} required={!this.state.modelSystemsCC_FreeText} customErrorMsg="Enter EFO or CL ID, and/or free text" /> <Input type="textarea" ref="cellCultureFreeText" label={<span>Cell culture model type/line <span className="normal">(free text)</span>:</span>} error={this.getFormError('cellCultureFreeText')} clearError={this.clrFormErrors.bind(null, 'cellCultureFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" value={MS_cellCultureFreeText} inputDisabled={this.cv.othersAssessed} row="2" placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" handleChange={this.handleChange} required={!this.state.modelSystemsCC_EfoId} customErrorMsg="Enter EFO or CL ID, and/or free text" /> </div> : null} <Input type="textarea" ref="descriptionOfGeneAlteration" label="Description of gene alteration:" error={this.getFormError('descriptionOfGeneAlteration')} clearError={this.clrFormErrors.bind(null, 'descriptionOfGeneAlteration')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={MS_descriptionOfGeneAlteration} inputDisabled={this.cv.othersAssessed} required /> {curator.renderPhenotype(null, 'Experimental')} <Input type="textarea" ref="model.phenotypeHPOObserved" label={<LabelPhenotypeObserved />} rows="1" error={this.getFormError('model.phenotypeHPOObserved')} clearError={this.clrFormErrors.bind(null, 'model.phenotypeHPOObserved')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" value={MS_phenotypeHPOObserved} placeholder="e.g. HP:0010704, MP:0010805" handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required={!this.state.modelSystemsPOMSFT} customErrorMsg="Enter HPO ID(s) and/or free text" /> <Input type="textarea" ref="phenotypeFreetextObserved" label={<span>Phenotype(s) observed in model system <span className="normal">(free text)</span>:</span>} error={this.getFormError('phenotypeFreetextObserved')} clearError={this.clrFormErrors.bind(null, 'phenotypeFreetextObserved')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="2" value={MS_phenotypeFreetextObserved} handleChange={this.handleChange} placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" inputDisabled={this.cv.othersAssessed} required={!this.state.modelSystemsPOMSHPO} customErrorMsg="Enter HPO ID(s) and/or free text" /> <Input type="textarea" ref="model.phenotypeHPO" label={<LabelPatientPhenotype />} rows="1" error={this.getFormError('model.phenotypeHPO')} clearError={this.clrFormErrors.bind(null, 'model.phenotypeHPO')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" value={MS_phenotypeHPO} placeholder="e.g. HP:0010704" handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required={!this.state.modelSystemsPPFT} customErrorMsg="Enter HPO ID(s) and/or free text" /> <Input type="textarea" ref="model.phenotypeFreeText" label={<span>Human phenotype(s) <span className="normal">(free text)</span>:</span>} error={this.getFormError('model.phenotypeFreeText')} clearError={this.clrFormErrors.bind(null, 'model.phenotypeFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="2" value={MS_phenotypeFreeText} handleChange={this.handleChange} placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" inputDisabled={this.cv.othersAssessed} required={!this.state.modelSystemsPPHPO} customErrorMsg="Enter HPO ID(s) and/or free text" /> <Input type="textarea" ref="explanation" label="Explanation of how model system phenotype is similar to phenotype observed in humans:" error={this.getFormError('explanation')} clearError={this.clrFormErrors.bind(null, 'explanation')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={MS_explanation} inputDisabled={this.cv.othersAssessed} required /> <Input type="textarea" ref="evidenceInPaper" label="Information about where evidence can be found on paper" error={this.getFormError('evidenceInPaper')} clearError={this.clrFormErrors.bind(null, 'evidenceInPaper')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={MS_evidenceInPaper} inputDisabled={this.cv.othersAssessed} /> </div> ); } const LabelPhenotypeObserved = () => { return ( <span>Phenotype(s) observed in model system <span className="normal">(<a href={external_url_map['HPOBrowser']} target="_blank" title="Open HPO Browser in a new tab">HPO</a> or MP ID)</span>:</span> ); }; const LabelPatientPhenotype = () => { return ( <span>Human phenotype(s) <span className="normal">(<a href={external_url_map['HPOBrowser']} target="_blank" title="Open HPO Browser in a new tab">HPO</a> ID)</span>:</span> ); }; /** * Rescue type curation panel. * Call with .call(this) to run in the same context as the calling component. */ function TypeRescue() { let experimental = this.state.experimental ? this.state.experimental : {}; let rescue = experimental.rescue ? experimental.rescue : {}; let RES_rescueType, RES_cellCulture, RES_cellCultureFreeText, RES_patientCells, RES_patientCellsFreeText, RES_nonHumanModel, RES_humanModel, RES_descriptionOfGeneAlteration, RES_phenotypeHPO, RES_phenotypeFreeText, RES_rescueMethod, RES_explanation, RES_evidenceInPaper; if (rescue) { RES_rescueType = rescue.rescueType ? rescue.rescueType : 'none'; RES_cellCulture = rescue.cellCulture ? rescue.cellCulture : ''; RES_cellCultureFreeText = rescue.cellCultureFreeText ? rescue.cellCultureFreeText : ''; RES_patientCells = rescue.patientCells ? rescue.patientCells : ''; RES_patientCellsFreeText = rescue.patientCellsFreeText ? rescue.patientCellsFreeText : ''; RES_nonHumanModel = rescue.nonHumanModel ? rescue.nonHumanModel : 'none'; RES_humanModel = rescue.humanModel ? rescue.humanModel : ''; RES_descriptionOfGeneAlteration = rescue.descriptionOfGeneAlteration ? rescue.descriptionOfGeneAlteration : ''; RES_phenotypeHPO = rescue.phenotypeHPO ? rescue.phenotypeHPO : ''; RES_phenotypeFreeText = rescue.phenotypeFreeText ? rescue.phenotypeFreeText : ''; RES_rescueMethod = rescue.rescueMethod ? rescue.rescueMethod : ''; RES_explanation = rescue.explanation ? rescue.explanation : ''; RES_evidenceInPaper = rescue.evidenceInPaper ? rescue.evidenceInPaper : ''; } return ( <div className="row form-row-helper"> <Input type="select" ref="rescueType" label="Rescue observed in human, non-human model organism, cell culture model, or patient cells?:" error={this.getFormError('rescueType')} clearError={this.clrFormErrors.bind(null, 'rescueType')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" defaultValue="none" value={RES_rescueType} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="Human">Human</option> <option value="Non-human model organism">Non-human model organism</option> <option value="Cell culture model">Cell culture model</option> <option value="Patient cells">Patient cells</option> </Input> {this.state.rescueType === 'Human' ? <div> <Input type="text" ref="rescue.humanModel" label="Proband label:" value={RES_humanModel} handleChange={this.handleChange} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" /> </div> : null} {this.state.rescueType === 'Non-human model organism' ? <div> <Input type="select" ref="rescue.nonHumanModel" label="Non-human model organism:" error={this.getFormError('rescue.nonHumanModel')} clearError={this.clrFormErrors.bind(null, 'rescue.nonHumanModel')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" defaultValue="none" value={RES_nonHumanModel} handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required> <option value="none">No Selection</option> <option disabled="disabled"></option> <option value="Budding yeast (Saccharomyces cerevisiae) 4932">Budding yeast (Saccharomyces cerevisiae) 4932</option> <option value="Cat (Felis catus) 9685">Cat (Felis catus) 9685</option> <option value="Chicken (Gallus gallus) 9031">Chicken (Gallus gallus) 9031</option> <option value="Chimpanzee (Pan troglodytes) 9598">Chimpanzee (Pan troglodytes) 9598</option> <option value="Chlamydomonas (Chlamydomonas reinhardtii) 3055">Chlamydomonas (Chlamydomonas reinhardtii) 3055</option> <option value="Cow (Bos taurus) 9913">Cow (Bos taurus) 9913</option> <option value="Dog (Canis lupus familiaris) 9615">Dog (Canis lupus familiaris) 9615</option> <option value="Fission yeast (Schizosaccharomyces pombe) 4896">Fission yeast (Schizosaccharomyces pombe) 4896</option> <option value="Frog (Xenopus) 262014">Frog (Xenopus) 262014</option> <option value="Fruit fly (Drosophila) 7215">Fruit fly (Drosophila) 7215</option> <option value="Gerbil (Gerbillinae) 10045">Gerbil (Gerbillinae) 10045</option> <option value="Guinea pig (Cavia porcellus) 10141">Guinea pig (Cavia porcellus) 10141</option> <option value="Hamster (Cricetinae) 10026">Hamster (Cricetinae) 10026</option> <option value="Macaque (Macaca) 9539">Macaque (Macaca) 9539</option> <option value="Mouse (Mus musculus) 10090">Mouse (Mus musculus) 10090</option> <option value="Pig (Sus scrofa) 9823">Pig (Sus scrofa) 9823</option> <option value="Rabbit (Oryctolagus cuniculus) 9986">Rabbit (Oryctolagus cuniculus) 9986</option> <option value="Rat (Rattus norvegicus) 10116">Rat (Rattus norvegicus) 10116</option> <option value="Round worm (Caenorhabditis elegans) 6239">Round worm (Caenorhabditis elegans) 6239</option> <option value="Sheep (Ovis aries) 9940">Sheep (Ovis aries) 9940</option> <option value="Zebra finch (Taeniopygia guttata) 59729">Zebra finch (Taeniopygia guttata) 59729</option> <option value="Zebrafish (Danio rerio) 7955">Zebrafish (Danio rerio) 7955</option> </Input> </div> : null} {this.state.rescueType === 'Cell culture model' ? <div> {curator.renderWarning('CL_EFO')} <p className="col-sm-7 col-sm-offset-5"> Search the <a href={external_url_map['EFO']} target="_blank">EFO</a> or <a href={external_url_map['CL']} target="_blank">Cell Ontology (CL)</a> using the OLS. </p> <Input type="textarea" ref="rescue.cellCulture" label={<span>Cell culture model type/line <span className="normal">(EFO or CL ID)</span>:</span>} error={this.getFormError('rescue.cellCulture')} clearError={this.clrFormErrors.bind(null, 'rescue.cellCulture')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input no-resize" rows="1" value={RES_cellCulture} placeholder="e.g. EFO:0001187 or EFO_0001187; CL:0000057 or CL_0000057" inputDisabled={this.cv.othersAssessed} handleChange={this.handleChange} required={!this.state.rescueCC_FreeText} customErrorMsg="Enter EFO or CL ID, and/or free text" /> <Input type="textarea" ref="rescue.cellCultureFreeText" label={<span>Cell culture model type/line <span className="normal">(free text)</span>:</span>} error={this.getFormError('rescue.cellCultureFreeText')} clearError={this.clrFormErrors.bind(null, 'rescue.cellCultureFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" value={RES_cellCultureFreeText} inputDisabled={this.cv.othersAssessed} row="2" placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" handleChange={this.handleChange} required={!this.state.rescueCC_EfoId} customErrorMsg="Enter EFO or CL ID, and/or free text" /> </div> : null} {this.state.rescueType === 'Patient cells' ? <div> {curator.renderWarning('CL')} <p className="col-sm-7 col-sm-offset-5"> Search the <a href={external_url_map['CL']} target="_blank">Cell Ontology (CL)</a> using the OLS. </p> <Input type="textarea" ref="rescue.patientCells" label={<span>Patient cell type/line <span className="normal">(CL ID)</span>:</span>} error={this.getFormError('rescue.patientCells')} clearError={this.clrFormErrors.bind(null, 'rescue.patientCells')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input no-resize" rows="1" value={RES_patientCells} placeholder="e.g. CL:0000057 or CL_0000057" inputDisabled={this.cv.othersAssessed} handleChange={this.handleChange} required={!this.state.rescuePCells_FreeText} customErrorMsg="Enter CL ID and/or free text" /> <Input type="textarea" ref="rescue.patientCellsFreeText" label={<span>Patient cell type/line <span className="normal">(free text)</span>:</span>} error={this.getFormError('rescue.patientCellsFreeText')} clearError={this.clrFormErrors.bind(null, 'rescue.patientCellsFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" value={RES_patientCellsFreeText} inputDisabled={this.cv.othersAssessed} row="2" placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" handleChange={this.handleChange} required={!this.state.rescuePCells_ClId} customErrorMsg="Enter CL ID and/or free text" /> </div> : null} <Input type="textarea" ref="descriptionOfGeneAlteration" label="Description of gene alteration:" error={this.getFormError('descriptionOfGeneAlteration')} clearError={this.clrFormErrors.bind(null, 'descriptionOfGeneAlteration')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={RES_descriptionOfGeneAlteration} inputDisabled={this.cv.othersAssessed} required /> {curator.renderPhenotype(null, 'Experimental')} <Input type="textarea" ref="rescue.phenotypeHPO" label={<LabelPhenotypeRescue />} rows="1" error={this.getFormError('rescue.phenotypeHPO')} clearError={this.clrFormErrors.bind(null, 'rescue.phenotypeHPO')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" inputClassName="uppercase-input" value={RES_phenotypeHPO} placeholder="e.g. HP:0010704" handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} required={!this.state.rescuePRFT} customErrorMsg="Enter HPO ID(s) and/or free text" /> <Input type="textarea" ref="rescue.phenotypeFreeText" label={<span>Phenotype to rescue <span className="normal">(free text)</span>:</span>} error={this.getFormError('rescue.phenotypeFreeText')} clearError={this.clrFormErrors.bind(null, 'rescue.phenotypeFreeText')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="2" value={RES_phenotypeFreeText} handleChange={this.handleChange} placeholder="Use free text descriptions only after verifying no appropriate ontology term exists" inputDisabled={this.cv.othersAssessed} required={!this.state.rescuePRHPO} customErrorMsg="Enter HPO ID(s) and/or free text" /> <Input type="textarea" ref="rescueMethod" label="Description of method used to rescue:" error={this.getFormError('rescueMethod')} clearError={this.clrFormErrors.bind(null, 'rescueMethod')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={RES_rescueMethod} inputDisabled={this.cv.othersAssessed} required /> <Input type="checkbox" ref="wildTypeRescuePhenotype" label="Does the wild-type rescue the above phenotype?:" error={this.getFormError('wildTypeRescuePhenotype')} clearError={this.clrFormErrors.bind(null, 'wildTypeRescuePhenotype')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" checked={this.state.wildTypeRescuePhenotype} defaultChecked="false" handleChange={this.handleChange} inputDisabled={this.cv.othersAssessed} /> <p className="col-sm-7 col-sm-offset-5 hug-top alert alert-warning"><strong>Warning:</strong> not checking the above box indicates this criteria has not been met for this evidence; this should be taken into account during its evaluation.</p> {this.state.showPatientVariantRescue ? <Input type="checkbox" ref="patientVariantRescue" label="Does patient variant rescue?:" error={this.getFormError('patientVariantRescue')} clearError={this.clrFormErrors.bind(null, 'patientVariantRescue')} handleChange={this.handleChange} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" checked={this.state.patientVariantRescue} defaultChecked="false" inputDisabled={this.cv.othersAssessed} /> : null} <Input type="textarea" ref="explanation" label="Explanation of rescue of phenotype:" error={this.getFormError('explanation')} clearError={this.clrFormErrors.bind(null, 'explanation')} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" value={RES_explanation} inputDisabled={this.cv.othersAssessed} required={this.state.wildTypeRescuePhenotype} /> <Input type="textarea" ref="evidenceInPaper" label="Information about where evidence can be found on paper" labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" rows="5" inputDisabled={this.cv.othersAssessed} value={RES_evidenceInPaper} /> </div> ); } const LabelPhenotypeRescue = () => { return ( <span>Phenotype to rescue <span className="normal">(<a href={external_url_map['HPOBrowser']} target="_blank" title="Open HPO Browser in a new tab">HPO</a> ID)</span>:</span> ); }; /** * Display the Experimental Data variant panel. The number of copies depends on the variantCount state variable. */ function ExperimentalDataVariant() { let experimental = this.state.experimental; let variants = experimental && experimental.variants; return ( <div className="row"> {this.cv.othersAssessed ? <div> {variants.map(function(variant, i) { return ( <div key={i} className="variant-view-panel variant-view-panel-edit"> <h5>Variant {i + 1}</h5> <dl className="dl-horizontal"> {variant.clinvarVariantId ? <div> <dl className="dl-horizontal"> <dt>ClinVar VariationID</dt> <dd><a href={external_url_map['ClinVarSearch'] + variant.clinvarVariantId} title={"ClinVar entry for variant " + variant.clinvarVariantId + " in new tab"} target="_blank">{variant.clinvarVariantId}</a></dd> </dl> </div> : null } {renderVariantLabelAndTitle(variant)} {variant.otherDescription ? <div> <dl className="dl-horizontal"> <dt>Other description</dt> <dd>{variant.otherDescription}</dd> </dl> </div> : null } </dl> </div> ); })} </div> : <div> {!experimental || !variants || variants.length === 0 ? <div className="row"> <p className="col-sm-7 col-sm-offset-5">If your Experimental data is about one or more variants, please add these variant(s) below</p> </div> : null} {_.range(this.state.variantCount).map(i => { var variant; if (variants && variants.length) { variant = variants[i]; } return ( <div key={'variant' + i} className="variant-panel"> <div className="row"> <div className="col-sm-7 col-sm-offset-5"> <p className="alert alert-warning"> ClinVar VariationID should be provided in all instances it exists. This is the only way to associate probands from different studies with the same variant, and ensures the accurate counting of probands. </p> </div> </div> {this.state.variantInfo[i] ? <div> {this.state.variantInfo[i].clinvarVariantId ? <div className="row"> <span className="col-sm-5 control-label"><label>{<LabelClinVarVariant />}</label></span> <span className="col-sm-7 text-no-input"><a href={external_url_map['ClinVarSearch'] + this.state.variantInfo[i].clinvarVariantId} target="_blank">{this.state.variantInfo[i].clinvarVariantId}</a></span> </div> : null} {this.state.variantInfo[i].carId ? <div className="row"> <span className="col-sm-5 control-label"><label>{LabelCARVariant(this.state.variantRequired)}</label></span> <span className="col-sm-7 text-no-input"><a href={`https:${external_url_map['CARallele']}${this.state.variantInfo[i].carId}.html`} target="_blank">{this.state.variantInfo[i].carId}</a></span> </div> : null} {renderVariantLabelAndTitle(this.state.variantInfo[i], true)} </div> : null} <Input type="text" ref={'variantUuid' + i} value={variant && variant.uuid ? variant.uuid : ''} handleChange={this.handleChange} error={this.getFormError('variantUuid' + i)} clearError={this.clrFormErrors.bind(null, 'variantUuid' + i)} labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="hidden" /> <div className="row"> <div className="form-group"> <span className="col-sm-5 control-label">{!this.state.variantInfo[i] ? <label>Add Variant:{this.state.variantRequired ? ' *' : null}</label> : <label>Clear Variant Selection:</label>}</span> <span className="col-sm-7"> {!this.state.variantInfo[i] || (this.state.variantInfo[i] && this.state.variantInfo[i].clinvarVariantId) ? <AddResourceId resourceType="clinvar" parentObj={{'@type': ['variantList', 'Individual'], 'variantList': this.state.variantInfo}} buttonText="Add ClinVar ID" protocol={this.props.href_url.protocol} clearButtonRender={true} editButtonRenderHide={true} clearButtonClass="btn-inline-spacer" initialFormValue={this.state.variantInfo[i] && this.state.variantInfo[i].clinvarVariantId} fieldNum={String(i)} updateParentForm={this.updateVariantId} buttonOnly={true} /> : null} {!this.state.variantInfo[i] ? <span> - or - </span> : null} {!this.state.variantInfo[i] || (this.state.variantInfo[i] && !this.state.variantInfo[i].clinvarVariantId) ? <AddResourceId resourceType="car" parentObj={{'@type': ['variantList', 'Individual'], 'variantList': this.state.variantInfo}} buttonText="Add CA ID" protocol={this.props.href_url.protocol} clearButtonRender={true} editButtonRenderHide={true} clearButtonClass="btn-inline-spacer" initialFormValue={this.state.variantInfo[i] && this.state.variantInfo[i].carId} fieldNum={String(i)} updateParentForm={this.updateVariantId} buttonOnly={true} /> : null} </span> </div> </div> </div> ); })} {this.state.variantCount < MAX_VARIANTS ? <div> <Input type="button" ref="addvariant" inputClassName="btn-default btn-last pull-right" title={this.state.variantCount ? "Add another variant associated with Experimental data" : "Add variant associated with Experimental data"} clickHandler={this.handleAddVariant} inputDisabled={this.state.addVariantDisabled || this.cv.othersAssessed} /> </div> : null} </div> } </div> ); } const LabelClinVarVariant = () => { return <span><a href={external_url_map['ClinVar']} target="_blank" title="ClinVar home page at NCBI in a new tab">ClinVar</a> Variation ID:</span>; }; const LabelCARVariant = variantRequired => { return <span><strong><a href={external_url_map['CAR']} target="_blank" title="ClinGen Allele Registry in a new tab">ClinGen Allele Registry</a> ID:{variantRequired ? ' *' : null}</strong></span>; }; /** * Component to render view-only page of experimental data */ const ExperimentalViewer = createReactClass({ mixins: [FormMixin, RestMixin, AssessmentMixin, CuratorHistory], cv: { assessmentTracker: null, // Tracking object for a single assessment gdmUuid: '' // UUID of the GDM; passed in the query string }, getInitialState: function() { return { assessments: null, // Array of assessments for the experimental data updatedAssessment: '', // Updated assessment value userScoreObj: {}, // Logged-in user's score object submitBusy: false, // True while form is submitting experimentalEvidenceType: null, formError: false }; }, // Called by child function props to update user score obj handleUserScoreObj: function(newUserScoreObj) { this.setState({userScoreObj: newUserScoreObj}, () => { if (!newUserScoreObj.hasOwnProperty('score') || (newUserScoreObj.hasOwnProperty('score') && newUserScoreObj.score !== false && newUserScoreObj.scoreExplanation)) { this.setState({formError: false}); } }); }, // Redirect to Curation-Central page handlePageRedirect: function() { let tempGdmPmid = curator.findGdmPmidFromObj(this.props.context); let tempGdm = tempGdmPmid[0]; let tempPmid = tempGdmPmid[1]; window.location.href = '/curation-central/?gdm=' + tempGdm.uuid + '&pmid=' + tempPmid; }, // Handle the score submit button scoreSubmit: function(e) { let experimental = this.props.context; /*****************************************************/ /* Experimental score status data object */ /*****************************************************/ let newUserScoreObj = Object.keys(this.state.userScoreObj).length ? this.state.userScoreObj : {}; if (Object.keys(newUserScoreObj).length) { if(newUserScoreObj.hasOwnProperty('score') && newUserScoreObj.score !== false && !newUserScoreObj.scoreExplanation) { this.setState({formError: true}); return false; } this.setState({submitBusy: true}); /***********************************************************/ /* Either update or create the user score object in the DB */ /***********************************************************/ if (newUserScoreObj.scoreStatus) { // Update and create score object when the score object has the scoreStatus key/value pair if (this.state.userScoreObj.uuid) { return this.putRestData('/evidencescore/' + this.state.userScoreObj.uuid, newUserScoreObj).then(modifiedScoreObj => { this.setState({submitBusy: false}); return Promise.resolve(modifiedScoreObj['@graph'][0]['@id']); }).then(data => { this.handlePageRedirect(); }); } else { return this.postRestData('/evidencescore/', newUserScoreObj).then(newScoreObject => { let newScoreObjectUuid = null; if (newScoreObject) { newScoreObjectUuid = newScoreObject['@graph'][0]['@id']; } return Promise.resolve(newScoreObjectUuid); }).then(newScoreObjectUuid => { return this.getRestData('/experimental/' + experimental.uuid, null, true).then(freshExperimental => { // flatten both context and fresh experimental let newExperimental = curator.flatten(experimental); let freshFlatExperimental = curator.flatten(freshExperimental); // take only the scores from the fresh experimental to not overwrite changes // in newExperimental newExperimental.scores = freshFlatExperimental.scores ? freshFlatExperimental.scores : []; // push new score uuid to newExperimental's scores list newExperimental.scores.push(newScoreObjectUuid); return this.putRestData('/experimental/' + experimental.uuid, newExperimental).then(updatedExperimentalObj => { this.setState({submitBusy: false}); return Promise.resolve(updatedExperimentalObj['@graph'][0]); }); }); }).then(data => { this.handlePageRedirect(); }); } } else if (!newUserScoreObj.scoreStatus) { // If an existing score object has no scoreStatus key/value pair, the user likely removed score // Then delete the score entry from the score list associated with the evidence if (this.state.userScoreObj.uuid) { newUserScoreObj['status'] = 'deleted'; return this.putRestData('/evidencescore/' + this.state.userScoreObj.uuid, newUserScoreObj).then(modifiedScoreObj => { let modifiedScoreObjectUuid = null; if (modifiedScoreObj) { modifiedScoreObjectUuid = modifiedScoreObj['@graph'][0]['@id']; } return Promise.resolve(modifiedScoreObjectUuid); }).then(modifiedScoreObjectUuid => { return this.getRestData('/experimental/' + experimental.uuid, null, true).then(freshExperimental => { // flatten both context and fresh experimental let newExperimental = curator.flatten(experimental); let freshFlatExperimental = curator.flatten(freshExperimental); // take only the scores from the fresh experimental to not overwrite changes // in newExperimental newExperimental.scores = freshFlatExperimental.scores ? freshFlatExperimental.scores : []; // push new score uuid to newIndividual's scores list if (newExperimental.scores.length) { newExperimental.scores.forEach(score => { if (score === modifiedScoreObjectUuid) { let index = newExperimental.scores.indexOf(score); newExperimental.scores.splice(index, 1); } }); } return this.putRestData('/experimental/' + experimental.uuid, newExperimental).then(updatedExperimentalObj => { this.setState({submitBusy: false}); return Promise.resolve(updatedExperimentalObj['@graph'][0]); }); }); }).then(data => { this.handlePageRedirect(); }); } } } }, componentWillMount: function() { var experimental = this.props.context; // Get the GDM and Family UUIDs from the query string this.cv.gdmUuid = queryKeyValue('gdm', this.props.href); if (experimental && experimental.assessments && experimental.assessments.length) { this.setState({assessments: experimental.assessments}); } if (typeof this.props.session.user_properties !== undefined) { var user = this.props.session && this.props.session.user_properties; this.loadAssessmentTracker(user); } if (experimental.evidenceType === 'Protein Interactions') { this.setState({experimentalEvidenceType: null}); } else if (experimental.evidenceType === 'Biochemical Function') { if (experimental.biochemicalFunction.geneWithSameFunctionSameDisease && Object.keys(experimental.biochemicalFunction.geneWithSameFunctionSameDisease).length) { this.setState({experimentalEvidenceType: 'A. Gene(s) with same function implicated in same disease'}); } else { this.setState({experimentalEvidenceType: 'B. Gene function consistent with phenotype(s)'}); } this.setState({experimentalEvidenceType: experimental.biochemicalFunction.functionalAlterationType}); } else if (experimental.evidenceType === 'Expression') { if (experimental.expression.normalExpression && Object.keys(experimental.expression.normalExpression).length) { this.setState({experimentalEvidenceType: 'A. Gene normally expressed in tissue relevant to the disease'}); } else { this.setState({experimentalEvidenceType: 'B. Altered expression in Patients'}); } } else if (experimental.evidenceType === 'Functional Alteration') { this.setState({experimentalEvidenceType: experimental.functionalAlteration.functionalAlterationType}); } else if (experimental.evidenceType === 'Model Systems') { this.setState({experimentalEvidenceType: experimental.modelSystems.modelSystemsType}); } else if (experimental.evidenceType === 'Rescue') { this.setState({experimentalEvidenceType: experimental.rescue.rescueType}); } }, componentWillReceiveProps: function(nextProps) { if (typeof nextProps.session.user_properties !== undefined && nextProps.session.user_properties != this.props.session.user_properties) { var user = nextProps.session && nextProps.session.user_properties; this.loadAssessmentTracker(user); } }, loadAssessmentTracker: function(user) { var experimental = this.props.context; var assessments = this.state.assessments ? this.state.assessments : (experimental.assessments ? experimental.assessments : null); // Make an assessment tracker object once we get the logged in user info if (!this.cv.assessmentTracker && user) { var userAssessment; // Find if any assessments for the segregation are owned by the currently logged-in user if (assessments && assessments.length) { // Find the assessment belonging to the logged-in curator, if any. userAssessment = Assessments.userAssessment(assessments, user && user.uuid); } this.cv.assessmentTracker = new AssessmentTracker(userAssessment, user, experimental.evidenceType); } }, handleSearchLinkById(id) { let searchURL; if (id.indexOf('EFO') > -1) { searchURL = external_url_map['EFOSearch']; } else if (id.indexOf('CL') > -1) { searchURL = external_url_map['CLSearch']; } return searchURL; }, render: function() { var experimental = this.props.context; /****************************************/ /* Retain pre-existing assessments data */ /****************************************/ var assessments = this.state.assessments ? this.state.assessments : (experimental.assessments ? experimental.assessments : null); var validAssessments = []; _.map(assessments, assessment => { if (assessment.value !== 'Not Assessed') { validAssessments.push(assessment); } }); var user = this.props.session && this.props.session.user_properties; var userExperimental = user && experimental && experimental.submitted_by && user.uuid === experimental.submitted_by.uuid ? true : false; let affiliation = this.props.affiliation; let affiliatedExperimental = affiliation && Object.keys(affiliation).length && experimental && experimental.affiliation && affiliation.affiliation_id === experimental.affiliation ? true : false; var experimentalUserAssessed = false; // TRUE if logged-in user doesn't own the experimental data, but the experimental data's owner assessed it var othersAssessed = false; // TRUE if we own this experimental data, and others have assessed it var updateMsg = this.state.updatedAssessment ? 'Assessment updated to ' + this.state.updatedAssessment : ''; // See if others have assessed if (userExperimental) { othersAssessed = Assessments.othersAssessed(assessments, user.uuid); } // Note if we don't own the experimental data, but the owner has assessed it if (user && experimental && experimental.submitted_by) { var experimentalUserAssessment = Assessments.userAssessment(assessments, experimental.submitted_by.uuid); if (experimentalUserAssessment && experimentalUserAssessment.value !== Assessments.DEFAULT_VALUE) { experimentalUserAssessed = true; } } var tempGdmPmid = curator.findGdmPmidFromObj(experimental); var tempGdm = tempGdmPmid[0]; var tempPmid = tempGdmPmid[1]; let evidenceScores = experimental && experimental.scores && experimental.scores.length ? experimental.scores : []; let isEvidenceScored = false; if (evidenceScores.length) { evidenceScores.map(scoreObj => { if (scoreObj.scoreStatus && scoreObj.scoreStatus.match(/Score|Review|Contradicts/ig)) { isEvidenceScored = true; } }); } let experimentalEvidenceType = this.state.experimentalEvidenceType; let modelSystems_phenotypeHPOObserved = experimental.modelSystems.phenotypeHPOObserved ? experimental.modelSystems.phenotypeHPOObserved.split(', ') : []; let modelSystems_phenotypeHPO = experimental.modelSystems.phenotypeHPO ? experimental.modelSystems.phenotypeHPO.split(', ') : []; let rescue_phenotypeHPO = experimental.rescue.phenotypeHPO ? experimental.rescue.phenotypeHPO.split(', ') : []; return ( <div> <ViewRecordHeader gdm={tempGdm} pmid={tempPmid} /> <div className="container"> <div className="row curation-content-viewer"> <div className="viewer-titles"> <h1>View Experimental Data {experimental.label}</h1> <h2> {tempGdm ? <a href={'/curation-central/?gdm=' + tempGdm.uuid + (tempGdm ? '&pmid=' + tempPmid : '')}><i className="icon icon-briefcase"></i></a> : null} <span> &#x2F;&#x2F; Experimental Data {experimental.label} ({experimental.evidenceType})</span> </h2> </div> {experimental.evidenceType === 'Biochemical Function' ? <Panel title="Biochemical Function" panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>Identified function of gene in this record</dt> <dd>{experimental.biochemicalFunction.identifiedFunction ? <a href={external_url_map['GOSearch'] + experimental.biochemicalFunction.identifiedFunction.replace(':', '_')} title={"GO entry for " + experimental.biochemicalFunction.identifiedFunction + " in new tab"} target="_blank">{experimental.biochemicalFunction.identifiedFunction}</a> : null}</dd> </div> <div> <dt>Identified function of gene in this record (free text)</dt> <dd>{experimental.biochemicalFunction.identifiedFunctionFreeText ? experimental.biochemicalFunction.identifiedFunctionFreeText : null}</dd> </div> <div> <dt>Evidence for above function</dt> <dd>{experimental.biochemicalFunction.evidenceForFunction}</dd> </div> <div> <dt>Notes on where evidence found in paper</dt> <dd>{experimental.biochemicalFunction.evidenceForFunctionInPaper}</dd> </div> </dl> </Panel> : null} {experimental.evidenceType === 'Biochemical Function' && experimental.biochemicalFunction.geneWithSameFunctionSameDisease.evidenceForOtherGenesWithSameFunction && experimental.biochemicalFunction.geneWithSameFunctionSameDisease.evidenceForOtherGenesWithSameFunction !== '' ? <Panel title="A. Gene(s) with same function implicated in same disease" panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>Other gene(s) with same function as gene in record</dt> <dd>{experimental.biochemicalFunction.geneWithSameFunctionSameDisease.genes && experimental.biochemicalFunction.geneWithSameFunctionSameDisease.genes.map(function(gene, i) { return <span key={gene.symbol}>{i > 0 ? ', ' : ''}<a href={external_url_map['HGNC'] + gene.hgncId} title={"HGNC entry for " + gene.symbol + " in new tab"} target="_blank">{gene.symbol}</a></span>; })}</dd> </div> <div> <dt>Evidence that above gene(s) share same function with gene in record</dt> <dd>{experimental.biochemicalFunction.geneWithSameFunctionSameDisease.evidenceForOtherGenesWithSameFunction}</dd> </div> <div> <dt>This gene or genes have been implicated in the above disease</dt> <dd>{experimental.biochemicalFunction.geneWithSameFunctionSameDisease.geneImplicatedWithDisease ? 'Yes' : 'No'}</dd> </div> <div> <dt>How has this other gene(s) been implicated in the above disease?</dt> <dd>{experimental.biochemicalFunction.geneWithSameFunctionSameDisease.explanationOfOtherGenes}</dd> </div> <div> <dt>Additional comments</dt> <dd>{experimental.biochemicalFunction.geneWithSameFunctionSameDisease.evidenceInPaper}</dd> </div> </dl> </Panel> : null} {experimental.evidenceType === 'Biochemical Function' && ((experimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeHPO && experimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeHPO.join(', ') !== '') || (experimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeFreeText && experimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeFreeText !== '')) ? <Panel title="B. Gene function consistent with phenotype" panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>HPO ID(s)</dt> <dd>{experimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeHPO && experimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeHPO.map(function(hpo, i) { return <span key={hpo}>{i > 0 ? ', ' : ''}<a href={external_url_map['HPO'] + hpo} title={"HPOBrowser entry for " + hpo + " in new tab"} target="_blank">{hpo}</a></span>; })}</dd> </div> <div> <dt>Phenotype</dt> <dd>{experimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.phenotypeFreeText}</dd> </div> <div> <dt>Explanation of how phenotype is consistent with disease</dt> <dd>{experimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.explanation}</dd> </div> <div> <dt>Notes on where evidence found in paper</dt> <dd>{experimental.biochemicalFunction.geneFunctionConsistentWithPhenotype.evidenceInPaper}</dd> </div> </dl> </Panel> : null} {experimental.evidenceType === 'Protein Interactions' ? <Panel title="Protein Interactions" panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>Interacting Gene(s)</dt> <dd>{experimental.proteinInteractions.interactingGenes && experimental.proteinInteractions.interactingGenes.map(function(gene, i) { return <span key={gene.symbol + '-' + i}>{i > 0 ? ', ' : ''}<a href={external_url_map['HGNC'] + gene.hgncId} title={"HGNC entry for " + gene.symbol + " in new tab"} target="_blank">{gene.symbol}</a></span>; })}</dd> </div> <div> <dt>Interaction Type</dt> <dd>{experimental.proteinInteractions.interactionType}</dd> </div> <div> <dt>Method by which interaction detected</dt> <dd>{experimental.proteinInteractions.experimentalInteractionDetection}</dd> </div> <div> <dt>This gene or genes have been implicated in the above disease</dt> <dd>{experimental.proteinInteractions.geneImplicatedInDisease ? 'Yes' : 'No'}</dd> </div> <div> <dt>Explanation of relationship of other gene(s) to the disease</dt> <dd>{experimental.proteinInteractions.relationshipOfOtherGenesToDisese}</dd> </div> <div> <dt>Information about where evidence can be found on paper</dt> <dd>{experimental.proteinInteractions.evidenceInPaper}</dd> </div> </dl> </Panel> : null} {experimental.evidenceType === 'Expression' ? <Panel title="Expression" panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>Organ or tissue relevant to disease (Uberon ID)</dt> <dd>{experimental.expression.organOfTissue && experimental.expression.organOfTissue.map((uberonId, i) => { if (uberonId.indexOf('UBERON') > -1) { return <span key={uberonId}>{i > 0 ? ', ' : ''}<a href={external_url_map['UberonSearch'] + uberonId.replace(':', '_')} title={"Uberon entry for " + uberonId + " in new tab"} target="_blank">{uberonId}</a></span>; } else { return <span key={uberonId}>{i > 0 ? ', ' : ''}{uberonId}</span> } })}</dd> </div> <div> <dt>Organ or tissue relevant to disease (free text)</dt> <dd>{experimental.expression.organOfTissueFreeText ? experimental.expression.organOfTissueFreeText : null}</dd> </div> </dl> </Panel> : null} {experimental.evidenceType === 'Expression' && experimental.expression.normalExpression.expressedInTissue && experimental.expression.normalExpression.expressedInTissue == true ? <Panel title="A. Gene normally expressed in tissue relevant to the disease" panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>The gene is normally expressed in the above tissue</dt> <dd>{experimental.expression.normalExpression.expressedInTissue ? 'Yes' : 'No'}</dd> </div> <div> <dt>Evidence for normal expression in disease tissue</dt> <dd>{experimental.expression.normalExpression.evidence}</dd> </div> <div> <dt>Notes on where evidence found in paper</dt> <dd>{experimental.expression.normalExpression.evidenceInPaper}</dd> </div> </dl> </Panel> : null} {experimental.evidenceType === 'Expression' && experimental.expression.alteredExpression.expressedInPatients && experimental.expression.alteredExpression.expressedInPatients == true ? <Panel title="B. Altered expression in patients" panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>Expression is altered in patients who have the disease</dt> <dd>{experimental.expression.alteredExpression.expressedInPatients ? 'Yes' : 'No'}</dd> </div> <div> <dt>Evidence for altered expression in patients</dt> <dd>{experimental.expression.alteredExpression.evidence}</dd> </div> <div> <dt>Notes on where evidence found in paper</dt> <dd>{experimental.expression.alteredExpression.evidenceInPaper}</dd> </div> </dl> </Panel> : null} {experimental.evidenceType === 'Functional Alteration' ? <Panel title="Functional Alteration" panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>Cultured patient or non-patient cells carrying candidate variants?</dt> <dd>{experimental.functionalAlteration.functionalAlterationType}</dd> </div> {experimental.functionalAlteration.functionalAlterationType === 'Patient cells' ? <div> <dt>Patient cell type</dt> <dd>{experimental.functionalAlteration.patientCells ? <a href={external_url_map['CLSearch'] + experimental.functionalAlteration.patientCells.replace(':', '_')} title={"CL entry for " + experimental.functionalAlteration.patientCells + " in new tab"} target="_blank">{experimental.functionalAlteration.patientCells}</a> : null}</dd> </div> : <div> <dt>Non-patient cell type</dt> <dd>{experimental.functionalAlteration.nonPatientCells ? <a href={this.handleSearchLinkById(experimental.functionalAlteration.nonPatientCells) + experimental.functionalAlteration.nonPatientCells.replace(':', '_')} title={"EFO entry for " + experimental.functionalAlteration.nonPatientCells + " in new tab"} target="_blank">{experimental.functionalAlteration.nonPatientCells}</a> : null}</dd> </div> } {experimental.functionalAlteration.functionalAlterationType === 'Patient cells' ? <div> <dt>Patient cell type (free text)</dt> <dd>{experimental.functionalAlteration.patientCellsFreeText ? experimental.functionalAlteration.patientCellsFreeText : null}</dd> </div> : <div> <dt>Non-patient cell type (free text)</dt> <dd>{experimental.functionalAlteration.nonPatientCellsFreeText ? experimental.functionalAlteration.nonPatientCellsFreeText : null}</dd> </div> } <div> <dt>Description of gene alteration</dt> <dd>{experimental.functionalAlteration.descriptionOfGeneAlteration}</dd> </div> <div> <dt>Normal function of gene</dt> <dd>{experimental.functionalAlteration.normalFunctionOfGene ? <a href={external_url_map['GOSearch'] + experimental.functionalAlteration.normalFunctionOfGene.replace(':', '_')} title={"GO entry for " + experimental.functionalAlteration.normalFunctionOfGene + " in new tab"} target="_blank">{experimental.functionalAlteration.normalFunctionOfGene}</a> : null}</dd> </div> <div> <dt>Normal function of gene (free text)</dt> <dd>{experimental.functionalAlteration.normalFunctionOfGeneFreeText ? experimental.functionalAlteration.normalFunctionOfGeneFreeText: null}</dd> </div> <div> <dt>Evidence for altered function</dt> <dd>{experimental.functionalAlteration.evidenceForNormalFunction}</dd> </div> <div> <dt>Notes on where evidence found in paper</dt> <dd>{experimental.functionalAlteration.evidenceInPaper}</dd> </div> </dl> </Panel> : null} {experimental.evidenceType === 'Model Systems' ? <Panel title="Model Systems" panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>Non-human model organism or cell culture model?</dt> <dd>{experimental.modelSystems.modelSystemsType}</dd> </div> {experimental.modelSystems.modelSystemsType === 'Non-human model organism' ? <div> <dt>Non-human model organism type</dt> <dd>{experimental.modelSystems.nonHumanModel}</dd> </div> : <div> <dt>Cell culture model type</dt> <dd>{experimental.modelSystems.cellCulture ? <a href={this.handleSearchLinkById(experimental.modelSystems.cellCulture) + experimental.modelSystems.cellCulture.replace(':', '_')} title={"EFO entry for " + experimental.modelSystems.cellCulture + " in new tab"} target="_blank">{experimental.modelSystems.cellCulture}</a> : null}</dd> </div> } {experimental.modelSystems.modelSystemsType === 'Cell culture model' ? <div> <dt>Cell culture type (free text)</dt> <dd>{experimental.modelSystems.cellCultureFreeText ? experimental.modelSystems.cellCultureFreeText : null}</dd> </div> : null} <div> <dt>Description of gene alteration</dt> <dd>{experimental.modelSystems.descriptionOfGeneAlteration}</dd> </div> <div> <dt>Phenotype(s) observed in model system (HPO or MP)</dt> <dd>{modelSystems_phenotypeHPOObserved && modelSystems_phenotypeHPOObserved.map((hpo, i) => { if (hpo.indexOf('HP') > -1) { return <span key={hpo}>{i > 0 ? ', ' : ''}<a href={external_url_map['HPO'] + hpo} title={"HPO Browser entry for " + hpo + " in new tab"} target="_blank">{hpo}</a></span>; } else { return <span key={hpo}>{i > 0 ? ', ' : ''}{hpo}</span> } })}</dd> </div> <div> <dt>Phenotype(s) observed in model system (free text)</dt> <dd>{experimental.modelSystems.phenotypeFreetextObserved}</dd> </div> <div> <dt>Human phenotype(s) (HPO)</dt> <dd>{modelSystems_phenotypeHPO && modelSystems_phenotypeHPO.map((hpo, i) => { return <span key={hpo}>{i > 0 ? ', ' : ''}<a href={external_url_map['HPO'] + hpo} title={"HPO Browser entry for " + hpo + " in new tab"} target="_blank">{hpo}</a></span>; })}</dd> </div> <div> <dt>Human phenotype(s) (free text)</dt> <dd>{experimental.modelSystems.phenotypeFreeText}</dd> </div> <div> <dt>Explanation of how model system phenotype is similar to phenotype observed in humans</dt> <dd>{experimental.modelSystems.explanation}</dd> </div> <div> <dt>Information about where evidence can be found on paper</dt> <dd>{experimental.modelSystems.evidenceInPaper}</dd> </div> </dl> </Panel> : null} {experimental.evidenceType == 'Rescue' ? <Panel title="Rescue" panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>Rescue observed in the following</dt> <dd>{experimental.rescue.rescueType}</dd> </div> {experimental.rescue.rescueType === 'Patient cells' ? <div className="rescue-observed-group"> <div> <dt>Patient cell type</dt> <dd>{experimental.rescue.patientCells ? <a href={external_url_map['CLSearch'] + experimental.rescue.patientCells.replace(':', '_')} title={"CL entry for " + experimental.rescue.patientCells + " in new tab"} target="_blank">{experimental.rescue.patientCells}</a> : null}</dd> </div> <div> <dt>Patient cell type (free text)</dt> <dd>{experimental.rescue.patientCellsFreeText ? experimental.rescue.patientCellsFreeText : null}</dd> </div> </div> : null} {experimental.rescue.rescueType === 'Cell culture model' ? <div className="rescue-observed-group"> <div> <dt>Cell culture model</dt> <dd>{experimental.rescue.cellCulture ? <a href={this.handleSearchLinkById(experimental.rescue.cellCulture) + experimental.rescue.cellCulture.replace(':', '_')} title={"EFO entry for " + experimental.rescue.cellCulture + " in new tab"} target="_blank">{experimental.rescue.cellCulture}</a> : null}</dd> </div> <div> <dt>Cell culture model (free text)</dt> <dd>{experimental.rescue.cellCultureFreeText ? experimental.rescue.cellCultureFreeText : null}</dd> </div> </div> : null} {experimental.rescue.rescueType === 'Non-human model organism' ? <div> <dt>Non-human model organism</dt> <dd>{experimental.rescue.nonHumanModel}</dd> </div> : null} {experimental.rescue.rescueType === 'Human' ? <div> <dt>Human</dt> <dd>{experimental.rescue.humanModel ? experimental.rescue.humanModel : null}</dd> </div> : null} <div> <dt>Description of gene alteration</dt> <dd>{experimental.rescue.descriptionOfGeneAlteration}</dd> </div> <div> <dt>Phenotype to rescue</dt> <dd>{rescue_phenotypeHPO && rescue_phenotypeHPO.map((hpo, i) => { return <span key={hpo}>{i > 0 ? ', ' : ''}<a href={external_url_map['HPO'] + hpo} title={"HPO Browser entry for " + hpo + " in new tab"} target="_blank">{hpo}</a></span>; })}</dd> </div> <div> <dt>Phenotype to rescue</dt> <dd>{experimental.rescue.phenotypeFreeText}</dd> </div> <div> <dt>Method used to rescue</dt> <dd>{experimental.rescue.rescueMethod}</dd> </div> <div> <dt>The wild-type rescues the above phenotype</dt> <dd>{experimental.rescue.wildTypeRescuePhenotype ? 'Yes' : 'No'}</dd> </div> {experimental.rescue.hasOwnProperty('patientVariantRescue') ? <div> <dt>The patient variant rescues</dt> <dd>{experimental.rescue.patientVariantRescue ? 'Yes' : 'No'}</dd> </div> : null} <div> <dt>Explanation of rescue of phenotype</dt> <dd>{experimental.rescue.explanation}</dd> </div> <div> <dt>Information about where evidence can be found on paper</dt> <dd>{experimental.rescue.evidenceInPaper}</dd> </div> </dl> </Panel> : null} {experimental.variants && experimental.variants.length > 0 ? <Panel title="Associated Variants" panelClassName="panel-data"> {experimental.variants.map(function(variant, i) { return ( <div key={'variant' + i} className="variant-view-panel"> <h5>Variant {i + 1}</h5> {variant.clinvarVariantId ? <div> <dl className="dl-horizontal"> <dt>ClinVar VariationID</dt> <dd><a href={`${external_url_map['ClinVarSearch']}${variant.clinvarVariantId}`} title={`ClinVar entry for variant ${variant.clinvarVariantId} in new tab`} target="_blank">{variant.clinvarVariantId}</a></dd> </dl> </div> : null } {variant.carId ? <div> <dl className="dl-horizontal"> <dt>ClinGen Allele Registry ID</dt> <dd><a href={`http:${external_url_map['CARallele']}${variant.carId}.html`} title={`ClinGen Allele Registry entry for ${variant.carId} in new tab`} target="_blank">{variant.carId}</a></dd> </dl> </div> : null } {renderVariantLabelAndTitle(variant)} {variant.otherDescription ? <div> <dl className="dl-horizontal"> <dt>Other description</dt> <dd>{variant.otherDescription}</dd> </dl> </div> : null } </div> ); })} </Panel> : null} {/* Retain pre-existing assessments data in display */} {validAssessments.length ? <Panel panelClassName="panel-data"> <dl className="dl-horizontal"> <div> <dt>Assessments</dt> <dd> <div> {validAssessments.map(function(assessment, i) { return ( <span key={assessment.uuid}> {i > 0 ? <br /> : null} {assessment.value + ' (' + assessment.submitted_by.title + ')'} </span> ); })} </div> </dd> </div> </dl> </Panel> : null} <Panel title="Experimental Data - Other Curator Scores" panelClassName="panel-data"> <ScoreViewer evidence={experimental} otherScores={true} session={this.props.session} affiliation={affiliation} /> </Panel> <Panel title="Experimental Data Score" panelClassName="experimental-evidence-score-viewer" open> {isEvidenceScored || (!isEvidenceScored && affiliation && affiliatedExperimental) || (!isEvidenceScored && !affiliation && userExperimental) ? <ScoreExperimental evidence={experimental} experimentalType={experimental.evidenceType} experimentalEvidenceType={experimentalEvidenceType} evidenceType="Experimental" session={this.props.session} handleUserScoreObj={this.handleUserScoreObj} scoreSubmit={this.scoreSubmit} formError={this.state.formError} affiliation={affiliation} /> : null} {!isEvidenceScored && ((affiliation && !affiliatedExperimental) || (!affiliation && !userExperimental)) ? <div className="row"> <p className="alert alert-warning creator-score-status-note">The creator of this evidence has not yet scored it; once the creator has scored it, the option to score will appear here.</p> </div> : null} </Panel> </div> </div> </div> ); } }); content_views.register(ExperimentalViewer, 'experimental'); /** * Display a history item for adding experimental data */ class ExperimentalAddHistory extends Component { render() { var history = this.props.history; var experimental = history.primary; var gdm = history.meta.experimental.gdm; var article = history.meta.experimental.article; return ( <div> Experimental data <a href={experimental['@id']}>{experimental.label}</a> <span> ({experimental.evidenceType}) added to </span> <strong>{gdm.gene.symbol}-{gdm.disease.term}-</strong> <i>{gdm.modeInheritance.indexOf('(') > -1 ? gdm.modeInheritance.substring(0, gdm.modeInheritance.indexOf('(') - 1) : gdm.modeInheritance}</i> <span> for <a href={'/curation-central/?gdm=' + gdm.uuid + '&pmid=' + article.pmid}>PMID:{article.pmid}</a></span> <span>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span> </div> ); } } history_views.register(ExperimentalAddHistory, 'experimental', 'add'); /** * Display a history item for modifying experimental data */ class ExperimentModifyHistory extends Component { render() { var history = this.props.history; var experimental = history.primary; return ( <div> Experimental data <a href={experimental['@id']}>{experimental.label}</a> <span> ({experimental.evidenceType}) modified</span> <span>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span> </div> ); } } history_views.register(ExperimentModifyHistory, 'experimental', 'modify'); /** * Display a history item for deleting experimental data */ class ExperimentDeleteHistory extends Component { render() { var history = this.props.history; var experimental = history.primary; return ( <div> <span>Experimental data {experimental.label} deleted</span> <span>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span> </div> ); } } history_views.register(ExperimentDeleteHistory, 'experimental', 'delete');
client/auth/Forgot.js
bryanph/Geist
import React from 'react' import fetchJSON from './utils/fetch' import { withRouter } from 'react-router-dom' import { Link } from 'react-router-dom' import { RenderErrors, ValidationErrors } from './Error' import getHeaders from './headers' import { FlatButton } from '../app/components/button' import { InputEmail, ValidateInput } from '../app/components/input' class Forgot extends React.Component { constructor(props) { super(props) this.state = { errors: [], validationErrors: {}, } this.handleResponse = this.handleResponse.bind(this) this.handleError = this.handleError.bind(this) } handleResponse(json, response) { if (Object.keys(json.errfor).length) { return this.setState({validationErrors: json.errfor}) } if (json.errors.length) { return this.setState({errors: json.errors}) } this.props.history.push({ pathname: '/auth/login/forgot/success', search: this.props.location.search }) } handleError(error) { console.error(error) } render() { const { errors, validationErrors, } = this.state return ( <div> <div className="panel"> <span className="panel-title">Reset your password</span> <span className="panel-authText">Enter your email address to receive a reset link</span> <ForgotForm handleError={this.handleError} handleResponse={this.handleResponse} /> </div> <div className="panel bottom-panel"> <Link to='/auth/login'>Back to login</Link> </div> { validationErrors ? <ValidationErrors errors={this.state.validationErrors} /> : null } { errors ? <RenderErrors errors={this.state.errors} /> : null } </div> ) } } export default withRouter(Forgot) class ForgotForm extends React.Component { constructor(props) { super(props) this.state = { email: '', errors: {}, } this.handleSubmit = this.handleSubmit.bind(this); this.validate = this.validate.bind(this); } handleSubmit(e) { e.preventDefault() const errors = this.validate(this.state.email) if (Object.keys(errors).length > 0) { return this.setState({ errors }) } fetchJSON('/auth/login/forgot', { method: 'POST', headers: getHeaders(), body: JSON.stringify({ email: this.state.email, }) }) .then(this.props.handleResponse) .catch(this.props.handleError) } validate(email) { const errors = {} if (!email) { errors.email = "Required" } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email)) { errors.email = "Invalid email address" } return errors } render() { return ( <form className="forgotForm"> <ValidateInput error={this.state.errors.email}> <InputEmail name="email" placeholder="email" onChange={e => this.setState({ email: e.target.value })} value={this.state.email} /> </ValidateInput> <FlatButton onClick={this.handleSubmit} style={{marginTop: '10px'}} >Reset password</FlatButton> </form> ) } } export const ForgotPassword = (props) => ( <Link to='/auth/login/forgot'>Forgot your password?</Link> ) export const ForgotSuccess = (props) => ( <div className="interact panel with-logo"> <div className="logo"></div> <h3>Reset your password</h3> <p>An email has been sent to your email address with instructions to reset your account</p> <Link to='/auth/login'>Back to login</Link> </div> ) export const ForgotError = (props) => ( <div className="interact panel with-logo"> <div className="logo"></div> <h3>Error</h3> <p>Something went wrong, please try again.</p> <Link to='/auth/login'>Back to login</Link> </div> )
app/containers/DashboardPage.js
ClearwaterClinical/cwc-react-redux-starter
import React from 'react' import { connect } from 'react-redux' import { t } from '../i18n' import { Panel } from 'react-bootstrap' class DashboardPage extends React.Component { componentDidMount () { document.title = `${t('navigation.dashboard')} | ${t('_brand-styled')}` } render () { const { user } = this.props return ( <Panel header={<h3>{t('title.welcome')} {user.username}</h3>}> {t('welcome-message')} </Panel> ) } } function mapStateToProps (state) { return { user: state.user } } function mapDispatchToProps (dispatch) { return {} } export default connect(mapStateToProps, mapDispatchToProps)(DashboardPage)
src/svg-icons/navigation/more-vert.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationMoreVert = (props) => ( <SvgIcon {...props}> <path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); NavigationMoreVert = pure(NavigationMoreVert); NavigationMoreVert.displayName = 'NavigationMoreVert'; NavigationMoreVert.muiName = 'SvgIcon'; export default NavigationMoreVert;
docs/app/Examples/elements/Step/Groups/StepExampleVertical.js
mohammed88/Semantic-UI-React
import React from 'react' import { Icon, Step } from 'semantic-ui-react' const steps = [ { completed: true, icon: 'truck', title: 'Shipping', description: 'Choose your shipping options' }, { completed: true, icon: 'credit card', title: 'Billing', description: 'Enter billing information' }, { active: true, icon: 'info', title: 'Confirm Order', description: 'Verify order details' }, ] const StepExampleVertical = () => ( <div> <Step.Group vertical> <Step completed> <Icon name='truck' /> <Step.Content> <Step.Title>Shipping</Step.Title> <Step.Description>Choose your shipping options</Step.Description> </Step.Content> </Step> <Step completed> <Icon name='credit card' /> <Step.Content title='Billing' description='Enter billing information' /> </Step> <Step active icon='info' title='Confirm Order' description='Verify order details' /> </Step.Group> <br /> <Step.Group vertical items={steps} /> </div> ) export default StepExampleVertical
src/components/SkeletonText/SkeletonText-story.js
joshblack/carbon-components-react
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable no-console */ import React from 'react'; import { storiesOf } from '@storybook/react'; import { withKnobs, boolean, number, select } from '@storybook/addon-knobs'; import SkeletonText from '../SkeletonText'; const widths = { '100%': '100%', '250px': '250px', }; const props = () => ({ heading: boolean('Skeleton text at a larger size (heading)'), paragraph: boolean('Use multiple lines of text (paragraph)'), lineCount: number('The number of lines in a paragraph (lineCount)', 3), width: select( 'Width (in px or %) of single line of text or max-width of paragraph lines (width)', widths, '100%' ), }); storiesOf('SkeletonText', module) .addDecorator(withKnobs) .add( 'Default', () => ( <div style={{ width: '300px' }}> <SkeletonText {...props()} /> </div> ), { info: { text: ` Skeleton states are used as a progressive loading state while the user waits for content to load. `, }, } );
src/svg-icons/av/forward-5.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvForward5 = (props) => ( <SvgIcon {...props}> <path d="M4 13c0 4.4 3.6 8 8 8s8-3.6 8-8h-2c0 3.3-2.7 6-6 6s-6-2.7-6-6 2.7-6 6-6v4l5-5-5-5v4c-4.4 0-8 3.6-8 8zm6.7.9l.2-2.2h2.4v.7h-1.7l-.1.9s.1 0 .1-.1.1 0 .1-.1.1 0 .2 0h.2c.2 0 .4 0 .5.1s.3.2.4.3.2.3.3.5.1.4.1.6c0 .2 0 .4-.1.5s-.1.3-.3.5-.3.2-.5.3-.4.1-.6.1c-.2 0-.4 0-.5-.1s-.3-.1-.5-.2-.2-.2-.3-.4-.1-.3-.1-.5h.8c0 .2.1.3.2.4s.2.1.4.1c.1 0 .2 0 .3-.1l.2-.2s.1-.2.1-.3v-.6l-.1-.2-.2-.2s-.2-.1-.3-.1h-.2s-.1 0-.2.1-.1 0-.1.1-.1.1-.1.1h-.6z"/> </SvgIcon> ); AvForward5 = pure(AvForward5); AvForward5.displayName = 'AvForward5'; AvForward5.muiName = 'SvgIcon'; export default AvForward5;
src/parser/warlock/destruction/modules/talents/Inferno.js
FaideWW/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import AbilityTracker from 'parser/shared/modules/AbilityTracker'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatThousands } from 'common/format'; import StatisticListBoxItem from 'interface/others/StatisticListBoxItem'; import RainOfFire from '../features/RainOfFire'; import SoulShardTracker from '../soulshards/SoulShardTracker'; const FRAGMENTS_PER_CHAOS_BOLT = 20; const FRAGMENTS_PER_RAIN_OF_FIRE = 30; /* Inferno (Tier 60 Destruction talent): Rain of Fire damage has a 20% chance to generate a Soul Shard Fragment. */ class Inferno extends Analyzer { static dependencies = { rainOfFire: RainOfFire, soulShardTracker: SoulShardTracker, abilityTracker: AbilityTracker, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.INFERNO_TALENT.id); } get averageRainOfFireDamage() { // Rain of Fire has different spellId for cast and damage but AbilityTracker picks up both of them const rofDamage = this.abilityTracker.getAbility(SPELLS.RAIN_OF_FIRE_DAMAGE.id); const rofCast = this.abilityTracker.getAbility(SPELLS.RAIN_OF_FIRE_CAST.id); return ((rofDamage.damageEffective + rofDamage.damageAbsorbed) / rofCast.casts) || 0; } get averageChaosBoltDamage() { const chaosBolt = this.abilityTracker.getAbility(SPELLS.CHAOS_BOLT.id); return ((chaosBolt.damageEffective + chaosBolt.damageAbsorbed) / chaosBolt.casts) || 0; } subStatistic() { // ESTIMATED fragments from Rain of Fire, see comments in SoulShardTracker._getRandomFragmentDistribution() const fragments = this.soulShardTracker.getGeneratedBySpell(SPELLS.RAIN_OF_FIRE_DAMAGE.id); const estimatedRofDamage = Math.floor(fragments / FRAGMENTS_PER_RAIN_OF_FIRE) * this.averageRainOfFireDamage; const estimatedChaosBoltDamage = Math.floor(fragments / FRAGMENTS_PER_CHAOS_BOLT) * this.averageChaosBoltDamage; return ( <StatisticListBoxItem title={<><strong>Estimated</strong> bonus fragments from <SpellLink id={SPELLS.INFERNO_TALENT.id} /></>} value={fragments} valueTooltip={`While majority of sources of Soul Shard Fragments are certain, chance based sources (Inferno and Immolate crits) make tracking the fragments 100% correctly impossible (fragment generation is NOT in logs).<br /><br /> If you used all these bonus fragments on Chaos Bolts, they would do ${formatThousands(estimatedChaosBoltDamage)} damage (${this.owner.formatItemDamageDone(estimatedChaosBoltDamage)}).<br /> If you used them on Rain of Fires, they would do ${formatThousands(estimatedRofDamage)} damage (${this.owner.formatItemDamageDone(estimatedRofDamage)}) <strong>assuming an average of ${this.rainOfFire.averageTargetsHit.toFixed(2)} targets</strong>.<br /> Both of these estimates are based on average damage of respective spells during the fight.`} /> ); } } export default Inferno;
vendor/laravel/framework/src/Illuminate/Foundation/Console/Presets/react-stubs/Example.js
binmurv/C.B.U.L.M.S.
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; export default class Example extends Component { render() { return ( <div className="container"> <div className="row"> <div className="col-md-8 col-md-offset-2"> <div className="panel panel-default"> <div className="panel-heading">Example Component</div> <div className="panel-body"> I'm an example component! </div> </div> </div> </div> </div> ); } } if (document.getElementById('example')) { ReactDOM.render(<Example />, document.getElementById('example')); }
app/javascript/mastodon/features/standalone/hashtag_timeline/index.js
sylph-sin-tyaku/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { expandHashtagTimeline } from 'mastodon/actions/timelines'; import Masonry from 'react-masonry-infinite'; import { List as ImmutableList } from 'immutable'; import DetailedStatusContainer from 'mastodon/features/status/containers/detailed_status_container'; import { debounce } from 'lodash'; import LoadingIndicator from 'mastodon/components/loading_indicator'; const mapStateToProps = (state, { hashtag }) => ({ statusIds: state.getIn(['timelines', `hashtag:${hashtag}`, 'items'], ImmutableList()), isLoading: state.getIn(['timelines', `hashtag:${hashtag}`, 'isLoading'], false), hasMore: state.getIn(['timelines', `hashtag:${hashtag}`, 'hasMore'], false), }); export default @connect(mapStateToProps) class HashtagTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, statusIds: ImmutablePropTypes.list.isRequired, isLoading: PropTypes.bool.isRequired, hasMore: PropTypes.bool.isRequired, hashtag: PropTypes.string.isRequired, }; componentDidMount () { const { dispatch, hashtag } = this.props; dispatch(expandHashtagTimeline(hashtag)); } handleLoadMore = () => { const maxId = this.props.statusIds.last(); if (maxId) { this.props.dispatch(expandHashtagTimeline(this.props.hashtag, { maxId })); } } setRef = c => { this.masonry = c; } handleHeightChange = debounce(() => { if (!this.masonry) { return; } this.masonry.forcePack(); }, 50) render () { const { statusIds, hasMore, isLoading } = this.props; const sizes = [ { columns: 1, gutter: 0 }, { mq: '415px', columns: 1, gutter: 10 }, { mq: '640px', columns: 2, gutter: 10 }, { mq: '960px', columns: 3, gutter: 10 }, { mq: '1255px', columns: 3, gutter: 10 }, ]; const loader = (isLoading && statusIds.isEmpty()) ? <LoadingIndicator key={0} /> : undefined; return ( <Masonry ref={this.setRef} className='statuses-grid' hasMore={hasMore} loadMore={this.handleLoadMore} sizes={sizes} loader={loader}> {statusIds.map(statusId => ( <div className='statuses-grid__item' key={statusId}> <DetailedStatusContainer id={statusId} compact measureHeight onHeightChange={this.handleHeightChange} /> </div> )).toArray()} </Masonry> ); } }
webapp-src/src/Login/PasswordForm.js
babelouest/glewlwyd
import React, { Component } from 'react'; import i18next from 'i18next'; import apiManager from '../lib/APIManager'; import messageDispatcher from '../lib/MessageDispatcher'; class PasswordForm extends Component { constructor(props) { super(props); this.state = { username: props.username, password: "", config: props.config, currentUser: props.currentUser, userList: props.userList }; this.handleChangeUsername = this.handleChangeUsername.bind(this); this.handleChangePassword = this.handleChangePassword.bind(this); this.validateLogin = this.validateLogin.bind(this); } componentWillReceiveProps(nextProps) { this.setState({ username: nextProps.username, password: "", config: nextProps.config, currentUser: nextProps.currentUser, userList: nextProps.userList }); } handleChangeUsername(e) { this.setState({username: e.target.value}); } handleChangePassword(e) { this.setState({password: e.target.value}); } validateLogin(e) { e.preventDefault(); if (this.state.username && this.state.password) { var scheme = { username: this.state.username, password: this.state.password }; apiManager.glewlwydRequest("/auth/", "POST", scheme) .then(() => { messageDispatcher.sendMessage('App', {type: 'loginSuccess'}); }) .fail(() => { messageDispatcher.sendMessage('Notification', {type: "danger", message: i18next.t("login.error-login")}); }); } } gotoManageUsers() { messageDispatcher.sendMessage('App', {type: 'SelectAccount'}); } render() { var inputUsername, manageUsersButton; if (this.state.currentUser) { inputUsername = <input type="text" className="form-control" name="username" id="username" disabled={true} value={this.state.currentUser.username} /> } else { inputUsername = <input type="text" className="form-control" name="username" id="username" required="" placeholder={i18next.t("login.login-placeholder")} value={this.state.username} onChange={this.handleChangeUsername} autoFocus={true}/>; } if (this.state.userList.length > 0) { manageUsersButton = <button type="button" className="btn btn-secondary" onClick={this.gotoManageUsers}>{i18next.t("login.manage-users")}</button> } return ( <form action="#" id="passwordForm"> <div className="form-group"> <h4>{i18next.t("login.enter-login-password")}</h4> </div> <div className="form-group"> <div className="input-group mb-3"> <div className="input-group-prepend"> <label className="input-group-text" htmlFor="username">{i18next.t("login.login")}</label> </div> {inputUsername} </div> </div> <div className="form-group"> <div className="input-group mb-3"> <div className="input-group-prepend"> <label className="input-group-text" htmlFor="password">{i18next.t("login.password")}</label> </div> <input type="password" className="form-control" name="password" id="password" required="" placeholder={i18next.t("login.password-placeholder")} value={this.state.password} onChange={this.handleChangePassword} autoFocus={!!this.state.currentUser}/> </div> </div> <div className="row"> <div className="col-md-3"> <button type="submit" name="loginbut" id="loginbut" className="btn btn-primary btn-lg btn-block" onClick={(e) => this.validateLogin(e)} title={i18next.t("login.sign-in-title")}>{i18next.t("login.btn-ok")}</button> </div> <div className="col-md-9 text-right mt-2"> {manageUsersButton} </div> </div> </form> ); } } export default PasswordForm;
src/components/Icon.js
CookPete/rplayr
// http://dmfrancisco.github.io/react-icons import React from 'react' import classNames from './Icon.scss' export default function Icon ({ icon, className = '', ...extraProps }) { return ( <svg {...extraProps} className={classNames.icon + ' ' + className} viewBox='0 0 24 24' preserveAspectRatio='xMidYMid meet' fit > {renderGraphic(icon)} </svg> ) } function renderGraphic (icon) { switch (icon) { case 'play': return <g><path d='M8 5v14l11-7z'></path></g> case 'pause': return <g><path d='M6 19h4V5H6v14zm8-14v14h4V5h-4z'></path></g> case 'next': return <g><path d='M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z'></path></g> case 'prev': return <g><path d='M6 6h2v12H6zm3.5 6l8.5 6V6z'></path></g> case 'volume': return <g><path d='M18.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z'></path></g> case 'search': return <g><path d='M15.5 14h-.79l-.28-.27c.98-1.14 1.57-2.62 1.57-4.23 0-3.59-2.91-6.5-6.5-6.5s-6.5 2.91-6.5 6.5 2.91 6.5 6.5 6.5c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99 1.49-1.49-4.99-5zm-6 0c-2.49 0-4.5-2.01-4.5-4.5s2.01-4.5 4.5-4.5 4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5z'></path></g> case 'clear': return <g><path d='M19 6.41l-1.41-1.41-5.59 5.59-5.59-5.59-1.41 1.41 5.59 5.59-5.59 5.59 1.41 1.41 5.59-5.59 5.59 5.59 1.41-1.41-5.59-5.59z'></path></g> } }
app/containers/App/index.js
j921216063/chenya
/** * * App * * 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) */ import React from 'react'; import Helmet from 'react-helmet'; // import styled from 'styled-components'; import Header from 'components/Header'; import Footer from 'components/Footer'; import withProgressBar from 'components/ProgressBar'; // const AppWrapper = styled.div` // max-width: calc(768px + 16px * 2); // margin: 0 auto; // display: flex; // min-height: 100%; // padding: 0 16px; // flex-direction: column; // `; export function App(props) { return ( <div> <Helmet titleTemplate="%s - 承燁工程顧問股份有限公司" defaultTitle="承燁工程顧問股份有限公司" meta={[ { name: 'description', content: '風力發電 ,渦輪風力發電機' }, ]} /> <Header /> {React.Children.toArray(props.children)} <Footer /> </div> ); } App.propTypes = { children: React.PropTypes.node, }; export default withProgressBar(App);
client/components/singleentry/DetailTable.js
MusicConnectionMachine/VisualizationG6
import React from 'react' export default class DetailTable extends React.Component { constructor (props) { super(props) var entries = [] let defaultEntries = [] if (props.type === 'artists') { defaultEntries = [ { id: 'name', name: 'Name' }, { id: 'dateOfBirth', name: 'Date of Birth' }, { id: 'dateOfDeath', name: 'Date of Death' }, { id: 'placeOfBirth', name: 'Place of Birth' }, { id: 'placeOfDeath', name: 'Place of Death' }, { id: 'nationality', name: 'Nationality' } ] } else if (props.type === 'works') { defaultEntries = [ { id: 'title', name: 'Title' }, { id: 'compositionyear', name: 'Date of Composition' } ] } for (var i = 0; i < defaultEntries.length; i++) { let value = props.myData[defaultEntries[i].id] if (value) { entries.push({ name: defaultEntries[i].name, value: value }) } } if (props.myData.wiki_link || props.myData.source_link) { entries.push({ name: 'Further Information', value: (<a href={props.myData.wiki_link} target='_blank'>Wikipedia</a>) }) } if (props.myData['tags']) { let mappingKey = 0 entries.push({ name: 'Tags', value: props.myData.tags.map(name => { return ( <span key={mappingKey++}><div className='label label-default'>{name}</div> </span> ) }) }) } this.state = { entries: entries } } render () { let mappingKey = 0 return ( <div className='detailbox'> <table className='table table-hover'> <thead> <tr> <th colSpan='2'> Detailed Information </th> </tr> </thead> <tbody> {this.state.entries.map(entry => ( <tr key={mappingKey++}> <td style={{ whiteSpace: 'nowrap' }}> {entry.name} </td> <td> {entry.value} </td> </tr> ))} </tbody> </table> </div> ) } } DetailTable.propTypes = { type: React.PropTypes.string, id: React.PropTypes.string, myData: React.PropTypes.object } DetailTable.contextTypes = { router: React.PropTypes.object }
src/routes/UIElement/iconfont/index.js
zhangjingge/sse-antd-admin
import React from 'react' import { Iconfont } from '../../../components' import { Table, Row, Col } from 'antd' import styles from './index.less' const iconlist = ['Cherry', 'Cheese', 'Bread', 'Beer', 'Beet', 'Bacon', 'Banana', 'Asparagus', 'Apple'] const IcoPage = () => <div className="content-inner"> <ul className={styles.list}> {iconlist.map(item => <li key={item}><Iconfont className={styles.icon} type={item} /><span className={styles.name}>{item}</span></li>)} </ul> <h2 style={{ margin: '16px 0' }}>Props</h2> <Row> <Col lg={18} md={24}> <Table rowKey={(record, key) => key} pagination={false} bordered scroll={{ x: 800 }} columns={[ { title: '参数', dataIndex: 'props', }, { title: '说明', dataIndex: 'desciption', }, { title: '类型', dataIndex: 'type', }, { title: '默认值', dataIndex: 'default', }, ]} dataSource={[ { props: 'type', desciption: '图标类型', type: 'String', default: '-', }]} /> </Col> </Row> </div> export default IcoPage
lib/components/elements/text-box/style.js
rento19962/relax
import React from 'react'; import Utils from '../../../utils'; import Colors from '../../../colors'; import {Types} from '../../../data-types'; export default { type: 'text', options: [ { label: 'Font Family', id: 'font', type: Types.Font }, { label: 'Font Size', id: 'fontSize', type: Types.Pixels }, { label: 'Line Height', id: 'lineHeight', type: Types.Pixels }, { label: 'Letter Spacing', id: 'letterSpacing', type: Types.Pixels }, { label: 'Color', id: 'color', type: Types.Color }, { label: 'Links underline', id: 'linkUnderline', type: Types.Boolean }, { label: 'Links color', id: 'linkColor', type: Types.Color }, { label: 'Links color hover', id: 'linkColorOver', type: Types.Color } ], defaults: { font: {}, fontSize: 16, lineHeight: 16, letterSpacing: 0, color: { value: '#ffffff', opacity: 100 }, linkUnderline: true, linkColor: { value: '#ffffff', opacity: 100 }, linkColorOver: { value: '#ffffff', opacity: 100 } }, rules: (props) => { var rule = {}; rule.fontSize = props.fontSize+'px'; rule.lineHeight = props.lineHeight+'px'; rule.color = Colors.getColorString(props.color); rule.letterSpacing = props.letterSpacing+'px'; if (props.font && props.font.family && props.font.fvd) { rule.fontFamily = props.font.family; Utils.processFVD(rule, props.font.fvd); } // links rule.a = { textDecoration: props.linkUnderline ? 'underline' : 'none', color: Colors.getColorString(props.linkColor), ':hover': { color: Colors.getColorString(props.linkColorOver) } }; return { text: rule }; }, getIdentifierLabel: (props) => { var variation = props.font && props.font.fvd && ' ' + props.font.fvd.charAt(1)+'00' || ''; return (props.font && props.font.family || '') + variation; }, preview: (classesMap) => { var holderStyle = { height: 55, lineHeight: '55px' }; var style = { display: 'inline-block', verticalAlign: 'bottom' }; return ( <div style={holderStyle}> <div className={classesMap.text || ''} style={style}>month</div> </div> ); } };
app/javascript/mastodon/features/ui/util/react_router_helpers.js
codl/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { Switch, Route } from 'react-router-dom'; import ColumnLoading from '../components/column_loading'; import BundleColumnError from '../components/bundle_column_error'; import BundleContainer from '../containers/bundle_container'; // Small wrapper to pass multiColumn to the route components export class WrappedSwitch extends React.PureComponent { render () { const { multiColumn, children } = this.props; return ( <Switch> {React.Children.map(children, child => React.cloneElement(child, { multiColumn }))} </Switch> ); } } WrappedSwitch.propTypes = { multiColumn: PropTypes.bool, children: PropTypes.node, }; // Small Wraper to extract the params from the route and pass // them to the rendered component, together with the content to // be rendered inside (the children) export class WrappedRoute extends React.Component { static propTypes = { component: PropTypes.func.isRequired, content: PropTypes.node, multiColumn: PropTypes.bool, } renderComponent = ({ match }) => { const { component, content, multiColumn } = this.props; return ( <BundleContainer fetchComponent={component} loading={this.renderLoading} error={this.renderError}> {Component => <Component params={match.params} multiColumn={multiColumn}>{content}</Component>} </BundleContainer> ); } renderLoading = () => { return <ColumnLoading />; } renderError = (props) => { return <BundleColumnError {...props} />; } render () { const { component: Component, content, ...rest } = this.props; return <Route {...rest} render={this.renderComponent} />; } }
src/packages/@ncigdc/modern_components/DownloadClinicalDropdown/DownloadClinicalDropdown.relay.js
NCI-GDC/portal-ui
// @flow import React from 'react'; import { graphql } from 'react-relay'; import { withRouter } from 'react-router-dom'; import { compose, withPropsOnChange } from 'recompose'; import Query from '@ncigdc/modern_components/Query'; import { makeFilter, addInFilters } from '@ncigdc/utils/filters'; export default (Component: ReactClass<*>) => compose( withRouter, withPropsOnChange( ['filters', 'selectedIds'], ({ filters, selectedIds }) => { const downloadFilters = selectedIds && selectedIds.length ? addInFilters( ...filters, makeFilter([ { field: 'cases.case_id', value: selectedIds, }, ]), ) : filters; return { filters: downloadFilters, variables: { filters: downloadFilters, }, }; }, ), )((props: Object) => { const caseQuery = props.scope === 'explore' ? graphql` query DownloadClinicalDropdownExplore_relayQuery( $filters: FiltersArgument ) { viewer { explore { cases { hits(first: 0, filters: $filters) { total } } } } } ` : graphql` query DownloadClinicalDropdownRepository_relayQuery( $filters: FiltersArgument ) { viewer { repository { cases { hits(first: 0, filters: $filters) { total } } } } } `; return ( <Query parentProps={props} variables={props.variables} Component={Component} style={{ width: 'auto' }} query={caseQuery} /> ); });
client/containers/process_by_id.js
vidi-insights/vidi-dashboard
'use strict' import React from 'react' import {connect} from 'react-redux' import {Link} from 'react-router' import {Panel, PageHeader} from '../components/index' import ChartistGraph from 'react-chartist' import {subscribe, unsubscribe} from '../actions/vidi' import _ from 'lodash' export const ProcessById = React.createClass({ componentDidMount () { this.props.dispatch(subscribe('processes')) this.props.dispatch(subscribe('event_loop')) }, componentWillUnmount () { this.props.dispatch(unsubscribe('processes')) this.props.dispatch(unsubscribe('event_loop')) }, render () { var body = null var data = _.find(this.props.processes, ['pid', this.props.params.id]) if (data) { var event_loop = _.find(this.props.event_loop, ['pid', data.pid]) body =( <div className="process-card"> {make_process_sections(data)} {make_event_loop_section(event_loop)} </div> ) } return ( <div className="page page-processes"> <div className="container-fluid"> <PageHeader title={'Back'} titleLink={'/'} /> </div> <div className="container-fluid"> {body} </div> </div> ) } }) export default connect((state) => { var vidi = state.vidi var processes = vidi.processes || {data: [null]} var event_loop = vidi.event_loop || {data: [null]} return { processes: processes.data, event_loop: event_loop.data } })(ProcessById) function make_process_sections (data) { var now = data.latest return ( <div key={(now.pid + 'process')}> <div className="process-heading has-btn cf"> <h1 className="mt0 mb0 txt-truncate fl-left"><span className="status status-small status-healthy"></span> {now.pid}</h1> </div> <div className="row middle-xs process-stats-row no-gutter"> <div className="col-xs-12 col-sm-6 col-md-6 col-lg-6 process-stats-container process-stats-floated cf"> <h2 className="txt-truncate m0">{now.proc_uptime}</h2> <p className="label-dimmed m0">Process uptime</p> </div> <div className="col-xs-12 col-sm-6 col-md-6 col-lg-6 process-stats-container process-stats-floated cf"> <h2 className="txt-truncate m0">{now.sys_uptime}</h2> <p className="label-dimmed m0">System uptime</p> </div> </div> <div className="row middle-xs process-stats-row no-gutter"> <div className="col-xs-6 col-sm-3 col-md-3 process-stats-container cf"> <h2 className="txt-truncate m0">{now.pid}</h2> <p className="label-dimmed m0">Pid</p> </div> <div className="col-xs-6 col-sm-3 col-md-3 process-stats-container cf"> <h2 className="txt-truncate m0">{now.title}</h2> <p className="label-dimmed m0">Title</p> </div> <div className="col-xs-6 col-sm-3 col-md-3 process-stats-container cf"> <h2 className="txt-truncate m0">{now.arch}</h2> <p className="label-dimmed m0">Architecture</p> </div> <div className="col-xs-6 col-sm-3 col-md-3 process-stats-container cf"> <h2 className="txt-truncate m0">{now.platform}</h2> <p className="label-dimmed m0">Platform</p> </div> </div> <div className="row middle-xs process-stats-row no-gutter"> <div className="col-xs-6 col-sm-3 col-md-3 process-stats-container cf"> <h2 className="txt-truncate m0">{now.ver_node}</h2> <p className="label-dimmed m0">Node</p> </div> <div className="col-xs-6 col-sm-3 col-md-3 process-stats-container cf"> <h2 className="txt-truncate m0">{now.ver_v8}</h2> <p className="label-dimmed m0">V8</p> </div> <div className="col-xs-6 col-sm-3 col-md-3 process-stats-container cf"> <h2 className="txt-truncate m0">{now.ver_uv}</h2> <p className="label-dimmed m0">LibUV</p> </div> <div className="col-xs-6 col-sm-3 col-md-3 process-stats-container cf"> <h2 className="txt-truncate m0">{now.ver_openssl}</h2> <p className="label-dimmed m0">OpenSSL</p> </div> </div> <div className="row middle-xs no-gutter"> <h3 className="col-xs-12 mb0 mt0 process-heading">Heap Usage</h3> </div> <div className="row middle-xs"> <div className="col-xs-12 mtb"> <ChartistGraph type={'Line'} data={{labels: data.series.time, series: [data.series.heap_total, data.series.heap_rss, data.series.heap_used]}} options={{ fullWidth: true, showArea: false, showLine: true, showPoint: false, chartPadding: {right: 30}, axisX: {labelOffset: {x: -15}, labelInterpolationFnc: (val) => { if (_.last(val) == '0') return val else return null }}, }}/> </div> </div> <div className="row middle-xs process-stats-row no-gutter"> <div className="col-xs-6 col-sm-4 col-md-4 process-stats-container process-stats-floated process-stats-compact cf"> <p className="txt-truncate m0">{now.heap_total + ' mb'}</p> <p className="label-dimmed m0">Total</p> </div> <div className="col-xs-6 col-sm-4 col-md-4 process-stats-container process-stats-floated process-stats-compact cf"> <p className="txt-truncate m0">{now.heap_used + ' mb'}</p> <p className="label-dimmed m0">Used</p> </div> <div className="col-xs-12 col-sm-4 col-md-4 process-stats-container process-stats-floated process-stats-compact cf"> <p className="txt-truncate m0">{now.heap_rss + ' mb'}</p> <p className="label-dimmed m0">Rss</p> </div> </div> </div> ) return section } function make_event_loop_section (event_loop) { return ( <div key={(event_loop.latest.pid + 'event_loop')}> <div className="row middle-xs process-stats-row no-gutter"> <h3 className="col-xs-12 mb0 mt0 process-heading">Event Loop</h3> <div className="col-xs-12 mtb"> <ChartistGraph type={'Line'} data={{labels: event_loop.series.time, series: [event_loop.series.delay, event_loop.series.limit]}} options={{ fullWidth: true, showArea: false, showLine: true, showPoint: false, chartPadding: {right: 30}, axisX: { labelOffset: {x: -15}, labelInterpolationFnc: function (val) { if (_.last(val) == '0') return val else return null }} }}/> </div> </div> <div className="row middle-xs process-stats-row no-gutter"> <div className="col-xs-6 col-sm-4 col-md-4 process-stats-container process-stats-floated process-stats-compact cf"> <p className="txt-truncate m0">{(Math.round(event_loop.latest.delay * 100) / 100)}</p> <p className="label-dimmed m0">Delay</p> </div> <div className="col-xs-6 col-sm-4 col-md-4 process-stats-container process-stats-floated process-stats-compact cf"> <p className="txt-truncate m0">{event_loop.latest.limit}</p> <p className="label-dimmed m0">Limit</p> </div> <div className="col-xs-12 col-sm-4 col-md-4 process-stats-container process-stats-floated process-stats-compact cf"> <p className="txt-truncate m0 label-met">{event_loop.latest.over_limit}</p> <p className="label-dimmed m0">Over Limit</p> </div> </div> </div> ) }
resources/_pages/Contact.js
AndrewTJohnston/andrewtjohnston.com
import React from 'react' import Nodes from './ContactNodes' import Share from './ShareContact' export default React.createClass({ getInitialState() { return { data: require('json!./../_assets/data/contact.json'), width: 1000, height: 1000 } }, render() { return ( <div> <Share /> <Nodes data={ this.state.data } width={ this.state.width } height={ this.state.height }/> </div> ) } })
app/components/build/Show.js
buildkite/frontend
// @flow import React from 'react'; import PropTypes from 'prop-types'; import { RootContainer } from 'react-relay/classic'; import * as BuildQuery from 'app/queries/Build'; import AnnotationsList from './AnnotationsList'; import Header from './Header'; declare var Buildkite: { JobComponent: Object, BuildManualJobSummaryComponent: Object, BuildTriggerJobSummaryComponent: Object, BuildWaiterJobSummaryComponent: Object }; type Props = { store: { on: Function, off: Function, getBuild: Function } }; type State = { build: { number: number, account: { slug: string }, project: { slug: string }, jobs: Array<{ id: string, type: string, state: string, retriedInJobUuid: string }> } }; export default class BuildShow extends React.PureComponent<Props, State> { static propTypes = { store: PropTypes.shape({ on: PropTypes.func.isRequired, off: PropTypes.func.isRequired, getBuild: PropTypes.func.isRequired }).isRequired }; constructor(initialProps: Props) { super(initialProps); this.state = { build: initialProps.store.getBuild() }; // `this.props.store` is an EventEmitter which always // calls a given event handler in its own context 🤦🏻‍♀️ // so let's override that! this.handleStoreChange = this.handleStoreChange.bind(this); } componentDidMount() { this.props.store.on('change', this.handleStoreChange); } componentWillUnmount() { this.props.store.off('change', this.handleStoreChange); } handleStoreChange = () => { this.setState({ build: this.props.store.getBuild() }); }; render() { const build = this.state.build; return ( <div> <Header build={build} showRebuild={true} showUnknownEmailPrompt={true} /> <RootContainer Component={AnnotationsList} route={{ name: 'AnnotationsRoute', queries: { build: BuildQuery.query }, params: BuildQuery.prepareParams({ organization: build.account.slug, pipeline: build.project.slug, number: build.number }) }} /> {this.renderJobList()} </div> ); } renderJobList() { let inRetryGroup = false; // job-list-pipeline is needed by the job components' styles return ( <div className="job-list-pipeline"> {this.state.build.jobs.map((job) => { // Don't even bother showing broken jobs if (job.state === 'broken') { return null; } if (job.type === "script") { // Figures out if we're inside a "retry-group" and comes up with // the neccessary class name. let retryGroupClassName; if (!inRetryGroup && job.retriedInJobUuid) { // Start of the group retryGroupClassName = "job-retry-group-first"; inRetryGroup = true; } else if (inRetryGroup && job.retriedInJobUuid) { // Middle of the group retryGroupClassName = "job-retry-group-middle"; } else if (inRetryGroup && !job.retriedInJobUuid) { // Ends of the group retryGroupClassName = "job-retry-group-last"; inRetryGroup = false; } return ( <Buildkite.JobComponent key={job.id} job={job} build={this.state.build} className={retryGroupClassName} /> ); } else if (job.type === "manual") { return <Buildkite.BuildManualJobSummaryComponent key={job.id} job={job} />; } else if (job.type === "trigger") { return <Buildkite.BuildTriggerJobSummaryComponent key={job.id} job={job} />; } else if (job.type === "waiter") { return <Buildkite.BuildWaiterJobSummaryComponent key={job.id} job={job} />; } })} </div> ); } }
src/decorators/withViewport.js
JosephArcher/KappaKappaKapping
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); // eslint-disable-line react/no-set-state } }; } export default withViewport;
webapp/app/components/Notifications/Form/Groups/SelectedGroups/index.js
EIP-SAM/SAM-Solution-Node-js
// // Component selected groups form notifications // import React from 'react'; import { FormGroup, FormControl, ControlLabel, HelpBlock } from 'react-bootstrap'; import ButtonPopover from 'components/ButtonPopover'; import Option from 'components/Option'; import styles from 'components/Notifications/styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class NotificationsFormSelectedGroups extends React.Component { constructor(props) { super(props); this.onChangeSelectedGroups = this.onChangeSelectedGroups.bind(this); } onChangeSelectedGroups(event) { const options = event.target.options; const value = []; for (let i = 0; i < options.length; i++) { if (options[i].selected) { value.push({ id: parseInt(options[i].value, 10), name: options[i].text }); } } this.props.unselectedGroupsOnChange(value); } render() { let validationState = null; let errorMessage = ''; if (this.props.selectedGroupsError !== '') { validationState = 'error'; errorMessage = this.props.selectedGroupsError; } let selectedGroups = []; let selectedGroupsOption = []; if (this.props.selectedGroups.length > 0) { selectedGroups = this.props.selectedGroups.map(user => ( { value: user.id, text: user.name } )); selectedGroupsOption = selectedGroups.map((item, index) => ( <Option object={item} key={`item-${index}`} /> )); } return ( <FormGroup controlId="selectedGroups" className={styles.form} validationState={validationState}> <ControlLabel>Selected Groups</ControlLabel> <ButtonPopover id="selectedGroups" trigger={['hover', 'focus']} buttonType="link" icon="question-sign" popoverContent="Select one or several groups and remove them from the group using CTRL^ key" placement="right" /> <FormControl componentClass="select" onChange={this.onChangeSelectedGroups} multiple> {selectedGroupsOption} </FormControl> <HelpBlock>{errorMessage}</HelpBlock> </FormGroup> ); } } NotificationsFormSelectedGroups.propTypes = { selectedGroups: React.PropTypes.arrayOf(React.PropTypes.object), unselectedGroupsOnChange: React.PropTypes.func, selectedGroupsError: React.PropTypes.string, };
react-flux-mui/js/material-ui/src/svg-icons/image/hdr-strong.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageHdrStrong = (props) => ( <SvgIcon {...props}> <path d="M17 6c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zM5 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/> </SvgIcon> ); ImageHdrStrong = pure(ImageHdrStrong); ImageHdrStrong.displayName = 'ImageHdrStrong'; ImageHdrStrong.muiName = 'SvgIcon'; export default ImageHdrStrong;
node_modules/react-router-scroll/test/routes.js
juhov/travis-test
import React from 'react'; import { Route } from 'react-router-dom'; function Page1() { return ( <div style={{ width: 20000, height: 20000 }} /> ); } function Page2() { return ( <div style={{ width: 10000, height: 10000 }} /> ); } export const syncRoutes = [ <Route path="/" exact key="page1" component={Page1} />, <Route path="/page2" key="page2" component={Page2} />, ]; export function createElementRoutes(Page) { return ( <Page> <Route exact path="/" /> <Route path="/other" /> </Page> ); }
server/sonar-web/src/main/js/apps/component-measures/details/treemap/MeasureTreemap.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import Spinner from './../../components/Spinner'; import { getLeakValue } from '../../utils'; import { Treemap } from '../../../../components/charts/treemap'; import { getChildren } from '../../../../api/components'; import { formatMeasure } from '../../../../helpers/measures'; import { translate, translateWithParameters, getLocalizedMetricName } from '../../../../helpers/l10n'; import { getComponentUrl } from '../../../../helpers/urls'; import Workspace from '../../../../components/workspace/main'; const HEIGHT = 500; export default class MeasureTreemap extends React.Component { state = { fetching: true, components: [], breadcrumbs: [] }; componentDidMount () { const { component } = this.props; this.mounted = true; this.fetchComponents(component.key); } componentDidUpdate (nextProps) { if (nextProps.metric !== this.props.metric) { this.fetchComponents(this.props.component.key); } } componentWillUnmount () { this.mounted = false; } fetchComponents (componentKey) { const { metric } = this.props; const metrics = ['ncloc', metric.key]; const options = { s: 'metric', metricSort: 'ncloc', asc: false }; return getChildren(componentKey, metrics, options).then(r => { const components = r.components.map(component => { const measures = {}; const key = component.refKey || component.key; component.measures.forEach(measure => { const shouldUseLeak = measure.metric.indexOf('new_') === 0; measures[measure.metric] = shouldUseLeak ? getLeakValue(measure) : measure.value; }); return { ...component, measures, key }; }); this.setState({ components, fetching: false }); }); } getTooltip (component) { const { metric } = this.props; let inner = [ component.name, `${translate('metric.ncloc.name')}: ${formatMeasure(component.measures['ncloc'], 'INT')}` ]; const colorMeasure = component.measures[metric.key]; const formatted = colorMeasure != null ? formatMeasure(colorMeasure, metric.type) : '—'; inner.push(`${getLocalizedMetricName(metric)}: ${formatted}`); inner = inner.join('<br>'); return `<div class="text-left">${inner}</div>`; } getPercentColorScale (metric) { const color = d3.scale.linear().domain([0, 25, 50, 75, 100]); color.range(metric.direction === 1 ? ['#d4333f', '#ed7d20', '#eabe06', '#b0d513', '#00aa00'] : ['#00aa00', '#b0d513', '#eabe06', '#ed7d20', '#d4333f']); return color; } getRatingColorScale () { return d3.scale.linear() .domain([1, 2, 3, 4, 5]) .range(['#00aa00', '#b0d513', '#eabe06', '#ed7d20', '#d4333f']); } getLevelColorScale () { return d3.scale.ordinal() .domain(['ERROR', 'WARN', 'OK', 'NONE']) .range(['#d4333f', '#ed7d20', '#00aa00', '#b4b4b4']); } getScale () { const { metric } = this.props; if (metric.type === 'LEVEL') { return this.getLevelColorScale(); } if (metric.type === 'RATING') { return this.getRatingColorScale(); } return this.getPercentColorScale(metric); } handleRectangleClick (node) { const isFile = node.qualifier === 'FIL' || node.qualifier === 'UTS'; if (isFile) { return Workspace.openComponent({ uuid: node.id }); } this.fetchComponents(node.key).then(() => { let nextBreadcrumbs = [...this.state.breadcrumbs]; const index = this.state.breadcrumbs.findIndex(b => b.key === node.key); if (index !== -1) { nextBreadcrumbs = nextBreadcrumbs.slice(0, index); } nextBreadcrumbs = [...nextBreadcrumbs, { key: node.key, name: node.name, qualifier: node.qualifier }]; this.setState({ breadcrumbs: nextBreadcrumbs }); }); } handleReset () { const { component } = this.props; this.fetchComponents(component.key).then(() => { this.setState({ breadcrumbs: [] }); }); } renderTreemap () { const { metric } = this.props; const colorScale = this.getScale(); const items = this.state.components .filter(component => component.measures['ncloc']) .map(component => { const colorMeasure = component.measures[metric.key]; return { id: component.id, key: component.key, name: component.name, qualifier: component.qualifier, size: component.measures['ncloc'], color: colorMeasure != null ? colorScale(colorMeasure) : '#777', tooltip: this.getTooltip(component), label: component.name, link: getComponentUrl(component.key) }; }); return ( <Treemap items={items} breadcrumbs={this.state.breadcrumbs} height={HEIGHT} canBeClicked={() => true} onRectangleClick={this.handleRectangleClick.bind(this)} onReset={this.handleReset.bind(this)}/> ); } render () { const { metric } = this.props; const { fetching } = this.state; if (fetching) { return ( <div className="measure-details-treemap"> <div className="note text-center" style={{ lineHeight: `${HEIGHT}px` }}> <Spinner/> </div> </div> ); } return ( <div className="measure-details-treemap"> <ul className="list-inline note measure-details-treemap-legend"> <li> {translateWithParameters('component_measures.legend.color_x', getLocalizedMetricName(metric))} </li> <li> {translateWithParameters('component_measures.legend.size_x', translate('metric.ncloc.name'))} </li> </ul> {this.renderTreemap()} </div> ); } }
src/parser/priest/holy/modules/talents/90/Halo.js
fyruna/WoWAnalyzer
import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import TalentStatisticBox, { STATISTIC_ORDER } from 'interface/others/TalentStatisticBox'; import React from 'react'; import ItemHealingDone from 'interface/others/ItemHealingDone'; import ItemDamageDone from 'interface/others/ItemDamageDone'; // Example Log: /report/hRd3mpK1yTQ2tDJM/1-Mythic+MOTHER+-+Kill+(2:24)/14-丶寶寶小喵 class Halo extends Analyzer { haloDamage = 0; haloHealing = 0; haloOverhealing = 0; haloCasts = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.HALO_TALENT.id); } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId === SPELLS.HALO_DAMAGE.id) { this.haloDamage += event.amount || 0; } } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (spellId === SPELLS.HALO_HEAL.id) { this.haloHealing += event.amount || 0; this.haloOverhealing += event.overhealing || 0; } } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId === SPELLS.HALO_TALENT.id) { this.haloCasts += 1; } } statistic() { return ( <TalentStatisticBox talent={SPELLS.HALO_TALENT.id} value={( <> <ItemHealingDone amount={this.haloHealing} /><br /> <ItemDamageDone amount={this.haloDamage} /> </> )} tooltip={`Halos Cast: ${this.haloCasts}`} position={STATISTIC_ORDER.CORE(6)} /> ); } } export default Halo;
PublicApp/Main.js
sergiu-paraschiv/pi-media-center-automation
import React from 'react'; import ReactDOM from 'react-dom'; import InjectTapEventPlugin from 'react-tap-event-plugin'; import PageComponent from './Page/components/PageComponent'; InjectTapEventPlugin(); ReactDOM.render( <PageComponent />, document.getElementById('content') );
node_modules/radium/src/resolve-styles.js
Sweetgrassbuffalo/ReactionSweeGrass-v2
/* @flow */ import type {Config} from './config'; import appendImportantToEachValue from './append-important-to-each-value'; import cssRuleSetToString from './css-rule-set-to-string'; import getState from './get-state'; import getStateKey from './get-state-key'; import hash from './hash'; import {isNestedStyle, mergeStyles} from './merge-styles'; import Plugins from './plugins/'; import ExecutionEnvironment from 'exenv'; import React from 'react'; const DEFAULT_CONFIG = { plugins: [ Plugins.mergeStyleArray, Plugins.checkProps, Plugins.resolveMediaQueries, Plugins.resolveInteractionStyles, Plugins.keyframes, Plugins.visited, Plugins.removeNestedStyles, Plugins.prefix, Plugins.checkProps, ], }; // Gross let globalState = {}; // Declare early for recursive helpers. let resolveStyles = ((null: any): ( component: any, // ReactComponent, flow+eslint complaining renderedElement: any, config: Config, existingKeyMap?: {[key: string]: boolean}, shouldCheckBeforeResolve: true, ) => any); const _shouldResolveStyles = function(component) { return component.type && !component.type._isRadiumEnhanced; }; const _resolveChildren = function( { children, component, config, existingKeyMap, }, ) { if (!children) { return children; } const childrenType = typeof children; if (childrenType === 'string' || childrenType === 'number') { // Don't do anything with a single primitive child return children; } if (childrenType === 'function') { // Wrap the function, resolving styles on the result return function() { const result = children.apply(this, arguments); if (React.isValidElement(result)) { return resolveStyles(component, result, config, existingKeyMap, true); } return result; }; } if (React.Children.count(children) === 1 && children.type) { // If a React Element is an only child, don't wrap it in an array for // React.Children.map() for React.Children.only() compatibility. const onlyChild = React.Children.only(children); return resolveStyles(component, onlyChild, config, existingKeyMap, true); } return React.Children.map(children, function(child) { if (React.isValidElement(child)) { return resolveStyles(component, child, config, existingKeyMap, true); } return child; }); }; // Recurse over props, just like children const _resolveProps = function( { component, config, existingKeyMap, props, }, ) { let newProps = props; Object.keys(props).forEach(prop => { // We already recurse over children above if (prop === 'children') { return; } const propValue = props[prop]; if (React.isValidElement(propValue)) { newProps = {...newProps}; newProps[prop] = resolveStyles( component, propValue, config, existingKeyMap, true, ); } }); return newProps; }; const _buildGetKey = function( { componentName, existingKeyMap, renderedElement, }, ) { // We need a unique key to correlate state changes due to user interaction // with the rendered element, so we know to apply the proper interactive // styles. const originalKey = typeof renderedElement.ref === 'string' ? renderedElement.ref : renderedElement.key; const key = getStateKey(originalKey); let alreadyGotKey = false; const getKey = function() { if (alreadyGotKey) { return key; } alreadyGotKey = true; if (existingKeyMap[key]) { let elementName; if (typeof renderedElement.type === 'string') { elementName = renderedElement.type; } else if (renderedElement.type.constructor) { elementName = renderedElement.type.constructor.displayName || renderedElement.type.constructor.name; } throw new Error( 'Radium requires each element with interactive styles to have a unique ' + 'key, set using either the ref or key prop. ' + (originalKey ? 'Key "' + originalKey + '" is a duplicate.' : 'Multiple elements have no key specified.') + ' ' + 'Component: "' + componentName + '". ' + (elementName ? 'Element: "' + elementName + '".' : ''), ); } existingKeyMap[key] = true; return key; }; return getKey; }; const _setStyleState = function(component, key, stateKey, value) { if (!component._radiumIsMounted) { return; } const existing = component._lastRadiumState || (component.state && component.state._radiumStyleState) || {}; const state = {_radiumStyleState: {...existing}}; state._radiumStyleState[key] = {...state._radiumStyleState[key]}; state._radiumStyleState[key][stateKey] = value; component._lastRadiumState = state._radiumStyleState; component.setState(state); }; const _runPlugins = function( { component, config, existingKeyMap, props, renderedElement, }, ) { // Don't run plugins if renderedElement is not a simple ReactDOMElement or has // no style. if ( !React.isValidElement(renderedElement) || typeof renderedElement.type !== 'string' || !props.style ) { return props; } let newProps = props; const plugins = config.plugins || DEFAULT_CONFIG.plugins; const componentName = component.constructor.displayName || component.constructor.name; const getKey = _buildGetKey({ renderedElement, existingKeyMap, componentName, }); const getComponentField = key => component[key]; const getGlobalState = key => globalState[key]; const componentGetState = (stateKey, elementKey) => getState(component.state, elementKey || getKey(), stateKey); const setState = (stateKey, value, elementKey) => _setStyleState(component, elementKey || getKey(), stateKey, value); const addCSS = css => { const styleKeeper = component._radiumStyleKeeper || component.context._radiumStyleKeeper; if (!styleKeeper) { if (__isTestModeEnabled) { return {remove() {}}; } throw new Error( 'To use plugins requiring `addCSS` (e.g. keyframes, media queries), ' + 'please wrap your application in the StyleRoot component. Component ' + 'name: `' + componentName + '`.', ); } return styleKeeper.addCSS(css); }; let newStyle = props.style; plugins.forEach(plugin => { const result = plugin({ ExecutionEnvironment, addCSS, appendImportantToEachValue, componentName, config, cssRuleSetToString, getComponentField, getGlobalState, getState: componentGetState, hash, mergeStyles, props: newProps, setState, isNestedStyle, style: newStyle, }) || {}; newStyle = result.style || newStyle; newProps = result.props && Object.keys(result.props).length ? {...newProps, ...result.props} : newProps; const newComponentFields = result.componentFields || {}; Object.keys(newComponentFields).forEach(fieldName => { component[fieldName] = newComponentFields[fieldName]; }); const newGlobalState = result.globalState || {}; Object.keys(newGlobalState).forEach(key => { globalState[key] = newGlobalState[key]; }); }); if (newStyle !== props.style) { newProps = {...newProps, style: newStyle}; } return newProps; }; // Wrapper around React.cloneElement. To avoid processing the same element // twice, whenever we clone an element add a special prop to make sure we don't // process this element again. const _cloneElement = function(renderedElement, newProps, newChildren) { // Only add flag if this is a normal DOM element if (typeof renderedElement.type === 'string') { newProps = {...newProps, 'data-radium': true}; } return React.cloneElement(renderedElement, newProps, newChildren); }; // // The nucleus of Radium. resolveStyles is called on the rendered elements // before they are returned in render. It iterates over the elements and // children, rewriting props to add event handlers required to capture user // interactions (e.g. mouse over). It also replaces the style prop because it // adds in the various interaction styles (e.g. :hover). // resolveStyles = function( component: any, // ReactComponent, flow+eslint complaining renderedElement: any, // ReactElement config: Config = DEFAULT_CONFIG, existingKeyMap?: {[key: string]: boolean}, shouldCheckBeforeResolve: boolean = false, ): any { // ReactElement existingKeyMap = existingKeyMap || {}; if ( !renderedElement || // Bail if we've already processed this element. This ensures that only the // owner of an element processes that element, since the owner's render // function will be called first (which will always be the case, since you // can't know what else to render until you render the parent component). (renderedElement.props && renderedElement.props['data-radium']) || // Bail if this element is a radium enhanced element, because if it is, // then it will take care of resolving its own styles. (shouldCheckBeforeResolve && !_shouldResolveStyles(renderedElement)) ) { return renderedElement; } const newChildren = _resolveChildren({ children: renderedElement.props.children, component, config, existingKeyMap, }); let newProps = _resolveProps({ component, config, existingKeyMap, props: renderedElement.props, }); newProps = _runPlugins({ component, config, existingKeyMap, props: newProps, renderedElement, }); // If nothing changed, don't bother cloning the element. Might be a bit // wasteful, as we add the sentinal to stop double-processing when we clone. // Assume benign double-processing is better than unneeded cloning. if ( newChildren === renderedElement.props.children && newProps === renderedElement.props ) { return renderedElement; } return _cloneElement( renderedElement, newProps !== renderedElement.props ? newProps : {}, newChildren, ); }; // Only for use by tests let __isTestModeEnabled = false; if (process.env.NODE_ENV !== 'production') { resolveStyles.__clearStateForTests = function() { globalState = {}; }; resolveStyles.__setTestMode = function(isEnabled) { __isTestModeEnabled = isEnabled; }; } export default resolveStyles;
app/javascript/mastodon/features/direct_timeline/components/conversation.js
primenumber/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import StatusContent from 'mastodon/components/status_content'; import AttachmentList from 'mastodon/components/attachment_list'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import DropdownMenuContainer from 'mastodon/containers/dropdown_menu_container'; import AvatarComposite from 'mastodon/components/avatar_composite'; import Permalink from 'mastodon/components/permalink'; import IconButton from 'mastodon/components/icon_button'; import RelativeTimestamp from 'mastodon/components/relative_timestamp'; import { HotKeys } from 'react-hotkeys'; import { autoPlayGif } from 'mastodon/initial_state'; import classNames from 'classnames'; const messages = defineMessages({ more: { id: 'status.more', defaultMessage: 'More' }, open: { id: 'conversation.open', defaultMessage: 'View conversation' }, reply: { id: 'status.reply', defaultMessage: 'Reply' }, markAsRead: { id: 'conversation.mark_as_read', defaultMessage: 'Mark as read' }, delete: { id: 'conversation.delete', defaultMessage: 'Delete conversation' }, muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' }, unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' }, }); export default @injectIntl class Conversation extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { conversationId: PropTypes.string.isRequired, accounts: ImmutablePropTypes.list.isRequired, lastStatus: ImmutablePropTypes.map, unread:PropTypes.bool.isRequired, scrollKey: PropTypes.string, onMoveUp: PropTypes.func, onMoveDown: PropTypes.func, markRead: PropTypes.func.isRequired, delete: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; _updateEmojis () { const node = this.namesNode; if (!node || autoPlayGif) { return; } const emojis = node.querySelectorAll('.custom-emoji'); for (var i = 0; i < emojis.length; i++) { let emoji = emojis[i]; if (emoji.classList.contains('status-emoji')) { continue; } emoji.classList.add('status-emoji'); emoji.addEventListener('mouseenter', this.handleEmojiMouseEnter, false); emoji.addEventListener('mouseleave', this.handleEmojiMouseLeave, false); } } componentDidMount () { this._updateEmojis(); } componentDidUpdate () { this._updateEmojis(); } handleEmojiMouseEnter = ({ target }) => { target.src = target.getAttribute('data-original'); } handleEmojiMouseLeave = ({ target }) => { target.src = target.getAttribute('data-static'); } handleClick = () => { if (!this.context.router) { return; } const { lastStatus, unread, markRead } = this.props; if (unread) { markRead(); } this.context.router.history.push(`/statuses/${lastStatus.get('id')}`); } handleMarkAsRead = () => { this.props.markRead(); } handleReply = () => { this.props.reply(this.props.lastStatus, this.context.router.history); } handleDelete = () => { this.props.delete(); } handleHotkeyMoveUp = () => { this.props.onMoveUp(this.props.conversationId); } handleHotkeyMoveDown = () => { this.props.onMoveDown(this.props.conversationId); } handleConversationMute = () => { this.props.onMute(this.props.lastStatus); } handleShowMore = () => { this.props.onToggleHidden(this.props.lastStatus); } setNamesRef = (c) => { this.namesNode = c; } render () { const { accounts, lastStatus, unread, scrollKey, intl } = this.props; if (lastStatus === null) { return null; } const menu = [ { text: intl.formatMessage(messages.open), action: this.handleClick }, null, ]; menu.push({ text: intl.formatMessage(lastStatus.get('muted') ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMute }); if (unread) { menu.push({ text: intl.formatMessage(messages.markAsRead), action: this.handleMarkAsRead }); menu.push(null); } menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDelete }); const names = accounts.map(a => <Permalink to={`/accounts/${a.get('id')}`} href={a.get('url')} key={a.get('id')} title={a.get('acct')}><bdi><strong className='display-name__html' dangerouslySetInnerHTML={{ __html: a.get('display_name_html') }} /></bdi></Permalink>).reduce((prev, cur) => [prev, ', ', cur]); const handlers = { reply: this.handleReply, open: this.handleClick, moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, toggleHidden: this.handleShowMore, }; return ( <HotKeys handlers={handlers}> <div className={classNames('conversation focusable muted', { 'conversation--unread': unread })} tabIndex='0'> <div className='conversation__avatar' onClick={this.handleClick} role='presentation'> <AvatarComposite accounts={accounts} size={48} /> </div> <div className='conversation__content'> <div className='conversation__content__info'> <div className='conversation__content__relative-time'> {unread && <span className='conversation__unread' />} <RelativeTimestamp timestamp={lastStatus.get('created_at')} /> </div> <div className='conversation__content__names' ref={this.setNamesRef}> <FormattedMessage id='conversation.with' defaultMessage='With {names}' values={{ names: <span>{names}</span> }} /> </div> </div> <StatusContent status={lastStatus} onClick={this.handleClick} expanded={!lastStatus.get('hidden')} onExpandedToggle={this.handleShowMore} collapsable /> {lastStatus.get('media_attachments').size > 0 && ( <AttachmentList compact media={lastStatus.get('media_attachments')} /> )} <div className='status__action-bar'> <IconButton className='status__action-bar-button' title={intl.formatMessage(messages.reply)} icon='reply' onClick={this.handleReply} /> <div className='status__action-bar-dropdown'> <DropdownMenuContainer scrollKey={scrollKey} status={lastStatus} items={menu} icon='ellipsis-h' size={18} direction='right' title={intl.formatMessage(messages.more)} /> </div> </div> </div> </div> </HotKeys> ); } }
app/components/Home.js
firewenda/testwebsite
import React from 'react'; import {Link} from 'react-router'; import HomeStore from '../stores/HomeStore' import HomeActions from '../actions/HomeActions'; import {first, without, findWhere} from 'underscore'; class Home extends React.Component { constructor(props) { super(props); this.state = HomeStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { HomeStore.listen(this.onChange); HomeActions.getTwoCharacters(); } componentWillUnmount() { HomeStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } handleClick(character) { var winner = character.characterId; var loser = first(without(this.state.characters, findWhere(this.state.characters, { characterId: winner }))).characterId; HomeActions.vote(winner, loser); } render() { var characterNodes = this.state.characters.map((character, index) => { return ( <div key={character.characterId} className={index === 0 ? 'col-xs-6 col-sm-6 col-md-5 col-md-offset-1' : 'col-xs-6 col-sm-6 col-md-5'}> <div className='thumbnail fadeInUp animated'> <img onClick={this.handleClick.bind(this, character)} src={'http://image.eveonline.com/Character/' + character.characterId + '_512.jpg'}/> <div className='caption text-center'> <ul className='list-inline'> <li><strong>Race:</strong> {character.race}</li> <li><strong>Bloodline:</strong> {character.bloodline}</li> </ul> <h4> <Link to={'/characters/' + character.characterId}><strong>{character.name}</strong></Link> </h4> </div> </div> </div> ); }); return ( <div className='container'> <h3 className='text-center'>Click on the portrait. Select your favorite.</h3> <div className='row'> {characterNodes} </div> </div> ); } } export default Home;
src/decorators/withSize.js
orionsoft/parts
import React from 'react' import autobind from 'autobind-decorator' import throttle from 'lodash/throttle' export default function(ComposedComponent) { return class WithSize extends React.Component { constructor(props) { super(props) this.state = this.calculateSize() this.debouncedHandle = throttle(this.setNewState, 50) } calculateSize() { const {innerHeight, innerWidth} = window return {innerHeight, innerWidth} } @autobind setNewState() { this.setState(this.calculateSize()) } componentDidMount() { window.addEventListener('resize', this.debouncedHandle) } componentWillUnmount() { window.removeEventListener('resize', this.debouncedHandle) } render() { return <ComposedComponent {...this.props} {...this.state} /> } } }
svg/logo.js
michael-lowe-nz/NBA-battles
import React from 'react' module.exports = () => <svg id="Layer_1" x="0px" y="0px" width="220px" height="220.5px"> <circle fill="#FFFFFF" stroke="#000000" strokeWidth="3" strokeMiterlimit="10" cx="110" cy="110.25" r="93.982"/> <line fill="none" stroke="#000000" strokeWidth="3" strokeMiterlimit="10"/> <g> <path d="M69.178,166.379c-0.062-0.477-0.223-0.906-0.481-1.289c-0.376-0.516-0.959-0.773-1.75-0.773 c-1.128,0-1.899,0.559-2.314,1.676c-0.22,0.592-0.329,1.379-0.329,2.361c0,0.936,0.109,1.688,0.329,2.256 c0.399,1.062,1.151,1.594,2.255,1.594c0.783,0,1.339-0.211,1.668-0.633s0.529-0.969,0.599-1.641h3.41 c-0.078,1.016-0.446,1.977-1.103,2.883c-1.048,1.461-2.601,2.191-4.657,2.191s-3.57-0.609-4.54-1.828s-1.455-2.799-1.455-4.74 c0-2.191,0.536-3.896,1.607-5.115s2.549-1.828,4.434-1.828c1.604,0,2.915,0.359,3.936,1.078s1.624,1.988,1.812,3.809H69.178z"/> <path d="M85.537,173.008c-1.078,1.33-2.715,1.996-4.91,1.996s-3.832-0.666-4.91-1.996c-1.078-1.332-1.617-2.934-1.617-4.807 c0-1.842,0.539-3.439,1.617-4.789s2.715-2.025,4.91-2.025s3.832,0.676,4.91,2.025s1.617,2.947,1.617,4.789 C87.154,170.074,86.615,171.676,85.537,173.008z M82.865,171.162c0.523-0.695,0.785-1.682,0.785-2.961s-0.262-2.266-0.785-2.955 s-1.273-1.035-2.25-1.035s-1.729,0.346-2.256,1.035s-0.791,1.676-0.791,2.955s0.264,2.266,0.791,2.961 c0.527,0.693,1.279,1.041,2.256,1.041S82.342,171.855,82.865,171.162z"/> <path d="M105.482,161.844c0.547,0.219,1.043,0.602,1.488,1.148c0.359,0.445,0.602,0.992,0.727,1.641 c0.078,0.43,0.117,1.059,0.117,1.887l-0.023,8.051h-3.422v-8.133c0-0.484-0.078-0.883-0.234-1.195 c-0.297-0.594-0.844-0.891-1.641-0.891c-0.922,0-1.559,0.383-1.91,1.148c-0.18,0.406-0.27,0.895-0.27,1.465v7.605h-3.363v-7.605 c0-0.758-0.078-1.309-0.234-1.652c-0.281-0.617-0.832-0.926-1.652-0.926c-0.953,0-1.594,0.309-1.922,0.926 c-0.18,0.352-0.27,0.875-0.27,1.57v7.688h-3.387v-12.75h3.246v1.863c0.414-0.664,0.805-1.137,1.172-1.418 c0.648-0.5,1.488-0.75,2.52-0.75c0.977,0,1.766,0.215,2.367,0.645c0.484,0.398,0.852,0.91,1.102,1.535 c0.438-0.75,0.98-1.301,1.629-1.652c0.688-0.352,1.453-0.527,2.297-0.527C104.381,161.516,104.936,161.625,105.482,161.844z"/> <path d="M121.627,163.168c1.042,1.102,1.562,2.719,1.562,4.852c0,2.25-0.509,3.965-1.527,5.145s-2.33,1.77-3.934,1.77 c-1.022,0-1.871-0.254-2.548-0.762c-0.369-0.281-0.731-0.691-1.085-1.23v6.656h-3.305v-17.801h3.199v1.887 c0.361-0.555,0.747-0.992,1.156-1.312c0.746-0.57,1.635-0.855,2.665-0.855C119.313,161.516,120.585,162.066,121.627,163.168z M119.063,165.57c-0.454-0.758-1.19-1.137-2.208-1.137c-1.224,0-2.064,0.574-2.521,1.723c-0.237,0.609-0.355,1.383-0.355,2.32 c0,1.484,0.398,2.527,1.194,3.129c0.474,0.352,1.034,0.527,1.682,0.527c0.939,0,1.656-0.359,2.149-1.078s0.74-1.676,0.74-2.871 C119.744,167.199,119.518,166.328,119.063,165.57z"/> <path d="M130.604,166.801c0.621-0.078,1.065-0.176,1.334-0.293c0.479-0.203,0.72-0.52,0.72-0.949c0-0.523-0.185-0.885-0.553-1.084 s-0.908-0.299-1.621-0.299c-0.8,0-1.366,0.195-1.698,0.586c-0.238,0.289-0.396,0.68-0.476,1.172h-3.223 c0.07-1.117,0.385-2.035,0.941-2.754c0.887-1.125,2.409-1.688,4.566-1.688c1.404,0,2.652,0.277,3.743,0.832 s1.636,1.602,1.636,3.141v5.859c0,0.406,0.008,0.898,0.023,1.477c0.023,0.438,0.09,0.734,0.199,0.891s0.273,0.285,0.492,0.387 v0.492h-3.633c-0.102-0.258-0.172-0.5-0.211-0.727s-0.07-0.484-0.094-0.773c-0.464,0.5-0.998,0.926-1.604,1.277 c-0.723,0.414-1.54,0.621-2.451,0.621c-1.163,0-2.124-0.33-2.882-0.99c-0.759-0.66-1.138-1.596-1.138-2.807 c0-1.57,0.61-2.707,1.83-3.41c0.669-0.383,1.652-0.656,2.951-0.82L130.604,166.801z M132.646,168.359 c-0.214,0.133-0.43,0.24-0.647,0.322s-0.517,0.158-0.897,0.229l-0.76,0.141c-0.713,0.125-1.225,0.277-1.535,0.457 c-0.526,0.305-0.789,0.777-0.789,1.418c0,0.57,0.16,0.982,0.482,1.236c0.32,0.254,0.711,0.381,1.172,0.381 c0.729,0,1.401-0.211,2.017-0.633s0.934-1.191,0.958-2.309V168.359z"/> <path d="M145.988,161.498c0.043,0.004,0.139,0.01,0.287,0.018v3.422c-0.211-0.023-0.398-0.039-0.562-0.047 s-0.297-0.012-0.398-0.012c-1.344,0-2.246,0.438-2.707,1.312c-0.258,0.492-0.387,1.25-0.387,2.273v6.105h-3.363v-12.773h3.188 v2.227c0.516-0.852,0.965-1.434,1.348-1.746c0.625-0.523,1.438-0.785,2.438-0.785C145.893,161.492,145.945,161.494,145.988,161.498 z"/> <path d="M156.556,162.055c0.892,0.4,1.627,1.029,2.208,1.891c0.522,0.758,0.862,1.639,1.018,2.641 c0.09,0.586,0.126,1.432,0.109,2.535h-9.303c0.052,1.281,0.497,2.18,1.336,2.695c0.51,0.32,1.124,0.48,1.842,0.48 c0.761,0,1.379-0.195,1.854-0.586c0.26-0.211,0.489-0.504,0.688-0.879h3.41c-0.09,0.758-0.503,1.527-1.238,2.309 c-1.145,1.242-2.746,1.863-4.806,1.863c-1.7,0-3.199-0.523-4.499-1.572c-1.3-1.047-1.949-2.752-1.949-5.113 c0-2.213,0.587-3.91,1.76-5.09c1.173-1.182,2.695-1.771,4.567-1.771C154.664,161.457,155.665,161.656,156.556,162.055z M151.56,164.939c-0.472,0.488-0.769,1.146-0.89,1.979h5.754c-0.061-0.887-0.357-1.561-0.89-2.02s-1.192-0.688-1.98-0.688 C152.696,164.211,152.031,164.453,151.56,164.939z"/> </g> <g> <path d="M9.853,53.277h15.766l28.57,50.185V53.277h14.014v71.973H53.166l-29.3-51.068v51.068H9.853V53.277z"/> <path d="M135.992,60.943c2.202,3.06,3.304,6.722,3.304,10.986c0,4.395-1.111,7.927-3.333,10.596 c-1.242,1.498-3.072,2.865-5.489,4.102c3.673,1.335,6.444,3.451,8.313,6.348c1.869,2.897,2.804,6.413,2.804,10.547 c0,4.265-1.068,8.089-3.204,11.475c-1.359,2.246-3.059,4.134-5.098,5.664c-2.298,1.758-5.009,2.962-8.132,3.613 c-3.124,0.65-6.514,0.977-10.17,0.977h-32.43V53.277h34.781C126.115,53.407,132.333,55.962,135.992,60.943z M96.913,65.777v15.869 h17.492c3.125,0,5.662-0.594,7.611-1.782c1.949-1.188,2.924-3.296,2.924-6.323c0-3.353-1.289-5.566-3.866-6.641 c-2.223-0.749-5.058-1.123-8.505-1.123H96.913z M96.913,93.56v19.19h17.474c3.12,0,5.551-0.424,7.288-1.27 c3.153-1.562,4.73-4.557,4.73-8.984c0-3.743-1.529-6.315-4.585-7.715c-1.706-0.781-4.104-1.188-7.192-1.221H96.913z"/> <path d="M175.111,53.277h17.017l25.464,71.973h-16.309l-4.749-14.795h-26.505l-4.879,14.795h-15.731L175.111,53.277z M174.12,98.052h18.433l-9.092-28.32L174.12,98.052z"/> </g> </svg>
step7-flux/node_modules/react-router/es6/Lifecycle.js
jintoppy/react-training
'use strict'; import warning from './routerWarning'; import React from 'react'; import invariant from 'invariant'; var object = React.PropTypes.object; /** * The Lifecycle mixin adds the routerWillLeave lifecycle method to a * component that may be used to cancel a transition or prompt the user * for confirmation. * * On standard transitions, routerWillLeave receives a single argument: the * location we're transitioning to. To cancel the transition, return false. * To prompt the user for confirmation, return a prompt message (string). * * During the beforeunload event (assuming you're using the useBeforeUnload * history enhancer), routerWillLeave does not receive a location object * because it isn't possible for us to know the location we're transitioning * to. In this case routerWillLeave must return a prompt message to prevent * the user from closing the window/tab. */ var Lifecycle = { contextTypes: { history: object.isRequired, // Nested children receive the route as context, either // set by the route component using the RouteContext mixin // or by some other ancestor. route: object }, propTypes: { // Route components receive the route object as a prop. route: object }, componentDidMount: function componentDidMount() { process.env.NODE_ENV !== 'production' ? warning(false, 'the `Lifecycle` mixin is deprecated, please use `context.router.setRouteLeaveHook(route, hook)`. http://tiny.cc/router-lifecyclemixin') : undefined; !this.routerWillLeave ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin requires you to define a routerWillLeave method') : invariant(false) : undefined; var route = this.props.route || this.context.route; !route ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin must be used on either a) a <Route component> or ' + 'b) a descendant of a <Route component> that uses the RouteContext mixin') : invariant(false) : undefined; this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute(route, this.routerWillLeave); }, componentWillUnmount: function componentWillUnmount() { if (this._unlistenBeforeLeavingRoute) this._unlistenBeforeLeavingRoute(); } }; export default Lifecycle;