path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
demos/react/react-native.js | iCasa/js-xlsx | /* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
import * as XLSX from 'xlsx';
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View, Button, Alert, Image } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';
// react-native-fs
import { writeFile, readFile, DocumentDirectoryPath } from 'react-native-fs';
const DDP = DocumentDirectoryPath + "/";
const input = res => res;
const output = str => str;
// react-native-fetch-blob
/*
import RNFetchBlob from 'react-native-fetch-blob';
const { writeFile, readFile, dirs:{ DocumentDir } } = RNFetchBlob.fs;
const DDP = DocumentDir + "/";
const input = res => res.map(x => String.fromCharCode(x)).join("");
const output = str => str.split("").map(x => x.charCodeAt(0));
*/
const make_cols = refstr => Array.from({length: XLSX.utils.decode_range(refstr).e.c + 1}, (x,i) => XLSX.utils.encode_col(i));
export default class SheetJS extends Component {
constructor(props) {
super(props);
this.state = {
data: [[1,2,3],[4,5,6]],
cols: make_cols("A1:C2")
};
this.importFile = this.importFile.bind(this);
this.exportFile = this.exportFile.bind(this);
};
importFile() {
Alert.alert("Rename file to sheetjs.xlsx", "Copy to " + DDP, [
{text: 'Cancel', onPress: () => {}, style: 'cancel' },
{text: 'Import', onPress: () => {
readFile(DDP + "sheetjs.xlsx", 'ascii').then((res) => {
/* parse file */
const wb = XLSX.read(input(res), {type:'binary'});
/* convert first worksheet to AOA */
const wsname = wb.SheetNames[0];
const ws = wb.Sheets[wsname];
const data = XLSX.utils.sheet_to_json(ws, {header:1});
/* update state */
this.setState({ data: data, cols: make_cols(ws['!ref']) });
}).catch((err) => { Alert.alert("importFile Error", "Error " + err.message); });
}}
]);
}
exportFile() {
/* convert AOA back to worksheet */
const ws = XLSX.utils.aoa_to_sheet(this.state.data);
/* build new workbook */
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "SheetJS");
/* write file */
const wbout = XLSX.write(wb, {type:'binary', bookType:"xlsx"});
const file = DDP + "sheetjsw.xlsx";
writeFile(file, output(wbout), 'ascii').then((res) =>{
Alert.alert("exportFile success", "Exported to " + file);
}).catch((err) => { Alert.alert("exportFile Error", "Error " + err.message); });
};
render() { return (
<View style={styles.container}>
<Image style={{width: 128, height: 128}} source={require('./logo.png')} />
<Text style={styles.welcome}>SheetJS React Native Demo</Text>
<Text style={styles.instructions}>Import Data</Text>
<Button onPress={this.importFile} title="Import data from a spreadsheet" color="#841584" />
<Text style={styles.instructions}>Export Data</Text>
<Button disabled={!this.state.data.length} onPress={this.exportFile} title="Export data to XLSX" color="#841584" />
<Text style={styles.instructions}>Current Data</Text>
<Table style={styles.table}>
<Row data={this.state.cols} style={styles.thead} textStyle={styles.text}/>
<Rows data={this.state.data} style={styles.tr} textStyle={styles.text}/>
</Table>
</View>
); };
};
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF' },
welcome: { fontSize: 20, textAlign: 'center', margin: 10 },
instructions: { textAlign: 'center', color: '#333333', marginBottom: 5 },
thead: { height: 40, backgroundColor: '#f1f8ff' },
tr: { height: 30 },
text: { marginLeft: 5 },
table: { width: "100%" }
});
AppRegistry.registerComponent('SheetJS', () => SheetJS);
|
docs/src/SupportPage.js | victorzhang17/react-bootstrap | import React from 'react';
import NavMain from './NavMain';
import PageHeader from './PageHeader';
import PageFooter from './PageFooter';
export default class Page extends React.Component {
render() {
return (
<div>
<NavMain activePage="support" />
<PageHeader
title="Need help?"
subTitle="Community resources for answering your React-Bootstrap questions." />
<div className="container bs-docs-container">
<div className="row">
<div className="col-md-9" role="main">
<div className="bs-docs-section">
<p className="lead">Stay up to date on the development of React-Bootstrap and reach out to the community with these helpful resources.</p>
<h3>Stack Overflow</h3>
<p><a href="http://stackoverflow.com/questions/ask">Ask questions</a> about specific problems you have faced, including details about what exactly you are trying to do. Make sure you tag your question with <code className="js">react-bootstrap</code>. You can also read through <a href="http://stackoverflow.com/questions/tagged/react-bootstrap">existing React-Bootstrap questions</a>.</p>
<h3>Live help</h3>
<p>Bring your questions and pair with other react-bootstrap users in a <a href="http://start.thinkful.com/react/?utm_source=github&utm_medium=badge&utm_campaign=react-bootstrap">live Thinkful hangout</a>. Hear about the challenges other developers are running into, or screenshare your own code with the group for feedback.</p>
<h3>Chat rooms</h3>
<p>Discuss questions in the <code className="js">#react-bootstrap</code> channel on the <a href="http://www.reactiflux.com/">Reactiflux Slack</a> or on <a href="https://gitter.im/react-bootstrap/react-bootstrap">Gitter</a>.</p>
<h3>GitHub issues</h3>
<p>The issue tracker is the preferred channel for bug reports, features requests and submitting pull requests. See more about how we use issues in the <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/CONTRIBUTING.md#issues">contribution guidelines</a>.</p>
</div>
</div>
</div>
</div>
<PageFooter />
</div>
);
}
shouldComponentUpdate() {
return false;
}
}
|
pootle/static/js/shared/mixins/FormValidationMixin.js | unho/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react'; // eslint-disable-line no-unused-vars
export const FormValidationMixin = {
getInitialState() {
return {
errors: {},
};
},
clearValidation() {
this.setState({ errors: {} });
},
validateResponse(xhr) {
// XXX: should this also check for HTTP 500, 404 etc.?
const response = JSON.parse(xhr.responseText);
this.setState({ errors: response.errors });
},
/* Layout */
renderSingleError(errorMsg, i) {
return <li key={i}>{errorMsg}</li>;
},
/* Renders form's global errors. These errors come in a special
* `__all__` field */
renderAllFormErrors() {
const { errors } = this.state;
if (errors.hasOwnProperty('__all__')) {
return (
<ul className="errorlist errorlist-all">
{errors.__all__.map(this.renderSingleError)}
</ul>
);
}
return null;
},
};
export default FormValidationMixin;
|
src/clincoded/static/components/individual_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, 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 { parseAndLogError } from './mixins';
import { parsePubmed } from '../libs/parse-pubmed';
import { AddResourceId } from './add_external_resource';
import * as CuratorHistory from './curator_history';
import * as methods from './methods';
import { ScoreIndividual } from './score/individual_score';
import { ScoreViewer } from './score/viewer';
import HpoTermModal from './hpo_term_modal';
import { IndividualDisease } from './disease';
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;
const MAX_VARIANTS = 2;
const IndividualCuration = createReactClass({
mixins: [FormMixin, RestMixin, CurationMixin, CuratorHistory],
contextTypes: {
navigate: PropTypes.func
},
// Keeps track of values from the query string
queryValues: {},
propTypes: {
session: PropTypes.object,
href: PropTypes.string
},
getInitialState() {
return {
proband_selected: null, // select proband at the form
gdm: null, // GDM object given in query string
group: null, // Group object given in query string
family: null, // Family object given in query string
individual: null, // If we're editing an individual, this gets the fleshed-out individual object we're editing
annotation: null, // Annotation object given in query string
extraIndividualCount: 0, // Number of extra families to create
extraIndividualNames: [], // Names of extra families to create
variantCount: 0, // Number of variants loaded
variantInfo: {}, // Extra holding info for variant display
individualName: '', // Currently entered individual name
genotyping2Disabled: true, // True if genotyping method 2 dropdown disabled
proband: null, // If we have an associated family that has a proband, this points at it
biallelicHetOrHom: null, // Conditional rendering of denovo questions depending on proband answer for semidom
submitBusy: false, // True while form is submitting
recessiveZygosity: null, // Indicates which zygosity checkbox should be checked, if any
userScoreObj: {}, // Logged-in user's score object
diseaseObj: {},
diseaseUuid: null,
diseaseError: null,
scoreError: false,
scoreErrorMsg: '',
hpoWithTerms: [],
hpoElimWithTerms: []
};
},
// 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({scoreError: false, scoreErrorMsg: ''});
}
});
},
// Handle value changes in various form fields
handleChange: function(ref, e) {
var dbsnpid, clinvarid, hgvsterm, othervariant;
if (ref === 'genotypingmethod1' && this.refs[ref].getValue()) {
// Disable the Genotyping Method 2 if Genotyping Method 1 has no value
this.setState({genotyping2Disabled: this.refs[ref].getValue() === 'none'});
} else if (ref === 'individualname') {
this.setState({individualName: this.refs[ref].getValue()});
} else if (ref === 'zygosityHomozygous') {
if (this.refs[ref].toggleValue()) {
this.setState({recessiveZygosity: 'Homozygous'});
this.refs['zygosityHemizygous'].resetValue();
} else {
this.setState({recessiveZygosity: null});
}
} else if (ref === 'zygosityHemizygous') {
if (this.refs[ref].toggleValue()) {
this.setState({recessiveZygosity: 'Hemizygous'});
this.refs['zygosityHomozygous'].resetValue();
} else {
this.setState({recessiveZygosity: null});
}
} else if (ref === 'proband' && this.refs[ref].getValue() === 'Yes') {
this.setState({proband_selected: true});
} else if (ref === 'proband') {
this.setState({proband_selected: false});
} else if (ref === 'probandIs') {
if (this.refs[ref].getValue() === 'Biallelic homozygous' || this.refs[ref].getValue() === 'Biallelic compound heterozygous') {
this.setState({biallelicHetOrHom: true});
} else {
this.setState({biallelicHetOrHom: false});
}
}
},
// Handle a click on a copy phenotype/demographics button
handleClick: function(obj, item, e) {
e.preventDefault(); e.stopPropagation();
var hpoIds = '';
var hpoElimIds = '';
if (item === 'phenotype') {
if (obj.hpoIdInDiagnosis && obj.hpoIdInDiagnosis.length) {
hpoIds = obj.hpoIdInDiagnosis.map(function(hpoid, i) {
return (hpoid);
});
this.setState({ hpoWithTerms: hpoIds });
} else {
this.setState({ hpoWithTerms: [] });
}
if (obj.termsInDiagnosis) {
this.refs['phenoterms'].setValue(obj.termsInDiagnosis);
}
} else if (item === 'demographics') {
if (obj.countryOfOrigin) {
this.refs['country'].setValue(obj.countryOfOrigin);
}
if (obj.ethnicity) {
this.refs['ethnicity'].setValue(obj.ethnicity);
}
if (obj.race) {
this.refs['race'].setValue(obj.race);
}
} else if (item === 'notphenotype') {
if (obj.hpoIdInElimination && obj.hpoIdInElimination.length) {
hpoElimIds = obj.hpoIdInElimination.map(function(elimhpo, i) {
return (elimhpo);
});
this.setState({ hpoElimWithTerms: hpoElimIds });
} else {
this.setState({ hpoElimWithTerms: [] });
}
if (obj.termsInElimination) {
this.refs['notphenoterms'].setValue(obj.termsInElimination);
}
}
},
// 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 groupUuid = this.queryValues.groupUuid;
var familyUuid = this.queryValues.familyUuid;
var individualUuid = this.queryValues.individualUuid;
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 : '',
groupUuid ? '/groups/' + groupUuid : '',
familyUuid ? '/families/' + familyUuid: '',
individualUuid ? '/individuals/' + individualUuid: '',
annotationUuid ? '/evidence/' + annotationUuid : ''
]);
// With all given query string variables, get the corresponding objects from the DB.
this.getRestDatas(
uris
).then(datas => {
// 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 'group':
stateObj.group = data;
break;
case 'family':
stateObj.family = data;
break;
case 'individual':
stateObj.individual = 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 && stateObj.gdm.omimId) {
this.setOmimIdState(stateObj.gdm.omimId);
}
// Update the individual name
if (stateObj.individual) {
this.setState({individualName: stateObj.individual.label});
if (stateObj.individual.diagnosis && stateObj.individual.diagnosis.length > 0) {
this.setState({diseaseObj: stateObj.individual['diagnosis'][0]});
}
if (stateObj.individual['hpoIdInDiagnosis'] && stateObj.individual['hpoIdInDiagnosis'].length > 0) {
this.setState({ hpoWithTerms: stateObj.individual['hpoIdInDiagnosis'] });
}
if (stateObj.individual['hpoIdInElimination'] && stateObj.individual['hpoIdInElimination'].length > 0) {
this.setState({ hpoElimWithTerms: stateObj.individual['hpoIdInElimination'] });
}
if (stateObj.individual.proband) {
// proband individual
this.setState({proband_selected: true});
}
else {
this.setState({proband_selected: false});
}
if (stateObj.individual.probandIs === 'Biallelic homozygous' || stateObj.individual.probandIs === 'Biallelic compound heterozygous') {
this.setState({biallelicHetOrHom: true});
}
}
// Based on the loaded data, see if the second genotyping method drop-down needs to be disabled.
// Also see if we need to disable the Add Variant button
if (stateObj.individual) {
stateObj.genotyping2Disabled = !(stateObj.individual.method && stateObj.individual.method.genotypingMethods && stateObj.individual.method.genotypingMethods.length);
stateObj.recessiveZygosity = stateObj.individual.recessiveZygosity ? stateObj.individual.recessiveZygosity : null;
// If this individual has variants and isn't the proband in a family, handle the variant panels.
if (stateObj.individual.variants && stateObj.individual.variants.length && !(stateObj.individual.proband && stateObj.family)) {
var variants = stateObj.individual.variants;
// This individual has variants
stateObj.variantCount = variants.length ? variants.length : 0;
stateObj.variantInfo = {};
// Go through each variant to determine how its form fields should be disabled.
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,
'associatedPathogenicities': variants[i].associatedPathogenicities && variants[i].associatedPathogenicities.length ? variants[i].associatedPathogenicities : []
};
}
}
}
}
// If we didn't get a family in the query string, see if we're editing an individual, and it has associated
// families. If it does, get the first (really the only) one.
if (!stateObj.family && stateObj.individual && stateObj.individual.associatedFamilies && stateObj.individual.associatedFamilies.length) {
stateObj.family = stateObj.individual.associatedFamilies[0];
}
// If we have a family, see if it has a proband
if (stateObj.family && stateObj.family.individualIncluded && stateObj.family.individualIncluded.length) {
var proband = _(stateObj.family.individualIncluded).find(function(individual) {
return individual.proband;
});
if (proband) {
stateObj.proband = proband;
}
}
// Set all the state variables we've collected
this.setState(stateObj);
// No annotation; just resolve with an empty promise.
return Promise.resolve();
});
},
// Called when user changes the number of copies of family
extraIndividualCountChanged: function(ref, e) {
this.setState({extraIndividualCount: e.target.value});
},
// Write a family object to the DB.
writeIndividualObj: function(newIndividual, individualLabel) {
var methodPromise; // Promise from writing (POST/PUT) a method to the DB
// Get a new family object ready for writing. Modify a copy of it instead
// of the one we were given.
var writerIndividual = _.clone(newIndividual);
if (individualLabel) {
writerIndividual.label = individualLabel;
}
// If a method and/or segregation object was created (at least one method/segregation field set), assign it to the individual.
// If writing multiple family objects, reuse the one we made, but assign new methods and segregations because each family
// needs unique objects here.
var newMethod = methods.create.call(this);
if (newMethod) {
writerIndividual.method = newMethod;
}
// Either update or create the individual object in the DB
if (this.state.individual) {
// We're editing a family. PUT the new family object to the DB to update the existing one.
return this.putRestData('/individuals/' + this.state.individual.uuid, writerIndividual).then(data => {
return Promise.resolve(data['@graph'][0]);
});
} else {
// We created a family; post it to the DB
return this.postRestData('/individuals/', writerIndividual).then(data => {
return Promise.resolve(data['@graph'][0]);
});
}
},
// Called when a form is submitted.
submitForm: function(e) {
e.preventDefault(); e.stopPropagation(); // Don't run through HTML submit handler
// Save all form values from the DOM.
this.saveAllFormValues();
/**
* 1) Make sure there is an explanation for the score selected differently from the default score
* 2) Make sure there is a selection of the 'Confirm Case Information type' if the 'Select Status'
* value equals '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({scoreError: true, scoreErrorMsg: 'A reason is required for the changed score.'});
return false;
}
if (newUserScoreObj['scoreStatus'] === 'Score' && !newUserScoreObj['caseInfoType']) {
this.setState({scoreError: true, scoreErrorMsg: 'A case information type is required for the Score status.'});
return false;
}
}
// Start with default validation; indicate errors on form if not, then bail
if (this.validateDefault()) {
var family = this.state.family;
let gdm = this.state.gdm;
var currIndividual = this.state.individual;
var newIndividual = {}; // Holds the new group object;
var individualDiseases = [], individualArticles, individualVariants = [];
var evidenceScores = []; // Holds new array of scores
let individualScores = currIndividual && currIndividual.scores ? currIndividual.scores : [];
const semiDom = gdm && gdm.modeInheritance ? gdm.modeInheritance.indexOf('Semidominant') > -1 : false;
const maxVariants = semiDom ? 3 : MAX_VARIANTS;
// Find any pre-existing score(s) and put their '@id' values into an array
if (individualScores.length) {
individualScores.forEach(score => {
evidenceScores.push(score['@id']);
});
}
var formError = false;
var pmids = curator.capture.pmids(this.getFormValue('otherpmids'));
var hpoIds = this.state.hpoWithTerms ? this.state.hpoWithTerms : null;
var notHpoIds = this.state.hpoElimWithTerms ? this.state.hpoElimWithTerms : null;
let recessiveZygosity = this.state.recessiveZygosity;
let variantUuid0 = this.getFormValue('variantUuid0'),
variantUuid1 = this.getFormValue('variantUuid1');
// Disease is required for proband individual
if (this.state.proband_selected && (this.state.diseaseObj && !Object.keys(this.state.diseaseObj).length)) {
formError = true;
this.setState({diseaseError: 'Required for proband'}, () => {
this.setFormErrors('diseaseError', 'Required for proband');
});
}
// Check that all gene symbols have the proper format (will check for existence later)
if (pmids && pmids.length && _(pmids).any(function(id) { return id === null; })) {
// PMID list is bad
formError = true;
this.setFormErrors('otherpmids', 'Use PubMed IDs (e.g. 12345678) separated by commas');
}
// Get variant uuid's if they were added via the modals
for (var i = 0; i < maxVariants; i++) {
// Grab the values from the variant form panel
var variantId = this.getFormValue('variantUuid' + i);
// Build the search string depending on what the user entered
if (variantId) {
// Make a search string for these terms
individualVariants.push('/variants/' + variantId);
}
}
if (!formError) {
let searchStr;
this.setState({submitBusy: true});
/**
* Retrieve disease from database. If not existed, add it to the database.
*/
let diseaseObj = this.state.diseaseObj;
if (Object.keys(diseaseObj).length && diseaseObj.diseaseId) {
searchStr = '/search?type=disease&diseaseId=' + diseaseObj.diseaseId;
} else {
/**
* Disease is not required for a non-proband
*/
searchStr = '';
}
this.getRestData(searchStr).then(diseaseSearch => {
if (Object.keys(diseaseSearch).length && diseaseSearch.hasOwnProperty('total')) {
let diseaseUuid;
if (diseaseSearch.total === 0) {
return this.postRestData('/diseases/', diseaseObj).then(result => {
let newDisease = result['@graph'][0];
diseaseUuid = newDisease['uuid'];
this.setState({diseaseUuid: diseaseUuid}, () => {
individualDiseases.push(diseaseUuid);
return Promise.resolve(result);
});
});
} else {
let _id = diseaseSearch['@graph'][0]['@id'];
diseaseUuid = _id.slice(10, -1);
this.setState({diseaseUuid: diseaseUuid}, () => {
individualDiseases.push(diseaseUuid);
});
}
} else {
return Promise.resolve(null);
}
}, e => {
// The given disease couldn't be retrieved for some reason.
this.setState({submitBusy: false}); // submit error; re-enable submit button
this.setState({diseaseError: 'Error on validating disease.'});
throw e;
}).then(diseases => {
// Handle 'Add any other PMID(s) that have evidence about this same Group' list of PMIDs
if (pmids && pmids.length) {
// User entered at least one PMID
searchStr = '/search/?type=article&' + pmids.map(function(pmid) { return 'pmid=' + pmid; }).join('&');
return this.getRestData(searchStr).then(articles => {
if (articles['@graph'].length === pmids.length) {
// Successfully retrieved all PMIDs, so just set individualArticles and return
individualArticles = articles;
return Promise.resolve(articles);
} else {
// some PMIDs were not in our db already
// generate list of PMIDs and pubmed URLs for those PMIDs
var missingPmids = _.difference(pmids, articles['@graph'].map(function(article) { return article.pmid; }));
var missingPmidsUrls = [];
for (var missingPmidsIndex = 0; missingPmidsIndex < missingPmids.length; missingPmidsIndex++) {
missingPmidsUrls.push(external_url_map['PubMedSearch'] + missingPmids[missingPmidsIndex]);
}
// get the XML for the missing PMIDs
return this.getRestDatasXml(missingPmidsUrls).then(xml => {
var newArticles = [];
var invalidPmids = [];
var tempArticle;
// loop through the resulting XMLs and parsePubmed them
for (var xmlIndex = 0; xmlIndex < xml.length; xmlIndex++) {
tempArticle = parsePubmed(xml[xmlIndex]);
// check to see if Pubmed actually had an entry for the PMID
if ('pmid' in tempArticle) {
newArticles.push(tempArticle);
} else {
// PMID was not found at Pubmed
invalidPmids.push(missingPmids[xmlIndex]);
}
}
// if there were invalid PMIDs, throw an error with a list of them
if (invalidPmids.length > 0) {
this.setState({submitBusy: false}); // submit error; re-enable submit button
this.setFormErrors('otherpmids', 'PMID(s) ' + invalidPmids.join(', ') + ' not found');
throw invalidPmids;
}
// otherwise, post the valid PMIDs
if (newArticles.length > 0) {
return this.postRestDatas('/articles', newArticles).then(data => {
for (var dataIndex = 0; dataIndex < data.length; dataIndex++) {
articles['@graph'].push(data[dataIndex]['@graph'][0]);
}
individualArticles = articles;
return Promise.resolve(data);
});
}
return Promise(articles);
});
}
});
} else {
// No PMIDs entered; just pass null to the next then
return Promise.resolve(null);
}
}).then(data => {
var newVariants = [];
if (currIndividual && currIndividual.proband && family) {
// Editing a proband in a family. Get updated variants list from the target individual since it is changed from the Family edit page
return this.getRestData('/individuals/' + currIndividual.uuid).then(updatedIndiv => {
newVariants = updatedIndiv.variants.map(function(variant) { return '/variants/' + variant.uuid + '/'; });
return Promise.resolve(newVariants);
});
}
// No variant search strings. Go to next THEN.
return Promise.resolve([]);
}).then(newVariants => {
if (currIndividual && currIndividual.proband && family) {
individualVariants = newVariants;
}
// No variant search strings. Go to next THEN indicating no new named variants
return Promise.resolve(null);
}).then(response => {
/*************************************************************/
/* 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(data => {
// Make a new individual object based on form fields.
var newIndividual = this.createIndividual(individualDiseases, individualArticles, individualVariants, evidenceScores, hpoIds, notHpoIds);
return this.writeIndividualObj(newIndividual);
}).then(newIndividual => {
var promise;
// If we're adding this individual to a group, update the group with this family; otherwise update the annotation
// with the family.
if (!this.state.individual) {
if (this.state.group) {
// Add the newly saved individual to a group
promise = this.getRestData('/groups/' + this.state.group.uuid, null, true).then(freshGroup => {
var group = curator.flatten(freshGroup);
if (!group.individualIncluded) {
group.individualIncluded = [];
}
group.individualIncluded.push(newIndividual['@id']);
// Post the modified group to the DB
return this.putRestData('/groups/' + this.state.group.uuid, group).then(data => {
return {individual: newIndividual, group: data['@graph'][0], modified: false};
});
});
} else if (this.state.family) {
// Add the newly saved individual to a family
promise = this.getRestData('/families/' + this.state.family.uuid, null, true).then(freshFamily => {
var family = curator.flatten(freshFamily);
if (!family.individualIncluded) {
family.individualIncluded = [];
}
family.individualIncluded.push(newIndividual['@id']);
// Post the modified family to the DB
return this.putRestData('/families/' + this.state.family.uuid, family).then(data => {
return {individual: newIndividual, family: data['@graph'][0], modified: false};
});
});
} else {
// Not part of a group or family, so add the individual to the annotation instead.
promise = this.getRestData('/evidence/' + this.state.annotation.uuid, null, true).then(freshAnnotation => {
// Get a flattened copy of the fresh annotation object and put our new individual into it,
// ready for writing.
var annotation = curator.flatten(freshAnnotation);
if (!annotation.individuals) {
annotation.individuals = [];
}
annotation.individuals.push(newIndividual['@id']);
// Post the modified annotation to the DB
return this.putRestData('/evidence/' + this.state.annotation.uuid, annotation).then(data => {
return {individual: newIndividual, annotation: data['@graph'][0], modified: false};
});
});
}
} else {
// Editing an individual; not creating one
promise = Promise.resolve({individual: newIndividual, modified: true});
}
return promise;
}).then(data => {
// Add to the user history. data.individual always contains the new or edited individual. data.group contains the group the individual was
// added to, if it was added to a group. data.annotation contains the annotation the individual was added to, if it was added to
// the annotation, and data.family contains the family the individual was added to, if it was added to a family. If none of data.group,
// data.family, nor data.annotation exist, data.individual holds the existing individual that was modified.
recordIndividualHistory(this.state.gdm, this.state.annotation, data.individual, data.group, data.family, data.modified, this);
// Navigate to Curation Central or Family Submit page, depending on previous page
this.resetAllFormValues();
if (this.queryValues.editShortcut) {
this.context.navigate('/curation-central/?gdm=' + this.state.gdm.uuid + '&pmid=' + this.state.annotation.article.pmid);
} else {
var submitLink = '/individual-submit/?gdm=' + this.state.gdm.uuid + '&evidence=' + this.state.annotation.uuid + '&individual=' + data.individual.uuid;
if (this.state.family) {
submitLink += '&family=' + this.state.family.uuid;
} else if (this.state.group) {
submitLink += '&group=' + this.state.group.uuid;
}
this.context.navigate(submitLink);
}
}).catch(function(e) {
console.log('INDIVIDUAL CREATION ERROR=: %o', e);
});
}
}
},
// Create a family object to be written to the database. Most values come from the values
// in the form. The created object is returned from the function.
createIndividual: function(individualDiseases, individualArticles, individualVariants, individualScores, hpoIds, notHpoIds) {
var value;
var currIndividual = this.state.individual;
var family = this.state.family;
const semiDom = this.state.gdm && this.state.gdm.modeInheritance ? this.state.gdm.modeInheritance.indexOf('Semidominant') > -1 : false;
// Make a new family. If we're editing the form, first copy the old family
// to make sure we have everything not from the form.
var newIndividual = this.state.individual ? curator.flatten(this.state.individual) : {};
newIndividual.label = this.getFormValue('individualname');
// Get an array of all given disease IDs
if (individualDiseases && individualDiseases.length) {
newIndividual.diagnosis = individualDiseases.map(disease => { return disease; });
}
else if (newIndividual.diagnosis && newIndividual.diagnosis.length > 0) {
delete newIndividual.diagnosis;
}
// Fill in the individual fields from the Diseases & Phenotypes panel
if (hpoIds && hpoIds.length) {
newIndividual.hpoIdInDiagnosis = hpoIds;
} else if (newIndividual.hpoIdInDiagnosis) {
delete newIndividual.hpoIdInDiagnosis;
}
var phenoterms = this.getFormValue('phenoterms');
if (phenoterms) {
newIndividual.termsInDiagnosis = phenoterms;
} else if (newIndividual.termsInDiagnosis) {
delete newIndividual.termsInDiagnosis;
}
if (notHpoIds && notHpoIds.length) {
newIndividual.hpoIdInElimination = notHpoIds;
}
else if (newIndividual.hpoIdInElimination) {
delete newIndividual.hpoIdInElimination
}
phenoterms = this.getFormValue('notphenoterms');
if (phenoterms) {
newIndividual.termsInElimination = phenoterms;
}
// Fill in the individual fields from the Demographics panel
value = this.getFormValue('sex');
if (value !== 'none') { newIndividual.sex = value; }
value = this.getFormValue('country');
if (value !== 'none') {
newIndividual.countryOfOrigin = value;
} else {
if (newIndividual && newIndividual.countryOfOrigin) {
delete newIndividual['countryOfOrigin'];
}
}
value = this.getFormValue('ethnicity');
if (value !== 'none') {
newIndividual.ethnicity = value;
} else {
if (newIndividual && newIndividual.ethnicity) {
delete newIndividual['ethnicity'];
}
}
value = this.getFormValue('race');
if (value !== 'none') {
newIndividual.race = value;
} else {
if (newIndividual && newIndividual.race) {
delete newIndividual['race'];
}
}
value = this.getFormValue('agetype');
newIndividual.ageType = value !== 'none' ? value : '';
value = this.getFormValueNumber('agevalue');
if (value) {
newIndividual.ageValue = value;
} else {
if (newIndividual && newIndividual.ageValue) {
delete newIndividual['ageValue'];
}
}
value = this.getFormValue('ageunit');
newIndividual.ageUnit = value !== 'none' ? value : '';
// Field only available on GDMs with Semidominant MOI (and individual is not a family-based proband)
if (semiDom && !(currIndividual && currIndividual.proband && family)) {
value = this.getFormValue('probandIs');
newIndividual.probandIs = value !== 'none' ? value : '';
}
// Fill in the individual fields from the Additional panel
value = this.getFormValue('additionalinfoindividual');
if (value) { newIndividual.additionalInformation = value; }
if (individualArticles) {
newIndividual.otherPMIDs = individualArticles['@graph'].map(function(article) { return article['@id']; });
}
if (individualVariants) {
newIndividual.variants = individualVariants;
}
if (individualScores) {
newIndividual.scores = individualScores;
}
// Set the proband boolean
value = this.getFormValue('proband');
if (value && value !== 'none') { newIndividual.proband = value === "Yes"; }
/*************************************************/
/* Individual variant form fields. */
/* Only applicable when individual is associated */
/* with a family and 1 or more variants */
/*************************************************/
if (individualVariants) {
value = this.state.recessiveZygosity;
if (value && value !== 'none') {
newIndividual.recessiveZygosity = value;
} else {
if (newIndividual && newIndividual.recessiveZygosity) {
delete newIndividual['recessiveZygosity'];
}
}
value = this.getFormValue('individualBothVariantsInTrans');
if (value && value !== 'none') {
newIndividual.bothVariantsInTrans = value;
} else {
if (newIndividual && newIndividual.bothVariantsInTrans) {
delete newIndividual['bothVariantsInTrans'];
}
}
value = this.getFormValue('individualDeNovo');
if (value && value !== 'none') {
newIndividual.denovo = value;
} else {
if (newIndividual && newIndividual.denovo) {
delete newIndividual['denovo'];
}
}
value = this.getFormValue('individualMaternityPaternityConfirmed');
if (value && value !== 'none') {
newIndividual.maternityPaternityConfirmed = value;
} else {
if (newIndividual && newIndividual.maternityPaternityConfirmed) {
delete newIndividual['maternityPaternityConfirmed'];
}
}
}
// 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 (!newIndividual.affiliation) {
newIndividual.affiliation = this.props.affiliation.affiliation_id;
}
}
return newIndividual;
},
// Update the ClinVar Variant ID fields upon interaction with the Add Resource modal
updateVariantId: function(data, fieldNum) {
var newVariantInfo = _.clone(this.state.variantInfo);
let variantCount = this.state.variantCount;
if (data) {
// 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,
'associatedPathogenicities': data.associatedPathogenicities && data.associatedPathogenicities.length ? data.associatedPathogenicities : []
};
variantCount += 1; // We have one more variant to show
} else {
// Reset the form and display values
this.refs['variantUuid' + fieldNum].setValue('');
delete newVariantInfo[fieldNum];
variantCount -= 1; // we have one less variant to show
}
// Set state
this.setState({variantInfo: newVariantInfo, variantCount: variantCount});
this.clrFormErrors('zygosityHemizygous');
this.clrFormErrors('zygosityHomozygous');
},
// Determine whether a Family is associated with a Group
// or
// whether an individual is associated with a Family or a Group
getAssociation: function(item) {
var associatedGroups, associatedFamilies;
if (this.state.group) {
associatedGroups = [this.state.group];
} else if (this.state.family && this.state.family.associatedGroups && this.state.family.associatedGroups.length) {
associatedGroups = this.state.family.associatedGroups;
}
if (this.state.family) {
associatedFamilies = [this.state.family];
} else if (this.state.individual && this.state.individual.associatedFamilies && this.state.individual.associatedFamilies.length) {
associatedFamilies = this.state.individual.associatedFamilies;
}
switch(item) {
case 'individual':
return this.state.individual;
case 'family':
return this.state.family;
case 'associatedFamilies':
return associatedFamilies;
case 'associatedGroups':
return associatedGroups;
default:
break;
}
},
// After the Family Curation page component mounts, grab the GDM, group, family, and annotation UUIDs (as many as given)
// from the query string and retrieve the corresponding objects 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() {
// Get the 'evidence', 'gdm', and 'group' UUIDs from the query string and save them locally.
this.loadData();
},
updateHpo: function(hpoWithTerms) {
if (hpoWithTerms) {
this.setState({ hpoWithTerms });
}
},
updateElimHpo: function(hpoElimWithTerms) {
if (hpoElimWithTerms) {
this.setState({ hpoElimWithTerms });
}
},
/**
* Update the 'diseaseObj' state used to save data upon form submission
*/
updateDiseaseObj(diseaseObj) {
this.setState({diseaseObj: diseaseObj}, () => {
this.clrFormErrors('diseaseError');
});
},
/**
* Clear error msg on missing disease
*/
clearErrorInParent() {
this.setState({diseaseError: null});
},
render: function() {
var gdm = this.state.gdm;
var individual = this.state.individual;
var annotation = this.state.annotation;
var pmid = (annotation && annotation.article && annotation.article.pmid) ? annotation.article.pmid : null;
var method = (individual && individual.method && Object.keys(individual.method).length) ? individual.method : {};
var submitErrClass = 'submit-err pull-right' + (this.anyFormErrors() ? '' : ' hidden');
var probandLabel = (individual && individual.proband ? <i className="icon icon-proband"></i> : null);
var variantTitle = (individual && individual.proband) ? <h4>Individual<i className="icon icon-proband-white"></i> – Variant(s) segregating with Proband</h4> : <h4>Individual — Associated Variant(s)</h4>;
var session = (this.props.session && Object.keys(this.props.session).length) ? this.props.session : null;
// Get a list of associated groups if editing an individual, or the group in the query string if there was one, or null.
var groups = (individual && individual.associatedGroups) ? individual.associatedGroups :
(this.state.group ? [this.state.group] : null);
// Get a list of associated families if editing an individual, or the family in the query string if there was one, or null.
var families = (individual && individual.associatedFamilies) ? individual.associatedFamilies :
(this.state.family ? [this.state.family] : null);
// Figure out the family and group page titles
var familyTitles = [];
var groupTitles = [];
if (individual) {
// Editing an individual. get associated family titles, and associated group titles
groupTitles = groups.map(function(group) { return {'label': group.label, '@id': group['@id']}; });
familyTitles = families.map(function(family) {
// If this family has associated groups, add their titles to groupTitles.
if (family.associatedGroups && family.associatedGroups.length) {
groupTitles = groupTitles.concat(family.associatedGroups.map(function(group) { return {'label': group.label, '@id': group['@id']}; }));
}
return {'label': family.label, '@id': family['@id']};
});
} else {
// Curating an individual.
if (families) {
// Given a family in the query string. Get title from first (only) family.
familyTitles[0] = {'label': families[0].label, '@id': families[0]['@id']};
// If the given family has associated groups, add those to group titles
if (families[0].associatedGroups && families[0].associatedGroups.length) {
groupTitles = families[0].associatedGroups.map(function(group) {
return {'label': group.label, '@id': group['@id']};
});
}
} else if (groups) {
// Given a group in the query string. Get title from first (only) group.
groupTitles[0] = {'label': groups[0].label, '@id': groups[0]['@id']};
}
}
// Retrieve methods data of "parent" evidence (assuming only one "parent", either a family or a group)
var parentEvidenceMethod;
var parentEvidenceName = '';
if (families && families.length) {
parentEvidenceMethod = (families[0].method && Object.keys(families[0].method).length) ? families[0].method : null;
parentEvidenceName = 'Family';
} else if (groups && groups.length) {
parentEvidenceMethod = (groups[0].method && Object.keys(groups[0].method).length) ? groups[0].method : null;
parentEvidenceName = 'Group';
}
// Get the query strings. Have to do this now so we know whether to render the form or not. The form
// uses React controlled inputs, so we can only render them the first time if we already have the
// family object read in.
this.queryValues.gdmUuid = queryKeyValue('gdm', this.props.href);
this.queryValues.familyUuid = queryKeyValue('family', this.props.href);
this.queryValues.groupUuid = queryKeyValue('group', this.props.href);
this.queryValues.individualUuid = queryKeyValue('individual', this.props.href);
this.queryValues.annotationUuid = queryKeyValue('evidence', 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.individualUuid || this.queryValues.editShortcut) ?
'/curation-central/?gdm=' + gdm.uuid + (pmid ? '&pmid=' + pmid : '')
: '/individual-submit/?gdm=' + gdm.uuid + (individual ? '&individual=' + individual.uuid : '') + (annotation ? '&evidence=' + annotation.uuid : '');
}
// Find any pre-existing scores associated with the evidence
let evidenceScores = individual && individual.scores ? individual.scores : [];
let variantInfo = this.state.variantInfo;
return (
<div>
{(!this.queryValues.individualUuid || individual) ?
<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={annotation.article} displayJournal pmidLinkout />
</div>
: null}
<div className="viewer-titles">
<h1>{individual ? 'Edit' : 'Curate'} Individual Information</h1>
<h2>
{gdm ? <a href={'/curation-central/?gdm=' + gdm.uuid + (pmid ? '&pmid=' + pmid : '')}><i className="icon icon-briefcase"></i></a> : null}
{groupTitles.length ?
<span> // Group {groupTitles.map(function(group, i) { return <span key={group['@id']}>{i > 0 ? ', ' : ''}<a href={group['@id']}>{group.label}</a></span>; })}</span>
: null}
{familyTitles.length ?
<span> // Family {familyTitles.map(function(family, i) { return <span key={family['@id']}>{i > 0 ? ', ' : ''}<a href={family['@id']}>{family.label}</a></span>; })}</span>
: null}
<span> // {this.state.individualName ? <span>Individual {this.state.individualName}{probandLabel}</span> : <span className="no-entry">No entry</span>}</span>
</h2>
</div>
<div className="row group-curation-content">
<div className="col-sm-12">
<Form submitHandler={this.submitForm} formClassName="form-horizontal form-std">
<Panel>
{IndividualName.call(this)}
</Panel>
<PanelGroup accordion>
<Panel title={LabelPanelTitle(individual, 'Disease & Phenotype(s)')} open>
{IndividualCommonDiseases.call(this)}
</Panel>
</PanelGroup>
<PanelGroup accordion>
<Panel title={LabelPanelTitle(individual, 'Demographics')} open>
{IndividualDemographics.call(this)}
</Panel>
</PanelGroup>
<PanelGroup accordion>
<Panel title={LabelPanelTitle(individual, 'Methods')} open>
{methods.render.call(this, method, 'individual', '', parentEvidenceMethod, parentEvidenceName)}
</Panel>
</PanelGroup>
<PanelGroup accordion>
<Panel title={variantTitle} open>
{IndividualVariantInfo.call(this)}
</Panel>
</PanelGroup>
<PanelGroup accordion>
<Panel title={LabelPanelTitle(individual, 'Additional Information')} open>
{IndividualAdditional.call(this)}
</Panel>
</PanelGroup>
{(this.state.family && this.state.proband_selected) || (!this.state.family && this.state.proband_selected) ?
<div>
<PanelGroup accordion>
<Panel title={LabelPanelTitle(individual, 'Score Proband')} panelClassName="proband-evidence-score" open>
<ScoreIndividual evidence={individual} modeInheritance={gdm.modeInheritance} evidenceType="Individual"
variantInfo={variantInfo} session={session} handleUserScoreObj={this.handleUserScoreObj}
scoreError={this.state.scoreError} scoreErrorMsg={this.state.scoreErrorMsg} affiliation={this.props.affiliation}
gdm={gdm} pmid={pmid ? pmid : null} />
</Panel>
</PanelGroup>
</div>
: null}
<div className="curation-submit clearfix">
<Input type="submit" inputClassName="btn-primary pull-right btn-inline-spacer" id="submit" title="Save" submitBusy={this.state.submitBusy} />
{gdm ? <a href={cancelUrl} className="btn btn-default btn-inline-spacer pull-right">Cancel</a> : null}
{individual ?
<DeleteButton gdm={gdm} parent={families.length > 0 ? families[0] : (groups.length > 0 ? groups[0] : annotation)} item={individual} pmid={pmid} />
: null}
<div className={submitErrClass}>Please fix errors on the form and resubmit.</div>
</div>
</Form>
</div>
</div>
</div>
</div>
: null}
</div>
);
}
});
curator_page.register(IndividualCuration, 'curator_page', 'individual-curation');
/**
* HTML labels for inputs follow.
* @param {object} individual - Individual's data object
* @param {string} labelText - Value of label
*/
const LabelPanelTitle = (individual, labelText) => {
return (
<h4>Individual<span>{individual && individual.proband ? <i className="icon icon-proband-white"></i> : null}</span> — {labelText}</h4>
);
};
/**
* Individual Name group curation panel.
* Call with .call(this) to run in the same context as the calling component.
* @param {string} displayNote
*/
function IndividualName(displayNote) {
let individual = this.state.individual;
let family = this.state.family;
let familyProbandExists = false;
let probandLabel = (individual && individual.proband ? <i className="icon icon-proband"></i> : null);
if (individual && individual.proband) familyProbandExists = individual.proband;
if (family && family.individualIncluded && family.individualIncluded.length && family.individualIncluded.length > 0) {
for (var i = 0; i < family.individualIncluded.length; i++) {
if (family.individualIncluded[i].proband === true) familyProbandExists = true;
}
}
return (
<div className="row">
{family && !familyProbandExists ?
<div className="col-sm-7 col-sm-offset-5">
<p className="alert alert-warning">
This page is only for adding non-probands to the Family. To create a proband for this Family, please edit its Family page: <a href={"/family-curation/?editsc&gdm=" + this.queryValues.gdmUuid + "&evidence=" + this.queryValues.annotationUuid + "&family=" + family.uuid}>Edit {family.label}</a>
</p>
</div>
: null}
{!this.getAssociation('individual') && !this.getAssociation('associatedFamilies') && !this.getAssociation('associatedGroups') ?
<div className="col-sm-7 col-sm-offset-5"><p className="alert alert-warning">If this Individual is part of a Family or a Group, please curate that Group or Family first and then add the Individual as a member.</p></div>
: null}
<Input type="text" ref="individualname" label={<span>{probandLabel}Individual Label:</span>} handleChange={this.handleChange}
value={individual && individual.label ? individual.label : ''}
error={this.getFormError('individualname')} clearError={this.clrFormErrors.bind(null, 'individualname')} maxLength="60"
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" required />
<p className="col-sm-7 col-sm-offset-5 input-note-below">Note: Do not enter real names in this field. {curator.renderLabelNote('Individual')}</p>
{displayNote ?
<p className="col-sm-7 col-sm-offset-5">Note: If there is more than one individual with IDENTICAL information, you can indicate this at the bottom of this form.</p>
: null}
{!family ?
<div>
<Input type="select" ref="proband" label="Is this Individual a proband:" value={individual && individual.proband ? "Yes" : (individual ? "No" : "none")}
error={this.getFormError('proband')} clearError={this.clrFormErrors.bind(null, 'proband')} handleChange={this.handleChange}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" required>
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</Input>
<p className="col-sm-7 col-sm-offset-5 input-note-below">
Note: Probands are indicated by the following icon: <i className="icon icon-proband"></i>
</p>
</div>
: null}
</div>
);
}
/**
* If the individual is being edited (we know this because there was an individual
* UUID in the query string), then don’t present the ability to specify multiple individuals.
*/
function IndividualCount() {
let individual = this.state.individual;
return (
<div>
<p className="col-sm-7 col-sm-offset-5">
If more than one individual has exactly the same information entered above and is associated with the same variants, you can specify how many extra copies of this
individual to make with this drop-down menu to indicate how many <em>extra</em> copies of this individual to make when you submit this form, and specify the names
of each extra individual below that.
</p>
<Input type="select" ref="extraindividualcount" label="Number of extra identical Individuals to make:" defaultValue="0" handleChange={this.extraIndividualCountChanged}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
{_.range(11).map(function(count) { return <option key={count}>{count}</option>; })}
</Input>
{_.range(this.state.extraIndividualCount).map(i => {
return (
<Input key={i} type="text" ref={'extraindividualname' + i} label={'Individual Label ' + (i + 2)}
error={this.getFormError('extraindividualname' + i)} clearError={this.clrFormErrors.bind(null, 'extraindividualname' + i)}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" required />
);
})}
</div>
);
}
/**
* Diseases individual curation panel.
* Call with .call(this) to run in the same context as the calling component.
*/
function IndividualCommonDiseases() {
let individual = this.state.individual;
let family = this.state.family;
let group = this.state.group;
let associatedGroups, associatedFamilies;
let probandLabel = (individual && individual.proband ? <i className="icon icon-proband"></i> : null);
// If we're editing an individual, make editable values of the complex properties
const hpoIdVal = individual && individual.hpoIdInDiagnosis ? individual.hpoIdInDiagnosis : [];
const notHpoIdVal = individual && individual.hpoIdInElimination ? individual.hpoIdInElimination : [];
const hpoWithTerms = this.state.hpoWithTerms ? this.state.hpoWithTerms : [];
const hpoElimWithTerms = this.state.hpoElimWithTerms ? this.state.hpoElimWithTerms : [];
const addHpoTermButton = hpoWithTerms.length ? <span>HPO Terms <i className="icon icon-pencil"></i></span> : <span>HPO Terms <i className="icon icon-plus-circle"></i></span>;
const addElimTermButton = hpoElimWithTerms.length ? <span>HPO Terms <i className="icon icon-pencil"></i></span> : <span>HPO Terms <i className="icon icon-plus-circle"></i></span>;
// Make a list of diseases from the group, either from the given group,
// or the individual if we're editing one that has associated groups.
if (group) {
// We have a group, so get the disease array from it.
associatedGroups = [group];
} else if (individual && individual.associatedGroups && individual.associatedGroups.length) {
// We have an individual with associated groups. Combine the diseases from all groups.
associatedGroups = individual.associatedGroups;
}
// Make a list of diseases from the family, either from the given family,
// or the individual if we're editing one that has associated families.
if (family) {
// We have a group, so get the disease array from it.
associatedFamilies = [family];
} else if (individual && individual.associatedFamilies && individual.associatedFamilies.length) {
// We have an individual with associated groups. Combine the diseases from all groups.
associatedFamilies = individual.associatedFamilies;
}
return (
<div className="row">
{associatedGroups && associatedGroups[0].commonDiagnosis && associatedGroups[0].commonDiagnosis.length ? curator.renderDiseaseList(associatedGroups, 'Group') : null}
{associatedFamilies && associatedFamilies[0].commonDiagnosis && associatedFamilies[0].commonDiagnosis.length > 0 ? curator.renderDiseaseList(associatedFamilies, 'Family') : null}
<IndividualDisease group={associatedGroups && associatedGroups[0] ? associatedGroups[0] : null}
family={associatedFamilies && associatedFamilies[0] ? associatedFamilies[0] : null}
individual={individual} gdm={this.state.gdm} session={this.props.session}
updateDiseaseObj={this.updateDiseaseObj} clearErrorInParent={this.clearErrorInParent}
diseaseObj={this.state.diseaseObj} error={this.state.diseaseError}
probandLabel={probandLabel} required={this.state.proband_selected} />
{associatedGroups && ((associatedGroups[0].hpoIdInDiagnosis && associatedGroups[0].hpoIdInDiagnosis.length) || associatedGroups[0].termsInDiagnosis) ?
curator.renderPhenotype(associatedGroups, 'Individual', 'hpo', 'Group')
:
(associatedFamilies && ((associatedFamilies[0].hpoIdInDiagnosis && associatedFamilies[0].hpoIdInDiagnosis.length) || associatedFamilies[0].termsInDiagnosis) ?
curator.renderPhenotype(associatedFamilies, 'Individual', 'hpo', 'Family') : curator.renderPhenotype(null, 'Individual', 'hpo')
)
}
<div className="col-sm-5 control-label">
<span>
<label>Phenotype(s) in Common </label>
<span className="normal">(<a href={external_url_map['HPOBrowser']} target="_blank" title="Open HPO Browser in a new tab">HPO</a> ID(s))</span>:
</span>
</div>
<div className="form-group hpo-term-container">
{hpoWithTerms.length ?
<ul>
{hpoWithTerms.map((term, i) => {
return (
<li key={i}>{term}</li>
);
})}
</ul>
: null}
<HpoTermModal addHpoTermButton={addHpoTermButton} passHpoToParent={this.updateHpo} savedHpo={hpoIdVal} inElim={false} />
</div>
{associatedGroups && ((associatedGroups[0].hpoIdInDiagnosis && associatedGroups[0].hpoIdInDiagnosis.length) || associatedGroups[0].termsInDiagnosis) ?
curator.renderPhenotype(associatedGroups, 'Individual', 'ft', 'Group')
:
(associatedFamilies && ((associatedFamilies[0].hpoIdInDiagnosis && associatedFamilies[0].hpoIdInDiagnosis.length) || associatedFamilies[0].termsInDiagnosis) ?
curator.renderPhenotype(associatedFamilies, 'Individual', 'ft', 'Family') : curator.renderPhenotype(null, 'Individual', 'ft')
)
}
<Input type="textarea" ref="phenoterms" label={LabelPhenoTerms()} rows="2"
value={individual && individual.termsInDiagnosis ? individual.termsInDiagnosis : ''}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" />
{associatedGroups && ((associatedGroups[0].hpoIdInDiagnosis && associatedGroups[0].hpoIdInDiagnosis.length) || associatedGroups[0].termsInDiagnosis) ?
<Input type="button" ref="phenotypecopygroup" wrapperClassName="col-sm-7 col-sm-offset-5 orphanet-copy" inputClassName="btn-copy btn-last btn-sm" title="Copy Phenotype from Associated Group"
clickHandler={this.handleClick.bind(this, associatedGroups[0], 'phenotype')} />
: null}
{associatedFamilies && ((associatedFamilies[0].hpoIdInDiagnosis && associatedFamilies[0].hpoIdInDiagnosis.length) || associatedFamilies[0].termsInDiagnosis) ?
<Input type="button" ref="phenotypecopygroup" wrapperClassName="col-sm-7 col-sm-offset-5 orphanet-copy" inputClassName="btn-copy btn-last btn-sm" title="Copy Phenotype from Associated Family"
clickHandler={this.handleClick.bind(this, associatedFamilies[0], 'phenotype')} />
: null}
<p className="col-sm-7 col-sm-offset-5">Enter <em>phenotypes that are NOT present in Individual</em> if they are specifically noted in the paper.</p>
{associatedGroups && ((associatedGroups[0].hpoIdInElimination && associatedGroups[0].hpoIdInElimination.length) || associatedGroups[0].termsInElimination) ?
curator.renderPhenotype(associatedGroups, 'Individual', 'nothpo', 'Group')
:
(associatedFamilies && ((associatedFamilies[0].hpoIdInElimination && associatedFamilies[0].hpoIdInElimination.length) || associatedFamilies[0].termsInElimination) ?
curator.renderPhenotype(associatedFamilies, 'Individual', 'nothpo', 'Family') : null
)
}
<div className="col-sm-5 control-label">
<span>
<label className="emphasis">NOT Phenotype(s) </label>
<span className="normal">(<a href={external_url_map['HPOBrowser']} target="_blank" title="Open HPO Browser in a new tab">HPO</a> ID(s))</span>:
</span>
</div>
<div className="form-group hpo-term-container">
{hpoElimWithTerms.length ?
<ul>
{hpoElimWithTerms.map((term, i) => {
return (
<li key={i}>{term}</li>
);
})}
</ul>
: null}
<HpoTermModal addHpoTermButton={addElimTermButton} passElimHpoToParent={this.updateElimHpo} savedElimHpo={notHpoIdVal} inElim={true} />
</div>
{associatedGroups && ((associatedGroups[0].hpoIdInElimination && associatedGroups[0].hpoIdInElimination.length) || associatedGroups[0].termsInElimination) ?
curator.renderPhenotype(associatedGroups, 'Individual', 'notft', 'Group')
:
(associatedFamilies && ((associatedFamilies[0].hpoIdInElimination && associatedFamilies[0].hpoIdInElimination.length) || associatedFamilies[0].termsInElimination) ?
curator.renderPhenotype(associatedFamilies, 'Individual', 'notft', 'Family') : null
)
}
<Input type="textarea" ref="notphenoterms" label={LabelPhenoTerms('not')} rows="2"
value={individual && individual.termsInElimination ? individual.termsInElimination : ''}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" />
{associatedGroups && ((associatedGroups[0].hpoIdInElimination && associatedGroups[0].hpoIdInElimination.length) || associatedGroups[0].termsInElimination) ?
<Input type="button" ref="notphenotypecopygroup" wrapperClassName="col-sm-7 col-sm-offset-5 orphanet-copy" inputClassName="btn-copy btn-last btn-sm" title="Copy NOT Phenotype from Associated Group"
clickHandler={this.handleClick.bind(this, associatedGroups[0], 'notphenotype')} />
: null}
{associatedFamilies && ((associatedFamilies[0].hpoIdInElimination && associatedFamilies[0].hpoIdInElimination.length) || associatedFamilies[0].termsInElimination) ?
<Input type="button" ref="notphenotypecopygroup" wrapperClassName="col-sm-7 col-sm-offset-5 orphanet-copy" inputClassName="btn-copy btn-last btn-sm" title="Copy NOT Phenotype from Associated Family"
clickHandler={this.handleClick.bind(this, associatedFamilies[0], 'notphenotype')} />
: null}
</div>
);
}
/**
* HTML labels for inputs follow.
* @param {string} bool - Value of 'not'
*/
const LabelPhenoTerms = bool => {
return (
<span>
{bool && bool === 'not' ? <span className="emphasis">NOT </span> : ''}
Phenotype(s) (<span className="normal">free text</span>):
</span>
);
};
/**
* Demographics individual curation panel.
* Call with .call(this) to run in the same context as the calling component.
*/
function IndividualDemographics() {
let individual = this.state.individual;
let associatedParentObj;
let associatedParentName = '';
let hasParentDemographics = false;
// Retrieve associated "parent" as an array (check for family first, then group)
if (this.state.family) {
associatedParentObj = [this.state.family];
associatedParentName = 'Family';
} else if (individual && individual.associatedFamilies && individual.associatedFamilies.length) {
associatedParentObj = individual.associatedFamilies;
associatedParentName = 'Family';
} else if (this.state.group) {
associatedParentObj = [this.state.group];
associatedParentName = 'Group';
} else if (individual && individual.associatedGroups && individual.associatedGroups.length) {
associatedParentObj = individual.associatedGroups;
associatedParentName = 'Group';
}
// Check if associated "parent" has any demographics data
if (associatedParentObj && (associatedParentObj[0].countryOfOrigin || associatedParentObj[0].ethnicity || associatedParentObj[0].race)) {
hasParentDemographics = true;
}
return (
<div className="row">
<Input type="select" ref="sex" label="Sex:" defaultValue="none"
value={individual && individual.sex ? individual.sex : 'none'}
error={this.getFormError('sex')} clearError={this.clrFormErrors.bind(null, 'sex')}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" required>
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Unknown">Unknown</option>
<option value="Intersex">Intersex</option>
<option value="MTF/Transwoman/Transgender Female">MTF/Transwoman/Transgender Female</option>
<option value="FTM/Transman/Transgender Male">FTM/Transman/Transgender Male</option>
<option value="Ambiguous">Ambiguous</option>
<option value="Other">Other</option>
</Input>
<div className="col-sm-7 col-sm-offset-5 sex-field-note">
<div className="alert alert-info">Select "Unknown" for "Sex" if information not provided in publication.</div>
</div>
{hasParentDemographics ?
<Input type="button" ref="copyparentdemographics" wrapperClassName="col-sm-7 col-sm-offset-5 demographics-copy"
inputClassName="btn-copy btn-sm" title={'Copy Demographics from Associated ' + associatedParentName}
clickHandler={this.handleClick.bind(this, associatedParentObj[0], 'demographics')} />
: null}
{hasParentDemographics ? curator.renderParentEvidence('Country of Origin Associated with ' + associatedParentName + ':', associatedParentObj[0].countryOfOrigin) : null}
<Input type="select" ref="country" label="Country of Origin:" defaultValue="none"
value={individual && individual.countryOfOrigin ? individual.countryOfOrigin : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
{country_codes.map(function(country_code) {
return <option key={country_code.code} value={country_code.name}>{country_code.name}</option>;
})}
</Input>
{hasParentDemographics ? curator.renderParentEvidence('Ethnicity Associated with ' + associatedParentName + ':', associatedParentObj[0].ethnicity) : null}
<Input type="select" ref="ethnicity" label="Ethnicity:" defaultValue="none"
value={individual && individual.ethnicity ? individual.ethnicity : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Hispanic or Latino">Hispanic or Latino</option>
<option value="Not Hispanic or Latino">Not Hispanic or Latino</option>
<option value="Unknown">Unknown</option>
</Input>
{hasParentDemographics ? curator.renderParentEvidence('Race Associated with ' + associatedParentName + ':', associatedParentObj[0].race) : null}
<Input type="select" ref="race" label="Race:" defaultValue="none"
value={individual && individual.race ? individual.race : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="American Indian or Alaska Native">American Indian or Alaska Native</option>
<option value="Asian">Asian</option>
<option value="Black">Black</option>
<option value="Native Hawaiian or Other Pacific Islander">Native Hawaiian or Other Pacific Islander</option>
<option value="White">White</option>
<option value="Mixed">Mixed</option>
<option value="Unknown">Unknown</option>
</Input>
<h4 className="col-sm-7 col-sm-offset-5">Age</h4>
<div className="demographics-age-range">
<Input type="select" ref="agetype" label="Type:" defaultValue="none"
value={individual && individual.ageType ? individual.ageType : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Onset">Onset</option>
<option value="Report">Report</option>
<option value="Diagnosis">Diagnosis</option>
<option value="Death">Death</option>
</Input>
<Input type="number" inputClassName="integer-only" ref="agevalue" label="Value:" maxVal={150}
value={individual && individual.ageValue ? individual.ageValue : ''}
error={this.getFormError('agevalue')} clearError={this.clrFormErrors.bind(null, 'agevalue')}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" />
<Input type="select" ref="ageunit" label="Unit:" defaultValue="none"
value={individual && individual.ageUnit ? individual.ageUnit : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Days">Days</option>
<option value="Weeks">Weeks</option>
<option value="Months">Months</option>
<option value="Years">Years</option>
</Input>
</div>
</div>
);
}
/**
* Only called if we have an associated family
*/
function IndividualVariantInfo() {
let individual = this.state.individual;
let family = this.state.family;
let gdm = this.state.gdm;
let annotation = this.state.annotation;
let variants = individual && individual.variants;
let gdmUuid = gdm && gdm.uuid ? gdm.uuid : null;
let pmidUuid = annotation && annotation.article.pmid ? annotation.article.pmid : null;
let userUuid = gdm && gdm.submitted_by.uuid ? gdm.submitted_by.uuid : null;
const semiDom = gdm && gdm.modeInheritance ? gdm.modeInheritance.indexOf('Semidominant') > -1 : false;
const maxVariants = semiDom ? 3 : MAX_VARIANTS;
return (
<div className="row form-row-helper">
{individual && individual.proband && family ?
<div>
<p>Variant(s) for a proband associated with a Family can only be edited through the Family page: <a href={"/family-curation/?editsc&gdm=" + gdm.uuid + "&evidence=" + annotation.uuid + "&family=" + family.uuid}>Edit {family.label}</a></p>
{individual.probandIs ? <p><strong>Proband is: </strong>{individual.probandIs}</p> : null}
{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>
<dt>ClinVar Variation ID</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>
</div>
: null}
{variant.carId ?
<div>
<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>
</div>
: null}
{renderVariantLabelAndTitle(variant)}
{variant.uuid ?
<div>
<dt className="no-label"></dt>
<dd>
<a href={'/variant-central/?variant=' + variant.uuid} target="_blank">View variant evidence in Variant Curation Interface</a>
</dd>
</div>
: null}
{variant.otherDescription && variant.otherDescription.length ?
<div>
<dt>Other description</dt>
<dd>{variant.otherDescription}</dd>
</div>
: null}
{individual.recessiveZygosity && i === 0 ?
<div>
<dt>If Recessive, select variant zygosity</dt>
<dd>{individual.recessiveZygosity}</dd>
</div>
: null }
</dl>
</div>
);
})}
{variants && variants.length ?
<div className="variant-panel">
<Input type="select" ref="individualBothVariantsInTrans" label={<span>If there are 2 variants described, are they both located in <i>trans</i> with respect to one another?</span>}
defaultValue="none" value={individual && individual.bothVariantsInTrans ? individual.bothVariantsInTrans : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="Not Specified">Not Specified</option>
</Input>
<Input type="select" ref="individualDeNovo" label={<span>If the individual has one variant, is it <i>de novo</i><br/>OR<br/>If the individual has 2 variants, is at least one <i>de novo</i>?</span>}
defaultValue="none" value={individual && individual.denovo ? individual.denovo : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</Input>
<Input type="select" ref="individualMaternityPaternityConfirmed" label={<span>If the answer to the above <i>de novo</i> question is yes, is the variant maternity and paternity confirmed?</span>}
defaultValue="none" value={individual && individual.maternityPaternityConfirmed ? individual.maternityPaternityConfirmed : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</Input>
</div>
: null}
</div>
:
<div>
{ semiDom ?
<Input type="select" label="The proband is:" ref="probandIs" handleChange={this.handleChange}
defaultValue="none" value={individual && individual.probandIs ? individual.probandIs : 'none'}
error={this.getFormError('probandIs')} clearError={this.clrFormErrors.bind(null, 'probandIs')}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" required={this.state.proband_selected}>
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Monoallelic heterozygous">Monoallelic heterozygous (e.g. autosomal)</option>
<option value="Hemizygous">Hemizygous (e.g. X-linked)</option>
<option value="Biallelic homozygous">Biallelic homozygous (e.g. the same variant is present on both alleles, autosomal or X-linked)</option>
<option value="Biallelic compound heterozygous">Biallelic compound heterozygous (e.g. two different variants are present on the alleles, autosomal or X-linked)</option>
</Input>
:
<div>
<Input type="checkbox" ref="zygosityHomozygous" label={<span>Check here if homozygous:<br /><i className="non-bold-font">(Note: if homozygous, enter only 1 variant below)</i></span>}
error={this.getFormError('zygosityHomozygous')} clearError={this.clrFormErrors.bind(null, 'zygosityHomozygous')}
handleChange={this.handleChange} defaultChecked="false" checked={this.state.recessiveZygosity == 'Homozygous'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
</Input>
<Input type="checkbox" ref="zygosityHemizygous" label="Check here if hemizygous:"
error={this.getFormError('zygosityHemizygous')} clearError={this.clrFormErrors.bind(null, 'zygosityHemizygous')}
handleChange={this.handleChange} defaultChecked="false" checked={this.state.recessiveZygosity == 'Hemizygous'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
</Input>
</div>}
{_.range(maxVariants).map(i => {
var variant;
if (variants && variants.length) {
variant = variants[i];
}
return (
<div key={i} className="variant-panel">
{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 /></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 className="row variant-curation">
<span className="col-sm-5 control-label"><label></label></span>
<span className="col-sm-7 text-no-input">
<a href={'/variant-central/?variant=' + this.state.variantInfo[i].uuid} target="_blank">View variant evidence in Variant Curation Interface</a>
</span>
</div>
</div>
: null}
<Input type="text" ref={'variantUuid' + i} value={variant && variant.uuid ? variant.uuid : ''}
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:</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.biallelicHetOrHom || (Object.keys(this.state.variantInfo).length > 0 && this.state.proband_selected) ?
<div className="variant-panel">
<Input type="select" ref="individualBothVariantsInTrans" label={<span>If there are 2 variants described, are they both located in <i>trans</i> with respect to one another?</span>}
defaultValue="none" value={individual && individual.bothVariantsInTrans ? individual.bothVariantsInTrans : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="Not Specified">Not Specified</option>
</Input>
<Input type="select" ref="individualDeNovo" label={<span>If the individual has one variant, is it <i>de novo</i><br/>OR<br/>If the individual has 2 variants, is at least one <i>de novo</i>?</span>}
defaultValue="none" value={individual && individual.denovo ? individual.denovo : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</Input>
<Input type="select" ref="individualMaternityPaternityConfirmed" label={<span>If the answer to the above <i>de novo</i> question is yes, is the variant maternity and paternity confirmed?</span>}
defaultValue="none" value={individual && individual.maternityPaternityConfirmed ? individual.maternityPaternityConfirmed : 'none'}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</Input>
</div>
: null}
</div>
}
</div>
);
}
const LabelClinVarVariant = () => {
return <span><strong><a href={external_url_map['ClinVar']} target="_blank" title="ClinVar home page at NCBI in a new tab">ClinVar</a> Variation ID:</strong></span>;
};
const LabelCARVariant = () => {
return <span><strong><a href={external_url_map['CAR']} target="_blank" title="ClinGen Allele Registry in a new tab">ClinGen Allele Registry</a> ID:</strong></span>;
};
const LabelOtherVariant = () => {
return <span>Other description when a ClinVar VariationID does not exist <span className="normal">(important: use CA ID registered with <a href={external_url_map['CAR']} target="_blank">ClinGen Allele Registry</a> whenever possible)</span>:</span>;
};
/**
* Additional Information family curation panel.
* Call with .call(this) to run in the same context as the calling component.
*/
function IndividualAdditional() {
var individual = this.state.individual;
var probandLabel = (individual && individual.proband ? <i className="icon icon-proband"></i> : null);
// If editing an individual, get its existing articles
let otherpmidsVal = individual && individual.otherPMIDs ? individual.otherPMIDs.map(function(article) { return article.pmid; }).join(', ') : '';
return (
<div className="row">
<Input type="textarea" ref="additionalinfoindividual" label={<span>Additional Information about Individual{probandLabel}:</span>}
rows="5" value={individual && individual.additionalInformation ? individual.additionalInformation : ''}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" />
<Input type="textarea" ref="otherpmids" label={<span>Enter PMID(s) that report evidence about this Individual{probandLabel}:</span>}
rows="5" value={otherpmidsVal} placeholder="e.g. 12089445, 21217753"
error={this.getFormError('otherpmids')} clearError={this.clrFormErrors.bind(null, 'otherpmids')}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group" />
</div>
);
}
/**
* Score Proband panel.
* Call with .call(this) to run in the same context as the calling component.
*/
function IndividualScore() {
let individual = this.state.individual;
let scores = individual && individual.scores ? individual.scores : null;
return (
<div className="row">
<Input type="select" ref="scoreStatus" label="Select Status:" defaultValue="none" value={scores && scores.length ? scores[0].scoreStatus : null}
labelClassName="col-sm-5 control-label" wrapperClassName="col-sm-7" groupClassName="form-group">
<option value="none">No Selection</option>
<option disabled="disabled"></option>
<option value="Score">Score</option>
<option value="Review">Review</option>
<option value="Contradicts">Contradicts</option>
</Input>
<div className="col-sm-7 col-sm-offset-5 score-status-note">
<div className="alert alert-warning">Note: The next release will provide a calculated score for this proband based on the information provided as well as the ability to adjust this score within the allowed range specified by the Clinical Validity Classification.</div>
</div>
</div>
);
}
const IndividualViewer = createReactClass({
// Start:: Evidence score submission hanlding for viewer
mixins: [RestMixin],
propTypes: {
context: PropTypes.object,
session: PropTypes.object,
href: PropTypes.string,
affiliation: PropTypes.object
},
getInitialState: function() {
return {
gdmUuid: queryKeyValue('gdm', this.props.href),
gdm: null,
userScoreObj: {}, // Logged-in user's score object
submitBusy: false, // True while form is submitting
scoreError: false,
scoreErrorMsg: ''
};
},
componentDidMount() {
if (this.state.gdmUuid) {
return this.getRestData('/gdm/' + this.state.gdmUuid).then(gdm => {
this.setState({gdm: gdm});
}).catch(err => {
console.log('Fetching gdm error =: %o', err);
});
}
},
// 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({scoreError: false, scoreErrorMsg: ''});
}
});
},
// 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;
},
scoreSubmit: function(e) {
let individual = this.props.context;
/*****************************************************/
/* Proband score status data object */
/*****************************************************/
let newUserScoreObj = Object.keys(this.state.userScoreObj).length ? this.state.userScoreObj : {};
/**
* 1) Make sure there is an explanation for the score selected differently from the default score
* 2) Make sure there is a selection of the 'Confirm Case Information type' if the 'Select Status'
* value equals 'Score'
*/
if (Object.keys(newUserScoreObj).length) {
if (newUserScoreObj.hasOwnProperty('score') && newUserScoreObj.score !== false && !newUserScoreObj.scoreExplanation) {
this.setState({scoreError: true, scoreErrorMsg: 'A reason is required for the changed score.'});
return false;
}
if (newUserScoreObj['scoreStatus'] === 'Score' && !newUserScoreObj['caseInfoType']) {
this.setState({scoreError: true, scoreErrorMsg: 'A case information type is required for the Score status.'});
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('/individual/' + individual.uuid, null, true).then(freshIndividual => {
// flatten both context and fresh individual
let newIndividual = curator.flatten(individual);
let freshFlatIndividual = curator.flatten(freshIndividual);
// take only the scores from the fresh individual to not overwrite changes
// in newIndividual
newIndividual.scores = freshFlatIndividual.scores ? freshFlatIndividual.scores : [];
// push new score uuid to newIndividual's scores list
newIndividual.scores.push(newScoreObjectUuid);
return this.putRestData('/individual/' + individual.uuid, newIndividual).then(updatedIndividualObj => {
this.setState({submitBusy: false});
return Promise.resolve(updatedIndividualObj['@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('/individual/' + individual.uuid, null, true).then(freshIndividual => {
// flatten both context and fresh individual
let newIndividual = curator.flatten(individual);
let freshFlatIndividual = curator.flatten(freshIndividual);
// take only the scores from the fresh individual to not overwrite changes
// in newIndividual
newIndividual.scores = freshFlatIndividual.scores ? freshFlatIndividual.scores : [];
// push new score uuid to newIndividual's scores list
if (newIndividual.scores.length) {
newIndividual.scores.forEach(score => {
if (score === modifiedScoreObjectUuid) {
let index = newIndividual.scores.indexOf(score);
newIndividual.scores.splice(index, 1);
}
});
}
return this.putRestData('/individual/' + individual.uuid, newIndividual).then(updatedIndividualObj => {
this.setState({submitBusy: false});
return Promise.resolve(updatedIndividualObj['@graph'][0]);
});
});
}).then(data => {
this.handlePageRedirect();
});
}
}
}
},
// End:: Evidence score submission hanlding for viewer
render() {
var individual = this.props.context;
var user = this.props.session && this.props.session.user_properties;
var userIndividual = user && individual && individual.submitted_by && user.uuid === individual.submitted_by.uuid ? true : false;
let affiliation = this.props.affiliation;
let affiliatedIndividual = affiliation && Object.keys(affiliation).length && individual && individual.affiliation && affiliation.affiliation_id === individual.affiliation ? true : false;
var method = individual.method;
var variants = (individual.variants && individual.variants.length) ? individual.variants : [];
var i = 0;
var groupRenders = [];
var probandLabel = (individual && individual.proband ? <i className="icon icon-proband"></i> : null);
let evidenceScores = individual && individual.scores && individual.scores.length ? individual.scores : [];
let isEvidenceScored = false;
if (evidenceScores.length) {
evidenceScores.map(scoreObj => {
if (scoreObj.scoreStatus && scoreObj.scoreStatus.match(/Score|Review|Contradicts/ig)) {
isEvidenceScored = true;
}
});
}
// Collect all families to render, as well as groups associated with these families
var familyRenders = individual.associatedFamilies.map(function(family, j) {
groupRenders = family.associatedGroups.map(function(group) {
return (
<span key={group.uuid}>
{i++ > 0 ? ', ' : ''}
<a href={group['@id']}>{group.label}</a>
</span>
);
});
return (
<span key={family.uuid}>
<span key={family.uuid}>
{j > 0 ? ', ' : ''}
<a href={family['@id']}>{family.label}</a>
</span>
</span>
);
});
// Collect all groups associated with these individuals directly
var directGroupRenders = individual.associatedGroups.map(function(group) {
return (
<span key={group.uuid}>
{i++ > 0 ? ', ' : ''}
{group.label}
</span>
);
});
groupRenders = groupRenders.concat(directGroupRenders);
var tempGdmPmid = curator.findGdmPmidFromObj(individual);
var tempGdm = tempGdmPmid[0];
var tempPmid = tempGdmPmid[1];
let associatedFamily = individual.associatedFamilies && individual.associatedFamilies.length ? individual.associatedFamilies[0] : null;
let segregation = associatedFamily && associatedFamily.segregation ? associatedFamily.segregation : null;
var probandIs = individual && individual.probandIs;
const semiDom = tempGdm && tempGdm.modeInheritance ? tempGdm.modeInheritance.indexOf('Semidominant') > -1 : false;
const biallelicHetOrHom = semiDom && (probandIs === 'Biallelic homozygous' || probandIs === 'Biallelic compound heterozygous');
return (
<div>
<ViewRecordHeader gdm={tempGdm} pmid={tempPmid} />
<div className="container">
<div className="row curation-content-viewer">
<div className="viewer-titles">
<h1>View Individual: {individual.label}{probandLabel}</h1>
<h2>
{tempGdm ? <a href={'/curation-central/?gdm=' + tempGdm.uuid + (tempGdm ? '&pmid=' + tempPmid : '')}><i className="icon icon-briefcase"></i></a> : null}
{groupRenders.length ?
<span> // Group {groupRenders}</span>
: null}
{familyRenders.length ?
<span> // Family {familyRenders}</span>
: null}
<span> // Individual {individual.label}</span>
</h2>
</div>
<Panel title={LabelPanelTitleView(individual, 'Disease & Phenotype(s)')} panelClassName="panel-data">
<dl className="dl-horizontal">
<div>
<dt>Common Diagnosis</dt>
<dd>{individual.diagnosis && individual.diagnosis.map(function(disease, i) {
return <span key={disease.diseaseId}>{i > 0 ? ', ' : ''}{disease.term} {!disease.freetext ? <a href={external_url_map['MondoSearch'] + disease.diseaseId} target="_blank">{disease.diseaseId.replace('_', ':')}</a> : null}</span>;
})}</dd>
</div>
<div>
<dt>HPO IDs</dt>
<dd>{individual.hpoIdInDiagnosis && individual.hpoIdInDiagnosis.map(function(hpo, i) {
let id = hpo.match(/\HP:\d{7}/g);
return <span key={hpo}>{i > 0 ? ', ' : ''}<a href={external_url_map['HPO'] + id} title={"HPOBrowser entry for " + hpo + " in new tab"} target="_blank">{hpo}</a></span>;
})}</dd>
</div>
<div>
<dt>Phenotype Terms</dt>
<dd>{individual.termsInDiagnosis}</dd>
</div>
<div>
<dt>NOT HPO IDs</dt>
<dd>{individual.hpoIdInElimination && individual.hpoIdInElimination.map(function(hpo, i) {
let id = hpo.match(/\HP:\d{7}/g);
return <span key={hpo}>{i > 0 ? ', ' : ''}<a href={external_url_map['HPO'] + id} title={"HPOBrowser entry for " + hpo + " in new tab"} target="_blank">{hpo}</a></span>;
})}</dd>
</div>
<div>
<dt>NOT phenotype terms</dt>
<dd>{individual.termsInElimination}</dd>
</div>
</dl>
</Panel>
<Panel title={LabelPanelTitleView(individual, 'Demographics')} panelClassName="panel-data">
<dl className="dl-horizontal">
<div>
<dt>Sex</dt>
<dd>{individual.sex}</dd>
</div>
<div>
<dt>Country of Origin</dt>
<dd>{individual.countryOfOrigin}</dd>
</div>
<div>
<dt>Ethnicity</dt>
<dd>{individual.ethnicity}</dd>
</div>
<div>
<dt>Race</dt>
<dd>{individual.race}</dd>
</div>
<div>
<dt>Age Type</dt>
<dd>{individual.ageType}</dd>
</div>
<div>
<dt>Value</dt>
<dd>{individual.ageValue}</dd>
</div>
<div>
<dt>Age Unit</dt>
<dd>{individual.ageUnit}</dd>
</div>
</dl>
</Panel>
<Panel title={LabelPanelTitleView(individual, 'Methods')} panelClassName="panel-data">
<dl className="dl-horizontal">
<div>
<dt>Previous testing</dt>
<dd>{method ? (method.previousTesting === true ? 'Yes' : (method.previousTesting === false ? 'No' : '')) : ''}</dd>
</div>
<div>
<dt>Description of previous testing</dt>
<dd>{method && method.previousTestingDescription}</dd>
</div>
<div>
<dt>Genome-wide study</dt>
<dd>{method ? (method.genomeWideStudy === true ? 'Yes' : (method.genomeWideStudy === false ? 'No' : '')) : ''}</dd>
</div>
<div>
<dt>Genotyping methods</dt>
<dd>{method && method.genotypingMethods && method.genotypingMethods.join(', ')}</dd>
</div>
{method && (method.entireGeneSequenced === true || method.entireGeneSequenced === false) ?
<div>
<dt>Entire gene sequenced</dt>
<dd>{method.entireGeneSequenced === true ? 'Yes' : 'No'}</dd>
</div>
: null}
{method && (method.copyNumberAssessed === true || method.copyNumberAssessed === false) ?
<div>
<dt>Copy number assessed</dt>
<dd>{method.copyNumberAssessed === true ? 'Yes' : 'No'}</dd>
</div>
: null}
{method && (method.specificMutationsGenotyped === true || method.specificMutationsGenotyped === false) ?
<div>
<dt>Specific mutations genotyped</dt>
<dd>{method.specificMutationsGenotyped === true ? 'Yes' : 'No'}</dd>
</div>
: null}
<div>
<dt>Description of genotyping method</dt>
<dd>{method && method.specificMutationsGenotypedMethod}</dd>
</div>
</dl>
</Panel>
<Panel title={LabelPanelTitleView(individual, '', true)} panelClassName="panel-data">
{semiDom ?
<div>
<dl className="dl-horizontal">
<dt>The proband is</dt>
<dd>{probandIs}</dd>
</dl>
</div>
:
<div>
<dl className="dl-horizontal">
<dt>Zygosity</dt>
<dd>{individual && individual.recessiveZygosity ? individual.recessiveZygosity : "None selected"}</dd>
</dl>
</div>
}
{variants.map(function(variant, i) {
return (
<div key={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>
);
})}
{(variants && variants.length && individual.proband) || biallelicHetOrHom ?
<div className="variant-view-panel family-associated">
<div>
<dl className="dl-horizontal">
<dt>If there are 2 variants described, are they both located in <i>trans</i> with respect to one another?</dt>
<dd>{individual.bothVariantsInTrans}</dd>
</dl>
</div>
<div>
<dl className="dl-horizontal">
<dt>If the individual has one variant, is it <i>de novo</i> OR If the individual has 2 variants, is at least one <i>de novo</i>?</dt>
<dd>{individual.denovo}</dd>
</dl>
</div>
<div>
<dl className="dl-horizontal">
<dt>If the answer to the above <i>de novo</i> question is yes, is the variant maternity and paternity confirmed?</dt>
<dd>{individual.maternityPaternityConfirmed}</dd>
</dl>
</div>
</div>
: null}
</Panel>
<Panel title={LabelPanelTitleView(individual, 'Additional Information')} panelClassName="panel-data">
<dl className="dl-horizontal">
<div>
<dt>Additional Information about Individual</dt>
<dd>{individual.additionalInformation}</dd>
</div>
<dt>Other PMID(s) that report evidence about this same Individual</dt>
<dd>{individual.otherPMIDs && individual.otherPMIDs.map(function(article, i) {
return <span key={article.pmid}>{i > 0 ? ', ' : ''}<a href={external_url_map['PubMed'] + article.pmid} title={"PubMed entry for PMID:" + article.pmid + " in new tab"} target="_blank">PMID:{article.pmid}</a></span>;
})}</dd>
</dl>
</Panel>
{(associatedFamily && individual.proband) || (!associatedFamily && individual.proband) ?
<div>
<Panel title={LabelPanelTitleView(individual, 'Other Curator Scores')} panelClassName="panel-data">
<ScoreViewer evidence={individual} otherScores={true} session={this.props.session} affiliation={affiliation} />
</Panel>
<Panel title={LabelPanelTitleView(individual, 'Score Proband')} panelClassName="proband-evidence-score-viewer" open>
{isEvidenceScored || (!isEvidenceScored && affiliation && affiliatedIndividual) || (!isEvidenceScored && !affiliation && userIndividual) ?
<ScoreIndividual evidence={individual} modeInheritance={tempGdm? tempGdm.modeInheritance : null} evidenceType="Individual"
session={this.props.session} handleUserScoreObj={this.handleUserScoreObj} scoreSubmit={this.scoreSubmit}
scoreError={this.state.scoreError} scoreErrorMsg={this.state.scoreErrorMsg} affiliation={affiliation}
variantInfo={variants} gdm={this.state.gdm} pmid={tempPmid ? tempPmid : null} />
: null}
{!isEvidenceScored && ((affiliation && !affiliatedIndividual) || (!affiliation && !userIndividual)) ?
<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>
: null}
</div>
</div>
</div>
);
}
});
content_views.register(IndividualViewer, 'individual');
/**
* HTML labels for inputs follow.
* @param {object} individual - Individual's data object
* @param {string} labelText - Value of label
* @param {boolean} hasVariant - Flag for associated variant
*/
const LabelPanelTitleView = (individual, labelText, hasVariant) => {
if (hasVariant) {
labelText = (individual && individual.associatedFamilies.length && individual.proband) ?
'Variant(s) segregating with Proband' :
'Associated Variant(s)';
}
return (
<h4>
<span className="panel-title-std">
Individual{<span>{individual && individual.proband ? <i className="icon icon-proband"></i> : null}</span>} — {labelText}
</span>
</h4>
);
};
/**
* Make a starter individual from the family and write it to the DB; always called from
* family curation. Pass an array of disease objects to add, as well as an array of variants.
* Returns a promise once the Individual object is written.
* @param {string} label
* @param {object} diseases
* @param {object} variants
* @param {object} zygosity
* @param {string} probandIs - Value of "The proband is" form field (expected to be null for none/"No Selection")
* @param {object} context
*/
export function makeStarterIndividual(label, diseases, variants, zygosity, probandIs, affiliation, context) {
let newIndividual = {};
newIndividual.label = label;
newIndividual.diagnosis = diseases;
newIndividual.proband = true;
if (variants) {
// It's possible to create a proband w/o variants at the moment
newIndividual.variants = variants;
}
if (zygosity) newIndividual.recessiveZygosity = zygosity;
if (probandIs) newIndividual.probandIs = probandIs;
if (affiliation) newIndividual.affiliation = affiliation.affiliation_id;
const newMethod = {dateTime: moment().format()};
newIndividual.method = newMethod;
// We created an individual; post it to the DB and return a promise with the new individual
return context.postRestData('/individuals/', newIndividual).then(data => {
return Promise.resolve(data['@graph'][0]);
});
}
/**
* Update the individual with the variants, and write the updated individual to the DB.
* @param {object} individual
* @param {object} variants
* @param {object} zygosity
* @param {string} probandIs - Value of "The proband is" form field (expected to be null for none/"No Selection")
* @param {object} context
*/
export function updateProbandVariants(individual, variants, zygosity, probandIs, context) {
let updateNeeded = true;
const probandIsExisting = individual && individual.probandIs ? individual.probandIs : null;
// Check whether the variants from the family are different from the variants in the individual
if (individual.variants && (individual.variants.length === variants.length)) {
// Same number of variants; see if the contents are different.
// Need to convert individual variant array to array of variant @ids, because that's what's in the variants array.
var missing = _.difference(variants, individual.variants.map(function(variant) { return variant['@id']; }));
updateNeeded = !!missing.length;
} else if ((individual.variants && individual.variants.length !== variants.length)
|| (!individual.variants && individual.variants && individual.variants.length > 0)) {
// Update individual's variant object if the number of variants do not match
updateNeeded = true;
}
/***********************************************************/
/* Update individual's recessiveZygosity property if: */
/* The passed argument is different from the strored value */
/***********************************************************/
let tempZygosity = zygosity ? zygosity : null;
let tempIndivZygosity = individual.recessiveZygosity ? individual.recessiveZygosity : null;
if (tempZygosity !== tempIndivZygosity) {
updateNeeded = true;
}
// Check if value of "The proband is" form field changed
if (probandIs !== probandIsExisting) {
updateNeeded = true;
}
if (updateNeeded) {
let writerIndividual = curator.flatten(individual);
let updatedScores = [];
// manage variants variable in individual object
if (!variants || (variants && variants.length === 0)) {
// if all variants are removed, prepare evidenceScore objects so their
// status can be set to 'deleted'
if (individual.scores && individual.scores.length) {
individual.scores.map(score => {
let flatScore = curator.flatten(score);
flatScore.status = 'deleted';
updatedScores.push(context.putRestData(score['@id'] + '?render=false', flatScore));
});
}
// delete relevant fields from updated individual object
delete writerIndividual['variants'];
delete writerIndividual['scores'];
} else {
writerIndividual.variants = variants;
}
// manage zygosity variable in individual object
if (zygosity) {
writerIndividual.recessiveZygosity = zygosity;
} else {
delete writerIndividual['recessiveZygosity'];
}
// Set probandIs attribute in individual object (based on form field value)
if (probandIs) {
writerIndividual.probandIs = probandIs;
} else {
delete writerIndividual['probandIs'];
}
return context.putRestData('/individuals/' + individual.uuid, writerIndividual).then(data => {
// update any evidenceScore objects, if any
return Promise.all(updatedScores);
});
}
return Promise.resolve(null);
}
export function recordIndividualHistory(gdm, annotation, individual, group, family, modified, context) {
// Add to the user history. data.individual always contains the new or edited individual. data.group contains the group the individual was
// added to, if it was added to a group. data.annotation contains the annotation the individual was added to, if it was added to
// the annotation, and data.family contains the family the individual was added to, if it was added to a family. If none of data.group,
// data.family, nor data.annotation exist, data.individual holds the existing individual that was modified.
let meta, historyPromise;
if (modified){
historyPromise = context.recordHistory('modify', individual);
} else {
if (family) {
// Record the creation of a new individual added to a family
meta = {
individual: {
gdm: gdm['@id'],
family: family['@id'],
article: annotation.article['@id']
}
};
historyPromise = context.recordHistory('add', individual, meta);
} else if (group) {
// Record the creation of a new individual added to a group
meta = {
individual: {
gdm: gdm['@id'],
group: group['@id'],
article: annotation.article['@id']
}
};
historyPromise = context.recordHistory('add', individual, meta);
} else if (annotation) {
// Record the creation of a new individual added to a GDM
meta = {
individual: {
gdm: gdm['@id'],
article: annotation.article['@id']
}
};
historyPromise = context.recordHistory('add', individual, meta);
}
}
return historyPromise;
}
/**
* Display a history item for adding an individual
*/
class IndividualAddHistory extends Component {
render() {
var history = this.props.history;
var individual = history.primary;
var gdm = history.meta.individual.gdm;
var group = history.meta.individual.group;
var family = history.meta.individual.family;
var article = history.meta.individual.article;
return (
<div>
Individual <a href={individual['@id']}>{individual.label}</a>
<span> added to </span>
{family ?
<span>family <a href={family['@id']}>{family.label}</a></span>
:
<span>
{group ?
<span>group <a href={group['@id']}>{group.label}</a></span>
:
<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>
}
</span>
}
<span> for <a href={'/curation-central/?gdm=' + gdm.uuid + '&pmid=' + article.pmid}>PMID:{article.pmid}</a>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span>
</div>
);
}
}
history_views.register(IndividualAddHistory, 'individual', 'add');
/**
* Display a history item for modifying an individual
*/
class IndividualModifyHistory extends Component {
render() {
var history = this.props.history;
var individual = history.primary;
return (
<div>
Individual <a href={individual['@id']}>{individual.label}</a>
<span> modified</span>
<span>; {moment(history.date_created).format("YYYY MMM DD, h:mm a")}</span>
</div>
);
}
}
history_views.register(IndividualModifyHistory, 'individual', 'modify');
/**
* Display a history item for deleting an individual
*/
class IndividualDeleteHistory extends Component {
render() {
var history = this.props.history;
var individual = history.primary;
return (
<div>
<span>Individual {individual.label} deleted</span>
<span>; {moment(individual.last_modified).format("YYYY MMM DD, h:mm a")}</span>
</div>
);
}
}
history_views.register(IndividualDeleteHistory, 'individual', 'delete');
|
frontend/javascript/components/app.component.js | artyomtrityak/letsplay-graphql-sever | import React from 'react';
import Relay from 'react-relay';
class App extends React.Component {
render() {
return (
<div>
<h1>Users list</h1>
<ul>
{this.props.viewer.users.map(user =>
<li key={user.id}>{user.email} (ID: {user.id})</li>
)}
</ul>
</div>
);
}
}
export default Relay.createContainer(App, {
fragments: {
viewer: () => Relay.QL`
fragment on RootViewerType {
users(page: 1) {
id,
email
},
}
`
}
});
|
react-native-life/ReactNativeLife/js/Components/SectionList/index.js | CaMnter/front-end-life | /**
* @author CaMnter
*/
import React from 'react';
import {SectionListExample} from "./SectionList";
class Root extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<SectionListExample/>
);
}
}
module.exports = Root; |
app/containers/MainPage/index.js | PeterKow/clientAurity | /*
*
* MainPage
*
*/
import React from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { fetchTest } from 'dbTweets'
import { createSelector } from 'reselect';
import mainSelector from 'mainSelector';
import Button from 'Button';
import SnippetContainer from 'components/snippet/snippet.container'
import styles from './styles.css';
import DataSource from 'components/data-source/data-source'
function MainPage({ dispatch }) {
return (
<div className={ styles.mainPage }>
<DataSource />
<SnippetContainer />
<Button onClick={ () => dispatch(push('/home')) } >Go to home</Button>
<Button onClick={ () => dispatch(fetchTest()) } >Fetch test</Button>
</div>
)
}
const mapStateToProps = createSelector(
mainSelector,
(main) => ({ main })
)
function mapDispatchToProps(dispatch) {
return {
dispatch,
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MainPage);
|
app/javascript/mastodon/features/getting_started/components/announcements.js | tootsuite/mastodon | import React from 'react';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ReactSwipeableViews from 'react-swipeable-views';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from 'mastodon/components/icon_button';
import Icon from 'mastodon/components/icon';
import { defineMessages, injectIntl, FormattedMessage, FormattedDate } from 'react-intl';
import { autoPlayGif, reduceMotion, disableSwiping } from 'mastodon/initial_state';
import elephantUIPlane from 'mastodon/../images/elephant_ui_plane.svg';
import { mascot } from 'mastodon/initial_state';
import unicodeMapping from 'mastodon/features/emoji/emoji_unicode_mapping_light';
import classNames from 'classnames';
import EmojiPickerDropdown from 'mastodon/features/compose/containers/emoji_picker_dropdown_container';
import AnimatedNumber from 'mastodon/components/animated_number';
import TransitionMotion from 'react-motion/lib/TransitionMotion';
import spring from 'react-motion/lib/spring';
import { assetHost } from 'mastodon/utils/config';
const messages = defineMessages({
close: { id: 'lightbox.close', defaultMessage: 'Close' },
previous: { id: 'lightbox.previous', defaultMessage: 'Previous' },
next: { id: 'lightbox.next', defaultMessage: 'Next' },
});
class Content extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
announcement: ImmutablePropTypes.map.isRequired,
};
setRef = c => {
this.node = c;
}
componentDidMount () {
this._updateLinks();
}
componentDidUpdate () {
this._updateLinks();
}
_updateLinks () {
const node = this.node;
if (!node) {
return;
}
const links = node.querySelectorAll('a');
for (var i = 0; i < links.length; ++i) {
let link = links[i];
if (link.classList.contains('status-link')) {
continue;
}
link.classList.add('status-link');
let mention = this.props.announcement.get('mentions').find(item => link.href === item.get('url'));
if (mention) {
link.addEventListener('click', this.onMentionClick.bind(this, mention), false);
link.setAttribute('title', mention.get('acct'));
} else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) {
link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false);
} else {
let status = this.props.announcement.get('statuses').find(item => link.href === item.get('url'));
if (status) {
link.addEventListener('click', this.onStatusClick.bind(this, status), false);
}
link.setAttribute('title', link.href);
link.classList.add('unhandled-link');
}
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
}
}
onMentionClick = (mention, e) => {
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/@${mention.get('acct')}`);
}
}
onHashtagClick = (hashtag, e) => {
hashtag = hashtag.replace(/^#/, '');
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/tags/${hashtag}`);
}
}
onStatusClick = (status, e) => {
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/@${status.getIn(['account', 'acct'])}/${status.get('id')}`);
}
}
handleMouseEnter = ({ currentTarget }) => {
if (autoPlayGif) {
return;
}
const emojis = currentTarget.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
emoji.src = emoji.getAttribute('data-original');
}
}
handleMouseLeave = ({ currentTarget }) => {
if (autoPlayGif) {
return;
}
const emojis = currentTarget.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
emoji.src = emoji.getAttribute('data-static');
}
}
render () {
const { announcement } = this.props;
return (
<div
className='announcements__item__content translate'
ref={this.setRef}
dangerouslySetInnerHTML={{ __html: announcement.get('contentHtml') }}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
/>
);
}
}
class Emoji extends React.PureComponent {
static propTypes = {
emoji: PropTypes.string.isRequired,
emojiMap: ImmutablePropTypes.map.isRequired,
hovered: PropTypes.bool.isRequired,
};
render () {
const { emoji, emojiMap, hovered } = this.props;
if (unicodeMapping[emoji]) {
const { filename, shortCode } = unicodeMapping[this.props.emoji];
const title = shortCode ? `:${shortCode}:` : '';
return (
<img
draggable='false'
className='emojione'
alt={emoji}
title={title}
src={`${assetHost}/emoji/${filename}.svg`}
/>
);
} else if (emojiMap.get(emoji)) {
const filename = (autoPlayGif || hovered) ? emojiMap.getIn([emoji, 'url']) : emojiMap.getIn([emoji, 'static_url']);
const shortCode = `:${emoji}:`;
return (
<img
draggable='false'
className='emojione custom-emoji'
alt={shortCode}
title={shortCode}
src={filename}
/>
);
} else {
return null;
}
}
}
class Reaction extends ImmutablePureComponent {
static propTypes = {
announcementId: PropTypes.string.isRequired,
reaction: ImmutablePropTypes.map.isRequired,
addReaction: PropTypes.func.isRequired,
removeReaction: PropTypes.func.isRequired,
emojiMap: ImmutablePropTypes.map.isRequired,
style: PropTypes.object,
};
state = {
hovered: false,
};
handleClick = () => {
const { reaction, announcementId, addReaction, removeReaction } = this.props;
if (reaction.get('me')) {
removeReaction(announcementId, reaction.get('name'));
} else {
addReaction(announcementId, reaction.get('name'));
}
}
handleMouseEnter = () => this.setState({ hovered: true })
handleMouseLeave = () => this.setState({ hovered: false })
render () {
const { reaction } = this.props;
let shortCode = reaction.get('name');
if (unicodeMapping[shortCode]) {
shortCode = unicodeMapping[shortCode].shortCode;
}
return (
<button className={classNames('reactions-bar__item', { active: reaction.get('me') })} onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} title={`:${shortCode}:`} style={this.props.style}>
<span className='reactions-bar__item__emoji'><Emoji hovered={this.state.hovered} emoji={reaction.get('name')} emojiMap={this.props.emojiMap} /></span>
<span className='reactions-bar__item__count'><AnimatedNumber value={reaction.get('count')} /></span>
</button>
);
}
}
class ReactionsBar extends ImmutablePureComponent {
static propTypes = {
announcementId: PropTypes.string.isRequired,
reactions: ImmutablePropTypes.list.isRequired,
addReaction: PropTypes.func.isRequired,
removeReaction: PropTypes.func.isRequired,
emojiMap: ImmutablePropTypes.map.isRequired,
};
handleEmojiPick = data => {
const { addReaction, announcementId } = this.props;
addReaction(announcementId, data.native.replace(/:/g, ''));
}
willEnter () {
return { scale: reduceMotion ? 1 : 0 };
}
willLeave () {
return { scale: reduceMotion ? 0 : spring(0, { stiffness: 170, damping: 26 }) };
}
render () {
const { reactions } = this.props;
const visibleReactions = reactions.filter(x => x.get('count') > 0);
const styles = visibleReactions.map(reaction => ({
key: reaction.get('name'),
data: reaction,
style: { scale: reduceMotion ? 1 : spring(1, { stiffness: 150, damping: 13 }) },
})).toArray();
return (
<TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}>
{items => (
<div className={classNames('reactions-bar', { 'reactions-bar--empty': visibleReactions.isEmpty() })}>
{items.map(({ key, data, style }) => (
<Reaction
key={key}
reaction={data}
style={{ transform: `scale(${style.scale})`, position: style.scale < 0.5 ? 'absolute' : 'static' }}
announcementId={this.props.announcementId}
addReaction={this.props.addReaction}
removeReaction={this.props.removeReaction}
emojiMap={this.props.emojiMap}
/>
))}
{visibleReactions.size < 8 && <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} button={<Icon id='plus' />} />}
</div>
)}
</TransitionMotion>
);
}
}
class Announcement extends ImmutablePureComponent {
static propTypes = {
announcement: ImmutablePropTypes.map.isRequired,
emojiMap: ImmutablePropTypes.map.isRequired,
addReaction: PropTypes.func.isRequired,
removeReaction: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
selected: PropTypes.bool,
};
state = {
unread: !this.props.announcement.get('read'),
};
componentDidUpdate () {
const { selected, announcement } = this.props;
if (!selected && this.state.unread !== !announcement.get('read')) {
this.setState({ unread: !announcement.get('read') });
}
}
render () {
const { announcement } = this.props;
const { unread } = this.state;
const startsAt = announcement.get('starts_at') && new Date(announcement.get('starts_at'));
const endsAt = announcement.get('ends_at') && new Date(announcement.get('ends_at'));
const now = new Date();
const hasTimeRange = startsAt && endsAt;
const skipYear = hasTimeRange && startsAt.getFullYear() === endsAt.getFullYear() && endsAt.getFullYear() === now.getFullYear();
const skipEndDate = hasTimeRange && startsAt.getDate() === endsAt.getDate() && startsAt.getMonth() === endsAt.getMonth() && startsAt.getFullYear() === endsAt.getFullYear();
const skipTime = announcement.get('all_day');
return (
<div className='announcements__item'>
<strong className='announcements__item__range'>
<FormattedMessage id='announcement.announcement' defaultMessage='Announcement' />
{hasTimeRange && <span> · <FormattedDate value={startsAt} hour12={false} year={(skipYear || startsAt.getFullYear() === now.getFullYear()) ? undefined : 'numeric'} month='short' day='2-digit' hour={skipTime ? undefined : '2-digit'} minute={skipTime ? undefined : '2-digit'} /> - <FormattedDate value={endsAt} hour12={false} year={(skipYear || endsAt.getFullYear() === now.getFullYear()) ? undefined : 'numeric'} month={skipEndDate ? undefined : 'short'} day={skipEndDate ? undefined : '2-digit'} hour={skipTime ? undefined : '2-digit'} minute={skipTime ? undefined : '2-digit'} /></span>}
</strong>
<Content announcement={announcement} />
<ReactionsBar
reactions={announcement.get('reactions')}
announcementId={announcement.get('id')}
addReaction={this.props.addReaction}
removeReaction={this.props.removeReaction}
emojiMap={this.props.emojiMap}
/>
{unread && <span className='announcements__item__unread' />}
</div>
);
}
}
export default @injectIntl
class Announcements extends ImmutablePureComponent {
static propTypes = {
announcements: ImmutablePropTypes.list,
emojiMap: ImmutablePropTypes.map.isRequired,
dismissAnnouncement: PropTypes.func.isRequired,
addReaction: PropTypes.func.isRequired,
removeReaction: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
state = {
index: 0,
};
static getDerivedStateFromProps(props, state) {
if (props.announcements.size > 0 && state.index >= props.announcements.size) {
return { index: props.announcements.size - 1 };
} else {
return null;
}
}
componentDidMount () {
this._markAnnouncementAsRead();
}
componentDidUpdate () {
this._markAnnouncementAsRead();
}
_markAnnouncementAsRead () {
const { dismissAnnouncement, announcements } = this.props;
const { index } = this.state;
const announcement = announcements.get(announcements.size - 1 - index);
if (!announcement.get('read')) dismissAnnouncement(announcement.get('id'));
}
handleChangeIndex = index => {
this.setState({ index: index % this.props.announcements.size });
}
handleNextClick = () => {
this.setState({ index: (this.state.index + 1) % this.props.announcements.size });
}
handlePrevClick = () => {
this.setState({ index: (this.props.announcements.size + this.state.index - 1) % this.props.announcements.size });
}
render () {
const { announcements, intl } = this.props;
const { index } = this.state;
if (announcements.isEmpty()) {
return null;
}
return (
<div className='announcements'>
<img className='announcements__mastodon' alt='' draggable='false' src={mascot || elephantUIPlane} />
<div className='announcements__container'>
<ReactSwipeableViews animateHeight={!reduceMotion} adjustHeight={reduceMotion} index={index} onChangeIndex={this.handleChangeIndex}>
{announcements.map((announcement, idx) => (
<Announcement
key={announcement.get('id')}
announcement={announcement}
emojiMap={this.props.emojiMap}
addReaction={this.props.addReaction}
removeReaction={this.props.removeReaction}
intl={intl}
selected={index === idx}
disabled={disableSwiping}
/>
)).reverse()}
</ReactSwipeableViews>
{announcements.size > 1 && (
<div className='announcements__pagination'>
<IconButton disabled={announcements.size === 1} title={intl.formatMessage(messages.previous)} icon='chevron-left' onClick={this.handlePrevClick} size={13} />
<span>{index + 1} / {announcements.size}</span>
<IconButton disabled={announcements.size === 1} title={intl.formatMessage(messages.next)} icon='chevron-right' onClick={this.handleNextClick} size={13} />
</div>
)}
</div>
</div>
);
}
}
|
src/Parser/HolyPaladin/Modules/Features/CastEfficiency.js | Yuyz0112/WoWAnalyzer | import React from 'react';
import ITEMS from 'common/ITEMS';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import ISSUE_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE';
import CoreCastEfficiency from 'Parser/Core/Modules/CastEfficiency';
const SPELL_CATEGORY = {
ROTATIONAL: 'Rotational Spell',
COOLDOWNS: 'Cooldown',
OTHERS: 'Spell',
};
class CastEfficiency extends CoreCastEfficiency {
static CPM_ABILITIES = [
{
spell: SPELLS.HOLY_SHOCK_HEAL,
category: SPELL_CATEGORY.ROTATIONAL,
getCasts: castCount => castCount.healingHits,
getCooldown: haste => 9 / (1 + haste),
extraSuggestion: 'Casting Holy Shock often enough is very important.',
},
{
spell: SPELLS.LIGHT_OF_DAWN_CAST,
category: SPELL_CATEGORY.ROTATIONAL,
getCooldown: haste => 12 / (1 + haste), // TODO: Implement 4PT20
getOverhealing: (_, getAbility) => {
const { healingEffective, healingAbsorbed, healingOverheal } = getAbility(SPELLS.LIGHT_OF_DAWN_HEAL.id);
return healingOverheal / (healingEffective + healingAbsorbed + healingOverheal);
},
extraSuggestion: 'Casting Light of Dawn often enough is very important.',
},
{
spell: SPELLS.JUDGMENT_CAST,
category: SPELL_CATEGORY.ROTATIONAL,
getCooldown: haste => 12 / (1 + haste),
isActive: combatant => combatant.hasTalent(SPELLS.JUDGMENT_OF_LIGHT_TALENT.id),
recommendedCastEfficiency: 0.85, // this rarely overheals, so keeping this on cooldown is pretty much always best
getOverhealing: (_, getAbility) => {
const { healingEffective, healingAbsorbed, healingOverheal } = getAbility(SPELLS.JUDGMENT_OF_LIGHT_HEAL.id);
return healingOverheal / (healingEffective + healingAbsorbed + healingOverheal);
},
extraSuggestion: 'You should cast it whenever Judgment of Light has dropped, which is usually on cooldown without delay. Alternatively you can ignore the debuff and just cast it whenever Judgment is available; there\'s nothing wrong with ignoring unimportant things to focus on important things.',
},
{
spell: SPELLS.BESTOW_FAITH_TALENT,
category: SPELL_CATEGORY.ROTATIONAL,
getCooldown: haste => 12,
isActive: combatant => combatant.hasTalent(SPELLS.BESTOW_FAITH_TALENT.id),
recommendedCastEfficiency: 0.7,
extraSuggestion: <span>If you can't or don't want to cast <SpellLink id={SPELLS.BESTOW_FAITH_TALENT.id} /> more consider using <SpellLink id={SPELLS.LIGHTS_HAMMER_TALENT.id} /> or <SpellLink id={SPELLS.CRUSADERS_MIGHT_TALENT.id} /> instead.</span>,
},
{
spell: SPELLS.LIGHTS_HAMMER_TALENT,
category: SPELL_CATEGORY.ROTATIONAL,
getCooldown: haste => 60,
isActive: combatant => combatant.hasTalent(SPELLS.LIGHTS_HAMMER_TALENT.id),
getOverhealing: (_, getAbility) => {
const { healingEffective, healingAbsorbed, healingOverheal } = getAbility(SPELLS.LIGHTS_HAMMER_HEAL.id);
return healingOverheal / (healingEffective + healingAbsorbed + healingOverheal);
},
},
{
spell: SPELLS.CRUSADER_STRIKE,
category: SPELL_CATEGORY.ROTATIONAL,
getCooldown: haste => 4.5 / (1 + haste),
charges: 2,
isActive: combatant => combatant.hasTalent(SPELLS.CRUSADERS_MIGHT_TALENT.id),
recommendedCastEfficiency: 0.60,
extraSuggestion: <span>When you are using <SpellLink id={SPELLS.CRUSADERS_MIGHT_TALENT.id} /> it is important to use <SpellLink id={SPELLS.CRUSADER_STRIKE.id} /> often enough to benefit from the talent. Use a different talent if you are unable to.</span>,
},
{
spell: SPELLS.HOLY_PRISM_TALENT,
category: SPELL_CATEGORY.ROTATIONAL,
getCooldown: haste => 20,
isActive: combatant => combatant.hasTalent(SPELLS.HOLY_PRISM_TALENT.id),
},
{
spell: SPELLS.RULE_OF_LAW_TALENT,
category: SPELL_CATEGORY.COOLDOWNS,
getCooldown: haste => 30,
charges: 2,
isActive: combatant => combatant.hasTalent(SPELLS.RULE_OF_LAW_TALENT.id),
noSuggestion: true,
},
{
spell: SPELLS.DIVINE_PROTECTION,
category: SPELL_CATEGORY.COOLDOWNS,
getCooldown: haste => 60,
recommendedCastEfficiency: 0.6,
importance: ISSUE_IMPORTANCE.MINOR,
},
{
spell: SPELLS.ARCANE_TORRENT,
category: SPELL_CATEGORY.COOLDOWNS,
getCooldown: haste => 90,
hideWithZeroCasts: true,
},
{
spell: SPELLS.TYRS_DELIVERANCE_CAST,
category: SPELL_CATEGORY.COOLDOWNS,
getCooldown: haste => 90,
extraSuggestion: '',
},
{
spell: SPELLS.VELENS_FUTURE_SIGHT,
category: SPELL_CATEGORY.COOLDOWNS,
getCooldown: haste => 75,
isActive: combatant => combatant.hasTrinket(ITEMS.VELENS_FUTURE_SIGHT.id),
},
{
spell: SPELLS.GNAWED_THUMB_RING,
category: SPELL_CATEGORY.COOLDOWNS,
getCooldown: haste => 180,
isActive: combatant => combatant.hasFinger(ITEMS.GNAWED_THUMB_RING.id),
},
{
spell: SPELLS.HOLY_AVENGER_TALENT,
category: SPELL_CATEGORY.COOLDOWNS,
getCooldown: haste => 90,
isActive: combatant => combatant.hasTalent(SPELLS.HOLY_AVENGER_TALENT.id),
},
{
spell: SPELLS.AVENGING_WRATH,
category: SPELL_CATEGORY.COOLDOWNS,
getCooldown: haste => 120,
},
{
spell: SPELLS.BLESSING_OF_SACRIFICE,
category: SPELL_CATEGORY.COOLDOWNS,
getCooldown: haste => 150,
recommendedCastEfficiency: 0.5,
noSuggestion: true,
importance: ISSUE_IMPORTANCE.MINOR,
},
{
spell: SPELLS.AURA_MASTERY,
category: SPELL_CATEGORY.COOLDOWNS,
getCooldown: haste => 180,
},
{
spell: SPELLS.LIGHT_OF_THE_MARTYR,
category: SPELL_CATEGORY.OTHERS,
getCooldown: haste => null,
},
{
spell: SPELLS.FLASH_OF_LIGHT,
name: `Filler ${SPELLS.FLASH_OF_LIGHT.name}`,
category: SPELL_CATEGORY.OTHERS,
getCasts: castCount => (castCount.casts || 0) - (castCount.healingIolHits || 0),
getCooldown: haste => null,
getOverhealing: ({ healingEffective, healingAbsorbed, healingOverheal, healingIolHealing, healingIolAbsorbed, healingIolOverheal }) => (healingOverheal - healingIolOverheal) / ((healingEffective - healingIolHealing) + (healingAbsorbed - healingIolAbsorbed) + (healingOverheal - healingIolOverheal)),
},
{
spell: SPELLS.FLASH_OF_LIGHT,
name: `Infusion of Light ${SPELLS.FLASH_OF_LIGHT.name}`,
category: SPELL_CATEGORY.OTHERS,
getCasts: castCount => castCount.healingIolHits || 0,
getCooldown: haste => null,
getOverhealing: ({ healingIolHealing, healingIolAbsorbed, healingIolOverheal }) => healingIolOverheal / (healingIolHealing + healingIolAbsorbed + healingIolOverheal),
},
{
spell: SPELLS.HOLY_LIGHT,
name: `Filler ${SPELLS.HOLY_LIGHT.name}`,
category: SPELL_CATEGORY.OTHERS,
getCasts: castCount => (castCount.casts || 0) - (castCount.healingIolHits || 0),
getCooldown: haste => null,
getOverhealing: ({ healingEffective, healingAbsorbed, healingOverheal, healingIolHealing, healingIolAbsorbed, healingIolOverheal }) => (healingOverheal - healingIolOverheal) / ((healingEffective - healingIolHealing) + (healingAbsorbed - healingIolAbsorbed) + (healingOverheal - healingIolOverheal)),
},
{
spell: SPELLS.HOLY_LIGHT,
name: `Infusion of Light ${SPELLS.HOLY_LIGHT.name}`,
category: SPELL_CATEGORY.OTHERS,
getCasts: castCount => castCount.healingIolHits || 0,
getCooldown: haste => null,
getOverhealing: ({ healingIolHealing, healingIolAbsorbed, healingIolOverheal }) => healingIolOverheal / (healingIolHealing + healingIolAbsorbed + healingIolOverheal),
},
];
static SPELL_CATEGORIES = SPELL_CATEGORY;
}
export default CastEfficiency;
|
actor-apps/app-web/src/app/index.js | mxw0417/actor-platform | import crosstab from 'crosstab';
import React from 'react';
import Router from 'react-router';
import Raven from 'utils/Raven'; // eslint-disable-line
import injectTapEventPlugin from 'react-tap-event-plugin';
import Deactivated from 'components/Deactivated.react';
import Login from 'components/Login.react';
import Main from 'components/Main.react';
import JoinGroup from 'components/JoinGroup.react';
import LoginStore from 'stores/LoginStore';
import LoginActionCreators from 'actions/LoginActionCreators';
const DefaultRoute = Router.DefaultRoute;
const Route = Router.Route;
const RouteHandler = Router.RouteHandler;
const ActorInitEvent = 'concurrentActorInit';
if (crosstab.supported) {
crosstab.on(ActorInitEvent, (msg) => {
if (msg.origin !== crosstab.id && window.location.hash !== '#/deactivated') {
window.location.assign('#/deactivated');
window.location.reload();
}
});
}
const initReact = () => {
if (window.location.hash !== '#/deactivated') {
if (crosstab.supported) {
crosstab.broadcast(ActorInitEvent, {});
}
if (location.pathname === '/app/index.html') {
window.messenger = new window.actor.ActorApp(['ws://' + location.hostname + ':9080/']);
} else {
window.messenger = new window.actor.ActorApp();
}
}
const App = React.createClass({
render() {
return <RouteHandler/>;
}
});
const routes = (
<Route handler={App} name="app" path="/">
<Route handler={Main} name="main" path="/"/>
<Route handler={JoinGroup} name="join" path="/join/:token"/>
<Route handler={Login} name="login" path="/auth"/>
<Route handler={Deactivated} name="deactivated" path="/deactivated"/>
<DefaultRoute handler={Main}/>
</Route>
);
const router = Router.run(routes, Router.HashLocation, function (Handler) {
injectTapEventPlugin();
React.render(<Handler/>, document.getElementById('actor-web-app'));
});
if (window.location.hash !== '#/deactivated') {
if (LoginStore.isLoggedIn()) {
LoginActionCreators.setLoggedIn(router, {redirect: false});
}
}
};
window.jsAppLoaded = () => {
setTimeout(initReact, 0);
};
|
src/svg-icons/content/move-to-inbox.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentMoveToInbox = (props) => (
<SvgIcon {...props}>
<path d="M19 3H4.99c-1.11 0-1.98.9-1.98 2L3 19c0 1.1.88 2 1.99 2H19c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 12h-4c0 1.66-1.35 3-3 3s-3-1.34-3-3H4.99V5H19v10zm-3-5h-2V7h-4v3H8l4 4 4-4z"/>
</SvgIcon>
);
ContentMoveToInbox = pure(ContentMoveToInbox);
ContentMoveToInbox.displayName = 'ContentMoveToInbox';
ContentMoveToInbox.muiName = 'SvgIcon';
export default ContentMoveToInbox;
|
packages/reactor-kitchensink/src/examples/Layouts/fit/fit.js | sencha/extjs-reactor | import React, { Component } from 'react';
import { Container, Panel } from '@extjs/ext-react';
import colors from '../../colors';
export default class FitLayoutExample extends Component {
render() {
return (
<Container layout="vbox" padding={10}>
<Panel shadow ui="instructions" margin="0 0 20 0">
<div>A <b>fit</b> layout displays a single item, which takes on the full height and width of the container.</div>
</Panel>
<Panel layout="fit" height={200} flex={1} shadow>
<Container {...itemDefaults} style={colors.card.red}>Content</Container>
</Panel>
</Container>
)
}
}
const itemDefaults = {
layout: {
type: 'vbox',
pack: 'center',
align: 'center'
}
}
|
node_modules/material-ui/src/styles/theme-decorator.js | DocWave/Doc-tor | import React from 'react';
export default (customTheme) => {
return function(Component) {
return React.createClass({
childContextTypes: {
muiTheme: React.PropTypes.object,
},
getChildContext() {
return {
muiTheme: customTheme,
};
},
render() {
return React.createElement(Component, this.props);
},
});
};
};
|
tests/react_modules/es6class-proptypes-callsite.js | fletcherw/flow | /* @flow */
import React from 'react';
import Hello from './es6class-proptypes-module';
class HelloLocal extends React.Component<void, {name: string}, void> {
defaultProps = {};
propTypes = {
name: React.PropTypes.string.isRequired,
};
render(): React.Element<*> {
return <div>{this.props.name}</div>;
}
}
class Callsite extends React.Component<void, {}, void> {
render(): React.Element<*> {
return (
<div>
<Hello />
<HelloLocal />
</div>
);
}
}
module.exports = Callsite;
|
src/components/icons/PauseCircleIconBold.js | InsideSalesOfficial/insidesales-components | import React from 'react';
import { colors, generateFillFromProps } from '../styles/colors';
const PauseCircleIconBold = props => (
<svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 512 512">
{props.title && <title>{props.title}</title>}
<path {...generateFillFromProps(props, colors.grayD)} d="M 256 8 C 119 8 8 119 8 256 s 111 248 248 248 s 248 -111 248 -248 S 393 8 256 8 Z m -16 328 c 0 8.8 -7.2 16 -16 16 h -48 c -8.8 0 -16 -7.2 -16 -16 V 176 c 0 -8.8 7.2 -16 16 -16 h 48 c 8.8 0 16 7.2 16 16 v 160 Z m 112 0 c 0 8.8 -7.2 16 -16 16 h -48 c -8.8 0 -16 -7.2 -16 -16 V 176 c 0 -8.8 7.2 -16 16 -16 h 48 c 8.8 0 16 7.2 16 16 v 160 Z" />
<path d="M0 0h24v24H0z" fill="none" />
</svg>
);
export default PauseCircleIconBold;
|
ssr_demo/react-ssr-demo/src/createApp.js | hstarorg/PythonDemo | import App from './pages/App';
import { Provider } from 'react-redux';
import React from 'react';
export const createApp = (store) => (
<Provider store={store}>
<App />
</Provider>
);
|
fixtures/fiber-debugger/src/index.js | aickin/react | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(<App />, document.getElementById('root'));
|
viewer/core/static/js/app/components/views/chart.js | openjck/distribution-viewer | import React from 'react';
import Fetching from './fetching';
import ChartAxisContainer from '../containers/chart-axis-container';
import ChartLineContainer from '../containers/chart-line-container';
import ChartHoverContainer from '../containers/chart-hover-container';
import ChartFocus from './chart-focus';
export default class extends React.Component {
constructor(props) {
super(props);
}
renderPopulations(props, populationData) {
let renderings = [];
for (let populationName in populationData) {
if (populationData.hasOwnProperty(populationName)) {
const currentPopulation = populationData[populationName];
renderings.push(
<g key={props.metricId + populationName} className="population" data-population={populationName}>
<ChartLineContainer
populationName={populationName}
metricId={props.metricId}
xScale={props.xScale}
yScale={props.yScale}
data={currentPopulation[props.activeDatasetName]}
/>
<ChartFocus />
</g>
);
}
}
return renderings;
}
render() {
if (this.props.noData) {
return (
<div className={`chart chart-${this.props.metricId} no-data`}>
<span className="warning">No data</span>
<span>(try selecting different populations)</span>
</div>
);
} else if (this.props.isFetching) {
return (
<div className={`chart is-fetching chart-${this.props.metricId}`}>
<Fetching />
</div>
);
} else {
var all, pdExcludingAll, pdOnlyAll;
if (this.props.populationData['All']) {
// ES6!
//
// This is equivalent the following:
// const all = this.props.populdationData['All'];
// const pdExcludingAll = this.props.populdationData[... everything else ...];
// const pdOnlyAll = { 'All': all };
({'All': all, ...pdExcludingAll} = this.props.populationData);
pdOnlyAll = { 'All': all }
} else {
pdExcludingAll = this.props.populationData;
}
return (
<div className={`chart chart-${this.props.metricId}`}>
<div className={this.props.tooltip ? 'tooltip-wrapper' : ''}>
<h2 className={`chart-list-name ${this.props.tooltip ? 'tooltip-hover-target' : ''}`}>{this.props.name}</h2>
{this.props.tooltip}
</div>
<svg width={this.props.size.width} height={this.props.size.height}>
<g transform={this.props.size.transform}>
<ChartAxisContainer
metricId={this.props.metricId}
metricType={this.props.metricType}
scale={this.props.xScale}
axisType="x"
refLabels={this.props.refLabels}
size={this.props.size.innerHeight}
/>
<ChartAxisContainer
metricId={this.props.metricId}
scale={this.props.yScale}
axisType="y"
refLabels={this.props.refLabels}
size={this.props.size.innerWidth}
/>
<g className="populations">
{/*
In SVG, the elemenet that appears last in the markup has the
greatest "z-index". We want the "All" population to appear above
other populations when they overlap, so we need to render it last.
*/}
{this.renderPopulations(this.props, pdExcludingAll)}
{pdOnlyAll && this.renderPopulations(this.props, pdOnlyAll)}
</g>
<ChartHoverContainer
metricId={this.props.metricId}
size={this.props.size}
xScale={this.props.xScale}
yScale={this.props.yScale}
populations={this.props.populationData}
activeDatasetName={this.props.activeDatasetName}
hoverString={this.props.hoverString}
refLabels={this.props.refLabels}
metricType={this.props.metricType}
/>
</g>
</svg>
</div>
);
}
}
}
|
client/src/containers/App.js | Nonsoft/crdweb | import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import AppLayout from '../components/AppLayout';
import AppRoutes from '../routes/AppRoutes';
import Login from './Login'
import { fetchUserLogout, fetchInitData } from '../actions';
class App extends Component {
componentDidMount() {
this.props.fetchInitData()
}
render() {
const { admin, isLogin, fetchUserLogout } = this.props
return (
isLogin ? (
<AppLayout admin={admin} handlePoweroff={(username) => fetchUserLogout(username)}>
<AppRoutes
auth={admin.auth}
/>
</AppLayout>
) : (
<Login/>
)
);
}
}
App.propTypes = {
admin: PropTypes.object.isRequired,
isLogin: PropTypes.bool.isRequired,
fetchUserLogout: PropTypes.func.isRequired,
}
const mapStateToProps = (state) => {
return {
admin: state.admin,
isLogin: state.isLogin,
}
}
const mapDispatchToProps = {
fetchUserLogout,
fetchInitData,
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
|
node_modules/react-router/es6/RoutingContext.js | MichaelWiss/React_E | import React from 'react';
import RouterContext from './RouterContext';
import warning from './routerWarning';
var RoutingContext = React.createClass({
displayName: 'RoutingContext',
componentWillMount: function componentWillMount() {
process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0;
},
render: function render() {
return React.createElement(RouterContext, this.props);
}
});
export default RoutingContext; |
src/client/components/TeamCardWidget/TeamCardWidget.js | vidaaudrey/trippian | import log from '../../log'
import React from 'react'
const TeamCardWidget = ({
github = 'https://github.com/trippian/', name = '', image = '', about = '', location = '', role = 'Software Engineer'
}) => {
return (
<div className="col-xs-12 col-sm-6 col-md-6 team">
<div className="text-center">
<div className="circle-image photo">
<a href={github}>
<img src={image} alt={name} />
</a>
</div>
<div className="row">
<h2>{name}</h2>
<h4>{location}</h4>
<h4>{role}</h4>
<p className="text-left">{about}</p>
</div>
</div>
</div>
)
}
TeamCardWidget.displayName = 'TeamCardWidget'
export default TeamCardWidget
|
site/IndexPage.js | konce/react-dnd | import './base.less';
import Constants, { APIPages, ExamplePages, Pages } from './Constants';
import HomePage from './pages/HomePage';
import APIPage from './pages/APIPage';
import ExamplePage from './pages/ExamplePage';
import React, { Component } from 'react';
const APIDocs = {
OVERVIEW: require('../docs/00 Quick Start/Overview.md'),
TUTORIAL: require('../docs/00 Quick Start/Tutorial.md'),
TESTING: require('../docs/00 Quick Start/Testing.md'),
FAQ: require('../docs/00 Quick Start/FAQ.md'),
TROUBLESHOOTING: require('../docs/00 Quick Start/Troubleshooting.md'),
DRAG_SOURCE: require('../docs/01 Top Level API/DragSource.md'),
DRAG_SOURCE_MONITOR: require('../docs/03 Monitoring State/DragSourceMonitor.md'),
DRAG_SOURCE_CONNECTOR: require('../docs/02 Connecting to DOM/DragSourceConnector.md'),
DROP_TARGET: require('../docs/01 Top Level API/DropTarget.md'),
DROP_TARGET_CONNECTOR: require('../docs/02 Connecting to DOM/DropTargetConnector.md'),
DROP_TARGET_MONITOR: require('../docs/03 Monitoring State/DropTargetMonitor.md'),
DRAG_DROP_CONTEXT: require('../docs/01 Top Level API/DragDropContext.md'),
DRAG_LAYER: require('../docs/01 Top Level API/DragLayer.md'),
DRAG_LAYER_MONITOR: require('../docs/03 Monitoring State/DragLayerMonitor.md'),
HTML5_BACKEND: require('../docs/04 Backends/HTML5.md'),
TEST_BACKEND: require('../docs/04 Backends/Test.md')
};
const Examples = {
CHESSBOARD_TUTORIAL_APP: require('../examples/00 Chessboard/Tutorial App'),
DUSTBIN_SINGLE_TARGET: require('../examples/01 Dustbin/Single Target'),
DUSTBIN_MULTIPLE_TARGETS: require('../examples/01 Dustbin/Multiple Targets'),
DUSTBIN_STRESS_TEST: require('../examples/01 Dustbin/Stress Test'),
DRAG_AROUND_NAIVE: require('../examples/02 Drag Around/Naive'),
DRAG_AROUND_CUSTOM_DRAG_LAYER: require('../examples/02 Drag Around/Custom Drag Layer'),
NESTING_DRAG_SOURCES: require('../examples/03 Nesting/Drag Sources'),
NESTING_DROP_TARGETS: require('../examples/03 Nesting/Drop Targets'),
SORTABLE_SIMPLE: require('../examples/04 Sortable/Simple'),
SORTABLE_CANCEL_ON_DROP_OUTSIDE: require('../examples/04 Sortable/Cancel on Drop Outside'),
SORTABLE_STRESS_TEST: require('../examples/04 Sortable/Stress Test'),
CUSTOMIZE_HANDLES_AND_PREVIEWS: require('../examples/05 Customize/Handles and Previews'),
CUSTOMIZE_DROP_EFFECTS: require('../examples/05 Customize/Drop Effects')
};
export default class IndexPage extends Component {
static getDoctype() {
return '<!doctype html>';
}
static renderToString(props) {
return IndexPage.getDoctype() +
React.renderToString(<IndexPage {...props} />);
}
constructor(props) {
super(props);
this.state = {
renderPage: !this.props.devMode
};
}
render() {
// Dump out our current props to a global object via a script tag so
// when initialising the browser environment we can bootstrap from the
// same props as what each page was rendered with.
const browserInitScriptObj = {
__html: 'window.INITIAL_PROPS = ' + JSON.stringify(this.props) + ';\n'
};
return (
<html>
<head>
<meta charSet="utf-8" />
<title>React DnD</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<link rel="stylesheet" type="text/css" href={this.props.files['main.css']} />
<base target="_blank" />
</head>
<body>
{this.state.renderPage && this.renderPage()}
<script dangerouslySetInnerHTML={browserInitScriptObj} />
<script src={this.props.files['main.js']}></script>
</body>
</html>
);
}
renderPage() {
switch (this.props.location) {
case Pages.HOME.location:
return <HomePage />;
}
for (let groupIndex in APIPages) {
const group = APIPages[groupIndex];
const pageKeys = Object.keys(group.pages);
for (let i = 0; i < pageKeys.length; i++) {
const key = pageKeys[i];
const page = group.pages[key];
if (this.props.location === page.location) {
return <APIPage example={page}
html={APIDocs[key]} />;
}
}
}
for (let groupIndex in ExamplePages) {
const group = ExamplePages[groupIndex];
const pageKeys = Object.keys(group.pages);
for (let i = 0; i < pageKeys.length; i++) {
const key = pageKeys[i];
const page = group.pages[key];
const Component = Examples[key];
if (this.props.location === page.location) {
return (
<ExamplePage example={page}>
<Component />
</ExamplePage>
);
}
}
}
throw new Error(
'Page of location ' +
JSON.stringify(this.props.location) +
' not found.'
);
}
componentDidMount() {
if (!this.state.renderPage) {
this.setState({
renderPage: true
});
}
}
} |
assets/jqwidgets/demos/react/app/chart/percentagestackedcolumns/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxChart from '../../../jqwidgets-react/react_jqxchart.js';
class App extends React.Component {
render() {
let sampleData = [{ a: 0.35, b: 14.5 }, { a: 1, b: 2.5 }, { a: 10, b: 0.2 }, { a: 100, b: 205 }, { a: 1, b: 100 }, { a: 5.11, b: 10.13 }, { a: 20.13, b: 10.13 }, { a: 600, b: 300 }];
let padding = { left: 5, top: 5, right: 5, bottom: 5 };
let titlePadding = { left: 0, top: 0, right: 0, bottom: 10 };
let xAxis =
{
dataField: ''
};
let valueAxis =
{
logarithmicScale: true,
logarithmicScaleBase: 2,
unitInterval: 1,
tickMarks: { interval: 1 },
gridLines: { interval: 1 },
title: { text: 'Value' },
labels: {
formatSettings: { decimalPlaces: 3, sufix: '' },
horizontalAlignment: 'right'
}
};
let seriesGroups =
[
{
type: 'stackedcolumn100',
columnsGapPercent: 50,
series: [
{ dataField: 'a', displayText: 'A' },
{ dataField: 'b', displayText: 'B' }
]
},
{
type: 'stackedline100',
series: [
{ dataField: 'a', displayText: 'A' },
{ dataField: 'b', displayText: 'B' }
]
}
];
return (
<JqxChart style={{ width: 850, height: 500 }}
title={'Logarithmic Scale Axis Example'} description={'Percentage Stacked Columns with logarithmic scale axis (base 2)'}
enableAnimations={false} padding={padding} titlePadding={titlePadding}
xAxis={xAxis} valueAxis={valueAxis} seriesGroups={seriesGroups} source={sampleData}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/device/signal-wifi-1-bar-lock.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi1BarLock = (props) => (
<SvgIcon {...props}>
<path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z"/><path d="M15.5 14.5c0-2.8 2.2-5 5-5 .4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4C5.3 3 .8 6.7.4 7L12 21.5l3.5-4.3v-2.7z" opacity=".3"/><path d="M6.7 14.9l5.3 6.6 3.5-4.3v-2.6c0-.2 0-.5.1-.7-.9-.5-2.2-.9-3.6-.9-3 0-5.1 1.7-5.3 1.9z"/>
</SvgIcon>
);
DeviceSignalWifi1BarLock = pure(DeviceSignalWifi1BarLock);
DeviceSignalWifi1BarLock.displayName = 'DeviceSignalWifi1BarLock';
export default DeviceSignalWifi1BarLock;
|
src/svg-icons/action/swap-horiz.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSwapHoriz = (props) => (
<SvgIcon {...props}>
<path d="M6.99 11L3 15l3.99 4v-3H14v-2H6.99v-3zM21 9l-3.99-4v3H10v2h7.01v3L21 9z"/>
</SvgIcon>
);
ActionSwapHoriz = pure(ActionSwapHoriz);
ActionSwapHoriz.displayName = 'ActionSwapHoriz';
ActionSwapHoriz.muiName = 'SvgIcon';
export default ActionSwapHoriz;
|
src/components/MultiSelect/MultiSelect-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.
*/
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import {
withKnobs,
boolean,
select,
text,
object,
} from '@storybook/addon-knobs';
import { withReadme } from 'storybook-readme';
import readme from './README.md';
import MultiSelect from '../MultiSelect';
const items = [
{
id: 'downshift-1-item-0',
text: 'Option 1',
},
{
id: 'downshift-1-item-1',
text: 'Option 2',
},
{
id: 'downshift-1-item-2',
text: 'Option 3',
},
{
id: 'downshift-1-item-3',
text: 'Option 4',
},
{
id: 'downshift-1-item-4',
text:
'An example option that is really long to show what should be done to handle long text',
},
];
const defaultLabel = 'MultiSelect Label';
const defaultPlaceholder = 'Filter';
const types = {
'Default (default)': 'default',
'Inline (inline)': 'inline',
};
const props = () => ({
id: text('MultiSelect ID (id)', 'carbon-multiselect-example'),
titleText: text('Title (titleText)', 'Multiselect title'),
helperText: text('Helper text (helperText)', 'This is not helper text'),
filterable: boolean(
'Filterable (`<MultiSelect.Filterable>` instead of `<MultiSelect>`)',
false
),
disabled: boolean('Disabled (disabled)', false),
light: boolean('Light variant (light)', false),
useTitleInItem: boolean('Show tooltip on hover', false),
type: select('UI type (Only for `<MultiSelect>`) (type)', types, 'default'),
label: text('Label (label)', defaultLabel),
invalid: boolean('Show form validation UI (invalid)', false),
invalidText: text(
'Form validation UI content (invalidText)',
'Invalid Selection'
),
onChange: action('onChange'),
listBoxMenuIconTranslationIds: object(
'Listbox menu icon translation IDs (for translateWithId callback)',
{
'close.menu': 'Close menu',
'open.menu': 'Open menu',
}
),
selectionFeedback: select(
'Selection feedback',
['top', 'fixed', 'top-after-reopen'],
'top-after-reopen'
),
});
storiesOf('MultiSelect', module)
.addDecorator(withKnobs)
.add(
'default',
withReadme(readme, () => {
const {
filterable,
listBoxMenuIconTranslationIds,
selectionFeedback,
...multiSelectProps
} = props();
const ComponentToUse = !filterable ? MultiSelect : MultiSelect.Filterable;
const placeholder = !filterable ? undefined : defaultPlaceholder;
return (
<div style={{ width: 300 }}>
<ComponentToUse
{...multiSelectProps}
items={items}
itemToString={item => (item ? item.text : '')}
placeholder={placeholder}
translateWithId={id => listBoxMenuIconTranslationIds[id]}
selectionFeedback={selectionFeedback}
/>
</div>
);
}),
{
info: {
text: `
MultiSelect
`,
},
}
)
.add(
'with initial selected items',
withReadme(readme, () => {
const {
filterable,
listBoxMenuIconTranslationIds,
selectionFeedback,
...multiSelectProps
} = props();
const ComponentToUse = !filterable ? MultiSelect : MultiSelect.Filterable;
const placeholder = !filterable ? undefined : defaultPlaceholder;
return (
<div style={{ width: 300 }}>
<ComponentToUse
{...multiSelectProps}
items={items}
itemToString={item => (item ? item.text : '')}
initialSelectedItems={[items[0], items[1]]}
placeholder={placeholder}
translateWithId={id => listBoxMenuIconTranslationIds[id]}
selectionFeedback={selectionFeedback}
/>
</div>
);
}),
{
info: {
text: `
Provide a set of items to initially select in the control
`,
},
}
);
|
src/scenes/dashboard/grouplist/index.js | PowerlineApp/powerline-rn | //This is the My Groups screen accessible via the burger menu
//Shows the user's current groups he is joined to except public town/state/country groups (which only appear on Group Selector, not in My Groups list below)
//https://api-dev.powerli.ne/api-doc#get--api-v2-user-groups
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import {
Content,
Container,
Title,
Text,
Button,
Icon,
Header,
Right,
Left,
Thumbnail,
List,
ListItem,
Body
} from 'native-base';
import Menu, {
MenuContext,
MenuTrigger,
MenuOptions,
MenuOption,
renderers
} from 'react-native-popup-menu';
import {
View,
RefreshControl
} from 'react-native';
const PLColors = require('PLColors');
import styles from './styles';
import { openDrawer } from '../../../actions/drawer';
import { getGroups } from 'PLActions';
class GroupList extends Component{
constructor(props){
super(props);
this.state = {
groupList: [],
lock: false,
refreshing: false
};
}
componentWillMount(){
this._onRefresh();
}
//Simple listing of user's CURRENT groups. Only shows groups the user is joined to
loadGroups(){
this.state.groupList = [];
var { token } = this.props;
getGroups(token).then(data => {
var groups = data.payload;
groups.map((item, index) => {
if(item.official_name && item.joined && item.group_type_label == 'common'){
var letter = item.official_name.toUpperCase()[0];
var i = this.check(letter);
if(i == -1){
this.state.groupList[this.state.groupList.length] = {
letter: letter,
groups: [item]
};
}else{
this.state.groupList[i].groups.push(item);
}
}
if(index == groups.length - 1){
console.log(this.state.groupList);
this.state.groupList.sort(function(a, b){
return a.letter < b.letter ? -1: (a.letter == b.letter ? 0: 1 );
});
this.setState({
groupList: this.state.groupList,
refreshing: false
});
}
});
})
.catch(err => {
console.log(err);
});
}
check(letter){
for(var i = 0; i < this.state.groupList.length; i++){
if(letter == this.state.groupList[i].letter){
return i;
}
}
return -1;
}
//Shortcut to go to Search for a group that user is presumably not already linked to
goToSearch(){
Actions.groupsearch();
}
//Gives user ability view the Group Profile for the selected group
goToProfile(group){
Actions.groupprofile(group);
}
_onRefresh(){
this.setState({
refreshing: true
});
this.loadGroups();
}
render(){
return (
<MenuContext customStyles={menuContextStyles}>
<Container>
<Header style={styles.header}>
<Left>
<Button transparent onPress={this.props.openDrawer}>
<Icon active name="menu" style={{color: 'white'}}/>
</Button>
</Left>
<Body>
<Title>My Groups</Title>
</Body>
<Right>
{/*We need to make it easier for user to tap this button. Larger tappable area needed*/}
<Button transparent onPress={() => this.goToSearch()}>
<Icon active name="add-circle" style={{color: 'white'}}/>
</Button>
</Right>
</Header>
<Content padder
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh.bind(this)}
/>
}
>
<List style={{backgroundColor: 'white', marginLeft: 17, marginTop: 17}}>
{
this.state.groupList.map((itemGroups, index1) => {
return (
<View key={index1}>
<ListItem itemHeader style={styles.itemHeaderStyle}>
<Text style={styles.itemHeaderText}>{itemGroups.letter}</Text>
</ListItem>
{
itemGroups.groups.map((item, index2) => {
return (
<ListItem style={styles.listItem} key={index2} onPress={() => this.goToProfile(item)}>
{item.avatar_file_path?
<Thumbnail square source={{uri: item.avatar_file_path+'&w=50&h=50&auto=compress,format,q=95'}}/>:
<View style={{width: 56, height: 56}}/>
}
<Body>
<Text style={styles.text1}>{item.official_name}</Text>
</Body>
</ListItem>
)
})
}
</View>
);
})
}
</List>
</Content>
</Container>
</MenuContext>
)
}
}
const menuContextStyles = {
menuContextWrapper: styles.container,
backdrop: styles.backdrop,
};
const mapStateToProps = state => ({
token: state.user.token,
page: state.activities.page,
totalItems: state.activities.totalItems,
payload: state.activities.payload,
count: state.activities.count,
});
const mapDispatchToProps = dispatch => ({
openDrawer: ()=> dispatch(openDrawer())
});
export default connect(mapStateToProps, mapDispatchToProps)(GroupList); |
client/components/Landing/Landing.js | ncrmro/reango | import React from 'react'
import Page from 'components/Page/Page'
import Link from 'react-router-dom/es/Link'
import Button from 'react-mdc-web/lib/Button/Button'
const Landing = () =>
<Page heading='Landing' >
<p>This is the landing page</p>
<Link to='/polls' ><Button>Polls</Button></Link>
</Page>
export default Landing
|
admin/client/components/Forms/InvalidFieldType.js | suryagh/keystone | import React from 'react';
module.exports = React.createClass({
displayName: 'InvalidFieldType',
propTypes: {
path: React.PropTypes.string,
type: React.PropTypes.string,
},
render () {
return <div className="alert alert-danger">Invalid field type <strong>{this.props.type}</strong> at path <strong>{this.props.path}</strong></div>;
},
});
|
app/javascript/mastodon/features/notifications/components/column_settings.js | Ryanaka/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { FormattedMessage } from 'react-intl';
import ClearColumnButton from './clear_column_button';
import GrantPermissionButton from './grant_permission_button';
import SettingToggle from './setting_toggle';
import { isStaff } from 'mastodon/initial_state';
export default class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
pushSettings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
onRequestNotificationPermission: PropTypes.func,
alertsEnabled: PropTypes.bool,
browserSupport: PropTypes.bool,
browserPermission: PropTypes.bool,
};
onPushChange = (path, checked) => {
this.props.onChange(['push', ...path], checked);
}
render () {
const { settings, pushSettings, onChange, onClear, alertsEnabled, browserSupport, browserPermission, onRequestNotificationPermission } = this.props;
const unreadMarkersShowStr = <FormattedMessage id='notifications.column_settings.unread_notifications.highlight' defaultMessage='Highlight unread notifications' />;
const filterBarShowStr = <FormattedMessage id='notifications.column_settings.filter_bar.show_bar' defaultMessage='Show filter bar' />;
const filterAdvancedStr = <FormattedMessage id='notifications.column_settings.filter_bar.advanced' defaultMessage='Display all categories' />;
const alertStr = <FormattedMessage id='notifications.column_settings.alert' defaultMessage='Desktop notifications' />;
const showStr = <FormattedMessage id='notifications.column_settings.show' defaultMessage='Show in column' />;
const soundStr = <FormattedMessage id='notifications.column_settings.sound' defaultMessage='Play sound' />;
const showPushSettings = pushSettings.get('browserSupport') && pushSettings.get('isSubscribed');
const pushStr = showPushSettings && <FormattedMessage id='notifications.column_settings.push' defaultMessage='Push notifications' />;
return (
<div>
{alertsEnabled && browserSupport && browserPermission === 'denied' && (
<div className='column-settings__row column-settings__row--with-margin'>
<span className='warning-hint'><FormattedMessage id='notifications.permission_denied' defaultMessage='Desktop notifications are unavailable due to previously denied browser permissions request' /></span>
</div>
)}
{alertsEnabled && browserSupport && browserPermission === 'default' && (
<div className='column-settings__row column-settings__row--with-margin'>
<span className='warning-hint'>
<FormattedMessage id='notifications.permission_required' defaultMessage='Desktop notifications are unavailable because the required permission has not been granted.' /> <GrantPermissionButton onClick={onRequestNotificationPermission} />
</span>
</div>
)}
<div className='column-settings__row'>
<ClearColumnButton onClick={onClear} />
</div>
<div role='group' aria-labelledby='notifications-unread-markers'>
<span id='notifications-unread-markers' className='column-settings__section'>
<FormattedMessage id='notifications.column_settings.unread_notifications.category' defaultMessage='Unread notifications' />
</span>
<div className='column-settings__row'>
<SettingToggle id='unread-notification-markers' prefix='notifications' settings={settings} settingPath={['showUnread']} onChange={onChange} label={unreadMarkersShowStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-filter-bar'>
<span id='notifications-filter-bar' className='column-settings__section'>
<FormattedMessage id='notifications.column_settings.filter_bar.category' defaultMessage='Quick filter bar' />
</span>
<div className='column-settings__row'>
<SettingToggle id='show-filter-bar' prefix='notifications' settings={settings} settingPath={['quickFilter', 'show']} onChange={onChange} label={filterBarShowStr} />
<SettingToggle id='show-filter-bar' prefix='notifications' settings={settings} settingPath={['quickFilter', 'advanced']} onChange={onChange} label={filterAdvancedStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-follow'>
<span id='notifications-follow' className='column-settings__section'><FormattedMessage id='notifications.column_settings.follow' defaultMessage='New followers:' /></span>
<div className='column-settings__row'>
<SettingToggle disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'follow']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'follow']} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'follow']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'follow']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-follow-request'>
<span id='notifications-follow-request' className='column-settings__section'><FormattedMessage id='notifications.column_settings.follow_request' defaultMessage='New follow requests:' /></span>
<div className='column-settings__row'>
<SettingToggle disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'follow_request']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'follow_request']} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'follow_request']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'follow_request']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-favourite'>
<span id='notifications-favourite' className='column-settings__section'><FormattedMessage id='notifications.column_settings.favourite' defaultMessage='Favourites:' /></span>
<div className='column-settings__row'>
<SettingToggle disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'favourite']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'favourite']} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'favourite']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'favourite']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-mention'>
<span id='notifications-mention' className='column-settings__section'><FormattedMessage id='notifications.column_settings.mention' defaultMessage='Mentions:' /></span>
<div className='column-settings__row'>
<SettingToggle disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'mention']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'mention']} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'mention']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'mention']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-reblog'>
<span id='notifications-reblog' className='column-settings__section'><FormattedMessage id='notifications.column_settings.reblog' defaultMessage='Boosts:' /></span>
<div className='column-settings__row'>
<SettingToggle disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'reblog']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'reblog']} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'reblog']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-poll'>
<span id='notifications-poll' className='column-settings__section'><FormattedMessage id='notifications.column_settings.poll' defaultMessage='Poll results:' /></span>
<div className='column-settings__row'>
<SettingToggle disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'poll']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'poll']} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'poll']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'poll']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-status'>
<span id='notifications-status' className='column-settings__section'><FormattedMessage id='notifications.column_settings.status' defaultMessage='New toots:' /></span>
<div className='column-settings__row'>
<SettingToggle disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'status']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'status']} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'status']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'status']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-update'>
<span id='notifications-update' className='column-settings__section'><FormattedMessage id='notifications.column_settings.update' defaultMessage='Edits:' /></span>
<div className='column-settings__row'>
<SettingToggle disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'update']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'update']} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'update']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'update']} onChange={onChange} label={soundStr} />
</div>
</div>
{isStaff && (
<div role='group' aria-labelledby='notifications-admin-sign-up'>
<span id='notifications-status' className='column-settings__section'><FormattedMessage id='notifications.column_settings.admin.sign_up' defaultMessage='New sign-ups:' /></span>
<div className='column-settings__row'>
<SettingToggle disabled={browserPermission === 'denied'} prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'admin.sign_up']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'admin.sign_up']} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'admin.sign_up']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'admin.sign_up']} onChange={onChange} label={soundStr} />
</div>
</div>
)}
</div>
);
}
}
|
src/routes.js | Kronenberg/WebLabsTutorials | import React from 'react';
import {IndexRoute, Route} from 'react-router';
import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth';
import {
App,
Chat,
Home,
Widgets,
About,
Login,
LoginSuccess,
Survey,
NotFound,
Pagination,
} from 'containers';
export default (store) => {
const requireLogin = (nextState, replace, cb) => {
function checkAuth() {
const { auth: { user }} = store.getState();
if (!user) {
// oops, not logged in, so can't be here!
replace('/');
}
cb();
}
if (!isAuthLoaded(store.getState())) {
store.dispatch(loadAuth()).then(checkAuth);
} else {
checkAuth();
}
};
/**
* Please keep routes in alphabetical order
*/
return (
<Route path="/" component={App}>
{ /* Home (main) route */ }
<IndexRoute component={Home}/>
{ /* Routes requiring login */ }
<Route onEnter={requireLogin}>
<Route path="support" component={Chat}/>
<Route path="loginSuccess" component={LoginSuccess}/>
</Route>
{ /* Routes */ }
<Route path="about" component={About}/>
<Route path="login" component={Login}/>
<Route path="pagination" component={Pagination}/>
<Route path="survey" component={Survey}/>
<Route path="widgets" component={Widgets}/>
{ /* Catch all route */ }
<Route path="*" component={NotFound} status={404} />
</Route>
);
};
|
src/components/Navbar/Navbar.js | hawaiilife/hawaiilife-react-starter-kit | /*
* React.js Starter Kit
* Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react'; // eslint-disable-line no-unused-vars
class Navbar {
render() {
return (
<div className="navbar-top" role="navigation">
<div className="container">
<a className="navbar-brand row" href="/">
<img src={require('./logo-small.png')} alt="React" />
</a>
</div>
</div>
);
}
}
export default Navbar;
|
app/react-icons/fa/tablet.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaTablet extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m21.3 31.4q0-0.5-0.4-1t-1-0.4-1 0.4-0.5 1 0.5 1 1 0.5 1-0.5 0.4-1z m8.6-3.5v-21.5q0-0.3-0.3-0.5t-0.5-0.2h-18.5q-0.3 0-0.5 0.2t-0.2 0.5v21.5q0 0.2 0.2 0.5t0.5 0.2h18.5q0.3 0 0.5-0.2t0.3-0.5z m2.8-21.5v24.3q0 1.5-1 2.5t-2.6 1.1h-18.5q-1.5 0-2.6-1.1t-1-2.5v-24.3q0-1.4 1.1-2.5t2.5-1h18.5q1.5 0 2.6 1t1 2.5z"/></g>
</IconBase>
);
}
}
|
packages/ringcentral-widgets-docs/src/app/pages/Components/ContactList/Demo.js | u9520107/ringcentral-js-widget | import React from 'react';
// eslint-disable-next-line
import ContactList from 'ringcentral-widgets/components/ContactList';
const props = {};
props.currentLocale = 'en-US';
props.contactGroups = [{
id: 'K',
caption: 'K',
contacts: [{
id: '123',
name: 'Kevin One',
extensionNumber: '1234',
type: 'company',
profileImageUrl: null,
}, {
id: '1234',
name: 'Kevin Two',
extensionNumber: '12345',
type: 'company',
profileImageUrl: null,
}],
}, {
id: 'T',
caption: 'T',
contacts: [{
id: '1233',
name: 'Tyler One',
extensionNumber: '1233',
type: 'company',
profileImageUrl: null,
}],
}];
props.getAvatarUrl = async () => null;
props.getPresence = async () => null;
props.width = 300;
props.height = 500;
/**
* A example of `ContactList`
*/
const ContactListDemo = () => (
<ContactList
{...props}
/>
);
export default ContactListDemo;
|
src/components/Sidebar/index.js | luigiplr/Ulterius | import React from 'react';
import _ from 'lodash';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import {
History
}
from 'react-router';
export
default React.createClass({
mixins: [PureRenderMixin, History],
getInitialState() {
return {
active: '/',
tabs: [{
name: 'Dashboard',
path: '/'
}, {
name: 'Network',
path: '/network'
}, {
name: 'Incidents',
path: '/incidents'
}]
};
},
markActive(tab, event) {
this.setState({
active: tab
});
_.defer(this.history.replaceState.bind(this, null, tab));
},
render() {
return (
<aside className="sidebar">
<ul>
<h1>Main</h1>
{
this.state.tabs.map((tab, idx) => {
return (
<li key={idx} onClick={this.markActive.bind(this, tab.path)} className={(this.state.active === tab.path) ? 'active' : ''}>
{tab.name}
</li>
);
}, this)
}
</ul>
</aside>
);
}
}); |
app/containers/CreateGamePage.js | cdiezmoran/playgrounds-desktop | // @flow
import React, { Component } from 'react';
import { push } from 'react-router-redux';
import { connect } from 'react-redux';
import type { Dispatch } from '../actions/types';
// import actions
import { addGameRequest, fetchEditGameIfNeeded, editGameRequest } from '../actions/game';
import { requestSignatureCall } from '../actions/upload';
// import components
import GameForm from '../components/Game/GameForm';
type Props = {
isUploading: boolean,
isFetching: boolean,
macURL: ?string,
winURL: ?string,
macName: ?string,
winName: ?string,
game: ?Object,
location: Object,
dispatch: Dispatch
};
/**
* CreateGamePage container
* Displays the game form to add or edit games
*/
class CreateGamePage extends Component {
handleAddGame: (game: Object) => void;
handleEditGame: (game: Object, id: string) => void;
handleRouteChange: (path: string) => void;
getSignedRequest: (file: Object, isWin: boolean) => void;
constructor(props: Props) {
super(props);
this.handleAddGame = this.handleAddGame.bind(this);
this.handleEditGame = this.handleEditGame.bind(this);
this.handleRouteChange = this.handleRouteChange.bind(this);
this.getSignedRequest = this.getSignedRequest.bind(this);
}
componentWillMount() {
const { dispatch, location } = this.props;
const search = location.search;
const params = new URLSearchParams(search);
const id = params.get('id');
console.log(id);
if (id) {
dispatch(fetchEditGameIfNeeded(id));
}
}
/**
* Dispatches the addGameRequest action
* @param {Object} game - New game object
*/
handleAddGame(game) {
this.props.dispatch(addGameRequest(game));
}
/**
* Dispatches the editGameRequest action
* @param {Object} game - Edited game object
* @param {string} id - Id of the game to edit
*/
handleEditGame(game, id) {
this.props.dispatch(editGameRequest(game, id));
}
/**
* Dispatches requestSignatureCall to get signed object for direct s3 upload
* @param {Object} file - File object to be signed
* @param {boolean} isWin - Target platform for file
*/
getSignedRequest(file, isWin) {
this.props.dispatch(requestSignatureCall(file, isWin));
}
/**
* Is used by child component to change route
* @param {string} path - Path to go to
*/
handleRouteChange(path) {
this.props.dispatch(push(path));
}
render() {
const {
isUploading, macURL, winURL, macName, winName, location, game, isFetching
} = this.props;
const search = location.search;
const params = new URLSearchParams(search);
const id = params.get('id');
const isEditing = id !== null;
return (
<div className="container more-pad">
<div className="create-header">
<h1>Create Game</h1>
<div className="full-divider" />
</div>
<div className="game-form">
{!isEditing &&
<GameForm
addGame={this.handleAddGame} winName={winName} macName={macName}
changeRoute={this.handleRouteChange} getSignedRequest={this.getSignedRequest}
isUploading={isUploading} macURL={macURL} winURL={winURL} isEditing
/>
}
{isEditing && !isFetching &&
<GameForm
editGame={this.handleEditGame} getSignedRequest={this.getSignedRequest}
changeRoute={this.handleRouteChange} winURL={winURL} macName={macName}
isUploading={isUploading} macURL={macURL} isEditing game={game}
winName={winName}
/>
}
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
isUploading: state.upload.isUploading,
macURL: state.upload.macURL,
winURL: state.upload.winURL,
macName: state.upload.macName,
winName: state.upload.winName,
game: state.game.editGame,
isFetching: state.game.isFetching,
location: state.router.location
};
}
export default connect(mapStateToProps)(CreateGamePage);
|
docs/app/Examples/elements/Label/Types/LabelExampleCorner.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Grid, Image } from 'semantic-ui-react'
const LabelExampleCorner = () => (
<Grid columns={2}>
<Grid.Column>
<Image
fluid
label={{ as: 'a', corner: 'left', icon: 'heart' }}
src='http://semantic-ui.com/images/wireframe/image.png'
/>
</Grid.Column>
<Grid.Column>
<Image
fluid
label={{ as: 'a', color: 'red', corner: 'right', icon: 'save' }}
src='http://semantic-ui.com/images/wireframe/image.png'
/>
</Grid.Column>
</Grid>
)
export default LabelExampleCorner
|
test/helpers/shallowRenderHelper.js | yeWangye/gallery-by-react | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
src-web/js/view/Editor.js | kwangkim/pigment | import React from 'react';
import Radium from 'radium';
import * as MaterialUI from 'material-ui';
import { getChildren, reactJoin } from './util';
let { Styles: { Colors } } = MaterialUI;
let theme = MaterialUI.Styles.ThemeManager().getCurrentTheme();
const headerStyle = {
//borderLeft: '4px solid gray',
borderBottom: '2px dashed #aaa',
padding: '0 0 10px',
};
const blockStyle = color => ({
borderLeft: `4px solid ${color}`,
borderTop: `1px solid ${Colors.grey200}`,
borderBottom: `1px solid ${Colors.grey200}`,
margin: '10px 0',
padding: '10px 0 10px 10px',
});
let styles = {
refLayout: {
display: 'flex',
flexDirection: 'row',
},
devLayout: {
marginTop: 10,
display: 'flex',
flexDirection: 'column',
// ...blockStyle(Colors.deepPurple200),
},
parameterLayout: {
marginTop: 10,
// ...blockStyle(Colors.orange500)
},
moduleLayout: {...blockStyle(Colors.cyan500)},
entryEntityLayout: {...blockStyle(Colors.red200)},
definitionLayout: {...blockStyle(Colors.amber500)},
purposeLet: {
color: Colors.indigo900
},
purposeProg: {
color: Colors.indigo900, display: 'flex'
},
entriesLayout: {
marginTop: 10,
},
entriesLayoutHeader: {
fontWeight: 400,
},
entryHeaderLayout: {...headerStyle},
moduleHeaderLayout: {...headerStyle},
nameExplainLayout: {},
suspendedStyle: { color: Colors.blue900 },
unstableStyle: { color: Colors.deepOrange500 },
stableStyle: { color: Colors.green700 },
dInTmRN: {
backgroundColor: Colors.blue100,
margin: '0 2px',
padding: '0 4px'
},
name: {
display: 'flex',
backgroundColor: Colors.orange100,
margin: '0 2px',
padding: '0 4px'
},
scheme: {
backgroundColor: Colors.teal100,
display: 'flex',
flexDirection: 'row',
padding: 4,
border: '4px solid white'
},
pair: {
display: 'inline-flex',
flexDirection: 'row',
borderStyle: 'solid',
borderColor: Colors.teal100,
borderWidth: '1px 1px 1px 4px',
margin: '2px',
alignItems: 'center',
},
err: { backgroundColor: Colors.orange700 },
};
@Radium
export class RefLayout extends React.Component {
render () {
const [name, ty] = getChildren(this.props.children);
return <div style={styles.refLayout}>
defining {name} as {ty}
</div>;
}
}
@Radium
export class ParameterLayout extends React.Component {
render () {
const [ tag ] = getChildren(this.props.children);
return <div style={styles.parameterLayout}>
(this definition is a {this.getParamDescription(tag)})
</div>;
}
getParamDescription(tag) {
switch (tag) {
case 'ParamLam':
return 'lambda';
case 'ParamAll':
return 'for all';
case 'ParamPi':
return 'pi';
}
}
}
const bracketedBorder = '1px solid #bbb';
class Bracketed extends React.Component {
render() {
return (
<div style={{borderLeft: bracketedBorder, display: 'flex', flexDirection: 'column'}}>
<div style={{display: 'flex', flexDirection: 'row'}}>
<div style={{width: 20, height: '50%', borderTop: bracketedBorder, borderLeft: bracketedBorder}} />
<div>{this.props.title}</div>
</div>
<div>
{this.props.children}
</div>
<div style={{width: 20, height: '50%', borderBottom: bracketedBorder, borderLeft: bracketedBorder}} />
</div>
);
}
}
@Radium
export class DefinitionLayout extends React.Component {
render () {
const [ dev, kindTag, kindInfo ] = getChildren(this.props.children);
return dev;
// return (
// <div style={styles.definitionLayout}>
// <PurposeLayout purpose={kindTag} info={kindInfo} />
// {dev}
// </div>
// );
}
}
@Radium
export class EntryModuleLayout extends React.Component {
render () {
const [header, dev] = getChildren(this.props.children);
return <div style={styles.entryModuleLayout}>
{header}
{dev}
</div>;
}
}
@Radium
export class DevLayout extends React.Component {
render () {
const [suspendState, entries] = getChildren(this.props.children);
return <div style={styles.devLayout}>
{this.showSuspend(suspendState)}
{entries}
</div>;
}
showSuspend(str) {
switch(str) {
case 'SuspendNone':
return (
<div style={styles.suspendedStyle}>
Not Suspended
</div>
);
case 'SuspendUnstable':
return (
<div style={styles.unstableStyle}>
Unstable
</div>
);
case 'SuspendStable':
return (
<div style={styles.stableStyle}>
Stable
</div>
);
}
}
}
@Radium
export class EntriesLayout extends React.Component {
render () {
const entries = getChildren(this.props.children);
return <div style={styles.entriesLayout}>
<div style={styles.entriesLayoutHeader}>ENTRIES</div>
{entries}
</div>;
}
}
@Radium
export class EntryHeaderLayout extends React.Component {
render () {
const [ref, metadata, ty] = getChildren(this.props.children);
return <div style={styles.entryHeaderLayout}>
{ref}
</div>;
}
}
@Radium
export class ModuleHeaderLayout extends React.Component {
render () {
const [name, purpose, metadata] = getChildren(this.props.children);
return <div style={styles.moduleHeaderLayout}>
{name}
<PurposeLayout purpose={purpose} />
</div>;
}
}
@Radium
export class PurposeLayout extends React.Component {
render() {
switch(this.props.purpose) {
case "LETG":
return (
<div style={styles.purposeLet}>
defining
</div>
);
case "PROGERR":
return (
<div style={styles.err}>
ERROR distilling scheme
</div>
);
case "PROG":
return (
<div style={styles.purposeProg}>
programming scheme {this.props.info}
</div>
);
}
}
}
@Radium
export class NameExplainLayout extends React.Component {
render () {
const [name, purpose, metadata] = getChildren(this.props.children);
return <div style={styles.nameExplainLayout}>
{name}
{purpose}
{metadata}
</div>;
}
}
@Radium
export class NameLayout extends React.Component {
render () {
const pieces = getChildren(this.props.children);
return <div style={styles.name}>
{reactJoin(pieces, ".")}
</div>;
}
}
@Radium
export class NamePieceLayout extends React.Component {
render () {
const { str, n } = this.props;
const sub = n === '0' ? "" : <sub style={{verticalAlign: 'sub'}}>{n}</sub>;
return <div style={{}}>
{str}
{sub}
</div>;
}
}
@Radium
export class EntryEntityLayout extends React.Component {
render () {
const [header, entity] = getChildren(this.props.children);
return <div style={styles.entryEntityLayout}>
{header}
{entity}
</div>;
}
}
const flexRow = {
display: 'flex',
flexDirection: 'row'
};
const sigmaTags = {
dunit: () => "*",
bind: ([s, x, t]) => (
<div style={flexRow}>
( {s} , \ {x} -> {t} )
</div>
),
const: ([s, t]) => (
<div style={flexRow}>
({s}, {t})
</div>
),
other: ([s, t]) => (
<div style={flexRow}>
Other({s}, {t})
</div>
),
}
@Radium
export class SigmaLayout extends React.Component {
render() {
return (
<div style={{}}>
{sigmaTags[this.props.tag](this.props.children)}
</div>
);
}
}
@Radium
export class SchemeLayout extends React.Component {
render() {
return (
<div style={styles.scheme}>
{this.props.tag}
{this.props.children}
</div>
);
}
}
@Radium
export class PairLayout extends React.Component {
render() {
return (
<div style={styles.pair}>
⟨{reactJoin(getChildren(this.props.children), ",")}⟩
</div>
);
}
}
@Radium
export class DHeadLayout extends React.Component {
render() {
return (
<div style={{}}>
{this.props.children}
</div>
);
}
}
DHeadLayout.tags = {
// param:
// annotation:
// embedding:
};
@Radium
export class CanLayout extends React.Component {
render() {
return (
<div style={{}}>
{this.selectTag(this.props.tag, getChildren(this.props.children))}
</div>
);
}
selectTag(tagName, children) {
return this.constructor.tags[tagName](children);
}
}
CanLayout.tags = {
set: () => "SET",
pi: p => p,
con: tm => <div>Con({tm})</div>,
// desc
mujust: tm => <div>Mu({tm})</div>,
munothing: tm => <div>Mu({tm})</div>,
// idesc
imujust: (tm, i) => <div>IMu({tm}, {i})</div>,
imunothing: (ii, d, i) => <div>Mu({ii}, {d}, {i})</div>,
// enum
enumt: tm => tm,
ze: () => "ze",
su: tm => tm,
// definitional equality
// TODO - hover / click behavior to describe what this means
eqblue: (pp, qq) => (
<div>
{pp} = {qq}
</div>
),
// free monad
monad: (d, x) => <div>monad({d}, {x})</div>,
"return": tm => <div>return {tm}</div>,
composite: tm => <div>composite {tm}</div>,
// labelled types
label: ([l, t]) => <div style={{display: 'flex', flexDirection: 'row'}}>{l} := {t}</div>,
lret: tm => <div>lret {tm}</div>,
// nu
nujust: tm => <div>nujust({tm})</div>,
nunothing: tm => <div>nunothing({tm})</div>,
coit: (d, sty, f, s) => <div>coit({d}, {sty}, {f}, {s})</div>,
// TODO prop, etc
sigma: s => s,
pair: p => p,
unit: () => "1",
void: () => "0",
};
@Radium
export class PiLayout extends React.Component {
render() {
// const [ s, t ] = getChildren(this.props.children);
const childs = reactJoin(getChildren(this.props.children), "->")
return (
<div style={{display: 'flex'}}>
{childs}
</div>
);
}
}
@Radium
export class JustPiLayout extends React.Component {
render() {
const [ s, t ] = getChildren(this.props.children);
return (
<div style={{display: 'flex'}}>
Pi({s}, {t})
</div>
);
}
}
@Radium
export class DependentParamLayout extends React.Component {
render() {
const { name } = this.props;
const [ s ] = getChildren(this.props.children);
return (
<div style={{display: 'flex'}}>
{name} : {s}
</div>
);
}
}
@Radium
export class DScopeLayout extends React.Component {
render() {
const bindings = getChildren(this.props.children);
return (
<div style={{display: 'flex'}}>
{reactJoin(bindings, ". ")}.
</div>
);
}
}
@Radium
export class DInTmRNLayout extends React.Component {
render() {
return (
<div className="dintmrn" style={{}}>
{this.props.children}
</div>
);
}
}
DInTmRNLayout.tags = {
// neutral
// dn:
// canonical
// dc:
// lambda
// dl:
};
@Radium
export class DExTmRNLayout extends React.Component {
render() {
return (
<div style={{}}>
{this.props.children}
</div>
);
}
}
@Radium
export class DSpineLayout extends React.Component {
render() {
return (
<div style={{}}>
{this.props.children}
</div>
);
}
}
@Radium
export class RelNameLayout extends React.Component {
render() {
return (
<div style={{}}>
{this.props.children}
</div>
);
}
}
@Radium
export class RelNamePieceLayout extends React.Component {
render() {
const { str, tag, n } = this.props;
return (
<div style={{}}>
{str}{this.constructor.tags[tag](n)}
</div>
);
}
}
RelNamePieceLayout.tags = {
rel: n => {
if (n === '0') {
return "";
} else {
return <sup style={{verticalAlign: 'super'}}>{n}</sup>;
}
},
abs: n => {
if (n === '0') {
return "";
} else {
return <sub style={{verticalAlign: 'sub'}}>{n}</sub>;
}
}
}
|
app/javascript/mastodon/features/standalone/hashtag_timeline/index.js | masto-donte-com-br/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { expandHashtagTimeline } from 'mastodon/actions/timelines';
import Masonry from 'react-masonry-infinite';
import { List as ImmutableList } from 'immutable';
import DetailedStatusContainer from 'mastodon/features/status/containers/detailed_status_container';
import { debounce } from 'lodash';
import LoadingIndicator from 'mastodon/components/loading_indicator';
const mapStateToProps = (state, { hashtag }) => ({
statusIds: state.getIn(['timelines', `hashtag:${hashtag}`, 'items'], ImmutableList()),
isLoading: state.getIn(['timelines', `hashtag:${hashtag}`, 'isLoading'], false),
hasMore: state.getIn(['timelines', `hashtag:${hashtag}`, 'hasMore'], false),
});
export default @connect(mapStateToProps)
class HashtagTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
isLoading: PropTypes.bool.isRequired,
hasMore: PropTypes.bool.isRequired,
hashtag: PropTypes.string.isRequired,
local: PropTypes.bool.isRequired,
};
static defaultProps = {
local: false,
};
componentDidMount () {
const { dispatch, hashtag, local } = this.props;
dispatch(expandHashtagTimeline(hashtag, { local }));
}
handleLoadMore = () => {
const { dispatch, hashtag, local, statusIds } = this.props;
const maxId = statusIds.last();
if (maxId) {
dispatch(expandHashtagTimeline(hashtag, { maxId, local }));
}
}
setRef = c => {
this.masonry = c;
}
handleHeightChange = debounce(() => {
if (!this.masonry) {
return;
}
this.masonry.forcePack();
}, 50)
render () {
const { statusIds, hasMore, isLoading } = this.props;
const sizes = [
{ columns: 1, gutter: 0 },
{ mq: '415px', columns: 1, gutter: 10 },
{ mq: '640px', columns: 2, gutter: 10 },
{ mq: '960px', columns: 3, gutter: 10 },
{ mq: '1255px', columns: 3, gutter: 10 },
];
const loader = (isLoading && statusIds.isEmpty()) ? <LoadingIndicator key={0} /> : undefined;
return (
<Masonry ref={this.setRef} className='statuses-grid' hasMore={hasMore} loadMore={this.handleLoadMore} sizes={sizes} loader={loader}>
{statusIds.map(statusId => (
<div className='statuses-grid__item' key={statusId}>
<DetailedStatusContainer
id={statusId}
compact
measureHeight
onHeightChange={this.handleHeightChange}
/>
</div>
)).toArray()}
</Masonry>
);
}
}
|
js/components/content/content.js | Krelix/krelix.github.io | /**
* Created by Adrien on 11/04/2016.
*/
import React from 'react';
export default class Content extends React.Component {
render() {
//TODO : set content to be rendered
return (
<main>
{this.props.children}
</main>
);
}
} |
packages/material-ui-icons/src/Undo.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Undo = props =>
<SvgIcon {...props}>
<path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z" />
</SvgIcon>;
Undo = pure(Undo);
Undo.muiName = 'SvgIcon';
export default Undo;
|
UI/Buttons/ButtonStopWatch.js | Datasilk/Dedicate | import React from 'react';
import { View, TouchableOpacity} from 'react-native';
import {G, Path} from 'react-native-svg';
import SvgIcon from 'ui/SvgIcon';
import AppStyles from 'dedicate/AppStyles';
export default class ButtonStopWatch extends React.Component {
constructor(props){
super(props);
}
render() {
const color = this.props.color || AppStyles.color;
return (
<View style={this.props.style}>
<TouchableOpacity onPress={this.props.onPress}>
<SvgIcon {...this.props}>
<G>
<Path d="m41 3v-3h-18v3h7v6.05q-9.9602 0.66465-17.15 7.9-7.85 7.9-7.85 19.05 0 11.25 7.85 19.1 7.9 7.9 19.15 7.9 11.2 0 19.1-7.9 7.9-7.85 7.9-19.1 0-11.15-7.9-19.05-7.185-7.2305-17.1-7.9v-6.05h7m7.3 16.8q6.7 6.7 6.7 16.2 0 9.6-6.7 16.3-6.75 6.7-16.3 6.7t-16.3-6.7q-6.7-6.7-6.7-16.3 0-9.5 6.7-16.2 6.15-6.2 14.6-6.7 0.85-0.1 1.7-0.1t1.7 0.1q8.45 0.5 14.6 6.7m-13.3 16.2q0-1.25-0.85-2.1-0.8-0.85-1.9-0.9-0.1 0-0.25 0-0.1 0-0.2 0-1.1 0.05-1.9 0.9-0.9 0.85-0.9 2.1t0.9 2.1q0.9 0.9 2.1 0.9 1.25 0 2.15-0.9 0.85-0.85 0.85-2.1z" fill={color}/>
<Path d="m49.15 46.3l0.95-1.8-12.3-6.6-0.95 1.75 12.3 6.65m-18.15-16.3h2v-10h-2v10z" fill={color}/>
</G>
</SvgIcon>
</TouchableOpacity>
</View>
);
}
} |
renderer/containers/UI/CryptoValue.js | LN-Zap/zap-desktop | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import Span from 'components/UI/Span'
import Value from 'components/UI/Value'
import { tickerSelectors } from 'reducers/ticker'
const mapStateToProps = state => ({
currency: tickerSelectors.cryptoUnit(state),
})
const ConnectedValue = connect(mapStateToProps)(Value)
const CryptoValue = ({ value, ...rest }) => {
return (
<Span {...rest}>
<ConnectedValue value={value} />
</Span>
)
}
CryptoValue.propTypes = {
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default CryptoValue
|
app/containers/HomePage/index.js | KarandikarMihir/react-boilerplate | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*/
import React from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import Helmet from 'react-helmet';
import messages from './messages';
import { createStructuredSelector } from 'reselect';
import {
selectRepos,
selectLoading,
selectError,
} from 'containers/App/selectors';
import {
selectUsername,
} from './selectors';
import { changeUsername } from './actions';
import { loadRepos } from '../App/actions';
import { FormattedMessage } from 'react-intl';
import RepoListItem from 'containers/RepoListItem';
import Button from 'components/Button';
import H2 from 'components/H2';
import List from 'components/List';
import ListItem from 'components/ListItem';
import LoadingIndicator from 'components/LoadingIndicator';
import styles from './styles.css';
export class HomePage extends React.Component {
/**
* when initial state username is not null, submit the form to load repos
*/
componentDidMount() {
if (this.props.username && this.props.username.trim().length > 0) {
this.props.onSubmitForm();
}
}
/**
* Changes the route
*
* @param {string} route The route we want to go to
*/
openRoute = (route) => {
this.props.changeRoute(route);
};
/**
* Changed route to '/features'
*/
openFeaturesPage = () => {
this.openRoute('/features');
};
render() {
let mainContent = null;
// Show a loading indicator when we're loading
if (this.props.loading) {
mainContent = (<List component={LoadingIndicator} />);
// Show an error if there is one
} else if (this.props.error !== false) {
const ErrorComponent = () => (
<ListItem item={'Something went wrong, please try again!'} />
);
mainContent = (<List component={ErrorComponent} />);
// If we're not loading, don't have an error and there are repos, show the repos
} else if (this.props.repos !== false) {
mainContent = (<List items={this.props.repos} component={RepoListItem} />);
}
return (
<article>
<Helmet
title="Home Page"
meta={[
{ name: 'description', content: 'A React.js Boilerplate application homepage' },
]}
/>
<div>
<section className={`${styles.textSection} ${styles.centered}`}>
<H2>
<FormattedMessage {...messages.startProjectHeader} />
</H2>
<p>
<FormattedMessage {...messages.startProjectMessage} />
</p>
</section>
<section className={styles.textSection}>
<H2>
<FormattedMessage {...messages.trymeHeader} />
</H2>
<form className={styles.usernameForm} onSubmit={this.props.onSubmitForm}>
<label htmlFor="username">
<FormattedMessage {...messages.trymeMessage} />
<span className={styles.atPrefix}>
<FormattedMessage {...messages.trymeAtPrefix} />
</span>
<input
id="username"
className={styles.input}
type="text"
placeholder="mxstbr"
value={this.props.username}
onChange={this.props.onChangeUsername}
/>
</label>
</form>
{mainContent}
</section>
<Button handleRoute={this.openFeaturesPage}>
<FormattedMessage {...messages.featuresButton} />
</Button>
</div>
</article>
);
}
}
HomePage.propTypes = {
changeRoute: React.PropTypes.func,
loading: React.PropTypes.bool,
error: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.bool,
]),
repos: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.bool,
]),
onSubmitForm: React.PropTypes.func,
username: React.PropTypes.string,
onChangeUsername: React.PropTypes.func,
};
export function mapDispatchToProps(dispatch) {
return {
onChangeUsername: (evt) => dispatch(changeUsername(evt.target.value)),
changeRoute: (url) => dispatch(push(url)),
onSubmitForm: (evt) => {
if (evt !== undefined && evt.preventDefault) evt.preventDefault();
dispatch(loadRepos());
},
dispatch,
};
}
const mapStateToProps = createStructuredSelector({
repos: selectRepos(),
username: selectUsername(),
loading: selectLoading(),
error: selectError(),
});
// Wrap the component to inject dispatch and state into it
export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
|
app/components/Chat/index.js | GuiaLa/guiala-web-app | /**
*
* Chat
*
*/
import React from 'react';
import styles from './styles.css';
function Chat() {
return (
<div className={ styles.chat }>
<h1>Chat chat chat, chat line!</h1>
</div>
);
}
export default Chat;
|
react/private/withTextProps.js | seek-oss/seek-style-guide | import React from 'react';
import PropTypes from 'prop-types';
import omit from 'lodash/omit';
import has from 'lodash/has';
import some from 'lodash/some';
import includes from 'lodash/includes';
import forEach from 'lodash/forEach';
export const sizes = [
'small',
'standard',
'large',
'subheading',
'heading',
'headline',
'hero'
];
const getBooleanSizePropTypes = () => {
const booleanProps = {};
forEach(sizes, size => {
booleanProps[size] = PropTypes.bool;
});
return booleanProps;
};
export const SizePropTypes = {
// eslint-disable-next-line consistent-return
size: (props, propName, componentName) => {
if (props.size && !includes(sizes, props.size)) {
return new Error(
`Invalid prop size='${props.size}' supplied to ${componentName}`
);
}
if (props.size && some(sizes, size => has(props, size))) {
return new Error(
`Seems that you've accidentially supplied boolean size along with size='${props.size}' to ${componentName}, please remove one of them. Otherwise boolean prop will overwrite the 'size' prop.`
);
}
},
...getBooleanSizePropTypes()
};
const parseBooleanSize = props => {
const sizeProps = {};
forEach(sizes, size => {
if (props[size]) {
sizeProps.size = size;
}
});
return sizeProps;
};
const withTextProps = OriginalComponent => {
const DecoratedComponent = props => {
const sizeProp = parseBooleanSize(props);
const newProps = {
...omit(props, sizes),
...sizeProp
};
return <OriginalComponent {...newProps} />;
};
DecoratedComponent.propTypes = SizePropTypes;
DecoratedComponent.displayName = OriginalComponent.displayName;
return DecoratedComponent;
};
export default withTextProps;
|
webapp/pages/infra_fails_page.js | dropbox/changes | import React from 'react';
import ChangesLinks from 'es6!display/changes/links';
import SectionHeader from 'es6!display/section_header';
import { ChangesPage, APINotLoadedPage } from 'es6!display/page_chrome';
import { Grid } from 'es6!display/grid';
import { SingleBuildStatus } from 'es6!display/changes/builds';
import { TimeText } from 'es6!display/time';
import * as api from 'es6!server/api';
import * as utils from 'es6!utils/utils';
/**
* Page with information on recent infrastructural failures.
*/
var InfraFailsPage = React.createClass({
getInitialState: function() {
return {
infraFailJobs: null,
}
},
componentDidMount: function() {
api.fetch(this, {
infraFailJobs: `/api/0/admin_dash/infra_fail_jobs/`
})
},
render: function() {
if (!api.allLoaded([this.state.infraFailJobs])) {
return <APINotLoadedPage
calls={[this.state.infraFailJobs]}
/>;
}
utils.setPageTitle(`Infra fails`);
var cellClasses = ['buildWidgetCell', 'nowrap', 'nowrap', 'wide easyClick', 'nowrap', 'nowrap'];
var headers = [ 'Build', 'Project', 'Name', 'Message', 'Target', 'Started'];
var data = this.state.infraFailJobs.getReturnedData();
var grid_data = _.map(data['recent'], d => {
return [
<SingleBuildStatus build={d.build} parentElem={this} />,
<div>{d.project.name}</div>,
<div>{d.name}</div>,
<a className="subtle" href={ChangesLinks.buildHref(d.build)}>
{d.build.name}
</a>,
ChangesLinks.phab(d.build),
<TimeText time={d.dateStarted} />];
})
return <ChangesPage>
<SectionHeader>Recent Infra fails</SectionHeader>
<div className="marginBottomM marginTopM paddingTopS">
Jobs with infrastructural failures in the last 24 hours.
</div>
<Grid
colnum={headers.length}
data={grid_data}
cellClasses={cellClasses}
headers={headers}
/>
</ChangesPage>;
}
});
export default InfraFailsPage;
|
server/sonar-web/src/main/js/apps/background-tasks/components/Header.js | lbndev/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info 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.
*/
/* @flow */
import React from 'react';
import { translate } from '../../../helpers/l10n';
const Header = () => {
return (
<header className="page-header">
<h1 className="page-title">
{translate('background_tasks.page')}
</h1>
<p className="page-description">
{translate('background_tasks.page.description')}
</p>
</header>
);
};
export default Header;
|
app/javascript/mastodon/components/missing_indicator.js | blackle/mastodon | import React from 'react';
import { FormattedMessage } from 'react-intl';
const MissingIndicator = () => (
<div className='regeneration-indicator missing-indicator'>
<div>
<div className='regeneration-indicator__figure' />
<div className='regeneration-indicator__label'>
<FormattedMessage id='missing_indicator.label' tagName='strong' defaultMessage='Not found' />
<FormattedMessage id='missing_indicator.sublabel' defaultMessage='This resource could not be found' />
</div>
</div>
</div>
);
export default MissingIndicator;
|
docs/app/Examples/collections/Form/FieldVariations/FormExampleInlineField.js | vageeshb/Semantic-UI-React | import React from 'react'
import { Form, Input } from 'semantic-ui-react'
const FormExampleInlineField = () => (
<Form>
<Form.Field inline>
<label>First name</label>
<Input placeholder='First name' />
</Form.Field>
</Form>
)
export default FormExampleInlineField
|
app/containers/ProcessViewPage/components/Burner/index.js | BrewPi/brewpi-ui | import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../../actions';
const classNames = require('classnames');
import styles from './styles.css';
import { SvgParent } from '../SvgParent';
const SvgBurner = require('./svg/burner.svg?tag=g');
const SvgFlame = require('./svg/flame.svg?tag=g');
const SvgFlameInner = require('./svg/flame_inner.svg?tag=g');
class Burner extends React.Component {
render() {
const power = this.props.settings.power;
const intensity = this.props.settings.intensity;
const flameScale = 1.0 - Math.pow(0.05, (intensity / 100.0));
const flameStyle = (intensity) ? { transform: `scaleY(${flameScale})` } : {};
let flames;
if (power) {
flames = (
<g className={styles.flameContainer} style={flameStyle} >
<SvgFlame className={styles.flame} style={flameStyle} />;
<SvgFlameInner className={styles.flameInner} style={flameStyle} />;
</g>
);
}
return (
<button className={styles.Burner} onClick={() => this.props.onClicked(this.props.id, this.props.settings.power)}>
<SvgParent viewBox={'0 0 100 50'}>
{flames}
<SvgBurner className={styles.burner} />
</SvgParent>
</button>
);
}
}
Burner.propTypes = {
settings: React.PropTypes.shape({
power: React.PropTypes.boolean,
intensity: React.PropTypes.number, // 0-100
}),
id: React.PropTypes.string,
onClicked: React.PropTypes.func,
};
Burner.defaultProps = {
settings: {
power: false,
intensity: 100,
},
};
function mapDispatchToProps(dispatch) {
return bindActionCreators({
onClicked: (id, oldPower) => dispatch(actions.powerTogglableClicked(id, oldPower)),
}, dispatch);
}
export default connect(null, mapDispatchToProps)(Burner);
|
app/javascript/mastodon/features/ui/components/columns_area.js | nonoz/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ReactSwipeableViews from 'react-swipeable-views';
import { links, getIndex, getLink } from './tabs_bar';
import BundleContainer from '../containers/bundle_container';
import ColumnLoading from './column_loading';
import BundleColumnError from './bundle_column_error';
import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, FavouritedStatuses } from '../../ui/util/async-components';
import { scrollRight } from '../../../scroll';
const componentMap = {
'COMPOSE': Compose,
'HOME': HomeTimeline,
'NOTIFICATIONS': Notifications,
'PUBLIC': PublicTimeline,
'COMMUNITY': CommunityTimeline,
'HASHTAG': HashtagTimeline,
'FAVOURITES': FavouritedStatuses,
};
@injectIntl
export default class ColumnsArea extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
intl: PropTypes.object.isRequired,
columns: ImmutablePropTypes.list.isRequired,
singleColumn: PropTypes.bool,
children: PropTypes.node,
};
state = {
shouldAnimate: false,
}
componentWillReceiveProps() {
this.setState({ shouldAnimate: false });
}
componentDidMount() {
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.setState({ shouldAnimate: true });
}
componentDidUpdate(prevProps) {
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.setState({ shouldAnimate: true });
if (this.props.children !== prevProps.children && !this.props.singleColumn) {
scrollRight(this.node);
}
}
handleSwipe = (index) => {
this.pendingIndex = index;
const nextLinkTranslationId = links[index].props['data-preview-title-id'];
const currentLinkSelector = '.tabs-bar__link.active';
const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`;
// HACK: Remove the active class from the current link and set it to the next one
// React-router does this for us, but too late, feeling laggy.
document.querySelector(currentLinkSelector).classList.remove('active');
document.querySelector(nextLinkSelector).classList.add('active');
}
handleAnimationEnd = () => {
if (typeof this.pendingIndex === 'number') {
this.context.router.history.push(getLink(this.pendingIndex));
this.pendingIndex = null;
}
}
setRef = (node) => {
this.node = node;
}
renderView = (link, index) => {
const columnIndex = getIndex(this.context.router.history.location.pathname);
const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] });
const icon = link.props['data-preview-icon'];
const view = (index === columnIndex) ?
React.cloneElement(this.props.children) :
<ColumnLoading title={title} icon={icon} />;
return (
<div className='columns-area' key={index}>
{view}
</div>
);
}
renderLoading = () => {
return <ColumnLoading />;
}
renderError = (props) => {
return <BundleColumnError {...props} />;
}
render () {
const { columns, children, singleColumn } = this.props;
const { shouldAnimate } = this.state;
const columnIndex = getIndex(this.context.router.history.location.pathname);
this.pendingIndex = null;
if (singleColumn) {
return columnIndex !== -1 ? (
<ReactSwipeableViews index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}>
{links.map(this.renderView)}
</ReactSwipeableViews>
) : <div className='columns-area'>{children}</div>;
}
return (
<div className='columns-area' ref={this.setRef}>
{columns.map(column => {
const params = column.get('params', null) === null ? null : column.get('params').toJS();
return (
<BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading} error={this.renderError}>
{SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn />}
</BundleContainer>
);
})}
{React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))}
</div>
);
}
}
|
src/index.js | ShevaDas/exhibitor-management | import React from 'react';
import { render } from 'react-dom';
import { ConnectedRouter as Router } from 'react-router-redux';
import { Switch, Route, Redirect } from 'react-router-dom';
import { Provider } from 'react-redux';
import store, { history } from './store';
import registerServiceWorker from './registerServiceWorker';
import App from './components/App';
import LoginContainer from './containers/LoginContainer';
import HomeContainer from './containers/HomeContainer';
import Portal from './components/Portal/Portal';
import Contact from './components/Contact/Contact';
import PrivateRoute from './containers/PrivateRoute';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
const sampleGenerator = (name) => {
return () => (
<h1>{name}</h1>
);
};
const Protected = sampleGenerator('Protected');
const router = (
<Provider store={store}>
<Router history={history}>
<App>
<Switch>
<PrivateRoute exact path="/" component={HomeContainer} />
<Route exact path="/login" component={LoginContainer} />
<Route exact path="/contact" component={Contact} />
<Route exact path="/portal" component={Portal} />
<PrivateRoute exact path="/protected" component={Protected} />
</Switch>
</App>
</Router>
</Provider>
);
render(router, document.getElementById('root'));
registerServiceWorker();
|
quizzical/app/Quizzical.js | CSergienko/quizzical | /** @module quizzical */
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, Link, useRouterHistory, browserHistory } from 'react-router';
import { createHistory, useBasename } from 'history';
import App from './components/App';
import QuestionList from './components/QuestionList';
import PageNotFound from './components/PageNotFound';
import configureStore from './redux/store';
import { Provider } from 'react-redux';
import { syncHistoryWithStore } from 'react-router-redux';
require('./Quizzical.scss');
/* eslint-disable */
let initialState = {
categories: [{
id: 0,
category_text: 'categroy A'
}],
questions: [{
id: 0,
question_text: 'Sample question'
}]
}
/* eslint-enable */
let store = configureStore(initialState);
// Ridiculously complex method just to set a base url. (API subject to change)
// const browserHistory = useRouterHistory(useBasename(createHistory))({
// //basename: '/troubleshooter'
// });
function add1(x){
return x + 1;
}
function add2(x){
x = x + 3;
return x + 2;
}
const history = syncHistoryWithStore(browserHistory, store)
const routes =
<Route path='/' component={App}>
<Route path="questions/:id/" component={QuestionList}/>
<Route path="*" component={PageNotFound} />
</Route>;
render(
<Provider store={store}>
<Router history={history}>
{routes}
</Router>
</Provider>,
document.getElementById('quizzical-app')
);
|
examples/immutable/components/submit-button.js | nikitka/react-redux-form | import React from 'react';
import { connect } from 'react-redux';
import Immutable from 'immutable';
const SubmitButton = ({ user }) => // user is an Immutable Map
<button type="submit">
Finish registration, {user.get('firstName')} {user.get('lastName')}!
</button>;
SubmitButton.propTypes = {
user: React.PropTypes.instanceOf(Immutable.Map).isRequired,
};
const mapStateToProps = (state) => {
// Enable one of the two:
return { user: state.user }; // Enable when using redux
// return { user: state.get('user') }; // Enable when using redux-immutable
};
export default connect(mapStateToProps)(SubmitButton);
|
threeforce/node_modules/react-bootstrap/es/MediaBody.js | wolfiex/VisACC | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType
};
var defaultProps = {
componentClass: 'div'
};
var MediaBody = function (_React$Component) {
_inherits(MediaBody, _React$Component);
function MediaBody() {
_classCallCheck(this, MediaBody);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
MediaBody.prototype.render = function render() {
var _props = this.props;
var Component = _props.componentClass;
var className = _props.className;
var props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props);
var bsProps = _splitBsProps[0];
var elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return MediaBody;
}(React.Component);
MediaBody.propTypes = propTypes;
MediaBody.defaultProps = defaultProps;
export default bsClass('media-body', MediaBody); |
src/containers/guide/level6.js | wunderg/PTC | import React from 'react';
import Highlight from '../../helpers/highlight.js';
import { objectProps, objectPropsExample, objectPropsSolution, eachModified, reduceModified } from './code/objectProps.js';
import { indexOf, indexOfExample, indexOfSolution, eachModifiedIndex, reduceModifiedIndex } from './code/indexOf.js';
export default () => (
<div className="card deep-purple lighten-5">
<div className="card-content">
<h3>Level 6 - ObjectProps and IndexOf using Reduce</h3>
<hr />
<ul className="lesson-list">
<li>
<div className="card">
<div className="card-content">
<h4><b>Lesson 1 - ObjectProps using Reduce</b></h4>
<hr />
<div className="">
<h5><b>Objectives:</b></h5>
<ul className="prompts">
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Teach student how to edit each and reduce to give additional functionality to current function</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Teach how to pass arguments down the chain by passing them into the callback</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Teach how to extract those arguments in the following functions</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Refer to reduce implementation</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Help student to create example</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Help student to walk thru every iteration - STEP by STEP</span></li>
</ul>
</div>
<div className="">
<h5><b>Technical:</b></h5>
</div>
<ul className="prompts">
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Create function objectProps</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> ObjectProps should accept collection</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> ObjectProps should use reduce and empty array as a startingValue</span></li>
</ul>
</div>
<div className="code">
<h5><b>Boilerplate:</b></h5>
<Highlight props={objectProps} />
</div>
<div className="code">
<h5><b>Example:</b></h5>
<Highlight props={objectPropsExample} />
</div>
<div className="code">
<h5><b>Solution:</b></h5>
<Highlight props={objectPropsSolution} />
<Highlight props={eachModified} />
<Highlight props={reduceModified} />
</div>
</div>
</li>
<li>
<div className="card">
<div className="card-content">
<h4><b>Lesson 2 - IndexOf using Reduce</b></h4>
<hr />
<div className="">
<h5><b>Objectives:</b></h5>
<ul className="prompts">
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Teach student how to edit each and reduce to give additional functionality</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Teach how to pass arguments down the line by passing them into the callback</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Teach how to extract those arguments in the following functions</span></li>
</ul>
</div>
<div className="">
<h5><b>Technical:</b></h5>
</div>
<ul className="prompts">
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Create function indexOf</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> IndexOf should accept collection and target</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> IndexOf should use reduce and no startingValue</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Explain that KEY in reduce would represent both KEY for object and INDEX for array</span></li>
<li><i className="fa fa-check green-text text-lighten-2"></i><span> Make sure that Each can operate on strings by adding || - (OR)</span></li>
</ul>
</div>
<div className="code">
<h5><b>Boilerplate:</b></h5>
<Highlight props={indexOf} />
</div>
<div className="code">
<h5><b>Example:</b></h5>
<Highlight props={indexOfExample} />
</div>
<div className="code">
<h5><b>Solution:</b></h5>
<Highlight props={eachModifiedIndex} />
<Highlight props={reduceModifiedIndex} />
<Highlight props={indexOfSolution} />
</div>
</div>
</li>
</ul>
</div>
</div>
);
|
src/components/Metronome.js | pyreta/MIDInterceptor-Electron | import React from 'react';
const Metronome = props => {
const quarter = props.clicks % 16 === 0;
const eighth = props.clicks % 8 === 0;
const whole = props.clicks % 64 === 0;
let label = ''
if (whole) {
label = 'BEEP'
} else if (quarter) {
label = 'boop'
} else if (eighth) {
label = ''
}
return <div style={{fontSize: '40px', color: 'red'}}>{label}</div>
}
export default Metronome;
|
src/main.js | betterTry/Blog-rRichText | import React from 'react';
import ReactDOM from 'react-dom';
import AppComponent from './react/App.jsx';
ReactDOM.render(<AppComponent />, document.getElementById('app')); |
reflux-app/components/Peg.js | Orientsoft/conalog-front | import React from 'react'
import _ from 'lodash'
import $ from '../../public/js/jquery.min'
import constants from '../const'
import PegActions from '../actions/PegActions'
import PegStore from '../stores/PegStore'
import CodeEditor from './Peg/CodeEditor'
import InputEditor from './Peg/InputEditor'
import Settings from './Peg/Settings'
import AppActions from '../actions/AppActions'
import AppStore from '../stores/AppStore'
class Peg extends React.Component {
constructor(props) {
super(props)
this.state = {
grammar: '',
buildResult: {},
input: '',
parseResult: {},
output: {},
cache: false,
optimize: 'speed',
saveResult: {}
}
}
componentDidMount() {
this.unsubscribe = PegStore.listen(function(state) {
this.setState(state)
}.bind(this))
// get grammar by name
$.get(constants.CONALOG_URL, {name: name})
.done((data, status) => {
if (status === 'OK') {
let grammar = data.grammar
PegActions.setCache(data.cache)
PegActions.setOptimize(data.optimize)
PegActions.build(grammar)
}
})
.fail((err) => {
// nothing to do
})
.always(() => {
PegActions.build(this.state.grammar)
PegActions.parse(this.state.input)
})
}
componentWillUnmount() {
if (_.isFunction(this.unsubscribe))
this.unsubscribe()
}
render() {
let className
if (this.state.saveResult.status !== '') {
className = "collapse.in alert alert-dismissible alert-" +
this.state.saveResult.status
}
else {
className = "collapse"
}
return (
<div className="container p-t-60">
<div className="row p-t-10">
<div className="col-lg-12">
<div ref="banner" className={ className }>
{ this.state.saveResult.detail }
</div>
</div>
</div>
<div className="row p-t-10">
<div className="col-lg-6">
<CodeEditor
grammar={ this.state.grammar }
buildResult={ this.state.buildResult }
/>
</div>
<div className="col-lg-6">
<InputEditor
input={ this.state.input }
parseResult={ this.state.parseResult }
output={ this.state.output }
/>
<Settings
name={ this.props.name }
cache={ this.state.cache }
optimize={ this.state.optimize }
buildResult={ this.state.buildResult }
/>
</div>
</div>
</div>
)
}
}
Peg.propTypes = {
}
Peg.defaultProps = {
}
export default Peg
|
src/components/chart.js | jeffgietz/rr_weather | import _ from 'lodash';
import React from 'react';
import { Sparklines, SparklinesLine, SparklinesReferenceLine } from 'react-sparklines';
function average(data) {
return _.round(_.sum(data)/data.length);
}
export default (props) => {
return(
<div>
<Sparklines height={120} width={180} data={props.data}>
<SparklinesLine color={props.color} />
<SparklinesReferenceLine type="avg" />
</Sparklines>
<div>{average(props.data)} {props.units}</div>
</div>
)
}
|
components/auth/Logout.js | rabbotio/nap | import { gql, graphql } from 'react-apollo'
import persist from '../../lib/persist'
import React from 'react'
import userProfile from '../userProfile.gql'
import PropTypes from 'prop-types'
const Logout = ({ logout }) => {
return (
<button onClick={logout}>LogOut (GraphQL)</button>
)
}
const logout = gql`
mutation logout {
logout {
isLoggedIn
loggedOutAt
}
errors {
code
message
}
}
`
Logout.propTypes = () => ({
logout: PropTypes.func.isRequired
})
export default graphql(logout, {
props: ({ mutate }) => ({
logout: () => mutate({
update: (proxy, { data }) => {
// Clear session
persist.willRemoveSessionToken()
// Read the data from our cache for this query.
let cached = proxy.readQuery({ query: userProfile })
// Errors
cached.errors = data.errors
// User
cached.user = data.logout.user ? data.logout.user : { _id: null, name: null, status: null, __typename: 'User' }
// Authen
cached.authen = {
isLoggedIn: data.logout.isLoggedIn,
sessionToken: data.logout.sessionToken,
__typename: 'Authen'
}
// Write our data back to the cache.
proxy.writeQuery({ query: userProfile, data: cached })
}
})
})
})(Logout)
|
src/Table/Row/Row.js | ctco/rosemary-ui | import React from 'react';
import PropTypes from 'prop-types';
const PROPERTY_TYPES = {
item: PropTypes.any,
rowProps: PropTypes.any
};
const DEFAULT_PROPS = {};
class Row extends React.Component {
constructor(props) {
super(props);
}
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.className !== this.props.className) {
return true;
}
return nextProps.item !== this.props.item;
}
render() {
return (
<tr
className={this.props.className}
onClick={e => this.props.onClick && this.props.onClick(e)}
{...this.props.rowProps}
>
{this.props.children}
</tr>
);
}
}
Row.propTypes = PROPERTY_TYPES;
Row.defaultProps = DEFAULT_PROPS;
export default Row;
|
js/common/TextSeparator.js | BarberHour/barber-hour | import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
} from 'react-native';
const TextSeparator = (props) => {
return(
<View style={[styles.container, props.style]}>
<View style={styles.separator} />
<Text style={styles.text}> OU </Text>
<View style={styles.separator} />
</View>
);
};
export default TextSeparator;
var styles = StyleSheet.create({
text: {
fontWeight: 'bold'
},
container: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
separator: {
height: 1,
backgroundColor: '#DCDCDC',
flex: 1,
}
});
|
src/components/post_show.js | pleaobraga/blog-react | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPost, deletePost } from '../actions';
class PostShow extends Component {
componentDidMount() {
const { id } = this.props.match.params;
this.props.fetchPost(id);
}
onDeleteClick() {
const { id } = this.props.match.params;
this.props.deletePost(id, () => {
this.props.history.push('/');
});
}
render() {
const { post } = this.props;
if (!post) {
return <div>Loading...</div>;
}
return (
<div>
<Link to="/" className="btn btn-primary" >Back To Index</Link>
<button
className="btn btn-danger pull-xs-right"
onClick={this.onDeleteClick.bind(this)}
>
Delete Post
</button>
<h3>{post.title}</h3>
<h6>Categories: {post.categories}</h6>
<p>{post.content}</p>
</div>
);
}
}
function mapStateToProps({ posts }, ownProps) {
return { post: posts[ownProps.match.params.id] };
}
export default connect(mapStateToProps, { fetchPost, deletePost })(PostShow); |
examples/todomvc/index.js | radnor/redux | import 'babel-core/polyfill';
import React from 'react';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
import 'todomvc-app-css/index.css';
const store = configureStore();
React.render(
<Provider store={store}>
{() => <App />}
</Provider>,
document.getElementById('root')
);
|
examples/only-client-render-external-dependencies/pages/index.js | BlancheXu/test | import React from 'react'
import Link from 'next/link'
import LineChart from '../components/LineChart'
const data = [
{ name: 'Page A', uv: 1000, pv: 2400, amt: 2400 },
{ name: 'Page B', uv: 3000, pv: 1398, amt: 2210 },
{ name: 'Page C', uv: 2000, pv: 9800, amt: 2290 },
{ name: 'Page D', uv: 2780, pv: 3908, amt: 2000 },
{ name: 'Page E', uv: 1890, pv: 4800, amt: 2181 },
{ name: 'Page F', uv: 2390, pv: 3800, amt: 2500 },
{ name: 'Page G', uv: 3490, pv: 4300, amt: 2100 }
]
const Index = () => (
<div>
<h1>Chart</h1>
<Link href='/chart'>
<a>Go to another chart</a>
</Link>
<LineChart width={400} height={400} data={data} />
</div>
)
export default Index
|
front/src/components/card/cardForm.js | tersfeld/DETER | import React from 'react';
import { Component } from 'react';
import {reduxForm} from 'redux-form';
import {addCard} from '../../actions/index';
class CardForm extends Component {
constructor(props) {
super(props);
}
onSubmit(props){
this.props.addCard(props)
.then(() => {
this.setRandomColor();
this.props.getCards();
});
}
render() {
const { fields:{name, color}, handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<div className="mdl-grid demo-content">
<div className="demo-cards mdl-cell mdl-cell--12-col mdl-cell--8-col-tablet mdl-typography--text-center">
<div className="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input className="mdl-textfield__input" type="text" {...name}/>
<label className="mdl-textfield__label">Got a new goal ?</label>
</div>
</div>
</div>
</form>
);
}
setRandomColor(){
const colorList = ['red', 'pink', 'purple', 'indigo', 'blue'];
const randomIndex = Math.floor((Math.random() * colorList.length));
this.props.fields.color.onChange(colorList[randomIndex]);
}
componentDidMount(){
this.setRandomColor();
}
componentDidUpdate() {
componentHandler.upgradeDom();
}
}
export default reduxForm(
{form: 'card',
fields: ['name', 'color']
}, null, {addCard})(CardForm);
|
src/packages/@ncigdc/components/Aggregations/ExactMatchFacet.js | NCI-GDC/portal-ui | // @flow
// Vendor
import React from 'react';
import { compose, withState, pure } from 'recompose';
import LocationSubscriber from '@ncigdc/components/LocationSubscriber';
// Custom
import { parseFilterParam } from '@ncigdc/utils/uri';
import { getFilterValue, makeFilter } from '@ncigdc/utils/filters';
import { Row, Column } from '@ncigdc/uikit/Flex';
import CheckCircleOIcon from '@ncigdc/theme/icons/CheckCircleOIcon';
import Input from '@ncigdc/uikit/Form/Input';
import { Tooltip } from '@ncigdc/uikit/Tooltip';
import Hidden from '../Hidden';
import {
CheckedLink,
CheckedRow,
Container,
GoLink,
} from '.';
const ExactMatchFacet = ({
collapsed,
doctype,
fieldNoDoctype,
inputValue,
placeholder,
setInputValue,
style,
title,
}) => {
return (
<LocationSubscriber>
{(ctx: { pathname: string, query: IRawQuery }) => {
const { filters } = ctx.query || {};
const currentFilters = parseFilterParam(filters, { content: [] })
.content;
const currentValues = getFilterValue({
currentFilters,
dotField: `${doctype}.${fieldNoDoctype}`,
}) || { content: { value: [] } };
return (
<Container className="test-exact-match-facet" style={style}>
{!collapsed && (
<Column>
{currentValues.content.value.map(v => (
<CheckedRow key={v}>
<Tooltip Component="Click to remove">
<CheckedLink
merge="toggle"
query={{
filters: makeFilter([
{
field: `${doctype}.${fieldNoDoctype}`,
value: [v],
},
]),
}}
>
<CheckCircleOIcon
style={{ paddingRight: '0.5rem' }}
/>
{v}
</CheckedLink>
</Tooltip>
</CheckedRow>
))}
<Row>
<label htmlFor={fieldNoDoctype}>
<Hidden>{title}</Hidden>
</label>
<Input
handleClear={() => {
setInputValue('');
}}
id={fieldNoDoctype}
name={fieldNoDoctype}
onChange={e => {
setInputValue(e.target.value);
}}
placeholder={placeholder}
style={{
borderRadius: '4px 0 0 4px',
}}
value={inputValue}
/>
<GoLink
dark={!!inputValue}
merge="toggle"
onClick={inputValue ? () => setInputValue('') : null}
query={inputValue && {
filters: makeFilter([
{
field: `${doctype}.${fieldNoDoctype}`,
value: [inputValue],
},
]),
}}
style={inputValue
? null
: {
color: '#6F6F6F',
cursor: 'not-allowed',
}}
>
Go!
</GoLink>
</Row>
</Column>
)}
</Container>
);
}}
</LocationSubscriber>
);
};
export default compose(
withState('inputValue', 'setInputValue', ''),
pure,
)(ExactMatchFacet);
|
app/containers/Permissions/UserList.js | klpdotorg/tada-frontend | import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { fetchUsers } from '../../actions';
import { UserListView } from '../../components/Permissions';
class GetUsers extends Component {
componentDidMount() {
this.props.fetchUsers();
}
render() {
return <UserListView {...this.props} />;
}
}
GetUsers.propTypes = {
fetchUsers: PropTypes.func,
};
const mapStateToProps = (state) => {
const { users, loading } = state.users;
const { selectedUsers } = state.permissions;
return {
users: Object.values(users),
selectedUsers,
loading,
};
};
const UserList = connect(mapStateToProps, { fetchUsers })(GetUsers);
export { UserList };
|
docs/src/app/components/pages/components/FontIcon/Page.js | ichiohta/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import iconCode from '!raw!material-ui/FontIcon/FontIcon';
import iconReadmeText from './README';
import IconExampleSimple from './ExampleSimple';
import iconExampleSimpleCode from '!raw!./ExampleSimple';
import IconExampleIcons from './ExampleIcons';
import iconExampleIconsCode from '!raw!./ExampleIcons';
const descriptions = {
custom: 'This example uses a custom font (not part of Material-UI). The `className` defines the specific ' +
'icon. The third example has a `hoverColor` defined.',
public: 'This example uses the [Material icons font]' +
'(http://google.github.io/material-design-icons/#icon-font-for-the-web), referenced in the `<head>` of the docs ' +
'site index page. The `className` defines the font, and the `IconFont` tag content defines the specific icon.',
};
const FontIconPage = () => (
<div>
<Title render={(previousTitle) => `Font Icon - ${previousTitle}`} />
<MarkdownElement text={iconReadmeText} />
<CodeExample
title="Custom icon font"
description={descriptions.custom}
code={iconExampleSimpleCode}
>
<IconExampleSimple />
</CodeExample>
<CodeExample
title="Public icon font"
description={descriptions.public}
code={iconExampleIconsCode}
>
<IconExampleIcons />
</CodeExample>
<PropTypeDescription code={iconCode} />
</div>
);
export default FontIconPage;
|
client/components/admin/layout/nav.js | maodouio/meteor-react-redux-base | import React from 'react';
import {Link} from 'react-router';
export default (props) => (
<div>
<div className="color-line">
</div>
<div id="logo" className="light-version">
<span>
{props.appName}
</span>
</div>
<nav role="navigation">
<Link to="#" className="header-link hide-menu" onClick={(e) => props.sidebar(e)}><i className="fa fa-bars" /></Link>
<div className="small-logo">
<span className="text-primary">{props.appName}</span>
</div>
<div className="mobile-menu">
<button type="button" className="navbar-toggle mobile-menu-toggle" data-toggle="collapse" data-target="#mobile-collapse">
<i className="fa fa-chevron-down" />
</button>
<div className="collapse mobile-navbar" id="mobile-collapse">
<ul className="nav navbar-nav">
<li>
<Link to="/" className="" onClick={(e) => Meteor.logout()}>退出</Link>
</li>
<li>
<Link className="" to="/">回到主页</Link>
</li>
</ul>
</div>
</div>
<div className="navbar-right">
<Link to="/" className="btn btn-info" style={{margin: '10px 20px'}}>回到主页<i className="pe-7s-upload pe-rotate-90" /></Link>
</div>
</nav>
</div>
);
|
docs/src/app/components/pages/components/Menu/ExampleIcons.js | ichiohta/material-ui | import React from 'react';
import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import RemoveRedEye from 'material-ui/svg-icons/image/remove-red-eye';
import PersonAdd from 'material-ui/svg-icons/social/person-add';
import ContentLink from 'material-ui/svg-icons/content/link';
import Divider from 'material-ui/Divider';
import ContentCopy from 'material-ui/svg-icons/content/content-copy';
import Download from 'material-ui/svg-icons/file/file-download';
import Delete from 'material-ui/svg-icons/action/delete';
import FontIcon from 'material-ui/FontIcon';
const style = {
paper: {
display: 'inline-block',
float: 'left',
margin: '16px 32px 16px 0',
},
rightIcon: {
textAlign: 'center',
lineHeight: '24px',
},
};
const MenuExampleIcons = () => (
<div>
<Paper style={style.paper}>
<Menu>
<MenuItem primaryText="Preview" leftIcon={<RemoveRedEye />} />
<MenuItem primaryText="Share" leftIcon={<PersonAdd />} />
<MenuItem primaryText="Get links" leftIcon={<ContentLink />} />
<Divider />
<MenuItem primaryText="Make a copy" leftIcon={<ContentCopy />} />
<MenuItem primaryText="Download" leftIcon={<Download />} />
<Divider />
<MenuItem primaryText="Remove" leftIcon={<Delete />} />
</Menu>
</Paper>
<Paper style={style.paper}>
<Menu>
<MenuItem primaryText="Clear Config" />
<MenuItem primaryText="New Config" rightIcon={<PersonAdd />} />
<MenuItem primaryText="Project" rightIcon={<FontIcon className="material-icons">settings</FontIcon>} />
<MenuItem
primaryText="Workspace"
rightIcon={
<FontIcon className="material-icons" style={{color: '#559'}}>settings</FontIcon>
}
/>
<MenuItem primaryText="Paragraph" rightIcon={<b style={style.rightIcon}>¶</b>} />
<MenuItem primaryText="Section" rightIcon={<b style={style.rightIcon}>§</b>} />
</Menu>
</Paper>
</div>
);
export default MenuExampleIcons;
|
app/containers/DevTools.js | dearfrankg/soundio | import React from 'react'
import {createDevTools} from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
export default createDevTools(
<DockMonitor
toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'
defaultIsVisible={false}>
<LogMonitor theme='tomorrow' />
</DockMonitor>
)
|
src/index.js | abobwhite/slate-editor | import React from 'react'
import ReactDOM from 'react-dom'
import ExampleApp from './example'
ReactDOM.render(
<ExampleApp />,
document.getElementById('root')
)
|
public/app/components/online-tab/index.js | vincent-tr/mylife-home-studio | 'use strict';
import React from 'react';
import * as mui from 'material-ui';
import * as bs from 'react-bootstrap';
import TreeContainer from '../../containers/online-tab/tree-container';
import DetailsContainer from '../../containers/online-tab/details-container';
import tabStyles from '../base/tab-styles';
class OnlineTab extends React.Component {
constructor(props) {
super(props);
this.state = { selectedNode: null };
}
changeValue(value) {
this.setState({ selectedNode: value });
}
render() {
return (
<bs.Grid fluid={true} style={Object.assign({}, tabStyles.fullHeight)}>
<bs.Row style={tabStyles.fullHeight}>
<bs.Col sm={3} style={Object.assign({}, tabStyles.noPadding, tabStyles.fullHeight)}>
<mui.Paper style={Object.assign({}, tabStyles.scrollable, tabStyles.fullHeight)}>
<TreeContainer
selectedNode={this.state.selectedNode}
selectedValueChanged={this.changeValue.bind(this)} />
</mui.Paper>
</bs.Col>
<bs.Col sm={9} style={Object.assign({}, tabStyles.noPadding, tabStyles.scrollable, tabStyles.fullHeight)}>
<DetailsContainer
value={this.state.selectedNode}
onChangeValue={this.changeValue.bind(this)} />
</bs.Col>
</bs.Row>
</bs.Grid>
);
}
}
export default OnlineTab;
|
src/routes/register/Register.js | Ozaroni/modestLifer | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Register.css';
class Register extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>{this.props.title}</h1>
<p>...</p>
</div>
</div>
);
}
}
export default withStyles(s)(Register);
|
app/js/components/Header.js | alex-xia/react-rocket-demo | 'use strict';
import React from 'react';
class Header extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<header>
Header
</header>
);
}
}
export default Header; |
src/components/LeftNavComponent.js | fredelf/dashboard | import React from 'react'
import { connect } from 'react-redux'
import { logout } from 'actions/auth'
import firebase from 'firebase'
import {FaThLarge, FaRocket, FaCog, FaGroup, FaSignOut} from 'react-icons/lib/fa'
import { browserHistory, Link } from 'react-router'
class LeftNavComponent extends React.Component {
constructor(props){
super(props)
this.state = {
loggedInUser: '',
profilePicUrl: ''
}
}
componentDidMount(){
firebase.database().ref('users/' + this.props.auth.uid).on('value', function(snapshot) {
var { firstname, lastname, profilePicUrl } = snapshot.val()
this.setState({
loggedInUser: firstname + " " + lastname,
profilePicUrl
})
}.bind(this))
}
onClick(){
const { dispatch } = this.props
dispatch(logout())
firebase.auth().signOut()
browserHistory.push("auth/login")
}
render(){
return(
<nav className="navbar-default navbar-static-side" role="navigation">
<div className="sidebar-collapse">
<ui className="nav metismenu" id="side-menu">
<li className="nav-header">
<div className="dropdown profile-element">
<span><img alt="image" className="img-circle img-circle-nav" src={this.state.profilePicUrl}></img></span>
<Link to={`/universe/veiledere/${this.props.auth.uid}`} className="dropdown-toggle">
<span className="clear"> <span className="block m-t-xs"> <strong className="font-bold">{this.state.loggedInUser}</strong>
</span> <span className="text-muted text-xs block">Min Profil</span> </span> </Link>
</div>
</li>
<li className={(this.props.nav.currentView === 'dashboard' ? "active": "")}>
<Link to="/universe/dashboard"><FaThLarge /> <span className="nav-label">Dashboard</span></Link>
</li>
<li className={(this.props.nav.currentView === 'startups' ? "active": "")}>
<Link to="/universe/startups"><FaRocket /> <span className="nav-label">Startups</span> </Link>
</li>
<li className={(this.props.nav.currentView === 'veiledere' ? "active": "")}>
<Link to="/universe/veiledere"><FaGroup /> <span className="nav-label">Sparkere</span> </Link>
</li>
<li className={(this.props.nav.currentView === 'admin' ? "active": "")}>
<Link to="/universe/admin"><FaCog /> <span className="nav-label">Admin</span> </Link>
</li>
<li style={{paddingTop: "40px"}}>
<a onClick={this.onClick.bind(this)}>
<FaSignOut /> Log out
</a>
</li>
</ui>
</div>
</nav>
)
}
}
export default connect((state) => ({
auth: state.auth,
nav: state.nav,
users: state.users
}))(LeftNavComponent)
|
client/src/javascript/components/modals/settings-modal/ResourcesTab.js | jfurrow/flood | import {Checkbox, Form, FormRow, Textbox} from 'flood-ui-kit';
import {FormattedMessage} from 'react-intl';
import React from 'react';
import ModalFormSectionHeader from '../ModalFormSectionHeader';
import SettingsTab from './SettingsTab';
export default class ResourcesTab extends SettingsTab {
state = {};
handleFormChange = ({event}) => {
this.handleClientSettingFieldChange(event.target.name, event);
};
render() {
return (
<Form onChange={this.handleFormChange}>
<ModalFormSectionHeader>
<FormattedMessage id="settings.resources.disk.heading" defaultMessage="Disk" />
</ModalFormSectionHeader>
<FormRow>
<Textbox
defaultValue={this.getFieldValue('directoryDefault')}
id="directoryDefault"
label={
<FormattedMessage
id="settings.resources.disk.download.location.label"
defaultMessage="Default Download Directory"
/>
}
/>
</FormRow>
<FormRow>
<Textbox
defaultValue={this.getFieldValue('networkMaxOpenFiles')}
id="networkMaxOpenFiles"
label={<FormattedMessage id="settings.resources.max.open.files" defaultMessage="Maximum Open Files" />}
width="one-half"
/>
<Checkbox
checked={this.getFieldValue('piecesHashOnCompletion') === '1'}
grow={false}
id="piecesHashOnCompletion"
labelOffset
matchTextboxHeight>
<FormattedMessage
id="settings.resources.disk.check.hash.label"
defaultMessage="Verify Hash on Completion"
/>
</Checkbox>
</FormRow>
<ModalFormSectionHeader>
<FormattedMessage id="settings.resources.memory.heading" defaultMessage="Memory" />
</ModalFormSectionHeader>
<FormRow>
<Textbox
defaultValue={this.getFieldValue('piecesMemoryMax')}
id="piecesMemoryMax"
label={
<div>
<FormattedMessage id="settings.resources.memory.max.label" defaultMessage="Max Memory Usage" />{' '}
<em className="unit">(MB)</em>
</div>
}
width="one-half"
/>
</FormRow>
</Form>
);
}
}
|
redux-client/src/app/redux/components/App.js | rahulharinkhede2013/enovos | import React from 'react';
import UserList from '../containers/user-list';
import UserDetails from '../containers/user-detail';
import DataTable from '../containers/dataTable';
import LoadData from '../containers/LoadData'
require('../../scss/style.scss');
import {bindActionCreators} from 'redux';
const App = () => (
<div>
<h2>User List</h2>
<UserList />
<hr />
<h2>User Details</h2>
<UserDetails />
<LoadData/>
<DataTable/>
</div>
);
export default App;
|
src/index.js | ksmithbaylor/simple-react-starter | import React from 'react';
import { render } from 'react-dom';
import App from './App';
render(<App />, document.getElementById('root'));
|
src/components/Loader/Loader.js | andrew-filonenko/habit-tracker | import React from 'react';
import bem from '../../utils/bem-helper';
import Icon from 'react-fa';
import cx from 'classnames';
export default function({ className: _className }) {
const { block, elem } = bem('b', 'loader');
const className = cx(block, _className);
return (
<div className={ className }>
<Icon className={ elem('icon') } spin size="5x" name="spinner" />
</div>
);
}
|
cerberus-dashboard/src/components/ConfirmationBox/ConfirmationBox.js | Nike-Inc/cerberus-management-service | /*
* Copyright (c) 2020 Nike, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react'
import { Component } from 'react'
import PropTypes from 'prop-types'
import './ConfirmationBox.scss'
export default class ConfirmationBox extends Component {
static propTypes = {
message: PropTypes.string.isRequired,
handleYes: PropTypes.func.isRequired,
handleNo: PropTypes.func.isRequired
}
render() {
const {message, handleYes, handleNo} = this.props
return (
<div className="confirmation-box-container ncss-brand">
<h2>Attention:</h2>
<h4 className="confirmation-box-message">{message}</h4>
<div className="confirmation-box-buttons">
<div className="confirmation-box-button ncss-btn-dark-grey u-uppercase" onClick={handleNo}>No</div>
<div className="confirmation-box-button ncss-btn-dark-grey u-uppercase" onClick={handleYes}>Yes</div>
</div>
</div>
)
}
} |
addon/tools/control-panel/main.js | 6a68/idea-town | /*
* This Source Code is subject to the terms of the Mozilla Public License
* version 2.0 (the 'License'). You can obtain a copy of the License at
* http://mozilla.org/MPL/2.0/.
*/
/* global CustomEvent */
import React, { Component } from 'react';
import { render } from 'react-dom';
import * as actions from '../../src/lib/actions';
import templates from './templates';
window.addEventListener('addon-action', event => {
// eslint-disable-next-line no-console
console.log('from addon', event.detail);
});
function send(action) {
document.documentElement.dispatchEvent(new CustomEvent('action', {
bubbles: true,
detail: action
}));
}
function createAction(type) {
const action = actions[type];
return action(createPayload(action.args));
}
function createPayload(args) {
const payload = {};
args.forEach(a => {
payload[a] = templates(a);
});
return payload;
}
class App extends Component {
constructor(props) {
super(props);
this.state = { action: '{}' };
}
render() {
return (
<form
onSubmit={e => {
e.preventDefault();
send(JSON.parse(this.state.action));
}}
>
<select
size="24"
onChange={e =>
this.setState({
action: JSON.stringify(createAction(e.target.value), null, 2)
})}
>
{Object
.keys(actions)
.map(type => <option key={type} value={type}>{type}</option>)}
</select>
<textarea
rows="24"
cols="60"
value={this.state.action}
onChange={e => this.setState({ action: e.target.value })}
/>
<input type="submit" value="send" />
</form>
);
}
}
render(<App />, document.getElementById('root'));
|
app/javascript/mastodon/features/follow_requests/index.js | Nyoho/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
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 Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import AccountAuthorizeContainer from './containers/account_authorize_container';
import { fetchFollowRequests, expandFollowRequests } from '../../actions/accounts';
import ScrollableList from '../../components/scrollable_list';
import { me } from '../../initial_state';
const messages = defineMessages({
heading: { id: 'column.follow_requests', defaultMessage: 'Follow requests' },
});
const mapStateToProps = state => ({
accountIds: state.getIn(['user_lists', 'follow_requests', 'items']),
isLoading: state.getIn(['user_lists', 'follow_requests', 'isLoading'], true),
hasMore: !!state.getIn(['user_lists', 'follow_requests', 'next']),
locked: !!state.getIn(['accounts', me, 'locked']),
domain: state.getIn(['meta', 'domain']),
});
export default @connect(mapStateToProps)
@injectIntl
class FollowRequests extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
accountIds: ImmutablePropTypes.list,
locked: PropTypes.bool,
domain: PropTypes.string,
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchFollowRequests());
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandFollowRequests());
}, 300, { leading: true });
render () {
const { intl, shouldUpdateScroll, accountIds, hasMore, multiColumn, locked, domain, isLoading } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.follow_requests' defaultMessage="You don't have any follow requests yet. When you receive one, it will show up here." />;
const unlockedPrependMessage = locked ? null : (
<div className='follow_requests-unlocked_explanation'>
<FormattedMessage
id='follow_requests.unlocked_explanation'
defaultMessage='Even though your account is not locked, the {domain} staff thought you might want to review follow requests from these accounts manually.'
values={{ domain: domain }}
/>
</div>
);
return (
<Column bindToDocument={!multiColumn} icon='user-plus' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollableList
scrollKey='follow_requests'
onLoadMore={this.handleLoadMore}
hasMore={hasMore}
isLoading={isLoading}
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
prepend={unlockedPrependMessage}
>
{accountIds.map(id =>
<AccountAuthorizeContainer key={id} id={id} />,
)}
</ScrollableList>
</Column>
);
}
}
|
modules/RoutingContext.js | neebz/react-router | import React from 'react'
import invariant from 'invariant'
import getRouteParams from './getRouteParams'
const { array, func, object } = React.PropTypes
/**
* A <RoutingContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
const RoutingContext = React.createClass({
propTypes: {
history: object.isRequired,
createElement: func.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired
},
getDefaultProps() {
return {
createElement: React.createElement
}
},
childContextTypes: {
history: object.isRequired,
location: object.isRequired
},
getChildContext() {
return {
history: this.props.history,
location: this.props.location
}
},
createElement(component, props) {
return component == null ? null : this.props.createElement(component, props)
},
render() {
const { history, location, routes, params, components } = this.props
let element = null
if (components) {
element = components.reduceRight((element, components, index) => {
if (components == null)
return element // Don't create new children use the grandchildren.
const route = routes[index]
const routeParams = getRouteParams(route, params)
const props = {
history,
location,
params,
route,
routeParams,
routes
}
if (element)
props.children = element
if (typeof components === 'object') {
const elements = {}
for (const key in components)
if (components.hasOwnProperty(key))
elements[key] = this.createElement(components[key], props)
return elements
}
return this.createElement(components, props)
}, element)
}
invariant(
element === null || element === false || React.isValidElement(element),
'The root route must render a single element'
)
return element
}
})
export default RoutingContext
|
client/src/components/shared/candidate.js | Siyanda-Mzam/hire-grad | import React, { Component } from 'react';
import SignIn from './sign-in';
// Authorization HOC
const Authorization = (WrappedComponent, allowedRoles) => {
alert("Yo")
return class WithAuthorization extends Component {
constructor(props) {
alert("Alert");
console.log(props);
super(props)
this.state = {
user: {
email: '[email protected]',
password: 'password',
role: 'employer'
}
}
}
verifyCredentials(providedCreds) {
const { role, email, password } = providedCreds;
return allowedRoles.includes(password) && allowedRoles.includes(email)
}
render() {
alert(JSON.stringify(this.state.user))
if (this.verifyCredentials(this.state.user)) {
alert("Correct");
return <WrappedComponent {...this.props} />
} else {
alert("Incorrect")
return <h1>You do not have a profile. Set it up</h1>
}
}
}
}
export default Authorization;
|
packages/showcase/data/mini-data-examples.js | uber/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import {XYPlot, LineSeries, MarkSeries, VerticalBarSeries} from 'react-vis';
const data = [
{x: 0, y: 8},
{x: 1, y: 5},
{x: 2, y: 4},
{x: 3, y: 9},
{x: 4, y: 1},
{x: 5, y: 7},
{x: 6, y: 6},
{x: 7, y: 3},
{x: 8, y: 2},
{x: 9, y: 0}
];
const defaultProps = {
width: 200,
height: 200,
margin: {top: 5, left: 5, right: 5, bottom: 5}
};
export function MiniCharts() {
return (
<div style={{display: 'flex'}}>
<XYPlot {...defaultProps}>
<VerticalBarSeries data={data} />
</XYPlot>
<XYPlot {...defaultProps}>
<LineSeries data={data} />
</XYPlot>
<XYPlot {...defaultProps}>
<MarkSeries data={data} />
</XYPlot>
</div>
);
}
|
src/svg-icons/social/people-outline.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPeopleOutline = (props) => (
<SvgIcon {...props}>
<path d="M16.5 13c-1.2 0-3.07.34-4.5 1-1.43-.67-3.3-1-4.5-1C5.33 13 1 14.08 1 16.25V19h22v-2.75c0-2.17-4.33-3.25-6.5-3.25zm-4 4.5h-10v-1.25c0-.54 2.56-1.75 5-1.75s5 1.21 5 1.75v1.25zm9 0H14v-1.25c0-.46-.2-.86-.52-1.22.88-.3 1.96-.53 3.02-.53 2.44 0 5 1.21 5 1.75v1.25zM7.5 12c1.93 0 3.5-1.57 3.5-3.5S9.43 5 7.5 5 4 6.57 4 8.5 5.57 12 7.5 12zm0-5.5c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 5.5c1.93 0 3.5-1.57 3.5-3.5S18.43 5 16.5 5 13 6.57 13 8.5s1.57 3.5 3.5 3.5zm0-5.5c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2z"/>
</SvgIcon>
);
SocialPeopleOutline = pure(SocialPeopleOutline);
SocialPeopleOutline.displayName = 'SocialPeopleOutline';
SocialPeopleOutline.muiName = 'SvgIcon';
export default SocialPeopleOutline;
|
src/examples/SuggestExample/SuggestExample.js | Hypnosphi/qex-controls-react | import React, { Component } from 'react';
import s from './SuggestExample.scss';
import { ISuggest } from '../../blocks';
function City({ option: { city, countryCode } }) {
return (
<div className={s.city}>
{city}
<span className={s.country}>
{countryCode}
</span>
</div>
);
}
class SuggestExample extends Component {
static initialState = {
examples: [
{
title: 'Array',
props: {
options: ['One', 'Two', 'Three'],
},
},
{
title: 'URL',
props: {
url: 'http://jsonplaceholder.typicode.com/users',
valueField: 'name',
},
},
{
title: 'HTTP query',
props: {
url: 'http://jsonplaceholder.typicode.com/users?_limit=5',
param: 'q',
placeholder: 'Name, company etc.',
valueField: 'name',
},
},
{
title: 'Custom template',
props: {
value: 'Paris',
valueField: 'city',
OptionView: City,
ButtonView: City,
options: [
{
city: 'London',
countryCode: 'GB',
},
{
city: 'Paris',
countryCode: 'FR',
},
{
city: 'Moscow',
countryCode: 'RU',
},
],
},
},
],
};
constructor(props) {
super(props);
this.state = SuggestExample.initialState;
}
onSelect(i, value) {
const props = this.state.examples[i].props;
Object.assign(
props,
{ value }
);
this.setState(this.state);
}
render() {
return (
<div className={s.group}>
<h3>ISuggest</h3>
{this.state.examples.map(
({ title, props }, i) => (
<div className={s.example}>
<h4>{title}</h4>
<div className={s.container}>
<ISuggest
onSelect={this.onSelect.bind(this, i)}
{...props}
/>
</div>
</div>
)
)}
</div>
);
}
}
export default SuggestExample;
|
packages/react/src/components/TimePicker/TimePicker-story.js | carbon-design-system/carbon-components | /**
* 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.
*/
import React from 'react';
import { action } from '@storybook/addon-actions';
import {
withKnobs,
boolean,
number,
select,
text,
} from '@storybook/addon-knobs';
import TimePicker from '../TimePicker';
import TimePickerSelect from '../TimePickerSelect';
import SelectItem from '../SelectItem';
import mdx from './TimePicker.mdx';
const sizes = {
'Small (sm)': 'sm',
'Medium (md) - default': undefined,
'Large (lg)': 'lg',
};
const props = {
timepicker: () => ({
pattern: text(
'Regular expression for the value (pattern in <TimePicker>)',
'(1[012]|[1-9]):[0-5][0-9](\\s)?'
),
placeholder: text(
'Placeholder text (placeholder in <TimePicker>)',
'hh:mm'
),
disabled: boolean('Disabled (disabled in <TimePicker>)', false),
light: boolean('Light variant (light in <TimePicker>)', false),
labelText: text('Label text (labelText in <TimePicker>)', 'Select a time'),
invalid: boolean(
'Show form validation UI (invalid in <TimePicker>)',
false
),
invalidText: text(
'Form validation UI content (invalidText in <TimePicker>)',
'A valid value is required'
),
maxLength: number('Maximum length (maxLength in <TimePicker>)', 5),
size: select('Field size (size)', sizes, undefined) || undefined,
onClick: action('onClick'),
onChange: action('onChange'),
onBlur: action('onBlur'),
}),
select: () => ({
disabled: boolean('Disabled (disabled in <TimePickerSelect>)', false),
labelText: text(
'Label text (labelText in <TimePickerSelect>)',
'Please select'
),
iconDescription: text(
'Trigger icon description (iconDescription in <TimePickerSelect>)',
'open list of options'
),
}),
};
export default {
title: 'Components/TimePicker',
decorators: [withKnobs],
parameters: {
component: TimePicker,
docs: {
page: mdx,
},
subcomponents: {
TimePickerSelect,
SelectItem,
},
},
};
export const Default = () => {
const selectProps = props.select();
return (
<TimePicker id="time-picker" {...props.timepicker()}>
<TimePickerSelect id="time-picker-select-1" {...selectProps}>
<SelectItem value="AM" text="AM" />
<SelectItem value="PM" text="PM" />
</TimePickerSelect>
<TimePickerSelect id="time-picker-select-2" {...selectProps}>
<SelectItem value="Time zone 1" text="Time zone 1" />
<SelectItem value="Time zone 2" text="Time zone 2" />
</TimePickerSelect>
</TimePicker>
);
};
Default.parameters = {
info: {
text: `
The time picker allow users to select a time.
`,
},
};
|
src/svg-icons/social/sentiment-satisfied.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialSentimentSatisfied = (props) => (
<SvgIcon {...props}>
<circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-4c-1.48 0-2.75-.81-3.45-2H6.88c.8 2.05 2.79 3.5 5.12 3.5s4.32-1.45 5.12-3.5h-1.67c-.7 1.19-1.97 2-3.45 2z"/>
</SvgIcon>
);
SocialSentimentSatisfied = pure(SocialSentimentSatisfied);
SocialSentimentSatisfied.displayName = 'SocialSentimentSatisfied';
SocialSentimentSatisfied.muiName = 'SvgIcon';
export default SocialSentimentSatisfied;
|
lib/encoding/XSS_AttrValue.js | waynecraig/encoding-present | require('./sass/fullpage.sass');
require('./sass/code.sass');
import React, { Component } from 'react';
import CodeBlock from '../components/CodeBlock';
import ArtTemplate from 'art-template/dist/template';
export default class Slide extends Component {
constructor() {
super();
this.state = {};
this.state.codeCom = this._codeCom = `// 普通文本替换
var A = 'ok';
return '<p id="{{A}}" onclick={{A}}></p>'.replace(/{{A}}/g, A);`;
this.state.codeArt = this._codeArt = `// Art-template
var A = 'ok';
// var A = '1 onmouseover=alert(1)';
// var A = '1" onmouseover=alert(1)';
// var A = 'alert(1)';
// var A = 'alert(1)';
// var A = '\\\\u0061lert(1)';
// var A = '\u0061lert(1)';
var render = ArtTemplate.compile('<p id="{{A}}" onclick={{A}}></p>');
return render({A:A});`;
this.state.codeJSX = this._codeJSX = `// JSX
var A = 'ok';
var s = {id: A, onClick: A};
// s.onClick = function() {...}; // 正常
// s.onClick = function() {eval(A)}; // 除非这样写才会被注入
return React.renderToString(React.createElement('p', s));
// equal to <p id={A} onclick={A}></p>>`;
}
getComResult() {
try {
var fun = new Function(this._codeCom);
return fun();
} catch(e) {
return e.toString();
}
}
getArtResult() {
try {
var fun = new Function('ArtTemplate', this._codeArt);
return fun(ArtTemplate);
} catch(e) {
return e.toString();
}
}
getJSXResult() {
try {
var fun = new Function('React', this._codeJSX);
return fun(React);
} catch(e) {
return e.toString();
}
}
update(v, type) {
this['_code' + type] = v;
}
apply(e, type) {
e.stopPropagation();
let s = {};
s['code'+type] = this['_code'+type];
s['res'+type] = this['get'+type+'Result']();
this.setState(s);
}
render() {
return (
<div className='fullpage'>
<h1>对属性值注入</h1>
<div className='code'>
<div className='block'>
<CodeBlock id='codeCom' onChange={(v)=>this.update(v, 'Com')}>
{this.state.codeCom}
</CodeBlock>
<span className='apply' onClick={(e)=>this.apply(e, 'Com')}>应用</span>
<div className='result'>{this.state.resCom}</div>
</div>
<div className='block'>
<CodeBlock id='codeArt' onChange={(v)=>this.update(v, 'Art')}>
{this.state.codeArt}
</CodeBlock>
<span className='apply' onClick={(e)=>this.apply(e, 'Art')}>应用</span>
<div className='result'>{this.state.resArt}</div>
</div>
<div className='block'>
<CodeBlock id='codeJSX' onChange={(v)=>this.update(v, 'JSX')}>
{this.state.codeJSX}
</CodeBlock>
<span className='apply' onClick={(e)=>this.apply(e, 'JSX')}>应用</span>
<div className='result'>{this.state.resJSX}</div>
</div>
</div>
</div>
)
}
}
|
src/RootCloseWrapper.js | Cellule/react-bootstrap | import React from 'react';
import domUtils from './utils/domUtils';
import EventListener from './utils/EventListener';
// TODO: Merge this logic with dropdown logic once #526 is done.
export default class RootCloseWrapper extends React.Component {
constructor(props) {
super(props);
this.handleDocumentClick = this.handleDocumentClick.bind(this);
this.handleDocumentKeyUp = this.handleDocumentKeyUp.bind(this);
}
bindRootCloseHandlers() {
const doc = domUtils.ownerDocument(this);
this._onDocumentClickListener =
EventListener.listen(doc, 'click', this.handleDocumentClick);
this._onDocumentKeyupListener =
EventListener.listen(doc, 'keyup', this.handleDocumentKeyUp);
}
handleDocumentClick(e) {
// If the click originated from within this component, don't do anything.
// e.srcElement is required for IE8 as e.target is undefined
let target = e.target || e.srcElement;
if (domUtils.contains(React.findDOMNode(this), target)) {
return;
}
this.props.onRootClose();
}
handleDocumentKeyUp(e) {
if (e.keyCode === 27) {
this.props.onRootClose();
}
}
unbindRootCloseHandlers() {
if (this._onDocumentClickListener) {
this._onDocumentClickListener.remove();
}
if (this._onDocumentKeyupListener) {
this._onDocumentKeyupListener.remove();
}
}
componentDidMount() {
this.bindRootCloseHandlers();
}
render() {
return React.Children.only(this.props.children);
}
componentWillUnmount() {
this.unbindRootCloseHandlers();
}
}
RootCloseWrapper.propTypes = {
onRootClose: React.PropTypes.func.isRequired
};
|
es/components/HeaderBar/AppTitle.js | welovekpop/uwave-web-welovekpop.club | import _jsx from "@babel/runtime/helpers/builtin/jsx";
import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import IconButton from "@material-ui/core/es/IconButton";
import AboutIcon from "@material-ui/icons/es/ArrowDropDown";
import logo from '../../../assets/img/logo-square.png';
var _ref2 =
/*#__PURE__*/
_jsx(AboutIcon, {});
var AppTitle = function AppTitle(_ref) {
var className = _ref.className,
children = _ref.children,
onClick = _ref.onClick;
return _jsx("div", {
className: cx('AppTitle', className)
}, void 0, _jsx("h1", {
className: "AppTitle-logo"
}, void 0, _jsx("img", {
className: "AppTitle-logoImage",
alt: children,
src: logo
})), _jsx(IconButton, {
className: "AppTitle-button",
onClick: onClick
}, void 0, _ref2));
};
AppTitle.propTypes = process.env.NODE_ENV !== "production" ? {
className: PropTypes.string,
children: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired
} : {};
export default AppTitle;
//# sourceMappingURL=AppTitle.js.map
|
client/extensions/woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal/step-confirmation-button/index.js | Automattic/woocommerce-services | /** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import FormButton from 'components/forms/form-button';
const StepConfirmationButton = ( { disabled, onClick, children } ) => {
return (
<div className="step-confirmation-button">
<FormButton type="button" onClick={ onClick } disabled={ Boolean( disabled ) } isPrimary>
{ children }
</FormButton>
</div>
);
};
StepConfirmationButton.propTypes = {
disabled: PropTypes.bool,
onClick: PropTypes.func.isRequired,
};
export default StepConfirmationButton;
|
actor-apps/app-web/src/app/components/activity/GroupProfile.react.js | way1989/actor-platform | import React from 'react';
import DialogActionCreators from 'actions/DialogActionCreators';
import LoginStore from 'stores/LoginStore';
import PeerStore from 'stores/PeerStore';
import DialogStore from 'stores/DialogStore';
import GroupStore from 'stores/GroupStore';
import InviteUserActions from 'actions/InviteUserActions';
import AvatarItem from 'components/common/AvatarItem.react';
import InviteUser from 'components/modals/InviteUser.react';
import GroupProfileMembers from 'components/activity/GroupProfileMembers.react';
const getStateFromStores = (groupId) => {
const thisPeer = PeerStore.getGroupPeer(groupId);
return {
thisPeer: thisPeer,
isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer),
integrationToken: GroupStore.getIntegrationToken()
};
};
class GroupProfile extends React.Component {
static propTypes = {
group: React.PropTypes.object.isRequired
};
componentWillUnmount() {
DialogStore.removeNotificationsListener(this.onChange);
GroupStore.addChangeListener(this.onChange);
}
componentWillReceiveProps(newProps) {
this.setState(getStateFromStores(newProps.group.id));
}
constructor(props) {
super(props);
DialogStore.addNotificationsListener(this.onChange);
GroupStore.addChangeListener(this.onChange);
this.state = getStateFromStores(props.group.id);
}
onAddMemberClick = group => {
InviteUserActions.modalOpen(group);
}
onLeaveGroupClick = groupId => {
DialogActionCreators.leaveGroup(groupId);
}
onNotificationChange = event => {
DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked);
}
onChange = () => {
this.setState(getStateFromStores(this.props.group.id));
};
render() {
const group = this.props.group;
const myId = LoginStore.getMyId();
const isNotificationsEnabled = this.state.isNotificationsEnabled;
const integrationToken = this.state.integrationToken;
let memberArea;
let adminControls;
if (group.adminId === myId) {
adminControls = (
<li className="profile__list__item">
<a className="red">Delete group</a>
</li>
);
}
if (DialogStore.isGroupMember(group)) {
memberArea = (
<div>
<div className="notifications">
<label htmlFor="notifications">Enable Notifications</label>
<div className="switch pull-right">
<input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange.bind(this)} type="checkbox"/>
<label htmlFor="notifications"></label>
</div>
</div>
<GroupProfileMembers groupId={group.id} members={group.members}/>
<ul className="profile__list profile__list--controls">
<li className="profile__list__item">
<a className="link__blue" onClick={this.onAddMemberClick.bind(this, group)}>Add member</a>
</li>
<li className="profile__list__item">
<a className="link__red" onClick={this.onLeaveGroupClick.bind(this, group.id)}>Leave group</a>
</li>
{adminControls}
</ul>
<InviteUser/>
</div>
);
}
return (
<div className="activity__body profile">
<div className="profile__name">
<AvatarItem image={group.bigAvatar}
placeholder={group.placeholder}
size="medium"
title={group.name}/>
<h3>{group.name}</h3>
</div>
{memberArea}
{integrationToken}
</div>
);
}
}
export default GroupProfile;
|
packages/mineral-ui-icons/src/IconPerson.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconPerson(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
</g>
</Icon>
);
}
IconPerson.displayName = 'IconPerson';
IconPerson.category = 'social';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.