path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
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> // {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> // 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'));
}
|
test/InputSpec.js
|
sheep902/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Input from '../src/Input';
import Button from '../src/Button';
import DropdownButton from '../src/DropdownButton';
import MenuItem from '../src/MenuItem';
import Glyphicon from '../src/Glyphicon';
import {shouldWarn} from './helpers';
describe('Input', () => {
it('renders children when type is not set', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input>
<span />
</Input>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'span'));
assert.throw(instance.getValue);
});
it('renders a select element when type=select', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="select" defaultValue="v">
<option value="v" />
<option value="w" />
</Input>
);
let select = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'select');
assert.ok(select);
assert.equal(React.findDOMNode(select).children.length, 2);
assert.equal(instance.getValue(), 'v');
});
it('renders a textarea element when type=textarea', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="textarea" defaultValue="v" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'textarea'));
assert.equal(instance.getValue(), 'v');
});
it('throws a warning when type=static', () => {
ReactTestUtils.renderIntoDocument(
<Input type="static" value="v" />
);
shouldWarn('deprecated');
});
it('renders an input element of given type when type is anything else', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="text" defaultValue="v" />
);
let node = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'input'));
assert.equal(node.getAttribute('type'), 'text');
assert.equal(instance.getValue(), 'v');
});
it('renders form-group wrapper', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input groupClassName="group" bsStyle="error" />
);
let node = React.findDOMNode(instance);
assert.include(node.className, 'form-group');
assert.include(node.className, 'group');
assert.include(node.className, 'has-error');
});
it('renders label', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input label="Label" labelClassName="label" id="input" />
);
let node = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'label'));
assert.ok(node);
assert.include(node.className, 'label');
assert.equal(node.textContent, 'Label');
assert.equal(node.getAttribute('for'), 'input');
});
it('renders wrapper', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input wrapperClassName="wrapper" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'wrapper'));
});
it('renders input-group', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input addonBefore="$" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group-addon'));
});
it('renders form-group with sm or lg class when bsSize is small or large', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input bsSize="small" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group-sm'));
instance = ReactTestUtils.renderIntoDocument(
<Input bsSize="large" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group-lg'));
});
it('renders input-group with sm or lg class name when bsSize is small or large', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input addonBefore="$" bsSize="small" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group-sm'));
instance = ReactTestUtils.renderIntoDocument(
<Input addonBefore="$" bsSize="large" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group-lg'));
});
it('renders btn-group', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input buttonAfter={<Button>!</Button>} />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group-btn'));
});
it('renders btn-group with dropdown', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input buttonAfter={<DropdownButton title='dropdown' id='herpa-derpa'>
<MenuItem key='1'>One</MenuItem>
</DropdownButton>} />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'input-group-btn'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'btn'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown-menu'));
});
it('renders help', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input help="Help" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'help-block'));
});
it('renders form-group class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-group'));
});
it('renders no form-group class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input standalone />
);
assert.equal(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'form-group').length, 0);
});
it('renders custom-form-group class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input groupClassName='custom-form-class' />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'custom-form-class'));
});
it('renders feedback icon', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input hasFeedback={true} bsStyle="error" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-control-feedback'));
});
it('renders file correctly', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="file" wrapperClassName="wrapper" label="Label" help="h" />
);
let node = React.findDOMNode(instance);
assert.include(node.className, 'form-group');
assert.equal(node.children[0].tagName.toLowerCase(), 'label');
assert.include(node.children[1].className, 'wrapper');
assert.equal(node.children[1].children[0].tagName.toLowerCase(), 'input');
assert.equal(node.children[1].children[0].className, '');
assert.equal(node.children[1].children[0].type, 'file');
assert.equal(node.children[1].children[1].className, 'help-block');
});
it('renders checkbox/radio correctly', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="checkbox" wrapperClassName="wrapper" label="Label" help="h" />
);
let node = React.findDOMNode(instance);
assert.include(node.className, 'form-group');
assert.include(node.children[0].className, 'wrapper');
assert.include(node.children[0].children[0].className, 'checkbox');
assert.equal(node.children[0].children[0].children[0].tagName.toLowerCase(), 'label');
assert.equal(node.children[0].children[0].children[0].children[0].tagName.toLowerCase(), 'input');
assert.include(node.children[0].children[1].className, 'help-block');
});
it('renders non-checkbox/radio correctly', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="text" label="l" wrapperClassName="wrapper" addonAfter="a" hasFeedback={true} help="h"/>
);
let node = React.findDOMNode(instance);
assert.include(node.className, 'form-group');
assert.equal(node.children[0].tagName.toLowerCase(), 'label');
assert.include(node.children[1].className, 'wrapper');
assert.include(node.children[1].children[0].className, 'input-group');
assert.equal(node.children[1].children[0].children[0].tagName.toLowerCase(), 'input');
assert.equal(node.children[1].children[0].children[1].tagName.toLowerCase(), 'span');
assert.include(node.children[1].children[1].className, 'form-control-feedback');
assert.include(node.children[1].children[2].className, 'help-block');
});
it('returns checked value for checkbox/radio', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="checkbox" checked readOnly />
);
assert.equal(instance.getChecked(), true);
});
it('returns the only selected option for select', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="select" value={'one'}>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</Input>
);
assert.equal(instance.getValue(), 'one');
});
it('returns all selected options for multiple select', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="select" multiple value={['one', 'two']}>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</Input>
);
assert.deepEqual(instance.getValue(), ['one', 'two']);
});
it('renders a disabled input correctly', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input type="text" disabled={true} />
);
let node = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'input'));
assert.isNotNull(node.getAttribute('disabled'));
});
context('when Input listens to feedback', () => {
it('renders success feedback as Glyphicon', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input hasFeedback={true} bsStyle="success" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'glyphicon'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'glyphicon-ok'));
});
it('renders warning feedback as Glyphicon', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input hasFeedback={true} bsStyle="warning" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'glyphicon'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'glyphicon-warning-sign'));
});
it('renders error feedback as Glyphicon', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Input hasFeedback={true} bsStyle="error" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'glyphicon'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'glyphicon-remove'));
});
context('when using feedbackIcon', () => {
it('uses the feedbackIcon', () => {
let customIcon = <Glyphicon glyph="star" />;
let instance = ReactTestUtils.renderIntoDocument(
<Input feedbackIcon={customIcon} hasFeedback={true} bsStyle="success" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'glyphicon'));
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'glyphicon-star'));
});
it('adds the .form-control-feedback class for Glyphicons', () => {
let customIcon = <Glyphicon glyph="star" />;
let instance = ReactTestUtils.renderIntoDocument(
<Input feedbackIcon={customIcon} hasFeedback={true} bsStyle="success" />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'form-control-feedback'));
});
});
});
});
|
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;
|
packages/react-percy-test-framework/src/__tests__/Suite-getSnapshotMarkup-tests.js
|
percy/react-percy
|
import React from 'react';
import Suite from '../Suite';
let executed;
let suite;
let parent;
const execute = name => executed.push(name);
const executeAsync = (name, delay) =>
new Promise(resolve => {
setTimeout(() => {
execute(name);
resolve();
}, delay);
});
const givenSyncBeforeAll = (targetSuite, name) => targetSuite.addBeforeAll(() => execute(name));
const givenAsyncBeforeAll = (targetSuite, name, delay = 1) =>
targetSuite.addBeforeAll(() => executeAsync(name, delay));
const givenSyncBeforeEach = (targetSuite, name) => targetSuite.addBeforeEach(() => execute(name));
const givenAsyncBeforeEach = (targetSuite, name, delay = 1) =>
targetSuite.addBeforeEach(() => executeAsync(name, delay));
const givenSyncAfterEach = (targetSuite, name) => targetSuite.addAfterEach(() => execute(name));
const givenAsyncAfterEach = (targetSuite, name, delay = 1) =>
targetSuite.addAfterEach(() => executeAsync(name, delay));
const givenSyncAfterAll = (targetSuite, name) => targetSuite.addAfterAll(() => execute(name));
const givenAsyncAfterAll = (targetSuite, name, delay = 1) =>
targetSuite.addAfterAll(() => executeAsync(name, delay));
const givenSyncSnapshot = (targetSuite, name) =>
targetSuite.addSnapshot({
fullTitle: () => name,
getMarkup: () => {
execute(name);
return {};
},
});
const givenAsyncSnapshot = (targetSuite, name, delay = 1) =>
targetSuite.addSnapshot({
fullTitle: () => name,
getMarkup: async () => {
await executeAsync(name, delay);
return {};
},
});
beforeEach(() => {
executed = [];
suite = new Suite('title');
suite.parent = parent = new Suite('parent');
});
describe('beforeAll hooks', () => {
it('executes synchronous beforeAll hooks in the order specified in the suite before rendering snapshot given snapshot in suite', async () => {
givenSyncBeforeAll(suite, 'beforeAll 1');
givenSyncBeforeAll(suite, 'beforeAll 2');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['beforeAll 1', 'beforeAll 2', 'snapshot']);
});
it('executes asynchronous beforeAll hooks in the order specified in the suite before rendering snapshot given snapshot in suite', async () => {
givenAsyncBeforeAll(suite, 'beforeAll 1', 2);
givenAsyncBeforeAll(suite, 'beforeAll 2', 1);
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['beforeAll 1', 'beforeAll 2', 'snapshot']);
});
it('executes synchronous beforeAll hook before beforeEach hooks in suite before rendering snapshot given snapshot in suite', async () => {
givenSyncBeforeAll(suite, 'beforeAll');
givenSyncBeforeEach(suite, 'beforeEach');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['beforeAll', 'beforeEach', 'snapshot']);
});
it('executes asynchronous beforeAll hook before beforeEach hooks in suite before rendering snapshot given snapshot in suite', async () => {
givenAsyncBeforeAll(suite, 'beforeAll');
givenSyncBeforeEach(suite, 'beforeEach');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['beforeAll', 'beforeEach', 'snapshot']);
});
it('executes synchronous beforeAll hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncBeforeAll(suite, 'beforeAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeAll', 'nested snapshot']);
});
it('executes asynchronous beforeAll hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncBeforeAll(suite, 'beforeAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeAll', 'nested snapshot']);
});
it('executes nested synchronous beforeAll hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncBeforeAll(nested, 'nested beforeAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested beforeAll', 'nested snapshot']);
});
it('executes nested asynchronous beforeAll hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncBeforeAll(nested, 'nested beforeAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested beforeAll', 'nested snapshot']);
});
it('executes synchronous beforeAll hook and nested synchronous beforeAll hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncBeforeAll(suite, 'beforeAll');
givenSyncBeforeAll(nested, 'nested beforeAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeAll', 'nested beforeAll', 'nested snapshot']);
});
it('executes synchronous beforeAll hook and nested asynchronous beforeAll hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncBeforeAll(suite, 'beforeAll');
givenAsyncBeforeAll(nested, 'nested beforeAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeAll', 'nested beforeAll', 'nested snapshot']);
});
it('executes asynchronous beforeAll hook and nested synchronous beforeAll hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncBeforeAll(suite, 'beforeAll');
givenSyncBeforeAll(nested, 'nested beforeAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeAll', 'nested beforeAll', 'nested snapshot']);
});
it('executes asynchronous beforeAll hook and nested asynchronous beforeAll hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncBeforeAll(suite, 'beforeAll');
givenAsyncBeforeAll(nested, 'nested beforeAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeAll', 'nested beforeAll', 'nested snapshot']);
});
});
describe('beforeEach hooks', () => {
it('executes synchronous beforeEach hooks in the order specified in the suite before rendering snapshot given snapshot in suite', async () => {
givenSyncBeforeEach(suite, 'beforeEach 1');
givenSyncBeforeEach(suite, 'beforeEach 2');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['beforeEach 1', 'beforeEach 2', 'snapshot']);
});
it('executes asynchronous beforeEach hooks in the order specified in the suite before rendering snapshot given snapshot in suite', async () => {
givenAsyncBeforeEach(suite, 'beforeEach 1', 2);
givenAsyncBeforeEach(suite, 'beforeEach 2', 1);
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['beforeEach 1', 'beforeEach 2', 'snapshot']);
});
it('executes synchronous beforeEach hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncBeforeEach(suite, 'beforeEach');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeEach', 'nested snapshot']);
});
it('executes asynchronous beforeEach hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncBeforeEach(suite, 'beforeEach');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeEach', 'nested snapshot']);
});
it('executes nested synchronous beforeEach hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncBeforeEach(nested, 'nested beforeEach');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested beforeEach', 'nested snapshot']);
});
it('executes nested asynchronous beforeEach hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncBeforeEach(nested, 'nested beforeEach');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested beforeEach', 'nested snapshot']);
});
it('executes synchronous beforeEach hook and nested synchronous beforeEach hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncBeforeEach(suite, 'beforeEach');
givenSyncBeforeEach(nested, 'nested beforeEach');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeEach', 'nested beforeEach', 'nested snapshot']);
});
it('executes synchronous beforeEach hook and nested asynchronous beforeEach hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncBeforeEach(suite, 'beforeEach');
givenAsyncBeforeEach(nested, 'nested beforeEach');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeEach', 'nested beforeEach', 'nested snapshot']);
});
it('executes asynchronous beforeEach hook and nested synchronous beforeEach hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncBeforeEach(suite, 'beforeEach');
givenSyncBeforeEach(nested, 'nested beforeEach');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeEach', 'nested beforeEach', 'nested snapshot']);
});
it('executes asynchronous beforeEach hook and nested asynchronous beforeEach hook before rendering snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncBeforeEach(suite, 'beforeEach');
givenAsyncBeforeEach(nested, 'nested beforeEach');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['beforeEach', 'nested beforeEach', 'nested snapshot']);
});
});
describe('afterEach hooks', () => {
it('executes synchronous afterEach hooks in the order specified in the suite after rendering sync snapshot given snapshot in suite', async () => {
givenSyncAfterEach(suite, 'afterEach 1');
givenSyncAfterEach(suite, 'afterEach 2');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach 1', 'afterEach 2']);
});
it('executes synchronous afterEach hooks in the order specified in the suite after rendering async snapshot given snapshot in suite', async () => {
givenSyncAfterEach(suite, 'afterEach 1');
givenSyncAfterEach(suite, 'afterEach 2');
givenAsyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach 1', 'afterEach 2']);
});
it('executes asynchronous afterEach hooks in the order specified in the suite after rendering sync snapshot given snapshot in suite', async () => {
givenAsyncAfterEach(suite, 'afterEach 1', 2);
givenAsyncAfterEach(suite, 'afterEach 2', 1);
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach 1', 'afterEach 2']);
});
it('executes asynchronous afterEach hooks in the order specified in the suite after rendering async snapshot given snapshot in suite', async () => {
givenAsyncAfterEach(suite, 'afterEach 1', 2);
givenAsyncAfterEach(suite, 'afterEach 2', 1);
givenAsyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach 1', 'afterEach 2']);
});
it('executes synchronous parent afterEach hook after rendering sync snapshot given snapshot in suite', async () => {
givenSyncAfterEach(parent, 'parent afterEach');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'parent afterEach']);
});
it('executes synchronous parent afterEach hook after rendering async snapshot given snapshot in suite', async () => {
givenSyncAfterEach(parent, 'parent afterEach');
givenAsyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'parent afterEach']);
});
it('executes asynchronous parent afterEach hook after rendering sync snapshot given snapshot in suite', async () => {
givenAsyncAfterEach(parent, 'parent afterEach');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'parent afterEach']);
});
it('executes asynchronous parent afterEach hook after rendering async snapshot given snapshot in suite', async () => {
givenAsyncAfterEach(parent, 'parent afterEach');
givenAsyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'parent afterEach']);
});
it('executes synchronous parent afterEach hook after sync suite afterEach hook after rendering sync snapshot given snapshot in suite', async () => {
givenSyncAfterEach(parent, 'parent afterEach');
givenSyncAfterEach(suite, 'afterEach');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'parent afterEach']);
});
it('executes synchronous parent afterEach hook after sync suite afterEach hook after rendering async snapshot given snapshot in suite', async () => {
givenSyncAfterEach(parent, 'parent afterEach');
givenSyncAfterEach(suite, 'afterEach');
givenAsyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'parent afterEach']);
});
it('executes synchronous parent afterEach hook after async suite afterEach hook after rendering sync snapshot given snapshot in suite', async () => {
givenSyncAfterEach(parent, 'parent afterEach');
givenAsyncAfterEach(suite, 'afterEach');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'parent afterEach']);
});
it('executes synchronous parent afterEach hook after async suite afterEach hook after rendering async snapshot given snapshot in suite', async () => {
givenSyncAfterEach(parent, 'parent afterEach');
givenAsyncAfterEach(suite, 'afterEach');
givenAsyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'parent afterEach']);
});
it('executes asynchronous parent afterEach hook after sync suite afterEach hook after rendering sync snapshot given snapshot in suite', async () => {
givenAsyncAfterEach(parent, 'parent afterEach');
givenSyncAfterEach(suite, 'afterEach');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'parent afterEach']);
});
it('executes asynchronous parent afterEach hook after sync suite afterEach hook after rendering async snapshot given snapshot in suite', async () => {
givenAsyncAfterEach(parent, 'parent afterEach');
givenSyncAfterEach(suite, 'afterEach');
givenAsyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'parent afterEach']);
});
it('executes asynchronous parent afterEach hook after async suite afterEach hook after rendering sync snapshot given snapshot in suite', async () => {
givenAsyncAfterEach(parent, 'parent afterEach');
givenAsyncAfterEach(suite, 'afterEach');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'parent afterEach']);
});
it('executes asynchronous parent afterEach hook after async suite afterEach hook after rendering async snapshot given snapshot in suite', async () => {
givenAsyncAfterEach(parent, 'parent afterEach');
givenAsyncAfterEach(suite, 'afterEach');
givenAsyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'parent afterEach']);
});
});
describe('afterAll hooks', () => {
it('executes synchronous afterAll hooks in the order specified in the suite after rendering sync snapshot given snapshot in suite', async () => {
givenSyncAfterAll(suite, 'afterAll 1');
givenSyncAfterAll(suite, 'afterAll 2');
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterAll 1', 'afterAll 2']);
});
it('executes synchronous afterAll hooks in the order specified in the suite after rendering async snapshot given snapshot in suite', async () => {
givenSyncAfterAll(suite, 'afterAll 1');
givenSyncAfterAll(suite, 'afterAll 2');
givenAsyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterAll 1', 'afterAll 2']);
});
it('executes asynchronous afterAll hooks in the order specified in the suite after rendering sync snapshot given snapshot in suite', async () => {
givenAsyncAfterAll(suite, 'afterAll 1', 2);
givenAsyncAfterAll(suite, 'afterAll 2', 1);
givenSyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterAll 1', 'afterAll 2']);
});
it('executes asynchronous afterAll hooks in the order specified in the suite after rendering async snapshot given snapshot in suite', async () => {
givenAsyncAfterAll(suite, 'afterAll 1', 2);
givenAsyncAfterAll(suite, 'afterAll 2', 1);
givenAsyncSnapshot(suite, 'snapshot');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterAll 1', 'afterAll 2']);
});
it('executes synchronous afterAll hook after sync afterEach hooks in suite after rendering sync snapshot given snapshot in suite', async () => {
givenSyncSnapshot(suite, 'snapshot');
givenSyncAfterEach(suite, 'afterEach');
givenSyncAfterAll(suite, 'afterAll');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'afterAll']);
});
it('executes synchronous afterAll hook after sync afterEach hooks in suite after rendering async snapshot given snapshot in suite', async () => {
givenAsyncSnapshot(suite, 'snapshot');
givenSyncAfterEach(suite, 'afterEach');
givenSyncAfterAll(suite, 'afterAll');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'afterAll']);
});
it('executes synchronous afterAll hook after async afterEach hooks in suite after rendering sync snapshot given snapshot in suite', async () => {
givenSyncSnapshot(suite, 'snapshot');
givenAsyncAfterEach(suite, 'afterEach');
givenSyncAfterAll(suite, 'afterAll');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'afterAll']);
});
it('executes synchronous afterAll hook after async afterEach hooks in suite after rendering async snapshot given snapshot in suite', async () => {
givenAsyncSnapshot(suite, 'snapshot');
givenAsyncAfterEach(suite, 'afterEach');
givenSyncAfterAll(suite, 'afterAll');
await suite.getSnapshotMarkup('snapshot');
expect(executed).toEqual(['snapshot', 'afterEach', 'afterAll']);
});
it('executes synchronous afterAll hook after nested snapshot sync afterAll hook after rendering sync snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncAfterAll(suite, 'afterAll');
givenSyncAfterAll(nested, 'nested afterAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested snapshot', 'nested afterAll', 'afterAll']);
});
it('executes synchronous afterAll hook after nested snapshot sync afterAll hook after rendering async snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncAfterAll(suite, 'afterAll');
givenSyncAfterAll(nested, 'nested afterAll');
givenAsyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested snapshot', 'nested afterAll', 'afterAll']);
});
it('executes synchronous afterAll hook after nested snapshot async afterAll hook after rendering sync snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncAfterAll(suite, 'afterAll');
givenAsyncAfterAll(nested, 'nested afterAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested snapshot', 'nested afterAll', 'afterAll']);
});
it('executes synchronous afterAll hook after nested snapshot async afterAll hook after rendering async snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenSyncAfterAll(suite, 'afterAll');
givenAsyncAfterAll(nested, 'nested afterAll');
givenAsyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested snapshot', 'nested afterAll', 'afterAll']);
});
it('executes asynchronous afterAll hook after nested snapshot sync afterAll hook after rendering sync snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncAfterAll(suite, 'afterAll');
givenSyncAfterAll(nested, 'nested afterAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested snapshot', 'nested afterAll', 'afterAll']);
});
it('executes asynchronous afterAll hook after nested snapshot sync afterAll hook after rendering async snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncAfterAll(suite, 'afterAll');
givenSyncAfterAll(nested, 'nested afterAll');
givenAsyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested snapshot', 'nested afterAll', 'afterAll']);
});
it('executes asynchronous afterAll hook after nested snapshot async afterAll hook after rendering sync snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncAfterAll(suite, 'afterAll');
givenAsyncAfterAll(nested, 'nested afterAll');
givenSyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested snapshot', 'nested afterAll', 'afterAll']);
});
it('executes asynchronous afterAll hook after nested snapshot async afterAll hook after rendering async snapshot given snapshot in nested suite', async () => {
const nested = new Suite('nested');
suite.addSuite(nested);
givenAsyncAfterAll(suite, 'afterAll');
givenAsyncAfterAll(nested, 'nested afterAll');
givenAsyncSnapshot(nested, 'nested snapshot');
await suite.getSnapshotMarkup('nested snapshot');
expect(executed).toEqual(['nested snapshot', 'nested afterAll', 'afterAll']);
});
});
describe('getSnapshotMarkup', () => {
it('returns snapshot markup given sync snapshot in suite', async () => {
const markup = <div>markup</div>;
suite.addSnapshot({
fullTitle: () => 'snapshot',
getMarkup: () => markup,
});
const snapshotMarkup = await suite.getSnapshotMarkup('snapshot');
expect(snapshotMarkup).toBe(markup);
});
it('returns snapshot markup given async snapshot in suite', async () => {
const markup = <div>markup</div>;
suite.addSnapshot({
fullTitle: () => 'snapshot',
getMarkup: async () => {
await executeAsync('something', 1);
return markup;
},
});
const snapshotMarkup = await suite.getSnapshotMarkup('snapshot');
expect(snapshotMarkup).toBe(markup);
});
it('returns snapshot markup given sync snapshot in nested suite', async () => {
const nestedSuite = new Suite('nested');
suite.addSuite(nestedSuite);
const markup = <div>markup</div>;
nestedSuite.addSnapshot({
fullTitle: () => 'nested snapshot',
getMarkup: () => markup,
});
const snapshotMarkup = await suite.getSnapshotMarkup('nested snapshot');
expect(snapshotMarkup).toBe(markup);
});
it('returns snapshot markup given async snapshot in nested suite', async () => {
const nestedSuite = new Suite('nested');
suite.addSuite(nestedSuite);
const markup = <div>markup</div>;
nestedSuite.addSnapshot({
fullTitle: () => 'nested snapshot',
getMarkup: async () => {
await executeAsync('something', 1);
return markup;
},
});
const snapshotMarkup = await suite.getSnapshotMarkup('nested snapshot');
expect(snapshotMarkup).toBe(markup);
});
it('rejects when no snapshot with given title is in suite or nested suites', async () => {
const nestedSuite = new Suite('nested');
suite.addSuite(nestedSuite);
await expect(suite.getSnapshotMarkup('non-existent snapshot')).rejects.toBeDefined();
});
});
|
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>
);
}
}
|
spec/react/copy-to-clipboard/copy_to_clipboard.spec.js
|
pivotal-cf/pivotal-ui
|
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {setProps} from '../../support/jest-helpers';
import {CopyToClipboard} from '../../../src/react/copy-to-clipboard';
import ClipboardHelper from '../../../src/react/copy-to-clipboard/clipboard_helper';
jest.useFakeTimers();
describe('CopyToClipboard', () => {
let text, onClick, subject;
beforeEach(() => {
text = 'some copy text';
onClick = jasmine.createSpy('onClick');
spyOn(ClipboardHelper, 'copy');
subject = ReactDOM.render(<CopyToClipboard {...{
text,
onClick
}}/>, root);
});
it('renders an anchor', () => {
expect('a.pui-copy-to-clipboard').toExist();
expect('a.pui-copy-to-clipboard').toHaveAttr('role', 'button');
});
it('renders a hidden tooltip with default text', () => {
expect('.tooltip-container').toHaveClass('tooltip-container-hidden');
expect('.tooltip-content').toHaveText('Copied');
});
describe('when given tooltip text', () => {
beforeEach(() => {
subject::setProps({tooltip: 'Copied successfully!'});
});
it('uses the custom tooltip text', () => {
expect('.tooltip-content').toHaveText('Copied successfully!');
});
});
describe('when given tooltipPlacement', () => {
beforeEach(() => {
subject::setProps({tooltipPlacement: 'right'});
});
it('places the tooltip where specified', () => {
expect('.tooltip.tooltip-right').toHaveText('Copied');
});
});
describe('when given additional props', () => {
beforeEach(() => {
subject::setProps({className: 'test-class', id: 'test-id', style: {opacity: '0.5'}});
});
it('passes the props to the anchor', () => {
expect('a.pui-copy-to-clipboard').toHaveClass('test-class');
expect('a.pui-copy-to-clipboard').toHaveAttr('id', 'test-id');
expect('a.pui-copy-to-clipboard').toHaveCss({opacity: '0.5'});
});
});
describe('clicking on the element', () => {
beforeEach(() => {
$('.pui-copy-to-clipboard .tooltip').click();
$('.pui-copy-to-clipboard').click();
});
it('makes tooltip visible', () => {
expect('.tooltip-container').toHaveClass('tooltip-container-visible');
});
it('hides tooltip after 1 seconds', () => {
jest.advanceTimersByTime(2000);
expect('.tooltip-container').not.toHaveClass('tooltip-container-visible');
});
it('copies the text to the clipboard', () => {
expect(ClipboardHelper.copy).toHaveBeenCalledWith(document, text);
});
it('calls the provided callback', () => {
expect(onClick).toHaveBeenCalled();
});
});
});
|
tests/routes/Home/components/HomeView.spec.js
|
shinja/react-redux-c3
|
import React from 'react'
import { HomeView } from 'routes/Home/components/HomeView'
import { render } from 'enzyme'
describe('(View) Home', () => {
let _component
beforeEach(() => {
_component = render(<HomeView />)
})
it('Renders a welcome message', () => {
const welcome = _component.find('h4')
expect(welcome).to.exist
expect(welcome.text()).to.match(/Welcome!/)
})
it('Renders an awesome duck image', () => {
const duck = _component.find('img')
expect(duck).to.exist
expect(duck.attr('alt')).to.match(/This is a duck, because Redux!/)
})
})
|
__tests__/Style-04.js
|
buildbreakdo/style-it
|
import React from 'react';
import { findDOMNode, render } from 'react-dom';
import TestUtils from 'react-addons-test-utils';
const removeNewlines = (string) => (string.replace(/(\r\n|\n|\r)/gm, ''))
import Style from '../src/index.js';
describe('Style-04', () => {
it('creates a contains selector scope when selector targets nothing and no root selector is present', () => {
const wrapper = TestUtils.renderIntoDocument(
<div>
<Style>
{`
.foo {
color: red;
}
`}
<div>
<div></div>
</div>
</Style>
</div>
);
const rootNode = findDOMNode(wrapper).children[0];
const styleNode = rootNode.children[0];
const scopedClass = rootNode.className.split(' ').slice(-1)[0];
expect(rootNode.className).toEqual(`${scopedClass}`);
expect(removeNewlines(styleNode.textContent)).toEqual(`.${scopedClass} .foo { color: red; }`);
});
});
|
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;
|
src/components/TextInput/index.js
|
IDEOorg/steps-guide-builder
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import './index.less';
export default class TextInput extends Component {
constructor(props) {
super(props);
this.state = {value: this.props.value ? this.props.value : ""};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({value: e.target.value}, () => {
if(this.props.onChange) {
this.props.onChange(this.state.value);
}
});
}
render() {
return (
<input className={classNames(this.props.className, "textinput")}
type="text" value={this.state.value}
onChange={this.handleChange}
placeholder={this.props.placeholder}
ref={this.props.parentRef}
/>
);
}
}
TextInput.propTypes = {
value: PropTypes.string,
onChange: PropTypes.func.isRequired,
className: PropTypes.string,
placeholder: PropTypes.string
};
TextInput.displayName = 'TextInput';
|
src/client.js
|
twomoonsfactory/custom-poll
|
/**
* THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER.
*/
import 'babel/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import createHistory from 'history/lib/createBrowserHistory';
import useScroll from 'scroll-behavior/lib/useStandardScroll';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import io from 'socket.io-client';
import {Provider} from 'react-redux';
import {reduxReactRouter, ReduxRouter} from 'redux-router';
import getRoutes from './routes';
import makeRouteHooksSafe from './helpers/makeRouteHooksSafe';
const client = new ApiClient();
// Three different types of scroll behavior available.
// Documented here: https://github.com/rackt/scroll-behavior
const scrollablehistory = useScroll(createHistory);
const dest = document.getElementById('content');
const store = createStore(reduxReactRouter, makeRouteHooksSafe(getRoutes), scrollablehistory, client, window.__data);
function initSocket() {
const socket = io('', {path: '/api/ws', transports: ['polling']});
socket.on('news', (data) => {
console.log(data);
socket.emit('my other event', { my: 'data from client' });
});
socket.on('msg', (data) => {
console.log(data);
});
return socket;
}
global.socket = initSocket();
const component = (
<ReduxRouter routes={getRoutes(store)} />
);
ReactDOM.render(
<Provider store={store} key="provider">
{component}
</Provider>,
dest
);
if (process.env.NODE_ENV !== 'production') {
window.React = React; // enable debugger
if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) {
console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
}
}
if (__DEVTOOLS__ && !window.devToolsExtension) {
const DevTools = require('./containers/DevTools/DevTools');
ReactDOM.render(
<Provider store={store} key="provider">
<div>
{component}
<DevTools />
</div>
</Provider>,
dest
);
}
|
blueocean-material-icons/src/js/components/svg-icons/social/person-outline.js
|
kzantow/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const SocialPersonOutline = (props) => (
<SvgIcon {...props}>
<path d="M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z"/>
</SvgIcon>
);
SocialPersonOutline.displayName = 'SocialPersonOutline';
SocialPersonOutline.muiName = 'SvgIcon';
export default SocialPersonOutline;
|
node_modules/react-bootstrap/es/ButtonGroup.js
|
okristian1/react-info
|
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 all from 'react-prop-types/lib/all';
import Button from './Button';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
vertical: React.PropTypes.bool,
justified: React.PropTypes.bool,
/**
* Display block buttons; only useful when used with the "vertical" prop.
* @type {bool}
*/
block: all(React.PropTypes.bool, function (_ref) {
var block = _ref.block,
vertical = _ref.vertical;
return block && !vertical ? new Error('`block` requires `vertical` to be set to have any effect') : null;
})
};
var defaultProps = {
block: false,
justified: false,
vertical: false
};
var ButtonGroup = function (_React$Component) {
_inherits(ButtonGroup, _React$Component);
function ButtonGroup() {
_classCallCheck(this, ButtonGroup);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ButtonGroup.prototype.render = function render() {
var _extends2;
var _props = this.props,
block = _props.block,
justified = _props.justified,
vertical = _props.vertical,
className = _props.className,
props = _objectWithoutProperties(_props, ['block', 'justified', 'vertical', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps)] = !vertical, _extends2[prefix(bsProps, 'vertical')] = vertical, _extends2[prefix(bsProps, 'justified')] = justified, _extends2[prefix(Button.defaultProps, 'block')] = block, _extends2));
return React.createElement('div', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return ButtonGroup;
}(React.Component);
ButtonGroup.propTypes = propTypes;
ButtonGroup.defaultProps = defaultProps;
export default bsClass('btn-group', ButtonGroup);
|
packages/reactor-kitchensink/src/examples/Charts/3DColumn/Basic3DColumn/Basic3DColumn.js
|
sencha/extjs-reactor
|
import React, { Component } from 'react';
import { Container } from '@extjs/ext-react';
import { Cartesian } from '@extjs/ext-react-charts';
import ChartToolbar from '../../ChartToolbar';
import createData from './createData';
Ext.require([
'Ext.chart.interactions.PanZoom',
'Ext.chart.axis.Numeric',
'Ext.chart.axis.Category',
'Ext.chart.axis.Numeric3D',
'Ext.chart.grid.HorizontalGrid3D',
'Ext.chart.series.Bar3D',
'Ext.chart.axis.Category3D'
]);
export default class Basic3DColumnChartExample extends Component {
constructor() {
super();
this.refresh();
}
store = Ext.create('Ext.data.Store', {
fields: ['id', 'g0', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'name']
});
state = {
theme: 'default'
};
refresh = () => {
this.store.loadData(createData(15));
}
changeTheme = theme => this.setState({theme})
render() {
const { theme } = this.state;
return (
<Container padding={!Ext.os.is.Phone && 10} layout="fit">
<ChartToolbar
onThemeChange={this.changeTheme}
onRefreshClick={this.refresh}
theme={theme}
/>
<Cartesian
shadow
store={this.store}
theme={theme}
series={{
type: 'bar3d',
xField: 'name',
yField: ['g1', 'g2', 'g3']
}}
axes={[{
type: 'numeric3d',
position: 'left',
fields: ['g1', 'g2', 'g3'],
grid: true,
label: {
rotate: {
degrees: -30
}
}
}, {
type: 'category3d',
position: 'bottom',
fields: 'name'
}]}
/>
</Container>
)
}
}
|
app/containers/App/index.js
|
nandakishore2009/smart-will
|
/**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import Helmet from 'react-helmet';
import withProgressBar from 'components/ProgressBar';
import Header from 'components/Header';
import Footer from 'components/Footer';
class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div>
<Helmet
titleTemplate="%s - Smart Will"
defaultTitle="Smart Will"
meta={[
{ name: 'description', content: 'Make your will' },
]}
/>
<Header />
{React.Children.toArray(this.props.children)}
<Footer />
</div>
);
}
}
export default withProgressBar(App);
|
modules/RouteContext.js
|
andreftavares/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
|
app/javascript/mastodon/features/pinned_statuses/index.js
|
Arukas/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchPinnedStatuses } from '../../actions/pin_statuses';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import StatusList from '../../components/status_list';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'column.pins', defaultMessage: 'Pinned toot' },
});
const mapStateToProps = state => ({
statusIds: state.getIn(['status_lists', 'pins', 'items']),
hasMore: !!state.getIn(['status_lists', 'pins', 'next']),
});
@connect(mapStateToProps)
@injectIntl
export default class PinnedStatuses extends ImmutablePureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
intl: PropTypes.object.isRequired,
hasMore: PropTypes.bool.isRequired,
};
componentWillMount () {
this.props.dispatch(fetchPinnedStatuses());
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
render () {
const { intl, statusIds, hasMore } = this.props;
return (
<Column icon='thumb-tack' heading={intl.formatMessage(messages.heading)} ref={this.setRef}>
<ColumnBackButtonSlim />
<StatusList
statusIds={statusIds}
scrollKey='pinned_statuses'
hasMore={hasMore}
/>
</Column>
);
}
}
|
src/PaginationButton.js
|
xsistens/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import createSelectedEvent from './utils/createSelectedEvent';
import CustomPropTypes from './utils/CustomPropTypes';
const PaginationButton = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
className: React.PropTypes.string,
eventKey: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]),
onSelect: React.PropTypes.func,
disabled: React.PropTypes.bool,
active: React.PropTypes.bool,
/**
* You can use a custom element for this component
*/
buttonComponentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
active: false,
disabled: false
};
},
handleClick(event) {
if (this.props.disabled) {
return;
}
if (this.props.onSelect) {
let selectedEvent = createSelectedEvent(this.props.eventKey);
this.props.onSelect(event, selectedEvent);
}
},
render() {
let classes = {
active: this.props.active,
disabled: this.props.disabled,
...this.getBsClassSet()
};
let {
className,
...anchorProps
} = this.props;
let ButtonComponentClass = this.props.buttonComponentClass;
return (
<li className={classNames(className, classes)}>
<ButtonComponentClass
{...anchorProps}
onClick={this.handleClick} />
</li>
);
}
});
export default PaginationButton;
|
src/svg-icons/social/party-mode.js
|
lawrence-yu/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPartyMode = (props) => (
<SvgIcon {...props}>
<path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 3c1.63 0 3.06.79 3.98 2H12c-1.66 0-3 1.34-3 3 0 .35.07.69.18 1H7.1c-.06-.32-.1-.66-.1-1 0-2.76 2.24-5 5-5zm0 10c-1.63 0-3.06-.79-3.98-2H12c1.66 0 3-1.34 3-3 0-.35-.07-.69-.18-1h2.08c.07.32.1.66.1 1 0 2.76-2.24 5-5 5z"/>
</SvgIcon>
);
SocialPartyMode = pure(SocialPartyMode);
SocialPartyMode.displayName = 'SocialPartyMode';
SocialPartyMode.muiName = 'SvgIcon';
export default SocialPartyMode;
|
app/javascript/mastodon/components/account.js
|
narabo/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Avatar from './avatar';
import DisplayName from './display_name';
import Permalink from './permalink';
import IconButton from './icon_button';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
follow: { id: 'account.follow', defaultMessage: 'Follow' },
unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' },
requested: { id: 'account.requested', defaultMessage: 'Awaiting approval' },
unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' },
unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' },
});
class Account extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
me: PropTypes.number.isRequired,
onFollow: PropTypes.func.isRequired,
onBlock: PropTypes.func.isRequired,
onMute: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleFollow = () => {
this.props.onFollow(this.props.account);
}
handleBlock = () => {
this.props.onBlock(this.props.account);
}
handleMute = () => {
this.props.onMute(this.props.account);
}
render () {
const { account, me, intl } = this.props;
if (!account) {
return <div />;
}
let buttons;
if (account.get('id') !== me && account.get('relationship', null) !== null) {
const following = account.getIn(['relationship', 'following']);
const requested = account.getIn(['relationship', 'requested']);
const blocking = account.getIn(['relationship', 'blocking']);
const muting = account.getIn(['relationship', 'muting']);
if (requested) {
buttons = <IconButton disabled={true} icon='hourglass' title={intl.formatMessage(messages.requested)} />;
} else if (blocking) {
buttons = <IconButton active={true} icon='unlock-alt' title={intl.formatMessage(messages.unblock, { name: account.get('username') })} onClick={this.handleBlock} />;
} else if (muting) {
buttons = <IconButton active={true} icon='volume-up' title={intl.formatMessage(messages.unmute, { name: account.get('username') })} onClick={this.handleMute} />;
} else {
buttons = <IconButton icon={following ? 'user-times' : 'user-plus'} title={intl.formatMessage(following ? messages.unfollow : messages.follow)} onClick={this.handleFollow} active={following} />;
}
}
return (
<div className='account'>
<div className='account__wrapper'>
<Permalink key={account.get('id')} className='account__display-name' href={account.get('url')} to={`/accounts/${account.get('id')}`}>
<div className='account__avatar-wrapper'><Avatar src={account.get('avatar')} staticSrc={account.get('avatar_static')} size={36} /></div>
<DisplayName account={account} />
</Permalink>
<div className='account__relationship'>
{buttons}
</div>
</div>
</div>
);
}
}
export default injectIntl(Account);
|
src/svg-icons/editor/border-horizontal.js
|
pancho111203/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderHorizontal = (props) => (
<SvgIcon {...props}>
<path d="M3 21h2v-2H3v2zM5 7H3v2h2V7zM3 17h2v-2H3v2zm4 4h2v-2H7v2zM5 3H3v2h2V3zm4 0H7v2h2V3zm8 0h-2v2h2V3zm-4 4h-2v2h2V7zm0-4h-2v2h2V3zm6 14h2v-2h-2v2zm-8 4h2v-2h-2v2zm-8-8h18v-2H3v2zM19 3v2h2V3h-2zm0 6h2V7h-2v2zm-8 8h2v-2h-2v2zm4 4h2v-2h-2v2zm4 0h2v-2h-2v2z"/>
</SvgIcon>
);
EditorBorderHorizontal = pure(EditorBorderHorizontal);
EditorBorderHorizontal.displayName = 'EditorBorderHorizontal';
EditorBorderHorizontal.muiName = 'SvgIcon';
export default EditorBorderHorizontal;
|
src/js/components/tabs/tab_button.js
|
working-minds/realizejs
|
import React, { Component } from 'react';
import PropTypes from '../../prop_types';
import { mixin } from '../../utils/decorators';
import {
CssClassMixin,
ContainerMixin,
FormContainerMixin
} from '../../mixins';
@mixin(
CssClassMixin,
ContainerMixin,
FormContainerMixin
)
export default class TabButton extends Component {
static propTypes = {
id: PropTypes.string,
title: PropTypes.string,
active: PropTypes.bool
};
static defaultProps = {
themeClassKey: 'tabs.tabButton',
errorThemeClassKey: 'tabs.tabButton.error',
className: 's1',
active: false
};
render () {
return (
<li className={this.formContainerClassName()}>
<a href={'#' + this.props.id} className={this.props.active ? "active" : ""}>
{this.props.title}
</a>
</li>
);
}
}
|
src/Item.js
|
karote00/todo-react
|
require('../stylesheets/item.scss');
import React, { Component } from 'react';
import FontAwesome from 'react-fontawesome';
import { tabStore } from './tabStore';
import classNames from 'classnames';
export class Item extends Component {
constructor(props) {
super(props);
this.state = {
list: tabStore.getState(),
complete: this.props.data.complete,
starred: this.props.data.starred,
path: this.props.path,
todo: this.props.data.todo,
changeInput: false
};
}
complete() {
this.setState({complete: !this.state.complete});
var idx = this.state.list.indexOf(this.props.data);
this.state.list[idx].complete = !this.state.complete;
tabStore.dispatch({
type: 'Complete',
item: this.props.data,
path: this.state.path,
});
this.props.onUpdate();
}
starred() {
this.setState({starred: !this.state.starred});
var idx = this.state.list.indexOf(this.props.data);
this.state.list[idx].starred = !this.state.starred;
tabStore.dispatch({
type: 'Starred',
item: this.props.data,
path: this.state.path,
});
this.props.onUpdate();
}
delete() {
tabStore.dispatch({
type: 'Delete',
item: this.props.data,
path: this.state.path
});
this.props.onUpdate();
}
handleChange(e) {
this.setState({todo: e.target.value});
}
changeInput(e) {
if (!this.state.complete) {
this.setState({changeInput: !this.state.changeInput});
if (!this.state.changeInput) {
var _item = this.refs.todoInput;
setTimeout(function() {
_item.focus();
_item.selectionStart = 10000;
_item.selectionEnd = 10000;
}, 50);
}
}
}
showInput(e) {
if (!this.state.complete) {
this.setState({changeInput: true});
var _item = this.refs.todoInput;
setTimeout(function() {
_item.focus();
_item.selectionStart = 10000;
_item.selectionEnd = 10000;
}, 50);
}
}
render() {
var name = {};
name[this.state.path] = true;
name['item-container'] = true;
var container = classNames(name);
var complete = classNames({
'complete': true,
'hidden': this.state.complete,
'edit': this.state.changeInput
});
var star = classNames({
'star': true,
'hidden': !this.state.starred
});
var star_o = classNames({
'star_o': true,
'hidden': this.state.starred,
'active': this.state.starred
});
var todoContainer = classNames({
'todo': true,
'edit': this.state.changeInput
})
var todoText = classNames({
'strike': this.state.complete && this.state.path != 'Complete'
});
return (
<div className={container}>
<div className="check">
<div className={complete} onClick={this.complete.bind(this)} ></div>
<FontAwesome name="check-circle" className={this.state.complete? '': 'hidden'} onClick={this.complete.bind(this)} />
</div>
<div className={todoContainer} onClick={this.showInput.bind(this)}>
<div className={this.state.changeInput? 'hidden': ''}><span onClick={this.changeInput.bind(this)} className={todoText}>{this.state.todo}</span></div>
<input type="text" ref="todoInput" onBlur={this.changeInput.bind(this)} onChange={this.handleChange.bind(this)} value={this.state.todo} className={!this.state.changeInput? 'hidden': ''} />
</div>
<ul className="menu">
<li className={star_o} onClick={this.starred.bind(this)}><FontAwesome name="star-o" /></li>
<li className={star} onClick={this.starred.bind(this)}><FontAwesome name="star" /></li>
<li className="bottom" onClick={this.delete.bind(this)}><FontAwesome name="trash-o" /></li>
</ul>
</div>
)
}
}
|
dist/react-input-autosize.es.js
|
JedWatson/react-input-autosize
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
var asyncGenerator = function () {
function AwaitValue(value) {
this.value = value;
}
function AsyncGenerator(gen) {
var front, back;
function send(key, arg) {
return new Promise(function (resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null
};
if (back) {
back = back.next = request;
} else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
if (value instanceof AwaitValue) {
Promise.resolve(value.value).then(function (arg) {
resume("next", arg);
}, function (arg) {
resume("throw", arg);
});
} else {
settle(result.done ? "return" : "normal", result.value);
}
} catch (err) {
settle("throw", err);
}
}
function settle(type, value) {
switch (type) {
case "return":
front.resolve({
value: value,
done: true
});
break;
case "throw":
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false
});
break;
}
front = front.next;
if (front) {
resume(front.key, front.arg);
} else {
back = null;
}
}
this._invoke = send;
if (typeof gen.return !== "function") {
this.return = undefined;
}
}
if (typeof Symbol === "function" && Symbol.asyncIterator) {
AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
return this;
};
}
AsyncGenerator.prototype.next = function (arg) {
return this._invoke("next", arg);
};
AsyncGenerator.prototype.throw = function (arg) {
return this._invoke("throw", arg);
};
AsyncGenerator.prototype.return = function (arg) {
return this._invoke("return", arg);
};
return {
wrap: function (fn) {
return function () {
return new AsyncGenerator(fn.apply(this, arguments));
};
},
await: function (value) {
return new AwaitValue(value);
}
};
}();
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var sizerStyle = {
position: 'absolute',
top: 0,
left: 0,
visibility: 'hidden',
height: 0,
overflow: 'scroll',
whiteSpace: 'pre'
};
var INPUT_PROPS_BLACKLIST = ['extraWidth', 'injectStyles', 'inputClassName', 'inputRef', 'inputStyle', 'minWidth', 'onAutosize', 'placeholderIsMinWidth'];
var cleanInputProps = function cleanInputProps(inputProps) {
INPUT_PROPS_BLACKLIST.forEach(function (field) {
return delete inputProps[field];
});
return inputProps;
};
var copyStyles = function copyStyles(styles, node) {
node.style.fontSize = styles.fontSize;
node.style.fontFamily = styles.fontFamily;
node.style.fontWeight = styles.fontWeight;
node.style.fontStyle = styles.fontStyle;
node.style.letterSpacing = styles.letterSpacing;
node.style.textTransform = styles.textTransform;
};
var isIE = typeof window !== 'undefined' && window.navigator ? /MSIE |Trident\/|Edge\//.test(window.navigator.userAgent) : false;
var generateId = function generateId() {
// we only need an auto-generated ID for stylesheet injection, which is only
// used for IE. so if the browser is not IE, this should return undefined.
return isIE ? '_' + Math.random().toString(36).substr(2, 12) : undefined;
};
var AutosizeInput = function (_Component) {
inherits(AutosizeInput, _Component);
createClass(AutosizeInput, null, [{
key: 'getDerivedStateFromProps',
value: function getDerivedStateFromProps(props, state) {
var id = props.id;
return id !== state.prevId ? { inputId: id || generateId(), prevId: id } : null;
}
}]);
function AutosizeInput(props) {
classCallCheck(this, AutosizeInput);
var _this = possibleConstructorReturn(this, (AutosizeInput.__proto__ || Object.getPrototypeOf(AutosizeInput)).call(this, props));
_this.inputRef = function (el) {
_this.input = el;
if (typeof _this.props.inputRef === 'function') {
_this.props.inputRef(el);
}
};
_this.placeHolderSizerRef = function (el) {
_this.placeHolderSizer = el;
};
_this.sizerRef = function (el) {
_this.sizer = el;
};
_this.state = {
inputWidth: props.minWidth,
inputId: props.id || generateId(),
prevId: props.id
};
return _this;
}
createClass(AutosizeInput, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.mounted = true;
this.copyInputStyles();
this.updateInputWidth();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps, prevState) {
if (prevState.inputWidth !== this.state.inputWidth) {
if (typeof this.props.onAutosize === 'function') {
this.props.onAutosize(this.state.inputWidth);
}
}
this.updateInputWidth();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.mounted = false;
}
}, {
key: 'copyInputStyles',
value: function copyInputStyles() {
if (!this.mounted || !window.getComputedStyle) {
return;
}
var inputStyles = this.input && window.getComputedStyle(this.input);
if (!inputStyles) {
return;
}
copyStyles(inputStyles, this.sizer);
if (this.placeHolderSizer) {
copyStyles(inputStyles, this.placeHolderSizer);
}
}
}, {
key: 'updateInputWidth',
value: function updateInputWidth() {
if (!this.mounted || !this.sizer || typeof this.sizer.scrollWidth === 'undefined') {
return;
}
var newInputWidth = void 0;
if (this.props.placeholder && (!this.props.value || this.props.value && this.props.placeholderIsMinWidth)) {
newInputWidth = Math.max(this.sizer.scrollWidth, this.placeHolderSizer.scrollWidth) + 2;
} else {
newInputWidth = this.sizer.scrollWidth + 2;
}
// add extraWidth to the detected width. for number types, this defaults to 16 to allow for the stepper UI
var extraWidth = this.props.type === 'number' && this.props.extraWidth === undefined ? 16 : parseInt(this.props.extraWidth) || 0;
newInputWidth += extraWidth;
if (newInputWidth < this.props.minWidth) {
newInputWidth = this.props.minWidth;
}
if (newInputWidth !== this.state.inputWidth) {
this.setState({
inputWidth: newInputWidth
});
}
}
}, {
key: 'getInput',
value: function getInput() {
return this.input;
}
}, {
key: 'focus',
value: function focus() {
this.input.focus();
}
}, {
key: 'blur',
value: function blur() {
this.input.blur();
}
}, {
key: 'select',
value: function select() {
this.input.select();
}
}, {
key: 'renderStyles',
value: function renderStyles() {
// this method injects styles to hide IE's clear indicator, which messes
// with input size detection. the stylesheet is only injected when the
// browser is IE, and can also be disabled by the `injectStyles` prop.
var injectStyles = this.props.injectStyles;
return isIE && injectStyles ? React.createElement('style', { dangerouslySetInnerHTML: {
__html: 'input#' + this.state.inputId + '::-ms-clear {display: none;}'
} }) : null;
}
}, {
key: 'render',
value: function render() {
var sizerValue = [this.props.defaultValue, this.props.value, ''].reduce(function (previousValue, currentValue) {
if (previousValue !== null && previousValue !== undefined) {
return previousValue;
}
return currentValue;
});
var wrapperStyle = _extends({}, this.props.style);
if (!wrapperStyle.display) wrapperStyle.display = 'inline-block';
var inputStyle = _extends({
boxSizing: 'content-box',
width: this.state.inputWidth + 'px'
}, this.props.inputStyle);
var inputProps = objectWithoutProperties(this.props, []);
cleanInputProps(inputProps);
inputProps.className = this.props.inputClassName;
inputProps.id = this.state.inputId;
inputProps.style = inputStyle;
return React.createElement(
'div',
{ className: this.props.className, style: wrapperStyle },
this.renderStyles(),
React.createElement('input', _extends({}, inputProps, { ref: this.inputRef })),
React.createElement(
'div',
{ ref: this.sizerRef, style: sizerStyle },
sizerValue
),
this.props.placeholder ? React.createElement(
'div',
{ ref: this.placeHolderSizerRef, style: sizerStyle },
this.props.placeholder
) : null
);
}
}]);
return AutosizeInput;
}(Component);
AutosizeInput.propTypes = {
className: PropTypes.string, // className for the outer element
defaultValue: PropTypes.any, // default field value
extraWidth: PropTypes.oneOfType([// additional width for input element
PropTypes.number, PropTypes.string]),
id: PropTypes.string, // id to use for the input, can be set for consistent snapshots
injectStyles: PropTypes.bool, // inject the custom stylesheet to hide clear UI, defaults to true
inputClassName: PropTypes.string, // className for the input element
inputRef: PropTypes.func, // ref callback for the input element
inputStyle: PropTypes.object, // css styles for the input element
minWidth: PropTypes.oneOfType([// minimum width for input element
PropTypes.number, PropTypes.string]),
onAutosize: PropTypes.func, // onAutosize handler: function(newWidth) {}
onChange: PropTypes.func, // onChange handler: function(event) {}
placeholder: PropTypes.string, // placeholder text
placeholderIsMinWidth: PropTypes.bool, // don't collapse size to less than the placeholder
style: PropTypes.object, // css styles for the outer element
value: PropTypes.any // field value
};
AutosizeInput.defaultProps = {
minWidth: 1,
injectStyles: true
};
export default AutosizeInput;
|
ext_frontend/src/index.js
|
per-garden/webapp
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
src/svg-icons/image/timer-3.js
|
mmrtnz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageTimer3 = (props) => (
<SvgIcon {...props}>
<path d="M11.61 12.97c-.16-.24-.36-.46-.62-.65-.25-.19-.56-.35-.93-.48.3-.14.57-.3.8-.5.23-.2.42-.41.57-.64.15-.23.27-.46.34-.71.08-.24.11-.49.11-.73 0-.55-.09-1.04-.28-1.46-.18-.42-.44-.77-.78-1.06-.33-.28-.73-.5-1.2-.64-.45-.13-.97-.2-1.53-.2-.55 0-1.06.08-1.52.24-.47.17-.87.4-1.2.69-.33.29-.6.63-.78 1.03-.2.39-.29.83-.29 1.29h1.98c0-.26.05-.49.14-.69.09-.2.22-.38.38-.52.17-.14.36-.25.58-.33.22-.08.46-.12.73-.12.61 0 1.06.16 1.36.47.3.31.44.75.44 1.32 0 .27-.04.52-.12.74-.08.22-.21.41-.38.57-.17.16-.38.28-.63.37-.25.09-.55.13-.89.13H6.72v1.57H7.9c.34 0 .64.04.91.11.27.08.5.19.69.35.19.16.34.36.44.61.1.24.16.54.16.87 0 .62-.18 1.09-.53 1.42-.35.33-.84.49-1.45.49-.29 0-.56-.04-.8-.13-.24-.08-.44-.2-.61-.36-.17-.16-.3-.34-.39-.56-.09-.22-.14-.46-.14-.72H4.19c0 .55.11 1.03.32 1.45.21.42.5.77.86 1.05s.77.49 1.24.63.96.21 1.48.21c.57 0 1.09-.08 1.58-.23.49-.15.91-.38 1.26-.68.36-.3.64-.66.84-1.1.2-.43.3-.93.3-1.48 0-.29-.04-.58-.11-.86-.08-.25-.19-.51-.35-.76zm9.26 1.4c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39s.03-.28.09-.41c.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11.19.07.35.17.48.29.13.12.22.26.29.42.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59-.43-.15-.92-.22-1.46-.22-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.68.23.96c.15.28.37.52.64.73.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.7.93.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02z"/>
</SvgIcon>
);
ImageTimer3 = pure(ImageTimer3);
ImageTimer3.displayName = 'ImageTimer3';
ImageTimer3.muiName = 'SvgIcon';
export default ImageTimer3;
|
examples/huge-apps/routes/Course/routes/Announcements/routes/Announcement/components/Announcement.js
|
chf2/react-router
|
/*globals COURSES:true */
import React from 'react'
class Announcement extends React.Component {
render() {
let { courseId, announcementId } = this.props.params
let { title, body } = COURSES[courseId].announcements[announcementId]
return (
<div>
<h4>{title}</h4>
<p>{body}</p>
</div>
)
}
}
export default Announcement
|
src/Parser/ShadowPriest/CombatLogParser.js
|
mwwscott0/WoWAnalyzer
|
import React from 'react';
import MainCombatLogParser from 'Parser/Core/CombatLogParser';
import DamageDone from 'Parser/Core/Modules/DamageDone';
import SuggestionsTab from 'Main/SuggestionsTab';
import AbilityTracker from './Modules/Core/AbilityTracker';
import CastEfficiency from './Modules/Features/CastEfficiency';
import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting';
import Insanity from './Modules/Core/Insanity';
import Mindbender from './Modules/Spells/Mindbender';
import Shadowfiend from './Modules/Spells/Shadowfiend';
import VampiricTouch from './Modules/Spells/VampiricTouch';
import ShadowWordPain from './Modules/Spells/ShadowWordPain';
import Voidform from './Modules/Spells/Voidform';
import VoidformAverageStacks from './Modules/Spells/VoidformAverageStacks';
import VoidTorrent from './Modules/Spells/VoidTorrent';
import Dispersion from './Modules/Spells/Dispersion';
import CallToTheVoid from './Modules/Spells/CallToTheVoid';
class CombatLogParser extends MainCombatLogParser {
static specModules = {
damageDone: [DamageDone, { showStatistic: true }],
alwaysBeCasting: AlwaysBeCasting,
abilityTracker: AbilityTracker,
castEfficiency: CastEfficiency,
insanity: Insanity,
// Abilities
mindbender: Mindbender,
shadowfiend: Shadowfiend,
vampiricTouch: VampiricTouch,
shadowWordPain: ShadowWordPain,
voidform: Voidform,
voidformAverageStacks: VoidformAverageStacks,
voidTorrent: VoidTorrent,
dispersion: Dispersion,
callToTheVoid: CallToTheVoid,
};
generateResults() {
const results = super.generateResults();
results.statistics = [
...results.statistics,
];
results.items = [
...results.items,
];
results.tabs = [
{
title: 'Suggestions',
url: 'suggestions',
render: () => (
<SuggestionsTab issues={results.issues} />
),
},
...results.tabs,
// {
// title: 'Talents',
// url: 'talents',
// render: () => (
// <Tab title="Talents">
// <Talents combatant={this.selectedCombatant} />
// </Tab>
// ),
// },
];
return results;
}
}
export default CombatLogParser;
|
src/field/ImageRenderer.js
|
carab/Pinarium
|
import React from 'react';
import useFirebaseImage from '../hooks/useFirebaseImage';
function ImageRenderer({value, name, ...props}) {
const [src] = useFirebaseImage(value);
if (src) {
return <img src={src} alt={value} {...props} />;
}
return null;
}
export default ImageRenderer;
|
web/src/js/__tests__/components/FlowView/ToggleEditSpec.js
|
vhaupert/mitmproxy
|
// jest.mock('../../../ducks/ui/flow')
import React from 'react'
import renderer from 'react-test-renderer'
import ToggleEdit from '../../../components/FlowView/ToggleEdit'
import { Provider } from 'react-redux'
import { startEdit, stopEdit } from '../../../ducks/ui/flow'
import { TFlow, TStore } from '../../ducks/tutils'
global.fetch = jest.fn()
let tflow = new TFlow()
describe('ToggleEdit Component', () => {
let store = TStore(),
provider = renderer.create(
<Provider store={store}>
<ToggleEdit/>
</Provider>),
tree = provider.toJSON()
afterEach(() => { store.clearActions() })
it('should render correctly', () => {
expect(tree).toMatchSnapshot()
})
it('should handle click on stopEdit', () => {
tree.children[0].props.onClick()
expect(fetch).toBeCalled()
})
it('should handle click on startEdit', () => {
store.getState().ui.flow.modifiedFlow = false
let provider = renderer.create(
<Provider store={store}>
<ToggleEdit/>
</Provider>),
tree = provider.toJSON()
tree.children[0].props.onClick()
expect(store.getActions()).toEqual([startEdit(tflow)])
})
})
|
src/js/routes.js
|
julianburr/wp-react-theme
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Index from './templates';
import Loading from './templates/loading';
import Home from './templates/home';
import SearchResult from './templates/search-result';
import Content from './templates/content';
import { connect } from 'react-redux';
import { Router, Route, IndexRoute } from 'react-router';
import { history } from './store';
import { loadSettings } from './actions/settings';
class WPThemeRoutes extends Component {
componentDidMount () {
if (this.props.loadSettings) {
this.props.loadSettings();
}
}
getRoutes () {
const { settings } = this.props;
// Home route
let routes = []; // [{path: '/', component: Home, name: 'home'}];
settings.routes.lists.forEach((route, i) => {
// Loop through routes from API
// These are generated using the WP rewrite rules!
routes.push({path: route, component: SearchResult});
})
routes.push({path: settings.routes.content, component: Content, name: 'post'});
// Finally add the content rule for everything else
routes.push({path: '*', component: Content, name: 'fallback'});
return routes;
}
willReceiveProps = (nextProps) => {
console.log('ROUTES will receive props', nextProps)
}
render () {
const { settings } = this.props;
console.log('ROUTES render')
// Show loading screen while we wait for the settings
// After settings have been loaded, return the routes
return settings ? (
<Router history={history}>
<Route path='/' component={Index}>
<IndexRoute component={Home} />
{this.getRoutes().map((route, i) => (
<Route key={i} path={route.path} component={route.component} />
))}
</Route>
</Router>
) : <Loading />;
}
}
/**
* Connect component to redux store
*/
const mapStateToProps = state => {
return {
settings: state.settings
};
}
const mapDispatchToProps = dispatch => {
return {
loadSettings: () => dispatch(loadSettings())
};
}
export default connect(mapStateToProps, mapDispatchToProps)(WPThemeRoutes)
|
app/static/src/diagnostic/EquipmentForm_modules/AditionalEqupmentParameters_modules/CableParams.js
|
vsilent/Vision
|
import React from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import Checkbox from 'react-bootstrap/lib/Checkbox';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import {findDOMNode} from 'react-dom';
import {hashHistory} from 'react-router';
import {Link} from 'react-router';
import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';
import Tooltip from 'react-bootstrap/lib/Tooltip';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
const TextField = React.createClass({
_onChange: function (e) {
this.props.onChange(e);
},
render: function () {
let tooltip = <Tooltip id={this.props.label}>{this.props.label}</Tooltip>;
var label = (this.props.label != null) ? this.props.label : "";
var name = (this.props.name != null) ? this.props.name : "";
var type = (this.props["data-type"] != null) ? this.props["data-type"]: undefined;
var len = (this.props["data-len"] != null) ? this.props["data-len"]: undefined;
var validationState = (this.props.errors[name]) ? 'error' : null;
var error = this.props.errors[name];
var value = (this.props["value"] != null) ? this.props["value"]: "";
return (
<OverlayTrigger overlay={tooltip} placement="top">
<FormGroup validationState={validationState}>
<ControlLabel>{label}</ControlLabel>
<FormControl type="text"
placeholder={label}
name={name}
data-type={type}
data-len={len}
onChange={this._onChange}
value={value}
/>
<HelpBlock className="warning">{error}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</OverlayTrigger>
);
}
});
var SelectField = React.createClass({
handleChange: function (event, index, value) {
this.setState({
value: event.target.value
});
},
getInitialState: function () {
return {
items: [],
isVisible: false,
value: -1
};
},
isVisible: function () {
return this.state.isVisible;
},
componentDidMount: function () {
var source = '/api/v1.0/' + this.props.source + '/';
this.serverRequest = $.authorizedGet(source, function (result) {
this.setState({items: (result['result'])});
}.bind(this), 'json');
},
componentWillUnmount: function () {
this.serverRequest.abort();
},
setVisible: function () {
this.state.isVisible = true;
},
render: function () {
var label = (this.props.label != null) ? this.props.label : "";
var value = (this.props.value != null) ? this.props.value : "";
var name = (this.props.name != null) ? this.props.name : "";
var validationState = (this.props.errors[name]) ? 'error' : null;
var error = this.props.errors[name];
var menuItems = [];
for (var key in this.state.items) {
menuItems.push(<option key={this.state.items[key].id}
value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>);
}
return (
<FormGroup validationState={validationState}>
<ControlLabel>{label}</ControlLabel>
<FormControl componentClass="select"
onChange={this.handleChange}
value={value}
name={this.props.name}
>
<option>{this.props.label}</option>);
{menuItems}
</FormControl>
<HelpBlock className="warning">{error}</HelpBlock>
</FormGroup>
);
}
});
var CableParams = React.createClass({
getInitialState: function () {
return {
'phase_number':'',
'sealed':'',
'model':'',
'threephase':'',
'insulation_id':'',
'id':'',
'errors': {}
}
},
handleChange: function(e){
var state = this.state;
if (e.target.type == "checkbox"){
state[e.target.name] = e.target.checked;
}
else
state[e.target.name] = e.target.value;
this.setState(state);
},
load:function() {
this.setState(this.props.equipment_item)
},
render: function () {
var errors = (Object.keys(this.state.errors).length) ? this.state.errors : this.props.errors;
return (
<div className="row">
<div className="col-md-4">
<TextField onChange={this.handleChange}
label="Model"
name="model"
value={this.state.model}
errors={errors}
data-len="50"/>
</div>
<div className="col-md-3">
<SelectField
source="insulation"
label="Insulation"
name="insulation_id"
value={this.state.insulation_id}
errors={errors}/>
</div>
<div className="col-md-2">
<Checkbox name="threephase" checked={this.state.threephase} onChange={this.handleChange}><b>Three Phase</b></Checkbox>
</div>
<div className="col-md-1">
<Checkbox name="sealed" checked={this.state.sealed} onChange={this.handleChange}><b>Sealed</b></Checkbox>
</div>
</div>
)
}
});
export default CableParams;
|
app/containers/MainContent.js
|
SiDevesh/Bootleg
|
// @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import MainContentComponent from '../components/MainContentComponent';
const mapStateToProps = (state) => {
return {
selectedPane: state.navPaneState.selectedPane,
windowWidth: state.themeState.windowWidth,
windowHeight: state.themeState.windowHeight,
navPaneOpen: state.themeState.navPaneOpen
}
}
//const mapDispatchToProps = (dispatch) => {
// return {
// onPaneSelect: (name) => {
// dispatch(callPaneSelect(name));
// }
// }
//}
const MainContent = connect(
mapStateToProps
)(MainContentComponent)
export default MainContent;
|
src/js/index.js
|
nikdelig/react-redux-sass-starter-kit
|
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import App from './components/App';
const root = document.getElementById('root');
render(
<Provider>
<Router>
<App />
</Router>
</Provider>,
root,
);
|
docs/src/pages/styles/basics/AdaptingHOC.js
|
lgollut/material-ui
|
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
const styles = {
root: {
background: (props) =>
props.color === 'red'
? 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)'
: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
border: 0,
borderRadius: 3,
boxShadow: (props) =>
props.color === 'red'
? '0 3px 5px 2px rgba(255, 105, 135, .3)'
: '0 3px 5px 2px rgba(33, 203, 243, .3)',
color: 'white',
height: 48,
padding: '0 30px',
margin: 8,
},
};
function MyButtonRaw(props) {
const { classes, color, ...other } = props;
return <Button className={classes.root} {...other} />;
}
MyButtonRaw.propTypes = {
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object.isRequired,
color: PropTypes.oneOf(['blue', 'red']).isRequired,
};
const MyButton = withStyles(styles)(MyButtonRaw);
export default function AdaptingHOC() {
return (
<React.Fragment>
<MyButton color="red">Red</MyButton>
<MyButton color="blue">Blue</MyButton>
</React.Fragment>
);
}
|
src/components/Popovers.js
|
vonubisch/Cordova-PhoneGap-Babel-React-Hotloader-Webpack-OnsenUI-FontAwesome
|
import React from 'react';
import {Page, Toolbar, BackButton, Popover} from 'react-onsenui';
class Popovers extends React.Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
};
}
showPopover() {
this.setState({isOpen: true});
setTimeout(() => {
this.setState({isOpen: false});
}, 1000);
}
getTarget() {
return this.popover.target;
}
renderToolbar() {
return (
<Toolbar>
<div className="left">
<BackButton>Back</BackButton>
</div>
<div className="center">
Popovers
</div>
</Toolbar>
);
}
render() {
return (
<Page renderToolbar={this.renderToolbar}>
<div style={{textAlign: 'center'}}>
<br/>
<div
onClick={this.showPopover.bind(this)}
style={{
width: '100px',
height: '100px',
display: 'inline-block',
backgroundColor: 'rgba(0, 0, 0, 0.1)',
color: 'rgba(0, 0, 0, 0.6)',
lineHeight: '100px'
}}
ref={(popover) => { this.popover = popover; }}
>
Click me!
</div>
</div>
<Popover direction="down" isOpen={this.state.isOpen} getTarget={this.getTarget.bind(this)}>
<div
style={{
textAlign: 'center',
lineHeight: '100px'
}}
>
{"I'm a popover!"}
</div>
</Popover>
</Page>
);
}
}
export default Popovers;
|
ee/client/omnichannel/additionalForms/MaxChatsPerAgentDisplay.js
|
VoiSmart/Rocket.Chat
|
import React from 'react';
import { useTranslation } from '../../../../client/contexts/TranslationContext';
import UserInfo from '../../../../client/views/room/contextualBar/UserInfo';
const MaxChatsPerAgentDisplay = ({
data: { livechat: { maxNumberSimultaneousChat = '' } = {} } = {},
}) => {
const t = useTranslation();
return (
maxNumberSimultaneousChat && (
<>
<UserInfo.Label>{t('Max_number_of_chats_per_agent')}</UserInfo.Label>
<UserInfo.Info>{maxNumberSimultaneousChat}</UserInfo.Info>
</>
)
);
};
export default MaxChatsPerAgentDisplay;
|
next-express/components/Header.js
|
thoughtbit/node-web-starter
|
import React from 'react'
import Link from 'next/link'
import NProgress from 'nprogress'
import Router from 'next/router'
Router.onRouteChangeStart = (url) => {
console.log(`Loading: ${url}`)
NProgress.start()
}
Router.onRouteChangeComplete = () => NProgress.done()
Router.onRouteChangeError = () => NProgress.done()
export default () => (
<header>
<nav className="nav">
<Link href='/'><a>Home</a></Link>
<Link href='/blog'><a>blog</a></Link>
<Link href='/blog?id=first' as='/blog/first'><a>My first blog post</a></Link>
<Link href='/contact'><a>Contact</a></Link>
<Link href='/about'><a>About</a></Link>
<Link href='/error'><a>Error</a></Link>
</nav>
<style jsx global>{`
.nav {
text-align: center;
}
.nav a {
display: inline-block;
padding: 5px;
border: 1px solid #eee;
margin: 0 5px;
}
.nav a:hover {
background: #ccc;
}
`}</style>
</header>
)
|
src/DatePicker/Calendar.spec.js
|
xmityaz/material-ui
|
/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import Calendar from './Calendar';
import {addMonths, dateTimeFormat} from './dateUtils';
import getMuiTheme from '../styles/getMuiTheme';
describe('<Calendar />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
describe('Next Month Button', () => {
it('should initially be disabled if the current month is the same as the month in the maxDate prop', () => {
const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
const maxDate = new Date(initialDate.toDateString());
const wrapper = shallowWithContext(
<Calendar
initialDate={initialDate}
DateTimeFormat={dateTimeFormat}
locale="en-US"
maxDate={maxDate}
/>
);
assert.notOk(wrapper.find('CalendarToolbar').prop('nextMonth'));
});
it('should initially be disabled if the current month is after the month in the maxDate prop', () => {
const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
let maxDate = new Date(initialDate.toDateString());
maxDate = addMonths(maxDate, -1);
const wrapper = shallowWithContext(
<Calendar
initialDate={initialDate}
DateTimeFormat={dateTimeFormat}
locale="en-US"
maxDate={maxDate}
/>
);
assert.notOk(wrapper.find('CalendarToolbar').prop('nextMonth'));
});
it('should initially enable the next month button if the current month is before the maxDate prop', () => {
const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
let maxDate = new Date(initialDate.toDateString());
maxDate = addMonths(maxDate, 1);
const wrapper = shallowWithContext(
<Calendar
initialDate={initialDate}
DateTimeFormat={dateTimeFormat}
locale="en-US"
maxDate={maxDate}
/>
);
assert.ok(wrapper.find('CalendarToolbar').prop('nextMonth'));
});
it('should reenable the next month button when the current month is before the maxDate prop', () => {
const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
const maxDate = new Date(initialDate.toDateString());
const wrapper = shallowWithContext(
<Calendar
initialDate={initialDate}
DateTimeFormat={dateTimeFormat}
locale="en-US"
maxDate={maxDate}
/>
);
wrapper.instance().handleMonthChange(-1);
wrapper.update();
assert.ok(wrapper.find('CalendarToolbar').prop('nextMonth'));
});
it('should redisable the next month button when the current month is the same as the maxDate prop', () => {
const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
let maxDate = new Date(initialDate.toDateString());
maxDate = addMonths(maxDate, 1);
const wrapper = shallowWithContext(
<Calendar
initialDate={initialDate}
DateTimeFormat={dateTimeFormat}
locale="en-US"
maxDate={maxDate}
/>
);
wrapper.instance().handleMonthChange(1);
wrapper.update();
assert.notOk(wrapper.find('CalendarToolbar').prop('nextMonth'));
});
});
describe('Previous Month Button', () => {
it(`should initially disable the previous month button if the current month
is the same as the minDate month prop`, () => {
const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
const minDate = new Date(initialDate.toDateString());
const wrapper = shallowWithContext(
<Calendar
initialDate={initialDate}
DateTimeFormat={dateTimeFormat}
locale="en-US"
minDate={minDate}
/>
);
assert.notOk(wrapper.find('CalendarToolbar').prop('prevMonth'));
});
it(`should initially disable the previous month button if the current month
is before the minDate month prop`, () => {
const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
let minDate = new Date(initialDate.toDateString());
minDate = addMonths(initialDate, 1);
const wrapper = shallowWithContext(
<Calendar
initialDate={initialDate}
DateTimeFormat={dateTimeFormat}
locale="en-US"
minDate={minDate}
/>
);
assert.notOk(wrapper.find('CalendarToolbar').prop('prevMonth'));
});
it('should initially enable the previous month button if the current month is after the minDate month prop', () => {
const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
let minDate = new Date(initialDate.toDateString());
minDate = addMonths(initialDate, -1);
const wrapper = shallowWithContext(
<Calendar
initialDate={initialDate}
DateTimeFormat={dateTimeFormat}
locale="en-US"
minDate={minDate}
/>
);
assert.ok(wrapper.find('CalendarToolbar').prop('prevMonth'));
});
it('should enable the previous month button when the current month is after the minDate month prop', () => {
const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
const minDate = new Date(initialDate.toDateString());
const wrapper = shallowWithContext(
<Calendar
initialDate={initialDate}
DateTimeFormat={dateTimeFormat}
locale="en-US"
minDate={minDate}
/>
);
wrapper.instance().handleMonthChange(1);
wrapper.update();
assert.ok(wrapper.find('CalendarToolbar').prop('prevMonth'));
});
it('should disable the previous month button when the current month is the same as the minDate month prop', () => {
const initialDate = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
let minDate = new Date(initialDate.toDateString());
minDate = addMonths(minDate, -1);
const wrapper = shallowWithContext(
<Calendar
initialDate={initialDate}
DateTimeFormat={dateTimeFormat}
locale="en-US"
minDate={minDate}
/>
);
wrapper.instance().handleMonthChange(-1);
wrapper.update();
assert.notOk(wrapper.find('CalendarToolbar').prop('prevMonth'));
});
});
});
|
node_modules/react-bootstrap/es/Tooltip.js
|
NickingMeSpace/questionnaire
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import isRequiredForA11y from 'prop-types-extra/lib/isRequiredForA11y';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
/**
* An html id attribute, necessary for accessibility
* @type {string|number}
* @required
*/
id: isRequiredForA11y(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),
/**
* Sets the direction the Tooltip is positioned towards.
*/
placement: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The "top" position value for the Tooltip.
*/
positionTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The "left" position value for the Tooltip.
*/
positionLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The "top" position value for the Tooltip arrow.
*/
arrowOffsetTop: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The "left" position value for the Tooltip arrow.
*/
arrowOffsetLeft: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
};
var defaultProps = {
placement: 'right'
};
var Tooltip = function (_React$Component) {
_inherits(Tooltip, _React$Component);
function Tooltip() {
_classCallCheck(this, Tooltip);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Tooltip.prototype.render = function render() {
var _extends2;
var _props = this.props,
placement = _props.placement,
positionTop = _props.positionTop,
positionLeft = _props.positionLeft,
arrowOffsetTop = _props.arrowOffsetTop,
arrowOffsetLeft = _props.arrowOffsetLeft,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'className', 'style', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2));
var outerStyle = _extends({
top: positionTop,
left: positionLeft
}, style);
var arrowStyle = {
top: arrowOffsetTop,
left: arrowOffsetLeft
};
return React.createElement(
'div',
_extends({}, elementProps, {
role: 'tooltip',
className: classNames(className, classes),
style: outerStyle
}),
React.createElement('div', { className: prefix(bsProps, 'arrow'), style: arrowStyle }),
React.createElement(
'div',
{ className: prefix(bsProps, 'inner') },
children
)
);
};
return Tooltip;
}(React.Component);
Tooltip.propTypes = propTypes;
Tooltip.defaultProps = defaultProps;
export default bsClass('tooltip', Tooltip);
|
src/svg-icons/social/location-city.js
|
mtsandeep/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialLocationCity = (props) => (
<SvgIcon {...props}>
<path d="M15 11V5l-3-3-3 3v2H3v14h18V11h-6zm-8 8H5v-2h2v2zm0-4H5v-2h2v2zm0-4H5V9h2v2zm6 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V9h2v2zm0-4h-2V5h2v2zm6 12h-2v-2h2v2zm0-4h-2v-2h2v2z"/>
</SvgIcon>
);
SocialLocationCity = pure(SocialLocationCity);
SocialLocationCity.displayName = 'SocialLocationCity';
SocialLocationCity.muiName = 'SvgIcon';
export default SocialLocationCity;
|
src/components/pages/register.js
|
cosminseceleanu/react-sb-admin-bootstrap4
|
import React from 'react';
import {Link} from 'react-router-dom';
import {
Card,
CardBody,
CardHeader,
Form,
Input,
Label,
FormGroup,
Button,
Col
} from 'reactstrap';
const Register = () => {
return (
<Card className="card-register mx-auto mt-5">
<CardHeader>Register an Account</CardHeader>
<CardBody>
<Form>
<FormGroup>
<div className="form-row">
<Col md="6">
<Label>First name</Label>
<Input type="text" placeholder="Enter first name"/>
</Col>
</div>
</FormGroup>
<FormGroup>
<div className="form-row">
<Col md="6">
<Label>Last name</Label>
<Input type="text" placeholder="Enter last name"/>
</Col>
</div>
</FormGroup>
<FormGroup>
<div className="form-row">
<Col md="6">
<Label>Email address</Label>
<Input type="email" placeholder="Enter email"/>
</Col>
</div>
</FormGroup>
<FormGroup>
<div className="form-row">
<Col md="6">
<Label>Password</Label>
<Input type="password" placeholder="Password"/>
</Col>
</div>
</FormGroup>
<FormGroup>
<div className="form-row">
<Col md="6">
<Label>Confirm Password</Label>
<Input type="password" placeholder="Confirm password"/>
</Col>
</div>
</FormGroup>
<Button color="primary" block>Register</Button>
</Form>
<div className="text-center">
<Link className="d-block small mt-3" to="/login">Login</Link>
<Link className="d-block small" to="/forgot-password">Forgot Password?</Link>
</div>
</CardBody>
</Card>
)
};
export default Register;
|
app/src/components/RSSPanels/SuggestedFeeds.js
|
GetStream/Winds
|
import { Link } from 'react-router-dom';
import getPlaceholderImageURL from '../../util/getPlaceholderImageURL';
import { Img } from 'react-image';
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import Panel from '../Panel';
import { getSuggestedRss, followRss, unfollowRss } from '../../api';
class SuggestedFeeds extends React.Component {
componentDidMount() {
if (!this.props.suggestedRssFeeds.length) getSuggestedRss(this.props.dispatch);
}
render() {
return (
<Panel headerText="Suggested Feeds">
{this.props.suggestedRssFeeds.map((rssFeed) => {
const id = rssFeed._id;
const favicon = rssFeed.images ? rssFeed.images.favicon : null;
return (
<Link key={id} to={`/rss/${id}`}>
<Img src={[favicon, getPlaceholderImageURL(id)]} />
<div>{rssFeed.title}</div>
<div
className={`clickable ${
rssFeed.isFollowed ? 'active' : ''
}`}
onClick={(e) => {
e.preventDefault();
rssFeed.isFollowed
? unfollowRss(this.props.dispatch, id)
: followRss(this.props.dispatch, id);
}}
>
Follow
</div>
</Link>
);
})}
</Panel>
);
}
}
SuggestedFeeds.defaultProps = {
suggestedRssFeeds: [],
};
SuggestedFeeds.propTypes = {
dispatch: PropTypes.func.isRequired,
suggestedRssFeeds: PropTypes.arrayOf(PropTypes.shape()),
};
const mapStateToProps = (state) => {
if (!state.suggestedRssFeeds) return { suggestedRssFeeds: [] };
let suggestedRssFeeds = state.suggestedRssFeeds;
if (state.followedRssFeeds) {
suggestedRssFeeds = suggestedRssFeeds.map((item) => ({
...item,
isFollowed: !!state.followedRssFeeds[item._id],
}));
}
if (state.aliases) {
suggestedRssFeeds = suggestedRssFeeds.map((item) => {
if (state.aliases[item._id]) item.title = state.aliases[item._id].alias;
return item;
});
}
return {
suggestedRssFeeds,
};
};
export default connect(mapStateToProps)(SuggestedFeeds);
|
app/views/Proposals/Proposal/View/View.js
|
RcKeller/STF-Refresh
|
// NOTE: This abstraction isn't necessary, but directories will be super cluttered without.
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Alert } from 'antd'
import Head from './Head/Head'
import Overview from './Overview/Overview'
import Body from './Body/Body'
import Legacy from './Legacy/Legacy'
import Manifests from './Manifests/Manifests'
import { Loading } from '../../../../components'
/*
PROPOSAL PAGE / VIEW:
Container for proposal content rendering
Conditially renders sections based on if the data is present
(e.g. renders Overview and Body for new format proposals)
*/
@connect(state => ({
proposal: state.db.proposal._id,
isLegacy: state.db.proposal.body
? state.db.proposal.body.legacy.length > 0
: false,
published: state.db.proposal.published,
inReview: state.db.proposal.status === 'In Review'
}))
class View extends React.Component {
static propTypes = {
proposal: PropTypes.string,
isLegacy: PropTypes.bool,
published: PropTypes.bool
}
render ({ proposal, published, isLegacy, inReview } = this.props) {
// Once the proposal has loaded, render it. Only render body if published.
return (
<Loading render={proposal} title='proposal content'>
<section>
<Head />
{!published
? <Alert type='warning' showIcon
message='Unpublished Proposal'
description='This proposal has been withdrawn from publication by either an author or administrator. It exists for STF recordkeeping. For further inquiries, e-mail STFCweb@uw.edu'
/>
: <div>
{isLegacy ? <Legacy /> : <div><Overview /><hr /><Body /></div>}
<hr />
<Manifests />
{inReview &&
<Alert type='warning' style={{ marginTop: 28 }}
banner showIcon={false}
message={<h3>Like this proposal?</h3>}
description={<span>Endorse it - <b>it could make the difference that gets this approved!</b> Use the endorsement tab at the top to leave your remarks.</span>}
/>
}
</div>
}
</section>
</Loading>
)
}
}
export default View
|
fields/types/datetime/DatetimeField.js
|
davibe/keystone
|
import DateInput from '../../components/DateInput';
import Field from '../Field';
import moment from 'moment';
import React from 'react';
import { Button, FormField, FormInput, FormNote, InputGroup } from 'elemental';
module.exports = Field.create({
displayName: 'DatetimeField',
focusTargetRef: 'dateInput',
// default input formats
dateInputFormat: 'YYYY-MM-DD',
timeInputFormat: 'h:mm:ss a',
// parse formats (duplicated from lib/fieldTypes/datetime.js)
parseFormats: ['YYYY-MM-DD', 'YYYY-MM-DD h:m:s a', 'YYYY-MM-DD h:m a', 'YYYY-MM-DD H:m:s', 'YYYY-MM-DD H:m'],
getInitialState () {
return {
dateValue: this.props.value ? this.moment(this.props.value).format(this.dateInputFormat) : '',
timeValue: this.props.value ? this.moment(this.props.value).format(this.timeInputFormat) : ''
};
},
getDefaultProps () {
return {
formatString: 'Do MMM YYYY, h:mm:ss a'
};
},
moment (value) {
var m = moment(value);
if (this.props.isUTC) m.utc();
return m;
},
// TODO: Move isValid() so we can share with server-side code
isValid (value) {
return moment(value, this.parseFormats).isValid();
},
// TODO: Move format() so we can share with server-side code
format (value, format) {
format = format || this.dateInputFormat + ' ' + this.timeInputFormat;
return value ? this.moment(value).format(format) : '';
},
handleChange (dateValue, timeValue) {
var value = dateValue + ' ' + timeValue;
var datetimeFormat = this.dateInputFormat + ' ' + this.timeInputFormat;
this.props.onChange({
path: this.props.path,
value: this.isValid(value) ? moment(value, datetimeFormat).toISOString() : null
});
},
dateChanged (value) {
this.setState({ dateValue: value });
this.handleChange(value, this.state.timeValue);
},
timeChanged (event) {
this.setState({ timeValue: event.target.value });
this.handleChange(this.state.dateValue, event.target.value);
},
setNow () {
var dateValue = moment().format(this.dateInputFormat);
var timeValue = moment().format(this.timeInputFormat);
this.setState({
dateValue: dateValue,
timeValue: timeValue
});
this.handleChange(dateValue, timeValue);
},
renderNote () {
if (!this.props.note) return null;
return <FormNote note={this.props.note} />;
},
renderUI () {
var input;
var fieldClassName = 'field-ui';
if (this.shouldRenderField()) {
input = (
<InputGroup>
<InputGroup.Section grow>
<DateInput ref="dateInput" name={this.props.paths.date} value={this.state.dateValue} format={this.dateInputFormat} onChange={this.dateChanged} />
</InputGroup.Section>
<InputGroup.Section grow>
<FormInput name={this.props.paths.time} value={this.state.timeValue} placeholder="HH:MM:SS am/pm" onChange={this.timeChanged} autoComplete="off" />
</InputGroup.Section>
<InputGroup.Section>
<Button onClick={this.setNow}>Now</Button>
</InputGroup.Section>
</InputGroup>
);
} else {
input = <FormInput noedit>{this.format(this.props.value, this.props.formatString)}</FormInput>;
}
return (
<FormField label={this.props.label} className="field-type-datetime">
{input}
{this.renderNote()}
</FormField>
);
}
});
|
app/components/Icon.js
|
alexeyraspopov/evo
|
import React from 'react';
export default function Icon({type, className = ''}) {
return <span className={`material-icons ${className}`}>{type}</span>;
}
|
fields/components/columns/ArrayColumn.js
|
suryagh/keystone
|
import React from 'react';
import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue';
var ArrayColumn = React.createClass({
displayName: 'ArrayColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value || !value.length) return null;
return value.join(', ');
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = ArrayColumn;
|
frontend/src/Components/Table/VirtualTable.js
|
lidarr/Lidarr
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Grid, WindowScroller } from 'react-virtualized';
import Measure from 'Components/Measure';
import Scroller from 'Components/Scroller/Scroller';
import { scrollDirections } from 'Helpers/Props';
import hasDifferentItemsOrOrder from 'Utilities/Object/hasDifferentItemsOrOrder';
import styles from './VirtualTable.css';
function overscanIndicesGetter(options) {
const {
cellCount,
overscanCellsCount,
startIndex,
stopIndex
} = options;
// The default getter takes the scroll direction into account,
// but that can cause issues. Ignore the scroll direction and
// always over return more items.
const overscanStartIndex = startIndex - overscanCellsCount;
const overscanStopIndex = stopIndex + overscanCellsCount;
return {
overscanStartIndex: Math.max(0, overscanStartIndex),
overscanStopIndex: Math.min(cellCount - 1, overscanStopIndex)
};
}
class VirtualTable extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
width: 0
};
this._grid = null;
}
componentDidUpdate(prevProps, prevState) {
const {
items,
scrollIndex,
scrollTop,
onRecompute
} = this.props;
const {
width
} = this.state;
if (this._grid &&
(prevState.width !== width ||
hasDifferentItemsOrOrder(prevProps.items, items))) {
onRecompute(width);
// recomputeGridSize also forces Grid to discard its cache of rendered cells
this._grid.recomputeGridSize();
}
if (scrollIndex != null && scrollIndex !== prevProps.scrollIndex) {
this._grid.scrollToCell({
rowIndex: scrollIndex,
columnIndex: 0
});
}
if (this._grid && scrollTop !== undefined && scrollTop !== 0) {
this._grid.scrollToPosition({ scrollTop });
}
}
//
// Control
setGridRef = (ref) => {
this._grid = ref;
}
//
// Listeners
onMeasure = ({ width }) => {
this.setState({
width
});
}
//
// Render
render() {
const {
isSmallScreen,
className,
items,
scroller,
scrollTop: ignored,
header,
headerHeight,
rowHeight,
rowRenderer,
...otherProps
} = this.props;
const {
width
} = this.state;
const gridStyle = {
boxSizing: undefined,
direction: undefined,
height: undefined,
position: undefined,
willChange: undefined,
overflow: undefined,
width: undefined
};
const containerStyle = {
position: undefined
};
return (
<WindowScroller
scrollElement={isSmallScreen ? undefined : scroller}
>
{({ height, registerChild, onChildScroll, scrollTop }) => {
if (!height) {
return null;
}
return (
<Measure
whitelist={['width']}
onMeasure={this.onMeasure}
>
<Scroller
className={className}
scrollDirection={scrollDirections.HORIZONTAL}
>
{header}
<div ref={registerChild}>
<Grid
ref={this.setGridRef}
autoContainerWidth={true}
autoHeight={true}
autoWidth={true}
width={width}
height={height}
headerHeight={height - headerHeight}
rowHeight={rowHeight}
rowCount={items.length}
columnCount={1}
columnWidth={width}
scrollTop={scrollTop}
onScroll={onChildScroll}
overscanRowCount={2}
cellRenderer={rowRenderer}
overscanIndicesGetter={overscanIndicesGetter}
scrollToAlignment={'start'}
isScrollingOptout={true}
className={styles.tableBodyContainer}
style={gridStyle}
containerStyle={containerStyle}
{...otherProps}
/>
</div>
</Scroller>
</Measure>
);
}
}
</WindowScroller>
);
}
}
VirtualTable.propTypes = {
isSmallScreen: PropTypes.bool.isRequired,
className: PropTypes.string.isRequired,
items: PropTypes.arrayOf(PropTypes.object).isRequired,
scrollIndex: PropTypes.number,
scrollTop: PropTypes.number,
scroller: PropTypes.instanceOf(Element).isRequired,
header: PropTypes.node.isRequired,
headerHeight: PropTypes.number.isRequired,
rowHeight: PropTypes.oneOfType([PropTypes.func, PropTypes.number]).isRequired,
rowRenderer: PropTypes.func.isRequired,
onRecompute: PropTypes.func.isRequired
};
VirtualTable.defaultProps = {
className: styles.tableContainer,
headerHeight: 38,
rowHeight: 38,
onRecompute: () => {}
};
export default VirtualTable;
|
test/test_helper.js
|
kleavjames/SimpleYoutubeSearchApp
|
import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
fields/types/boolean/BooleanField.js
|
danielmahon/keystone
|
import React from 'react';
import Field from '../Field';
import Checkbox from '../../components/Checkbox';
import { FormField } from '../../../admin/client/App/elemental';
const NOOP = () => {};
module.exports = Field.create({
displayName: 'BooleanField',
statics: {
type: 'Boolean',
},
propTypes: {
indent: React.PropTypes.bool,
label: React.PropTypes.string,
onChange: React.PropTypes.func.isRequired,
path: React.PropTypes.string.isRequired,
value: React.PropTypes.bool,
},
valueChanged (value) {
this.props.onChange({
path: this.props.path,
value: value,
});
},
renderFormInput () {
if (!this.shouldRenderField()) return;
return (
<input
name={this.getInputName(this.props.path)}
type="hidden"
value={!!this.props.value}
/>
);
},
renderUI () {
const { indent, value, label, path } = this.props;
return (
<div data-field-name={path} data-field-type="boolean">
<FormField offsetAbsentLabel={indent}>
<label style={{ height: '2.3em' }}>
{this.renderFormInput()}
<Checkbox
checked={value}
onChange={(this.shouldRenderField() && this.valueChanged) || NOOP}
readonly={!this.shouldRenderField()}
/>
<span style={{ marginLeft: '.75em' }}>
{label}
</span>
</label>
{this.renderNote()}
</FormField>
</div>
);
},
});
|
src/applications/disability-benefits/all-claims/pages/contactInformation.js
|
department-of-veterans-affairs/vets-website
|
import React from 'react';
// import _ from 'platform/utilities/data';
import merge from 'lodash/merge';
import omit from 'platform/utilities/data/omit';
import fullSchema from 'vets-json-schema/dist/21-526EZ-ALLCLAIMS-schema.json';
// import dateUI from 'platform/forms-system/src/js/definitions/date';
// import dateRangeUI from 'platform/forms-system/src/js/definitions/dateRange';
import phoneUI from 'platform/forms-system/src/js/definitions/phone';
import emailUI from 'platform/forms-system/src/js/definitions/email';
import ReviewCardField from 'platform/forms-system/src/js/components/ReviewCardField';
import {
contactInfoDescription,
contactInfoUpdateHelpDescription,
// forwardingAddressDescription,
// ForwardingAddressViewField,
phoneEmailViewField,
} from '../content/contactInformation';
// import { isInFuture } from '../validations';
// import { hasForwardingAddress, forwardingCountryIsUSA } from '../utils';
import { addressUISchema } from '../utils/schemas';
import {
ADDRESS_PATHS,
USA,
MILITARY_STATE_LABELS,
MILITARY_STATE_VALUES,
MILITARY_CITIES,
STATE_LABELS,
STATE_VALUES,
} from '../constants';
import {
validateMilitaryCity,
validateMilitaryState,
validateZIP,
} from '../validations';
const {
// forwardingAddress,
phoneAndEmail,
} = fullSchema.properties;
const mailingAddress = merge(
{
properties: {
'view:livesOnMilitaryBase': {
type: 'boolean',
},
'view:livesOnMilitaryBaseInfo': {
type: 'object',
properties: {},
},
},
},
fullSchema.definitions.address,
);
const countryEnum = fullSchema.definitions.country.enum;
const citySchema = fullSchema.definitions.address.properties.city;
export const uiSchema = {
'ui:title': 'Contact information',
'ui:description': contactInfoDescription,
phoneAndEmail: {
'ui:title': 'Phone & email',
'ui:field': ReviewCardField,
'ui:options': {
viewComponent: phoneEmailViewField,
},
primaryPhone: phoneUI('Phone number'),
emailAddress: emailUI(),
},
mailingAddress: {
...omit(
['ui:order'],
addressUISchema(ADDRESS_PATHS.mailingAddress, 'Mailing address', true),
),
'view:livesOnMilitaryBase': {
'ui:title':
'I live on a United States military base outside of the United States',
},
'view:livesOnMilitaryBaseInfo': {
'ui:description': () => (
<div className="vads-u-padding-x--2p5">
<va-additional-info trigger="Learn more about military base addresses">
<span>
The United States is automatically chosen as your country if you
live on a military base outside of the country.
</span>
</va-additional-info>
</div>
),
},
country: {
'ui:title': 'Country',
'ui:autocomplete': 'country',
'ui:options': {
updateSchema: (formData, schema, uiSchemaCountry) => {
const uiSchemaDisabled = uiSchemaCountry;
if (formData.mailingAddress?.['view:livesOnMilitaryBase']) {
const formDataMailingAddress = formData.mailingAddress;
formDataMailingAddress.country = USA;
uiSchemaDisabled['ui:disabled'] = true;
return {
enum: [USA],
};
}
uiSchemaDisabled['ui:disabled'] = false;
return {
enum: countryEnum,
};
},
},
},
addressLine1: {
'ui:title': 'Street address (20 characters maximum)',
'ui:autocomplete': 'address-line1',
'ui:errorMessages': {
required: 'Please enter a street address',
},
},
addressLine2: {
'ui:title': 'Street address line 2 (20 characters maximum)',
'ui:autocomplete': 'address-line2',
'ui:errorMessages': {
pattern: 'Please enter a valid street address',
},
},
addressLine3: {
'ui:title': 'Street address line 3 (20 characters maximum)',
'ui:autocomplete': 'address-line3',
'ui:errorMessages': {
pattern: 'Please enter a valid street address',
},
},
city: {
'ui:autocomplete': 'address-level2',
'ui:errorMessages': {
pattern: 'Please enter a valid city',
required: 'Please enter a city',
},
'ui:options': {
replaceSchema: formData => {
if (formData.mailingAddress?.['view:livesOnMilitaryBase'] === true) {
return {
type: 'string',
title: 'APO/FPO/DPO',
enum: MILITARY_CITIES,
};
}
return merge(
{
title: 'City',
},
citySchema,
);
},
},
'ui:validations': [
{
options: { addressPath: 'mailingAddress' },
// pathWithIndex is called in validateMilitaryCity
validator: validateMilitaryCity,
},
],
},
state: {
'ui:title': 'State',
'ui:autocomplete': 'address-level1',
'ui:options': {
hideIf: formData =>
!formData.mailingAddress?.['view:livesOnMilitaryBase'] &&
formData.mailingAddress.country !== USA,
updateSchema: formData => {
if (
formData.mailingAddress?.['view:livesOnMilitaryBase'] ||
MILITARY_CITIES.includes(formData.mailingAddress.city)
) {
return {
enum: MILITARY_STATE_VALUES,
enumNames: MILITARY_STATE_LABELS,
};
}
return {
enum: STATE_VALUES,
enumNames: STATE_LABELS,
};
},
},
'ui:required': formData =>
formData.mailingAddress?.['view:livesOnMilitaryBase'] ||
formData.mailingAddress.country === USA,
'ui:validations': [
{
options: { addressPath: 'mailingAddress' },
// pathWithIndex is called in validateMilitaryState
validator: validateMilitaryState,
},
],
'ui:errorMessages': {
pattern: 'Please enter a valid state',
required: 'Please enter a state',
},
},
zipCode: {
'ui:title': 'Postal code',
'ui:autocomplete': 'postal-code',
'ui:validations': [validateZIP],
'ui:required': formData =>
formData.mailingAddress?.['view:livesOnMilitaryBase'] ||
formData.mailingAddress.country === USA,
'ui:errorMessages': {
required: 'Please enter a postal code',
pattern:
'Please enter a valid 5- or 9-digit postal code (dashes allowed)',
},
'ui:options': {
widgetClassNames: 'va-input-medium-large',
hideIf: formData =>
!formData.mailingAddress?.['view:livesOnMilitaryBase'] &&
formData.mailingAddress.country !== USA,
},
},
},
// 'view:hasForwardingAddress': {
// 'ui:title': 'My address will be changing soon.',
// },
// forwardingAddress: merge(
// addressUISchema(ADDRESS_PATHS.forwardingAddress, 'Forwarding address'),
// {
// 'ui:field': ReviewCardField,
// 'ui:subtitle': forwardingAddressDescription,
// 'ui:order': [
// 'effectiveDate',
// 'country',
// 'addressLine1',
// 'addressLine2',
// 'addressLine3',
// 'city',
// 'state',
// 'zipCode',
// ],
// 'ui:options': {
// viewComponent: ForwardingAddressViewField,
// expandUnder: 'view:hasForwardingAddress',
// },
// effectiveDate: merge(
// dateRangeUI(
// 'Start date',
// 'End date (optional)',
// 'End date must be after start date',
// ),
// {
// from: {
// 'ui:required': hasForwardingAddress,
// 'ui:validations': [isInFuture],
// },
// },
// ),
// country: {
// 'ui:required': hasForwardingAddress,
// },
// addressLine1: {
// 'ui:required': hasForwardingAddress,
// },
// city: {
// 'ui:required': hasForwardingAddress,
// },
// state: {
// 'ui:required': formData =>
// hasForwardingAddress(formData) && forwardingCountryIsUSA(formData),
// },
// zipCode: {
// 'ui:required': formData =>
// hasForwardingAddress(formData) && forwardingCountryIsUSA(formData),
// },
// },
// ),
'view:contactInfoDescription': {
'ui:description': contactInfoUpdateHelpDescription,
},
};
export const schema = {
type: 'object',
properties: {
phoneAndEmail,
mailingAddress,
// 'view:hasForwardingAddress': {
// type: 'boolean',
// },
// forwardingAddress,
'view:contactInfoDescription': {
type: 'object',
properties: {},
},
},
};
|
src/containers/auth/AuthenticateView.js
|
yursky/recommend
|
/**
* Authenticate Screen
* - Entry screen for all authentication
* - User can tap to login, forget password, signup...
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { Component } from 'react';
import {
View,
Image,
StyleSheet,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
// Consts and Libs
import { AppStyles, AppSizes, AppColors } from '@theme/';
// Components
import { Spacer, Text, Button } from '@ui/';
/* Styles ==================================================================== */
const styles = StyleSheet.create({
background: {
backgroundColor: AppColors.brand.primary,
height: AppSizes.screen.height,
width: AppSizes.screen.width,
},
logo: {
width: AppSizes.screen.width * 0.85,
resizeMode: 'contain',
},
whiteText: {
color: '#FFF',
},
});
/* Component ==================================================================== */
class Authenticate extends Component {
static componentName = 'Authenticate';
render = () => (
<View style={[AppStyles.containerCentered, AppStyles.container, styles.background]}>
<Image
source={require('../../images/wide.png')}
style={[styles.logo]}
/>
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]}>
<Button
title={'Login'}
icon={{ name: 'lock' }}
onPress={Actions.login}
backgroundColor={'#CB009E'}
/>
</View>
</View>
<Spacer size={10} />
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]}>
<Button
title={'Sign up'}
icon={{ name: 'face' }}
onPress={Actions.signUp}
backgroundColor={'#CB009E'}
/>
</View>
</View>
<Spacer size={15} />
<Text p style={[AppStyles.textCenterAligned, styles.whiteText]}>
- or -
</Text>
<Spacer size={10} />
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]} />
<View style={[AppStyles.flex2]}>
<Button
small
title={'Skip'}
onPress={Actions.app}
raised={false}
backgroundColor={'rgba(255,255,255,0.2)'}
/>
</View>
<View style={[AppStyles.flex1]} />
</View>
<Spacer size={40} />
</View>
)
}
/* Export Component ==================================================================== */
export default Authenticate;
|
app/javascript/mastodon/features/followers/index.js
|
lindwurm/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import {
lookupAccount,
fetchAccount,
fetchFollowers,
expandFollowers,
} from '../../actions/accounts';
import { FormattedMessage } from 'react-intl';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import HeaderContainer from '../account_timeline/containers/header_container';
import ColumnBackButton from '../../components/column_back_button';
import ScrollableList from '../../components/scrollable_list';
import MissingIndicator from 'mastodon/components/missing_indicator';
import TimelineHint from 'mastodon/components/timeline_hint';
const mapStateToProps = (state, { params: { acct, id } }) => {
const accountId = id || state.getIn(['accounts_map', acct]);
if (!accountId) {
return {
isLoading: true,
};
}
return {
accountId,
remote: !!(state.getIn(['accounts', accountId, 'acct']) !== state.getIn(['accounts', accountId, 'username'])),
remoteUrl: state.getIn(['accounts', accountId, 'url']),
isAccount: !!state.getIn(['accounts', accountId]),
accountIds: state.getIn(['user_lists', 'followers', accountId, 'items']),
hasMore: !!state.getIn(['user_lists', 'followers', accountId, 'next']),
isLoading: state.getIn(['user_lists', 'followers', accountId, 'isLoading'], true),
blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false),
};
};
const RemoteHint = ({ url }) => (
<TimelineHint url={url} resource={<FormattedMessage id='timeline_hint.resources.followers' defaultMessage='Followers' />} />
);
RemoteHint.propTypes = {
url: PropTypes.string.isRequired,
};
export default @connect(mapStateToProps)
class Followers extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.shape({
acct: PropTypes.string,
id: PropTypes.string,
}).isRequired,
accountId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
blockedBy: PropTypes.bool,
isAccount: PropTypes.bool,
remote: PropTypes.bool,
remoteUrl: PropTypes.string,
multiColumn: PropTypes.bool,
};
_load () {
const { accountId, isAccount, dispatch } = this.props;
if (!isAccount) dispatch(fetchAccount(accountId));
dispatch(fetchFollowers(accountId));
}
componentDidMount () {
const { params: { acct }, accountId, dispatch } = this.props;
if (accountId) {
this._load();
} else {
dispatch(lookupAccount(acct));
}
}
componentDidUpdate (prevProps) {
const { params: { acct }, accountId, dispatch } = this.props;
if (prevProps.accountId !== accountId && accountId) {
this._load();
} else if (prevProps.params.acct !== acct) {
dispatch(lookupAccount(acct));
}
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandFollowers(this.props.accountId));
}, 300, { leading: true });
render () {
const { accountIds, hasMore, blockedBy, isAccount, multiColumn, isLoading, remote, remoteUrl } = this.props;
if (!isAccount) {
return (
<Column>
<MissingIndicator />
</Column>
);
}
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
let emptyMessage;
if (blockedBy) {
emptyMessage = <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' />;
} else if (remote && accountIds.isEmpty()) {
emptyMessage = <RemoteHint url={remoteUrl} />;
} else {
emptyMessage = <FormattedMessage id='account.followers.empty' defaultMessage='No one follows this user yet.' />;
}
const remoteMessage = remote ? <RemoteHint url={remoteUrl} /> : null;
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<ScrollableList
scrollKey='followers'
hasMore={hasMore}
isLoading={isLoading}
onLoadMore={this.handleLoadMore}
prepend={<HeaderContainer accountId={this.props.accountId} hideTabs />}
alwaysPrepend
append={remoteMessage}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
>
{blockedBy ? [] : accountIds.map(id =>
<AccountContainer key={id} id={id} withNote={false} />,
)}
</ScrollableList>
</Column>
);
}
}
|
client/modules/core/components/error.js
|
open-dash/open-dash
|
import React from 'react';
const CustomError = ({error}) => (
<div style={{ color: 'red', textAlign: 'center' }}>
{error.message}
</div>
);
export default CustomError;
|
src/server.js
|
nobleach/react-redux-example
|
import Express from 'express';
import React from 'react';
import Router from 'react-router';
import Location from 'react-router/lib/Location';
import routes from './views/routes';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createRedux from './redux/create';
import { Provider } from 'redux/react';
import api from './api/api';
import ApiClient from './ApiClient';
const app = new Express();
const proxy = httpProxy.createProxyServer({
target: 'http://localhost:' + config.apiPort
});
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'favicon.ico')));
let webpackStats;
if (process.env.NODE_ENV === 'production') {
webpackStats = require('../webpack-stats.json');
}
if (app.get('env') === 'production') {
app.use(require('serve-static')(path.join(__dirname, '..', 'static')));
}
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
app.use((req, res) => {
const client = new ApiClient(req);
const redux = createRedux(client);
const location = new Location(req.path, req.query);
if (process.env.NODE_ENV === 'development') {
webpackStats = require('../webpack-stats.json');
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
delete require.cache[require.resolve('../webpack-stats.json')];
}
Router.run(routes, location, (error, initialState) => {
if (error) {
res.status(500).send(error);
} else {
Promise.all(initialState.components
.filter(component => component.fetchData)
.map(component => {
return component.fetchData(redux.dispatch);
}))
.then(() => {
const state = redux.getState();
res.send('<!doctype html>\n' + React.renderToString(
<html lang="en-us">
<head>
<meta charSet="utf-8"/>
<title>React Redux Isomorphic Example</title>
<link rel="shortcut icon" href="/favicon.ico"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css"
media="screen, projection" rel="stylesheet" type="text/css"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"
media="screen, projection" rel="stylesheet" type="text/css"/>
{webpackStats.css.map((css, i) => <link href={css} ref={i}
media="screen, projection" rel="stylesheet" type="text/css"/>)}
</head>
<body>
<div id="content" dangerouslySetInnerHTML={{__html: React.renderToString(
<Provider redux={redux}>
{() => <Router location={location} {...initialState}/>}
</Provider>)
}}/>
<script dangerouslySetInnerHTML={{__html: `window.__data=${JSON.stringify(state)};`}}/>
<script src={webpackStats.script[0]}/>
</body>
</html>));
}).catch((err) => {
res.status(500).send(err.stack);
});
}
});
});
if (config.port) {
app.listen(config.port, (err) => {
if (err) {
console.error(err);
} else {
api().then(() => {
console.info('==> ✅ Server is listening');
console.info('==> 🌎 %s running on port %s, API on port %s', config.app.name, config.port, config.apiPort);
});
}
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
src/containers/Main.js
|
WapGeaR/react-redux-boilerplate-auth
|
import React from 'react'
import {BreadCrumbs, PageHeading} from 'template/layout'
import {Block} from 'template/components'
export default class Main extends React.Component {
render() {
return(
<div className="page-content">
<BreadCrumbs childs={[
{name: 'Dashboard', url: '/', last: true}
]}/>
<PageHeading title="Dashboard" />
<div className="container-fluid">
<div>
<div className="row">
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="warning"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="danger"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="success"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="information"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="purple"
additional="12 сайтов в цепи" />
</div>
<div className="col-md-3">
<Block
title="Автоматизация"
subtitle="еще 24 дня"
content="113 статей"
style="teal"
additional="12 сайтов в цепи" />
</div>
</div>
</div>
</div>
</div>)
}
}
|
src/components/tab/tab_body.js
|
n7best/react-weui
|
import React from 'react';
import classNames from '../../utils/classnames';
/**
* Content Wrapper for Tab
*/
export default class TabBody extends React.Component {
render() {
const {children, className, ...others} = this.props;
const cls = classNames({
'weui-tab__panel': true
}, className);
return (
<div className={cls} {...others}>
{children}
</div>
);
}
}
|
examples/todomvc/src/components/Master.js
|
lore/lore
|
/**
* This component serves as the root of your application, and should typically be the only
* component subscribed to the store.
*
* It is also a good place to fetch the current user. Once you have configured 'models/currentUser'
* to fetch the current user (by pointing it to the correct API endpoint) uncomment the commented
* out code below in order to fetch the user, display a loading experience while they're being
* fetched, and store the user in the applications context so that components can retrieve it
* without having to pass it down through props or extract it from the Redux store directly.
**/
import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
import { connect } from 'lore-hook-connect';
import PayloadStates from '../constants/PayloadStates';
import RemoveLoadingScreen from './RemoveLoadingScreen';
import 'todomvc-common/base.css';
import 'todomvc-app-css/index.css';
export default connect(function(getState, props) {
return {
// user: getState('currentUser')
};
}, { subscribe: true })(
createReactClass({
displayName: 'Master',
// propTypes: {
// user: PropTypes.object.isRequired
// },
// childContextTypes: {
// user: PropTypes.object
// },
// getChildContext() {
// return {
// user: this.props.user
// };
// },
componentDidMount() {
// If you want to play with the router through the browser's dev console then
// uncomment out this line. React Router automatically provides 'router'
// to any components that are "routes" (such as Master and Layout), so this
// is a good location to attach it to the global lore object.
// lore.router = this.props.router;
},
render() {
// const { user } = this.props;
// if (user.state === PayloadStates.FETCHING) {
// return null;
// }
return (
<div>
<RemoveLoadingScreen/>
{React.cloneElement(this.props.children)}
</div>
);
}
})
);
|
client/components/PhotoDetailContainer.js
|
yinkyo/react-redux-learning
|
import React from 'react';
import PhotoDetail from './PhotoDetail';
// import Comment from ./Comment;
const PhotoDetailContainer = React.createClass({
render() {
const i = this.props.posts.findIndex(
(post) => post.code === this.props.params.postId
);
const post = this.props.posts[i];
const comment = this.props.comments[post.code] ? this.props.comments[post.code] : []
return (
<PhotoDetail
{...post} i={i}
onClick={this.props.increment.bind(null, i)}
comment={comment} />
)
}
});
export default PhotoDetailContainer;
|
src/components/Button/icons/mail.js
|
yante/halfof8
|
import React from 'react';
export default ({ color }) => <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 16">
<g fill="none" fill-rule="evenodd">
<path d="M-2-4h24v24H-2z"/>
<path fill={color || "#5261FF"} fill-rule="nonzero" d="M18 0H2C.9 0 .01.9.01 2L0 14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zm0 14H2V4l8 5 8-5v10zm-8-7L2 2h16l-8 5z"/>
</g>
</svg>
|
src/svg-icons/action/restore-page.js
|
mtsandeep/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionRestorePage = (props) => (
<SvgIcon {...props}>
<path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm-2 16c-2.05 0-3.81-1.24-4.58-3h1.71c.63.9 1.68 1.5 2.87 1.5 1.93 0 3.5-1.57 3.5-3.5S13.93 9.5 12 9.5c-1.35 0-2.52.78-3.1 1.9l1.6 1.6h-4V9l1.3 1.3C8.69 8.92 10.23 8 12 8c2.76 0 5 2.24 5 5s-2.24 5-5 5z"/>
</SvgIcon>
);
ActionRestorePage = pure(ActionRestorePage);
ActionRestorePage.displayName = 'ActionRestorePage';
ActionRestorePage.muiName = 'SvgIcon';
export default ActionRestorePage;
|
node_modules/semantic-ui-react/dist/es/modules/Accordion/AccordionTitle.js
|
SuperUncleCat/ServerMonitoring
|
import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _isNil from 'lodash/isNil';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly, createShorthandFactory } from '../../lib';
import Icon from '../../elements/Icon';
/**
* A title sub-component for Accordion component.
*/
var AccordionTitle = function (_Component) {
_inherits(AccordionTitle, _Component);
function AccordionTitle() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, AccordionTitle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = AccordionTitle.__proto__ || Object.getPrototypeOf(AccordionTitle)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e, _this.props);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(AccordionTitle, [{
key: 'render',
value: function render() {
var _props = this.props,
active = _props.active,
children = _props.children,
className = _props.className,
content = _props.content;
var classes = cx(useKeyOnly(active, 'active'), 'title', className);
var rest = getUnhandledProps(AccordionTitle, this.props);
var ElementType = getElementType(AccordionTitle, this.props);
if (_isNil(content)) {
return React.createElement(
ElementType,
_extends({}, rest, { className: classes, onClick: this.handleClick }),
children
);
}
return React.createElement(
ElementType,
_extends({}, rest, { className: classes, onClick: this.handleClick }),
React.createElement(Icon, { name: 'dropdown' }),
content
);
}
}]);
return AccordionTitle;
}(Component);
AccordionTitle._meta = {
name: 'AccordionTitle',
type: META.TYPES.MODULE,
parent: 'Accordion'
};
AccordionTitle.handledProps = ['active', 'as', 'children', 'className', 'content', 'onClick'];
export default AccordionTitle;
AccordionTitle.propTypes = process.env.NODE_ENV !== "production" ? {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Whether or not the title is in the open state. */
active: PropTypes.bool,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
/**
* Called on click.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props.
*/
onClick: PropTypes.func
} : {};
AccordionTitle.create = createShorthandFactory(AccordionTitle, function (content) {
return { content: content };
});
|
src/components/containers/Zones.js
|
aerendon/yik-yak
|
import React, { Component } from 'react';
import Zone from '../presentation/Zone.js';
import superagent from 'superagent';
class Zones extends Component {
constructor() {
super()
this.state = {
zone: {
name: '',
zipCode: ''
},
list: []
}
}
componentDidMount() {
console.log('componentDidMount');
superagent
.get('/api/zone')
.query(null)
.set('Accept', 'application/json')
.end((err, response) => {
if (err) {
alert('ERROR: ' + err);
}
console.log(JSON.stringify(response.body));
let results = response.body.results;
this.setState({
list: results
});
});
}
updateZone(event) {
console.log(event.target.value);
let updatedZone = Object.assign({}, this.state.zone);
updatedZone[event.target.id] = event.target.value;
this.setState({
zone: updatedZone
})
}
addZone() {
console.log('ADD ZONE: ' + JSON.stringify(this.state.zone));
let updatedList = Object.assign([], this.state.list);
updatedList.push(this.state.zone);
this.setState({
list: updatedList
});
}
render() {
const listItems = this.state.list.map((zone, i) => {
return (
<li key={i}><Zone currentZone={zone} /></li>
)
});
return (
<div>
<ol>
{listItems}
</ol>
<input id="name" onChange={this.updateZone.bind(this)} className="form-control" type="text" placeholder="Name" /><br />
<input id="zipCode" onChange={this.updateZone.bind(this)} className="form-control" type="text" placeholder="Zip Code" /><br />
<button onClick={this.addZone.bind(this)} className="btn btn-danger">Add Zone</button>
</div>
);
}
}
export default Zones
|
packages/material-ui-icons/src/PlusOne.js
|
cherniavskii/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M10 8H8v4H4v2h4v4h2v-4h4v-2h-4zm4.5-1.92V7.9l2.5-.5V18h2V5z" /></g>
, 'PlusOne');
|
examples/huge-apps/routes/Course/components/Dashboard.js
|
frankleng/react-router
|
import React from 'react';
class Dashboard extends React.Component {
render () {
return (
<div>
<h3>Course Dashboard</h3>
</div>
);
}
}
export default Dashboard;
|
src/components/Main.js
|
aframevr/aframe-inspector
|
import React from 'react';
THREE.ImageUtils.crossOrigin = '';
const Events = require('../lib/Events.js');
import ComponentsSidebar from './components/Sidebar';
import ModalTextures from './modals/ModalTextures';
import ModalHelp from './modals/ModalHelp';
import SceneGraph from './scenegraph/SceneGraph';
import CameraToolbar from './viewport/CameraToolbar';
import TransformToolbar from './viewport/TransformToolbar';
import ViewportHUD from './viewport/ViewportHUD';
import { injectCSS } from '../lib/utils';
// Megahack to include font-awesome.
injectCSS('https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css');
export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
entity: null,
inspectorEnabled: true,
isModalTexturesOpen: false,
sceneEl: AFRAME.scenes[0],
visible: {
scenegraph: true,
attributes: true
}
};
Events.on('togglesidebar', event => {
if (event.which === 'all') {
if (this.state.visible.scenegraph || this.state.visible.attributes) {
this.setState({
visible: {
scenegraph: false,
attributes: false
}
});
} else {
this.setState({
visible: {
scenegraph: true,
attributes: true
}
});
}
} else if (event.which === 'attributes') {
this.setState(prevState => ({
visible: {
attributes: !prevState.visible.attributes
}
}));
} else if (event.which === 'scenegraph') {
this.setState(prevState => ({
visible: {
scenegraph: !prevState.visible.scenegraph
}
}));
}
this.forceUpdate();
});
}
componentDidMount() {
Events.on(
'opentexturesmodal',
function(selectedTexture, textureOnClose) {
this.setState({
selectedTexture: selectedTexture,
isModalTexturesOpen: true,
textureOnClose: textureOnClose
});
}.bind(this)
);
Events.on('entityselect', entity => {
this.setState({ entity: entity });
});
Events.on('inspectortoggle', enabled => {
this.setState({ inspectorEnabled: enabled });
});
Events.on('openhelpmodal', () => {
this.setState({ isHelpOpen: true });
});
}
onCloseHelpModal = value => {
this.setState({ isHelpOpen: false });
};
onModalTextureOnClose = value => {
this.setState({ isModalTexturesOpen: false });
if (this.state.textureOnClose) {
this.state.textureOnClose(value);
}
};
toggleEdit = () => {
if (this.state.inspectorEnabled) {
AFRAME.INSPECTOR.close();
} else {
AFRAME.INSPECTOR.open();
}
};
renderComponentsToggle() {
if (!this.state.entity || this.state.visible.attributes) {
return null;
}
return (
<div className="toggle-sidebar right">
<a
onClick={() => {
this.setState({ visible: { attributes: true } });
this.forceUpdate();
}}
className="fa fa-plus"
title="Show components"
/>
</div>
);
}
renderSceneGraphToggle() {
if (this.state.visible.scenegraph) {
return null;
}
return (
<div className="toggle-sidebar left">
<a
onClick={() => {
this.setState({ visible: { scenegraph: true } });
this.forceUpdate();
}}
className="fa fa-plus"
title="Show scenegraph"
/>
</div>
);
}
render() {
const scene = this.state.sceneEl;
const toggleButtonText = this.state.inspectorEnabled
? 'Back to Scene'
: 'Inspect Scene';
return (
<div>
<a className="toggle-edit" onClick={this.toggleEdit}>
{toggleButtonText}
</a>
{this.renderSceneGraphToggle()}
{this.renderComponentsToggle()}
<div
id="inspectorContainer"
className={this.state.inspectorEnabled ? '' : 'hidden'}
>
<SceneGraph
scene={scene}
selectedEntity={this.state.entity}
visible={this.state.visible.scenegraph}
/>
<div id="viewportBar">
<CameraToolbar />
<ViewportHUD />
<TransformToolbar />
</div>
<div id="rightPanel">
<ComponentsSidebar
entity={this.state.entity}
visible={this.state.visible.attributes}
/>
</div>
</div>
<ModalHelp
isOpen={this.state.isHelpOpen}
onClose={this.onCloseHelpModal}
/>
<ModalTextures
ref="modaltextures"
isOpen={this.state.isModalTexturesOpen}
selectedTexture={this.state.selectedTexture}
onClose={this.onModalTextureOnClose}
/>
</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.